mote-engine / v0.56.0
Developer manual
A 3D engine for the web with three modes: ASCII characters, Ray surfaces with physical materials and WebGPU ray tracing, and Wireframe indexed edges with hidden-line removal. Objects share the same owned mesh, deformation and continuous material/cut fields in every mode. It loads glTF models, includes primitives, physics, lights, independent particle effects, stage transitions, a code backdrop.
Install
After you buy a licence, your download link delivers the versioned ESM package and its TypeScript declarations. Version 0.56.0 has no runtime dependencies.
With npm, from your project folder:
npm install ./mote-engine-0.56.0.tgz
Then import it by name:
import { createScene, cssColors } from "mote-engine";
The package is ESM only and ships its TypeScript types. Entry points:
| Import | What |
|---|---|
mote-engine |
everything |
mote-engine/geometry |
meshes, sampling, built-in shapes and capsuleMesh (no browser needed) |
mote-engine/gltf |
the glTF reader (no browser needed) |
mote-engine/text |
still frames as plain text (no browser needed) |
mote-engine/backdrop |
the code backdrop |
mote-engine/effects |
effect factories and live parameter definitions |
mote-engine/physics |
rigid bodies, joints that can break, puppets (physicsPuppets, humanoid), raycasts and snapshots |
mote-engine/director |
scene-operation and timeline validation, the timeline compiler and sampler, createSceneFromJson (Scene JSON v2), replayLog (loaded on demand by the scene), the shot prompt describeShot and orthographic views (orthographicView, drawOrthoMesh) |
mote-engine/video |
recordVideo, which records a scene with a stepped clock as an MP4 file in the browser (WebCodecs), and muxMp4, the MP4 writer on its own (no browser needed) |
mote-engine/constellation |
the constellation renderer plugin (small wireframe solids on every surface) |
mote-engine/components |
components: record catalog, registry, the motor family dc-servo, the sensor families (imu, encoder, lidar-2d, tof-zone) and robots from description files (loadRobot, loadRobotInScene) (experimental) |
mote-engine/element |
the <mote-scene> custom element |
mote-engine/native |
native adapter transport (experimental) |
Release notes
mote-engine 0.56
0.56 gives every scene a scene graph and reads more model formats. scene.graph hands out a stable handle for each object of a stage, with its parent and children, its local transform and its exact world matrix, and lets you create, attach, move and detach nodes while the scene runs. Models now also load from COLLADA and binary FBX, and glTF files compressed with Draco or KTX2 load through decoders your application hosts. A scene that never touches its graph draws as in 0.55, apart from the custom-mode change below.
The scene graph. scene.graph is the graph of the stage on screen, and scene.graphAt(index) that of another stage. Each stage has a root, @root/<index>, and each node is a NodeHandle: its id, its parent, its children in order, its roles (mesh, bone, camera, light, helper) and item, the object it draws. getById, find and traverse search a node and everything under it, depth first. A glTF file read as a tree keeps its node names, and its bones, cameras and lights are nodes too. IDs must be unique across the whole scene: reading the graph of a scene with duplicates throws a GraphError of kind invalid, and the scene is left as it was.
Local transforms and world matrices. A node's position, quaternion and scale are live views of its transform in its parent's space, written with .set(...) or .copy(...); setTransform writes a partial transform at once. matrixWorld is the exact column-major world matrix, shear included, and copyMatrixWorld(out) fills a Float64Array of yours without allocating, for code that reads it every frame.
Creating, attaching, detaching. await scene.graph.create(spec) makes a node from a NodeSpec: a Scene JSON v2 object (a primitive, a model file, one glTF node, an SVG or Gaussian splats), a group, a camera or a light. A new node is detached, and drawn only once you add it under a parent. parent.add(a, b) moves nodes under a parent in one step, keeping their local transforms; remove and removeFromParent() detach a subtree without destroying it. While a subtree is detached its geometry, materials and handles are kept, its bodies leave the simulation, its joints and effects pause and its running tweens end where they are. Attached again, its bodies start at rest, its joints are made again and its effects resume without catch-up particles.
Helpers. graph.create({ id, helper: { kind: "axes" } }) makes an inspection overlay: axes, an XZ grid, or a box, light or camera drawn for the node named by target. Helpers draw in ASCII, Wireframe, Ray and custom mode, and are never geometry, colliders or something pick finds. graph.useCamera(node) looks through a camera node, a glTF camera for instance, and useCamera(null) puts the previous rig back.
import { createScene, box } from "mote-engine";
const scene = createScene(canvas, {
stages: [{ items: [{ id: "room" }, { id: "door", parent: "room", source: box(), motion: "none" }] }],
});
await scene.ready;
const graph = scene.graph;
const door = graph.getById("door"); // door.parent.id === "room"
door.position.set(1, 0, 0); // in the room's space
const world = door.copyMatrixWorld(new Float64Array(16));
const panel = await graph.create({ id: "panel", object: { shape: "box", material: { color: "#6688cc" } } });
door.add(panel); // drawn from now on, under the door
graph.root.add(await graph.create({ id: "axes", helper: { kind: "axes" } }));
panel.removeFromParent(); // detached, kept for later
Using the scene graph and Local transforms and world matrices have the whole API, its guards and its errors (GraphError, with a kind and a path).
Scene JSON and the log. Scene JSON stays at version 2, with no graph fields: a graph edit is drawn but not recorded. An edit that changes something marks scene.log() incomplete (unrecorded says from which frame and why), and describe() lists with complete: false each node it cannot write: helpers, detached nodes and nodes made with create. Graph operations in the log and Scene JSON version 3 are planned for 0.57.
COLLADA and FBX. loadCollada(url) reads static COLLADA 1.4 and 1.5 models: triangles, polylists and simple polygons, node hierarchies, the file's unit and up axis, and Phong, Blinn and Lambert colours. loadFbx(url) reads binary FBX 7.x static meshes with their hierarchy's transforms, normals, UVs, vertex colours and materials, and converts the file's axes and units to Y-up metres. loadModel detects both, Scene JSON takes { "model": "statue.dae" } or an .fbx file (format: "dae" or "fbx" when the name does not say), and <mote-scene src> loads them. Both are bounded by MODEL_LIMITS; ColladaOptions and FbxOptions are their options. See Collada models and Binary FBX.
Draco and KTX2 through your own decoders. loadGltf and loadGltfFiles take decoders: the Draco glTF decoder and the Basis Universal transcoder, as files your application hosts (path) or as their contents (module). The engine ships no decoder and fetches none of its own; each decode runs in a short-lived Worker within timeoutMs. parseGltfAsync(bytes, { decoders }) gives a document for gltfTree, skins and animations.
import { loadGltf } from "mote-engine";
const source = await loadGltf("/models/model.glb", {
decoders: { draco: { path: "/decoders/draco/" }, ktx2: { path: "/decoders/basis/" }, timeoutMs: 15000 },
});
Without a decoder, an optional compression extension falls back to the file's uncompressed data, as parseGltf, gltfSource, Scene JSON and <mote-scene> always do; a file that requires the extension is refused with the names of the decoder files it needs. External glTF decoders lists the files and where to get them.
Also in 0.56: an OBJ's MTL Ps and map_Ps now set sheenColor and sheenColorMap, without the warning 0.55 gave.
Breaking changes:
ItemSpecno longer takes glTF metadata as input.name,bone,provenance,cameraDefinitionandlightDefinitionon an object you write are refused with aTypeErrorthat names the field's JSON pointer, and the scene does not change. The itemsgltfTreeItemsreturns still carry them, also when you spread them into your own. To make a named node, a bone, a camera or a light, use aNodeSpecwithgraph.create.
Behaviour changes:
describe()of a tree built in code. A scene made fromgltfTreeItems(tree, { gltf })in your page now getscomplete: false, with anunserializablediagnostic for each node's glTF name and origin, which version 2 cannot hold. A tree declared in the document withgltfTreestays complete.- Custom mode draws
scene.debugprimitives last, after the effects and the plugin's output. While any helper is attached they also draw without depth occlusion, because a plugin exposes no depth.
Known limits: the graph has no reparenting that keeps the world pose, no clone, no node events, no lookAt and no layers. Structural edits are capped at 4096 nodes and 256 helpers a stage and 64 levels. An orthographic camera node stays readable, but useCamera refuses it with unsupported-projection. In ASCII a helper is depth-tested against the nearest sampled surface point in each cell, so a sparsely sampled object can let it show through. COLLADA reads the static pose only: skins, morphs, polygon holes and external references are refused, and textures are ignored with a warning. FBX reads binary static meshes only: no skinning, animation, blend shapes, cameras, lights or textures, and ASCII FBX is refused. Scene JSON, <mote-scene> and loadModel take no decoder configuration, so a model that is only compressed is loaded with loadGltf and given to the scene in code. In Node a decoder needs a Web Worker adapter. KTX2 textures are 2D, at most 4096 × 4096, and only their base mip is kept.
mote-engine 0.55
0.55 reads more of the 3D formats a web project meets and widens the GPU paths. Models load from OBJ with MTL materials, STL and mesh PLY; SVG drawings become flat or extruded shapes; glTF files compressed with meshopt load with no decoder to host; and glTF materials gain unlit, sheen, anisotropy and iridescence. ASCII can draw its glyphs with WebGPU, and Wireframe without WebGPU now falls back to WebGL2 instead of ASCII.
Models from OBJ, STL and PLY. loadModel(url) picks the reader by extension or content: OBJ with its MTL files and textures, STL (ASCII or binary, with VisCAM and SolidView colours) and mesh PLY (ASCII or binary). loadObj, loadStl and loadPlyMesh read one format, and all take normalize: false to keep the file's units. OBJ triangulates concave polygons and keeps smoothing groups; MTL maps the classic and PBR factors, base-colour maps and normal maps. A file is checked before its meshes are allocated, within MODEL_LIMITS (64 MiB a file by default; maxBytes, maxVertices, maxFaces and maxMaterials tighten them). Scene JSON takes { "model": "part.obj" }, and <mote-scene src> loads .obj, .stl and .ply URLs. A PLY without faces still goes to the Gaussian-splat reader.
SVG as shapes. svgSource(text, { depth, bevel, curveSegments, stroke }) reads paths with arcs, the basic shapes and nested transforms without a DOM, in Node or a browser, each fill in its own colour and with its holes. depth: 0, the default, gives a flat shape. Scene JSON takes { "svg": "mark.svg", "depth": 0.08 }.
import { createScene, loadModel, svgSource } from "mote-engine";
const mark = svgSource(svgText, { depth: 0.08, bevel: 0.01 });
const scene = createScene(canvas, {
mode: "ray",
stages: [{ items: [{ id: "part", source: loadModel("/models/part.obj"), motion: "none" }] }, mark],
});
OBJ, STL and mesh PLY and Other sources have the details.
meshopt without a decoder. glTF files compressed with EXT_meshopt_compression or KHR_meshopt_compression load through every glTF reader, decoded by the engine itself: no WebAssembly, no decoder path, no setup. Every compressed range is checked before its output is allocated, within 64 MiB a buffer view and 256 MiB a model.
glTF materials. KHR_materials_unlit, KHR_materials_sheen, KHR_materials_anisotropy and KHR_materials_iridescence are read with their textures, and Material has the same fields for your own materials: unlit; sheenColor, sheenRoughness; anisotropyStrength, anisotropyRotation; iridescence, iridescenceIor, iridescenceThicknessMin, iridescenceThicknessMax; and their maps. Ray shades all four; ASCII and Wireframe draw an unlit material without lighting and the other three as their base colour. Mesh.tangents keeps a file's own tangents. See Materials.
ASCII on WebGPU. glyphRenderer: "webgpu" draws ASCII's characters and the effects' glyphs with WebGPU, falling back to WebGL2 and then Canvas2D. With "auto", the default, WebGPU is used only once the scene has a device for Ray or Wireframe, so a plain ASCII page downloads nothing more and asks for no device. The element takes glyph-renderer="webgpu".
Also in 0.55: the new readers, and the WebGL2 Wireframe, load on demand, the first time a scene or <mote-scene> needs them, so a page that uses none of them downloads none of them.
Behaviour changes:
- Wireframe without WebGPU draws with WebGL2, hidden lines and preview faces included, where 0.54 drew the scene in ASCII; ASCII stays the last fallback.
scene.modestays"wireframe",stats().backendstarts withwebgl2andstats().ray.fellBackgives the reason. See Wireframe. - ASCII after Ray or Wireframe. In a scene that already opened a WebGPU device,
"auto"now draws the glyphs with it. The pictures match WebGL2's except for small local differences where a glyph overlaps a halo. - glTF files that 0.54 refused now load: those compressed with meshopt, and those that require unlit, sheen, anisotropy or iridescence.
Known limits: SVG has no CSS stylesheets, no text and no gradients (a gradient fill takes its first stop's colour). An OBJ face has at most 4096 vertices. The WebGL2 Wireframe shades flat, keeps its coverage cap of 262,144 pixels, and has no smoothing or mipmap options. Ray's refined glass does not add sheen or anisotropy, and tangents cannot be morph targets. Draco is not read in 0.55: 0.56 reads it through a decoder you host.
mote-engine 0.54
0.54 lets code, or an AI working through it, arrange a scene by where its objects really are. Five new scene operations place objects on, beside and in line with others by their world bounding boxes; orthographic views draw a scene from above, the front and the side at a known scale; and scene.geometry hands over each object's triangles as they stand. Scenes that use none of it run as in 0.53.
Spatial operations. placeOn, placeRelative, align, distribute and resolveOverlaps join scene.applyOps and timeline cues. They measure each object's world bounding box, its children included, with Y up and a metre to a scene unit: rest a vase on a table without sinking into it, put a chair 20 cm in front of it, line shelves up against a wall, space objects evenly, push overlapping ones apart. A batch is validated whole before anything moves, every error with its JSON pointer, and the operations are logged and replayed like the others. OpsResult.placed says where each operation left its objects (PlacedObject: position, world box, moved).
const { placed } = await scene.applyOps([
{ op: "placeOn", id: "table" }, // on the floor
{ op: "placeOn", id: "vase", on: "table" }, // on the table, centred
{ op: "placeRelative", id: "chair", to: "table", side: "front", distance: 0.2 }, // 20 cm in front of it
{ op: "resolveOverlaps", ids: ["chair", "stool"], fixed: ["table"], gap: 0.05 }, // 5 cm apart at least
]);
Scene operations and the log has every field of the five.
Orthographic views. From mote-engine/director: orthographicView(kind, min, max, width, height) frames a world box from the "top", the "front" or the "side" with no perspective, projectOrthographic and unprojectOrthographic go between world points and pixels, and createOrthoPicture with drawOrthoMesh draw a scene's triangles into an RGBA picture in their base colours: a plan or an elevation on which lengths are read with one number. See Orthographic views of a scene.
The scene's triangles. scene.geometry(visit) hands over each drawn object's mesh as the frame draws it (skins and morph targets applied), the matrix that places it, and its materials' base colours and doubleSided flags. What it hands over is borrowed until the visitor returns. It is a query, not a call for every frame.
Also in 0.54: scene.bounds(id, out) fills a SceneBounds record of yours and returns it, so an outline that follows an object every frame allocates nothing. See Measuring the scene.
Placeholders in a shot prompt. describeShot takes placeholders: a sentence that tells a video model the guide's figures are blocking placeholders, whose paths, actions and timing it keeps while it gives them natural human motion. ShotDescription.placeholders says whether it was added.
Behaviour change: describeShot adds the placeholders sentence by default when the scene has skinned figures, or subjects whose ids contain the whole word mannequin, dummy or puppet. Pass placeholders: false to keep the 0.53 text.
Known limits: the boxes are axis-aligned in the world, so a turned object's box is larger than the object, and a chair pushed under a table overlaps it. An object with nothing to measure yet (a model still loading, a group whose children draw nothing) is the operation's runtime error. Orthographic pictures are flat drawings in base colours: no texture maps, lights, shadows, effects or Gaussian splats.
mote-engine 0.53
0.53 takes a scene from Blender to a video file. A glTF file's cameras and punctual lights now drive the scene, a Scene JSON document can name them so that the same small document loads each new export, recordVideo records a scene as an MP4 file in the browser, and describeShot writes the text prompt that goes with a guide video for an AI video model. Scenes without them run as in 0.52.
A model's cameras. gltfCameras(doc, tree) lists a file's cameras, each with its field of view and the nodes that carry it, and gltfCameraRig(doc, tree, ids, { camera }) gives the rig that puts the scene's camera on a camera's node, by index or name. The node's animation, played by gltfTracks, moves the camera as it moves in Blender. The rig is a new kind, { kind: "attach", target, distance? }: the eye at an object's origin, looking along its −Z axis with its +Y up, read every frame where the object is drawn. Any object can carry the camera this way, and the camera operation and timeline cues take it too. See A model's cameras and Camera rigs.
A model's lights. gltfLights(doc, tree) reads a file's KHR_lights_punctual lights, and gltfSceneLights(doc, tree, ids) makes a scene light for each node that carries one, attached to that node's object, so the node's animation moves it. The file's lux and candela become Ray's physical units: with Blender's Data › Lighting › Standard export, a light comes back with the power it had in Blender, measured against Cycles within 0.05%. Directional, point and spot lights you write in code take attach: "<item id>" too. See A model's lights.
From Blender and back. In a version 2 document, a stage object { "gltfTree": "shot.glb" } declares the file's whole node tree, "camera": { "gltf": "shot.glb", "camera": "Camera", ... } names one of its cameras, a lights entry { "gltf": "shot.glb", "lights": "all" } selects its lights, and "animation": { "clip": "Dolly" } on the tree plays one of its clips. createSceneFromJson resolves them (sceneFromJson only checks them), and describe() writes them back as references to the file, not as copied poses: edit in Blender, export over the same file and load the same document again. See From Blender to mote and back.
Exporting a video. recordVideo(scene, options), from the new entry point mote-engine/video, steps a scene with a stepped clock frame by frame, encodes each picture with the browser's WebCodecs encoder and writes the MP4 file itself, with no other library. It takes seconds or from and to, fps (it must divide the clock's rate), codec ("avc", the default, "vp9" or "av1"), bitrate, background, refined for path-traced Ray frames, signal and onProgress, and resolves with the file as a blob. muxMp4, the MP4 writer on its own, runs without a browser. See Exporting a video.
A prompt for a video model. describeShot(scene, { from, to, style, negative, maxLength, language }), from mote-engine/director, describes what a stepped scene made by createSceneFromJson (or a Scene JSON document) plays over a frame range: the camera's moves with their measured degrees and metres, the subjects in view, the lights and the look. It samples a private copy, so the scene you pass is neither stepped nor changed, and the same scene and options give the same text byte for byte. prompt and promptShort stay within maxLength (900 by default), in English or, with language: "it", Italian.
import { createSceneFromJson, describeShot } from "mote-engine/director";
import { recordVideo } from "mote-engine/video";
// shotJson: a version 2 document with a gltfTree, the file's camera and lights,
// and a stepped clock: "clock": { "time": 0, "step": 0.016666666666666666 }
const made = await createSceneFromJson(canvas, shotJson);
if (!made.ok) throw new Error(made.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
const scene = made.scene;
await scene.ready;
const shot = await describeShot(scene, { to: 240, style: "soft morning light" });
const video = await recordVideo(scene, { to: 240, fps: 30, background: "#ffffff" });
// video.blob: the MP4 file; shot.prompt: the text that goes with it
Also in 0.53: cameras and lights are read as untrusted input like the rest of a glTF file, at most 256 of each and 4096 nodes that carry them (GLTF_CAMERA_LIMITS, GLTF_LIGHT_LIMITS). A light with out-of-range values is skipped with a light-invalid diagnostic and never fails the file. The flat loaders, loadGltf among them, read neither and load files as before.
Known limits: recordVideo needs a stepped clock and a canvas on screen, records no audio, and makes at most 10 000 pictures a recording. With the browser's software H.264 encoder the bytes repeat from run to run up to 640 × 360; at 720p and above the frames, timing and size repeat but the bytes can differ. gltfCameraRig refuses an orthographic camera, and a camera's animated zoom is not played: animate the rig's fov with a timeline track instead. A light's range fades smoothly rather than cutting off as in Blender (about 0.56 times Cycles' light at half the range), and Blender's area lights are not exported as punctual lights. describeShot's thresholds for a file camera's composite shot were tuned on a single shot, the default maxLength can leave out the least visible subjects of a rich scene, and a scene not made from Scene JSON (procedural sources, puppets) is refused with a TypeError.
mote-engine 0.52
0.52 brings the engine's first characters: puppets. A puppet is a figure of rigid parts, one body for each bone, that stands in its pose in a physics world or a scene and turns into a ragdoll when it is hit hard enough, one part at a time. Worlds and scenes without puppets step exactly as before.

Puppets in a world. world.use(physicsPuppets()), from the physics entry point, makes a figure with one body per bone and one joint from each bone to its parent. humanoid("mannequin") gives a standing figure of 15 parts with a human body's shares of the mass; "dummy" has 11, its hands in the forearms and its feet in the shins. Elbows, knees, ankles, wrists, the neck and the waist are hinges with limits, and shoulders and hips are ball joints. A figure of your own is a PuppetSpec: a list of bones, each with its parent, where it lies in the rest pose, its shape and its joint. The whole spec is checked before one body is made.
Standing, then limp. A puppet starts "animated": its parts are kinematic bodies in the rest pose, which push what they meet, and moveTo takes the figure somewhere else over the next step. goLimp() turns every part dynamic where it is, keeping its velocity and its contacts. With limpOnImpact, a hit of at least impulse N·s turns limp the bone it lands on, the bones within spread joints of it and everything that hangs from them. The parts collide with each other unless they are joined, without taking any of the 16 collision groups, and a step with puppets allocates nothing.
import { createPhysicsWorld, physicsEvents, physicsPuppets, humanoid } from "mote-engine/physics";
const world = createPhysicsWorld();
world.use(physicsEvents()); // the impacts limpOnImpact reads
const puppets = world.use(physicsPuppets());
world.addBody({ type: "static", shape: { type: "plane", normal: [0, 1, 0], offset: 0 } });
const puppet = puppets.add(humanoid("mannequin", { height: 1.75, mass: 70 }), { position: [0, 0, 0] });
puppet.limpOnImpact = { impulse: 2, spread: 1 }; // N·s: the part hit and its neighbours
// ... later, all of it:
puppet.goLimp(); // a ragdoll, which falls
Puppets in a scene. A stage declares them in puppets, and the scene (it needs physics) draws each part as an ordinary object of the stage, "actor.head" or "actor.forearm.L", in ASCII, Ray and Wireframe. scene.puppet(id) is the puppet's handle. The scene's events name the parts by their ids, a limp part can be grabbed and thrown, and a body thrown at a standing puppet turns limp what its limpOnImpact says.
import { createScene, materials } from "mote-engine";
const scene = createScene(canvas, {
mode: "ray",
physics: { scale: 1.25, floor: -0.8 }, // metres to a scene unit
stages: [{ items: [], puppets: [{
id: "actor", spec: "mannequin", position: [0, -0.8, 0],
material: { head: materials.gold }, // one material, or one per bone
limpOnImpact: { impulse: 5 },
}] }],
});
await scene.ready;
scene.puppet("actor").goLimp();
Each part is drawn with the mesh of its collision shape. capsuleMesh, new in the geometry entry point, is that capsule as a mesh, for your own objects too. Puppets and Puppets in a scene have the whole API.
Also in 0.52: a scene's fixed physics step no longer allocates while bodies are awake, in contact or pushed, with the same results bit for bit.
Known limits: this first version has no cone or twist limits (joint: { type: "cone" } is refused, so shoulders and hips turn freely), no "powered" mode, no clips and no getting up. A ragdoll does not return to "animated": remove the puppet and add it again, or show its stage again, which stands a new one in its place. Puppets are not in Scene JSON yet, and world.snapshot() and restore() throw while a world holds one. A landing stretches the soft joints: the dummy's part by about 2 cm, and the mannequin's hands and feet can go past their hinges' limits by up to 17° for a few steps. jointSolver: "chain" holds every hinge's limit. A stage's joints cannot name a puppet's part, and a puppet cannot be added to a stage already on screen.
mote-engine 0.51
0.51 lets joints break and say when they reach their limits, and puts a robot's description file in a scene. World snapshots have a new version: read the breaking changes below before you update.
Joints that break. Every joint takes breakForce in newtons, and a hinge, a weld and a slider also take breakTorque in newton metres, at every scale. When the load over a step passes the threshold, the joint breaks after that step: it leaves the world, joint.broken turns true and onJointBreak tells it once. In a scene the event carries the objects' ids and the joint's jointId, scene.physics.hinge(id).broken says so, and a broken joint stays broken until its stage is shown again. Scene JSON's joints and a robot file's take the same two fields.
Limits that tell. onJointLimit now fires when a hinge, a slider or a distance joint starts to push against its limit: once, and again only after the joint has left the limit and come back.
const scene = createScene(canvas, {
physics: {
events: {
onJointBreak: (e) => console.log(`${e.jointId} let go of ${e.a}`),
onJointLimit: (e) => console.log(`${e.jointId} is on its ${e.which} stop`),
},
},
stages: [{
items: [lamp], // a 2 kg lamp: it weighs 19.6 N
joints: [{ id: "cord", type: "distance", a: "lamp", anchorA: [0.7, 0.42, 0], anchorB: [0.7, 0.9, 0], breakForce: 30 }],
}],
});
Choose a threshold with a margin: with the default solver a load put on at once swings to about 1.4 times its resting value before it settles.
A body changes type in place. body.setType("dynamic", { keepContacts: true }) lets go of a kinematic body without ending its contacts or losing its velocity, and the same works from dynamic to kinematic. Puppets go limp this way.
A robot in a scene. loadRobotInScene(scene, json, catalog, options), from the components entry point, builds a robot's description file in the stage on screen: each body an object of the stage, each joint a joint of the stage, with its motors and sensors attached. It steps bit for bit as the same file loaded in a world with loadRobot, and robot.remove() leaves the scene as it was.
Ray queries without allocating. world.raycastInto(origin, dir, maxDistance, hit) finds the nearest hit like raycast and writes the body, point, normal and distance into a record you reuse.
Breaking changes:
- World snapshots are version 2. They now keep the joints' break thresholds and which limits hold each joint. A snapshot taken with 0.50 or earlier is refused whole (
Invalid world snapshot: version 1; expected 2) and the world is left as it was. Before you update, finish or discard the runs whose snapshots you keep, then take them again with this version. There is no conversion. SceneHinge.indexfollows the joint's place in its stage. When a robot loaded earlier in the same stage is removed, the joints after it move up, and a removed joint's handle reads -1. Keep the handlescene.physics.hinge(id)gives you, or look a hinge up by its id, never by an index you stored.ItemSpec.shapeis checked. On a source fromgltfTreeItems(tree, { gltf }), a shape that does not name the source's real node and file is refused with aTypeError, where 0.50 accepted it.
Known limits: a robot loads only into the stage on screen, and when its stage is shown again its motors and sensors are attached anew, without the commands they had (robot.generation counts it).
mote-engine 0.50
0.50 loads scenes and robots from files. A robot written as data is built exactly as the same calls would build it, and Scene JSON keeps a scene's hierarchy, so describe() writes parents and groups and the document loads back as the same scene.
A robot from a file. loadRobot(world, json, catalog, options), from the components entry point, reads a robot written as data: its bodies and their collision shapes, its joints between bodies named by id, and its motors and sensors, each citing the id of its record in a component catalog. It builds them in a physics world in the file's order, and the robot steps bit for bit as the same robot built in code. validateRobotFile(json) checks a description without building it. A wrong file is refused whole before a body is made, every error with its JSON pointer, what was expected and what was found.
import { createPhysicsWorld } from "mote-engine/physics";
import { components, createComponentCatalog, dcServoMotor, jsonComponentSource, loadRobot } from "mote-engine/components";
const world = createPhysicsWorld({ jointSolver: "chain" });
const comps = world.use(components());
comps.registerMotorModel("dc-servo", dcServoMotor);
const parts = jsonComponentSource(partsJson); // the records the file cites
const catalog = createComponentCatalog(parts.source, { families: comps.families });
const loaded = await loadRobot(world, robotJson, catalog, { components: comps, position: [0, 0, 0.5] });
if (!loaded.ok) console.log(loaded.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
else loaded.robot.motor("servo").setPosition(0.5); // handles by the file's ids
A hierarchy in Scene JSON. A version 2 object can have a parent, the id of another object of its stage, and its transform is then in its parent's space. An object without a shape is a group, and { "gltf": "robot.glb", "node": "Arm.L" } is one node of a glTF file as a shape. scene.describe() now writes a hierarchy as it is, a tree read with gltfTreeItems(tree, { gltf }) included, and the document loads back as the same scene. A parent that is missing, a cycle and more than 64 levels are refused with the field's JSON pointer.
Rigged characters on the timeline. A timeline now holds up to 4096 tracks instead of 256, so the animation of a glTF rig with a hundred joints and more plays through gltfTracks. Validating the largest timelines takes a few hundred milliseconds: install them outside interaction handlers.
Integration recipes. The manual has Integration recipes for the <mote-scene> element's lifecycle, a React component that survives StrictMode and a paste-ready block for a CMS page.
Behaviour changes:
- Ray culls the back faces of skinned and morphed meshes when their material is not double-sided, as it already did for static meshes. A skinned model that was visible from behind or from inside now disappears from there. Give the materials that must show their back
doubleSided: true, for example withdoc.json.materials?.forEach((m) => { m.doubleSided = true; })beforegltfTree. - Unit quaternions are kept to the bit. A rotation given as a quaternion within 1e-12 of unit length is no longer normalised again, so
item.set(item.transform)changes nothing. Matrices, and physics runs started from them, can differ from 0.49 in the last digit.
Known limits: a robot's description holds no mesh and no plane, and a compound's children are solids; a motor, and a sensor on a joint, go on a hinge. Skins and morph targets cannot be written in Scene JSON: describe() says so with item-skin and item-morph.
mote-engine 0.49
0.49 gives a physics world motors. A robot simulated with the engine can now drive its hinges with geared DC servos described by data, next to the sensors of 0.48, and a whole robot with every motor and sensor attached saves and restores exactly. A handful of smaller changes come with it. Scenes and worlds without motors run exactly as before.

Servos on hinges. The components entry point ships its first motor family, dcServoMotor. Register it under the family name your records use, then attach a record to a hinge of a world made with jointSolver: "chain". The servo commands the hinge in position, velocity or torque, whichever its record lists, and its numbers are the record's: two servos are two records, and the same code moves both.
- At the battery's voltage the motor follows its torque-speed line: the stall torque and the no-load speed scale with the voltage.
- The gearbox's backlash, static and viscous friction and the rotor's reflected inertia are modelled, with a current limit that must be above the no-load current (one at or below it is refused).
- A servo holding still does no work, a step allocates nothing, and the servo's state is in the world's snapshot.
import { createPhysicsWorld } from "mote-engine/physics";
import { components, dcServoMotor } from "mote-engine/components";
const world = createPhysicsWorld({ jointSolver: "chain" });
const comps = world.use(components());
comps.registerMotorModel("dc-servo", dcServoMotor);
const motor = comps.attachMotor(shoulder, servoRecord, { voltage: 11.1 }); // shoulder: a hinge of this world
motor.setPosition(0.5); // rad; setVelocity(rad/s) and setTorque(N·m) if the record lists them
const reading = new Float64Array(4);
world.step(1 / 60);
motor.read(reading); // [angle, speed, torque, current]
attachMotor also takes a scene's hinge, the handle scene.physics.hinge(id) gives: the servo follows that hinge through every rebuild of the scene.
Commanding a hinge without allocating. world.writeHinge(hinge, from, at?) sets a hinge's motor, drive, friction and damping from eight numbers of your typed array, and world.readHingeLoad(hinge, out, at?) writes its torque and work into one. They are for controllers that compute their commands at every step.
A whole robot, saved and restored. Motors and sensors of every family share one module, one step and one snapshot. A robot with eight servos and twelve sensors restored from a snapshot continues bit for bit, sensor noise included, in the same world or in a new one built the same way.
Morph weights from the director. The director's set and animate operations take an object's weights, the weights of its morph targets: set writes them at once, animate blends them over the same eases as the other properties. Scene JSON objects and the director's add accept weights too. A list of the wrong length, or weights on an object without morph targets, is refused and writes nothing.
Collapsed objects stop colliding. An object whose scale has a zero component, its own or a parent's, is not drawn, and now its body no longer collides either. Contacts open when it collapses end with one contactEnd, the scene's raycasts miss it, and a dynamic body stays where it is until the scale comes back. In 0.48 such a body kept a thin collider that still collided.
Scene JSON checks driven hinges. sceneFromJson now refuses a hinge with an active drive, friction or damping when the document has physics without jointSolver: "chain", with the field's JSON pointer and the message createScene gives. In 0.48 the document loaded and the scene refused it when it was made. A document without physics is accepted, as before.
Ray. The mesh arena no longer allocates at every frame for each mesh it holds.
Known limits: the servo applies the rotor's inertia and the backlash once per step, so with several sub-steps it can run up to about 20 % faster than the model. Sensors cannot be attached to a scene's hinge yet, and a motor on a scene's hinge leaves with the world when the stage changes. A model's own weights given in the director's add are not checked against its number of morph targets.
mote-engine 0.48
0.48 gives a physics world sensors. A robot simulated with the engine can now read an IMU, its joints' encoders, a 2D LiDAR and a zoned time-of-flight sensor, each at its own rate, with its own delay and noise, and with no allocation in the step. Scenes and worlds without sensors run exactly as before.

Sensors. The components entry point ships the engine's first four sensor families: imuSensor, encoderSensor, lidar2dSensor and tofZoneSensor. A sensor is a record of data with its parameters in SI units; register the families your records name, then attach each record to a body or a hinge.
- Each sensor reads at its own
rate, with alatency. - Its noise comes from a seed: the same seed gives the same readings in every run, and another sensor's draws never change it.
- Readings are copied into your own
Float64ArrayorFloat32Array, withNaNwhere there is no measure. - The sensors' state is saved and restored with the world's snapshot, so a restored run continues bit for bit.
import { createPhysicsWorld } from "mote-engine/physics";
import { components, imuSensor, lidar2dSensor } from "mote-engine/components";
const world = createPhysicsWorld();
const comps = world.use(components());
comps.registerSensorModel("imu", imuSensor);
comps.registerSensorModel("lidar-2d", lidar2dSensor);
const imu = comps.attachSensor(chassis, { position: [0, 0.02, 0] }, imuRecord, { seed: 42 });
const lidar = comps.attachSensor(chassis, { position: [0, 0.05, 0] }, lidarRecord, { group: 2, mask: 1, seed: 7 });
const reading = new Float64Array(imu.size); // [ax, ay, az, gx, gy, gz]
const scan = new Float32Array(lidar.size); // one distance per ray
world.step(1 / 60);
imu.read(reading);
lidar.read(scan);
The LiDAR and the ToF cast their rays in one batch through the world's batched raycast. A full 360-ray LiDAR sweep costs about 0.13 ms. A sensor of another kind is a family of your own, made with createSensor, which gives it the same rate, latency, seeded noise and snapshot.
Reading the world without allocating. world.readPose, readVelocity and readCenter write a body's pose, its linear and angular velocity, and its centre of mass into a buffer of yours. world.readHinge writes a hinge's angle and speed. They are what the sensors use, and are there for controllers that run every step.
Hinges that stay on their axis. A hinge whose load hangs off its axis, such as a wheel mounted beside its arm, twists with the default solver. With physics: { jointSolver: "chain" }, an eight-hinge robot of 1.8 kg turning in place stays within about 0.001° of its axes, where the default twists about 3°. Scene JSON can now ask for it too, with physics.jointSolver and physics.jointHertz, and describe() keeps them. The default solver is unchanged.
Determinism, stated. The manual now says which levels of determinism the world guarantees. The same code, inputs and runtime give bit-identical runs in one process and in separate Node processes on the same host, and a restored snapshot continues bit for bit. It also says what is not promised: other machines, other runtimes, other engine versions, and GPU images.
Known limits: the chain solver is chosen for the whole world or scene, not per hinge, and costs about 2.5 times the default's joint work. The range sensors need a collision group and mask that keep them from seeing their own body. Motors as components (attachMotor with a servo family) come in a later release.
mote-engine 0.47
0.47 lets a model move the way its file says. A skinned mesh now bends with its skeleton, and a mesh with morph targets changes shape, in ASCII, Ray and Wireframe. Models without skins or shape keys draw exactly as before.

Skinning. gltfTree now reads a file's skins. Every bone becomes an object of the scene, and the mesh follows its bones every frame. Move a bone the way you move any object, with set, animate or a timeline track, and the skin bends with it. gltfTracks plays the file's own animation on the bones, so a walk cycle walks.
Morph targets. Shape keys are read too. A mesh with targets gets weights, one number for each target: set them by hand, or animate them with the timeline's new weights kind. gltfTracks now plays the file's weights channels as well, stepped, linear or cubic-spline.
import { createScene, parseGltf, gltfTree, gltfTreeItems } from "mote-engine";
const doc = parseGltf(await (await fetch("/models/squid.glb")).arrayBuffer());
const { items } = gltfTreeItems(gltfTree(doc), { id: "squid", motion: "none" });
const scene = createScene(canvas, { mode: "ray", stages: [{ items }] });
await scene.item("squid/Arm").animate({ rotation: [0, 0, 40] }, 1); // a bone: the skin bends
scene.item("squid/Body").weights = [1, 0]; // the first shape key, fully on
// The second shape key, in and out every 2 s: a `weights` track.
await scene.setTimeline({ version: 1, duration: 2, loop: true, tracks: [{
target: "item:squid/Body", property: "weights",
keys: [{ t: 0, v: [0, 0] }, { t: 1, v: [0, 1] }, { t: 2, v: [0, 0] }],
}] });
The timeline drives physics. A position or rotation track on a kinematic body now moves it at the track's own velocity on every physics step, so whatever it hits is pushed as hard as it really moves. Impulse cues fire once each time the playhead crosses them, even when a slow frame skips past.
Also in 0.47: picks and bounds follow the deformed mesh, and a skin that is not valid is refused with an error naming the skin and the accessor, instead of loading unskinned.
mote-engine 0.46
0.46 lets a model's animation mirror and hide its parts. A scale can now be negative or 0, on any object, in a timeline and in Scene JSON. Scenes that use neither draw exactly as before.
Mirrors and collapses. A negative scale component mirrors the object along that axis: scale: [-1, 1, 1] is its mirror image, drawn the right way round in ASCII, Ray and Wireframe, with its children mirrored too. A component of 0 collapses the object: it draws nothing until its scale changes again, and neither does anything under it. A glTF animation that flips or hides a node now plays as the file has it.
const gear = scene.item("gear");
await gear.animate({ scale: [-1, 1, 1] }, 1); // turns into its own mirror image in 1 s
gear.set({ scale: [1, 0, 1] }); // gone, until its scale is set again
Saved scenes keep their curves. Scene JSON now accepts the timeline's hermite keys, so a scene playing a model's cubic-spline animation is saved and loaded again with the exact same motion.
Also in 0.46: the fire and snow effects no longer make garbage every frame, so scenes with them run without the small pauses of the garbage collector. Ray's still-frame refinement also stays within its frame time when another page or app shares the GPU.
mote-engine 0.45
0.45 lets a model keep its parts. A glTF file can now be read as a tree of nodes, one object for each node, each one under its parent. Its own animations then play on those objects: the walk cycle or the opening door that came with the file. Models read the usual way, with loadGltf, draw exactly as before.
A model as a tree. gltfTree(doc) reads the file's nodes with their hierarchy and gltfTreeItems makes the scene's objects of them. Turn one node and its children follow, about the node's own origin: a door turns on its hinge, not around the middle of its panel. At rest the tree is the same model you get from loadGltf.
import { createScene, parseGltf, gltfTree, gltfTreeItems } from "mote-engine";
import { gltfTracks } from "mote-engine/director";
const doc = parseGltf(await (await fetch("/models/robot.glb")).arrayBuffer());
const tree = gltfTree(doc);
const { items, ids } = gltfTreeItems(tree, { id: "robot", motion: "none" });
const scene = createScene(canvas, { mode: "ray", stages: [{ items }] });
const { timeline, diagnostics } = gltfTracks(doc, tree, ids, { animation: "Walk", loop: true });
await scene.setTimeline(timeline); // diagnostics lists what is not played
Parents and groups for any object. Every object can now have a parent: give it the id of another object of the same stage, and moving, animating or spinning the parent carries the child with it, in ASCII, Ray and Wireframe. An object without a source is a group: it draws nothing and only places its children. Removing a parent leaves its children where they are.
The file's own animations. gltfTracks turns an animation's channels into timeline tracks for position, rotation and scale. Stepped, linear and cubic-spline curves play exactly as the glTF specification defines them. Skins and shape keys are not played yet, and diagnostics says so instead of dropping them silently.
Also in 0.45: effects do less work in their first frames, so scenes with fire, snow or sparks start more smoothly.
mote-engine 0.44
0.44 puts three more effects in the scene's world. In Ray with WebGPU a nebula, a lightning strike and fireworks now stand among your objects: hidden by what is in front of them, seen from any camera, and lighting what is around them. In ASCII, Wireframe and Ray without WebGPU they draw as before.
A nebula in a box. nebula({ volume: { min, max } }) fills a box of the world with glowing gas in filaments, crossed by dark dust lanes, going from color to color2 towards its core. It fades to nothing at the box's faces, the camera can fly into it, and it mixes with fog, smoke, fire and clouds in the same march.
import { createScene } from "mote-engine";
import { nebula, lightning, fireworks } from "mote-engine/effects";
const scene = createScene(canvas, {
mode: "ray", stages: [{ items: [city] }],
effects: [
nebula({ volume: { min: [-2.2, 0.3, -2.5], max: [2.2, 1.6, -0.8] } }),
lightning({ kind: "mixed" }),
fireworks({ ray: { light: true, smoke: true } }),
],
});
Lightning among the objects. A strike now stands on an upright plane through the point it hits. It passes behind the buildings in front of it, and its flash is a real light: it lights and shadows the scene and glows inside the clouds, fog and smoke.
Fireworks that light the night. Each burst lights the scene in its stars' colours and leaves a puff of smoke that the next bursts light up. The light and the smoke cost GPU time while a burst is alive; fireworks({ ray: { light: false, smoke: false } }) keeps the stars alone, at the old cost.
Also in 0.44: smoke follows the wind the same whatever the order of your effects, and scene.seek() refuses to go back after a change that failed halfway, instead of silently undoing it.
mote-engine 0.43
0.43 puts effects inside the scene. In Ray a fire, smoke and fog can now live in a box of the world: hidden by what stands in front of them, seen through glass, lit by the scene's lights, and able to burn and drift together at every quality. Outside Ray, and in ASCII and Wireframe, they draw as in 0.42.
A fire in the scene. fire({ volume: { min, max } }) makes the flames an emissive volume in that box, with embers among the objects and, with light, a flickering light of its own. Flames taller than their box bend under its top and run along it, as in a fireplace.
import { createScene } from "mote-engine";
import { fire, smoke } from "mote-engine/effects";
const hearth = { min: [2.0, 0.4, -2.5], max: [3.0, 1.05, -1.9] };
const scene = createScene(canvas, {
mode: "ray", stages: [{ items: [house] }],
effects: [
fire({ volume: hearth, intensity: 1.2, light: 0.8 }),
smoke({ volume: hearth, density: 0.8, opacity: 0.7 }),
],
});
Smoke and fog in the world. smoke({ volume }) anchors the plume to a box: it rises, pools under the box's top and rolls down its sides. fog({ volume }) is a volumetric fog, densest on the box's floor and thinning with height, that the camera can walk into. Behind a window or a pane, fog, smoke and fire are now seen through it instead of stopping at the glass.
Together at every quality. A volume can leave the march toward local lights (lightMarch: false in a custom volume manifest); fire, smoke and fog do, so all three install side by side at fixed "high" and "ultra", and "auto" no longer drops the scene to the low tier.
Lights you do not see. visible: false on a point, spot or area light keeps its light and its shadows but hides the light itself, in view, in mirrors and through glass — for a light standing in for a fire, or a soft-shadow radius without the glowing ball. Emissive surfaces seen through glass keep their glow.
Also in 0.43: Gaussian splats (INRIA PLY) in Ray and scene.seek() back in time for stepped scenes.
mote-engine 0.42
0.42 opens the engine to an AI: a coding assistant or an agent can load a scene, look at it, stage it and render its frames — all as data, nothing it sends is ever evaluated as code. Working with AI shows how.
Under it, three parts of the director's API are now public, and ASCII and Wireframe scenes still draw as in 0.41 — the director runtime loads only when you reach for it.
A runtime for scene operations. scene.applyOps(opsOrBatch) applies add, remove, set, animate, camera, stage, physics, timeline and render operations to a running scene — the vocabulary that was validation-only in 0.41. Every operation is appended to a capped log (scene.log()); with a stepped clock, replayLog() from mote-engine/director rebuilds any frame from it, bit for bit. A batch is validated whole and refused whole.
Observation. scene.describe() returns the running scene as a reloadable Scene JSON v2 document, with diagnostics and the assets it uses (each with a SHA-256 digest). scene.observe(cb) reports what happened on screen, and scene.project(point), scene.bounds(id) and scene.pick(x, y) answer where a point lands in the frame, where an object sits, and what lies under a pixel.
Scene JSON v2. createSceneFromJson(doc), from mote-engine/director, reads a version: 2 document — the richer shape describe() emits, carrying the camera rig, the clock, the timeline and the log. Version 1 is untouched: every 0.41 document still loads through sceneFromJson(), byte for byte.
mote-engine 0.41
0.41 adds a renderer that comes with the engine: constellation. It draws every object as small wireframe solids riding on its surface, in rows that run into its folds, coloured by how the surface turns towards you, and hides the far side. It is a renderer plugin, so it is mode: "custom"; the other modes draw as in 0.40.

import { createScene } from "mote-engine";
import { constellation } from "mote-engine/constellation";
const stars = constellation({ shape: "tetrahedron", spacing: 0.03, size: 0.0115 });
const scene = createScene(canvas, {
mode: "custom", renderer: stars,
stages: [{ items: [brain] }, { items: [world] }],
});
Morphs between any shapes. When the next stage's objects differ in topology, the solids of the leaving object fly over to places on the arriving one, each on its own arc. Renderer plugins can read the same transition through the new optional RendererItem.weight (0 to 1).
Burst. stars.burst (0 to 1, set at any time, from a scroll position or a clock) sends the solids flying off the surface, and brings them back.
Effects as solids. Particle effects are drawn in the same solid, very small; surface effects (dissolve, hologram, neon, gravity and the others) cut, tint and light the solids as they do the ASCII cells.
Options. shape (tetrahedron, triangle, cube, octahedron or your own corners and edges), spacing, layout (lattice or scatter), size, folds, depth, behind, stroke, spin, glow, pointer, drifters, colors and weight(u, v, w). Options are validated and copied; Canvas 2D alone, no GPU needed.
Wireframe. The GPU pass skips faces behind the nearest opaque one, and a fragment arena that fills no longer paints the frame magenta: it draws what fits and grows. Large meshes pulled apart by tornado or vortex stay fluid. stats().ray.wireframe reports the arena (fragments, capacity, overflow, edges).
mote-engine 0.40
0.40 gives a scene the controls a director needs. A clock that moves only when you step it, cameras that follow and orbit what is on the set, and a timeline that moves objects, lights, the camera and effects over time. Scenes that use none of it draw exactly as in 0.39.
Stepped clock. clock: { time, step } makes a scene whose time advances only by scene.step(frames), each step exactly step seconds. Two runs of the same steps give the same frames, the same physics and the same random numbers.
const scene = createScene(canvas, { mode: "ray", clock: { time: 0, step: 1 / 60 } });
await scene.step(30); // half a second, frame by frame
Camera rigs. scene.setCameraRig(rig) sets a camera the scene evaluates every frame, in every mode: static, path, lookAt, orbit and follow, with an optional fov, roll, handheld noise and a blend from the previous camera. In Ray a moving rig is motion, not a cut, so the picture stays clean while the camera travels. scene.camera reads the camera a frame drew; scene.cameraCut() asks for a hard cut.
scene.setCameraRig({ kind: "follow", target: "car", offset: [0, 1.5, 6], fov: 40, blend: 0.8 });
Scene timeline. scene.setTimeline(doc) installs tracks of keyframes over objects' transforms, visibility and materials, lights, the camera rig, exposure, zoom and effects' live parameters, plus named cues (timeline.onCue tells you when the playhead crosses one). The document is validated whole before anything changes (errors carry a JSON pointer), and playback allocates nothing per frame. The handle (scene.timeline) plays, pauses, seeks and sets the rate. Effects with live parameters (water, clouds, fog, smoke, wind, vortex, magnet) can be animated by the timeline; EFFECT_PARAMS marks them live.
const { ok, timeline, errors } = await scene.setTimeline({
version: 1, duration: 8,
tracks: [
{ target: "item:car", property: "position", keys: [{ t: 0, v: [-3, 0, 0] }, { t: 8, v: [3, 0, 0], ease: "inOut" }] },
{ target: "camera", property: "fov", keys: [{ t: 0, v: 50 }, { t: 8, v: 30 }] }
]
});
timeline.seek(2); // a motion, never a cut
New entry point. mote-engine/director exports the validators (validateSceneOps, validateTimeline) and the timeline compiler and sampler, for tools that prepare scene documents outside the page. The scene loads this code on demand, the first time a timeline is set, so pages that never use it do not download it.
The API change is additive. Behaviour to note:
- An object with a dynamic body is kinematic while a timeline track holds its transform, then dynamic again at rest, as under
animate. - The first
setTimelineloads the director's code;scene.readycovers it.
mote-engine 0.39
0.39 makes Ray volumes hold their picture and makes mode switches cheap. Animated smoke keeps its temporal history, switching back to ASCII is instant, and a sliced scene no longer blocks the page while it resamples.
0.39.1 is the version to install. It draws the black hole in Ray exactly as 0.38 did. 0.39.0 moved that effect onto the public custom-shader parts and drew it wrong in real scenes (a sphere covering the disk a few seconds after the scene opened); 0.39.1 takes that change back, and nothing else. If you installed 0.39.0, update.
The API change is additive. A shader parameter declaration takes an optional history:
params: {
time: { type: "f32", default: 0, min: -1e6, max: 1e6, history: "continuous" }, // a change keeps the history
density: { type: "f32", default: 1, min: 0, max: 4 } // "reset", the default: a change restarts it
}
"reset" is the rule until now: a written change rejects the temporal history of the manifest's volumes once. "continuous" declares a value that evolves smoothly from frame to frame, such as a clock; its changes keep the history, reprojected by the volume's advection. Any other value fails validation, and manifests without the field behave exactly as before. See Custom shaders.
Behaviour to note:
- Animated
smokein Ray (speedother than 0) accumulates its temporal history again (its clock ishistory: "continuous"), and a step of Ray's adaptive internal scale no longer restarts the history ofapi: 1volumes. - Switching a scene back to ASCII reuses its glyph pen's WebGL2 context instead of making a new one each time; at most 4 idle pens are kept on a page. Outside ASCII, after the scene has drawn ASCII,
scene.glyphRendererandstats().glyphRenderermay now read"gpu"(the kept pen) where they read"canvas"before. - A
fireworksshell climbs from four radii of its own star below the edge, not four object-dot radii, so a largerparticleStyle.sizeor a switch to ASCII no longer moves where shells start and burst. - A sliced scene (
sliceLayout: true) no longer blocks the page while its stages are sampled again, for example while the particle count changes: the same points in the same order, computed in steps.GlyphParticles.spawnand thesparksburst no longer allocate for each random number; seeded and fixed-clock results are unchanged.
mote-engine 0.38
One scene API for every renderer. The scene function and its type no longer say ASCII, because the same scene draws in ASCII, Wireframe, Ray and your own renderer. The old names are removed, with no alias; TypeScript points at each use.

| Before 0.38 | 0.38 |
|---|---|
createAsciiScene(canvas, options) |
createScene(canvas, options) |
AsciiScene (and AsciiScene<M>) |
Scene (and Scene<M>) |
AsciiArtOptions, AsciiDust (runArt) |
ArtOptions, ArtDust |
AsciiBlocksOptions (runBlocks) |
BlocksOptions |
renderer: "auto" | "gpu" | "canvas" (what draws the glyphs) |
glyphRenderer: "auto" | "gpu" | "canvas" |
scene.renderer, stats().renderer, type Renderer |
scene.glyphRenderer, stats().glyphRenderer, type GlyphRenderer |
<mote-scene renderer="canvas"> |
<mote-scene glyph-renderer="canvas"> |
mode: "toon", setMode("toon") (a plugin's id as the mode) |
mode: "custom", renderer: "toon", setMode("custom", "toon") |
A renderer plugin draws in the new mode "custom". Give the scene the plugin, or the id it was registered with, as renderer:
import { createScene, registerPlugin, torusKnot } from "mote-engine";
import { createToonPlugin } from "./toon.js"; // your renderer plugin
const toon = createToonPlugin();
const scene = createScene(canvas, {
mode: "custom", renderer: toon,
stages: [{ items: [{ id: "knot", source: torusKnot(2, 3) }] }]
});
await scene.ready;
scene.setMode("ray"); // the same scene, traced
scene.setMode("custom"); // back to the renderer it was given
registerPlugin(toon);
scene.setMode("custom", "toon"); // or one registered by id
SceneMode is now "ascii" | "ray" | "wireframe" | "custom". While a plugin draws, scene.mode and stats().mode read "custom" and stats().rendererPlugin.id names the plugin; before, they read the plugin's id. A plugin's id as the mode still works as a deprecated alias, with the same choice and fallback. renderer now names mode custom's plugin and nothing else: given with any other mode it throws a TypeError that points old glyph code at glyphRenderer. In scene JSON, render.mode takes "custom" with render.renderer; on the element, <mote-scene mode="custom" renderer="toon">. "ascii", asciiScaleDensity and the ascii-scale-density attribute keep their names, because they act in ASCII alone.
In Ray, smoke() is now a 3D volume built on the public custom-shader volume contract: objects hide the plume and the plume hides them, with the camera inside or outside it. SmokeOptions.ray adds temporal and shadows (both on by default). ASCII and Wireframe draw smoke as before.
The natural lens flare draws a starburst of more, thinner rays: 30 for the default 6 blades instead of 18. The cinematic look is unchanged. In Ray on Chrome with Apple GPUs, mirrors show what is beside them again near their silhouette. ASCII picks the exact number of shadow casters among objects without a mesh, and effects in a scene without a fixed clock no longer allocate memory for each random number; seeded and fixed-clock results are unchanged.
mote-engine 0.37
Bring your own shaders. A ray manifest with api: 1 is a stable contract for the volume, light, post, unlit layer and lens part kinds. Existing api: 0 manifests keep working unchanged; changing only the number to 1 opts a manifest into the stability rules. validateRayManifest(manifest) checks a manifest on the CPU, without WebGPU, for authoring tools and build steps, and the part types (VolumePart, LightPart, PostPart, LayerPart, LensPart, SurfacePart) are exported from the package root. See Custom shaders.

A new surface part kind is available as a candidate of api: 1: Ray grows engine-made shells over one scene item and your WGSL decides each shell fragment's coverage and colour. The fur on the home page is built this way. A candidate may still change before it is frozen; ASCII and Wireframe draw the item's base mesh.
In ASCII, an object scaled up on screen keeps the density it has at its own size. This costs more samples; set asciiScaleDensity: false (or scene.asciiScaleDensity = false) on slow systems to keep the 0.36 behaviour. Objects without a mesh, such as point-sampled sources, are now drawn next to meshes in the same stage.
In Ray, settings that rebuild the scene no longer pause the page while the picking structures are rebuilt. In Wireframe and Ray, the heat haze, scanlines and glitch effects draw on the GPU instead of reading the canvas back every frame.
mote-engine 0.36
ASCII caches the constant part of each mesh sample between frames. When changing a raw texture, assign a new RawTexture or replace its pixels array so the renderer sees the change. Editing the same byte array in place leaves the cached image in use.
ASCII pages now load less JavaScript up front. Ray and Wireframe load the GPU rendering modules when requested. A Ray effect with a shader manifest also loads the experimental effect host. Keep the complete installed package together so its lazy imports resolve.
The built-in modes are "ascii", "wireframe" and "ray". Older Dots scenes should select a supported mode and move their independent particle settings to particleStyle. Toon is a renderer plugin. Register the plugin and follow its setup before calling scene.setMode("toon").
A first display-space capture now reads the same pixel values as subsequent captures of the same fixed-clock frame. Use the same browser, renderer, scene and clock when comparing frames.
First scene
Give the canvas a CSS size, then mount the scene when the element exists.
<canvas id="art" style="width: 100%; height: 360px"></canvas>
import { createScene, materials, torusKnot } from "mote-engine";
const canvas = document.querySelector("#art");
const scene = createScene(canvas, {
mode: "ray",
ray: { fallback: "ascii", samples: 32 },
stages: [{ items: [{
id: "knot", source: torusKnot(2, 3),
material: materials.copper, motion: "tumble"
}] }]
});
await scene.ready;
// Release the scene when its view is removed.
// scene.destroy();
Choosing a renderer
| Look | When to use it |
|---|---|
| ASCII | Character-based surfaces, editorial graphics and a fallback on devices without WebGPU. |
| Wireframe | Inspect indexed edges and hidden lines. Use the wireframe options for antialiasing and surface opacity. |
| Ray | Trace reflections, refraction and shadows. Inspect scene.mode for the actual renderer after fallback. |
| Toon plugin | Banded lighting, hatching and outlines from your own renderer plugin, drawn in mode "custom". The showcase uses an example plugin written against the experimental renderer API. |
The material collection shows the same studio lighting on six physical surfaces. materials.glass and materials.diamond set different indices of refraction. Use ray.flare for an optical highlight in Ray mode, and scene.capture({ refined: true }) when a still frame should include the path tracer's accumulated samples.
Browser imports
If you have no build step, unpack the archive and serve the folder that holds index.js next to the rest of your site. An import map keeps the short name:
<script type="importmap">
{ "imports": { "mote-engine": "/vendor/mote-engine/index.js" } }
</script>
<script type="module" src="/app.js"></script>
Working with AI
mote-engine is built to be driven by code, which makes it easy to drive from an AI: a coding assistant that writes your scenes, an agent that directs the camera, or a training loop that needs a world it can reset. Three properties make that work.
- Everything is data. A scene, a batch of scene operations and a timeline are JSON documents. The scene has a published schema in the package,
schemas/scene.schema.json; operations and timelines are checked byvalidateSceneOps()andvalidateTimeline()frommote-engine/director. - Every mistake has an address. The validators never guess: an unknown field or a value out of range is refused, and each error carries the JSON pointer of the field, what was expected and what was found. That is exactly what a model needs to correct itself.
- The same input gives the same frames. A fixed or stepped clock makes time an input. The same document and the same steps give the same transforms, bodies and CPU pictures, bit for bit.
Training worlds. The physical world API runs in Node.js without a browser: bodies, joints, ray queries and snapshots you can restore, for a learning loop that needs a world it can reset. A robot can be written as data too: validateRobotFile() checks its description with the same kind of errors, each with its JSON pointer, and loadRobot() builds it.
Giving an assistant the context. Point your coding assistant at the package's TypeScript declarations (node_modules/mote-engine/dist/**/*.d.ts) and the scene schema above, and ask it to write scenes as JSON rather than as code. Then let it check its own work with sceneFromJson(), which needs no browser, before anything is drawn.
Driving it from outside the browser. The downloadable package installs no command. A process of your own that drives a page with the engine (in a headless browser, for example) gets the same control through the scene's API: scene operations, the timeline, describe() and the validators, with the same determinism.
Scenes an AI can write
A scene written as JSON is checked whole by sceneFromJson(doc). It gives the options to make the scene with, or every error found.
{
"version": 1,
"camera": { "position": [0, 0, 4.2], "target": [0, 0, 0], "fov": 32, "width": 800, "height": 500 },
"objects": [
{ "id": "knot", "shape": "torusKnot", "material": { "preset": "gold" } }
],
"lights": [{ "kind": "environment", "preset": "studio", "intensity": 1 }],
"render": { "mode": "ray" }
}
import { createScene, sceneFromJson } from "mote-engine";
const result = sceneFromJson(textFromTheModel);
if (!result.ok) {
// Send these back to the model: each says where, what was expected and what was found.
return result.errors.map((e) => `${e.path}: ${e.message}`).join("\n");
}
const scene = createScene(canvas, result.options);
An error reads like /objects/0/material/roughness must be a number from 0 to 1, not 2. Unknown fields are refused rather than ignored, so a model that invents an option finds out at once. Parsing never loads the models or maps a document names.
A version 2 document can also keep a hierarchy: an object's parent, groups without a shape, and one node of a glTF file as a shape. A missing parent or a cycle is refused at the object's JSON pointer, and scene.describe() writes a hierarchy back the same way. See A hierarchy in Scene JSON.
A document can name a model file as a shape, { "model": "chair.obj" } (glTF, OBJ, STL, PLY, COLLADA or binary FBX), or an SVG drawing, { "svg": "mark.svg", "depth": 0.08 }. A version 2 document can also declare a glTF file's whole node tree with its camera, its lights and an animation clip, so an AI can work on a scene made in Blender without copying its poses: see From Blender to mote and back. Edits made through scene.graph are not in Scene JSON yet; describe() says which nodes it left out.
Directing a scene
An AI that directs a scene needs a clock it controls, a camera it can aim and a way to plan motion ahead. All three are in the engine.
- A stepped clock.
createScene(canvas, { clock: { time: 0, step: 1 / 60 } })makes a scene whose time moves only whenscene.step(frames)is called. Between steps nothing moves, so an agent can look, decide and act. See the stepped clock. - Camera rigs.
scene.setCameraRig({ kind: "orbit", center: "hero", distance: 6, yaw: 30, pitch: 15, blend: 0.5 })aims the camera at an object or a point, and it follows the object as it moves:static,path,lookAt,orbit,follow, andattach, which puts the camera on an object such as a glTF file's camera node. See camera rigs. - Timelines.
scene.setTimeline(doc)plays tracks of keys over objects, lights, the camera rig and effects, with named cues. A model can write the whole shot as one document, with up to 4096 tracks: enough for a rigged character's whole animation. See the scene timeline.
import { validateTimeline } from "mote-engine/director";
const check = validateTimeline(planFromTheModel);
if (!check.ok) return check.errors; // JSON pointers again, e.g. /tracks/2/keys/1/t
const { timeline } = await scene.setTimeline(planFromTheModel);
validateSceneOps(), from the same entry point, checks a batch of scene operations against the same rules, with the same kind of errors: add, remove, set and animate on an object, a light or an effect, camera, stage, physics impulses, timeline and render, and since 0.54 the spatial operations placeOn, placeRelative, align, distribute and resolveOverlaps, which place objects by their world bounding boxes. Since 0.42 the matching runtime is public: scene.applyOps(batch) applies it to a running scene, every operation is appended to scene.log(), and replayLog() (also from mote-engine/director) rebuilds any frame of a stepped scene from that log. Validation is bounded, so an untrusted document cannot make it run away: depth, nodes and size are capped.
Looking at the scene. An agent that acts needs to see. scene.describe() returns the whole running scene as a reloadable Scene JSON v2 document (the shape createSceneFromJson() reads back), with diagnostics and the assets it uses. scene.observe(cb) reports stage changes, cues and physics events as they happen, and scene.project(point), scene.bounds(id) and scene.pick(x, y) answer where a point lands on screen, where an object sits and what lies under a pixel. For measuring, orthographicView() and drawOrthoMesh() (from mote-engine/director) draw the scene's triangles, read with scene.geometry(visit), as a plan or an elevation at a known scale. See Orthographic views of a scene.
Images for training. To build a dataset, combine a fixed clock with scene.capture(): the same scene JSON at the same time puts every object, light and camera in the same place, so keeping the document is enough to make the frame again. Your own code handles annotation and training.
Guide videos. With a stepped clock, recordVideo() (from mote-engine/video) records the shot as an MP4 file in the browser, and describeShot() (from mote-engine/director) writes the prompt that goes with it for an AI video model: the camera's moves, the subjects, the lights and the look, the same text for the same scene and options. See Exporting a video.
Physical world API
The mote-engine/physics entry point runs in Node.js without a browser or GPU. It supplies rigid bodies, static and kinematic colliders, articulated joints, contact events, batch ray queries and deterministic CPU snapshots. Rendering is optional.
For a learning environment, your application defines the task, action space, observations, reward and episode boundaries. The engine advances the physical state. A policy can command a hinge through setDriveTarget() or setMotor(), or apply forces and impulses to a body. Use a fixed step such as world.step(1 / 60) independently of the display frame rate.
| Operation | Public API |
|---|---|
| Create the environment | createPhysicsWorld({ jointSolver: "chain" }) |
| Add objects and constraints | world.addBody(spec), world.addJoint(spec) |
| Drive a joint | hinge.setDriveTarget(radians), hinge.setMotor(speed, torque) |
| Joints that break, limits that tell | breakForce, breakTorque on a joint; physicsEvents() with onJointBreak and onJointLimit |
| Let go of a kinematic body | body.setType("dynamic", { keepContacts: true }) |
| Move a kinematic body | body.moveTo(position, quaternion) |
| Read physical state | body.position, body.velocity, hinge.angle, hinge.angularVelocity, hinge.torque |
| Read state every step without allocating | world.readPose(body, out), world.readVelocity(body, out), world.readHinge(hinge, out), world.readHingeLoad(hinge, out) |
| Command a hinge every step without allocating | world.writeHinge(hinge, commands) (motor, drive, friction and damping from eight numbers) |
| Simulated motors | world.use(components()), then attachMotor(hinge, record, { voltage }) with dcServoMotor (mote-engine/components) |
| Simulated sensors | world.use(components()), then attachSensor(body, pose, record, { seed }) with imuSensor, encoderSensor, lidar2dSensor or tofZoneSensor (mote-engine/components) |
| A robot from a description file | loadRobot(world, json, catalog, options), validateRobotFile(json) (mote-engine/components) |
| Figures that fall | world.use(physicsPuppets()), then puppets.add(humanoid("mannequin")), puppet.limpOnImpact, puppet.goLimp(), puppet.readPose(out) |
| LiDAR-style observations | world.raycastBatch(origin, directions, range, distances) |
| Nearest hit without allocating | world.raycastInto(origin, direction, maxDistance, hit) |
| Advance time | world.step(dt) |
| Save and reset state | world.snapshot(), world.restore(snapshot) |
A snapshot restores into the same engine version and an identically configured world; snapshots are version 2 since 0.51, and a world that holds a puppet cannot be saved yet. Use the new body and joint handles returned by world.restore(snapshot). With the same engine build, runtime and inputs, a run repeats bit for bit, in one process and across Node processes on the same host, and a sensor's noise repeats from its seed; bit equality across machines, JavaScript runtimes or engine versions is not promised (Physics → Determinism). A miss in a batch ray query is NaN; the optional body-id output uses -1.
The physical-world lab shows recordings of an air dancer driven by seven hinge joints and a LiDAR sweep with measured distances. Download the adapter and episode loop from the training API section, keep them together in a project with mote-engine installed, and run:
node physical-training.mjs
The example adapter exposes reset(), step(action), observe() and scan(). Its action is seven joint targets in radians, clamped to ±1.2. Each action advances twelve 1/60-second steps. Observations contain joint angles and angular velocities; reward is the negative Euclidean error from the target pose. Success requires error below 0.06 radians and each joint speed below 0.15 rad/s. Episodes are truncated after 120 actions. The included controller asks for the target pose; replace it with your policy and training algorithm. No model training is bundled into the engine.
For visual observations, render a browser scene and call scene.capture(). Use sceneFromJson() to validate saved scene descriptions and a fixed clock to repeat a camera view. The vision gallery shows frames from different seeds. Your training code handles annotation, optimisation and model evaluation.
Scan an object in Node.js
The direction buffer packs XYZ triples. Both output arrays use the same ray order. Resolve body IDs to application labels such as a pallet, wall or moving target.
import { createPhysicsWorld } from "mote-engine/physics";
const world = createPhysicsWorld();
const target = world.addBody({
type: "static", shape: { type: "sphere", radius: 0.5 },
position: [0, 1, -2]
});
const labels = new Map([[target.id, "target"]]);
const rays = new Float32Array([0, 0, -1, 1, 0, 0]);
const distances = new Float32Array(2);
const bodies = new Int32Array(2);
world.raycastBatch([0, 1, 0], rays, 5, distances, { bodies });
console.log(labels.get(bodies[0]), distances[0]); // target, 1.5
console.log(bodies[1], distances[1]); // -1, NaN
world.clear();
Quick start
<canvas id="art" style="width: 100%; height: 480px"></canvas>
import { createScene, loadGltf, cssColors } from "mote-engine";
const scene = createScene(document.getElementById("art") as HTMLCanvasElement, {
stages: [loadGltf("/models/logo.glb"), loadGltf("/models/shield.glb")],
colors: cssColors(), // reads --ascii-text and --ascii-accent
});
Each stage holds for five seconds, then the particles melt into smoke and gather into the next one. Add mode: "ray" and the models are drawn as solids with their own materials, ray traced with WebGPU (ascii where the browser has none); add physics: {} and objects with a body fall, collide and can be thrown. The canvas is sized by CSS; the drawing follows its size and the pixel ratio. Call scene.destroy() when the canvas goes away.
The <mote-scene> element
The same scene as an HTML element, for a page with no build step (a CMS, a static site): one script, then the element where the scene goes.
<script type="module">
import { defineMoteScene } from "/vendor/mote-engine/element/mote-scene.js";
defineMoteScene();
</script>
<mote-scene src="/models/logo.glb /models/shield.glb" mode="ray"></mote-scene>
In this example, the contents of the installed dist/ directory are served at /vendor/mote-engine/: serve the whole directory, which holds the element, its modules and the ones Ray, physics and custom effects load when a scene asks for them (an ASCII page fetches neither Ray's nor the physics world's). On upgrade, replace the directory as one unit, so no module comes from another version. With a bundler, register the element through the package export:
import { defineMoteScene } from "mote-engine/element";
defineMoteScene(); // or defineMoteScene("my-scene")
The element is 16:9 of its width unless the page sets its height, draws on a canvas in its shadow root (mote-scene::part(canvas)), and destroys its scene when it leaves the page; moved within the page (an editor reordering blocks), it keeps it. Its colours are --ascii-text and --ascii-accent, read on the element, so a page can set them for one scene.
| Attribute | |
|---|---|
src |
Space-separated stages. A glTF, OBJ, STL or mesh/Gaussian PLY URL (prefix a splat with splat: to force the Gaussian reader), or shape:box, shape:sphere, shape:torus, shape:knot. Defaults to a knot. |
src-normalize |
Set to false to preserve the coordinates of model and Gaussian PLY stages. |
splat-ambient |
Apply ambient and hemisphere lights to Gaussian PLY colours in Ray. |
motion |
turn (default), sway, steady, tumble, none, for every stage |
mode |
ascii (default), ray (solids with materials, WebGPU; ascii where there is none, ray's chunk fetched only then), wireframe (the meshes' edges) or custom (the renderer plugin renderer names; without one, left out with a warning) |
renderer |
with mode="custom", the id of the renderer plugin it draws with (registered with registerPlugin): <mote-scene mode="custom" renderer="toon">. With another mode it is kept for when the mode becomes custom |
glyph-renderer |
auto, webgpu, gpu or canvas: what draws the glyphs (ASCII's characters and the effects' glyphs), as the glyphRenderer option |
morph-style, morph, hold |
as the options of the same names |
autoplay |
autoplay="false" stays on the first stage |
particles, max-particles, ascii-scale-density, font-size, zoom, halo, trails, smoke, interactive, ambient-ripples, reduced-motion |
as the options |
color, accent |
the colours, over the CSS ones |
label |
the picture's accessible name. Default 3D scene, which says nothing: give it |
controls |
native buttons on the picture, as on a <video>: Previous, Pause or Play, Next, and the stage (2 / 3). Tab reaches them, Space and Enter press them, the left and right arrows step the stages from inside them. mote-scene::part(controls), part(control), part(status) |
paused |
stopped. The picture stays, and survives a rebuild and leaving the page; el.paused is the same thing |
label-pause, label-play, label-previous, label-next, label-controls |
the controls' words, for a page in another language |
What the page writes inside the element is its text alternative, so the canvas is not the only channel: see Accessibility.
A boolean attribute is true when present and false as "false"; a value the option does not take is left out with a warning in the console. The scene takes src, motion, mode, morph-style, morph, autoplay, particles, max-particles, ascii-scale-density, font-size, zoom, renderer, glyph-renderer, color, accent, reduced-motion, paused, label, controls and the label-* words as they change; any other attribute, or one of the first ones taken away, rebuilds it on the stage it was showing.
From code:
const el = document.querySelector("mote-scene")!;
el.scene?.goTo(1); // the scene (null while the element is off the page)
el.stages = [{ source: box(), motion: "sway" }, loadGltf("/models/gear.glb")]; // in place of src
el.options = { effects: [snow()], click: explode() }; // what the attributes do not cover; an attribute set wins
el.paused = true; // stops it, as the attribute does: use this rather than el.scene.pause(), it survives a rebuild
el.addEventListener("mote-ready", () => {}); // the sources of the latest load are in
el.addEventListener("mote-error", (e) => e.preventDefault()); // one failed, or the scene could not start (e.detail); the content shows; without preventDefault it goes to the console
Integration recipes
The wrappers below are optional: the engine itself has no React or CMS dependency. Every snippet in this section is the exact source the engine's browser test runs — the React files byte for byte, the element snippet as its own page, the CMS block as the recipe's paste-ready HTML — so mount, draw, updates, unmount and remount are all verified.
Custom element lifecycle
Registration is idempotent, so a page that evaluates the element module twice — two bundles that both register it, a second script URL — defines one class and makes no second scene. The element owns its scene, follows live attributes and CSS resize, and destroys the scene after the disconnection microtask; moving it within the page does not recreate it.
<div id="scene-host" style="width: 480px"></div>
<script type="module">
import { defineMoteScene } from "mote-engine/element";
defineMoteScene();
defineMoteScene(); // no second registration, no second scene
const host = document.querySelector("#scene-host");
const element = document.createElement("mote-scene");
element.setAttribute("src", "shape:box");
element.setAttribute("glyph-renderer", "canvas");
element.setAttribute("autoplay", "false");
element.setAttribute("label", "A rotating box");
element.textContent = "A rotating three-dimensional box.";
element.addEventListener("mote-error", (event) => {
event.preventDefault(); // our status text handles it instead
host.textContent = `Could not start the scene: ${event.detail}`;
});
const ready = new Promise((resolve) => element.addEventListener("mote-ready", resolve, { once: true }));
host.append(element);
await ready;
element.setAttribute("color", "#eeeeee"); // live theme, same scene
element.setAttribute("src", "shape:sphere"); // new source, same scene
host.style.width = "320px"; // observed automatically
element.remove();
await Promise.resolve(); // element.scene is now null
host.append(element); // one new scene, using the same shadow canvas
await element.scene.ready;
</script>
Listen for mote-error and keep fallback HTML inside the element. A rejected load marks data-mote-state="failed"; without preventDefault() the error is also reported to the console. mode="ray" falls back to ASCII when WebGPU or its lazy module is unavailable.
React
The effect cleanup owns scene.destroy(). It runs when the component unmounts, before a shape/mode replacement, and between StrictMode's development setups, so a double mount ends with one live scene. Colours and zoom update the existing scene. The active flag keeps a late scene.ready settlement — in StrictMode's first pass the promise resolves after that scene was destroyed — from reaching an effect that was already cleaned up.
MoteScene.jsx, the component to copy:
import { useEffect, useRef, useState } from "react";
import { box, createScene, sphere, torusKnot } from "mote-engine";
const sources = { box, sphere, knot: torusKnot };
export function MoteScene({ shape = "box", mode = "ascii", color = "#222222", accent = "#006699", zoom = 0.85, onReady }) {
const canvasRef = useRef(null);
const sceneRef = useRef(null);
const readyRef = useRef(onReady);
const [error, setError] = useState(null);
readyRef.current = onReady;
useEffect(() => {
let active = true;
let scene;
setError(null);
try {
scene = createScene(canvasRef.current, {
stages: [{ source: sources[shape]() }],
mode,
glyphRenderer: "canvas",
autoplay: false,
ambientRipples: false,
colors: { text: color, accent },
zoom,
ray: { fallback: "ascii" },
});
} catch (cause) {
setError(cause);
return undefined;
}
sceneRef.current = scene;
scene.ready.then(
() => {
if (active) readyRef.current?.(scene);
},
(cause) => {
if (active) setError(cause);
},
);
return () => {
active = false;
scene.destroy();
if (sceneRef.current === scene) sceneRef.current = null;
};
}, [shape, mode]);
useEffect(() => {
sceneRef.current?.setColors({ text: color, accent });
}, [color, accent]);
useEffect(() => {
if (sceneRef.current) sceneRef.current.zoom = zoom;
}, [zoom]);
return (
<div
data-scene-state={error ? "failed" : "mounted"}
style={{ width: "100%", aspectRatio: "16 / 9", background: "#ffffff" }}
>
<canvas
ref={canvasRef}
aria-label={`A ${shape}`}
style={{ display: "block", width: "100%", height: "100%" }}
/>
{error && <p role="alert">Could not start the scene: {String(error)}</p>}
</div>
);
}
The application mounts it under StrictMode at the root: in development React then runs every effect's setup, cleanup and setup again on mount, and the cleanup above is what leaves one scene alive. main.jsx, complete:
import React, { StrictMode, useEffect, useRef, useState } from "react";
import { createRoot } from "react-dom/client";
import { MoteScene } from "./MoteScene.jsx";
// A still of the scene's first frame, as a CMS would take it for a share image.
function Still({ capture }) {
const canvasRef = useRef(null);
useEffect(() => {
const canvas = canvasRef.current;
canvas.width = capture.width;
canvas.height = capture.height;
canvas.getContext("2d").putImageData(
new ImageData(new Uint8ClampedArray(capture.data), capture.width, capture.height),
0,
0,
);
}, [capture]);
return (
<canvas
ref={canvasRef}
aria-label="A still of the scene"
style={{ width: 120, height: "auto", display: "block", border: "1px solid currentColor", marginTop: 8 }}
/>
);
}
function App() {
const [mounted, setMounted] = useState(true);
const [shape, setShape] = useState("box");
const [dark, setDark] = useState(false);
const [zoom, setZoom] = useState(0.85);
const [narrow, setNarrow] = useState(false);
const [readyShape, setReadyShape] = useState(null);
const [still, setStill] = useState(null);
const [captureError, setCaptureError] = useState(null);
return (
<main>
<h1>React lifecycle</h1>
<p>
<button
id="toggle"
type="button"
onClick={() => {
setReadyShape(null);
setStill(null);
setCaptureError(null);
setMounted((value) => !value);
}}
>
{mounted ? "Unmount" : "Mount"}
</button>
<button
id="theme"
type="button"
onClick={() => {
setDark((value) => !value);
setZoom((value) => (value === 0.85 ? 1 : 0.85));
}}
>
Change props
</button>
<select id="shape" aria-label="Shape" value={shape} onChange={(event) => setShape(event.target.value)}>
<option value="box">Box</option>
<option value="sphere">Sphere</option>
<option value="knot">Knot</option>
</select>
<button id="resize" type="button" onClick={() => setNarrow((value) => !value)}>
Resize
</button>
</p>
<div id="host" style={{ width: narrow ? 320 : 480, maxWidth: "100%" }}>
{mounted && (
<>
<MoteScene
shape={shape}
color={dark ? "#eeeeee" : "#222222"}
accent={dark ? "#66ccff" : "#006699"}
zoom={zoom}
onReady={(scene) => {
setReadyShape(shape);
// MoteScene calls this with the live scene only: in StrictMode's
// first pass the scene is destroyed before its ready settles, and
// a destroyed scene rejects capture with "destroyed".
scene.capture().then(
setStill,
(cause) => setCaptureError(cause?.message ?? String(cause)),
);
}}
/>
{still && <Still capture={still} />}
{captureError && <p role="alert">Could not capture a still: {captureError}</p>}
</>
)}
</div>
<p id="status" role="status">
{mounted ? (readyShape === shape ? `Ready: ${shape}` : "Loading") : "Unmounted"}
</p>
</main>
);
}
// StrictMode at the root: in development React runs every effect's setup,
// cleanup and setup again on mount, exactly as a real double mount does.
createRoot(document.querySelector("#root")).render(
<StrictMode>
<App />
</StrictMode>,
);
The example's onReady captures a still of the ready scene with scene.capture(), which a destroyed scene rejects with destroyed: the guard above is what keeps that callback on the live scene. Pass new shape, color, accent or zoom props through your normal React state.
CMS and static HTML
Serve the installed package's dist/ directory, whole, under a versioned URL such as /vendor/mote-engine/0.50.0/: the element module and every module it loads, those Ray and physics load on demand included. Replace that folder as a unit on upgrade. Load the module once per page, even with several scenes: loading it again under another URL evaluates it again and still registers one class and no second scene.
<script type="module">
import { defineMoteScene } from "/vendor/mote-engine/0.50.0/element/mote-scene.js";
defineMoteScene();
</script>
<mote-scene
id="scene"
src="shape:box"
mode="ascii"
glyph-renderer="canvas"
autoplay="false"
ambient-ripples="false"
label="A rotating box"
style="width: 480px; max-width: 100%"
>
<p>A rotating three-dimensional box.</p>
</mote-scene>
The CMS editor owns insertion and removal: removing the tag destroys its scene, and no React runtime or server-side engine component is required. Any site builder that takes custom HTML — WordPress, Wix, Squarespace, Webflow — can host this block; keep the fallback paragraph inside the element so the canvas is never the only channel.
Scenes, stages and objects
A scene is a list of stages. A stage is one or more objects shown together, and the scene morphs from stage to stage. A stage can be written in three ways:
stages: [
loadGltf("/models/monkey.glb"), // a source: one object, turning
{ source: box(), motion: "sway", transform: { scale: 0.8 } }, // one object
{ // several objects
hold: 8,
items: [
{ id: "left", source: torus(), transform: { position: [-0.9, 0, 0], scale: 0.5 }, motion: "tumble" },
{ id: "right", source: loadGltf("/models/gear.glb"), transform: { position: [0.9, 0, 0], scale: 0.5 } },
],
},
]
The scene's space has y up, x to the right and z towards the viewer, as in glTF. One unit is half the smaller side of the canvas (times zoom, 0.85 by default). Every source is normalised to fit a sphere of radius 1, so an object at scale 1 fills most of the height of a square canvas, whatever its size was in Blender.
Moving between stages:
// createScene(canvas, { stages, stage: 2 }) starts on stage 2
scene.goTo(2); // morphs to stage 2
scene.show(0); // shows stage 0 at once, no morph
scene.morphStyle = "explode"; // "smoke" (default), "direct", "swirl", "explode"
scene.morph = 2.5; // seconds a morph takes
scene.next();
scene.previous();
scene.autoplay = false;
await scene.setStages([...]); // a new list, resolves when the models have loaded
await scene.setStages([...], 3); // the same, showing stage 3 from the first frame
await scene.ready; // every source of the current list loaded
Object IDs across stages
Give objects distinct IDs across the whole scene, and update their parent references together when renaming them. This works with the current API:
const scene = createScene(document.querySelector("canvas")!, {
autoplay: false,
stages: [
{ items: [
{ id: "entry-door", source: box(), motion: "none" },
{ id: "entry-handle", parent: "entry-door", source: box(), transform: { scale: 0.1 } },
] },
{ items: [
{ id: "exit-door", source: box(), motion: "none" },
{ id: "exit-handle", parent: "exit-door", source: box(), transform: { scale: 0.1 } },
] },
],
});
await scene.ready;
scene.item("exit-door")!.set({ rotation: [0, 45, 0] });
scene.show(1);
Existing programmatic scenes with repeated IDs remain usable: scene.item(id) keeps its existing resolution. The internal scene graph identity check reads every stage and reports duplicates and reserved IDs without renaming objects or changing that lookup. Reserve @root, IDs starting with @root/, and IDs starting with @legacy/ for the engine. The graph facade rejects ambiguous scenes with invalid when scene.graph or scene.graphAt is accessed. Migrate by renaming IDs and their references in the original stage data, then recreate the scene or call setStages with the corrected data.
Moving objects
Every object has a transform (position, rotation, scale) and a motion that runs on top of it.
const gear = scene.item("right")!;
gear.set({ position: [0.5, 0.2, 0], rotation: [0, 45, 0], scale: 0.7 }); // at once
await gear.animate({ position: [0, 0, 0.5], scale: 1 }, 1.5); // eased, in 1.5 s
gear.motion = { spin: { axis: [0, 0, 1], speed: 40 }, tilt: 20 }; // degrees per second
console.log(gear.transform); // { position, rotation (quaternion), scale }
rotationtakes Euler angles in degrees, applied X, then Y, then Z (Blender's XYZ Euler), or a quaternion[x, y, z, w].scaletakes a number or a vector. When an object grows or shrinks a lot, the scene samples it again, so the surface keeps the same density on screen.- A negative component mirrors the object along that axis:
scale: [-1, 1, 1]is its mirror image, drawn the right way round in ASCII, Ray and Wireframe (its faces, their normals, the shading and the picks are the mirror's), and a parent's mirror is composed into its children as any transform. Two negative components are a half turn, not a mirror. - A component of 0 collapses the object: it is drawn as nothing (no surface, shadow, reflection, Wireframe edge or pick, and no mesh effect runs on it), says nothing in the console, and is drawn again as soon as its scale is another. So does every object under it, since a parent's scale is part of theirs (and a child left without its parent while collapsed,
scene.remove, stays collapsed, as it was drawn). This is also what an animation passing from a scale to its mirror goes through, for the one frame it is at 0. Objects drawn from points alone (a figure, a code panel: no triangles) keep their points instead, flattened onto the plane the scale leaves; with a scale of 0 on every axis they too draw nothing. - How thin an object is does not collapse it: under a parent of scale
[1, 1, 1e-6]a child is drawn, a millionth thick. Only a 0 does, in its own scale or in one above it. - A scale is finite:
NaNor an infinity is aTypeErroratcreateScene,setStages,spawn,setandanimate, before anything changes (as the timeline, Scene JSON and the scene operations refuse them). - A body follows either (see Physics): a mirrored object collides as its mirror image. While an object is collapsed, its body has no contacts and scene physics raycasts do not hit it. Every contact or sensor overlap already open emits one
contactEndorsensorExitwhen the collapse starts; nocontactBegin,contactPersist,impactorsensorEnteris emitted until the scale returns. A dynamic body stays where it is: settingvelocityor callingapplyImpulseis ignored, and both linear and angular velocity are zero on return. When a nonzero scale returns, so does the collider for the current scale, and a body still touching it begins a new contact.
- A negative component mirrors the object along that axis:
motionis one of:"turn": all the way round, tilted a little;"sway": left and right, so the front stays readable;"steady": a little sway, for words and logos;"tumble": spins around its own axis, tilted towards you, for rings and knots;"none";- a custom motion:
{ spin: { axis, speed }, sway: { axis, amplitude, period }, tilt }.
An object can be hidden and shown again where it is: gear.visible = false (or visible: false in its ItemSpec). Hidden, it is absent from the picture in every mode (no surface, shadow, reflection or Wireframe edge, and it hides nothing behind it), and pointer picks and scene.physics.raycast pass through it. Everything else goes on: its motion, its mesh effects, a morph in progress and its body, which is simulated and collides as before. Showing it rebuilds nothing.
For an animation of your own, change transforms in onFrame:
createScene(canvas, {
stages: [...],
onFrame: (t, scene) => scene.item("planet")?.set({ position: [Math.cos(t) * 0.5, 0, Math.sin(t) * 0.5] }),
});
Parents and groups
An object can move with another: give it parent, the id of an object of the same stage. Its transform is then in its parent's frame, and every frame it is drawn with its ancestors' matrices times its own (each T × R × S, the object's motion in its rotation). Moving, turning or scaling a parent, by set, animate, a timeline track, its motion or its body, moves its children exactly so, in ASCII, Ray and Wireframe alike.
stages: [{
items: [
{ id: "arm", source: box(), motion: "none", transform: { position: [-0.4, 0, 0], scale: [0.5, 0.1, 0.1] } },
{ id: "hand", parent: "arm", source: sphere(), motion: "none", transform: { position: [1, 0, 0], scale: [0.4, 2, 2] } },
{ id: "rig", motion: "none" }, // no source: a group
{ id: "lamp", parent: "rig", source: loadGltf("/models/lamp.glb"), transform: { position: [0.6, 0.5, 0], scale: 0.3 } },
],
}]
scene.item("arm")!.set({ rotation: [0, 0, 45] }); // the hand goes round with it
scene.item("hand")!.parent; // "arm"
scene.item("hand")!.transform; // still its own: position [1, 0, 0] in the arm's frame
- The frame is the parent's own space, the one its source is in: for a normalised source, the unit sphere around its centre. A child at position
[1, 0, 0]sits one parent radius to the right of the parent's centre, before the parent's own scale and rotation; at scale 1 its unit sphere is as large as its parent's. Nothing is fitted again when transforms compose: each source stays normalised on its own, and the scales multiply. So under a parent of scale 0.5, a child of scale 1 is drawn at 0.5. - A group is an object without a
source: it draws nothing, has no body and takes no effect, and is there to place its children. Use one as a pivot, or to move several objects together. - A rotation under a parent stretched unevenly (
scale: [0.5, 0.1, 0.1]above) shears the child. It is drawn with the exact matrix; what needs a position, a rotation and a scale apart (its body, its sampling density) reads the nearest ones. - Bodies: a child's body is where the child is drawn, and is carried there. A dynamic one is kinematic while it has a parent (as under
animate: it pushes what it meets and nothing pushes it), a kinematic one is led there, a static one put there when it moves. A parent with a dynamic body carries its children as any parent does. scene.remove(id)of a parent leaves its children where they are drawn, without a parent: their transforms become the scene's, and a child with a motion of its own goes on from that pose (an animation in flight on it ends).scene.spawn({ parent, ... })adds a child to an object already there.- A
parentthat is not an object of the stage (by itsid; an object without an id cannot be a parent), or a cycle of parents, is aTypeErrorwhen the scene is made, atsetStagesand atspawn(which rejects), and nothing changes. - Scene JSON (version 2) has the hierarchy: an object's
parent, a group as an object without ashape, and one node of a glTF file as a shape.scene.describe()writes it so, each child with its own transform, and the document loads back as the same hierarchy. See A hierarchy in Scene JSON. - A rotation given as a quaternion (in a
transform, toset,animateandspawn, in a Scene JSON document, in anaddorsetoperation) is kept to the bit when its length is within 1e-12 of 1, and normalised otherwise, as it always was. Three numbers are Euler angles, as ever. So a transform read and given back is the same transform:item.set(item.transform)changes nothing, and a hierarchy written bydescribe()composes to the same matrices when it is loaded. A quaternion read from a file (unit in single precision, about 6e-8 off) and one of any other length are normalised exactly as before.
Using the scene graph
The 0.56 scene graph exposes each stage's tree and supports detached creation, attachment and removal:
const scene = createScene(document.querySelector("canvas")!, {
autoplay: false,
stages: [{ items: [
{ id: "room" },
{ id: "door", parent: "room", source: box(), motion: "none" },
] }],
});
await scene.ready;
const graph = scene.graph;
const door = graph.getById("door");
console.log(door?.parent?.id); // "room"
console.log(graph.root.children.map(node => node.id)); // ["room"]
graph.traverse(node => console.log(node.id)); // root, room, door
console.log(graph.find(node => node.id === "door") === door); // true
scene.destroy();
scene.graph selects the current stage, or the destination during a morph.
scene.graphAt(index) selects one existing stage; its searches cannot find
objects in another stage. IDs must be unique across the whole scene. Legacy
duplicates and reserved IDs cause an invalid error on graph access and leave
the scene unchanged. Each synthetic root has ID @root/<index> and no parent
or item. Nodes expose the existing item through node.item; ItemHandle.parent
continues to return a string. children is a frozen insertion-order view, stable
until a structural edit. Searches and visits use depth-first preorder including
the starting node; misses return undefined. Mutating scene APIs during find
or traverse throw traversal (asynchronous spawn rejects); nested visits are
allowed up to 16 levels and release the block even when a callback throws.
The visit guard does not cover direct writes to live data such as lights,
shadows, effects or material fields, replacement of writable data properties
such as debug, or raw physics bodies exposed by puppet bones. These remain
open limits; use scene methods, item setters and item body controls for guarded edits.
The graph exposes identity, relations, item, queries and the transforms below.
glTF nodes keep their existing IDs, names and supplied URL provenance; a node can
have mesh, camera, light and bone roles together. Skin joints follow their declared
order and the model is fitted once. Detaching a joint restores bind pose with one
diagnostic until it returns; reattachment resolves live nodes without reviving old handles.
name, bone, provenance, cameraDefinition and lightDefinition are internal glTF item
metadata, not authored ItemSpec fields: ordinary inputs reject them with a
TypeError naming the JSON pointer before changing the scene. Items returned by
gltfTreeItems carry a protected loader snapshot, preserved by object spread;
editing their descriptive metadata does not change the graph. Use NodeSpec
for graph authoring.
glTF loader snapshots populate node.camera and node.light; their public descriptive
fields remain independent copies. Light data retains file units; gltfSceneLights
remains the explicit fitted photometric adapter, without duplicate rendered lights.
graph.useCamera(node) selects an attached perspective camera in the current stage;
useCamera(null) restores the saved rig. Detach freezes its last pose. Orthographic
data stays readable, but selection throws unsupported-projection; FOV and clip
reductions are diagnosed. Graph-created lights use local positions/directions,
follow their parents once and stop lighting while detached, within the existing
light limit. Legacy light attachments retain their origin/axis behavior. A legacy
Light.attach target's light role is snapshotted when its node handle is created;
later attachment edits do not recompute that handle's role list.
graph.create({ id, helper: { kind: "axes" } }) adds inspection overlays in
ASCII, Wireframe, Ray and custom modes. Helpers support axes (default size 1),
an XZ grid (default side 2, 10 divisions; 1–256 divisions), and box, light
or camera with a same-stage node ID in target. Axes and grids follow their
own composed transform. Boxes include mesh descendants and current skin/morph
deformation; icons follow their target. Directional and spot arrows both point
in the direction light travels. Perspective frusta use the viewport aspect and
the selected camera's viewer policy (FOV 5–150°, near .001, unbounded far), with
the drawable far plane shortened to keep depth and half-extents within 1000
scene units. Like the selected camera, perspective inspection normalizes the
target's orientation so inherited scale/shear does not skew the projection.
Orthographic frusta retain their authored extents and clips.
Box/light/camera helpers require identity TRS at creation and reject every later
TRS setter, including identity writes, with GraphError kind invalid at
/transform. They may be detached or direct children of the stage root only.
No helper may parent or target another helper; helpers may parent non-helper
nodes. These rules also apply while detached. Rejected setters and topology
batches preserve all nodes, history and ready. If a target ID is removed and
recreated during helper preparation, publication rejects with invalid at
/helper/target; retry creation to bind the new incarnation.
Helpers reuse the existing debug primitives: ASCII draws X/Y/Z glyphs and at
most one glyph per handle/cell/frame; graphical axes use distinct radii 1/2/3
CSS pixels as well as color. Wireframe and Ray share the existing 4096-dot
budget with public debug primitives. Helpers are depth-tested, including the
WebGL2/ASCII fallbacks. In ASCII the test compares against the nearest sampled
surface point in each cell, so a sparsely sampled occluder (a large or very near
object beyond maxParticles, or asciiScaleDensity: false) can let helpers and
scene.debug primitives show through its gaps. Ray draws them after composition, outside lighting,
reflections, BVH and temporal/path-tracing history. Custom renderer plugins
expose no readable depth: the overlay follows their output without occlusion,
with one projection-reduced warning per scene. Display capture() includes
the overlay, including refined Ray stills; linear capture retains its raw Ray
radiance contract, before display inspection and decorations.
Overlay support loads lazily when helper topology is linked and joins scene.ready.
If the overlay chunk fails to load, a helper overlay did not load warning names
the cause; scene.ready settles with inspection unavailable and public debug
drawing still usable, like the Ray loader's fallback.
Updates reuse buffers after composition/deformation; boxes share bounds of only
their target subtrees, selected once per topology change.
enabled: false hides only inspection. Missing, detached or collapsed targets
hide their helper with one missing-target warning per absence transition;
reattachment or restoring scale resumes it. Removed IDs never reconnect.
Mode changes, detach, replacement and destruction release internal draw handles;
detached nodes retain their preallocated geometry for reattachment. Helpers
participate in traversal and node/helper limits but have no Source, collider,
mesh, shadow, occlusion, pick or spatial-operation target.
Public debug drawing (scene.debug.points / scene.debug.lines) keeps the same
API and shared budgets. In custom mode, starting with 0.56, it draws after the
effects over-layer and the plugin output, even without helpers. While any helper
is attached (including disabled helpers), the shared overlay also draws public
primitives without depth occlusion or the scene cell mask (nearest = Infinity,
room = 1), because plugins expose no readable depth. Detaching all helpers
restores the ordinary public depth/mask inputs; the custom draw order stays the
same. ASCII, Wireframe and Ray keep their existing public debug depth behaviour.
Internal structural preflight checks a proposed batch before resource preparation:
4096 nodes per stage including the root, detached nodes and fit nodes, 64 real
ancestors, 256 helpers, and 1024 UTF-8 bytes per new ID or name. It rejects cycles
and cross-stage parenting without changing the scene. These limits do not restrict
queries on previously accepted legacy scenes. On a stage already above one of them,
structural edits, create and empty batches included, are refused with a limit
error; a reparent that repairs excessive depth can pass. Concurrent create calls
wait in the operations queue and are each rechecked before fetching, so the ones
beyond a limit are refused before any download.
create validates and copies a serializable NodeSpec, reserves its ID across all
stages, then waits in the scene's operations queue for its assets:
const node = await scene.graph.create({
id: "panel",
object: { shape: "box", material: { color: "#6688cc" } },
transform: { position: [1, 0, 0] },
});
console.log(node.attached); // false
console.log(scene.graph.getById("panel")); // undefined
console.log(node.getById("panel") === node); // true
Shapes use the same loader as Scene JSON v2: primitives, model files, glTF
(including one named or indexed node), SVG and Gaussian splats. A whole gltfTree
is not a single-node shape. Motion defaults to none. Until attached, new nodes
are not drawn; attaching one makes it render, and a body on it joins the physics
simulation once attached. They never enter legacy item lookup;
node.item is reserved for existing legacy items. Optional names, provenance and component data are copied and exposed
read-only; cameras and lights use the component behavior described above.
Duplicate IDs, including puppet IDs and future puppet parts, reject before fetching.
Failures and cancellation release the reservation without publishing a partial node.
Pausing cancels queued creation; setStages and destroy also release detached
storage and make old handles report alive === false. A loader already in flight
may finish, but its result cannot publish after cancellation. Stage replacement
and destruction reject pending creates and release their preparation jobs even
while a module or asset is still loading. Successful creation
marks the operation history incomplete; describe() reports detached nodes omitted
from Scene JSON v2, and graph-created nodes as unserializable even once attached.
Creation errors have GraphError.kind and path: module/asset failures use load,
and pausing queued work uses paused. An already paused scene uses busy.
Precedence follows execution: visit/lifecycle/morph guards, bounded input copy and
identity/structural checks and ID reservation, the seek/replay busy guard, Director
loading and pause admission, then queued
readiness, structural rechecks, lazy module loading, payload validation and assets.
Cancellation wins over a pending load; publication rechecks lifecycle and structure.
Attach, transfer or detach nodes with the same handles:
const group = await scene.graph.create({ id: "assembly" });
scene.graph.root.add(group);
group.add(node); // keeps the node's local transform
node.removeFromParent(); // keeps the node and its resources
scene.graph.root.add(node); // visible at the end of the root's children
parent.add(a, b) transfers all arguments atomically within one stage. New
children append in argument order; existing children keep their position, and
repeated arguments count once. parent.remove(a, b) detaches direct children;
other children are no-ops. Detached subtrees retain IDs, handles, geometry and
local transforms. Reattaching reuses the same CPU mesh and material. Legacy removal,
stage replacement and scene destruction release owned CPU storage once, including
detached meshes, without disposing borrowed sources or changing another item
sharing the source. ASCII sampling pauses while detached and reuses the mesh's
samples on reattachment; removal and teardown clear owned sample caches without
invalidating another node that shares its source. Wireframe drops cached mesh
references at these structural changes; its render buffers are released when leaving
the backend or destroying the scene, including when nodes are detached. Ray detachment
retires pending preparation immediately and completed CPU preparation claims at the next
scene frame or mode/device release boundary. A same-task or microtask reattach before
that boundary retains completed BLAS/preview preparation; after retirement it rebuilds
from the retained CPU geometry. Removal and destruction release only their own cache
claims and never submit late GPU work. Root queries exclude detached nodes; their
handle queries still work.
Their world matrices compose from the detached root's local transform. Cycles,
cross-stage transfers, using the root as a child and individual puppet-part transfers reject
before changing relationships. No-op edits preserve views and history; effective
edits mark history incomplete. The common busy, transition and traversal
guards apply even to no-ops. Detach removes subtree bodies from simulation and
closes each active contact or sensor pair once, delivered on the next physics tick.
Reattachment starts from the current pose with zero linear and angular velocity;
body commands while detached do not accumulate. Destruction also releases detached
body state. A reattached body also re-enters at rest when its stage is later hidden
and shown again. A contact end queued at detach is not delivered if the scene is
destroyed or its stages are replaced before the next physics tick; while physics is
paused it is held and delivered once, on the first tick after resuming. Detach also cancels every running tween in the subtree at its current
local pose and resolves its promise once; reattachment does not restart it. Graph
TRS edits and transfers that stay attached keep tweens running. Legacy removal,
stage replacement and scene destruction also settle pending tweens on detached
items. Mesh effects and their emitted particles pause while detached, retaining
bounded state, geometry and materials. Reattachment resumes without catch-up
emission; removal, stage replacement and scene destruction clear the owned effect
pools once, including detached nodes. This also applies to CPU fallbacks. Detach
suspends joints; reattachment recreates each once, with the same local anchors, axes
and limits, only when both bodies are active (or the sole body for a world anchor).
Recreated joints may emit jointLimit again. If the stage is hidden and shown
while an endpoint is detached, its suspended binding is discarded: reattachment
recalculates anchors from the stage definition at the current body poses.
Broken joints stay broken. Parent authority changes at the topology commit without
a physics step; the fixed rate remains 60 Hz. Destruction clears suspended joint
registrations too. Legacy removal and respawn keep their existing joint behavior.
An effective topology edit stores the stage's objects in depth-first order, so the
order describe() lists them, and the by-position pairing a stage morph uses, can
change for that stage; scenes that never edit the graph keep their order.
Removing a legacy item invalidates its node handle; setStages and destroy
invalidate all old handles, including detached nodes and roots. Dead handles keep
their final transforms, world matrix and metadata, report alive and attached
as false, and expose no parent, children or item. Their queries visit only themselves;
node edits throw stale. Reusing an ID creates a new incarnation. Retained stage
facades also throw stale after replacement or destruction. Roots cannot be removed
individually. Legacy spawn rejects IDs owned by graph-created nodes, attached or
detached, and automatic IDs skip them; legacy remove still addresses legacy items only.
The internal node listener registry suspends delivery while detached and unsubscribes once when its
incarnation ends. Queued callbacks become inert; destruction also closes scene inputs,
observers and cue subscriptions. Scene-wide observe() subscriptions survive setStages.
There is no public node listener API. After destruction, observe() returns an
inert unsubscribe, including on scenes using seek. Destruction is checked before
callback type validation: even an invalid late callback returns a no-op; on a live
scene a non-function callback throws TypeError.
Local transforms and world matrices
On an existing scene with a "door" object, move it in its parent's space and
read its exact world matrix:
const door = scene.graph.getById("door")!;
door.position.set(1, 0, 0);
door.setTransform({ rotation: [0, 45, 0], scale: [-1, 2, 1] });
const world = new Float64Array(16);
door.copyMatrixWorld(world);
console.log(world[12], world[13], world[14]); // scene-space position
position, quaternion (x, y, z, w) and scale are stable live views with
read-only components and chainable .set(...) / .copy(tuple) methods.
setTransform accepts partial local transforms; Euler input is in degrees,
X then Y then Z. Inputs are copied and validated atomically; signed and zero
scales are supported. Quaternion normalization matches item setters and preserves
already-unit values within 1e-12; input norms below 1e-12 are rejected with invalid.
Graph writes leave existing tweens running toward their original targets;
item.set retains its cancellation behavior. Use timeline tracks for animation.
matrixWorld is a live read-only view of 16 column-major doubles, including
ancestors, motion and the current interpolated body pose, without the camera or
view rotation. It preserves shear exactly. Retaining the view does not capture a
snapshot; copyMatrixWorld(out) writes the first 16 entries of a caller-owned
Float64Array. Warm TRS/facade reads and matrix copies allocate no storage and never
step the clock or solver. For per-frame use, call allocation-free copyMatrixWorld(out)
with reused storage. Reading matrixWorld[i] component by component may allocate
a number in some JavaScript engines.
Each stage keeps its own transforms during a morph; the synthetic root stays
immutable identity and never becomes a physics parent. Writes during graph visits
throw traversal; writes during a morph throw transition. Pending batches,
steps, seeks, replay, preparation and frame callbacks reject synchronous writes with busy,
before state or history changes. Await pending work and scene.ready, or the
morph hold, before editing. Effective edits mark scene.log().complete false
and expose the first frame and reason in unrecorded, also in describe().log.
No-op and rejected edits preserve history. Graph commands/replay and Scene JSON v3
are scheduled for 0.57. The 0.56 JSON v1/v2 loaders and schema have no graph fields.
describe() still returns a v2 document. It sets complete: false for each
unrepresentable helper, detached node, camera/light component, glTF node metadata
or graph-created node, including nodes already attached. Diagnostics include the
node ID and a JSON-pointer-like path into the runtime stage's items or detached
array; detached-node identifies detached omissions, and unserializable identifies
graph creation and omitted metadata/components. The remaining mesh/group data stays
v2-compatible. A declarative gltfTree can preserve its original nodes through the
file declaration; edits it cannot preserve retain tree-item diagnostics. Setup
completeness and describe().log.complete are independent: a representable TRS edit
can leave the setup complete while making unrecorded history incomplete.
The graph's public types are exported from the root API: SceneGraph, GraphScene, NodeHandle, NodeQuaternion, NodeSpec, NodeRole, NodeCamera, NodeProvenance, HelperSpec, DeepReadonly, GraphError and GraphErrorKind. Graph visits release their mutation block in a finally, so a callback that throws leaves the scene editable.
Models from Blender
The reader takes glTF 2.0: .glb, or .gltf with its .bin next to it or embedded. In Blender use File › Export › glTF 2.0 with:
- Format: glTF Binary (.glb);
- Transform › +Y Up: on (the default);
- Mesh › Apply Modifiers: on, so subdivision, bevels and mirrors are exported as you see them;
- Data › Compression: meshopt is decoded natively; Draco requires
loadGltfwith an application-supplied decoder. For synchronous loading, export without Draco or provide an optional uncompressed fallback. See External glTF decoders.
Both EXT_meshopt_compression and KHR_meshopt_compression work without a decoder download or any setup. The reader supports vertex streams v0 and v1, triangle and general index sequences, and the OCTAHEDRAL, QUATERNION, EXPONENTIAL and COLOR filters. A placeholder or marked uncompressed fallback buffer is not fetched when the compressed data is present. Compressed output is limited to 64 MiB per buffer view and 256 MiB per model; malformed streams are refused before their output is allocated.
const source = await loadGltf("model.glb"); // compressed or uncompressed glTF 2.0
What is read:
- every mesh of the scene, placed by its object's transform and its parents' (a model built from parented parts keeps its layout);
- smooth or flat shading as set in Blender (vertex normals). Edges where the surface bends sharply are drawn a little brighter, so the shape reads;
- the materials: for colour (see below), and in ray as the physical materials they are.
Animations, armatures and shape keys are not read by this flat loader (a model read as a node tree plays all three: A model as a tree of nodes); textures are drawn in every mode: per pixel in ray and wireframe, as each glyph's colour in ascii (see Render modes), and in ray a model keeps its own materials (see Materials: Blender's Principled BSDF as glTF exports it, transmission, IOR, volume, clear coat and textures included). Points, lines and curves have no surface and are skipped; convert text and curves to meshes first (Object › Convert › Mesh).
A file's cameras are not read by this flat loader either. A model read as a node tree takes them, and their animation with them: A model's cameras.
Everyday object library
The examples include 30 original procedural everyday objects for scene prototypes: furniture, kitchenware, appliances, vehicles and street fixtures. A catalog records each model's category, size in metres, named anchors and their positions, licence, content hashes and preview. Sizes are [width, height, depth] in glTF's Y-up frame. Load these models with normalize: false to preserve their real scale.
Anchors are empty glTF nodes with names such as anchor.seat, anchor.back, anchor.top, anchor.handle, anchor.door, anchor.driver_seat and anchor.wheel.fl. They give spatial tools stable places for sitting, placing objects, opening parts and locating wheels. The catalog has a JSON Schema 2020-12 definition; all geometry, colours and small PNG previews regenerate from one script without downloaded assets.
Colours
Characters come in two colours by default: the theme's text colour, and the accent for every material whose name contains accent (for example accent, accent glass). With colors: "material" each material keeps its own base colour (converted from Blender's linear colour to sRGB), and accent materials still take the accent:
loadGltf("/models/rocket.glb", { colors: "material" });
loadGltf("/models/logo.glb", { accent: /blue|glow/i }); // which materials are accent
loadGltf("/models/scene.glb", { nodes: ["Gear", "Hub"] }); // only these objects (and their children)
loadGltf takes a URL, a File or Blob (a dropped file), or bytes. gltfSource(bytes) does the same without awaiting, and parseGltf, gltfMesh, gltfNodes and gltfMaterials give the parts on their own.
Collada models
Load a static .dae model from a URL, File/Blob, or bytes with loadCollada, or let loadModel detect it:
import { createScene, loadCollada } from "mote-engine";
const canvas = document.querySelector("canvas");
const source = await loadCollada("/models/sculpture.dae");
const scene = createScene(canvas, {
mode: "wireframe",
stages: [{ items: [{ id: "sculpture", source, motion: "none" }] }],
});
await scene.ready;
// Call scene.destroy() when the canvas is removed.
The returned source supports both sample() and mesh(). COLLADA 1.4/1.5 triangles, polylist and simple polygons (including concave ones) are supported, with separate input offsets, accessor strides, normals and UVs. Geometry instances and node hierarchies bake matrix, translate, axis-angle rotate and scale in document order. The root asset's unit meter and X_UP/Y_UP/Z_UP convert to metres and Y-up before the default fit to a unit sphere. Pass { normalize: false } to keep those metric coordinates; ColladaOptions is the options type at the root API. Reflection preserves face winding; normals use the inverse transpose. The lowest numbered UV set becomes the mesh's UVs, with V converted to the image's top-down convention.
Scene JSON accepts { "model": "/models/sculpture.dae", "format": "dae", "normalize": false } in either version; format is optional when extension or content identifies the file. The custom element's src can also point to a .dae URL through the lazy model loader.
Phong, Blinn and Lambert profile_COMMON effects map linear diffuse, emission and specular colours, opacity and index of refraction to materials. Only materials bound by active geometry instances are read. Texture inputs are ignored with a warning: diffuse uses its colour factor or white, and emission uses its colour factor or no emission. Constant shaders use the emission colour as an unlit base; texture-only or absent emission gives an unlit white base with no emissive channel. Emission colour factors may exceed 1 and stay linear. Phong shininess converts to perceptual roughness; Lambert uses roughness 1. Degenerate faces (repeated vertices or zero area) and untriangulable polygons are dropped with one warning and a count per file; loading fails if no triangles remain. Animation libraries are ignored: this is the authored static pose. Skin/morph controllers, polygon holes, lookat/skew, external document references and nested asset unit/axis overrides are refused with diagnostics. Export a static mesh with colour factors for this reader.
Collada uses the same configurable MODEL_LIMITS as mesh loaders: 64 MiB per file, 3,000,000 expanded polygon corners, 1,000,000 triangulated faces and 65,280 bound materials by default. XML is UTF-8 only; the five predefined entities and valid XML numeric character references are decoded once without expansion beyond the input size. DOCTYPE, external and custom entities are refused. Additional parser caps are 100,000 XML elements/node visits, 1,000,000 work units (node visits and child scans, one-time geometry/primitive and binding scans, and 1 + nonempty part count per geometry-instance visit), depth 64, 64 attributes per element, 16 inputs, stride/offset width 32, UV set indices 0–7 and 256 corners per polygon. A per-file budget of 8,000,000 repeated ear-clipping search steps bounds superlinear triangulation work; triangles, quads and linear convex clipping do not spend it. Each instance_geometry element shares one resolved geometry, binding map and face/vertex counts across visits. Zero-count primitives are dropped but charged to the work budget. Expanded face/corner totals across all visits, ranges and references are checked before triangulation or sized output allocation. Each geometry is triangulated once in local space, then transformed per instance. Parsing and baking happen during loading.
OBJ, STL and mesh PLY
loadModel reads glTF, OBJ, STL, PLY, COLLADA and binary FBX from a URL, File/Blob, or bytes. It chooses by filename extension or content; format: "gltf" | "obj" | "stl" | "ply" | "dae" | "fbx" overrides detection. The returned source has the same sample() and mesh() contract as every other model:
import { createScene, loadModel } from "mote-engine";
const canvas = document.querySelector("canvas")!;
const scene = createScene(canvas, {
stages: [{ source: loadModel("/models/part.obj"), motion: "none" }],
mode: "ray",
});
await scene.ready;
// Use scene.item("...") or change stages here; call scene.destroy() when finished.
Use loadObj, loadStl or loadPlyMesh when the format is already known. All four functions accept normalize: false to retain file units. OBJ bytes or a Blob with external references also need baseUrl; mtllib paths resolve against the OBJ URL and map_* paths against their MTL URL. Browser image decoding is automatic. Elsewhere, pass decodeImage(bytes, mimeType); a failed MTL or image load emits a diagnostic and leaves usable geometry and colour factors in place. URL references follow the same rule as glTF buffers (new URL(reference, containingFileUrl)), including parent paths and other origins; the host controls which URLs may be fetched.
- OBJ reads positions, texture coordinates, normals, negative indices,
o/gcolour slots andusemtl. Polygons, including concave ones, are triangulated by ear clipping, with a limit of 4096 vertices per face and a clear error above it. Degenerate faces with repeated vertices or zero area are dropped with a diagnostic count. Vertex RGB (v x y z r g b, sRGB in 0..1) and backslash line continuation are supported.s off/s 0gives flat faces; positive smoothing groups share area-weighted normals, with UV and normal seams preserved. Without normals, flat face normals follow the engine's ordinary mesh rule. - MTL maps
Kdto linear base colour,Ksto specular colour,Nsto perceptual roughness(2 / (max(0, Ns) + 2)) ** 0.25whenPris absent,d/Trto opacity, andKeto emissive. The PBR extensionsPr,Pm,PcandPcrset roughness, metallic, clearcoat and clearcoat roughness.Psandmap_Psset the sheen colour and its map (see below).map_Kd,map_Bump/bumpandnormbecome base-colour and normal maps (-bmsets normal strength). - STL reads ASCII and binary facets and their normals. Binary VisCAM/SolidView 15-bit facet colours (blue in bits 0–4, red in bits 10–14, bit 15 marking validity) become linear material colours.
- PLY mesh reads ASCII, binary little-endian and binary big-endian 1.0, with polygon faces, normals,
u/v,s/tortexture_u/texture_v, and byte/integer/float RGB vertex colours. Faces use fan triangulation. A PLY with faces is a mesh; otherwise the Gaussian property block selects the existing Gaussian-splat loader.
Untrusted inputs are checked for finite values, valid indices and structure before sized mesh arrays are allocated. MODEL_LIMITS for OBJ, STL and mesh PLY defaults to 64 MiB a file, 3,000,000 vertices, 1,000,000 triangulated faces and 65,280 materials; maxBytes, maxVertices, maxFaces and maxMaterials can tighten them. Downloads are counted while streaming; PLY headers select the mesh or Gaussian budget before the body is accumulated. Gaussian splats retain their own 768 MiB budget and glTF retains its existing behaviour. OBJ dependencies are bounded to 128 MTL libraries, 4096 texture references, 256 MiB of downloaded dependency bytes in total and 16,777,216 pixels per decoded image. These are parser setup costs, not work in animation frames.
Starting with 0.56, MTL Ps sets sheenColor to the linear triplet [Ps, Ps, Ps], clamped to 0–1, without a warning. map_Ps sets sheenColorMap using RGB in sRGB, multiplied by Ps; a map without Ps uses a white factor, while an explicit Ps 0 disables sheen. Image URLs, decoding, limits and failure diagnostics follow the other MTL maps. Pr still sets the base roughness: the PBR MTL extension defines no separate sheen roughness, so sheenRoughness keeps its default of 0.
For example, save this as cloth.mtl beside an OBJ that declares mtllib cloth.mtl and selects usemtl cloth:
newmtl cloth
Kd 0.35 0.12 0.08
Pr 0.7
Ps 0.6
Loading that OBJ with loadObj produces sheenColor: [0.6, 0.6, 0.6] and roughness: 0.7. Add map_Ps sheen.png to multiply the sheen by an image beside the MTL; the mesh needs texture coordinates for the image.
The element loads the general model parsers on demand. The director records model files and their MTL, texture and glTF buffer dependencies in assets and describe().assets; clay also replaces general models' source materials.
In Scene JSON v1 or v2, the equivalent shape is:
{ "model": "models/part.ply", "format": "ply", "normalize": false }
format is optional. <mote-scene src="/models/part.obj"> and .stl/.ply URLs use the same dispatcher; a splat: prefix still forces the Gaussian reader.
Binary FBX
loadModel also accepts binary FBX 7.x, detected from .fbx or its binary header. Use format: "fbx" to select it explicitly, or loadFbx when the format is known:
import { createScene, loadFbx } from "mote-engine";
const canvas = document.querySelector("canvas")!;
const source = await loadFbx("/assets/sculpture.fbx");
const scene = createScene(canvas, {
mode: "ray",
stages: [{ items: [{ source, motion: "none" }] }],
});
await scene.ready;
// Call scene.destroy() when removing the canvas.
The source fits a unit sphere by default. normalize: false retains the model's placement and converts its declared axes and units to Y-up metres, with +Z towards the viewer. Geometry connections, repeated mesh instances, parent transforms, all six Euler orders, pre/post rotations, pivots, offsets and geometric transforms are baked into the static mesh. Concave polygons are triangulated. Degenerate or untriangulable faces are dropped, with one warning per file reporting the count; files with no remaining triangles are rejected. The first normal, UV and colour layers retain their mapping and indexed references. UV V is converted to top-down coordinates. Missing normals become flat triangle normals. Per-polygon materials map diffuse/emissive colours and factors, opacity, specular colour/strength and a Phong-to-roughness approximation; explicit roughness and metalness are read when present.
Both 32-bit and 64-bit node records and raw/zlib arrays are supported without a runtime dependency. The loader uses platform decompression when available and its own decoder otherwise. FbxOptions accepts normalize, sample and the four MODEL_LIMITS overrides. Additional fixed caps are 64 MiB per expanded array, 256 MiB in total, a 256:1 expansion ratio, 100,000 nodes, 1,000,000 properties, 64 hierarchy levels and 4096 corners per polygon; triangulation shares a deterministic budget of 10,000,000 steps across the whole file. For polygons with more than four corners, each blocker visit in an ear test (including visits skipped by adjacency or bounds) and each failed ear candidate costs one step. Triangles and quads cost zero steps; linear per-corner setup, successful clips and orientation calculations are not charged. Convex caps avoid quadratic ear searches; concave polygons scan reflex/collinear blockers without a spatial index (O(n·r) for n corners and r blockers). Files exceeding that work budget are rejected. Smaller maxBytes values tighten the expanded array caps. Actual decompressed lengths and back-references are checked before allocating decompression output.
This import reads static mesh data. Skinning, animation, blend shapes, constraints, cameras, lights, texture/video resources, extra UV/colour sets and custom property-template defaults are not imported. ASCII/big-endian FBX, spheric rotations and edge-mapped layers are rejected. Vertex colour alpha is ignored. The same reader works through Scene JSON { "model": "/assets/sculpture.fbx", "format": "fbx" } and <mote-scene src="/assets/sculpture.fbx">.
A model as a tree
loadGltf reads a model into one object: every node's transform is applied to its vertices and the parts are merged, so a part can no longer be turned on its own. gltfTree reads the same scene with its hierarchy kept, and gltfTreeItems makes the scene's objects of it, one per node, each the child of its parent's:
import { createScene, parseGltf, gltfTree, gltfTreeItems } from "mote-engine";
const doc = parseGltf(await (await fetch("/models/robot.glb")).arrayBuffer());
const tree = gltfTree(doc); // nodes, parents first, and the model's fit
const { items, ids } = gltfTreeItems(tree, { id: "robot" }); // ItemSpecs: a root, the fit, one object per node
const scene = createScene(canvas, { mode: "ray", stages: [{ items }] });
scene.item("robot")!.set({ scale: 0.8 }); // the whole model, as a flat one
scene.item("robot/Arm.L")!.animate({ rotation: [0, 0, 60] }, 1); // one node, about its own origin: its children follow
tree.nodesare the scene's nodes, a parent always before its children, each with thetranslation,rotation(a quaternion) andscalethe file gives it (amatrixis taken apart), itsparentandchildren, and asourcewhen it has a mesh. Nodes that draw the same mesh share one source.Sizes. A flat model is fitted, whole, to the unit sphere. A tree keeps that fit for the model and does not fit its parts: a node's source is in the node's own coordinates (its origin is the node's, so a door turns about its hinge and not about the middle of its panel), and the whole model's fit is one transform,
tree.fit(center,scale,radius).gltfTreeItemsputs it in a group of its own,<id>/fit, between the root and the file's root nodes. At rest, under the same root transform, the tree is the flat model: the same centre and radius to the bit, every vertex within 1e-6 of the unit sphere (the tests measure 2e-7 on the example models: the floats' rounding).Objects. The root
<id>is a group that stands where a flat model's object would (itstransformandmotionare yours:gltfTreeItems(tree, { id, transform, motion })); under<id>/fitcome the nodes,<id>/<node name>(<id>/#<node index>for a name that is empty or shared), with the file's own translation, rotation and scale as their transforms and no motion.ids[n]is the id oftree.nodes[n]'s object;gltfTreeMatrix(tree, n)is the matrix a node is drawn with at rest.gltfTree(doc, options)takes the flat loader's options (scene,nodes,colors,accent,sample,normalize: falseto keep metres). It is sync, likegltfSource: for a model with images, decode them first and hand them in (textures: await decodeGltfTextures(doc), and for Ray's materialsimages: await decodeGltfImages(doc), from thegltfsubpath).Untrusted input, as the flat loader: the same structural checks and accessor limits, and for the hierarchy at most 4096 nodes and 64 levels below a root; a cycle, a node under two parents and a transform that is not finite are refused with a message that names the node, and the limit on nodes is checked from the counts, before a node's children are read or queued. A transform the tree cannot keep exactly, a
matrixthat shears or a rotation that is not a unit quaternion, is refused when keeping it as a translation, rotation and scale would move a vertex by more than 8e-7 of the model's radius (a matrix whose axes lean on each other by more than 1e-6 is refused on sight): a tree is never accepted a little off, so at rest it is always within 1e-6 of the flat model. That holds for a rotation whose length is only a float's rounding from 1 as well: the flat loader composes it as written and the tree makes it unit, which moves a mesh by that rounding times its distance from the node, so a file whose pivot is many radii from its mesh can be refused bygltfTree(the message names the node, the rotation's length and the distance) whileloadGltfreads it. Write such rotations normalised in double precision, or read the model flat.Skins are read (0.47): a node with a
skinand a mesh is an object whose mesh the scene deforms every frame with its joints' objects, in ASCII, Ray and Wireframe alike. See Skinned meshes.Morph targets (shape keys) are read (0.47): a node whose mesh has targets is an object with
weights, one a target, which deform its mesh every frame. See Morph targets.Cameras are read: a node that carries one has
camera, the camera's index in the file, and is an object like any other (<id>/<node name>, a group when it has no mesh).gltfCameraslists them andgltfCameraRigputs the scene's camera on such a node. See A model's cameras.Punctual lights are read: a node that carries one has
light, the light's index inKHR_lights_punctual, and is an object like any other.gltfLightslists them andgltfSceneLightsmakes scene lights that follow those objects. See A model's lights.Animations are played on the tree by the director's timeline (
gltfTracks, see A model's animations).gltfNodeMeshes(doc)gives the per-node meshes on their own.In Scene JSON, a node of a file is a shape,
{ "gltf": "robot.glb", "node": "Arm.L" }, and the groups and parents are written as any others, so a tree can be a document: see A hierarchy in Scene JSON. A skin and morph targets are not part of that shape.A tree that
describe()can write. TellgltfTreeItemsthe file the tree was read from, as a document would name it, and each mesh node's object carries its shape (item.shape, which the scene keeps asItemSpec.shape):const { items } = gltfTreeItems(tree, { id: "robot", gltf: "models/robot.glb" }); items.find((item) => item.id === "robot/Arm.L")!.shape; // { gltf: "models/robot.glb", node: 4 }: the node's index in the file const scene = createScene(canvas, { stages: [{ items }] }); scene.describe().document; // the root, the fit and the nodes without a mesh as groups, each mesh node as { gltf, node }Without
gltfa tree's mesh nodes are sources the page made, whichdescribe()leaves out (procedural-source). With it, the scene checks each returned item'sshapeagainst its real source: another file, or a node that does not draw the source's mesh, is aTypeErroratcreateScene,setStagesorspawn, naming the object and the expected and given nodes. Nodes that draw the same mesh share one source, so the check accepts any of them (items[a].source === items[b].source): their shapes name the same geometry in their own spaces. The check follows thesource, so copying an item to add a material (items.map(item => ({ ...item, ...(item.source ? { material: { roughness: 0.4 } } : {}) }))) keeps it; replacing the source removes that provenance and leaves the new source'sshapeto the page's word. The node may be its index or its unique real name when that resolves to one of the nodes drawing the mesh. The file itself is not fetched and compared: give the file the tree was read from, with the loader's defaults (its default scene, the theme's colours, every node), or the document will not draw what the scene draws. An application source without that provenance keeps the page's word for itsshape, as before. In every caseItemSpec.shapeis checked when the scene is made, atsetStagesand atspawn:{ gltf, node }and nothing else,gltfa string that is not empty,nodea whole number from 0 or a name; aTypeErrorotherwise, and on a group. An object made from a document or by an operation needs none: it has its shape already.
Retained camera and light data
Tree nodes and generated items expose cameraDefinition and lightDefinition alongside their camera and light indices. The definitions keep the file's units and values, including perspective yfov/fov, optional aspect and far plane, orthographic magnifications and clipping planes, and punctual light colour, intensity, range and cone angles. Each definition's nodes contains only the carrying node's original index.
import { parseGltf, gltfTree, gltfTreeItems } from "mote-engine";
const url = new URL("scene.glb", location.href).href;
const response = await fetch(url);
if (!response.ok) throw new Error(`Model request failed: ${response.status}`);
const tree = gltfTree(parseGltf(await response.arrayBuffer()));
const { items } = gltfTreeItems(tree, { id: "shot", gltf: url });
for (const item of items) {
if (item.cameraDefinition || item.lightDefinition) {
console.log(item.provenance, item.cameraDefinition, item.lightDefinition);
}
}
provenance: { gltf, node } identifies every original node, including camera-only and light-only nodes without a source or shape; the generated root and fit have none. Without the gltf option, definitions remain available and provenance is absent. Items own copies of the definitions and their arrays. Invalid light values keep their index and a tree diagnostic, with no lightDefinition.
The graph exposes these loader snapshots through node.camera, node.light and node.provenance. Passing items to a scene does not select a camera or add illumination: use graph.useCamera or gltfCameraRig for the camera, and gltfSceneLights for fitted photometric lights. Orthographic scene projection remains unsupported. Scene JSON v2 does not encode per-node metadata; describe() diagnoses the loss unless a declarative gltfTree preserves it through the original file.
Skinned meshes
A glTF skin binds one mesh to a skeleton: every vertex follows up to four joints by weights (JOINTS_0, WEIGHTS_0), each joint a node of the file. gltfTree reads it, and gltfTreeItems gives the skinned node's object a skin (ItemSpec.skin): the ids of its joints' objects, the skeleton's root and the inverse bind matrices. Nothing else is needed: turn a joint's object (set, animate, a timeline track, gltfTracks) and the mesh bends.
const doc = parseGltf(bytes);
doc.json.materials?.forEach((material) => { material.doubleSided = true; }); // a cape visible from behind in Ray
const tree = gltfTree(doc); // tree.nodes[n].skin: joints, root, inverseBind
const { items, ids } = gltfTreeItems(tree, { id: "hero", motion: "none" });
const scene = createScene(canvas, { mode: "ray", stages: [{ items }] });
scene.item("hero/Forearm.L").animate({ rotation: [0, 0, 70] }, 0.6); // a joint: the skin follows
await scene.setTimeline(gltfTracks(doc, tree, ids, { loop: true }).timeline); // or the file's own animation
- What is drawn. Each vertex at the weighted sum of its joints' drawn matrices times their inverse binds (linear blend skinning, on the CPU, into the object's own copy of the mesh), with its normal and tangent. The same deformed mesh is what ASCII samples, Wireframe draws, Ray traces (its BLAS refit to every pose, the mesh uploaded again), picks hit (
scene.pick) and bounds measure (scene.bounds): nothing is left at the bind pose but the object's body (below). The pose is made from the matrices the frame draws the joints with, so it holds through a stage transition and under a turned view. A pose that does not change publishes nothing, and Ray's still picture goes on refining. - The skinned node's own transform places nothing, as glTF has it: the mesh is where its joints are. Move the model by its root (
<id>), or the skeleton by its root joint. The model's fit (tree.fit) takes a skinned mesh in its pose at rest; for a file whose skinned mesh at rest is not the mesh under its node, the tree at rest is then not the flat model, which reads no skin (loadGltf,gltfSourceandgltfMeshdraw the mesh as written, as before). - Effects on a skinned object start from its pose: a mesh hook's vertex comes in where the skin puts it, with the bind pose as its
rest. With an effect moving it the normals are rebuilt from the faces, as for any mesh. - Winding and mirrors. A skinned mesh's triangles wind as the specification says: as the mesh was written, turned round when the skeleton's root (
skin.skeleton, or the joints' lowest common ancestor) is mirrored, whatever the skinned node's own scale; never guessed from the deformed mesh or from the instance matrix's determinant. Normals stay on the side of the surface they were written on. In Ray the material'sdoubleSidedworks exactly as for a static mesh:false(the default) culls back faces by that winding, whiletruedraws both faces, including when a pose turns part of the skin inside out. Set it totruefor an open skinned surface (a cape) that must show its back. - Bodies. A skinned object's body, if it has one, is the hull of the mesh as written (the bind pose), carried by the node's transform: it does not follow the skin. Bones as bodies are not there yet.
- Limits.
JOINTS_0andWEIGHTS_0only: four influences a vertex (aJOINTS_1set is said intree.diagnostics,skin-influences, and left out). Joints as unsigned bytes or shorts, weights as floats or normalised unsigned bytes or shorts, made to sum to 1 (a vertex with none is bound to its first joint,skin-weights). At most 1024 joints a skin and 256 skins a document (GLTF_SKIN_LIMITS), within the tree's 4096 nodes and 64 levels. An animation's timeline has at most 4096 tracks (the glTF reader itself takes at most 1024 channels): 120 joints animated in translation, rotation and scale make 360 tracks and play; past either applicable cap the animation is refused. - Untrusted input. A skin that is not valid refuses the tree with an
Errorthat names the skin, the mesh's primitive and the accessor: a joint that is no node, named twice or outside the scene, askeletonthat is not above its joints, accessors of another type, component or count, sparse ones, inverse bind matrices that are not affine or not finite, a weight that is negative, a joint with a weight outside the skin. Everything that can be told from the JSON is checked before any buffer is read. - By hand.
ItemSpec.skin = { joints, root?, inverseBind? }works on any object whose source's mesh has influences (SurfaceMesh.skin: four joints and weights a vertex). A joint that is not an object of the stage (not spawned yet, or removed) leaves the mesh in its bind pose, said once in the console, until it is there. - Cost (measured on a desktop, an M3 Max, a new pose every frame; not measured on mobile): per thousand skinned vertices about 0.05 ms of skinning and, in Ray, 0.09 ms of refit and packing and 0.08 ms handing 0.25 MB to the GPU; the skin's own code allocates nothing. Twenty characters of a thousand vertices each, all moving, add about 4.7 ms to a Ray frame's CPU time (5.4 MB uploaded a frame) and 1.2 ms in ASCII: the cost grows with the vertices, not with the number of meshes. A mesh bent far from the pose its BLAS was built for (its refit tree past twice the cost it had when built) has the tree built again for the pose it is in, Ray's tree and the picks' alike: one build at a time on the page, the two kinds together, 2 ms of it a frame, the refit tree in use meanwhile. A pose that then holds still is within that bound one build later, for good; a mesh that never stops moving between poses far apart is built again at most once in 120 frames, and may be past the bound between two builds.
Morph targets
A glTF mesh may carry morph targets (Blender's shape keys): each a set of displacements, one a vertex, and a weight says how much of it is applied. gltfTree reads them, and gltfTreeItems gives the node's object its weights (ItemSpec.weights): the node's own, else the mesh's defaults, else zeros.
const tree = gltfTree(parseGltf(bytes)); // tree.nodes[n].weights: one number a target
const { items, ids } = gltfTreeItems(tree, { id: "face", motion: "none" });
const scene = createScene(canvas, { mode: "ray", stages: [{ items }] });
scene.item("face/Head").weights = [1, 0, 0.3]; // by hand: from the next frame
await scene.setTimeline(gltfTracks(doc, tree, ids, { loop: true }).timeline); // or the file's own `weights` animation
- What is drawn. Each vertex at its place as written plus every target's displacement times its weight, and its normal the same way (made unit length); the tangents stay the mesh's own. On the CPU, into the object's own copy of the mesh, in ASCII, Ray and Wireframe alike, so picks (
scene.pick), bounds (scene.bounds), Ray's BLAS and what ASCII samples follow the morphed mesh; the object's body does not (it stays the mesh as written). A mesh with a skin too is morphed first, then skinned, as glTF has it. Weights of any sign and size are applied as given. - Weights.
ItemHandle.weightsreads a copy and takes a list of numbers (undefined: the mesh's defaults); a timeline'sweightstrack onitem:<id>writes them (The scene timeline). Missing weights are 0, weights past the mesh's targets are left out. The same weights again publish nothing (Ray's still picture goes on refining), and with every weight 0 the mesh is the one written, bit for bit; nothing is allocated a frame. - Normals. Targets with
NORMALdisplacements use them. Targets without leave the normals to be rebuilt from the morphed faces, as an effect's deformation does. When only some of a mesh's targets have them, a shape's normals are the displaced ones while every target at work in it (a weight other than 0) has them, and its faces' as soon as one without is at work.TANGENTdisplacements are not read (tree.diagnostics,morph-tangent), nor those of other attributes (morph-attribute). - Ray treats a morphing mesh's material as a skinned one's:
doubleSided: falseculls back faces using the mesh's winding as written (turned round when the mesh's own node is mirrored, exactly as a static mesh's),truedraws both faces. Its BLAS is refit to every shape and built again past twice its cost. - Limits and untrusted input. At most 64 targets a primitive (
GLTF_MORPH_LIMITS), every primitive of a mesh as many;POSITIONandNORMALdisplacements as floats,VEC3, as many as the primitive's vertices (sparse accessors too);mesh.weightsandnode.weightsone finite number a target, and none on a mesh without targets or a node without a mesh. Anything else refuses the tree with anErrornaming the mesh, the primitive, the target and the accessor, every check that needs no buffer made before one is read. The model's fit takes a mesh at its weights at rest. The flat loaders (loadGltf,gltfSource,gltfMesh) read no target and draw the mesh as written, as before.
Size
A model is drawn with points spread over its surface by area, about half a character apart; small models need no more points than big ones. A mesh needs no particular resolution: a cube of 12 triangles and a sculpt of 500,000 both work. Above 80,000 points the spacing gets coarser (sample: { maxPoints }). For a fast first load, keep .glb files small: decimate dense sculpts in Blender (Decimate modifier) before exporting.
External glTF decoders
loadGltf accepts Draco geometry and Basis KTX2 textures through decoder files
hosted by your application. Configuration belongs to one load, so separate
applications and models can choose different decoder versions.
import { createScene, loadGltf } from "mote-engine";
const source = await loadGltf("/models/model.glb", {
decoders: {
draco: { path: "/decoders/draco/" },
ktx2: { path: "/decoders/basis/" },
timeoutMs: 15000,
},
});
const scene = createScene(document.querySelector("canvas"), {
mode: "ascii",
stages: [{ items: [{ source, motion: "none" }] }],
});
await scene.ready;
Place draco_wasm_wrapper_gltf.js and draco_decoder_gltf.wasm in the Draco
directory, and basis_transcoder.js and basis_transcoder.wasm in the Basis
directory. Obtain matching files from the Draco releases and prebuilt decoder
instructions and
Basis Universal project.
Both external decoders use Apache-2.0; retain their licenses when hosting them.
For existing filenames, set js and wasm relative to path. The JavaScript-only
Draco build uses { path: "/decoders/draco/", js: "draco_decoder_gltf.js", wasm: false }.
The engine loads the selected files only when a model uses that format. It has no default decoder URL, bundled decoder, WebAssembly payload or runtime dependency. Without a decoder for an extension, an optional extension uses its uncompressed accessors or PNG/JPEG texture source. Required extensions and missing fallbacks reject the load with the filenames and upstream location. A configured decoder takes precedence; corrupt data and decoder failures reject the load even when a fallback exists.
Applications that already own the files can pass
{ module: { javascript: jsFileContents, wasm: wasmBytes } } for either decoder.
javascript is the complete classic Emscripten script as a string and
wasmBytes is a Uint8Array; functions and initialized module instances cannot
cross the Worker boundary. This form makes no engine fetch for decoder assets.
parseGltfAsync(bytes, { decoders }, externalFileResolver) returns a document
usable with gltfMesh, gltfTree, skin and animation APIs. loadGltfFiles also
accepts decoders; its resolver supplies external KTX2 images as well as binary
buffers. parseGltf and gltfSource remain synchronous: they always use the
uncompressed fallback for optional extensions and reject required extensions
or missing fallbacks.
<mote-scene> and Scene JSON do not accept decoder configuration. They use
fallbacks for optional extensions; compressed-only models need loadGltf with
decoders, followed by passing the returned source to a scene in JavaScript.
The general loadModel API also has no decoder option in its public type.
Every decode runs in a short-lived Worker, terminated on success, error or
timeout. The deadline covers decoder download, initialization and decoding
once a job obtains a slot; two jobs run concurrently, with at most 64 queued.
timeoutMs accepts 1–120000 milliseconds. Serve assets with suitable CORS and
allow Blob Workers and WebAssembly compilation in the page's CSP. Node callers
need a Web Worker adapter; there is no main-thread decoding fallback. Worker
termination protects responsiveness; browser Workers do not impose a hard
memory or network sandbox on application-supplied scripts.
Draco currently accepts indexed TRIANGLES, at most 16 million components per accessor, 64 MiB decoded per primitive and 256 MiB per document. Counts, attribute widths, finite values and index ranges are checked before geometry is exposed. KTX2 accepts 2D Basis ETC1S/UASTC LDR images up to 4096×4096, with a 64 MiB encoded input cap and 256 MiB decoded image budget per document. It transcodes the base mip to RGBA8: four bytes per texel (4 MiB at 1024×1024), shared by CPU sampling and Ray materials. Ray retains its existing 2048-pixel resampling limit. Texture arrays, cubemaps, HDR, sparse Draco accessors and non-triangle Draco primitives are rejected. GPU block compression and authored KTX2 mip chains are not retained.
Other sources
Built-in shapes, as meshes: box(w, h, d), sphere(), torus(major, minor), torusKnot(p, q), cylinder(radius, halfHeight) and cone(radius, halfHeight) (around y, centred halfway up the axis; the cone's apex up), blocks() (a 3 × 3 × 3 cube of blocks), and the mesh builders boxMesh, sphereMesh, torusMesh, cylinderMesh, coneMesh, capsuleMesh, tubeMesh(curve).
capsuleMesh(radius, halfHeight, segments, rings) is the physics engine's capsule collider drawn: a cylinder around y from −halfHeight to +halfHeight closed by a half sphere at each end (it reaches halfHeight + radius either way), one smooth surface of segments sides (16) and rings bands of latitude over the two caps together (8, an even number). meshSource(capsuleMesh(0.1, 0.3), { normalize: false }) is a source in the mesh's own units: an object of it at scale 1 is the body { shape: { type: "capsule", radius: 0.1, halfHeight: 0.3 } }, which is how a puppet's parts are drawn.
The cylinder uses the physics engine's cylinder collider convention (axis y, radius, halfHeight; 32 sides by default, at the angles of the prism the collider collides as). Like every source it is fitted to the unit sphere, so its radius is Math.hypot(radius, halfHeight): give the object that scale and a body { shape: { type: "cylinder", radius, halfHeight } } and the drawn surface and the collider coincide.
Flat drawings extruded into solids (browser only):
extrudedPath("m12,1.5 l9.265,4.344 v3.621 s-0.475,9.052,-9.265,13.035 C2.735,18.517,2.735,9.465,2.735,9.465 v-3.621 L12,1.5 Z", { viewBox: [24, 24], depth: 0.17 });
extrudedText("hello", { weight: 800 });
extruded((ctx) => { ctx.fillStyle = "#f00"; ctx.fillRect(0, 0, 10, 10); }, [10, 10]);
What is painted red (#f00) is drawn in the accent on the front face.
svgSource(text, options) reads SVG geometry without a DOM, in Node or a browser, and gives every fill its own colour in all render modes:
import { createScene, svgSource } from "mote-engine";
const mark = svgSource(`<svg viewBox="0 0 24 24">
<path fill="#e04b3a" fill-rule="evenodd"
d="M12 2 21 12 12 22 3 12Z M12 7 17 12 12 17 7 12Z"/>
</svg>`, { depth: 0.08, bevel: 0.01, curveSegments: 24, stroke: true });
const scene = createScene(canvas, { stages: [mark], mode: "ray" });
Supported geometry is path (including elliptical arcs), rect, circle, ellipse, line, polyline, polygon and nested g transforms, with inherited fill, fill-rule and presentation attributes. depth is a fraction of the viewBox's larger side; its default 0 makes two flat faces. bevel defaults to 0 and is limited to half the thickness, curveSegments is 16 by default (1–128), and stroke: true turns stroke/stroke-width into filled outlines. In Scene JSON v1 and v2, an object's shape is { "svg": "/shapes/mark.svg", "depth": 0.08 }; the file is fetched only when the scene loads it.
The XML reader accepts the five predefined XML entities, refuses a DOCTYPE with an internal subset, and limits input to 2 MiB, 256 elements, 4096 generated points and 16 levels (SVG_LIMITS). CSS stylesheets, SVG text and gradient shading are not supported. A gradient fill uses its first stop's colour; unsupported elements are skipped and named in source.diagnostics. Strokes use butt caps and mitred joins; bevels use mitred offsets. Separate overlapping contours are filled independently with nonzero; triangles may overlap in flat and extruded geometry, covering the union without a polygon boolean operation. For overlapping evenodd contours and self-intersecting contours, a diagnostic names the element and the importer fills each contour (or its simple lobes) independently as nonzero. True XOR/union polygon booleans are not supported.
All 148 CSS named colours are supported. transparent, none and zero fill-opacity produce no fill geometry; fill/stroke opacity inherits through groups. Unknown colour names and missing gradient references emit a diagnostic naming the element and use black. Coordinates and viewBox components must be finite with absolute values at most 1e12; viewBox width and height must be at least 1e-12. Transformed and normalized coordinates must also be finite and at most 1e12 in absolute value, before triangulation and typed mesh allocation. Out-of-range input is refused.
Your own meshes: meshSource({ positions, indices, normals?, slots?, palette? }). The figures of the day's occasions, as the 404 page shows them: seasonSources(date, seasons, { religious: false }) (without religious: false, the religious feasts and symbols in RELIGIOUS_SEASONS are included). Effects on any source: crumbling(source, at, blend, side) turns one side into flickering dust that sheds glyphs.
Render modes
A scene draws its objects in one of three modes: ascii, ray, and wireframe, or with a renderer plugin of the application's (custom, below). The scene is one: the objects, their motions, the rigid bodies, the morphs, the effects and the clicks are the same whatever draws them, and the mode only decides how they look.
const scene = createScene(canvas, {
stages: [loadGltf("/models/city.glb")],
mode: "ray", // "ascii" (default), "ray", or "wireframe"
ray: { quality: "auto", toneMapping: "agx-punchy" },
});
scene.setMode("ascii"); // the other way from the next frame, the same owned mesh and effects continue
scene.mode; // "ascii" | "ray" | "wireframe": what draws now (ray asked for where it cannot be: its fallback)
ascii: every particle is a character of theramp, picked by how bright its cell is, in the theme's text colour or the accent.ray: the objects are solid surfaces with physical materials (Materials), drawn with WebGPU and ray traced: soft shadows, reflections, refraction through glass and water, the environment's light. The effects' particles are drawn in the same 3D frame: a snowflake behind a solid is hidden, one in front shows, one behind glass shows through it, dimmed by the light the glass lets through, and an effect's light (a fire's) lights the solids.wireframe: actual indexed mesh edges, with hidden lines suppressed by triangle depth and continuous surface coverage.custom: a renderer plugin (api: 0, experimental: the engine's own constellation renderer,mote-engine/constellation, is one, and the Toon look on motedrift.com another, from outside the engine), registered on the page withregisterPluginor given to one scene inplugins.rendererchooses it, by id or as theRendererPluginobject itself (which becomes one of the scene's own):
registerPlugin(toon);
const scene = createScene(canvas, { stages, mode: "custom", renderer: "toon", ray: {} });
scene.setMode("ray");
scene.setMode("custom"); // back to the renderer it was given
scene.setMode("custom", otherPlugin); // or another one, by id or object
scene.mode; // "custom"; scene.stats().rendererPlugin says which plugin, its state, and why the scene fell back from one
mode: "custom" with no plugin given throws a TypeError, as does setMode("custom") on a scene never given one, or a renderer with any other mode (in the options or in setMode). An id nobody registered draws as ascii, stats().rendererPlugin.reason saying renderer "…" is not registered (the rule unknown ids always had), and a plugin that fails goes along its fallback chain, which ends at ascii. What draws the glyphs is a separate option, glyphRenderer, in every mode. Before 0.38 the plugin's id was itself the mode (mode: "toon"): still accepted, deprecated.

Ray

Ray mode draws a hybrid frame, built for fluidity first. The solids are rasterised into a G-buffer, and rays are traced from it through a bounding volume hierarchy (built once per mesh on the CPU; the scene's objects in a top-level tree every frame, the traversal on the GPU): shadow rays towards the lights (soft, from their size), a reflection ray, refraction chains through glass, water and diamond (with the volume's absorption, and dispersion), ambient occlusion and the environment. The light is traced at an internal resolution (three-eighths to full, per side) and cleaned by a denoiser (an edge-avoiding à-trous filter of each frame, which keeps mirrors and clear glass sharp, then a temporal accumulation at full resolution); the geometry, textures and Fresnel come from the full-resolution G-buffer, and temporal antialiasing resolves the picture at the canvas's size, so a change of internal resolution keeps the history. A tone curve maps the HDR picture to the screen. When nothing moves the picture is held and refined, up to ray.samples samples, and then the GPU rests.
Light bounced off the other objects (indirect light) is found first by rays marched across the screen (against the depth buffer, reading the light the previous frame's denoiser filtered spatially, before any accumulation over frames, after McGuire and Mara, "Efficient GPU Screen-Space Ray Tracing", 2014). Where such a ray leaves the screen or passes behind a surface, it reads a cache of probes laid over the objects in world space (an irradiance volume, Greger et al. 1998, of spherical-harmonic probes, Ramamoorthi and Hanrahan 2001), a few of them traced again each frame and reused across pixels and frames (the principle of irradiance caching, Ward et al. 1988). Rough reflections and frosted glass read the same cache, so they stay calm in motion.
The still picture. When nothing moves, ray refines the held picture with a path tracer: the same scene and materials, every light and the environment sampled at each bounce and weighed against the surface's own sampling (multiple importance sampling, Veach and Guibas 1995), glass crossed by its Fresnel coin flip (a glass ball focuses a light into a caustic), dispersion with each pixel's wavelengths spread evenly over the spectrum. It takes as many samples a pixel a frame as fit in what the rest of the held frame leaves of one 60 fps frame's budget (12 ms of the GPU's time at most, whatever the page's rate: a frame drawn after a held one, an effect starting over the still picture, never waits behind a longer one; the held frame is timed whole, with what is drawn over it, while the path tracer refines it and whenever particles (with the pass that lights them), the effects' look over the solids (glyph hooks, ripples), a post pass (halo, bloom, lens) or the water are drawn over it, refined or not (a refined picture with nothing drawn over it is not timed); the readings size the path tracer's share and show in stats().ray, and copies back the solids' depth kept when it was first held rather than drawing them again), so effects animating over a still picture stay smooth; on large canvases a sample is spread over up to 256 frames (the next run of a 16 × 16 ordered dither's values a frame, as many as its share holds); the scene paints a still picture at its idle rate (ambientFps, 30 a second by default) whether the path tracer refines it or not, as any resting frame (the hold never changes the paint rate: while an effect moves, every frame is painted, as always); once it is refined the GPU is nearly at rest (the picture copied, nothing traced); always at the full resolution, each sample's random numbers independent (a pixel converges to its own picture, not a pattern). What is shown blends its running mean over the hybrid's picture by how sure the mean is: per pixel, from that pixel's own mean and the hybrid's picture there alone, the mean's variance against how far it stands from the hybrid's (a shrinkage weight), at least a share that grows to the whole at ray.samples; so the picture shown is never further from the converged one than the hybrid's own, and the path tracer's alone at the end. The hand-over is a fade (a pixel moves by a level or two a frame at most on the screen, in the dark as in the light; the objects' silhouettes go over to the path tracer's own coverage too), so a still picture never flickers while it refines. A path's radiance is clamped at a luminance of 256 (the rare far brighter paths, a small light found through glass, are cut there), and while samples gather, a mean its own samples disagree on (a firefly: one sample far above the rest) is shown no brighter than that mean without the stray sample, about, or a little over the hybrid's picture there (a first sample alone, at most four times it), the limit loosening as samples gather and gone at ray.samples; the mean itself keeps it. Above the device's largest storage buffer (24 bytes a pixel) a still picture is not path traced: a console warning, once, stats().ray.pathTracer is "off" and stats().ray.samples stays 0.
Refinement costs power. Until a still picture is refined the GPU works every frame painted, up to one 60 fps frame's budget each: on the budget scene (Performance) that is minutes at the idle rate of 30 a second, where a GPU that clocks down under that steady load reads each held frame up to twice as long, so the path tracer gets fewer samples a frame. On a page read on a laptop or a phone, ask for fewer samples (ray: { samples: 64 }), or none (samples: 0: the hybrid's picture is held as it is, and the GPU rests at once); a page that wants the picture refined sooner paints faster at rest (ambientFps: 60, the idle rate of every resting frame, refined or not). Refined, the GPU only copies the held picture, about 2 ms a frame.
Fast screens. On a screen faster than 60 Hz, ray paints its busy frames (an effect, a morph, a touch) every n-th refresh, the most refreshes apart that still give at least 60 paints a second (a screen a little slower than n × 60 Hz, by up to 6 Hz, counts as n × 60 Hz and paints a little under 60 a second: 5 % slower at 120 Hz, 2.5 % at 240, about 1.7 % at 360; at 119.9 Hz, every other refresh, 59.95 a second), evenly spaced: 75, 90 and 100 Hz, every refresh (75, 90 and 100 a second); 120 Hz, every other (60); 144 Hz, every other (72); 165 Hz, every other (82.5); 240 Hz, every fourth (60); 360 Hz, every sixth (60). ASCII and Wireframe paint at the screen's own rate. The refresh is the shortest recent interval between animation frames. auto's budget is the period painted at when that is shorter than a 60 fps frame (90 Hz: 11.1 ms; 144 Hz, two refreshes: 13.9 ms), and the 60 fps budget otherwise: the period only tightens ray's budget, never relaxes it, so a page whose animation frames come at 30 a second (a battery saver) still budgets each frame for 60 fps. A frame budgeted for 60 fps is not asked for at every refresh of a fast screen, so the GPU is not saturated and no frame comes late or unevenly. In both modes the bodies and the particles in flight are drawn where they are at each painted frame's own time (interpolated between the fixed 60 Hz steps: Physics), so motion is smooth either way, at 60 to 100 paints a second in ray and at the screen's rate in ascii.
Quality. quality: "auto" (the default) holds the frame rate on two axes, and a last resort, from the GPU's time of the whole frame: from its first pass through the last pass drawn over the solids (the effects' particles, the halo and bloom), then the tone curve's own time (not the wait between for the canvas to come back from the screen). The internal resolution is continuous: it is chosen again every frame from the time of the newest frame that completed (the passes at the internal resolution apart from those at the canvas's, so the cost per pixel is known), in steps of 1/32 within the lighting tier's range, aiming at 12.45 ms (a quarter of a 60 fps frame left for the page, the compositor and a frame's spread) with a band of ±10 % that keeps it from hunting, and it is applied at once; while the picture is still the resolution does not rise (it falls if even the still picture is over the band). The lighting tier (ambient occlusion, secondary shadows, the second glossy ray, the indirect light's screen rays and probes, the shadow rays) changes only on a sustained run, counted: a reading over the band even at the tier's smallest resolution counts up (by more when it is far over), one within it counts down, and at a count of 30 readings the tier steps down, at once to the tier that reading says fits (several at once when far over); a reading over the frame's whole budget (16.6 ms) counts at least 2 (at lowest, where the count drives the output, it counts as itself); up after 120 readings in a row in which the next tier would fit. A climb the load takes back soon is not tried again as soon: a step down past a tier entered less than 480 frames before doubles that tier's wait before it climbs again, up to 960 readings (16 s at 60 fps), and a climb that holds 480 frames (8 s) sets its wait back to 120 (2 s); each tier keeps its own wait, and asking for auto again starts them over. So a load that comes and goes (4 s light, 4 s heavy) changes the tier a few times in ten minutes, not every cycle. One slow frame never changes it, except once at the start: the first reading from the fourth frame on (the first frames fill caches and make their pipelines: the budget scene's first one read 36 ms of passes that take 4) far over twice the band takes auto straight to a tier that fits. Only the GPU's time drives it (timestamp queries where the device has them, the submission's time otherwise), never how the picture changes. A fixed quality fixes the tier and lets the resolution move within that tier's range, aiming at the same 12.45 ms for the whole frame (so heavy effects drawn over the solids lower its resolution too), and a still frame over the band lowers it as well (never raises it); on a scene heavier than its smallest resolution can hold, it may exceed the frame's budget. Below low, auto alone goes to lowest; and when even lowest at its smallest resolution stays over the band on the same count, the last resort: the whole frame drawn at half the canvas's pixels per side (at a pixel ratio of 2, the page's own resolution; the solids and the effects' dots alike, stretched to the canvas: a last resort, for weak GPUs; the page's text stays sharp; stats().ray.output is 0.5), back to the whole once lowest would fit at it for 120 readings in a row (its cost at the whole output from the capped one by their ratio measured across the step: a frame's fixed costs do not shrink with its pixels), then the tiers up as before. And after 240 readings at half the output the whole is tried: its first steady reading measures the ratio anew (from the third frame at the whole output: each change of output makes the frame's textures again, and its first two frames read more than the output costs; on the budget scene 22.5 and 10.0 ms, the third 8.8, then 8.3), and over the band the half output is back at once and the next trial comes twice as late (240, 480, 960, then every 1920 readings: 4, 8, 16, then 32 s at 60 fps). For 240 frames after any return, three readings over the band in a row take the half output again at once (a load in bursts: a few frames over, not the counter's 30; the odd slow frame of a load the whole output holds does not) and the next return waits at least twice as long, up to 1920 readings (32 s at 60 fps); so it does when the counter reaches 30 first in those 240 frames (readings over the band one or two in a row, never three). So no reading, however far off, holds the output down for more than 1920 readings (32 s at 60 fps). Bursts that come within 240 frames of a return keep the half output between them (the return cut short, the next held longer); bursts further apart than that still take the half output once each and give it back after (two to four changes a burst: 40 frames at twice the load every 400, 100 changes in 20,000 frames). Each trial, and each change of output, costs a short shimmer: the antialiasing's and the denoiser's histories start again with the new textures (a few frames noisier, as after a cut), and the first frame at the new output takes longer (on the budget scene, 22.5 ms against 8.3 at the whole output, 6.8 against 4.5 at half); a trial that finds the line still crossed shows about four frames at the whole output, over the budget. A canvas resized makes the frame's textures again too, and its first two frames' readings are left out alike: a window's edge dragged for seconds does not walk auto down its tiers or halve the output on those frames' readings. The tiers:
| Quality | Internal resolution | Ambient occlusion | Secondary shadows | Glossy rays | Refraction interfaces | Indirect light |
|---|---|---|---|---|---|---|
lowest (auto only) |
0.375 to 0.5 | no | no | 1 | 4 | the probe cache (64 a frame); one shadow ray a pixel instead of one a light (to a light drawn by its share of the light, its visibility standing for all of theirs: exact where every light is seen or none, noisier in partial shadow), and the shadow catcher reflects nothing; the effects' particles one shadow ray each, the same way |
low |
0.5 to 0.69 | no | no | 1 | 4 | the probe cache (64 probes traced a frame); the effects' particles one shadow ray each, to a light drawn by its share |
medium |
0.5 to 0.81 | yes | no | 1 | 6 | the cache (128 a frame) |
high |
0.59 to 0.94 | yes | yes | 1 | 6 | 1 screen ray a pixel, then the cache (192 a frame) |
ultra |
0.75 to 1 | yes | yes | 2 on rough surfaces | 6 | 2 screen rays, then the cache (384 a frame, twice the rays each) |
auto starts at high.
Options (SceneOptions.ray; scene.setRay(options) changes them while the scene runs, fallback apart, and scene.ray reads the ones in effect):
| Option | Default | |
|---|---|---|
quality |
"auto" |
"auto", or "low", "medium", "high", "ultra" (above) |
samples |
512 | the most samples a still picture refines to; 0: never refined (the hybrid's picture held, the GPU at rest at once: for battery-sensitive pages, a lower count or 0) |
exposure |
0 | in stops |
flare |
off | the lens flare: true, or { kind, look, intensity, blades, ghosts, streak, veil, tint, squeeze, sources }; see the lens flare |
toneMapping |
"agx-punchy" |
AgX with a contrasty look (coloured light, a fire's, keeps its colour); "agx" (AgX's base look: bright colours go pale towards white), "aces", "neutral" (the materials' colours kept), "none" |
floor |
a shadow catcher, when the scene has a floor shadow or a physics floor | true or { y, catcher, material, shadow, reflect }: y defaults to just under the objects (to the physics floor, with physics); a catcher (the default) is invisible but for the shadows and reflections that fall on it, over the page; otherwise a surface of material; shadow how dark its shadows are (0 to 1), reflect how much it mirrors the objects (0 to 1); false: none |
fallback |
"ascii" |
the mode drawn where WebGPU is not, or "wireframe" |
scene.setRay({ exposure: 1, toneMapping: "neutral" }); // from the next frame, same device and renderer
scene.setRay({ flare: { kind: "anamorphic" } }); // the lens flare, on and off the same way
scene.setRay({ ...scene.ray, quality: "high" }); // what is in effect, one thing changed
A value it does not know (an unknown quality or curve, an exposure that is not a finite number, samples that are not a finite number from 0, a floor's y that is not a number or its shadow or reflect outside 0 to 1, another fallback) throws a TypeError with a message and changes nothing; the options given when the scene is made are checked the same way (createScene throws). While the scene draws another mode, the options are kept for when it is in ray.
WebGPU and the fallback. Ray needs WebGPU: Chrome and Edge from 113 on Windows, macOS and ChromeOS, and from 121 on Android 12 or later (Qualcomm and ARM GPUs); Safari 26 (macOS, iOS, iPadOS, visionOS); Firefox from 141 on Windows and from 145 on Apple silicon Macs with macOS 26. On Linux, Firefox on Android and Intel Macs it is still coming, GPU by GPU or behind a flag, so check rather than assume: the scene does. Where there is none (no navigator.gpu, no adapter, a device refused, no WebGPU canvas context), the scene draws ray.fallback from the first frame: scene.mode says so, and stats().backend says why (webgl2 (ray fell back: no WebGPU here (navigator.gpu missing))). The first time, ray loads its side and waits for its device before it draws (scene.ready too).
Loaded when needed. Ray's side (the renderer, its passes and shaders, and the points' rasterizer that draws the effects' particles in ray and wireframe) is loaded with import() the first time a scene asks for ray or wireframe with WebGPU available. The WebGL2 Wireframe fallback and its particle pen load only when that fallback is needed, without fetching Ray or asking for a WebGPU device. The custom-effect host (the ray manifests' validator and compiler front, see custom shaders) loads the first time ray runs an effect with a manifest, the public CPU validator the first time validateRayManifest is called, and the rigid bodies' world (about 145 KB) when a scene has physics; an ASCII page that does not call the validator never downloads any of them. With a bundler that splits chunks (esbuild, Vite, webpack, Rollup) they are chunks of their own: the no-build-step <mote-scene> bundle takes about 464 KB minified (180 KB gzipped) up front with esbuild (plain build). Until ray's side is there nothing is drawn in ray (as while its device is asked for) and scene.ray and setRay work as always; if it cannot be fetched (a network error, a chunk missing), the scene falls back to ray.fallback and draws, stats().ray.fellBack says ray did not load (…), and the browser keeps the failed module: ray is not tried again until the page is reloaded (a bundler's own chunk loader may fetch it again on the next switch to ray); until the world is there the objects with a body stay where they are placed, and scene.physics and item.body keep what is set and called on them for it. The world on its own (createPhysicsWorld) is mote-engine/physics. Ray asks for a replacement device after loss; Wireframe continues with WebGL2. An explicit setMode("wireframe") tries WebGPU again. destroy() releases every buffer and texture, and a scene destroyed while its device is still being asked for makes nothing. Shaders and pipelines are kept per device: switching back to ray, or a second ray scene on the page, compiles none again.
Heavy models. Objects own their geometry in all three modes. Ray prepares the indexed mesh, retained BVH and GPU arenas before scene.ready resolves. Vertex data uses 80 bytes per packed vertex, including immutable rest coordinates; a deformation refits the existing hierarchy and updates retained buffers rather than replacing the source. Large animated imports still have a synchronous deformation/refit cost: measure it for the intended model and viewport. Wireframe can explicitly simplify its preview with lowPoly; Ray and physics continue to use the full source. Texture uploads remain budgeted, with material factors used until images arrive.
Mesh effects. Each object owns its modified indexed mesh. Ordered vertex hooks deform that geometry; normals and tangents are rebuilt and the retained BVH is refitted before tracing. Continuous surface programs evaluate cuts, coats, tint and emission at each actual intersection, including a hole smaller than one triangle. Primary, reflection, shadow and transmission rays share that coverage. Free dust, snow and sparks are independent emitters: their count never controls whether an object exists. Geometry and surface revisions invalidate temporal history. keepClear masks only the final picture under page text; it never removes physical shadows or material.
Stats. stats().ray gives the GPU's time a frame (gpuMs: the whole frame, the effects drawn over the solids and the tone curve included; held frames while the path tracer refines them or while anything is drawn over them: an effect's particles and the pass that lights them, the effects' look over the solids (glyph hooks, ripples), the halo, the bloom, the lens, the water; a refined picture with nothing drawn over it is not timed, so gpuMs keeps its last reading then; a reading arrives every frame or two, some frames late: readings counts them, so each is counted once), the lighting tier it was drawn at, the internal resolution's scale, the share of the canvas per side the frame was drawn at (output: 1 at usual sizes, 0.5 at auto's last resort, less past the device-pixel ceiling or the device's largest texture: Memory), the path tracer's samples (0 while anything moves) and whether it can run at this size (pathTracer, "on" or "off"), the probes traced again last frame (probes), whether the picture is refined (held, its samples gathered and faded in: nothing more will change ray's picture of the objects, so with nothing moving the canvas no longer changes from that frame on; it comes when the fade's longest schedule ends, which can be some frames after the last visible change, never before; where the path tracer does not run (pathTracer "off", or samples: 0) the final picture is the hybrid's held one, refined from the first held frame with samples 0; effects, particles or water moving over the still objects change the canvas whether it is refined or not), the objects drawn solid, and, in the fallback mode, why ray fell back (fellBack, "" when it did not).
3D Gaussian splats
Load a binary little-endian INRIA PLY alongside a glTF building model in one scene. Use metre-scale coordinates for the building and supply a column-major matrix that maps the splat into that space. The matrix is optional when the two inputs already share coordinates.
const scan = await loadGaussianSplats("house.ply", {
normalize: false,
matrix: scanToBuilding,
shDegree: 3,
ambient: true,
});
const building = await loadGltf("house.glb", { normalize: false });
const scene = createScene(canvas, {
mode: "ray",
lights: [{ kind: "ambient", color: [1, 0.95, 0.88], intensity: 0.9 }],
stages: [{ items: [{ id: "scan", source: scan, motion: "none" }, { id: "building", source: building, motion: "none" }] }],
});
scene.setCameraRig({ kind: "static", pose: { position: [0, 1.6, 2], target: [0, 1.6, 0] }, fov: 60 });
Both loaders fit the source to a unit sphere by default. Splat colours come from the PLY's spherical harmonics and use the captured lighting by default. With ambient: true, Ray multiplies the captured colours in linear space by the scene's ambient lights and the average of each hemisphere light. Use exposure for a cloud-specific adjustment in stops and maxSplats to retain an evenly spaced subset. Ray quality tiers can reduce the effective SH degree. ASCII and Wireframe draw coloured point centres.
Ray composites the splats into the same linear HDR image as the glTF mesh, after temporal antialiasing, against the mesh's unjittered depth. Director camera rigs and timeline camera and ambient-light operations apply to these sources. The JSON representation is { "gaussianSplats": "house.ply", "normalize": false, "ambient": true } in an object's shape. The Director records the PLY's path and hash for replay.
Wireframe

mode: "wireframe" draws the edges of the actual indexed mesh. A triangle depth prepass hides rear edges, including across continuous cuts and alpha textures. WebGPU draws first (stats().backend reads webgpu-wireframe). If WebGPU is missing, its module or device cannot be prepared, or its device is lost, WebGL2 draws the same indexed meshes with hidden lines and preview faces. scene.mode stays "wireframe", stats().backend starts with webgl2, and stats().ray.fellBack gives the reason. If WebGL2 is unavailable or its context is lost, the whole scene draws ASCII. Ray still defaults to ASCII on failure; ray: { fallback: "wireframe" } selects the Wireframe fallback chain. The glyphRenderer option controls the glyphs and effect particles separately from the meshes.
Use the Render tab's Scene inspection controls, or configure the scene directly:
scene.setWireframe({
lowPoly: 0.7, // 0: original; 1: coarsest preview
surfaces: "transparent", // "hidden", "solid", "transparent"
surfaceOpacity: 0.25,
edges: true,
hiddenLines: false, // X-ray view of occluded edges
lineWidth: 1,
});
scene.setMode("ray"); // full geometry, same scene and camera
The same options can be supplied as SceneOptions.wireframe or JSON render.wireframe. scene.wireframe returns the current settings. The demo remembers them across reloads and rebuilds. Low poly clusters vertices in rest space and removes collapsed faces; it is an approximate inspection view that can lose small features. It never edits the source, effect state or physics colliders. Set lowPoly: 0 to inspect exact topology.
Wireframe includes triangulation diagonals. It does not trace reflections or refraction, or add a contour around a newly cut boundary. Edges use material colours and emission; visible faces have flat preview shading by default, and smoothSurfaces: true interpolates the vertex normals instead. The WebGPU inspection buffer is capped at 524,288 pixels and scaled to the visible canvas, including on Retina displays. WebGL2 uses a CPU coverage buffer capped at 262,144 pixels and draws triangles and edge strips, or presents the resolved pixels for wide strokes, alpha textures and continuous cuts. Both use CSS-pixel stroke widths and the same face opacity. WebGL2 keeps flat face shading; smoothSurfaces, antialias, fxaa and mipmaps are WebGPU-only. Raster boundaries can differ by a device pixel; above the caps, the different internal resolutions can change thin-line detail. Effect particles keep their layers; their intersections with meshes in WebGL2 use visibility at each particle's centre. Lenses and continuous glows use their CPU or image fallback so they can affect the complete picture. On WebGPU, coverage, depth and alpha are worked out in the GPU's fragment shaders, into a fragment pool sized to the buffer, so the cost grows with the fragments covered, on the GPU. Use measured frame costs for large imported models. Sources without an indexed mesh() choose a whole-scene ASCII fallback before readiness, with the reason available in stats.
The lens flare
Off unless asked for: what a camera's lens adds round a strong light, in Ray only (ASCII and Wireframe ignore it, and do not load it). ray: { flare: true } turns on the natural look, faint as in real footage; look: "cinematic" is the stronger one, and kind: "anamorphic" swaps the iris's spikes and round ghosts for a thin horizontal streak and oval ghosts.
createScene(canvas, {
mode: "ray",
lights: [{ kind: "environment", preset: "sunset", background: true }],
ray: { flare: { kind: "spherical", look: "natural", blades: 6 } },
});
scene.setRay({ flare: false });
Two kinds of source flare:
- Every bright pixel of the frame's emission (glowing surfaces, sprites, the black hole's disk) gets a little: the veil, screen ghosts, and spikes or streak.
- Up to 8 key sources get all of it, faded by how much of them the objects hide and tinted by glass (32 rays through the scene a key, a frame): the environment's sun while its background shows, the effects that declare one (the black hole, fireworks), and your own in
flare.sources,{ x, y, intensity, color, z?, size? }in canvas pixels, read every frame.
A sun out of frame still veils the picture and throws ghosts in, up to 25° past the edge. intensity, ghosts, streak and veil run from 0 to 4. The flare is added before the tone map, reads only this frame's light, and costs nothing while off.
The sun is found in a map only at 100 or more, and 50 times the map's mean, so a dim map has no key source. At the low and lowest tiers only the key sources draw.
Toon

A renderer plugin draws the very same scene — the objects, their lights, motions and effects — in a look of your own. The Toon look on motedrift.com inks the outlines and lays flat bands of light over the geometry the built-in modes draw. It runs as mode: "custom" with the plugin as the renderer; setMode("custom", "toon") switches to it and setMode("ray") back, the scene unchanged. The engine ships the plugin API, and this look is an example of it.
Constellation

The engine's own renderer plugin, mote-engine/constellation, covers each object with small wireframe tetrahedra that ride its surface and run in rows into its folds, turning amber where the surface faces away. Change the stage and the solids fly from one object to the next; effects draw in the same solids, and burst sends them off into the dark or brings them home. It draws in Canvas 2D, so it needs no GPU.
import { createScene } from "mote-engine";
import { constellation } from "mote-engine/constellation";
const scene = createScene(canvas, {
mode: "custom", renderer: constellation({ shape: "tetrahedron" }),
stages: [{ items: [brain] }, { items: [world] }],
});
scene.next(); // the solids fly to the next stage
Particles effects
particleStyle configures independent emitters: size, bloom, focus, aperture, haze, custom sprites, and a custom emitter adapter. It never changes object coverage. particles controls ASCII sampling density: the objects of a stage share it, and an object larger on the screen than at its own size (scaled up, or nearer the camera) takes as many more samples as its surface grew there (in steps of 2^(1/4), within maxParticles; stats().particles counts them), so it keeps the density on screen it has at scale 1. That costs what the samples cost: on top of the 0.36.0 sample cache, Suzanne at scale 2.4 takes 90,509 samples and about 5 ms more a frame (headless Chrome, M3 Max); maxParticles caps it. asciiScaleDensity: false (attribute ascii-scale-density="false", live as scene.asciiScaleDensity) turns the growth off for slow systems: each object keeps its share of particles whatever its size, and a big one draws paler and thinner. Ray and Wireframe object coverage is independent of particle density; only the explicit Wireframe lowPoly setting simplifies preview geometry.
The actual EffectFrame.mode is ascii, ray, or wireframe. Object effects use Effect.mesh: per-object prepare, ordered local-space vertex, continuous surface, and dispose(objectId). ASCII samples the resulting geometry and material after those hooks. glyph is presentation decoration, such as Matrix characters or scanlines. draw emits independent particles and overlays; worldAt, projectWorld, and unprojectWorld connect screen triggers and world anchors. Legacy custom object particle callbacks and explicit Dots mode are rejected with migration diagnostics. The demo converts saved Dots preferences to Wireframe and retains unrelated preferences.
Equal-topology stage transitions interpolate actual vertices. Different topologies crossfade two real meshes; interrupted transitions retain the current geometry and weights. Physics colliders remain rigid: visual vertex deformation does not rebuild them each frame.
Materials
In ray each object is drawn with physical materials: glTF's metallic-roughness model with the extensions Blender's Principled BSDF exports.
- A glTF model keeps its own materials (a material picked as the accent takes the theme's accent); shapes and extrusions take their colour slots' (the theme's colours), matte.
ItemSpec.materialgives an object one material for all its surfaces, or a map of its glTF materials' names to the ones that replace them (the others kept).item.materialchanges it while the scene runs (from the next frame;undefinedfor its own; anything but an object is refused).
An <img>, a canvas, or a RawTexture whose width, height or pixels is a getter of your own (on it or its prototype, from the frame it is there) is read again for every sample of every frame in ASCII, as before.
ASCII and Wireframe consume the same current mesh/material fields; independent particles keep their own colours. In a browser loadGltf decodes the images ray's materials use the first time ray draws them (until then a map is drawn with its factors alone, as while an image loads): ASCII and Wireframe decode the textures they sample. A scaled node's volume (thickness, attenuation distance) is scaled with it.
import { createScene, materials, loadGltf, sphere, torusKnot } from "mote-engine";
const scene = createScene(canvas, {
mode: "ray",
stages: [{
items: [
{ id: "ball", source: sphere(), material: materials.glass, transform: { position: [-0.6, 0, 0], scale: 0.45 } },
{ id: "knot", source: torusKnot(2, 3), material: { ...materials.gold, roughness: 0.35 }, transform: { position: [0.6, 0, 0], scale: 0.45 } },
{ id: "car", source: loadGltf("/models/car.glb"), material: { paint: materials.plastic("#c01818") } }, // by glTF material name
],
}],
});
scene.item("ball")!.material = materials.diamond;
Presets (materials; the ones that take a colour accept linear RGB or CSS):
| Preset | |
|---|---|
glass, frostedGlass, water, diamond |
clear solids traced through their volume: glass (IOR 1.5, a faint green through its depth), frosted (a mottled rough surface), water (IOR 1.333, blue-green), diamond (IOR 2.417, dispersion) |
chrome, gold, copper, aluminium, brushedSteel |
metals, their colour the measured reflectance; chrome a true mirror, brushed steel streaked in colour and roughness |
plastic(color), rubber(color), ceramic(color) |
a smooth plastic, a matte rubber, a glazed ceramic (a clear glossy coat) |
marble, wood |
polished white marble with grey veins (under a clear polish); honey oak: flat-sawn white oak, two boards glued edge to edge (cathedral arches and straight rift grain, uneven growth rings, open pores in relief, rays, a pin knot) under a satin varnish, with its colour, normal and roughness maps |
emissive(color, strength) |
a surface that gives light, as a neon tube: a dark glassy body glowing in color (the bloom makes it shine) |
Every texture of the presets is made procedurally (seamless 512 × 512, the same bytes every time) and kept; no image ships. Reading a preset that uses one returns at once and starts its work, which runs a slice of about 8 ms at a time between the page's own tasks (no long task); until it is done the preset's maps are empty (0 × 0) and ray draws it with its factors, then from the next frame with its textures. The wood's three maps take about 150 to 200 ms of work in all on an M3 Max, marble's about 90 to 120, and the wood holds 3 MB (4 MB on the GPU with their mips). To have them ready:
await texturesReady()resolves once every procedural texture asked for so far is made (at once when none is being made): in a page, before a screenshot or a measurement that must see the textures;finishTextures()makes what is left now, at once (it blocks for that long): for a Node script or offline rendering, which reads the presets' pixels, and would otherwise see empty maps and wait, about 0.4 s for all of them, for the slices to run before it can exit.
import { finishTextures, materials, texturesReady } from "mote-engine";
const wood = materials.wood; // its maps empty for now, their work started
await texturesReady(); // a page: the slices done, wood.map.image is 512 × 512
finishTextures(); // Node, offline: done at once (nothing left here)
The wood, in detail:
- Its
roughness(0.6) is a factor on its roughness map's G channel (0.55 to 1: the pores rougher, the rays' flecks smoother), so the surface under the varnish ranges about 0.3 to 0.6. The map's R is its occlusion (occlusionMapis the same image). - A copy keeps every map it does not replace:
{ ...materials.wood, map: myImage }puts your colour over the oak's pores and rings (itsnormalMap,occlusionMapandmetallicRoughnessMap). Set those three toundefinedtoo to replace the wood entirely. - Every face of a box shows the whole 512 × 512 panel, so wooden objects side by side show the same figure. To vary them, give each one its own
offset(KHR_texture_transform), and ascalefor a finer or coarser grain, on all four maps alike:
import { materials, type Material, type TextureMap } from "mote-engine";
// The oak moved by `offset` (and scaled): one per object, so no two crates look alike.
const woodAt = (offset: [number, number], scale: [number, number] = [1, 1]): Material => {
const w = materials.wood;
const moved = (m: TextureMap): TextureMap => ({ ...m, offset, scale });
return { ...w, map: moved(w.map!), normalMap: moved(w.normalMap!), occlusionMap: moved(w.occlusionMap!), metallicRoughnessMap: moved(w.metallicRoughnessMap!) };
};
scene.item("crate-2")!.material = woodAt([0.37, 0.58]);
scene.item("crate-3")!.material = woodAt([0.71, 0.12], [1.25, 1.25]);
A flip (a negative scale) mirrors the image, but a normal map's relief keeps the mesh's own tangent frame: flipped across the grain (scale: [1, -1]) the pores' grooves light as ridges. Prefer offsets.
A material (Material; colours are linear RGB or CSS, lengths scene units):
| Field | Default | |
|---|---|---|
color, map |
white | base colour, and a texture that multiplies it (its alpha multiplies opacity) |
metallic, roughness, metallicRoughnessMap |
0, 0.5 | dielectric to metal; mirror to matte (under 0.05 the exact mirror ray); glTF's map (G roughness, B metal) |
normalMap, normalScale, occlusionMap, occlusionStrength |
tangent-space normals; ambient occlusion | |
emissive, emissiveStrength, emissiveMap |
black, 1 | light it gives |
unlit |
false | base colour (factor, texture and vertex colour) as emitted light, with no lighting and no emissive term |
sheenColor, sheenRoughness, sheenColorMap, sheenRoughnessMap |
black, 0 | a Charlie cloth lobe with energy-conserving attenuation of the base material; colour map RGB is sRGB, roughness map A is linear |
anisotropyStrength, anisotropyRotation, anisotropyMap |
0, 0 | anisotropic GGX, rotated counter-clockwise in tangent space (radians); map RG is direction from 0..1 to −1..1, B is strength |
iridescence, iridescenceIor, iridescenceThicknessMin, iridescenceThicknessMax, iridescenceMap, iridescenceThicknessMap |
0, 1.3, 100, 400 | a Belcour/Barla thin film, thickness in nanometres; strength map R and thickness map G (0 selects the minimum, 1 the maximum) are linear |
transmission, transmissionMap, ior |
0, 1.5 | how much light goes through, refracted by the index |
thickness, attenuationColor, attenuationDistance |
0, white, none | the volume: its thickness for thin or open shapes (0: thin-walled), the colour white light turns after that distance inside |
dispersion |
0 | 20 / the Abbe number (diamond about 0.36) |
clearcoat, clearcoatRoughness |
0, 0 | a clear varnish over it |
specular, specularColor |
1, white | the dielectric reflection's strength and tint |
opacity, alphaMode, alphaCutoff |
1, "opaque" |
"mask" cuts at the cutoff, "blend" blends |
doubleSided |
false | both faces drawn and lit |
import { createScene, sphere } from "mote-engine";
const canvas = document.querySelector("canvas")!;
const scene = createScene(canvas, {
mode: "ray",
stages: [{ items: [
{ id: "fabric", source: sphere(), transform: { position: [-1, 0, 0] },
material: { color: "#384050", roughness: 0.8,
sheenColor: [0.6, 0.6, 0.6], sheenRoughness: 0.4,
anisotropyStrength: 0.35, anisotropyRotation: Math.PI / 4,
iridescence: 0.2, iridescenceIor: 1.3, iridescenceThicknessMax: 400 } },
{ id: "sign", source: sphere(), transform: { position: [1, 0, 0] },
material: { color: "#ffb000", unlit: true } },
] }],
});
await scene.ready;
// Call scene.destroy() when the canvas is removed.
Ray reads KHR_materials_unlit, _sheen, _anisotropy and _iridescence, including their textures. Anisotropy uses authored TANGENT vectors even without UVs; otherwise it uses the normal-map UV-derived tangent frame, or a stable frame when UVs are degenerate. The public Mesh.tangents field accepts four floats per vertex (xyz direction and a bitangent sign of −1 or 1). Tangent morph targets remain unsupported. ASCII and Wireframe draw unlit base colour without lighting and approximate the other three extensions by ordinary base colour.
These are JavaScript/TypeScript material fields. Scene JSON can load them from glTF assets; inline Scene JSON material fields have not been extended. Imported maps retain the loader's UV0-only and zero texture-rotation restrictions. Without a thickness map, the maximum thickness is used; a reversed minimum/maximum range is valid, and zero thickness disables the film. Sheen uses a minimum squared roughness of 0.002, a numerical directional-albedo table, and a reciprocal energy bound at grazing angles. Hybrid environment sheen uses the local diffuse irradiance as an approximation; refined opaque paths sample the sheen lobe.
The refined dielectric path used when transmission * (1 - metallic) >= 0.5 retains its existing isotropic glass model: sheen, anisotropy and the thin film are not yet composed into that path. Use opaque materials when comparing these three extensions across hybrid and refined rendering.
Every texture takes KHR_texture_transform's offset, rotation and scale, a UV set and a wrap. resolveMaterial(material) gives it with every field filled. The built-in shapes and extrusions carry UVs and tangents, so any of them takes a textured material.
From Blender. Export with glTF 2.0 and a Principled BSDF: base colour (and an Image Texture), metallic, roughness, normal map, emission and its strength, Transmission Weight and IOR (KHR_materials_transmission, _ior), Coat Weight and Coat Roughness (_clearcoat), Specular IOR Level and tint (_specular). A volume (_volume): connect a Volume Absorption shader (its colour and density: the distance is 1 / density) to the Material Output's Volume, and give the thickness on a node group named glTF Material Output with a Thickness input (Blender's exporter reads it there).
Lights
The scene's lights (lights, scene.setLights(list), scene.setLight(i, partial)) are in scene units in the objects' frame: x right, y up, z towards the viewer. Ray traces them; ascii shades its glyphs by them (the new kinds approximated: an area light as a point light at its centre of intensity × width × height, an environment as a hemisphere light of its mean sky and ground). Wireframe does not light by them: its preview faces are shaded by their facing alone, flat by default, with interpolated vertex normals when wireframe.smoothSurfaces is true.
| Kind | Fields | |
|---|---|---|
ambient |
color, intensity |
light from everywhere |
hemisphere |
sky, ground, intensity, up |
sky above, ground below |
directional |
direction (towards the light), color, intensity, castShadow, angle |
the sun: angle is its apparent diameter in degrees (the sun's is 0.53; default 1 in ray): wider, softer shadows |
point |
position, color, intensity, range, castShadow, radius |
a bulb; radius the glowing sphere's (scene units; default 0.04 in ray): bigger, softer shadows |
spot |
position, direction, angle (radians, half the cone), penumbra, range, color, intensity, castShadow, radius |
a spot light |
area |
position, direction (the way its lit face looks), width, height, color, intensity, twoSided, castShadow |
a glowing rectangle: a softbox, a window |
environment |
preset ("studio", "sky", "sunset", "night", "none"), map, intensity, rotation (degrees about the vertical), background |
the world around the scene: ray reflects it, refracts it and is lit by it; map an equirectangular HDR (a .hdr URL, or one decoded with loadHdr); background shows it behind the objects (default false: the page shows) |
import { loadHdr } from "mote-engine";
scene.setLights([
{ kind: "directional", direction: [-0.45, 0.6, 0.66], angle: 2, castShadow: true },
{ kind: "area", position: [-1.3, 1.5, 1.5], direction: [1.3, -1.5, -1.5], width: 1.4, height: 0.9, intensity: 1.5 },
{ kind: "environment", map: await loadHdr("/sky.hdr"), intensity: 1, rotation: 40, background: true },
]);
Units. Intensities are in the scene's units, the same in every mode: a white matte surface facing a directional light of intensity 1 shows about 1. Ray turns them into physical units (radiance and irradiance, the inverse-square falloff with range as a soft cut): a directional light's irradiance is π × its intensity; a point or spot light's power is its intensity × π × (0.4 × range)², so it shows its intensity at 0.4 of its range as the ascii falloff about does; an area light's power is that of the point light ascii stands in for it; an environment of intensity 1 sits at today's brightness. The effects' lights (f.light) join ray's lights as point lights. An effect's flash (f.flash, lightning's) joins them as a directional light casting shadows, at π × its intensity, and a hemisphere light for the sky it lights.
Shadows. In ray every light casts a ray-traced shadow unless it says castShadow: false, soft by its size (angle, radius, an area's sides). Outside ray, shadows (ShadowOptions) asks for the CPU's shadow maps and floor shadow: ascii draws them for every shown object (a mesh casts from the samples ascii draws of its surface, any other object from its points; past 32768 points the same share of each object's casts), and wireframe draws neither. Without lights, the scene keeps today's lighting (an ambient and one directional light towards light), and ray adds a studio environment around it, so metal and glass have something to reflect.
HDR. decodeHdr(bytes) and loadHdr(url | Blob | bytes) read Radiance .hdr files (RGBE and XYZE, flat and run-length encoded) into the equirectangular map an environment light takes. A map wider than maxWidth (an option of both, 4096 by default: ray's environment has no use for more, and an 8K map is about 400 MB of floats) is averaged down by a whole factor as it is read ({ maxWidth: Infinity } keeps every pixel); a file too short for the size it claims is refused before anything is allocated.
Physics
A rigid-body engine written for the scene: convex shapes made from the models themselves, static meshes, contacts with friction and bounce, joints, sleeping, continuous collision for small fast bodies, ray casts and contact events. It writes the objects' transforms, so the bodies behave the same in ASCII, Ray and Wireframe.
- Without
physicsthere are no bodies at all. - The world is loaded with
import()when a scene hasphysics(scene.readywaits for it; what is set onscene.physicsor called onitem.bodybefore is kept for it). - In ray its floor is a shadow catcher by default (
ray.floor: falsefor none). - The world on its own:
import { createPhysicsWorld } from "mote-engine/physics"; a static or kinematic body added to it (or turned so) wakes the sleeping bodies it overlaps, which are pushed out.
const scene = createScene(canvas, {
mode: "ray",
physics: { gravity: [0, -9.81, 0], colliders: () => document.querySelectorAll("h1") },
stages: [{
items: [
{ id: "crate", source: box(), material: materials.wood, transform: { position: [0, 0.6, 0], scale: 0.3 }, body: { restitution: 0.2 } },
{ id: "ball", source: sphere(), material: materials.chrome, transform: { position: [0.2, 1, 0], scale: 0.15 }, body: { shape: "sphere", restitution: 0.6 } },
{ id: "monkey", source: loadGltf("/models/suzanne.glb"), motion: "sway", body: { type: "kinematic" } },
],
}],
click: shockwave(), // a click's blast wave throws the bodies
});
await scene.ready; // the world loaded: the bodies' masses known
const ball = scene.item("ball")!.body!;
ball.applyImpulse([ball.mass * 1.5, 0, 0]); // 1.5 units a second to the right (an impulse is mass × Δv)
// or simply: ball.velocity = [1.5, 0, 0];
await scene.spawn({ source: box(), transform: { position: [-0.5, 1, 0], scale: 0.2 }, body: {}, instant: true });
The world
Its options, SceneOptions.physics:
| Option | Default | |
|---|---|---|
gravity |
[0, -9.81, 0] |
metres per second² (scene.physics.gravity reads and sets it while the scene runs) |
scale |
1 | metres to a scene unit (one unit is half the canvas's smaller side × zoom) |
floor |
0.05 under the stage's lowest object | a static floor's height in scene units, or false for none; the floor shadow and ray's floor lie on it |
walls |
true | static planes at the canvas's edges (in the z = 0 plane) and in front and behind at z = ±1.5: what is thrown stays in view |
colliders |
none | HTML elements (their border boxes) or boxes in canvas pixels, as kinematic boxes 2 units deep in the z = 0 plane where they are on screen: a heading or a panel a body lands on. An element not found (null) is left out. Measured at most once a frame: on scroll, on resize, and four times a second while the scene draws. A collider is put where its element is at once, and a body resting on its top moves with it, so it rides a scroll or a fling at any speed and is never thrown; a body it meets otherwise is pushed out gently (3 units a second at most). Each element keeps its own collider: one hidden, collapsed or added to the list moves no other's (boxes in canvas pixels are known by their place among the boxes). When the page's layout changes while the scene rests, call scene.resize() |
grab |
true | a press on a dynamic body grabs it and letting go throws it |
substeps |
4 | solver sub-steps per 60 Hz step |
jointSolver |
"sequential" |
how the hinges are solved. "sequential": each joint on its own, softly, as every earlier version. "chain": the hinges of a step together, exactly, so a hinge carrying a load off its axis stays on it; a hinge then also takes drive, friction and damping. See Hinges under load |
jointHertz |
Infinity |
with "chain" only: how fast a hinge's position error is closed, in Hz (above 0 and up to 1e6, or Infinity: within one sub-step) |
paused |
false | nothing moves (scene.physics.paused; scene.physics.step() moves one step) |
onContact |
(e) => … when two bodies start touching: their objects' ids ("floor", "wall-left"…, an element's id or "collider-0"…), the point, the normal, the impulse and the closing speed |
Determinism
With the same engine code and runtime, identical options and exactly the same calls in the same order—including insertion order, dt, substeps and sensor seeds—the CPU world is bit-for-bit deterministic in one process and in separate Node processes on the same host. Restoring a world snapshot continues bit for bit under the same subsequent commands, with matching modules and components and the application-owned state restored too. A fixed sensor seed repeats its noise sequence; another seed gives another sequence.
Bit equality is not promised across machines, operating systems, JavaScript runtimes, Node/browser boundaries or engine versions. Changing insertion order, step size, substep count or command timing is a different numerical run. Scene interpolation, effects and application state are outside the world guarantee, as are wall-clock timings and GPU images, which are not bit-deterministic across hardware. Each level, with the test behind it, is listed in Determinism.
Borrowed events
Set physics.events to receive onContactBegin, onContactPersist, onContactEnd, onImpact, onSensorEnter, onSensorExit, onSleep, onWake, onJointBreak, onJointLimit and onBodyRemoved. Each SceneEvent carries:
- cached scene ids (
a,b; an unknown or absent body is"") and material names; timein seconds, a scene-unitpoint, unitlessnormal,jointandwhich;- impulse in N·s; closing
speedand tangentialslipin m/s.
The world applies scale once; the scene forwards those SI values unchanged.
The old onContact remains an independent allocating callback with its original raw solver units and ownership; leave it unset for allocation measurements.
The two joint events come from the stage's joints:
onJointLimitfires when a limit begins to push: a hinge's or a slider's lower or upper limit, a distance joint'sminormax.whichis"lower"or"upper", and there is one event per arrival, not one per step: the next comes after the joint has left that limit (by more than 2° for a hinge, 0.005 units for the others) and reached it again.onJointBreakfires once, in the step a joint breaks under its load (Joints that break);whichis the threshold it passed,"force"or"torque".
For both:
aandbare the joint's objects;jointIdis the stage joint'sid(""without one) andjointIndexits index in the stage'sjoints;pointis the joint's anchor ona,normalits axis (a hinge's, a slider's, a distance joint's direction);impulseis what the limit pushed over the step, or the reaction of the step that broke the joint: N·s, and N·m·s for a hinge's limit and for a"torque"break;jointis the world's own handle, already out of the world for a break.
A joint removed by the application, or with one of its objects, tells nothing.
A body opts in with the physics entry point's EV_CONTACT, EV_PERSIST, EV_IMPACT, EV_SLEEP and EV_SENSOR bit flags in body.events; body.material names its sound/interaction material and body.sensor makes it overlap without force. Event options accept impact: { minImpulse, minSpeed, cooldown, maxPerStep } and persistEvery. scene.physics.events exposes the current stage's raw PhysicsEvents callbacks alongside the scene-id callbacks; it is undefined until that world exists, and is replaced when the stage changes. Optional physics.modules install after the built-in events module. Physics and all modules keep loading lazily: a scene without physics does not request them.
The demo's Sounds of things stage is a debugging aid for the events above, not sound design: its audio is deliberately crude synthetic sine tones and noise that make impacts and slip audible while you inspect a scene, and it does not try to sound like real wood, metal, glass or rubber. Mote ships no natural or production audio feature; bring your own samples or synthesis through the same callbacks. The stage has wooden blocks, metal cans, glass marbles and a rubber ball you can grab and throw in ASCII or ray. Press Enable sound to synthesize its buffers after a real gesture. Impact impulse controls gain, each voice varies its rate by ±5%, and contact x pans it. Tangential slip drives a bounded rolling/scrape loop. The example owns Web Audio, caps the pool at 16 voices and 4 per material, drops the quietest, and stops/disconnects every voice on mute or stage teardown. No audio runs inside the engine.
Bodies
ItemSpec.body: type is "dynamic" (the default: physics moves it, its motion is ignored), "static" (it stays) or "kinematic" (it follows its transform and motion, and pushes what it meets). shape is "auto" (the default: the convex hull of the object's surface at its scale, at most 64 vertices), "box", "sphere" or "capsule" fitted to it, or a shape of the engine's in scene units ({ type: "sphere", radius }, "box", "capsule", "cylinder", "convex", "compound", and for static and kinematic bodies "mesh" and "plane"). Then the body's weight (density, 1000 by default, water's, times its volume in units³, a unit being scale metres: a ball 0.3 units across weighs 14 kg, a unit box 1000 kg; or mass), restitution (bounce, 0.3), friction (0.5), rollingFriction (0; a ball rolls on forever without it), linearDamping and angularDamping, gravityScale, collision group and mask, ccd (swept against static and kinematic geometry, the colliders too: small, fast bodies; thin dynamic bodies, the thinnest side under a quarter of the largest, cards, planks, coins, are swept by default, and ccd: false turns it off), canSleep, and a starting velocity and angularVelocity. An impulse is momentum (kg · units a second): body.mass × Δv, or set velocity. An object scaled (item.set, item.animate) keeps its body's joints, contacts and grab: its shape changes in place, and no onContact fires again for what it already touched.
On a standalone world, readPose, readVelocity and readCenter write a body's current state into a caller-owned Float64Array or Float32Array, starting at an optional index (0 by default), without allocating:
readPose: pose is[x, y, z, qx, qy, qz, qw]for the shape's origin and rotation;readVelocity: velocity is[vx, vy, vz, wx, wy, wz], linear velocity at the centre of mass followed by angular velocity, both in world space;readCenter: centre is the centre of mass[x, y, z]in world space.
A Float32Array rounds each value as usual. Each method returns false, writing nothing, when the body is not live in that world.
import { createPhysicsWorld } from "mote-engine/physics";
const world = createPhysicsWorld({ gravity: [0, 0, 0] });
const body = world.addBody({
shape: { type: "sphere", radius: 0.5 },
position: [0, 2, 0],
velocity: [1, 0, 0],
});
const pose = new Float64Array(7);
const velocity = new Float64Array(6);
const centre = new Float64Array(3);
world.step(1 / 60);
if (world.readPose(body, pose) && world.readVelocity(body, velocity) && world.readCenter(body, centre)) {
console.log(pose[1], velocity[0], centre[1]);
}
readHinge does the same for a hinge: it writes the hinge's angle (radians) and angular velocity (rad/s) into the buffer, two numbers from the index, bit for bit what hinge.angle and hinge.angularVelocity give. Those two are getters, and a number a getter returns is a new 16-byte heap number wherever the JavaScript engine does not inline the getter into the code that reads it (Node 22 often does not); readHinge never allocates, so it is the read for a loop that runs at every step. It returns false, writing nothing, for a joint that is not a live hinge of that world (another kind of joint, a removed hinge, another world's).
import { createPhysicsWorld } from "mote-engine/physics";
const world = createPhysicsWorld();
const arm = world.addBody({ shape: { type: "box", halfExtents: [0.25, 0.05, 0.05] }, position: [0.25, 0, 0], mass: 0.2 });
const hinge = world.addJoint({ type: "hinge", a: arm, b: null, anchor: [0, 0, 0], axis: [0, 0, 1] });
hinge.setMotor(2, 5); // 2 rad/s, up to 5 N·m
const state = new Float64Array(2); // [angle, angular velocity]
for (let i = 0; i < 60; i++) {
world.step(1 / 60);
if (world.readHinge(hinge, state)) {
// state[0] is hinge.angle, state[1] hinge.angularVelocity
}
}
console.log(state[0], state[1]); // about 2 rad after a second, at 2 rad/s
Two more calls complete it, for a controller that computes a hinge's commands at every step (a servo's model, a robot's firmware):
readHingeLoad(hinge, out, at?)writes the hinge's torque (N·m) and work (J) over the last step, bit for bithinge.torqueandhinge.work.writeHinge(hinge, from, at?)sets the hinge's commands from eight numbers of a typed array,[motor speed, motor maxTorque, drive target, drive stiffness, drive damping, drive maxTorque, friction, damping], in the units ofsetMotor,setDrive,setFrictionandsetDamping, which it stands for in one call: a number passed to a function is a new heap number wherever the engine does not inline the call, an element of a typed array never is.
A drive whose maxTorque is 0 is no drive; the joined bodies are woken when a command changes, and only then; what the setters refuse throws before anything changes (a drive, a friction or a damping that is not 0 needs jointSolver: "chain").
Both return false, changing nothing, for a joint that is not a live hinge of that world.
import { createPhysicsWorld } from "mote-engine/physics";
const world = createPhysicsWorld({ jointSolver: "chain", gravity: [0, 0, 0] });
const arm = world.addBody({ shape: { type: "box", halfExtents: [0.25, 0.05, 0.05] }, position: [0.25, 0, 0], mass: 0.2 });
const hinge = world.addJoint({ type: "hinge", a: arm, b: null, anchor: [0, 0, 0], axis: [0, 0, 1] });
// [motor speed, motor maxTorque, drive target, stiffness, damping, drive maxTorque, friction, damping]
const commands = new Float64Array([0, 0, 0, 20, 2, 5, 0.01, 0]);
const state = new Float64Array(2), load = new Float64Array(2);
for (let i = 0; i < 120; i++) {
commands[2] = 0.5 * Math.sin(i / 20); // a new drive target at every step, without a heap number
world.writeHinge(hinge, commands);
world.step(1 / 60);
world.readHinge(hinge, state); // [angle, angular velocity]
world.readHingeLoad(hinge, load); // [torque (N·m), work (J)] of that step
}
console.log(state[0], load[0]);
A body's type can change while the world runs: body.setType("kinematic"), "dynamic" or "static".
- By default its contacts end and begin again at the next step, with their events.
- Between
"kinematic"and"dynamic",setType(type, { keepContacts: true })keeps them, with what the solver holds for them, and keeps the body's velocities: a platform carried by hand and let go, or a falling body caught, goes on with what rests on it, and nothing ends, begins a second time or counts as an impact because of the change. Only the contacts the new type cannot have end (a kinematic body has none with static and other kinematic bodies), and the ones it lacked begin at the next step (a body turned dynamic meets the floor it was lying on). - A change to or from
"static"ignores the option.
import { createPhysicsWorld, physicsEvents } from "mote-engine/physics";
const world = createPhysicsWorld();
const events = world.use(physicsEvents());
events.onContactBegin = (e) => console.log("begin", e.idA, e.idB);
events.onContactEnd = (e) => console.log("end", e.idA, e.idB);
world.addBody({ type: "static", shape: { type: "plane", normal: [0, 1, 0], offset: 0 } }); // id 1
const tray = world.addBody({ type: "kinematic", shape: { type: "box", halfExtents: [1, 0.1, 1] }, position: [0, 0.1, 0], mass: 5 }); // id 2
world.addBody({ shape: { type: "box", halfExtents: [0.2, 0.2, 0.2] }, position: [0, 0.4, 0], mass: 1 }); // id 3
for (let i = 0; i < 30; i++) world.step(1 / 60); // "begin 2 3": the crate rests on the tray
tray.setVelocity([0.5, 0, 0]); // carried along by hand...
for (let i = 0; i < 30; i++) world.step(1 / 60);
tray.setType("dynamic", { keepContacts: true }); // ...then let go: it keeps its 0.5 m/s and the crate on it
for (let i = 0; i < 30; i++) world.step(1 / 60); // "begin 1 2" only: the tray, now dynamic, meets the floor
Ray queries
On a standalone world, raycastInto(origin, dir, maxDistance, out, filter?) finds the nearest hit like raycast, equal to it within a relative tolerance of 1e-12 (and an absolute 1e-12 near zero), but writes it into storage the caller reuses (a RayHitRecord: { body, point, normal, distance }) and allocates nothing after its internal buffers have reached their high-water mark.
dir: the direction need not be unit length; it is normalized, anddistanceis in world units.maxDistanceis above 0; positive infinity is accepted and clipped to1e12, exactly as inraycast.out.pointandout.normalare distinct caller-ownedFloat64Arrays of at least three numbers and keep their identity from one query to the next.
import { createPhysicsWorld } from "mote-engine/physics";
const world = createPhysicsWorld({ gravity: [0, 0, 0] });
world.addBody({ shape: { type: "sphere", radius: 0.5 }, position: [0, 0, 0] });
const hit = { body: null, point: new Float64Array(3), normal: new Float64Array(3), distance: 0 };
if (world.raycastInto([0, 0, 5], [0, 0, -2], 10, hit)) {
console.log(hit.distance); // 4.5
console.log([...hit.point]); // [0, 0, 0.5]
console.log([...hit.normal]); // [0, 0, 1]
}
The optional filter is the same body callback as raycast's and may itself run raycast, raycastInto or raycastBatch without corrupting the outer result.
- An ordinary miss returns
false, setsbodytonullanddistancetoInfinity, and zeroes both vectors; a zero direction or nonpositive maximum is this kind of miss. - A non-finite origin or direction, or a NaN maximum, also returns
false, but leaves the whole record untouched. - Invalid output storage, including a null or non-object record and aliased vectors, throws a
TypeErrorbefore the query or any write.
Use raycastBatch for a sweep of many rays with a group/mask filter.
The handles
item.body (applyImpulse(impulse, at?), applyForce(force, at?), velocity, angularVelocity, mass (kg; 0 for static and kinematic bodies; NaN while its model or the world loads), sleeping, wake(), sleep(), type; calls made before the body exists, its model or the world still loading, are kept and done in the order made, the velocities read meanwhile being those asked for, and after destroy() they do nothing). scene.physics (gravity, paused, raycast(x, y): the object under a canvas pixel and the point hit, as drawn, step()). scene.spawn(item) adds an object to the stage on screen (its particles fade in on it, or it shows at once with instant: true) and scene.remove(id) takes it out. A stage's world is its own: the stage shown makes its bodies from its objects' transforms as they are then.
Drawn between the steps
The world steps at a fixed 60 Hz and each frame draws every dynamic body where it is at the frame's own time, between its poses before and after the last step (position blended, rotation along the shorter way; Physics), so a body moves on every frame of a 120 Hz display.
item.transformof a dynamic body is that drawn pose: up to one step's motion behind the world's (itsvelocity, its contacts and the grab are the world's), and the world's exactly at 60 Hz, while paused and afterstep().- A press grabs a body where it is drawn, and
raycasthits it there. - A body put somewhere at once (spawned, a stage shown, moved by
item.set) is drawn there at once. item.animatecarries a dynamic body along the animation as a kinematic one, and lets it go at rest where the animation ends.
Joints
StageSpec.joints, between objects by their ids (b left out: pinned to the world): ball (a point of each kept together), hinge (turning about axis only, with limits in radians and a motor), distance (a rigid rod of length, by default as long as it is, a spring with stiffness in Hz and damping, or a rope with min and max), weld and slider (along axis, with limits). ball, hinge, weld and slider take one anchor; a distance joint takes its two ends, anchorA on a and anchorB on b (or the world). Anchors and axes are in scene units, where the objects are when the stage is shown. Jointed bodies do not collide with each other. A body named by a joint waits (is not made) while another object the joint names has its model loading, up to 5 s after the stage is shown, so the joint holds them as the stage placed them; an object removed and spawned again under its id gets its joints back: without a position it is placed on the first of its joints' partners that is there, as the stage had them (with none there, where the stage had it), and its joints pull a partner that has moved back to it (a chain that swung meanwhile is whole again); with a position given, it stays there and its joints are made from where it is, the stage's anchors carried with it, a joint's anchor in the world (anchorB of one pinned to the world) too.
// A slab in its own proportions, w × h × d scene units (a source is fitted to a radius of 1: its half diagonal).
const slab = (w: number, h: number, d: number, position: Vec3) => ({ source: box(w, h, d), transform: { position, scale: Math.hypot(w, h, d) / 2 } });
const stage: StageSpec = {
items: [
{ id: "post", ...slab(0.04, 0.6, 0.05, [0, -0.4, 0]), body: { type: "static" } },
{ id: "door", ...slab(0.5, 0.6, 0.035, [0.28, -0.4, 0]), material: materials.wood, body: {} },
{ id: "lamp", source: sphere(), material: materials.glass, transform: { position: [0.7, 0.3, 0], scale: 0.12 }, body: { shape: "sphere" } },
],
joints: [
{ type: "hinge", a: "door", b: "post", anchor: [0.03, -0.4, 0], axis: [0, 1, 0], limits: [-1.7, 1.7] },
// A rope from the lamp's top to a point of the world above it, at most as long as it is now.
{ type: "distance", a: "lamp", anchorA: [0.7, 0.42, 0], anchorB: [0.7, 0.9, 0], min: 0, max: 0.48 },
],
};
Joints that break, limits that tell
A joint can carry a limit to what it holds, each finite and positive, at every scale:
breakForcein newtons on any joint;breakTorquein newton metres on ahinge, aweldand aslider(aballand adistancejoint carry no torque).
After each step's solve, a joint whose load, as the mean over that step, was more than a threshold breaks: it leaves the world, its objects move freely from the next step (and collide with each other, as they did not while joined), and physics.events.onJointBreak tells it once, with the objects' ids, the joint's jointId and jointIndex, and which threshold it passed.
- The force is the one that holds the joint's points together (and a slider's or a distance joint's limits).
- The torque is the one that holds the rotation: a hinge's axis and its limits, a weld's and a slider's lock.
- A hinge's motor, drive, friction and damping are commands, not load: a motor does not break its own hinge, but a motor pushing against the hinge's limit loads the limit.
A broken joint stays broken. The scene does not make it again by itself; it is made again where every joint is: when one of its objects is removed and spawned again under its id (all that object's joints are made again), and when its stage is shown again. A hinge's handle says it with scene.physics.hinge(id).broken, and reads 0 with made false meanwhile. Scene JSON's joints and a robot file's take the same two fields.
const stage: StageSpec = {
items: [
{ id: "lamp", source: sphere(), material: materials.glass, transform: { position: [0.7, 0.3, 0], scale: 0.12 }, body: { shape: "sphere", mass: 2 } },
],
joints: [
// The lamp's cord: a 2 kg lamp weighs 19.6 N; pulled with more than 30 N, the cord breaks.
{ id: "cord", type: "distance", a: "lamp", anchorA: [0.7, 0.42, 0], anchorB: [0.7, 0.9, 0], breakForce: 30 },
],
};
const physics: ScenePhysicsOptions = {
events: {
onJointBreak: (e) => console.log(`${e.jointId} let go of ${e.a}: ${(e.impulse * 60).toFixed(0)} N`), // "cord let go of lamp: ..."
},
};
The same on a world of its own, where the events module is installed by hand and joint.broken says what happened to a joint (false for one removed with remove() or with one of its bodies):
import { createPhysicsWorld, physicsEvents } from "mote-engine/physics";
const world = createPhysicsWorld(); // a unit is a metre, gravity 9.81 m/s² down
const events = world.use(physicsEvents());
events.onJointLimit = (e) => console.log(`the gate is on its ${e.which} stop`);
events.onJointBreak = (e) => console.log(`the cord broke: ${(e.impulse * 60).toFixed(0)} N (${e.which})`);
// A 2 kg lamp on a cord that carries 30 N (its weight is 19.6 N), and a gate between two stops.
const lamp = world.addBody({ shape: { type: "sphere", radius: 0.1 }, mass: 2, position: [0, 1, 0] });
const cord = world.addJoint({ type: "distance", a: lamp, b: null, anchorA: [0, 1, 0], anchorB: [0, 1.5, 0], breakForce: 30 });
const gate = world.addBody({ shape: { type: "box", halfExtents: [0.25, 0.05, 0.05] }, mass: 1, position: [1.25, 1, 0] });
world.addJoint({ type: "hinge", a: gate, b: null, anchor: [1, 1, 0], axis: [0, 0, 1], limits: [-0.5, 0.5] });
for (let i = 0; i < 60; i++) world.step(1 / 60); // "the gate is on its lower stop", once
console.log(cord.broken, world.joints.length); // false 2: the cord holds the lamp
lamp.applyImpulse([0, -2, 0]); // a tug: 2 N·s taken within one step is 120 N more
world.step(1 / 60); // "the cord broke: 140 N (force)"
console.log(cord.broken, world.joints.length); // true 1: the lamp falls, the gate's hinge stays
Choose a threshold with a margin. By default joints are soft: a load put on at once swings past its resting value before it settles (a weight let go on a level arm loads its joint by about 1.4 times what it weighs there, for a few steps), and a body that lands on a hinge's limit loads it far more than one resting on it. With jointSolver: "chain" a hinge carries exactly the static load from the first step. A world that is restored from a snapshot has its thresholds and its limits' state back: a joint resting on its limit tells no second arrival, and a joint breaks at the same step again.
Hinges under load
By default each joint is solved on its own, softly, and a hinge whose load hangs off its axis (a wheel beside its arm) twists: on an eight-hinge robot of 1.8 kg turning in place, about 3° off axis with the pins 2.3 mm apart. Two options change how hinges are solved:
physics: { jointSolver: "chain" }solves a stage's hinges together, exactly: the same robot stays at about 0.001° and 0.0004 mm, at about 2.5 times the cost of a step, and no energy is created.jointHertz(Hz,Infinityby default) sets how fast a position error is taken back; the alignment does not depend on it (0.016° at 15 Hz).
Both are for the whole scene, given to every stage's world, read once when the scene is made, and a value that is not one throws from createScene; createPhysicsWorld takes the same two options, and Scene JSON has them as physics.jointSolver and physics.jointHertz. Without them nothing changes: a scene is solved as before, bit for bit. Ball, weld, slider and distance joints are solved as before in either case.
The options, the measurements and a hinge's commands (scene.physics.hinge(id): motor, position drive, friction, damping, and its angle, speed, torque and work) are in Commanding a hinge.
Puppets
A puppet is a figure of rigid parts: one body per bone and a joint from each bone to its parent, made in a world by the puppets module. While it is animated it stands in its pose: its parts are kinematic bodies, which push what they meet and are pushed by nothing. As a ragdoll its parts are dynamic bodies held by their joints. It turns ragdoll when it is told to, or bone by bone when it is hit hard enough. The module is in the physics entry point and works on a world of its own (createPhysicsWorld), as below; a scene makes the puppets its stages declare and draws them in every mode: Puppets in a scene.
import { createPhysicsWorld, physicsEvents, physicsPuppets, humanoid, EV_CONTACT, EV_IMPACT } from "mote-engine/physics";
const world = createPhysicsWorld(); // a unit is a metre, gravity 9.81 m/s² down
const events = world.use(physicsEvents()); // before the puppets, to have its callbacks: they read its impacts
const puppets = world.use(physicsPuppets());
world.addBody({ type: "static", shape: { type: "plane", normal: [0, 1, 0], offset: 0 } });
// A mannequin of 15 parts, 1.75 m and 70 kg, standing at the origin and facing +z: animated.
const puppet = puppets.add(humanoid("mannequin", { height: 1.75, mass: 70 }), { position: [0, 0, 0] });
// A hit of 2 N·s or more turns limp the bone it lands on, the bones one joint away, and what hangs from them.
puppet.limpOnImpact = { impulse: 2, spread: 1 };
events.onImpact = () => console.log(puppet.bones.filter((b) => b.body.type === "dynamic").map((b) => b.name).join(" "));
// A 2 kg ball thrown at its left forearm.
const [forearm] = puppet.bones.filter((b) => b.name === "forearm.L");
const arm = forearm.body.position;
world.addBody({ shape: { type: "sphere", radius: 0.06 }, mass: 2, position: [arm[0], arm[1], arm[2] + 1], velocity: [0, 0.8, -6], events: EV_CONTACT | EV_IMPACT });
for (let i = 0; i < 20; i++) world.step(1 / 60); // "upperArm.L forearm.L hand.L": the arm hangs limp from the shoulder
console.log(puppet.mode); // "animated": the rest of the figure stands
events.onImpact = null;
puppet.goLimp(); // all of it: a ragdoll, which falls
for (let i = 0; i < 240; i++) world.step(1 / 60);
const pose = new Float32Array(puppet.bones.length * 4 + 3);
puppet.readPose(pose); // each bone's turn from its rest pose, then where the pelvis is
console.log(puppet.mode, pose[puppet.bones.length * 4 + 1] < 0.5); // "ragdoll true": the pelvis is on the floor
puppet.remove(); // its bodies and joints leave the world
console.log(world.bodies.length); // 2: the floor and the ball
The figure is a PuppetSpec: a list of bones, the root first and every parent before its children. A bone has a name, its parent's name, and where it lies in the rest pose, from its head (where it meets its parent: the joint is there) to its tail, in the puppet's own space and in world units. Its part is a capsule from head to tail by default (radius, 0.2 × its length unless given), or shape: "box", "sphere", or any shape a dynamic body takes, in the bone's own frame: its centre midway along the bone, y from head to tail, x the bone's roll (xAxis; by default the hinge's axis, or the puppet's x). joint says how it hangs from its parent:
joint |
|
|---|---|
{ type: "hinge", axis, limits: [lower, upper] } |
turns about axis (a direction in the rest pose) only, between the two angles, in radians from the rest pose: lower ≤ 0 ≤ upper, each within ±π |
{ type: "ball" } |
turns freely about the head, without limits: the default |
{ type: "fixed" } |
held to its parent as it is in the rest pose |
{ type: "free" } |
the same as "ball" |
Masses:
- a bone's
massin kilograms, ordensity(1000) times its part's volume; PuppetSpec.massscales the whole figure to a total, and withmassFractions: trueeach bone'smassis its share of that total;- then every part lighter than its parent's mass divided by
massRatio(8 by default) is raised to it, and the total is restored: soft joints stretch under parts much heavier than what holds them.
selfCollide (true by default) makes the parts that are not joined to each other collide (an arm against the chest); joined parts never do, and with every other body, another puppet's parts included, they collide as any body does: a puppet uses none of the 16 collision groups.
The whole spec is checked before one body is made. These all throw (naming the bone) and leave the world as it was:
- a name used twice;
- a parent that is missing, comes later or makes a cycle;
- a bone of no length;
- a number that is not finite;
- a mass that is not positive;
- a hinge with a zero axis or its limits the wrong way round.
humanoid(kind, { height, mass }) gives the spec of a standing figure, its feet on y = 0, facing +z, its left side (the bones named ….L) at +x: "mannequin" (the default) has 15 parts, "dummy" 11 (the hands are part of the forearms and the feet of the shins). height is in world units (1.75), mass in kilograms (70), shared out as the segments of a human body. Elbows (0° to 140°), knees (0° to 120°), ankles (−35° to +15°), wrists (±60°), the neck (±35°) and the waist (±30°) are hinges with those limits; shoulders and hips are balls without limits, and it is the parts' collisions with each other that keep an arm out of the chest.
puppets.add(spec, { position, rotation, mode }) puts the figure's rest pose in the world there (mode is "animated" unless given) and returns a Puppet; puppets.list has those in the world.
Puppet |
|
|---|---|
bones |
per bone, in the spec's order: name, index, the body and the joint to its parent (the world's own handles; null for the root's joint) |
mode |
"animated", or "ragdoll" once no bone is animated any more |
moveTo(position, rotation?) |
where the figure is to stand at the end of the next step: its animated parts go there with the velocities that take them, as Body.moveTo, and push what is in the way. Call it at every step to walk the figure |
setMode("ragdoll"), goLimp() |
every part turns dynamic where it is. It keeps the velocity it had and the contacts it had: no contact ends or begins and nothing is an impact because of the change |
limpOnImpact |
{ impulse, spread?, all? } or null: an impact of at least impulse N·s on a part, from a body that is not another part of the same puppet, turns limp the bone it hit, the bones within spread joints of it (0 by default) and, however far, everything that hangs from a limp bone: a part still animated is a kinematic body, which nothing moves, and under a limp parent it would hold that parent up in the air. So a hit on a thigh takes the shin and the foot with it, and one that reaches the root takes the whole figure. With all, the whole puppet at any hit. It happens before the events module's callbacks, so onImpact already sees the bones limp. Assign a new object to change it |
readPose(out) |
the pose now, allocating nothing: per bone its rotation from its rest pose, in its parent's frame (x, y, z, w; all [0, 0, 0, 1] in the rest pose), then the root's head in the puppet's frame: 4 × bones + 3 numbers, into a Float32Array or a Float64Array |
remove() |
takes its bodies and joints out of the world |
The impacts are the events module's: its thresholds and its maxPerStep choose them, and the module is installed with the puppets when the world does not have it yet (install physicsEvents() first to keep its handle and its options). Removing one of a puppet's bodies by hand removes the whole puppet; removing one of its joints lets that bone, and what hangs from it, go limp. A step with puppets allocates nothing.
What is not there yet:
- Cone and twist limits.
joint: { type: "cone" }is refused (cone joints are not available yet). Shoulders and hips turn freely, so a ragdoll's limbs can take poses a body cannot. - The
"powered"mode and the drives that hold a pose against gravity, clips (play,stop), and getting up: a ragdoll does not return to"animated"(setMode("animated")on a puppet with a limp bone throws). Remove it and add it again to stand it up. - Puppets in Scene JSON (a scene's stages take them in code: Puppets in a scene), and in a world's snapshots: while the world holds a puppet,
world.snapshot()andworld.restore()throwpuppets are not saved in world snapshots yet: remove them before a snapshot or a restore, and change nothing. Remove the puppets, take the snapshot (after a step, as after any removal), and add them again. - Joints that hold in every fall. By default the joints are soft, and a landing stretches them. Measured on a 70 kg figure let fall from 0.6 m, in thirty slightly different falls: the dummy's joints part by about 2 cm for a step or two (2.5 cm at worst) and its hinges stay within 1.1° of their limits. The mannequin's hands and feet do worse: a part that light, caught between the floor and the weight of the body, is pushed past its hinge's limit by up to 17° and off its joint by 3.5 cm (7 cm at worst), for a few steps. Two of the world's options help.
contactHertz: 60makes every joint twice as stiff: the dummy's then part by less than 1 cm.jointSolver: "chain"solves the hinges exactly: every limit holds within 0.3°, the mannequin's too, but the balls at the shoulders and hips stay soft, and a ragdoll lying with its hinges on their limits can go on rocking by a fraction of a millimetre for seconds before it sleeps. No combination of the two made the mannequin hold in every fall.
Puppets in a scene
A stage declares its puppets in puppets, and the scene (with physics) makes each one in the stage's world and draws it as objects of the stage, one per part, in ASCII, Ray and Wireframe alike: physics writes the parts' transforms as it writes every body's, between the steps, so nothing jumps at 120 Hz. scene.puppet(id) is the puppet itself, the Puppet of the section above, in scene units.
import { createScene, sphere, materials } from "mote-engine";
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const scene = createScene(canvas, {
mode: "ray", // or "ascii", "wireframe": the same simulation
physics: {
scale: 1.25, // metres to a scene unit: the mannequin, 1.75 m, is 1.4 units tall
floor: -0.8,
events: { onImpact: (e) => console.log(e.a, e.b) }, // the parts by their objects' ids
},
stages: [{
items: [],
puppets: [{
id: "actor",
spec: "mannequin", // or "dummy", or a PuppetSpec of your own, in scene units
position: [0, -0.8, 0], // its feet on the floor
rotation: [0, 20, 0], // degrees, as an object's
material: { head: materials.gold }, // one material for every part, or by the bones' names
limpOnImpact: { impulse: 5 }, // a hit of 5 N·s turns limp the bone it lands on and what hangs from it
}],
}],
});
console.log(scene.puppet("actor")); // undefined: the physics is still loading
await scene.ready; // loaded: the parts are objects of the stage now
const puppet = scene.puppet("actor")!;
console.log(puppet.bones.length, scene.items().length, scene.item("actor.head")!.transform.position[1].toFixed(2)); // 15 15 0.47
// A 2 kg ball thrown at its left forearm: "actor.forearm.L ball" (onImpact).
const arm = scene.item("actor.forearm.L")!.transform.position;
await scene.spawn({
id: "ball", source: sphere(), material: materials.rubber("#e5484d"), instant: true,
transform: { position: [arm[0], arm[1], arm[2] + 0.8], scale: 0.07 },
body: { shape: "sphere", mass: 2, velocity: [0, 0.5, -6] },
});
await wait(500);
console.log(puppet.mode, puppet.bones.filter((b) => b.body.type === "dynamic").map((b) => b.name).join(" ")); // animated forearm.L hand.L
puppet.goLimp(); // the whole figure: a ragdoll, which falls
await wait(3000);
console.log(puppet.mode, scene.item("actor.head")!.transform.position[1] < 0); // ragdoll true: its head is down
scene.remove("actor.head"); // one part taken out takes the whole puppet with it
console.log(scene.puppet("actor"), scene.items().map((item) => item.id).join(" ")); // undefined ball
StageSpec.puppets[] |
|
|---|---|
id |
its name for scene.puppet(id). Its parts are the objects "<id>.<bone>" ("actor.head", "actor.forearm.L"), and every id that begins with "<id>." is the puppet's: no object and no other puppet of the scene may have one |
spec |
"mannequin" (15 parts) or "dummy" (11), a person 1.75 m tall and 70 kg at the scene's scale (1.75 / physics.scale units tall); or a PuppetSpec of your own, its lengths in scene units, as the bodies' shapes are |
position, rotation |
where the figure's frame is and how it is turned, as an object's transform: scene units, and Euler degrees [x, y, z] or a quaternion. A preset stands on that point, facing +z, the viewer |
material |
Ray's material for every part, or a map from bones' names to their parts' materials; the parts not named keep the scene's own colour |
mode |
"animated" (the default) or "ragdoll", limp from the start |
limpOnImpact |
what a hit does while it is animated: the puppet's limpOnImpact, set each time its stage is shown |
The parts are ordinary objects: they are listed by scene.items(), each has a handle (scene.item("actor.head"): its material, its visible, its transform to read), a pixel's ray finds them (scene.physics.raycast gives the part's id), and a limp part can be grabbed and thrown with the pointer as any dynamic body (an animated one cannot: a press on it is a click). Their transforms are physics': each is drawn where its body is, and a transform set on one by hand does not last. They have no body handle of their own (item.body is undefined): the puppet is the handle of them all, and puppet.bones[i].body is each part's body in the stage's world. Another object can hang from one (parent: "actor.hand.L") and is carried with it. Each part is drawn with the mesh of its collision shape, a capsule along its bone by default (capsuleMesh), a box or a sphere; parts of the same size share one mesh source (a figure's left and right limbs, two puppets of one preset).
Events and hits. The scene's events name a part by its object's id (e.a, e.b, and onContact's), so a callback tells an arm from a head; a body of the scene thrown at an animated puppet turns limp what limpOnImpact says, as in a world. The events module is installed in a stage's world when the stage has puppets, with the scene's physics.events options.
Its life. The parts' objects are made when the physics has loaded, which scene.ready waits for: before that scene.puppet(id) is undefined. A stage's puppets are made in its world when the stage is shown; shown again (another stage in between, or setStages), the stage makes them again, standing where it puts them: a ragdoll does not get up, a new puppet stands in its place, and scene.puppet(id) is then a new handle. scene.remove("<id>.<bone>") takes the whole puppet out of the scene, and so does puppet.remove() (its objects go after the frame). scene.destroy() clears everything. Puppets add nothing to what a frame allocates.
What is checked. When the scene is made and at setStages, before anything changes: puppets without physics, a puppet without an id or with another puppet's (in any stage), an object or another puppet whose id is a puppet's or begins with its "<id>." (a bone's name may have a . in it, so "a" and "a.b" could both have a part "a.b.root": the second is refused), a spec that is neither a preset nor a PuppetSpec, a mode that is not one of the two ("powered" is not available yet), a position, rotation or limpOnImpact of the wrong shape: each is a TypeError naming the stage and the puppet. An object without an id is named by the scene ("item-0", "item-1"…) with an id that is no puppet's. What only the puppets module can tell of a custom spec (a bone of no length, a missing parent) throws at setStages once the physics is there, and nothing changes. In a scene just made, where the physics is still loading, every spec of every stage is checked when it has loaded, before one part is made: if one is refused, scene.ready rejects with that error and none of the scene's puppets is made, the valid ones neither (no part, no handle, no body; the stages keep the objects they were built with, and setStages with valid puppets makes them). scene.spawn refuses an id that is a puppet's or one of its parts'.
Not there yet, beyond the puppets' own limits (no cone or twist limits, no "powered" mode, no clips, and a mannequin's hands and feet that a hard landing pushes past their limits for a few steps):
- Scene JSON. A document has no
puppets;scene.describe()leaves the parts' objects out, with a diagnostic for each. A scene on a stepped clock that has puppets steps as any other, but cannot go back:seekto an earlier frame rejects withnot-replayable. - Joints to a part.
StageSpec.jointsname objects with a body of their own; a puppet's part is not one and cannot be named there. - Adding a puppet to a stage on screen. Puppets come with their stage:
setStages(or another stage) brings a new one.
Grab and throw
A press on a dynamic body grabs it where the camera's ray through the pixel hits it (a soft spring to the pointer, on the plane through that point parallel to the screen); letting go throws it with the pointer's velocity over its last 80 ms. The grab is its pointer's: another finger neither grabs, clicks nor drags meanwhile, and a cancelled pointer (or a page hidden) lets the body go at rest. A press anywhere else is a click, as before. A finger on a body grabs it without scrolling the page: the scene prevents that touch's touchstart, through a non-passive listener on the pointer target registered when physics has grab on (a scroll that starts there waits for it: microseconds, or one pick where the browser sends the touch before the pointer); a finger elsewhere scrolls the page as usual. For a full-screen playground where no drag should scroll, set touch-action: none on the canvas or its pointer target.
Colliders and keepClear
A collider is an element's border box (getBoundingClientRect): a panel or a heading a body lands on whole. Each time it is measured it is put where its element is, and the bodies resting on its top (touching it, the contact's normal within 45° of up), and what rests so on them, move with its top in the same frame, keeping their own velocity: a body (or a stack) on a card rides a scroll or a fling with it, never thrown and, within the walls, never left behind (a rider the page carries past the canvas's top or bottom wall is left there), and stays on its top when the element grows. While physics is paused the colliders still follow their elements, and what rests on them stays where it is. A body the collider meets from the side or from below is pushed out by the solver as by anything put in its way, at most 3 units a second. keepClear measures an element's contents (a range over its text, falling back to its box), so a short heading leaves the space beside its line free. The same element can therefore collide over its whole box while the scene clears only its text.
The effects push the bodies
An object's mesh vertices are its body's sensors: what the effects' mesh hooks do to them (the accelerations and changes of velocity of explode, vortex and blackHole, and the points shockwave and magnet move them to) is summed into a force and a torque on the body. So:
explodeandshockwavethrow the bodies;vortexandblackHolepull them round;magnetgathers them;windand atornado's funnel also drag the bodies as air does (the drag grows with the area a body shows and the square of the air's speed relative to it): the default wind rolls a ball and slides a light box, while a unit box of water's density only leans into it;jellyanddisintegrateare the object's own deformation, and do not push.
Motors and sensors (components)
A motor or a sensor is a record of data (its model, where its values come from, its parameters in SI units), never code: the engine holds no component's data, and a new sensor of a kind it already models is one more record. Three parts, all in mote-engine/components, an entry point of its own that only a page using components loads:
- the catalog checks records (
validateComponent, with an error per field) and hands them out from wherever the application keeps them: a JSON document (jsonComponentSource), objects in memory (memoryComponentSource) or an adapter of its own for a database. The record's format isschemas/component.schema.json, which the package ships; - a family is the model that reads a record's parameters: the code. A record names its family (
"family": "imu"), and the application registers the families its records name; - the module is installed on a world with
world.use(components())and attaches records to its bodies and joints:attachSensor(body, pose, record, options),attachMotor(joint, record, options). A world without it steps exactly as before.
The engine's own families are four sensors, imuSensor, encoderSensor, lidar2dSensor and tofZoneSensor, and one motor, dcServoMotor (below). From a record's JSON to an IMU read at every step:
import { createPhysicsWorld } from "mote-engine/physics";
import { components, createComponentCatalog, encoderSensor, imuSensor, jsonComponentSource } from "mote-engine/components";
// The records are data: here a JSON text, as a file read by the application would be.
const text = JSON.stringify({
format: 1,
components: [{
format: 1, id: "acme-imu6", type: "sensor", family: "imu", model: "Acme IMU-6", version: 1,
source: { kind: "datasheet", ref: "https://acme.example/imu6.pdf" },
params: { rate: 100, accelNoise: 0.02, accelBias: 0.05, accelRange: 78.5, gyroNoise: 0.002, gyroBias: 0.01, gyroRange: 34.9 },
}],
});
const world = createPhysicsWorld();
const comps = world.use(components()); // once per world: keep the handle
comps.registerSensorModel("imu", imuSensor); // the families the records name
comps.registerSensorModel("encoder", encoderSensor);
const json = jsonComponentSource(text); // { ok, source } or { ok: false, errors }
if (!json.ok) throw new Error(json.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
const catalog = createComponentCatalog(json.source, { families: comps.families });
const found = await catalog.get("acme-imu6"); // checked by its family: { ok, component } or the errors
if (!found.ok) throw new Error(found.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
world.addBody({ type: "static", shape: { type: "plane", normal: [0, 1, 0], offset: 0 } });
const chassis = world.addBody({ shape: { type: "box", halfExtents: [0.1, 0.03, 0.06] }, position: [0, 0.03, 0], mass: 1 });
// On the chassis, 2 cm above its origin, with the body's axes; the seed is this unit's noise.
const imu = comps.attachSensor(chassis, { position: [0, 0.02, 0] }, found.component, { seed: 42 });
const reading = new Float64Array(imu.size); // [ax, ay, az, gx, gy, gz]
for (let i = 0; i < 120; i++) {
world.step(1 / 60);
if (imu.read(reading)) {
// reading is of the instant imu.time; at rest reading[1] is the 9.81 m/s² the floor pushes with
}
}
console.log(imu.count, imu.time, reading[1]); // 120 readings, the last at 2 s, about 9.81
A sensor's handle (what attachSensor returns for these families): read(out, at?) copies the current reading into a Float64Array or Float32Array of the application's, from an optional index, and returns false, writing NaN, before the first reading; time is the world's time the reading is of, count how many readings there have been (it grows when a new one is current), size how many numbers a reading is; rate and latency are the ones in use; detach() takes the sensor off, and attached tells. NaN in a reading is no measure.
What every sensor does. It reads at its own rate: at the instants t0 + k / rate from the moment it is attached, each taken at the end of the first step that reaches it (a sensor faster than the steps reads once a step). A reading taken at t is the current one from the first step that ends at t + latency. Its noise comes from a generator of its own, seeded by the attachment: the same seed gives the same readings in every run, another seed another sequence, and no other sensor's draws change it. The attachment's options are what depends on how the sensor is mounted and run, not on the component: rate and latency (replacing the record's) and seed (a whole number from 0 to 4294967295, default 0; give each sensor its own). A step allocates nothing with sensors working, nor does read; the sensors' state (generator, readings on their way) is saved and restored with world.snapshot() and world.restore(), so a restored run continues bit for bit.
| Family | Attached to | Parameter | Unit | |
|---|---|---|---|---|
imu |
a body, at a pose | rate (required) |
Hz | readings a second |
latency |
s | default 0 | ||
accelNoise, gyroNoise |
m/s², rad/s | standard deviation of one reading, per axis; default 0 | ||
accelBias, gyroBias |
m/s², rad/s | standard deviation of a unit's constant offset: each sensor draws its own, once, from its seed; default 0 | ||
accelRange, gyroRange |
m/s², rad/s | readings are held within ± the range; default none | ||
encoder |
a hinge (pose null) |
resolution (required) |
rad | the encoder's step: 2π over its counts a turn |
rate (required) |
Hz | readings a second | ||
latency |
s | default 0 | ||
lidar-2d |
a body, at a pose | scanRate (required) |
Hz | sweeps a second |
angularResolution (required) |
rad | the nearest whole ray count to 2π over this | ||
maxRange (required), minRange |
m | outside these, no measure; minimum default 0 | ||
rangeNoise |
m | standard deviation of one ray; default 0 | ||
dropout |
1 | probability of a lost point; default 0 | ||
latency |
s | default 0 | ||
mass, size |
kg, m | optional component data; size is three numbers | ||
tof-zone |
a body, at a pose | zones (required) |
1 | [columns, rows], whole numbers |
fieldOfView (required) |
rad | [horizontal, vertical] |
||
maxRange (required), minRange |
m | outside these, no measure; minimum default 0 | ||
frameRate |
Hz | frames a second, or the attachment's rate |
||
latency |
s | default 0 |
imureads six numbers in the sensor's own frame (the body's, turned by the attachment'srotation, at itsposition):[ax, ay, az, gx, gy, gz], the accelerometer in m/s² and then the gyroscope in rad/s. The accelerometer reads the specific force, as a real one does: the acceleration of the point it is mounted at less gravity's. At rest on a floor it reads 9.81 m/s² upwards, in free fall 0; on a turning body it has the centripetal acceleration of where it is mounted. The acceleration is the mean over the step that ends at the reading, written in the frame the sensor had at the middle of that step; the gyroscope is the body's angular velocity at the end of the step. Gravity is the one the body feels (the world's times the body'sgravityScale). Its own options:accelBiasandgyroBias, three numbers each, are a real unit's measured offsets, used instead of the drawn ones;metresPerUnitis the world's when it is not 1, so that the accelerometer reads m/s².encoderreads two numbers:[angle (rad), speed (rad/s)]. The angle is the hinge's (HingeJoint.angle, in (−π, π]) at the nearest multiple ofresolution. The speed is what the counts give: the counts gone by since the reading before, times the resolution, over the time between the two, so it comes in steps ofresolution × rateand is the mean speed between two readings; the counts follow the hinge through whole turns. An encoder has no noise: its error is its resolution.lidar-2dreads one distance in metres per ray, at the centres of equal angular cells over a full turn. Ray 0 is at-π + resolution / 2, just off −X behind the sensor; indices grow towards −Z, the sensor's left (+X ahead, +Y up, +Z right). The attachment'sblindSector(radians, total angle centred on +X, default 0) hides a sector. Every reading draws independent normal range errors and uniform dropout numbers from its seed; a miss, a dropped point or a noisy distance outside the range isNaN.tof-zonereads one distance in metres per zone through each zone's centre in the[horizontal, vertical]field of view. Withzones = [columns, rows], row 0 is the bottom row and column 0 the rightmost (+X ahead, +Y up, +Z right); readingr * columns + cruns from the bottom row upwards, right to left within each row. These are ray distances, not horizontal projections; a miss or an out-of-range distance isNaN.- Range-sensor options. Both require the rays' collision
groupandmask, integers in [-2^31, 2^32): the batch uses that collision pair rather than a per-body exclusion closure, so choose one that does not see the sensor's own body. The attachment's pose turns and translates the rays with the body.
LiDAR and zoned ToF
import { createPhysicsWorld } from "mote-engine/physics";
import { components, lidar2dSensor, tofZoneSensor } from "mote-engine/components";
const lidarRecord = {
format: 1, id: "acme-lidar", type: "sensor", family: "lidar-2d", model: "Acme 360 LiDAR", version: 1,
source: { kind: "datasheet", ref: "https://acme.example/lidar.pdf" },
params: { scanRate: 10, angularResolution: Math.PI / 180, maxRange: 8 },
};
const tofRecord = {
format: 1, id: "acme-tof", type: "sensor", family: "tof-zone", model: "Acme zoned ToF", version: 1,
source: { kind: "datasheet", ref: "https://acme.example/tof.pdf" },
params: { zones: [2, 1], fieldOfView: [Math.PI / 2, Math.PI / 4], maxRange: 4, frameRate: 60 },
};
const world = createPhysicsWorld({ gravity: [0, 0, 0] });
const comps = world.use(components());
comps.registerSensorModel("lidar-2d", lidar2dSensor);
comps.registerSensorModel("tof-zone", tofZoneSensor);
const chassis = world.addBody({ type: "static", group: 2, mask: 1, shape: { type: "box", halfExtents: [0.1, 0.05, 0.1] } });
world.addBody({ type: "static", group: 1, shape: { type: "box", halfExtents: [0.1, 1, 1] }, position: [2, 0, 0] });
const lidar = comps.attachSensor(chassis, { position: [0, 0.05, 0] }, lidarRecord, { group: 2, mask: 1, blindSector: Math.PI / 18 });
const tof = comps.attachSensor(chassis, null, tofRecord, { group: 2, mask: 1 });
const scan = new Float32Array(lidar.size), zones = new Float32Array(tof.size);
for (let i = 0; i < 6; i++) world.step(1 / 60);
lidar.read(scan); // 360 distances in metres, NaN where there is no measure
tof.read(zones); // two distances, row by row
console.log(lidar.size, tof.size, scan[190], zones[0]);
A sensor of another kind is a family of the application's, registered the same way and made with the same mechanism: createSensor(ctx, { size, rate, sample }) gives it the rate, the latency, the seeded noise, the buffer and the snapshot, and the family writes only what it measures. sensorOptions(ctx, own) checks and copies an attachment's options for such a family: rate, latency and seed, which it checks, and the names in own, which are the family's to check (any other name is a TypeError naming the family). docs/embed/components.md has the catalog, the sources, and how to write a family.
A servo on a hinge (dc-servo)
dcServoMotor is the family of a geared DC servo: attachMotor(hinge, record, options) puts one on a hinge of a world made with jointSolver: "chain", and the hinge's motor, drive, friction and damping are the servo's from then on. The servo's numbers are the record's: two servos are two records, and the same code moves both.
import { createPhysicsWorld } from "mote-engine/physics";
import { components, dcServoMotor } from "mote-engine/components";
// Two servos as data: an arm's, commanded in position, and a wheel's, in velocity.
const armServo = {
format: 1, id: "acme-s30", type: "motor", family: "dc-servo", model: "Acme S-30 bus servo", version: 1,
source: { kind: "datasheet", ref: "https://acme.example/s30.pdf" },
params: { nominalVoltage: 12, voltageRange: [6, 12.6], stallTorque: 2.94, noLoadSpeed: 4.7, stallCurrent: 2.7, noLoadCurrent: 0.2, commands: ["position"] },
};
const wheelServo = {
format: 1, id: "acme-s20-hs", type: "motor", family: "dc-servo", model: "Acme S-20 HS bus servo", version: 1,
source: { kind: "datasheet", ref: "https://acme.example/s20hs.pdf" },
params: { nominalVoltage: 12, stallTorque: 1.96, noLoadSpeed: 11.1, stallCurrent: 2.4, noLoadCurrent: 0.2, commands: ["velocity"] },
};
const world = createPhysicsWorld({ jointSolver: "chain" }); // the servo's rows are the chain solver's
const comps = world.use(components());
comps.registerMotorModel("dc-servo", dcServoMotor);
// An arm on a post, and a wheel at its end.
const arm = world.addBody({ shape: { type: "box", halfExtents: [0.1, 0.01, 0.01] }, position: [0.1, 0, 0], mass: 0.1 });
const wheel = world.addBody({ shape: { type: "sphere", radius: 0.03 }, position: [0.2, 0, 0], mass: 0.1 });
const shoulder = world.addJoint({ type: "hinge", a: arm, b: null, anchor: [0, 0, 0], axis: [0, 0, 1] });
const axle = world.addJoint({ type: "hinge", a: wheel, b: arm, anchor: [0.2, 0, 0], axis: [0, 0, 1] });
const armMotor = comps.attachMotor(shoulder, armServo, { voltage: 11.1 }); // the battery's voltage: the attachment's
const wheelMotor = comps.attachMotor(axle, wheelServo);
armMotor.setPosition(0.5); // rad, the hinge's angle
wheelMotor.setVelocity(6); // rad/s
// wheelMotor.setPosition(1) would throw: the record lists "velocity" only.
const reading = new Float64Array(8);
for (let i = 0; i < 120; i++) world.step(1 / 60);
armMotor.read(reading, 0); // [angle (rad), speed (rad/s), torque (N·m), current (A)]
wheelMotor.read(reading, 4);
console.log(reading[0].toFixed(3), reading[2].toFixed(3), reading[5].toFixed(3), reading[7].toFixed(2));
- The model. At the battery's voltage V, with k = V /
nominalVoltage, the motor at full duty gives T = k·stallTorque− (stallTorque/noLoadSpeed)·w: the stall torque and the no-load speed both scale with the voltage. Its current follows its torque, fromnoLoadCurrenttostallCurrent; acurrentLimit(the record's, or the attachment's when lower) is therefore a torque limit, and must be above the no-load current, which the motor draws with no torque at all: a record's that is not is refused by the family's check, an attachment's throws aRangeErrorand attaches nothing.staticFrictionandviscousFrictionare the gearbox's own,reflectedInertiathe rotor's inertia at the output,backlashthe gears' free play. - Commands.
setPosition(rad),setVelocity(rad/s),setTorque(N·m), each only when the record'scommandslists it (aTypeErrorotherwise, and nothing changes);release()for no command. In position the joint is held by a spring of the attachment'sstiffness(N·m/rad at the nominal voltage; by default the stall torque at 0.03 rad) with the motor's own back-EMF for damping (anddampingmore, an option), turns toward a far target at up to the no-load speed, and presses on what stops it with the stall torque. In velocity the commanded speed is held while the line allows the load, and the line's speed is otherwise.write(values, at)gives the command in force a new value from a typed array, for a controller that commands at every step without allocating;setVoltage(V)changes the battery's voltage (within the record'svoltageRange). - Readings.
read(out, at)copies[angle, speed, torque, current]of the last step into the caller's buffer and returnstrue(false, and fourNaN, before the motor's first step). The torque is what the servo put on the joint over the step, ashinge.torque; the current is estimated from it (NaNfor a record withoutstallCurrent).timeandcountsay which step the readings are of. - Energy. In position the servo is the hinge's own drive, whose work is counted and can never exceed what its commands paid: a servo holding still gives nothing. A step allocates nothing with servos commanded and read, and their state (command, voltage, gap, readings) is saved with
world.snapshot(). - In a scene.
attachMotoralso takes the handlescene.physics.hinge(id)gives, from a physics module installed on the scene (physics.modules): the servo then follows that hinge through every joint the scene makes for it. See docs/embed/components.md, which also says what the model approximates (the rotor's inertia and the backlash, once a step) and its limits.
A whole robot: motors and sensors together
Motors and sensors of every family share one module, one step and one snapshot. A cart on four wheels, built from a catalog: a servo and an encoder on each wheel's hinge, an IMU and a LiDAR on the chassis; driven for two seconds, and its second second run again from a snapshot.
import { createPhysicsWorld } from "mote-engine/physics";
import { components, createComponentCatalog, dcServoMotor, encoderSensor, imuSensor, jsonComponentSource, lidar2dSensor } from "mote-engine/components";
// The robot's parts as data: one document, as a file the application reads would be.
const text = JSON.stringify({
format: 1,
components: [
{ format: 1, id: "acme-s20-hs", type: "motor", family: "dc-servo", model: "Acme S-20 HS bus servo", version: 1,
source: { kind: "datasheet", ref: "https://acme.example/s20hs.pdf" },
params: { nominalVoltage: 12, voltageRange: [6, 12.6], stallTorque: 1.96, noLoadSpeed: 11.1, stallCurrent: 2.4, noLoadCurrent: 0.2, commands: ["velocity"] } },
{ format: 1, id: "acme-enc12", type: "sensor", family: "encoder", model: "Acme 12-bit magnetic encoder", version: 1,
source: { kind: "datasheet", ref: "https://acme.example/enc12.pdf" },
params: { resolution: (2 * Math.PI) / 4096, rate: 50 } },
{ format: 1, id: "acme-imu6", type: "sensor", family: "imu", model: "Acme IMU-6", version: 1,
source: { kind: "datasheet", ref: "https://acme.example/imu6.pdf" },
params: { rate: 100, latency: 0.005, accelNoise: 0.02, accelBias: 0.05, gyroNoise: 0.002, gyroBias: 0.01 } },
{ format: 1, id: "acme-lidar", type: "sensor", family: "lidar-2d", model: "Acme 360 LiDAR", version: 1,
source: { kind: "datasheet", ref: "https://acme.example/lidar.pdf" },
params: { scanRate: 10, angularResolution: Math.PI / 180, maxRange: 8, rangeNoise: 0.01, latency: 0.02 } },
],
});
const world = createPhysicsWorld({ jointSolver: "chain" }); // a dc-servo's rows are the chain solver's
const comps = world.use(components());
comps.registerMotorModel("dc-servo", dcServoMotor); // the families the records name
comps.registerSensorModel("encoder", encoderSensor);
comps.registerSensorModel("imu", imuSensor);
comps.registerSensorModel("lidar-2d", lidar2dSensor);
const json = jsonComponentSource(text);
if (!json.ok) throw new Error(json.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
const catalog = createComponentCatalog(json.source, { families: comps.families });
const part = async (id) => {
const found = await catalog.get(id); // checked by its family
if (!found.ok) throw new Error(found.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
return found.component;
};
const [servo, encoder, imuPart, lidarPart] = await Promise.all(["acme-s20-hs", "acme-enc12", "acme-imu6", "acme-lidar"].map(part));
// A floor, a wall 2 m ahead (+X) and a cart: a chassis on four wheels, each on a hinge about Z.
// The robot's bodies are in group 2 and meet the surroundings (group 1) only, not each other.
const ROBOT = 2, AROUND = 1;
world.addBody({ type: "static", group: AROUND, shape: { type: "plane", normal: [0, 1, 0], offset: 0 }, friction: 0.8 });
world.addBody({ type: "static", group: AROUND, shape: { type: "box", halfExtents: [0.05, 0.5, 1] }, position: [2, 0.5, 0] });
const chassis = world.addBody({ group: ROBOT, mask: AROUND, shape: { type: "box", halfExtents: [0.1, 0.02, 0.05] }, position: [0, 0.04, 0], mass: 1, canSleep: false });
const onZ = [Math.SQRT1_2, 0, 0, Math.SQRT1_2]; // a cylinder's axis is its Y: turned onto Z
const hinges = [[0.07, -0.07], [0.07, 0.07], [-0.07, -0.07], [-0.07, 0.07]].map(([x, z]) => {
const wheel = world.addBody({ group: ROBOT, mask: AROUND, shape: { type: "cylinder", radius: 0.03, halfHeight: 0.01 }, position: [x, 0.03, z], rotation: onZ, mass: 0.1, friction: 0.9, canSleep: false });
return world.addJoint({ type: "hinge", a: wheel, b: chassis, anchor: [x, 0.03, z], axis: [0, 0, 1] });
});
// Motors on the hinges, sensors on the hinges and on the chassis. What depends on the mounting is the
// attachment's: the battery's voltage, a sensor's pose and seed, the rays' collision group and mask.
const motors = hinges.map((hinge) => comps.attachMotor(hinge, servo, { voltage: 11.1 }));
const encoders = hinges.map((hinge) => comps.attachSensor(hinge, null, encoder));
const imu = comps.attachSensor(chassis, { position: [0, 0.02, 0] }, imuPart, { seed: 1 });
const lidar = comps.attachSensor(chassis, { position: [0, 0.05, 0] }, lidarPart, { group: ROBOT, mask: AROUND, seed: 2 });
for (const motor of motors) motor.setVelocity(0);
// The controller's buffers, made once: commanding, stepping and reading allocate nothing.
const command = new Float64Array(1), servoNow = new Float64Array(4), wheelNow = new Float64Array(2);
const inertial = new Float64Array(imu.size), scan = new Float32Array(lidar.size), up = new Float64Array(1);
const step = (i) => {
command[0] = -Math.min(5, 0.1 * i); // rad/s about Z: the wheels roll toward +X, up to 0.15 m/s
for (const motor of motors) motor.write(command);
world.step(1 / 60);
if (imu.read(inertial)) up[0] += inertial[1] / 60; // [ax, ay, az, gx, gy, gz]: the mean of ay over a second
};
// One second of steps from step `from`, and what the robot reads at its end.
const second = (from) => {
up[0] = 0;
for (let i = from; i < from + 60; i++) step(i);
motors[0].read(servoNow); // [angle, speed, torque, current]
encoders[0].read(wheelNow); // [angle, speed]
lidar.read(scan); // 360 distances; ray 180 looks ahead
return [servoNow[1], servoNow[3], wheelNow[1], up[0], scan[180]].map((n) => n.toFixed(4)).join(" ");
};
second(0);
const saved = world.snapshot(); // with every motor's command, every sensor's noise and its readings on their way
const first = second(60);
world.restore(saved); // the same world, one second back
const again = second(60);
console.log(first === again, first); // true: wheel speed -5 rad/s, about 0.24 A, the encoder's -5, 9.81 m/s² up, the wall 1.7 m ahead
- One order. The components run in the order they were attached, motors and sensors alike: a motor's command before the solver, a sensor's reading after the bodies moved. The world's snapshot lists them in that order, and a restore needs the same components on the same targets in the same order.
- One snapshot.
world.snapshot()holds every component's state with the bodies and the joints: a servo's command, voltage and gears' gap, a sensor's generator, the readings on their way and the current one. Afterworld.restore(saved), in the same world or in a new one built the same way (attached with other seeds too: the noise is the snapshot's), every motor's and every sensor's readings repeat bit for bit on the same runtime. What the application's own controller keeps between two steps (a ramp, an integrator, the last command it decided) is the application's to save and put back; a command already given to a motor is the motor's, and is in the snapshot. - Each at its own rate. The servos are commanded and read at every step, the IMU reads at 100 Hz (once a step in a world stepped at 60 Hz), the encoders at 50 Hz, the LiDAR at 10 Hz with its latency. A controller slower than the steps commands when it runs: between two of its runs each motor keeps the command it has.
- Nothing allocated. A step allocates nothing with servos, IMUs, encoders, a LiDAR, a ToF and a sensor family of the application's all working and read at every step (measured together against the same world alone, with V8's sampling heap profiler).
- A family of your own beside them must declare what it keeps between two steps (
createSensor'sstate, orctx.state): a state that is not in the snapshot stays where the run had taken it, and the restored run is another one.
A robot from a file
A robot can be written once, as data, and built from it: its bodies and their shapes, its joints, and the motors and sensors on them, each cited by the id of its record in a catalog. validateRobotFile(json) checks a description; loadRobot(world, json, catalog, options) checks it, asks the catalog for the records it cites, and makes the robot in a physics world.
import { createPhysicsWorld } from "mote-engine/physics";
import { components, createComponentCatalog, dcServoMotor, encoderSensor, imuSensor, jsonComponentSource, loadRobot } from "mote-engine/components";
// Two documents, as the files the application reads would be: the parts, and the robot that cites them.
const parts = JSON.stringify({
format: 1,
components: [
{ format: 1, id: "acme-s30", type: "motor", family: "dc-servo", model: "Acme S-30 bus servo", version: 1,
source: { kind: "datasheet", ref: "https://acme.example/s30.pdf" },
params: { nominalVoltage: 12, voltageRange: [6, 12.6], stallTorque: 2.94, noLoadSpeed: 4.7, commands: ["position"] } },
{ format: 1, id: "acme-enc12", type: "sensor", family: "encoder", model: "Acme 12-bit magnetic encoder", version: 1,
source: { kind: "datasheet", ref: "https://acme.example/enc12.pdf" },
params: { resolution: (2 * Math.PI) / 4096, rate: 50 } },
{ format: 1, id: "acme-imu6", type: "sensor", family: "imu", model: "Acme IMU-6", version: 1,
source: { kind: "datasheet", ref: "https://acme.example/imu6.pdf" },
params: { rate: 100, accelNoise: 0.02, gyroNoise: 0.002 } },
],
});
const arm = JSON.stringify({
format: 1,
bodies: [
{ id: "base", type: "static", shape: { type: "box", halfExtents: [0.1, 0.02, 0.1] }, position: [0, 0.02, 0] },
{ id: "arm", mass: 0.1, canSleep: false, position: [0.1, 0.1, 0],
shape: { type: "compound", children: [
{ shape: { type: "box", halfExtents: [0.1, 0.01, 0.01] } },
{ shape: { type: "sphere", radius: 0.02 }, position: [0.1, 0, 0] },
] } },
],
joints: [{ id: "shoulder", type: "hinge", a: "arm", b: "base", anchor: [0, 0.1, 0], axis: [0, 0, 1], limits: [-1.5, 1.5] }],
motors: [{ id: "servo", joint: "shoulder", component: { id: "acme-s30" }, options: { voltage: 11.1 } }],
sensors: [
{ id: "turned", joint: "shoulder", component: { id: "acme-enc12" } },
{ id: "imu", body: "arm", pose: { position: [0.05, 0, 0] }, component: { id: "acme-imu6" }, options: { seed: 3 } },
],
});
const world = createPhysicsWorld({ jointSolver: "chain" }); // a dc-servo's rows are the chain solver's
const comps = world.use(components());
comps.registerMotorModel("dc-servo", dcServoMotor); // the families the records name
comps.registerSensorModel("encoder", encoderSensor);
comps.registerSensorModel("imu", imuSensor);
const source = jsonComponentSource(parts);
if (!source.ok) throw new Error(source.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
const catalog = createComponentCatalog(source.source, { families: comps.families });
// The robot, half a metre along +Z: its handles by the ids of the file.
const loaded = await loadRobot(world, arm, catalog, { components: comps, position: [0, 0, 0.5] });
if (!loaded.ok) throw new Error(loaded.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
const robot = loaded.robot;
robot.motor("servo").setPosition(0.5); // rad: the shoulder, to half a radian
for (let i = 0; i < 120; i++) world.step(1 / 60);
const turned = new Float64Array(2);
robot.sensor("turned").read(turned); // [angle, speed] of the hinge, as the encoder counts them
// A description that cites a record the catalog does not have is refused, and nothing of it is made.
const other = JSON.parse(arm);
other.motors[0].component.id = "acme-s31";
const refused = await loadRobot(world, other, catalog, { components: comps });
console.log(turned[0].toFixed(2), robot.bodies.get("arm").position[2], world.bodies.length, refused.ok ? "loaded" : refused.errors[0].path);
// 0.50 0.5 2 /motors/0/component/id
- The format mirrors the calls. A body is
addBody's spec with anid(the shape a sphere, a box, a capsule, a cylinder, a convex hull, or a compound of those); a joint isaddJoint's with anidand its two bodies by their ids (bleft out: pinned to the world), of any kind the world has; a motor isattachMotor's arguments (joint, the record ascomponent: { id, version? }, the attachment'soptions); a sensor isattachSensor's (bodywith aposein its frame, orjoint; the record; theoptions). A record'sversionleft out is the highest the catalog has. A hinge'smotoris its own (setMotor, in N·m), which a motor component attached to it takes over. - The robot's frame. Positions, rotations (quaternions), anchors and axes are where the robot's parts are when it is assembled, in a frame of its own;
options.positionandoptions.rotationplace that frame in the world, so one file is loaded anywhere, and as many times as wanted. Without them the file's numbers reach the world bit for bit. - One order. Bodies, then joints, then motors, then sensors, each list in the file's order: the order the world keeps them in, runs the components in at each step, and lists them in its snapshot. Two worlds loaded from the same file are the same world, and a robot loaded from a file steps bit for bit as the same robot built by the same calls in that order.
- Refused with the field's pointer. A description that is wrong is refused whole, with every error found (a hundred at most), each
{ path, expected, got, message }with the field's JSON pointer, as a scene's and a record's are: an unknown field (with the name most likely meant), a number that is not finite or out of its range, an id used twice, a joint whose body is not there, a motor or a joint's sensor on a joint that is not a hinge, a sensor on both a body and a joint.loadRobotthen asks the catalog, and refuses at the citing entry (/motors/0/component/id) a record that is not there, a motor's record cited as a sensor (or the reverse), a record of a family the world's module has not registered, and one its family's check refuses. All of this is checked before one body is made. - Whole or not at all. What only code can refuse is refused while the robot is made: an option its family does not take, a
dc-servoin a world withoutjointSolver: "chain", a hinge'sdriveon the default solver. What was made of the robot until then is taken out again and the error names the entry (/motors/0): the world has no body, joint or component of a robot that did not load.robot.remove()takes a loaded robot out the same way. - Handles by id.
robot.bodies,robot.joints,robot.motorsandrobot.sensorsare maps by the file's ids;robot.hinge(id),robot.motor(id)androbot.sensor(id)give one and throw for an id the file does not have.
Limits, for now: a description holds no mesh and no plane (the shapes of a place, static), and a compound's children are solids, not compounds; a motor, and a sensor on a joint, go on a hinge; lengths are in the world's units, as addBody takes them. The robot's controller is the application's: a file describes what the robot is, not what it does. A robot taken out again while it was being made has used the world's body ids and fired its removal events. docs/embed/components.md has every field.
A robot in a scene
The same file goes in a scene with physics: loadRobotInScene(scene, json, catalog, options) makes each body an object of the stage on screen with that body, each joint a joint of the stage, and puts the motors and the sensors on them; it resolves to a SceneRobot (objects, joints, hinge(id), motor(id), sensor(id), made, generation, remove()) inside { ok, robot }. The robot is then the scene's: drawn in every mode, grabbed and thrown, pushed by the effects, with its hinges under scene.physics.hinge(id).
import { createScene } from "mote-engine";
import { components, createComponentCatalog, createComponentRegistry, dcServoMotor, encoderSensor, imuSensor, jsonComponentSource, loadRobotInScene } from "mote-engine/components";
// The same two documents as above: the parts, and the robot that cites them.
const parts = JSON.stringify({
format: 1,
components: [
{ format: 1, id: "acme-s30", type: "motor", family: "dc-servo", model: "Acme S-30 bus servo", version: 1,
source: { kind: "datasheet", ref: "https://acme.example/s30.pdf" },
params: { nominalVoltage: 12, voltageRange: [6, 12.6], stallTorque: 2.94, noLoadSpeed: 4.7, commands: ["position"] } },
{ format: 1, id: "acme-enc12", type: "sensor", family: "encoder", model: "Acme 12-bit magnetic encoder", version: 1,
source: { kind: "datasheet", ref: "https://acme.example/enc12.pdf" },
params: { resolution: (2 * Math.PI) / 4096, rate: 50 } },
{ format: 1, id: "acme-imu6", type: "sensor", family: "imu", model: "Acme IMU-6", version: 1,
source: { kind: "datasheet", ref: "https://acme.example/imu6.pdf" },
params: { rate: 100, accelNoise: 0.02, gyroNoise: 0.002 } },
],
});
const arm = JSON.stringify({
format: 1,
bodies: [
{ id: "base", type: "static", shape: { type: "box", halfExtents: [0.1, 0.02, 0.1] }, position: [0, 0.02, 0] },
{ id: "arm", mass: 0.1, canSleep: false, position: [0.1, 0.1, 0],
shape: { type: "compound", children: [
{ shape: { type: "box", halfExtents: [0.1, 0.01, 0.01] } },
{ shape: { type: "sphere", radius: 0.02 }, position: [0.1, 0, 0] },
] } },
],
joints: [{ id: "shoulder", type: "hinge", a: "arm", b: "base", anchor: [0, 0.1, 0], axis: [0, 0, 1], limits: [-1.5, 1.5] }],
motors: [{ id: "servo", joint: "shoulder", component: { id: "acme-s30" }, options: { voltage: 11.1 } }],
sensors: [
{ id: "turned", joint: "shoulder", component: { id: "acme-enc12" } },
{ id: "imu", body: "arm", pose: { position: [0.05, 0, 0] }, component: { id: "acme-imu6" }, options: { seed: 3 } },
],
});
// The families the records name, in a registry the scene's worlds share, and the components module itself:
// a scene makes a world for each stage it shows, and the module is installed on each.
const registry = createComponentRegistry();
registry.registerMotorModel("dc-servo", dcServoMotor);
registry.registerSensorModel("encoder", encoderSensor);
registry.registerSensorModel("imu", imuSensor);
const robots = components({ registry });
const source = jsonComponentSource(parts);
if (!source.ok) throw new Error(source.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
const catalog = createComponentCatalog(source.source, { families: registry.families });
// A scene with physics on the chain solver (a dc-servo's), a metre to a unit (physics.scale, 1 by default).
// Paused, and stepped by hand below; a page leaves it running and commands from physics.onStep.
const scene = createScene(canvas, {
physics: { jointSolver: "chain", paused: true, modules: [robots] },
stages: [{ items: [] }],
});
// The robot in the stage on screen, half a metre along +Z, its objects and joints under a prefix of their own.
const loaded = await loadRobotInScene(scene, arm, catalog, { components: robots, idPrefix: "arm.", position: [0, 0, 0.5] });
if (!loaded.ok) throw new Error(loaded.errors.map((e) => `${e.path}: ${e.message}`).join("\n"));
const robot = loaded.robot;
robot.motor("servo").setPosition(0.5); // rad: the shoulder, to half a radian
for (let i = 0; i < 120; i++) scene.physics.step();
const turned = new Float64Array(2);
robot.sensor("turned").read(turned); // [angle, speed] of the hinge, as the encoder counts them
const shoulder = robot.hinge("shoulder"); // the scene's own handle: scene.physics.hinge("arm.shoulder")
const object = scene.item(robot.objects.get("arm")); // the scene's object "arm.arm", drawn where its body is
const seen = [turned[0].toFixed(2), shoulder.angle.toFixed(2), object.id, object.transform.position[2], robot.made];
// The same file again under the same prefix is refused, and nothing of it is made. Removed, the robot leaves the scene as it was.
const again = await loadRobotInScene(scene, arm, catalog, { components: robots, idPrefix: "arm." });
robot.remove();
console.log(...seen, scene.items().length, again.ok ? "loaded" : again.errors[0].path);
// 0.50 0.50 arm.arm 0.5 true 0 /bodies/0/id
- Objects and stage joints. A body
baseis the objectscene.item("base"), withItemSpec.bodymade of the file's fields; a jointshoulderis a joint of the stage, and when it is a hingescene.physics.hinge("shoulder")is its handle (robot.hinge("shoulder")gives the same one).idPrefixgoes before every id ("arm.":arm.base,arm.shoulder), so one file is loaded as many times as wanted;robot.objectsandrobot.jointsmap the file's ids to the scene's. The robot goes in the stage on screen, which is the one a scene adds objects to (stage, when given, must be it), oncescene.readyhas resolved. - Drawn as its shapes, or as you say. Without more, each body is drawn as its collision shape, as it is: a box, a sphere, a cylinder, a capsule, a convex hull, a compound's parts each in its place.
sourcesgives another look by the body's id: a source already loaded (sources: { chassis: await loadGltf("/robot/chassis.glb") }), drawn about the body's origin at the size it was made, or{ source?, scale?, material?, visible? }(ascalefor a source, a material for either). A model placed otherwise on its body is an object of its own withparentthe body's object. - Units. Lengths are the scene's units,
physics.scalemetres each (1 by default: the file's metres are units), as a stage's bodies and joints are; masses are kilograms; a hinge's ownmotoris given to its handle, in N·m at every scale.positionandrotationplace the robot's frame in the scene, asloadRobot's do in a world. - Motors and sensors.
componentsis the module itself, whatcomponents({ registry })returns, with the records' families in its registry. A scene makes a new world for each stage it shows, so the module is installed on each: list it inphysics.modules, or let the robot install it.robot.motor(id)androbot.sensor(id)give the handles their families made, as in a world. - Refused before an object is made. With every error and its JSON pointer: the description and the records, as
loadRobotrefuses them; an id the scene already has, at the body's or the joint'sid(/bodies/0/id); a hinge'sdrive,frictionordampingin a scene withoutjointSolver: "chain", at the joint; and what is the scene's, at the root (""): nophysics, astagethe scene does not have or does not show. What only a family'screaterefuses (an option it does not take, adc-servowithout the chain solver) takes out again what was made, and names the entry (/motors/0). - The same robot as in a world. Its bodies are made by the same
addBody, its joints by the sameaddJoint, its components attached in the same order asloadRobotdoes. In a scene whose world is made as that world (the same gravity,substepsandjointSolver, the same bodies before the robot's or none:floor: false,walls: false), stepped with the same commands at the same steps, the robot steps bit for bit asloadRobot's: every body, every motor's and sensor's reading, and the world's snapshot. At anotherphysics.scalethe same holds against a world of those units. One difference is known: a body'srotationthat is not of length 1 (beyond 1e-12) is normalised once more by the scene than by a world, and may start a unit in the last place apart; write rotations normalised. - What the scene makes again. A scene makes a stage's bodies and joints again in a new world when the stage is shown again, and one object's when it is taken out and spawned again. The robot follows: before the first step of the new world its motors and sensors are attached again, new (a motor without a command, a sensor from its seed); in the same world a motor follows its hinge with its command, and a sensor is attached again when its body or joint was made again.
robot.madesays whether the robot is whole in the world on screen now, androbot.generationcounts those attachments: when it has changed, ask the robot for its motors and sensors again, and command them again. While its stage is not on screen,robot.motor(id)throws. - Removed.
robot.remove()takes out the components, the joints and the objects, and the scene is as it was: its objects, its stage's own joints, its description. Nothing stands in for a robot removed before others loaded after it:scene.describe()has no joint of it, and the others keep their hinges' handles, their motors and their commands (a handle'sindex, its joint's place in the stage's joints, moves up).setStagesreplaces the stages, and a robot of the old ones with them.
Limits, for now: a robot is loaded in the stage on screen, not in another one; sources takes sources already loaded; the scene's default floor is worked out when a stage is first shown, before a robot loaded later (give floor a height); a robot's components are not kept across a stage's worlds (attached again, new). docs/embed/components.md has the options, the handles and what is checked.
Limits
These follow from the soft-step solver (one sweep per sub-step, contacts as soft constraints) and the shapes it takes:
- Heavy bodies on light ones: a stack holds at 3 to 1, buckles after some seconds at 10 to 1, and at once from 30 to 1 (more sub-steps only delay it). Keep the masses of what stacks within a few times of each other. A chain holding ten times its links' weight stretches about 1 %.
- Soft contacts give a little under load: an 8-box stack sags about 1.75 cm at its top (raise the engine's contact stiffness for less).
- Dynamic bodies are convex: a concave model collides as its convex hull, unless it is given a compound of shapes. A
"mesh"shape is for static and kinematic bodies only, and one-sided: a triangle pushes only towards its front (its counter-clockwise face, the outside of a closed mesh), so a floor is passed through from below and an open sheet wound the wrong way lets bodies through. - Small, fast bodies against thin walls want
ccd: true; speculative contacts stop the rest. - An island with a rolling sphere stays awake until
rollingFrictionstops it. - With
floor: falseandwalls: falsebodies fall for ever (and keep the scene drawing). - Under an orbit, the walls and the colliders stay where the unturned view puts them.
- In ray, an object shows where its particles are attached (The skin): bodies keep their whole surface while they move, small ones included (each solid gets the particles its skin needs). A very small object has few points of its own, so its skin is dilated further and an effect's hole in it (
holes, a burn) has a coarser edge. More than 64 objects with a skin at once: the others are drawn whole (a console warning). - Thin slabs: a box in its own proportions (
box(w, h, d)) and a cube stretched by a scale vector draw the same (see The skin); the body's shape follows the scale either way. - Mirrored and collapsed objects: a body's shape is the object's at its scale, sign included, so a mirrored object (a negative scale component, its own or a parent's) collides as the mirror image it is drawn as, and weighs the same. While an object is collapsed by its own scale or an ancestor's, its body neither hits nor is hit: there are no contacts or scene physics raycast hits. Each already-open contact or sensor overlap emits exactly one
contactEndorsensorExitat collapse, in world order; nocontactBegin,contactPersist,impactorsensorEnteris emitted meanwhile. A dynamic body is not simulated: its pose stays fixed, settingvelocityand callingapplyImpulseare ignored, and its linear and angular velocity are zero on return. A kinematic body can still follow its transform, but cannot collide; a dynamic one stays dynamic on return, and a static one static. A joint to a collapsed body stays made and keeps holding its partner at the body's pose: the collapse takes away only the body's contacts and raycast hits. Restoring a nonzero scale restores the body's collider at that current scale; a still-overlapping body begins a new contact, and a scale animation can pass through 0 without NaN or errors. Under a parent passing through a mirror, a child's non-collapsed body turns over in that one frame (a mirror is not a motion a body can follow), and pushes what it touches accordingly.
const shelf = scene.item("shelf")!;
shelf.set({ scale: [1, 0, 1] }); // falling bodies pass through its body
shelf.set({ scale: [1, 0.1, 1] }); // they collide with this thin shelf again
Orbit
orbit: { yaw, pitch } (degrees) turns the view about the origin, in every mode: yaw about the vertical (the objects' fronts turn to the right), then pitch about the horizontal (their tops towards the viewer). The objects and the lights turn together (the lights stay in the world's frame) and gravity stays the world's −y. scene.orbit reads { yaw, pitch } (both can be set on it) and takes an Orbit (only what is given changes), from the next frame. Under a pitch ray's floor tips with the world (a resting object's shadow lies under it), and an environment turns with the yaw only. The demo turns the view with a right-drag or two fingers.
Ray also accepts a world-space cameraPose: { position, target, up?, allowOrbit? } or cameraPath: { keys, interpolation? }. position, target and up are three-component vectors in scene units; up defaults to [0, 1, 0]. A path has 2–4096 keys, each a pose with at, strictly increasing from 0 to 1. All keys must have the same normalized up; paths cannot allow orbit. interpolation is "linear" (default) or "smooth" (smoothstep within each segment). Coincident eye/target, collinear up, nonfinite values, and paths crossing a degenerate basis are rejected before replacing the current camera. The key limit bounds synchronous validation and copying work.
import { createScene, bindCameraScroll, sphere } from "mote-engine";
const scene = createScene(canvas, {
stages: [sphere()], mode: "ray", ray: {},
cameraPath: {
keys: [
{ at: 0, position: [-3, 1, 9], target: [0, 0, 0] },
{ at: 1, position: [3, 1, 7], target: [0, 0, 0] },
],
interpolation: "smooth",
},
cameraProgress: 0,
});
scene.cameraProgress = 0.5; // A clock or animation can drive this directly.
const unbind = bindCameraScroll(scene, section, { start: 0, end: 1 });
// At page teardown:
unbind();
scene.destroy();
scene.setCameraPose(pose) and scene.setCameraPath(path) validate and deep-copy their input; the last successful non-null setter replaces the other mode. If both options are supplied initially, the path takes precedence. Setting either to null clears both and restores the saved legacy orbit and scalar camera distance. Explicit cameras use the eye-target distance in place of camera. cameraProgress accepts finite numbers, clamps to 0–1, and remains unchanged when switching renderers or replacing the camera. Pose/path replacement is a camera cut; ordinary progress is motion. Returning to ray clears its camera history.
An explicit pose ignores scene.orbit writes, including a page's drag controls, unless allowOrbit: true; paths always ignore them. Allowed orbit starts at zero relative to the pose and does not change the legacy orbit restored on clear. ASCII and Wireframe draw the objects from the same world camera, target translation and roll included, and retain the requested pose/path and progress through a mode change, so returning to ray restores the world view. Physics picks and grab targets follow the camera, while body coordinates, gravity and force/velocity vectors keep their world frame. Environments currently follow eye-target heading only, independently of roll; a vertical eye-target direction retains the last defined heading (zero initially).
bindCameraScroll(scene, element, { start?, end? }) is optional. The element's travel runs from its top entering the viewport bottom (0) to its bottom exiting the viewport top (1); start and end select that interval (defaults 0 and 1). Distinct finite values are required; reversed intervals play backwards. Scroll and resize listeners are passive and coalesce into one animation frame. Geometry is cached at binding and refreshed on window/element resize, so scroll updates use numbers without requesting a new rectangle. Rebind after a layout change that only moves the element. Call the returned disposer before destroying the scene; it removes the listeners, disconnects its resize observer and cancels pending work. The engine itself does not depend on scrolling.
Camera rigs
scene.setCameraRig(rig) sets a camera the scene evaluates every frame, in every mode, from the objects where they are: a follow or an orbit is motion for Ray's temporal history, not a cut a frame. The rig's kinds, by kind:
| kind | fields | the camera |
|---|---|---|
static |
pose |
today's pose (setCameraPose is this rig) |
path |
path, progress? |
today's path; scene.cameraProgress drives it |
lookAt |
position, target (an object's id or a point) |
a free eye looking at an object or a point |
orbit |
center (id or point), distance, yaw, pitch |
the eye at distance from the centre, turned as orbit turns the view (yaw 0 on +z, 90 on −x; pitch raises it; keep pitch within ±89) |
follow |
target (id), offset, lookAt? (id, point or "target"), stiffness?, damping?, frame? |
the eye at the object plus offset (in the world's frame, or the object's with frame: "target"), looking at the object (or lookAt), both smoothed by a critically damped spring (stiffness /s², default 25; damping 0 or absent: critical) |
attach |
target (id), distance? |
the camera on the object: the eye at its origin, looking along its −Z axis, its +Y axis up, where the object is drawn (under its parents, with its motion, tweens and timeline tracks). The camera of a glTF file: see A model's cameras |
Every rig takes fov (vertical degrees, 5–150: the projection then spans it at the rig's distance, unit = h / (2 d tan(fov / 2)), so ASCII, Wireframe and Ray draw the same picture), roll (degrees about the view axis), up (before the roll; default the pose's or [0, 1, 0]), handheld: { amplitude, frequency, seed? } (value noise on eye and target, a function of scene time: a stepped scene reproduces it) and blend (seconds to crossfade eye, target, up, fov and roll from the camera as it was; 0, the default, is a cut).
scene.setCameraRig({ kind: "follow", target: "hero", offset: [0, 1.2, 4.5], fov: 45, handheld: { amplitude: 0.02, frequency: 2, seed: 7 } });
scene.setCameraRig({ kind: "orbit", center: "hero", distance: 6, yaw: 30, pitch: 15, blend: 0.5 }); // motion, not a cut
scene.cameraCut(); // the next frame resets Ray's history
const { position, target, up, fov, roll, distance, cut } = scene.camera; // the camera as the last frame drew it (a copy)
scene.setCameraRig(null); // the pose, path or orbit set before the rig
The rig is validated and deep-copied before anything changes (a TypeError or RangeError leaves the rig in place); setting one is synchronous (no module to load).
- A replacement is a cut unless
blendis above 0;setCameraPoseandsetCameraPathreplace a rig as they replace each other, andsetCameraRig(null)restores whatever they had set. - An object a rig names that is gone, or not on the stage shown, freezes the rig where it is (no error in the frame loop); a degenerate basis (the eye on its target, the up along the view) does the same.
- An
attachrig reads the object's two axes without their scale: the size of the object and of its parents changes nothing of the view, and a mirroring scale is not drawn mirrored. A scale of 0 along the object's Z or Y (its own, or a parent's) leaves no direction to read, and freezes the rig where it is, as an object that is gone. Under parents whose uneven scale shears the object, the view is where its −Z really points.upreplaces the object's +Y,rollturns about the view on top of the object's bank, anddistance(default 1, at least 1e-6) is how far ahead the camera'stargetpoint is: with afovthe perspective does not depend on it (it is the distance the scene's pixel sizes refer to), without one it is where the scene's zoom applies. - The pointer's orbit is off under a rig, but for a static one whose pose allows it.
scene.cameraRigreads the rig set (a copy), or the pose or path as a static or path rig.scene.camerareads single-precision values (the frame's matrices);fovis the rig's, or the one the projection spans (0 before the first layout).
The scene timeline
scene.setTimeline(doc) installs a timeline (TimelineJson, schemas/timeline.schema.json): tracks of keys over the objects' transforms, the lights' fields, the camera rig's parameters, an effect's live parameters, the scene's exposure or zoom, the stage index; and cues, named operation batches fired once each time the playhead crosses them. The playhead moves with the scene's time, so it follows the real, fixed or stepped clock without a case of its own: under a stepped clock a consumed step moves it by step × rate.
const { ok, timeline, errors } = await scene.setTimeline({
version: 1, duration: 12,
tracks: [
{ target: "item:jet", property: "position", keys: [{ t: 0, v: [0, 0, 0] }, { t: 4, v: [2, 1, 0], ease: "inOut" }] },
{ target: "item:jet", property: "rotation", keys: [{ t: 0, v: [0, 0, 0] }, { t: 4, v: [0, 90, 0], ease: [0.4, 0, 0.2, 1] }] },
{ target: "camera", property: "rig.yaw", keys: [{ t: 0, v: 0 }, { t: 12, v: 90 }] },
{ target: "light:1", property: "intensity", keys: [{ t: 2, v: 0 }, { t: 3, v: 5, ease: "in" }] },
{ target: "effect:fx:0", property: "density", keys: [{ t: 0, v: 0 }, { t: 2, v: 1 }] },
{ target: "item:jet", property: "visible", keys: [{ t: 8, v: false }] },
],
cues: [{ t: 3, name: "shot-2", ops: [{ op: "set", target: "item:jet", property: "material", value: { preset: "gold" } }] }],
});
timeline.seek(2); // a motion, never a cut
timeline.onCue((name, t) => console.log(name, t));
Targets are item:<id>, camera, light:<index>, effect:<id> (the effects' ids are fx:<n> in order of registration: the scene's, then each stage's, then addEffect's), scene and stage.
Value kinds:
position,scale(a number or three, of any sign: a negative component mirrors, a 0 collapses the object), a light'sposition,direction,upand the rig'srig.position,rig.target,rig.offsetlerp;rotation(Euler degrees or a quaternion) slerps;fov,roll,rig.distance,rig.yaw,rig.pitch,rig.progress,rig.handheld.amplitude, a light'sintensity,range,angle,penumbra,radius,width,height,rotation, the scene'sexposureandzoom, and an effect's numeric parameters lerp;- colours (
color,sky,ground;[r, g, b]linear or a CSS string) lerp in linear RGB; - an item's
weights(the weights of its mesh's morph targets: a list of 1 to 64 numbers, every key of a track as many) lerp, each weight on its own, and takehermitekeys with a tangent a weight; visible,material,motion, a light'scastShadowandbackground, a boolean effect parameter and the stageindexare steps, held until the next key.
The ease named on a key is the ease into it:
"linear";"in"(quadratic),"out","inOut"(the engine's smoothstep, so a one-keyanimateand a two-key track agree);"hold";- a cubic Bézier
[x1, y1, x2, y2]withx1andx2from 0 to 1; - or
"hermite"with the keys'inandouttangents (glTF's CUBICSPLINE: A model's animations).
A track writes its target every frame within its first and last keys (the last key's value is written once when crossed, so a frame that skips it still lands there); before its first key it writes nothing, and past its last key the object is the hand's again. A track on an object's transform ends that object's animate (as set does) and overwrites a set at the next sample.
With bodies:
- An object with a dynamic body is kinematic from its track's first key to its last, then dynamic at rest (velocity 0), as with
animate. - Position and rotation tracks are sampled at every fixed 60 Hz physics step's own end time and carry both a declared kinematic body and a dynamic body made kinematic by the track with
moveTo, including when one frame consumes several steps or frames arrive at a rate other than 60 Hz, so physics events and contacts see the track's linear and angular velocity rather than a teleport or zero-velocity substeps. - When a track starts mid-frame, its first active step reports the part of the step inside the track, not a whole step at the track's velocity.
- A child body's parent-composed pose, whether its body is dynamic or declared kinematic, still uses the composed frame transform interpolated over the frame's steps (including when the child has its own track); the hierarchy is not resampled at each physics step.
A track on a camera parameter needs a rig: when the scene has none, a static rig is made from the camera as it is (a cut, once, at the install).
An effect parameter can be tracked only when the effect serves it live (EFFECT_PARAMS[name][key].live === "param": the numbers and flags of water, clouds, fog, smoke, wind, vortex and magnet; the others, and every select and colour, change through set alone) — the document is refused at /tracks/<i>/property otherwise, as it is for an effect the page added without a param hook. A page-made effect takes part by giving param(key, value) (liveParams from the root builds a typed block for it, which the timeline writes in place).
The document is validated whole before anything changes, with JSON-pointer diagnostics and the walk's caps:
- 100 000 JSON values outside the tracks, which have their own 1 200 000-value budget;
- 4096 tracks, 4096 keys a track and 65 536 in all;
- 256 cues, 64 operations a cue;
- times finite and strictly increasing within
[0, duration],durationat most 3600 s.
A cue's operations go through validateSceneOps and may not be step, timeline, stages or system (refused at /cues/<i>/ops/<j>/op).
setTimeline:
- resolves
{ ok: true, timeline }with the handle (playing from 0;scene.timelinereads it); - resolves
{ ok: false, errors }for a refused document (nothing changed); - rejects with
{ kind: "load" }or{ kind: "destroyed" }; - throws a
TypeErrorfor an argument that is not an object ornull(nullremoves the timeline).
The director's module loads with import() on the first call and scene.ready covers the load.
The handle:
play(),pause();seek(seconds)(aRangeErroroutside0..duration; a motion, never a cut);rate(0.25 to 4);playing,time,duration;onCue(cb): the unsubscribe is returned. Physics and other cue operations run in order, exactly once per forward crossing, including when a frame skips over the cue or a loop crosses it again, up toLOOP_CYCLES_MAX(64) loop cycles in one frame; cues from cycles skipped beyond that cap are dropped. A seek fires nothing on its own sample. A cue exactly at the seek point stays armed and fires on the first forward advance withdt > 0(including afterseek(0)or a fixed clock rewound to 0 or less); a cue strictly behind the seek point does not fire again. Their operations are recorded for the operations runtime, which executes them.
A handle replaced by another setTimeline is inert. Sampling allocates nothing a frame: the keys live in typed arrays, the samples are written in place into the objects' transforms, the lights' fields, the rig's block and the effects' live blocks; under a stepped clock two runs give bit-identical state.
validateTimeline, compileTimeline and sampleTimeline are exported by mote-engine/director for tools that check a document before sending it.
A model's animations
The animations of a glTF model read as a tree (gltfTree, above) play as a timeline: gltfTracks turns one animation's channels into tracks on the nodes' objects, and setTimeline installs it.
import { createScene, parseGltf, gltfTree, gltfTreeItems } from "mote-engine";
import { gltfTracks } from "mote-engine/director";
const doc = parseGltf(await (await fetch("/models/robot.glb")).arrayBuffer());
const tree = gltfTree(doc);
const { items, ids } = gltfTreeItems(tree, { id: "robot", motion: "none" });
const scene = createScene(canvas, { mode: "ray", stages: [{ items }] });
const { timeline, animation, diagnostics } = gltfTracks(doc, tree, ids, { animation: "Walk", loop: true });
await scene.setTimeline(timeline); // animation.duration seconds; diagnostics: what is not played
- Each channel on a node of the tree is a track on that node's object:
translation→position,rotation→rotation(a quaternion),scale→scale. A child node under an animated parent moves with it, as any child (see Parents and groups). - The sampler's interpolation is kept exactly.
STEPgivesholdkeys;LINEARlinear keys, a rotation's a slerp the shorter way (the specification's);CUBICSPLINEgiveshermitekeys with the file's in- and out-tangents, and the timeline evaluates glTF's cubic Hermite spline (Appendix C) itself, the tangents scaled by the segment's length, a rotation normalised after: no Bézier stands in for it (the tests compare 32 points inside every segment with the specification's formulas, within 1e-6). Before a channel's first key frame its first value holds, after its last the last (glTF's clamping). gltfAnimations(doc, { animation })(root andgltfsubpath) reads the channels themselves: times and values asFloat64Arrays, a CUBICSPLINE's values as the file's triples (in-tangent, value, out-tangent).- Untrusted input, as the parser: every animation's structure, references, accessor types and counts are checked before anything is read (times are SCALAR floats; a translation's and a scale's values VEC3 floats; a rotation's VEC4 floats or normalised integers; a CUBICSPLINE has three values a key frame and two key frames at least), at most 1024 channels, 1024 samplers and 1 048 576 key frames in a document (
GLTF_ANIMATION_LIMITS); then the times must be finite, from 0 and strictly increasing, the values finite, and no key frame's rotation of length 0. A rule broken is anErrornaming the animation, the sampler or channel, and the accessor. - The timeline's own caps apply to the result and are checked first: 4096 channels played, 4096 key frames a channel, 65 536 in all, 3600 s, and a dedicated 1 200 000 JSON values under the tracks (a CUBICSPLINE key takes 15 of them, a rotation's 18; the budget admits the aggregate key cap even when every key is a CUBICSPLINE rotation). Other input keeps the general 100 000-value cap. The same
gltfTracks+setTimelinecalls above need no special option for a 120-joint TRS rig (360 tracks of 60 LINEAR keys each, 21 600 keys overall). - Setup cost. Conversion, validation and compilation are synchronous. In the 0.50 desktop measurement, the worst permitted shape (16 tracks × 4096 CUBICSPLINE rotation keys, 65 536 keys and 1 179 541 JSON values) took about 205 ms in
gltfTracksincluding its validation, then 151 ms assetTimelinevalidated it again and 21 ms to compile, about 376 ms in all. The second validation is intentional:setTimelineaccepts arbitrary documents and checks targets against the live scene. Install large rigs outside input handlers, frame callbacks and animation loops. - Director stdio. The server's 1 MiB line limit applies before the timeline budgets and can reject a large rig even when those budgets accept it. Install large timelines in process with
scene.setTimelineinstead. - Morph targets. A node's
weightschannel is aweightstrack on its object, two or more numbers a key (one a target of its mesh), with the same three interpolations: STEP, LINEAR, and CUBICSPLINE with the file's tangents, a weight each. Until 0.46 such a channel had aweightsdiagnostic and was not played. - Not played, and said (
diagnostics, each with acodeand a message): channels without a node (an extension's target,no-node), aweightschannel on a node whose mesh has no morph targets (weights-no-targets), and a channel on a node outside the tree's scene (node-outside-tree). - Skins. A channel on a skin's joint is a track like any other, and the skinned mesh deforms with the joint's object (Skinned meshes). Until 0.46 a document with skins had a
skindiagnostic and its meshes were drawn unskinned; the diagnostic is gone. - A scale channel is played as the file has it, whatever its sign: a negative component mirrors the node and a 0 collapses it, drawn as nothing (see
scaleunder Moving objects). A LINEAR channel from[1, 1, 1]to[-1, 1, 1]is[0, 1, 1]half way, and its end draws the node's mirror image, its children's with it, in every mode. Until 0.45 a key frame's 0 was raised to 1e-6 (scale-zero) and a channel with a negative scale was left out (scale-negative); neither diagnostic is given any more, andGLTF_TRACK_MIN_SCALEis deprecated and unused.
A hermite key can be written by hand too: { t, v, ease: "hermite", in, out }, the segment into the key glTF's cubic Hermite spline from the previous key's out tangent to this key's in tangent, in the value's units a second (a missing tangent is 0). It applies to interpolated properties alone (numbers, vectors, colours in linear RGB, quaternions: a hermite rotation's two keys must be [x, y, z, w]), and the tangents are read by a hermite segment alone.
A model's cameras
A scene built in Blender, with its camera and the camera's animation, plays through that camera: the cameras of a glTF model read as a tree (gltfTree, above) are listed by gltfCameras, and gltfCameraRig gives the rig that puts the scene's camera on a camera's node. The node's own animation and its parents' are tracks like any others (gltfTracks), so the camera flies as in Blender with no track of its own.
import { createScene, parseGltf, gltfTree, gltfTreeItems, gltfCameras, gltfCameraRig } from "mote-engine";
import { gltfTracks } from "mote-engine/director";
const doc = parseGltf(await (await fetch("/models/shot.glb")).arrayBuffer());
const tree = gltfTree(doc); // tree.nodes[n].camera: the camera a node carries
const { items, ids } = gltfTreeItems(tree, { id: "shot", motion: "none" });
const scene = createScene(canvas, { mode: "ray", stages: [{ items }] });
gltfCameras(doc, tree).cameras; // [{ index, name, type, yfov, fov, aspectRatio, znear, zfar, nodes }]
const { rig, camera, diagnostics } = gltfCameraRig(doc, tree, ids, { camera: "Camera" });
scene.setCameraRig(rig); // { kind: "attach", target: "shot/Camera", fov, distance }
const { timeline } = gltfTracks(doc, tree, ids, { loop: true });
await scene.setTimeline(timeline); // the camera moves with its node and its node's parents
In Blender, export with File › Export › glTF 2.0 as for any model (Models from Blender), and tick:
- Include › Data › Cameras, so the file has the cameras;
- Animation, so the camera object's keyframes (and its parents') are in the file. With Sampling Animations on (the default) every frame is a LINEAR key; off, Blender's Bézier curves are CUBICSPLINE keys. Both are played as the file has them.
Edit the scene in Blender, export again to the same file and load it again: the camera is found by its index or its name, whatever node the exporter puts it on.
- What is read. Every camera with its
index,nameandtype; a perspective camera'syfov(the vertical field of view, radians) andfov(the same in degrees),aspectRatio,znearandzfar; an orthographic one'sxmag,ymag,znearandzfar; andnodes, the nodes that carry it (their indices in the file; with thetree, the tree's nodes alone). - The view. A glTF camera looks along its node's −Z axis with the node's +Y up. The rig (
attach, see Camera rigs) reads those two axes and the node's origin from the matrix the scene composes for the node's object every frame: the model's root (yourtransform), its fit to the unit sphere, the node's parents and the node, with their scale left out of the view. The camera is therefore where the file puts it in the fitted model (the tests hold eye, direction and up within 1e-6 of a reference written from the glTF formulas, at rest and at 32 instants between an animation's key frames, LINEAR and CUBICSPLINE). Give the rootmotion: "none", or the model turns under its own camera. - The field of view is the camera's
yfov: a rig'sfovis vertical too. The canvas keeps its own aspect: with the aspect the file was made for (aspectRatio, Blender's render resolution) the picture is framed as in Blender; a wider canvas shows more at the sides, a narrower one less. - Several cameras.
{ camera }takes one by index or name (default the first). Switch with anothersetCameraRig: a cut, or{ ...rig, blend: 0.5 }for a move. When several nodes carry the same camera the first in the tree is taken and acamera-nodesdiagnostic says so;{ node }names another by its index in the file. - Not shown, and said (
diagnostics, each with acode, the camera's index and a message):- an orthographic camera is listed with its numbers and
camera-orthographic, andgltfCameraRigrefuses to make a rig for it: the scene's camera is a perspective one; - a field of view outside the rigs' 5 to 150 degrees is clamped to it, with
camera-fov(a very long lens: past about 230 mm on Blender's default sensor at 16:9); - a camera that no node carries has
camera-no-node.
- an orthographic camera is listed with its numbers and
- Read and not used.
znearandzfar(the scene has no clipping planes to set) andaspectRatio(the canvas has its own) are handed back and change nothing. An animation of the camera's own numbers (a zoom: Blender's focal length, which its exporter writes as aKHR_animation_pointerchannel onyfovwhen that option is on) is not played:gltfTrackssaysno-nodefor the channel. Animate the rig'sfovwith acameratrack instead (The scene timeline). - Untrusted input, as the parser: from the JSON alone, the list against its limit before a camera is read (256 cameras, 4096 nodes that carry one:
GLTF_CAMERA_LIMITS), then every field. Refused with anErrorthat names the camera and its node: a camera that is not an object, atypethat is neitherperspectivenororthographic, a camera without its type's object or with both, ayfovthat is not a finite number above 0 and below π, anaspectRatioor aznearnot above 0, azfarnot aboveznear, an orthographicxmagorymagof 0, and a node whosecamerais not the index of one.gltfTreerefuses the same for the cameras its nodes carry;loadGltfand the other flat loaders read no camera and load the file as before. A file without cameras is read exactly as before.
A model's lights
A glTF file's KHR_lights_punctual directional, point and spot lights can light the scene and follow their nodes. gltfLights lists what the file declares; gltfSceneLights turns each node that carries a light into a scene light attached to that node's object. The node's own animation and its parents', played by gltfTracks, move the light without a separate light track.
import { createScene, parseGltf, gltfTree, gltfTreeItems, gltfLights, gltfSceneLights } from "mote-engine";
import { gltfTracks } from "mote-engine/director";
const doc = parseGltf(await (await fetch("/models/shot.glb")).arrayBuffer());
const tree = gltfTree(doc);
const { items, ids } = gltfTreeItems(tree, { id: "shot", motion: "none" });
const { lights, diagnostics } = gltfSceneLights(doc, tree, ids);
const scene = createScene(canvas, { mode: "ray", stages: [{ items }], lights });
await scene.setTimeline(gltfTracks(doc, tree, ids, { loop: true }).timeline);
gltfLights(doc, tree).lights; // [{ index, name, type, color, intensity, range, nodes, ... }]
In Blender, use File › Export › glTF 2.0 and tick Include › Data › Punctual Lights. Choose Data › Lighting › Standard for the physical round trip below. Export Animation too when the light objects or their parents are animated. Editing and re-exporting the file and loading it again preserves the lights by their names and nodes.
- What is read. Every valid light's
index,name,type, linearcolor,intensityin the file's units, optionalrange, a spot'sinnerConeAngleandouterConeAngle, and thenodesthat carry it (withtree, only that tree's nodes). A carrying tree node haslight, its index in the extension's list. One definition carried by several nodes makes several scene lights, one at each node. A definition on no node is listed with alight-no-nodediagnostic and makes no scene light. A skipped light keeps its place in the file's numbering (index, a tree node'slight) but is not inlights, solightsis not indexed byindex: look a light up by itsindexfield, and expect the scene's lights (light:Nin operations) to count only the lights made. - Following the node. A glTF light shines along local −Z. Point and spot positions are the node's origin; a spot's direction is its −Z with scale removed. Mote's directional-light convention points towards the source, so its scene direction is the node's +Z with scale removed. The whole composed transform is followed: your model root, its fit, parents, motion, tweens and timeline tracks. If the attached object is missing, the light keeps its last valid pose. A collapsed Z axis freezes a directional or spot direction; a point light still follows a valid origin.
attachcan also be set on directional, point and spot lights supplied directly in code. It is not a Scene JSON field:describe()writes the light at its current pose and adds anomitteddiagnostic naming the light and itsattach. - Units. Standard glTF intensity is illuminance in lux for directional lights and luminous intensity in candela for point/spot lights. Using the 683 lm/W convention, Ray's directional irradiance is
lux / 683W/m² and its point/spot radiant intensity iscandela / 683W/sr. Blender Standard exports a sun ofEW/m² as683 Elux and a point or spot ofPW as683 P / (4π)cd. Those Ray values map back toEandP, measured against Blender's Cycles renderer within 0.05%. Blender's Unitless mode omits the 683 factor (point/spot still divide power by4π); Raw (Deprecated) writes the Blender strength without either conversion. Both are non-physical interchange choices: mote interprets the resulting numbers as glTF's standard lux/cd, so use Standard when the physical values matter. Blender exposure is multiplied into the exported intensity in every mode. - The model's fit. If
tree.fit.scaleiss, a file rangeRbecomes scene rangeR s; no file range means infinite range. Point/spot radiant intensity becomesI s², so irradiance is unchanged when every distance becomesd s:I s² / (d s)² = I / d². Directional irradiance does not scale.gltfSceneLightsapplies this compensation, including mote's scene-to-Ray conversion. UsegltfTree(doc, { normalize: false })to keep metres and the original radiant intensity. - Range. A finite range is a smooth window,
(1 - (d / range)²)², not Blender's hard cut-off at the custom distance. At half the range the factor is(3/4)² = 0.5625, so mote gives about 0.56× Cycles' light there; it reaches zero smoothly at the range. - Cones. A spot gets
angle = outerConeAngleandpenumbra = 1 - innerConeAngle / outerConeAngle; equal inner and outer angles mean penumbra 0. The full-light angle and cutoff are exact. Between them, mote's smoothstep interpolation in cosine approximates glTF's reference squared-cosine falloff; it is not claimed to be the same curve. - Shadows and visibility keep mote's defaults unless the helper's
{ castShadow, visible }overrides them. In Ray, direct lights cast shadows by default and point/spot lights have a visible emitting sphere by default. Outside Ray, cast shadows also need the scene'sshadowsoption and an explicitcastShadow: true; point lights do not cast CPU shadow maps. Punctual size, softness and visibility are not properties supplied by this glTF extension. - Not read. glTF has no area-light type in
KHR_lights_punctual, so Blender area lights are not exported as punctual lights and are not invented here.KHR_animation_pointerchanges to intensity, colour, range or cone angles are not played bygltfTracks; node translation, rotation and scale animation is played. The flatloadGltf/gltfSourceloaders still make geometry, not scene lights. - Untrusted input and leniency. The extension and node references are checked from JSON before buffers are allocated: at most 256 lights and 4096 light-carrying nodes (
GLTF_LIGHT_LIMITS), known types, structurally valid fields and valid node indices. Structural errors still refuse the file with an error naming the light or node. A light whose values are out of range—negative or non-finite colour or intensity, a non-positive or non-finite range, or cone angles outside0 ≤ inner ≤ outer ≤ π/2(a cone within float32 rounding of π/2, as Blender writes a 180° spot, is read as π/2)—is instead skipped with alight-invaliddiagnostic naming the light and its carrying node; the flat loaders never throw because of a light's values. A spot without aspotobject takes the specification defaults (inner 0, outer π/4) with alight-default-spotdiagnostic. A colour component above 1 is accepted as given. A file without the extension behaves exactly as before; unknown required extensions remain refused.
From Blender to mote and back
A Blender scene can keep its objects, parent hierarchy, camera, punctual lights and animation in one GLB, while a small Scene JSON document keeps only mote's own choices. The document names the file's content; it does not copy node transforms, camera poses or light directions. Editing and re-exporting the GLB therefore updates the next scene made from the same document.
In Blender, choose File › Export › glTF 2.0 and tick:
- Format: glTF Binary (.glb) and Transform › +Y Up;
- Mesh › Apply Modifiers, Include › Data › Cameras and Include › Data › Punctual Lights;
- Animation. Sampling every frame produces LINEAR keys; unsampled Blender Bézier curves become CUBICSPLINE keys. Both are played as exported;
- Data › Lighting › Standard when physical light values matter;
- Data › Compression: meshopt is decoded natively. Scene JSON uses the uncompressed fallback for optional Draco; compressed-only Draco requires
loadGltfwith an application-supplied decoder and a scene created in JavaScript. See External glTF decoders.
Declare the file's node tree as a stage group with gltfTree. A camera entry names a camera in that same file, a lights entry selects its punctual lights, and animation on the tree group selects a clip:
{
"version": 2,
"camera": { "gltf": "shot.glb", "camera": "Camera", "width": 960, "height": 540 },
"stages": [{
"items": [{
"id": "shot",
"gltfTree": "shot.glb",
"normalize": false,
"motion": "none",
"animation": { "clip": "Dolly", "loop": true }
}]
}],
"lights": [{ "gltf": "shot.glb", "lights": "all", "intensity": 1 }],
"render": { "mode": "ray", "quality": "low" },
"clock": { "time": 0, "step": 0.016666666666666666 },
"autoplay": false
}
Load it with createSceneFromJson(canvas, document, { resolveUrl }). Parsing validates the document and fetches nothing. Creating the scene reads each file once, makes the tree with gltfTreeItems, the camera's attach rig with gltfCameraRig, attached lights with gltfSceneLights, and the clip's timeline with gltfTracks. sceneFromJson alone is only the synchronous parser: it accepts these declarations but returns no generated tree objects, file camera rig, file lights or file-animation timeline for them; use createSceneFromJson to resolve them.
gltfTreeis the file's whole node tree under the group.transform,parentandmotionon that root remain mote's own.normalizedefaults totrue(the whole model fitted to the unit sphere);falsekeeps the file's coordinates and lengths. One document has one tree group per file, which is how its camera and lights find their attach targets.- The camera is
{ gltf, camera, node?, fov?, width, height, distance?, roll?, up?, handheld?, blend? }.camerais the file camera's index or name;nodeselects a carrying node when there are several. The file supplies its vertical field of view unlessfovoverrides it (5–150°). - The lights entry is
{ gltf, lights, intensity? }:"all", or a nonempty list of light indices in the file'sKHR_lights_punctuallist or names (not positions in the valid-light list after invalid lights are skipped).intensityis a multiplier. Several entries may select different lights of one file and keep their individual origins; selecting the same light twice, including by two"all"entries, is refused at the second entry. Ordinary mote lights can appear beside them. - The animation is
{ clip, loop? }on the tree group, the clip's index or name. One document plays one file animation, and does not also have an explicittimeline. - Mote-only data stays in the document: render settings, root placement, effects, physics, ordinary objects and lights, and the stepped clock used by
recordVideo. There is no need to copy the file's poses into JSON.
After editing Blender, export over the same GLB and create the scene again with the unchanged document. describe() writes these declarations back as file references—the gltfTree group, camera name, light selections and clip—not as expanded nodes, poses or generated tracks. A describe → load → describe round trip is identical. If the timeline is replaced after loading, describe() writes the explicit timeline and omits the stale tree animation; post-load node changes, removals and additions are reported by tree-item diagnostics with complete: false.
Scene operations and the log
scene.applyOps(batch) applies a batch of scene operations (SceneOp[], one operation, or their JSON text; schemas/scene-ops.schema.json), the director's way of driving a scene with data: it is validated whole against what the scene has now (validateSceneOps, loaded with the director's module on the first call, scene.ready covering the load) and refused whole with JSON-pointer diagnostics ({ ok: false, errors }, nothing applied), else queued and applied in order at the next frame boundary, before the step that frame consumes.
const result = await scene.applyOps([
{ op: "add", item: { id: "crate", shape: "box", transform: { position: [1, 1, 1], scale: 0.2 }, material: { preset: "gold" } } },
{ op: "effect", action: "add", name: "fog", id: "mist", params: { density: 0.4 } },
{ op: "camera", rig: { kind: "orbit", center: [0, 0, 0], distance: 3, yaw: 10, pitch: 5, fov: 40 } },
{ op: "animate", target: "item:crate", property: "position", to: [-1, 0, 0], seconds: 1.5, ease: "inOut" },
{ op: "step", frames: 90 }, // a stepped clock: the frames consumed before the next operation
{ op: "set", target: "effect:mist", property: "density", value: 0.8 },
]);
// { ok: true, applied: 6, frame: 90, ids: { 0: "crate", 1: "mist" } }
An add's object is a Scene JSON v2 object, so it can have a parent, be a group (no shape) or be one node of a glTF file (A hierarchy in Scene JSON):
await scene.applyOps([
{ op: "add", item: { id: "pivot", transform: { position: [0, 0.5, 0] } } }, // a group
{ op: "add", item: { id: "blade", parent: "pivot", shape: "box", transform: { scale: [0.8, 0.05, 0.1] } } },
{ op: "animate", target: "item:pivot", property: "rotation", to: [0, 0, 180], seconds: 2 }, // the blade goes round with it
]);
The parent must be there when the operation is applied, in the stage the object is added to (the one shown, or the one a transition is going to). Validation refuses, with the pointer /ops/<i>/item/parent, a parent the scene does not have (one added earlier in the same batch counts, one removed earlier does not) and an object that is its own parent. A parent that the scene has in another stage passes validation and fails when the operation is applied (the parent "x" of "y" is not an object of its stage): the operations before it stay and the rest are not applied. A stages operation's hierarchies are checked whole, as a document's.
add spawns an object (a model named by URL is fetched by the runtime and recorded with its SHA-256, a .gltf's separate buffers each fetched and recorded too, under the model's path, a hash and the URI as written; the batch waits for its bytes, so a step after it steps with the object in), remove takes one out, set writes one property at once (an object's position, rotation, scale, visible, material, motion, weights; a light's field; a camera parameter, fov, roll, rig.yaw... written into the rig's block as a track writes it; the scene's exposure or zoom; an effect's parameter through its one-off set), animate moves one over seconds on the timeline's own evaluator (the same eases; inOut unless given; a step kind such as visible is written when the seconds are up; a set on the same property ends it, as a track does), camera replaces the rig (cut for a cut), light and lights change or replace the lights, effect adds one (its id as given, else fx:<n>), sets, triggers or removes one, stage and stages move between or replace the stages, physics pushes a body, timeline installs or drives the timeline, render changes the mode, Ray's settings or the Wireframe style, step consumes frames (1 to 600 a batch in all; a stepped clock only). system operations are the engine's own and refused from callers. A batch holds at most 256 operations, 64 of them add.
An object's weights (one number a morph target, as many as its mesh has, ItemHandle.weights) is written by set and animated by animate one component at a time, nothing allocated a frame:
await scene.applyOps([
{ op: "set", target: "item:face", property: "weights", value: [1, 0, 0.3] },
{ op: "animate", target: "item:face", property: "weights", to: [0, 1, 0], seconds: 2, ease: "inOut" },
]);
Validation checks every list's shape (1 to 64 finite numbers) and checks its count whenever the object's mesh is known. This includes an object already in the scene and a primitive added earlier in the batch: a primitive has no morph targets, so neither add with its own weights nor a later set/animate weights is accepted. These validation failures refuse the whole batch with JSON-pointer diagnostics and apply nothing.
- A
removefollowed by anaddof the same id uses the replacement's count, never the removed object's. - If a model added earlier in the batch reveals its target count only while operations are being applied, a wrong-length
setoranimateis instead that operation's runtime error: it writes no weights, operations before it stay, and the rest are not applied. - A model's own
weightsin itsaddare not checked against its count: the object draws them as it would the same list given toItemHandle.weights.
Five operations put objects where they belong from their world bounding boxes: each object's real box, its mesh's vertices through its transform, with every object under it in its hierarchy (a group's box is its children's). Y is up; a scene unit is a metre.
const { placed } = await scene.applyOps([
{ op: "placeOn", id: "table" }, // on the floor, where it stands in plan
{ op: "placeOn", id: "vase", on: "table", at: [0.3, -0.1], gap: 0 }, // on top of the table, its centre at world x 0.3, z -0.1
{ op: "placeRelative", id: "chair", to: "table", side: "front", distance: 0.2 }, // 20 cm in front of it, centred on it
{ op: "align", ids: ["lamp", "shelf"], axis: "z", edge: "min", to: -2 }, // their backs against z = -2
{ op: "distribute", ids: ["a", "b", "c", "d"], axis: "x" }, // equal gaps between the first and the last
{ op: "resolveOverlaps", ids: ["chair", "stool"], fixed: ["table"], gap: 0.05 }, // out of each other's way, 5 cm apart
]);
// placed[0]: [{ id: "table", position: [0, 0.37, 0], box: { min, max }, moved: [0, -0.13, 0] }]
| Operation | What it does |
|---|---|
placeOn |
Rests id on the floor, or on top of on: its lowest point ends gap (default 0) above the support's highest, and never below it, so it does not reach into it. Without on the level is the floor's y where the scene gives one, else the physics floor, else 0, and the object keeps its place in plan. With on it is centred over that object. at: [x, z] is the world place of its centre in plan instead. |
placeRelative |
Puts id on a side of to: "right" (+X), "left" (−X), "above" (+Y), "below" (−Y), "front" (+Z, towards the viewer) or "behind" (−Z), with distance (default 0) between their facing faces. Above or below, it is centred on to in plan. Beside it, it is centred along the other horizontal axis and keeps its height: what stands on the floor stays on it. |
align |
Moves each of ids along axis ("x", "y", "z") so that its box's edge ("min", "center", "max"; default "center") is at to: a world coordinate, another object's same edge (its id) or, left out, the first listed object's, which stays. |
distribute |
Spaces ids evenly along axis, in the order they stand in along it: equal gaps between their boxes (spacing: "gaps", default) or equal steps between their centres ("centers"). Without gap the first and the last stay and the others are spread between them (three objects at least; an error when they do not fit). With gap the first stays and each next one follows at that distance. |
resolveOverlaps |
Moves objects apart until no two of their boxes overlap, gap apart at least. ids are taken in order of rank (default: the shown stage's visible objects without a parent): each gives way to those before it and to fixed, which never move, and goes to the nearest place clear of them, pushed in plan (axes: "xz", default) or along any axis ("xyz"). Two objects that do not move and overlap each other (two of fixed) cannot be put right: the operation is then a runtime error that names the pairs, and nothing is moved. |
Each one answers where it left its objects, in placed (type PlacedObject) under its index in the batch: the object's own position (in its parent's space when it has a parent: the world move goes through the parent's transform), its world box after the move as the scene measures it, and the world translation moved.
A parent and its child can be in one operation. Each object is then measured without the others the operation moves under it (a table and the cup on it are two boxes), its world target is worked out first, and the moves are applied from parents to children: a child is carried by its parent's move, and its own transform takes only the rest. So each ends where the operation says: two of them aligned on a centre both end centred there. Its box in placed is measured the same way, and moved is its whole world move, its parent's included. A reference (on, to, an object of fixed) must not hang under an object the same operation moves, since it would move with it: that is refused with a JSON pointer where the hierarchy is known when the batch is validated, and is the operation's runtime error otherwise.
Two boxes overlap when they share a volume: more than a nanometre on every axis. Boxes that touch do not, so an object resting on another is left alone. The boxes are axis-aligned in the world: a chair pushed under a table overlaps it, and a turned object's box is larger than the object.
Validation refuses, with a JSON pointer, an id the scene does not have (one added earlier in the batch counts), an object placed on or relative to itself, an id listed twice, more than 256 ids, an align of one object without a to, a distribute of two without a gap, and a reference under an object the operation moves. An object with nothing to measure (a group whose children draw nothing, a model still loading) is the operation's runtime error. The operations are logged and replayed as the others are.
The promise resolves after the frame that applied the last operation:
{ ok: true, applied, frame, ids }(the ids theaddandeffect addoperations got, by operation index), withplacedwhen the batch held a spatial operation;- or
{ ok: false, applied, failed, error }when a setter threw on what validation could not know (a model that fails to load, an object without a body): the operations before it stay, there is no rollback, the rest are not applied.
It rejects with { kind, message }: "load", "destroyed", "paused" (the scene draws no frame: resume it). A TypeError, synchronous, for an argument that is neither an object, an array nor a string.
A timeline cue's operations go through the same runtime, queued behind the batches queued: with none ahead they run right after the sample that crossed the cue; while a batch is still waiting (on a step, a model) they wait for it, as a batch queued then would. In cue order, once per crossing, one operation after the other (a cue's own models fetched in sequence), never from inside a paint, a physics step, an effect hook or another cue (a cue may not step, replace the timeline or the stages).
An effect declared in a stages operation's stage runs in that stage alone.
scene.log() is the scene's operations log: every batch that applied and every system operation the engine applied on a stepped scene (a layout, the DOM colliders measured), each at the frame it applied to, oldest first by the time it was recorded (a batch that waited, for a step or a model, as one entry per stretch, the entries sharing its batch number, each with the frame it applied at and the frame its last operation settled at, until; a batch's entries are recorded when its stretches settle, so they may follow system operations of frames they span). It returns a page of copies, at most 1024 entries (limit), from the entry after after (an entry's seq), with next to page on, the totals (ops, bytes: UTF-8, as the validator counts), firstFrame, the scene's frame and clock, and assets (the models and maps fetched by URL, with their digests). The log keeps at most 65 536 operations or 64 MiB of JSON: past either cap the oldest entries go (dropped) and complete reads false; scene.log({ clear: true }) empties it (clearedAt), with the same effect; so does a pause or a destroy that interrupts an operation a batch was waiting for whose effect may still land (interruptedAt: a timeline installed, stages replaced, a map fetched; a step interrupted is recorded with the frames it consumed, and leaves the log complete under a pause or a destroy, interrupted under a timeout; an add interrupted is undone). Under a real clock the log is a record; under the stepped clock a complete log replays the scene:
import { replayLog } from "mote-engine/director";
const log = sceneA.log(); // complete: true
const result = await replayLog(sceneB, log); // sceneB: the same document, a stepped clock
// { ok: true, entries, frame, partial: false }: sceneB's CPU state is sceneA's, frame for frame
replayLog takes the entries in frame order, puts each batch's stretches back together (the frames the page stepped through while the batch waited become steps of the batch's own, so what waited behind it waits the same), applies each batch at its frame and each system operation at its frame as the engine applied it (the layout as recorded, its size and pixel ratio instead of the canvas's measure; the DOM colliders' boxes as recorded, placed instead of the page's elements), and steps on to the log's frame after the last entry; it refuses an incomplete log ({ ok: false, kind: "incomplete" }) unless given { partial: true } (the result then says partial), a scene whose clock is not stepped ("clock"), an entry behind the scene's frame ("order"), a batch the scene refuses ("ops"), and a model or buffer whose digest differs from the log's ("asset-mismatch", with the path and the two digests).
Orthographic views of a scene
A scene's frames are perspective pictures. For measuring where things are, mote-engine/director has orthographic views: a projection with no perspective, in which a world point's place does not depend on its depth and a length is read with one number, and a small rasterizer that draws a scene's triangles through it.
import { createOrthoPicture, drawOrthoMesh, orthographicView, projectOrthographic } from "mote-engine/director";
// The plan of a 6 × 3 × 5 m room, in a picture of 800 × 600.
const view = orthographicView("top", [-3, 0, -2.5], [3, 3, 2.5], 800, 600);
view.scale; // pixels a metre
projectOrthographic(view, 1, 0, 2); // [x, y, depth]: the pixel of the world point (1, 0, 2), and its height towards the viewer
const picture = createOrthoPicture(800, 600, [24, 27, 33, 255]);
scene.geometry((object) => {
drawOrthoMesh(picture, view, { ...object, cull: true }); // picture.data: RGBA, row 0 at the top
});
orthographicView(kind, min, max, width, height, { margin?, scale? })frames the world boxmin..max, centred, withmarginof the picture left free on each side (default 0.08), or atscalepixels a unit.kindis"top"(seen from above: +X right, +Z down),"front"(seen from +Z: +X right, +Y up) or"side"(seen from +X: −Z right, +Y up);ORTHOGRAPHIC_AXEShas their axes.projectOrthographic(view, x, y, z, out?)gives a point's pixel and its depth towards the viewer in world units;unprojectOrthographic(view, px, py, depth?, out?)goes back.scene.geometry(visit)hands the visitor each drawn object of the stage shown, in the stage's order: itsid, its mesh'spositionsandindicesas they stand (deformed by its skin and its morph targets as the frame draws it), the 3 × 4matrixthat places it in the world, each triangle's material index (triMaterial) with the materials' basecolorsanddoubleSidedflags, and the object's owncolorandtwoSided. Hidden and collapsed objects, groups and objects without an indexed mesh are left out. Everything handed over is borrowed untilvisitreturns: the record is one object, rewritten for the next object, itsmatrixwith it, andpositions,indicesandtriMaterialare the object's own buffers, which a later frame may deform or replace. Copy what you keep, and write into none of it. A visitor may callscene.geometry()again: the nested call hands its own record (one a nesting depth, at most 16), so the outer visitor's record stays as it was until it returns. It is a query, not a call for every frame: it composes the hierarchies for the scene's time, makes an object's colour lists on its first call (and again when its material is replaced), and makes a rotation each call for an object with a motion; a second call for objects without a motion allocates nothing of its own.drawOrthoMesh(picture, view, mesh, maxDepth?)fills each triangle with its base colour under one fixed light and keeps the nearest surface. A pixel is filled when its centre is inside the triangle.cull: trueleaves out the triangles seen from behind, as Ray does, unless their material isdoubleSided;maxDepthcuts away what is nearer to the viewer than that many units past the view's centre, for a section.
The drawing has no materials' maps, lights, shadows or effects.
Measuring the scene
Three reads answer where things are in the picture the scene draws now, with no physics world:
scene.project(point): a world point on the canvas, in CSS pixels ({ x, y, depth }), ornullwhen it is behind the eye.scene.bounds(id, out?): an object's world boundingsphere(center,radius) andbox(min,max), as its mesh stands (deformed by a skin or morph targets), and itsscreenbox on the canvas (x,y,width,height, clipped to it, andvisible);undefinedfor an id the stage shown does not draw. Pass aSceneBoundsrecord of your own asoutto have it filled and returned instead of a new one: its vectors are reused too, so an observer that measures every frame allocates nothing. The answer is that same record, so copy what you keep before the next call with it.scene.pick(x, y, budget?): the visible object under a canvas pixel ({ id, point, normal?, coarse }), ornull. Bounding spheres are tested first, then at mostbudgettriangles;coarse: truemeans the answer comes from the nearest bounding sphere, not from a triangle (then there is nonormal).
const outline: SceneBounds = { sphere: { center: [0, 0, 0], radius: 0 }, box: { min: [0, 0, 0], max: [0, 0, 0] }, screen: { x: 0, y: 0, width: 0, height: 0, visible: false } };
function everyFrame() {
const b = scene.bounds("chair", outline); // filled in place: no allocation
if (b?.screen.visible) drawBox(b.screen);
requestAnimationFrame(everyFrame);
}
requestAnimationFrame(everyFrame);
Effects
Effects load into a scene and combine freely: they push the objects' particles (and, with physics, the bodies), change the glyphs drawn, draw glyphs of their own, shake the picture or react to clicks. In ray they are drawn in the same 3D frame as the solids.
import { createScene, fire, smoke, heatHaze, explode, holes, rain, lightning } from "mote-engine";
const scene = createScene(canvas, {
stages: [model, { items: [...], effects: [rain(), lightning()] }], // effects of one stage
effects: [fire({ intensity: 0.8 }), smoke(), heatHaze()], // effects of every stage
click: explode(), // what a click does
});
const wind = scene.addEffect(EFFECTS.wind({ strength: 0.6 }));
wind.set({ angle: 30 }); // change it while it runs
wind.remove();
scene.click = [ "ripple", holes({ heal: 8 }) ];
| Kind | Effects |
|---|---|
| Forces on the objects | wind, vortex, magnet (the pointer pushes or gathers), explode (debris, then it flies back together), holes (a click destroys a piece, the edge burns, it heals), shockwave, gravity (crumbles from below and piles up like sand, at the angle of repose), jelly, blackHole (opens beside the objects, bends them and swallows them slowly, then lets them go) |
| Glyph changes | rainbow (style: spectrum a hue wheel, film the thin-film interference of a soap bubble, oil of an oil slick), glitch, shake, scanlines, dissolve (burns away like paper, or falls to dust, and back), hologram, matrix, neon, heatHaze, laser, halo (light around the objects' outline, with turning rays; the outline lit too) |
| Glyphs and forces | tornado: a funnel from the ground (in ray, its floor line) up into the sky (or to the clouds' underside, fading into it), narrow at its foot and wrapped in a debris cloud that trails behind it, turning, snaking (bend) and wandering (wander); its wind is a Rankine vortex with inflow at the ground and an updraft in the core, carrying dust up the funnel, flinging heavier debris out and tearing the objects apart where it is faster than they hold (pull) |
| All three | disintegrate: the objects dissolve from one end into a stream of dust and crystal shards that flows away and settles on the ground; with metal, steel faces with a moving sheen |
| Glyphs of their own | fire, smoke, rain (splashes on the objects), snow (piles up on them), sparks (style: classic, grinder a jet of streaks bursting into stars, welding a flickering arc, curling spatter and glowing drops; from the edges, the pointer, a point or a contact point running along the objects), fireworks, starfield (with warp), bubbles, water (with the objects' reflection), lightning (strikes the objects, flashes; in ray the flash is a light of the scene, from the channel and casting shadows, the clouds lit as a sky all around, the objects keeping their colours; in ray with WebGPU the strike stands in the scene's world, on an upright plane through the point it struck: seen from any camera, hidden by the objects in front of it, inside the clouds, the fog and the smoke, its flash a point light on the channel that lights those media from within; in every mode a fractal bolt (in ascii, characters along its segments): a branching leader, the return stroke, restrikes, with branchiness, restrikes, slowmo and kind: cloud-to-ground, cloud-to-cloud, forked), confetti (paper pieces tumbling and gliding, from the sky or cannons, in mixed shapes and rainbow, party, pastel, gold or custom colours, lying where they land), aurora, fog, clouds (style: overcast, cumulus or layers; with rain and lightning a storm: the rain falls from their underside, the bolts strike from there and light them up), nebula (glowing gas in filaments crossed by dark dust lanes; with volume, a participating medium in a world box in Ray), meteors, drip, orbit (hidden behind the objects) |
In Wireframe water uses full-resolution scene pixels for its reflections and submerged refraction on both GPU and Canvas, without ASCII-cell sampling or a blur pass.
- The GPU path uses a dedicated continuous water shader with projected height-field swells with crest occlusion, finer wave bands, angle-dependent reflection, depth absorption and normal-dependent highlights.
- Canvas uses a pixel-based approximation with a continuous normal field.
- Neither path draws regular wave strokes or reflects the ASCII cell grid.
In ray mode the water is ray traced: a plane at the level with the same wave field and the same layers (the body, the sky and the objects reflected, glints), its reflections traced through the scene (an object above the water shows its underside in it) and its refraction meeting the submerged parts of the objects, absorbed by the water's colour; where nothing is under it the page shows through. It is traced at ray mode's internal resolution, within its frame budget. A level at or above the eye (the upper half of the canvas with a level camera) is drawn as in Wireframe.
ASCII uses the same wave phase and optical boundary, refracting submerged surface glyphs.
level, waves (0–3), speed (0–4), scale (.25–3), opacity (0–1), reflection, reflectivity (0–1), distortion (0–3) and glints (0–3) remain live. speed: 0 freezes the wave phase. ior (1–2.5, default 1.333) sets the optical index; 1 removes optical bending. Controls and wave clocks survive renderer/mode changes.
Lasers share the animated boundary and use Snell transmission plus dielectric Fresnel reflection, including total internal reflection, in graphical modes and ASCII. Their display tone mapping keeps the weaker reflected branch visible; traced branch powers sum to one. The laser overlay follows the water composite so its already split rays are not reflected a second time.
Laser contact adds interpolated linear surface light in graphical modes (including the optional code scanner), preserving each particle’s material and opacity instead of recolouring whole ASCII cells. The code scanner uses a segmented graphical core in graphical modes; literal scanner characters are confined to ASCII mode.
matrix draws distinct columns of crisp code in graphical modes and ASCII, with white-green leading characters and fading green tails. size (.5–6, default 1.7) scales the rain characters and their spacing independently of the scene font. density (0–3) immediately changes the active columns; speed (0–4) freezes all movement and flicker at 0. trail (0–3) changes tail length without moving the heads, mutation (0–4) controls symbol changes, and head (0–2) controls the white highlight. charset selects kana, binary or latin. color preserves saturated code colours, intensity (0–3) controls overall visibility, and surface (0–1) blends code into the objects (0 preserves their material). rain: false hides the background streams; intensity: 0 leaves everything untouched. Timing is independent of render FPS.
glitch applies short bursts of coherent horizontal tears, red/cyan channel fringes and local block corruption to the objects. Quiet intervals leave the surface clean; the effect does not shake the whole scene. Graphical modes and ASCII share burst timing, offsets and corruption. intensity (0–3) controls the overall strength, rate (0–5) controls new bursts, and speed (0–4) controls time (0 freezes the current failure). tear (0–2), rgb (0–2), blocks (0–1) and noise (0–1) independently control displacement, colour separation, packet-like dropout and corrupt characters. All controls update existing bursts; intensity: 0 leaves the surface untouched, while rate: 0 lets existing bursts finish and then stays clean. Burst scheduling uses a fixed time step, independent of rendered FPS. The shared GlitchModel used by other modules is unchanged.
drip gathers small beads under the objects' silhouettes, pinches them off, accelerates them under gravity and splashes on lower surfaces or the bottom of the canvas. Ray and Wireframe use translucent, non-emissive water with fine highlights; ASCII uses growing beads, falling marks and spreading splash glyphs from the same simulation. rate (0–5) controls arrivals, speed (0–3) controls the whole simulation (0 freezes it), size (0.25–8) scales water in every mode, and gravity (0–3) controls downward acceleration. opacity (0–1, default 0.7), splash (0–2), trail (0–2, the velocity-dependent stretch), wind (-2–2) and color (default neutral #bed1dc) update live. rate: 0 stops new beads while existing water finishes. Surface collision is a swept screen-space approximation; drops do not simulate fluid refraction or wet the underlying material. Emission and motion are independent of rendered FPS and backend.
meteors draws fast, straight streaks with a compact white-hot core, a cooling train that remains after the head has passed, and occasional daughter fragments. Graphical modes and ASCII share the same flight simulation; trails are deposited by distance rather than by rendered frame. rate (0–4) controls new arrivals, speed (0–4) controls the whole simulation (0 pauses flight and fading), and size (0.25–10) scales heads and train width, including multi-cell heads in ASCII. trail (0–3) controls train lifetime (0 hides it), intensity (0–3) controls brightness, and fragmentation (0–1) controls splitting. angle is in screen degrees (0 right, 90 down, 180 left); it and spread (0–90°) affect new arrivals without bending existing flights. Choose palette: "natural" | "ice" | "ember" | "custom", with color used by the custom palette. light (0–2, default 0) optionally lights nearby scene surfaces. Setting rate: 0 stops new meteors while existing heads and trains finish. These are bounded visual approximations, not a physical atmosphere simulation.
EFFECTS maps every name to its function, for menus, and EFFECT_PARAMS describes every effect's settings (a number with its range and step, an on/off, a choice, a colour, each with its default), so a settings panel can be built from it; effectDefaults(name) gives the defaults as an object. Sizes are in scene units, so an effect looks the same at any canvas size; effects with emitters can start from the objects' outline (source: "objects"), the ground or the pointer.
starfield uses compact warm-white and blue-white stars with a range of magnitudes and perspective speeds. size, brightness, twinkle and color work live in graphical modes and ASCII. warp stretches stars radially by their projected velocity; speed: 0 freezes both movement and scintillation. Changing the count or renderer keeps the existing stars in place.
Custom effects use frame(f), mesh.prepare(state, frame), mesh.vertex(vertex, frame), mesh.surface(writer, frame) and mesh.dispose(objectId). Vertex positions are local; frames provide local/world matrices and picked world anchors. Surface programs are bounded, atomic transactions managed by the scene. A nonfinite vertex update preserves the last coherent geometry and quarantines that installation.
glyphdecorates ASCII text.draw,offsetandtriggerprovide independent emitters, presentation and input.f.modereports the actual mode.f.worldAt,f.projectWorldandf.unprojectWorldconvert triggers and emitter positions without attaching them to camera pixels.f.surfaceTopandf.surfaceBottomquery the current covered mesh.- Material particles set
lit: true; Ray lights them with its scene lights. f.skyshares environmental information between effects.
GlyphParticles, noise2, fbm, hsl and gradient remain available for standalone effects. Glitch, scanlines and heat haze are intentional final-image effects in graphical modes; their decoration never changes traced geometry or shadows.
In graphical modes and ASCII, aurora({ bands: 4, light: 1 }) draws overlapping, folded curtains with fine striations: green bodies, pink lower fringes, violet regions and diffuse red upper emission. These colours vary coherently along the moving folds.
colorMix(0 to 1, default 1; "colours" in the demo) blends from green-only to the full palette, affecting both the sky and its reflected illumination without restarting the animation.bandssets the number of curtains (1 to 6).lightcontrols the aurora's illumination of the scene's actual materials (0 disables it).intensitychanges both the visible emission and the lighting, andspeed: 0freezes both.
ASCII samples the same optical field as one coloured density glyph per cell; switching modes preserves both animation clocks. The demo's Aurora preset shows it over the skyline with stars.
The aurora's internal rays have a faster clock than the large curtain folds: fine filaments drift sideways while packets of light rise and fade along them. raySpeed (default 1, range 0 to 3) controls this motion relative to the curtains; 0 stops the internal flow. Changing it preserves the animation phase. The aurora's illumination follows the moving emission too.
heatHaze bends the objects' contours with clear, rising pockets of turbulence in graphical modes and ASCII, on both renderers. amplitude controls displacement (0 disables it), from sets the top of the heated band as a viewport fraction (1 disables it), speed controls its evolution (0 freezes it), and scale controls pocket size. The field uses viewport units rather than cell indices, so the font size does not change its strength; live controls and mode changes preserve its phase. In ASCII it displaces the scene's glyphs; in Ray and Wireframe it bends the finished picture on the canvas, the other effects' marks included (a final-image effect, as above), rather than refracting a background image.
laser defaults to a physical scan sheet: a thin continuous pale core, a narrow coloured halo and stronger scattering where it crosses the objects. style: "code" uses a segmented core in graphical modes and code-scanner characters in ASCII. color, width, intensity, angle (degrees from vertical) and light (local reflected illumination; 0 disables it) update live in graphical modes and ASCII, on GPU and Canvas. speed: 0 freezes the current scan position and its scattering; changing controls or modes preserves the phase. The beam's thickness follows viewport scale, independently of camera aperture; ASCII represents its core and halo with oriented line characters and shaded neighbouring cells.
disintegrate advances a ragged, chipped fracture front through the actual surface. Each removed point can transfer material once into fine drifting dust or tumbling shards; the intact shape does not keep emitting duplicate silhouettes. Both modes and renderers share the same debris and floor deposits. amount selects the initial removed fraction (0 restores the whole object and clears debris; 1 removes every surface point); erosion adds removal per simulation second (default 0; keep it and breathe at 0 for a static front). Changing amount restarts that progression. The effect does not automatically rebuild consumed material. cut controls the dissolving side, independently of the stream's angle; ragged controls fracture detail and breathe modulates the front. speed: 0 freezes erosion, debris, facet reflections, steel sheen and settling. size, turbulence, gravity, opacity, dust, shards and rate control the debris; ground shows accumulated grains, metal adds the optional steel finish, and the halo control keeps unrelated surface glow subdued. Dust follows a smooth rotating air flow while heavier shards retain inertia and fall. Grain sizes and floor deposits use viewport units, independently of the ASCII font; particle pools and emission are capped.
orbit draws satellites on several inclined elliptical planes, with perspective, compact luminous heads and continuous tapered wakes. The near half passes in front of objects and the far half behind them; ASCII hides rear marks in occupied cells and reconstructs the same planes with bright heads and fading trail characters. bands (1–5), eccentricity, tilt, screen rotation and precession control the geometry. Satellites accelerate near their closest approach and the inner bands travel faster. speed integrates motion without phase jumps: 0 freezes heads, tails and precession, and negative values reverse travel. trail, size (0.25–10), intensity, color, radius and count work live in graphical modes and ASCII on both renderers. Existing satellite identities survive count changes and form the shared subset on mode/renderer changes. Head size follows viewport scale independently of aperture. ASCII reconstructs large bright bodies and wide trails across multiple character cells, rather than retaining a single glyph with a faint halo. Trail sampling and satellite counts are bounded.
bubbles draws translucent soap films with thin rims, white reflections and slowly changing iridescent grazing colours. Larger bubbles rise faster, sway and deform gently, then rupture into a brief perimeter spray. Graphical modes and ASCII share their live particles and animation phase: ASCII draws large hollow contours with coloured reflections and small bubbles as compact glyphs. size, rise, wobble, opacity, iridescence and color update live in both modes; speed: 0 freezes emission, motion and film evolution. rate controls new emission, and source selects the ground, objects or pointer (no emission outside the canvas). wind and windAngle steer the air independently of buoyancy: 0° right, 90° down, 180° left, 270° up. Scene lights tint reflections; camera aperture does not blur or enlarge the films. Pools, reflection detail and simulation steps are bounded.
smoke transports density through a persistent 2D fluid velocity field, with buoyancy, pressure projection and vorticity confinement producing rolling folds and fine wisps. Detail enters at the source and travels with the material; there is no independently animated density mask. Ray and Wireframe reconstruct its optical depth with overlapping soft kernels; ASCII shades the same evolving field and leaves the surface behind it visible. Projected optical self-shadowing darkens the inner rolls while thinner illuminated regions approach white. Its dominant shading direction follows the scene's light; scene and effect lights tint the smoke locally. opacity (0 to 1, default 0.85) controls transparency independently of density, colour and self-shadowing, so thin wisps transmit the background without black fringes. source selects object edges, the ground or the pointer (emission pauses outside the canvas); volume: { min: [x, y, z], max: [x, y, z] } instead anchors the plume to a world-space box in scene units, overriding source. In Ray the whole plume is bounded by that box, rising from its bottom centre and fading at its top; the CPU fallback projects that bottom centre as its nozzle. Change the box with set({ volume }), or pass null to return to source. density and color update the existing smoke immediately. wind controls strength and windAngle its screen direction: 0° right, 90° down, 180° left, 270° up; negative strength reverses it. rise controls buoyancy independently. turbulence changes rotational flow and scale changes the source width, affecting subsequent evolution rather than reshaping frozen material. speed: 0 freezes motion and emission. Every mode and renderer preserves the fluid field on switching. Font size and camera aperture do not enlarge the smoke. A short initial plume avoids an empty start, and simulation, field resolution and light sampling are bounded.
angle ("tilt" in the demo) inclines the aurora clockwise in screen space, from -180° to 180° (default 0°), about the middle of the sky. rotation turns transparent curtain planes around their vertical axis with perspective projection. The curtains sit at different depths, so turning them produces foreshortening and parallax; their light sources also move in depth. A full turn restores the same view. Both controls preserve the animation phase in either mode.
waveSpeed ("wave speed", 0 to 3, default 1) controls how quickly the large curtain folds evolve, independently of raySpeed. Set it to 0 to keep the curtain shapes still while their rays flow; master speed: 0 freezes both. Bright filaments and overlapping curtains develop restrained pale cores while their outer regions retain pink, green and violet.
fog({ density: 0.6, height: 0.55, turbulence: 1 }) forms low, rolling banks with curling wisps and a clear upper sky. Ray and Wireframe reconstruct a continuous optical field at three depths, so near vapour veils objects while far banks pass behind them. ASCII samples the same field into shaded density characters and attenuates the original surface glyphs under foreground fog. height (0.1 to 1), turbulence (0 to 2), density, speed and color work live in every mode. speed: 0 holds the field still unless another effect supplies wind; changing speed or render mode preserves its phase. layer: "under" keeps all fog behind the objects. The Fog demo preset shows it around the skyline.
In Ray, volume makes it a real participating medium in a world box (scene units, axis-aligned). This is ground fog:
fog({
volume: { min: [-4, 0, -3], max: [4, 0.8, 3] },
density: 0.6, height: 0.55, speed: 0.12, turbulence: 1, color: "#c4cdd3",
})
It is:
- densest on the box's floor, thinning with height (
height: the fraction of the box the bank reaches); - lit by the scene's lights and sun through the engine's volume lighting (with sun shadows and shafts;
ray: { shadows: false }turns them off); - occluded by and occluding the objects;
- drifting slowly at
speedscene units a second (plus the sky's wind whilespeedis above 0;speed: 0holds it still).
Objects inside it are veiled, the camera can walk into it, and nothing outside the box is fogged; its sides fade over 8% of the box's smaller horizontal side. At the floor the extinction is density × 2 per scene unit. set({ volume }) moves it to a new box, set({ volume: null }) returns to the 2D fog.
Without volume, Ray keeps the 2D fog: an effect cannot know the scene's world extent or its units (normalized objects or metres), so a guessed box would be wrong in one of them and would change every existing Ray scene.
Like the built-in smoke and clouds, it is admitted at fixed tiers through high; a fixed quality: "ultra" exceeds the media planner's aggregate work bound and reports it, while "auto" stays at the highest admitted tier.
nebula({ glow: 1, dust: 0.5, filaments: 1 }) is glowing gas crossed by dark dust: a body with an irregular outline that fades to nothing before its rim, its light gathered into thin filaments and arcs over a faint haze, going from color (the thin gas, default "#ff4fa3") to color2 (the dense gas towards the core, default "#7a5cff") and paling to white at its densest, with dust lanes that dim it. density (0 to 3) is how much gas and dust there is (0 draws nothing), glow (0 to 4) how bright the gas is, dust (0 to 3) how much dust crosses it, filaments (0 smooth to 2), scale (0.25 to 4) the size of its features, speed (0 to 1, default 0.05; 0 holds it still) how fast it slowly churns, and seed its pattern. Every number is a live parameter (a timeline can track it). Without volume it is a 2D backdrop over the whole canvas, under the objects (layer: "over" puts it over them): soft dots in Ray and Wireframe, coloured density characters in ASCII.
In Ray, volume makes it a participating medium in a world box (scene units, axis-aligned):
nebula({ volume: { min: [-2.6, -1.5, -2.2], max: [2.6, 1.5, 1.2] } })
The gas is emission and the dust is extinction (the blue more than the red, so what is behind a lane is reddened) with a low, blue albedo (dark lanes; a faint blue veil where the scene's lights reach it) and Draine's phase function for the light it scatters (phase: { g, alpha }; by default the g whose mean cosine is 0.6).
It is drawn by the engine's volume march on the public api: 1 volume contract, so it is:
- hidden by the objects in front of it;
- seen through glass;
- walked into by the camera;
- composed with
fog({ volume }),smoke({ volume }),fire({ volume })and the clouds in one march (a fog in front of it dims it by the fog's own transmittance).
Its density is zero at the box's faces, so the box never shows, and its light and extinction are relative to the box's size: the same settings look the same in a box of any size. It is out of the march toward the local lights (lightMarch: false, as the built-in fire, smoke and fog), so the media planner charges it its own samples alone and it is admitted at every tier, fixed "ultra" included, alone and beside them.
ray: { temporal: false } turns the temporal history off and ray: { shadows: false } the solids' and the sun's shadows on its dust. set({ volume }) moves the box without a new installation; set({ volume: null }) returns to the 2D nebula.
ASCII, Wireframe and Ray without WebGPU (or before the volume is installed) draw the 2D nebula where the box shows on the canvas, at the box's depth among the objects. Its light is seen and adds to the picture; it does not light the objects.
clouds({ style: "cumulus" }) forms irregular sunlit masses with eroded, translucent edges and shaded interiors. In Ray, once its built-in volume shader is installed, the clouds are a volume in the scene and this screen field is not drawn; Wireframe (and Ray until then) reconstructs a continuous optical field without repeated puff sprites; ASCII samples the same field into coloured density characters. overcast retains a broad storm ceiling; layers adds three depths, including a foreground bank. height (default 0.6) sets the sky's extent, scale the size of the masses, detail their fine billows, and thickness their optical density. light and sunAngle (screen degrees, default -135 toward the upper left) control directional illumination. sceneLight (0 to 2, default 1) also makes each bank respond to the actual scene and effect lights: coloured point lights brighten nearby vapour with range falloff, spots respect their cone, and directional/hemisphere lights follow the billows. Moving or dimming a source updates the screen field and ASCII alike; 0 disables this response. Thin, irregular openings break up the underside, especially at low coverage. These controls, cover, speed and color work live in either mode; zero cover or thickness clears the clouds, and zero speed freezes drift and internal evolution without resetting their phase. Cloud-limited rain and ground strikes use the actual underside; embedded lightning follows the bank through its openings. The Clouds demo preset shows fair-weather cumulus above the city.
For blackHole:
inclinationsets how face-on the accretion disk is, whiletiltrotates its orientation on screen (-180° to 180°).hotspots(0 to 2, default 0.7) adds compact bright gas condensations that orbit with the disk and appear in its lensed images; 0 disables them.palette: "thermal"retains the blackbody colour fit;"lilac"and"blue"apply cinematic grades as the local gas gets hotter, retaining warm outer gas and pale bright cores.diskTemperature: increase it (1500 to 30000 K in the panel) to bring out these hues.spin: 0freezes the disk texture and condensations.
The GPU pen (Ray, and Wireframe on the GPU renderer) traces these features in the disk plane, including their bent images, while the Canvas pen's dots and ASCII provide approximations with the same controls. Tilt, palette, temperature and hotspots update live without restarting ingestion.
Tornado in the demo shows a continuous condensation funnel with rotating helical filaments, irregular rolling dust plumes and angular solid debris carried by its Rankine vortex. The dust occupies six depth slices, rises into the lower cone and darkens the condensation at the base, concealing its narrow foot. debrisColor (default dark grey, #52575e) colours dust and fragments separately from the funnel's color. Where its wind is strong enough it pulls the objects' mesh vertices into its flow, depth included, releasing their spring back to the surface while they are entrained; with pull: 0 they return to rest. Ray and Wireframe reconstruct front and back optical shells at real depth, with soft contact against the objects; ASCII samples the same field into density glyphs. density controls condensation, detail fine edge turbulence, and flow the upward filament motion independently of spin. Master speed: 0 freezes the shape, filaments, dust and debris. Changing these rates preserves animation phase. ground (0.35 to 1, default 1) sets the ground's position on the canvas; sceneLight (default 1) lets actual scene and effect lights shade the vortex and its dust locally. width, taper, bend, wander, pull and debris remain available in either mode.
fire uses continuous rising sheets with warped folds, thin luminous fronts, openings and detached tips. With source: "objects" it burns across the full surface, including lower faces, partly obscures the surface behind its luminous sheets, and rises above it; ground makes a broad bed and pointer a local torch. Ray and Wireframe reconstruct the field with smooth emission kernels instead of repeated flame cutouts; ASCII shades the same heat field into characters. height, intensity, speed (0 freezes the flame), turbulence and light work live in every mode. palette selects natural, blue, green, violet, red or custom (using color); these are visual emission palettes, with matching scene illumination when light is enabled. Changing a palette or mode preserves the flame's phase. Camera aperture does not enlarge or defocus it.
fire({ volume: { min: [2.17, 0.5, -2.45], max: [2.83, 1.0, -2.10] } }) burns in a box of the scene's world instead (scene units, y up): a fire on a log pile, in a fireplace. The box's bottom face is the fuel bed and the flames rise to its top; height below 1 ends them lower. The box is a boundary, not a window: flames as tall as the box (height 1 or more) break against its top face, bend over and run along it, and curl back at its edges, as under a firebox's ceiling. For a fire in the open, give it a box taller than the flames you want and a height below 1. In Ray with WebGPU the flames are a volume of light in that box: seen from any camera, hidden by what stands in front (the hood, a wall), seen through glass, with embers rising among the objects, and light becomes a flickering point light in the box that casts the objects' shadows (0, the default: the flames light nothing but the picture and its bloom). The shape follows the box: a square bed burns to a peak, a long one to a ridge, and the flames keep their size relative to the box's height at any scene scale. Their pace does not follow the scale (scene units are not metres unless the scene says so): speed 1 suits a hearth, where the tongues pass a few times a second and the fine folds flicker at about 8 Hz; a real fire pulses slower as it grows (about 1.5/√width Hz, width in metres), so lower speed for a bonfire and raise it for a candle. intensity, height, speed, turbulence, palette, color and light work as above, and set({ volume }) moves the fire without reloading its shader; set({ volume: null }) returns to the 2D fire. Everywhere else (ASCII, Wireframe, Ray without WebGPU, or a volume Ray could not install) the 2D flames burn where the box's base shows on the canvas, as wide and as tall as the box shows, over the picture (they are not hidden by the objects). While Ray prepares the volume's shader nothing is drawn (up to 180 frames; wait for ready in scene.stats().effects to show the scene with its fire lit). source is not read while a volume is set. The volume is one of the scene's Ray media (at most 8, see custom shaders): it uses no texture and only emits, so it is out of the media's march toward the local lights and costs its own march samples alone: it is admitted at every quality tier and a medium beside it (smoke, clouds, a fog) is admitted where it is admitted alone. fire({ volume }) and smoke({ volume }) install together at every tier, fixed "ultra" included. A volume a fixed tier cannot admit is refused (failed in stats().effects, the fire's 2D form drawn instead). A value that is not a box (finite corners, max above min on every axis) throws, as does a box with a corner beyond 1e30 or a side under 1e-4 scene units (a RangeError naming the field); the settings table (EFFECT_PARAMS) lists it as a box, which the director's operations validate.
smoke({ volume: { min: [2.17, 0.68, -2.45], max: [2.83, 0.95, -2.08] } }) keeps the plume in a box of the scene's world (scene units, y up). In Ray with WebGPU the smoke is a volume in that box and the box is its boundary: it rises from the bottom centre as a column, breaks against the top face, pools and spreads under it and rolls down the side faces, so it reads as smoke under a ceiling (a firebox's, behind its glass). Its density is relative to the box: the same density and opacity look the same in a box of any size. It is lit by the scene's lights and shadowed by the solids, without the media's own dimming of the local lights (it leaves that march, so it stands beside a fire or a fog at every quality tier). While Ray prepares the volume, or if Ray refuses it, nothing is drawn: the 2D flow, which knows neither the box nor the solids about it, is the fallback only where there is no Ray volume (ASCII, Wireframe, Ray without WebGPU), rising from where the box's bottom centre shows. With a volume, scale only affects the CPU fallback's nozzle in ASCII and Wireframe (and Ray without WebGPU): the Ray volume is sized by the box alone. set({ volume }) moves the box without reloading the shader; set({ volume: null }) returns to the free plume of source. A box with a corner beyond 1e30 or a side under 1e-4 scene units throws a RangeError naming the field (the GPU holds its numbers as 32-bit floats; such a box would otherwise vanish silently).
fireworks in graphical modes uses compact, bright optical cores and fine glittering trails. Their size follows the viewport; foreground camera aperture and haze do not defocus the distant stars. GPU bloom adds surrounding glare while the cores stay defined. The same focused cores render on Canvas, preserving the shell shapes, colour changes, timings and glitter. ASCII shares the same shell programme, colour changes, glitter, splits and finale. Bright stars use compact crosses, trails cool into fine dots and ticks, and overlapping particles resolve to one glyph per cell. type, intensity, rate and finale work in both modes; switching mode preserves the live burst. In Ray with WebGPU each burst also lights the scene and leaves smoke: a point light where its stars are, in their colour as it changes, for as long as they burn (three bursts' lights at once at most; it lights the objects, casts their shadows and lights the scene's other volumes), and a puff of thin volumetric smoke that grows, drifts with the wind and is gone in a few seconds, dark until a later burst or the scene's light falls on it. Both cost GPU time: while a burst's light is on, Ray traces the objects again every frame (a still scene no longer rests), and the smoke is one more volume to march, one of the eight a scene composes. fireworks({ ray: { light: false } }), ray: { smoke: false } or both leave them out; with both off the effect installs no Ray shader at all and costs what its stars alone cost (in a scene that is otherwise still, either part alone keeps Ray drawing every frame while it is alive; only both off let it rest). ray is read when the effect is created: set does not change it, so make the effect again to switch. ASCII, Wireframe and Ray without WebGPU draw the stars alone either way.
wind progressively erodes objects: sustained wind cuts their surface away over several seconds and releases what it removes as small fragments carried downwind, while the objects' vertices flex in the gusts. The surface thins as the fragments disperse, rather than launching the entire object as a moving copy. erosion (0 to 3, default 1) controls the erosion rate separately from wind strength; 0 pauses new erosion while released fragments keep moving. Released fragments follow the current wind, so changing angle redirects them. No long streaks are drawn: sparse, tiny, transparent dust specks drift in a bounded volume around the origin, soft dots in Ray and Wireframe and . characters in ASCII. The panel's airborne dust switch (API option streaks, retained for compatibility) hides these specks without changing the wind forces.
The demo's Storm preset uses dark slate-grey clouds with subdued sunlight, thin neutral rain reflections and near-white lightning. The palette applies in graphical modes and ASCII; selecting Storm restores these colours even after tuning another weather preset.
Rain draws thin, neutral reflections with low alpha so the scene remains visible through the water. rain({ opacity: 0.35 }) controls this transparency independently of density; 0 makes existing drops and splashes invisible, and changes apply immediately in graphical modes and ASCII. color tints the reflections, defaulting to neutral grey rather than blue. Ray and Wireframe retain depth and motion blur, with finer streaks and translucent splashes. Tilted rain is emitted beyond the upwind edge to cover the whole viewport. The default source: "sky", also used by Storm, emits across the whole sky so rain remains visible through openings within the bank. The optional source: "clouds" limits emission to staggered heights inside the lower bank. Both fade through the continuous optical field, avoiding a dark separation band.
snow({ style: "natural" }) draws irregular white aggregates at different depths: many small distant flakes and fewer large foreground flakes. style: "classic" retains the eight decorative six-armed crystals. ASCII gives near natural flakes irregular multi-character footprints with faint outer fibres, while classic draws small branched crystals. Far flakes remain fine points, and flakes behind objects are screened by their silhouette. Both styles share live speed, size, wind (metres per second), gusts and flutter controls, alongside density, pile and melt. A separate wind effect takes precedence. The weather volume is populated immediately and continues beyond the screen edges; strong wind does not leave empty side strips. speed: 0 freezes the flakes and gust phase; changing speed or style does not restart the snowfall. White, softly transparent sprite edges stay in the same depth-sorted pass as the crystals, avoiding the dark masks caused by converting some flakes to defocused discs. Settled snow follows the objects' actual upper surfaces, stays white in the natural style, and falls away when its support moves.
Custom shaders
An effect can carry a ray manifest: WGSL that ray mode runs on the GPU next to the engine's own passes. This page describes the stable api: 1 contract and the legacy api: 0 compatibility path.
Stable for the installed kinds below.
volume,light,post, unlitlayerandlensare theapi: 1contract.simulateandlit: truelayers remain explicitly unsupported; no item shader material is promised. Existingapi: 0manifests are accepted with their existing semantics.
Support matrix
“CPU hooks” means the effect's own draw, glyph, offset and particle drawing, subject to its cpu policy. A GPU manifest is never translated to glyphs or wireframe edges.
| Part kind | Ray | ASCII | Wireframe | api: 1 state |
|---|---|---|---|---|
volume: an analytic participating medium marched by the engine |
Installed; ready after validation, compilation and media admission |
CPU hooks | CPU hooks | Stable |
light: up to 256 light slots written from JavaScript |
Installed | CPU hooks | CPU hooks | Stable |
post: a pointwise pass at the hdr or display stage |
Installed | CPU hooks | CPU hooks | Stable |
layer, lit absent or false: a quad, billboard or screen sheet placed behind or in front of an item |
Installed, depth-tested against solids | CPU hooks | CPU hooks | Stable |
layer with lit: true |
unsupported; no GPU batch from this manifest |
CPU hooks | CPU hooks | Unsupported |
lens: a world sphere whose rays are bent and walked against solids with bounded queries |
Installed; composition limits below apply | CPU hooks | CPU hooks | Stable |
simulate |
unsupported; no GPU batch from this manifest |
CPU hooks | CPU hooks | Unsupported |
| Shader materials replacing a scene item's BRDF | Not available | Not available | Not available | Not in the contract |
Prepared buffer/texture uploads are part of the same contract through Effect.prepareRayResources; see resource uploads. Public CPU validation is exported; the GPU compiler and GPU handles are not. Runtime installation status is read through scene.stats().effects.
Versioning and migration from api: 0
The API version belongs to each manifest, not to the package as a whole. api: 0 and api: 1 currently use the same declarations, WGSL ABI, validation and runtime behavior. There is no automatic rewrite and no migration diagnostic: changing only api: 0 to api: 1 opts the same manifest into the stability promise. New manifests should use api: 1; old ones can remain on api: 0 as a legacy, non-stable compatibility path. The api: 0 contract is not covered by the api: 1 freeze and may change in a future release.
Within api: 1, a release may fix implementation defects, improve diagnostic wording or add warnings, add helpers without changing existing ones, and add optional declarations whose omission preserves existing behavior. FxPart and diagnostics may also grow by additions within api: 1, so consumers must handle a default case for part kinds and diagnostics they do not know. The FxStatus["state"] union does not change. A later candidate part kind has its own row in the support matrix; when installed it reports ready and also emits the warning diagnostic candidate kind (api: 1 candidate; may change before it is frozen). It remains a candidate until separately promoted and does not change the frozen meaning of the five installed kinds above.
The freeze does not cover SimulatePart or the lit slot of LayerPart: those typed-but-unsupported slots, their declarations and their diagnostics may change within api: 1.
api: 2 is required to remove or rename an existing frozen kind, field, type or helper; change an entry signature, units, colour/alpha convention, default, ownership rule or fallback rule; tighten a limit so a previously valid manifest fails; or otherwise change an existing manifest's documented result. Relaxing a limit or adding an optional, backward-compatible capability does not by itself require api: 2. Security or robustness corrections, and device-dependent compilation or admission, may reject a manifest accepted by an earlier release or on another device without requiring api: 2. A future api: 2 does not withdraw api: 1 support.
Imports and public validation
Everything comes from the package root, with no deep imports. dist/ray/fx/* is internal, and the package exports map does not expose it.
import {
createScene, validateRayManifest,
type Effect, type EffectFrame, type RayPart, type FxPart,
type VolumePart, type LightPart, type PostPart, type LayerPart, type LensPart,
type SimulatePart, type FxLayerPlace, type ParamDecl, type ResourceDecl,
type BudgetDecl, type FxWriter, type FxLightValue, type FxValidation,
type FxStatus, type FxDiagnostic,
} from "mote-engine";
const checked: FxValidation = await validateRayManifest(candidate); // candidate may be unknown JSON
if (!checked.ok) console.error(checked.diagnostics);
validateRayManifest is asynchronous so its CPU validator loads on demand rather than becoming an eager dependency of every ASCII page. With the current plain, minified browser bundle, the first call downloads about 386 KB for the validator chunk. It acquires no adapter or device and exposes no GPU handle. It performs the same structural, ABI, resource-declaration and static-work checks used before installation; it does not run the driver compiler, bind scene item names, or apply device-specific and aggregate media admission. Therefore ok: true means eligible for those later gates, not guaranteed ready. Its FxValidation contains a fresh ok flag and diagnostics array.
The declarations name no WebGPU type. A project without @webgpu/types compiles them with skipLibCheck: false.
The manifest
const ray: RayPart = {
api: 1,
cpu: "none", // "all" (default) | "particles" | "none"
params: { density: { type: "f32", default: 2, min: 0, max: 8 }, glow: { type: "color", default: "#ff8a3d" } },
wgsl: `…one module for every part…`,
parts: [
{ kind: "volume", name: "fogball", fn: "fog", bounds: { min: [-1, -1, -1], max: [1, 1, 1] }, animated: true },
{ kind: "light", name: "lamp", max: 1 },
{ kind: "post", name: "grading", fn: "grade", stage: "hdr" },
],
};
const effect: Effect = { name: "my-shader", ray, frame(f) { /* feed f.fx */ }, draw(f) { /* fallback */ } };
scene.addEffect(effect);
Rules checked on the CPU before anything reaches the GPU:
parts: 1 to 64. Part names are unique WGSL identifiers, and every non-light part'sfnnames a function inwgsl.params: at most 256, in declaration order. Each takes one 16-byte uniform slot and is read in WGSL asc.params.<name>.f32,u32:default,minandmaxare required.u32values are integers.vec2f,vec3f,vec4f:defaultarray;min/maxoptional, applied to every component.color: a CSS colour string, resolved once at setup to linear RGB (sRGB transfer removed) and read asvec3f. Alpha is ignored. Without a DOM, hex,rgb()/rgba(),hsl()/hsla()and a few names are accepted. In a browser, any CSS colour the canvas accepts works.history(optional, any type):"reset"(the default) or"continuous". It decides what a changed value does to the temporal history of the manifest's volumes. With"reset", any written change rejects that history once (a discontinuity: the next frame is current-only, then it accumulates again). With"continuous", the change keeps the history: it is reprojected by the volume'sadvectionand clamped to the current neighbourhood, like motion. Declare"continuous"only for values that evolve smoothly from frame to frame, typically a clock your function reads (time: { type: "f32", default: 0, min: -1e6, max: 1e6, history: "continuous" }); a jump in such a value is not detected and shows as clamped ghosting for a few frames. Any other value is refused. Manifests withouthistorybehave exactly as before.
resources: up to 16 buffers or 2D/3D textures with fixed sizes for the five tiers (64 MiB per tier in total; the device's limits apply on top). They are accessible in WGSL asfxBuf_<name>(i)/fxTex_<name>(…)and are filled fromEffect.prepareRayResources; see resource uploads.budget:maxLoop(1–1024, default 128) caps each loop.cost(light/medium/heavy) multiplies the static estimate by 1/2/4.resolutionandstepsare five values per tier and are validated.stepsis read by post passes asc.steps(1 when absent), and by a lens as its walk's allowance (32 when absent, at most 32). For volumes, the march uses the engine's fixed step tables:stepsis reserved and does not override them.resolutionis reserved and unused by every installed kind inapi: 1.cpu: see below.
WGSL module rules
- Module items:
fn,struct,const,alias,var<private>. There are no attributes (@…) and no bindings of your own. - Names starting with
fx,mote,_fxor__are reserved, as are WGSL builtins and keywords. A single_is not an identifier either (WGSL reserves it for the phony assignment_ = value;, which is allowed). Identifiers are ASCII-only inapi: 0andapi: 1; non-ASCII text is accepted in comments and infxItem/fxHasnames. Every identifier must be declared by you or be in the public ABI below; anything else is an error. - String literals are allowed only as
fxItem("id")/fxHas("capability").discardandconst_assertare rejected. - Loops need a braced body; the engine inserts a guard that breaks after
maxLoopiterations. Recursion is rejected. There are at most 64 functions, 64 KiB of source and 32768 tokens. - A static work estimate (loop visits ≤ 4096, weighted operations ≤ 1 048 576 per entry) is a fault gate, not a time measurement. Each
let/return/assignment, operator, builtin and helper call adds to it, and each public helper costs at least 4096. Keep entry functions lean (see Known limits).
fxVisible and fxShadow retain eight geometric visits per query, shared by TLAS nodes, BLAS nodes and triangle tests. Procedural surface operations do not consume those eight visits. Instead, an entry that calls either helper reserves its fixed work first, then receives separate scalar-operation and loop-visit credits from the remaining limits above. The declared cost multiplier applies before those credits are allocated. Wrappers, loops and later queries in the same entry share the credits; they cannot refill them. Volume sampling, including sky and shadow sampling, starts a new credit allocation for each actual user-entry invocation.
Every surface operation pays its conservative opcode/profile cost and one visit before evaluation. Within both credits, the complete original surface/material formulas run. If either credit cannot pay the next operation, that query returns opaque visibility/transmittance; a partially evaluated surface cannot create a transparent hole. This enforces the declared work limit on previously unbounded procedural work. The fault belongs to that query: a later query clears the fault while retaining the remaining credits and its own eight geometric visits. Base Ray rendering and engine-generated segment shadows use their original surface evaluation without the user-query credits. A query-bearing entry can be rejected at a higher cost weight or by aggregate volume planning; the engine does not reduce material quality or march steps to admit it.
Public ABI (types and helpers callable from your WGSL): FxCtx FxParams FxRay FxMedium FxPhase FxBent FxSeg FxSurface FxLight, fxItem fxHas fxCameraPos fxCameraDir fxWorldToView fxProject fxPixelSize fxDistance fxSurface fxId fxLightCount fxLight fxLightAt fxShadow fxVisible fxSunTransmittance fxAmbient fxAmbientIn fxSky fxPhaseHG fxPhaseTwoLobe fxPhaseMie fxPhaseDraine fxPhase fxStep fxOctaves fxPowder fxBlackbody fxNoise3 fxNoise3p fxWorley3 fxFbm3 fxCurl3 fxIgn.
struct FxCtx { time: f32, dt: f32, frame: u32, tier: u32, steps: u32, budgetScale: f32, params: FxParams };
struct FxPhase { kind: u32, p: vec4f }; // build with fxPhaseHG(g), fxPhaseTwoLobe, fxPhaseMie, fxPhaseDraine
struct FxMedium { sigmaT: vec3f, albedo: vec3f, emission: vec3f, phase: FxPhase };
c.time and c.dt are in seconds (the scene clock). c.tier is the ray quality tier, from 0 (lowest) to 4 (ultra).
Entry signatures, colour, alpha and units
volume: fn name(p: vec3f, c: FxCtx) -> FxMedium
pis in the part's local coordinates, the same space asbounds. The writer'stransformmaps local to world (identity by default, so local equals world until you write one). The density is never sampled outsidebounds.sigmaT: extinction per world unit of ray length, per RGB channel. A scaled transform makes the box bigger without changing the coefficient, so optical depth grows with the scale. Scene units are not metres unless your scene says so.albedo: single-scattering albedo, 0–1. In-scattered light isincoming × sigmaT × albedowith the givenphase.emission: linear radiance added per world unit of path (not multiplied bysigmaT).- The engine scrubs the result: non-finite values become 0,
sigmaTis clamped to [0, 60000],albedoto [0, 1] andemissionto ±60000. - Options:
integratoraccepts only"march"("froxel"fails at installation).temporal(default true) uses the temporal history;falseuses the larger static step table.animated: truekeeps a resting or refining picture updating when the density readsc.time. A change written to a parameter rejects the history once unless that parameter is declaredhistory: "continuous"(see the manifest rules); a clock you feed through a parameter every frame should be declared so, or the volume never accumulates.advection: [x, y, z](world units per second, also writable) is the motion used to reproject that history; it does not move the density, so animate it in your function.castsShadowadds the medium's extinction to the sun's shadow map and traces solid occlusion of lights for its in-scattering.inReflections: "sky-layer"includes it in the sky layer that reflections see.lightMarch(default true) keeps the medium in the march toward the local lights;falsetakes it out (see the next point). - What a volume is charged, and
lightMarch. The media planner bounds the user entries one march ray may run: 2^27 weighted operations, a fault gate and not a time. Each part is charged for what its own declaration can run. Per march sample (the tier's steps, plus two per volume part of the scene) every part's entry runs once. On top of that, a part in the march toward the local lights (the default) dims the light a point or spot light sends to each sample by the media on the way: 32 lights of the tier's light steps (0, 0, 2, 2, 4 fromlowesttoultra), each step one entry of every part in that march.lightMarch: falsetakes a part out of it, both ways: the light it scatters from a local light is not dimmed by the media on the way (what every medium gets at the two lowest tiers), and it does not dim the light the other media receive. Its extinction along the view, the sun's transmittance map and the solids' shadows (castsShadow) are unchanged. Such a part is charged its own samples alone and the generated code runs no more than that for it, so a medium that only emits (a flame) or a thin one that carries its own shading (a smoke in its box) costs what its entry costs, and a medium beside it costs what it costs alone. With every part in the march the bound issamples × operations × (1 + parts × 32 × light steps), as before this option existed. The built-infire({ volume }),smoke({ volume }),fog({ volume })andnebula({ volume })declarelightMarch: falseand are admitted together at every tier, fixed"ultra"included; the built-in clouds, the freesmoke()plume and a manifest that does not say otherwise stay in the march. - Glass. Where the nearest solid in a pixel lets light through (a transmission above 0 on what is not all metal: a window, a fireplace's pane), the march goes on past it to the opaque solid behind. What the medium sends from behind the glass is dimmed by what the glass lets through (every crossing in front of the opaque solid: its transmission, less what Fresnel reflects, tinted and absorbed, as for the dots and the layers behind glass), and the medium's own extinction behind the glass dims only the share of the picture the glass lets through. It is seen straight through the glass, not bent, and every crossing counts as if it were at the nearest one: exact for a pane, an approximation for thick refracting glass and for a medium between two panes. A lens walk and the sky layer are unchanged.
- A scene composes at most 8 volume parts, from all effects together.
post: fn name(color: vec4f, pix: vec2f, c: FxCtx) -> vec4f
pixis the fragment's pixel centre (x + 0.5, y + 0.5) at the internal render resolution. These are not CSS pixels: ray's resolution scale and the device pixel ratio apply.coloris this pixel's value only, a single engine-owned load. You cannot read neighbouring pixels of the picture. You can read the scene atpixwithfxSurface,fxDistanceandfxId(compare withfxItem("item-id")).stage: "hdr":coloris premultiplied linear HDR radiance after the engine's own post effects, before exposure and tone mapping. Return the same kind of value.stage: "display":coloris the tone-mapped, sRGB-encoded, premultiplied picture in 0–1, and your result is copied to the canvas. Keeprgb ≤ alphaso the premultiplied value stays valid for the page's compositing.- The output is scrubbed: non-finite values become 0, rgb is clamped to ±60000 and alpha to [0, 1]. Post parts run in manifest order, and effects in scene order.
layer: fn name(uv: vec2f, i: u32, c: FxCtx) -> vec4f
{ kind: "layer", name: "halo", fn: "halo", shape: "billboard",
place: { of: "ship", side: "behind", offset: 0.2, soft: 0.5 } }
- The result is premultiplied linear HDR, scrubbed like a post result. It is unlit radiance: it is drawn after the TAA, has no history, and also feeds bloom and flare as this frame's emission. An opaque front layer blocks the emission it covers.
uvis (0, 0) at the shape's top left and (1, 1) at its bottom right.iis the instance,0toinstances - 1. There is no colour input. You receive nopix, sofxDistance,fxSurfaceandfxIdhave no fragment position to read at; the world-point helpers (fxVisible,fxShadow,fxProjectand the lights) work as in a post part.shape:"screen": the whole canvas. A transform is ignored."quad": the rectangle x, y in [-1, 1], z = 0, underfx.transform. It may tilt."billboard": faces the camera, at the transform's origin; half width and half height are the lengths of its x and y axes.
- The transform's origin is the item's centre on world axes with
of: "item-id", so the shape follows the item with no script. Withof: "all"it is the world origin. The default transform is a shape of half size 1. placedecides only the depth a fragment is compared at. The image never moves.of: an item id, or"all"for every instance in the frame, the floor excepted."all"is reserved: an item namedallcannot be a target.side: "behind": every fragment is at or past the target's far extent plusoffset. The target and everything nearer hide the layer, and it covers what lies past it.side: "front": every fragment is at or before the target's near extent minusoffset. It covers the target, and anything nearer than that plane still hides it.- A solid exactly on the plane is a tie, and a tie goes to the layer.
offset(scene units, default 0): positive moves away from the target, negative into it.soft(scene units, default 0): fades the layer over that distance in front of any solid, the target included. Afrontlayer withsoftaboveoffsettherefore fades towards the target's nearest point.- A tilted quad keeps its tilt but stays wholly on the declared side. It cannot cut through its target; use a
volumefor that.
- Glass. A layer past glass is dimmed by what the glass lets through, seen straight through it, not bent; a layer before it is not.
softis skipped past glass. - Order. Layers are sorted back to front every frame by their placement depth, so the order can change as the camera moves. At equal depth
behinddraws beforefront, and only then manifest and scene order. There is no per-pixel transparency sort: two layers that cross are sorted as wholes. - Target lifetime. A
place.ofthat names no item, or one ambiguous across stages, leaves the effectfailedwithUnknown scene item …on that part, and its CPU hooks run. The same happens at once whensetStagesremoves the item, and putting it back re-installs the manifest. An item that merely has no instance this frame (another stage) skips the layer for that frame; the state staysready. instancesdraws the shape N times at one shared transform and depth, withias a shading index. There is no per-instance placement yet. The static work estimate is charged N times, so an entry callingfxVisibleorfxShadow, which reserves most of the limit, fits only at one instance.lit: trueis not installed: the manifest staysunsupported, with a diagnostic naming the part. Your CPU hooks keep drawing.- Limits: the silhouette is decided per pixel, so a
behindlayer does not blend under an object's antialiased edge (a one-pixel band). A layer draws over a volume, not inside it, so fog in front of it does not attenuate it. It is not in reflections, refractions or the path tracer's picture.keepClearfades the solids, not layers. Translucent dots write depth, so one in front of a layer leaves a hard hole in it. An item's extent comes from its mesh's bounding box under its transform, which is conservative when rotated.
lens: fn name(r: FxRay, c: FxCtx) -> FxBent
{ kind: "lens", name: "hole", fn: "bend", center: [0, 0, 0], radius: 8 }
A lens is a sphere in the world. Every pixel whose ray enters it calls your function, which returns the path that ray really takes. The engine then walks that path against the scene's geometry: this is not a screen warp, and it can show what is in no pixel of the picture, such as something behind the camera or behind a wall.
struct FxRay { o: vec3f, d: vec3f, tMin: f32, tMax: f32 };
struct FxSeg { o: vec3f, d: vec3f, len: f32, shift: f32 };
struct FxBent { segs: array<FxSeg, 32>, count: u32, captured: bool };
- Frame.
centerandradius, and everything your function reads and returns, are in the part's local coordinates, the spacefx.transformmaps to the world. Identity by default, so local is world until you write one, and a moved or scaled lens needs no change tobend. Any invertible transform works; a singular one draws nothing that frame. Parameters and lights are still written fromframeas usual. FxRay.ois where the ray enters the sphere (the eye, when the camera is inside).dis its unit direction.tMinis 0.tMaxis the distance fromoto the first opaque solid on the straight ray, 60000 when there is none.FxBent.count == 0,capturedfalse: the lens leaves this pixel alone, at no walk cost.FxBent()is the identity.count == 0,capturedtrue: opaque black.- Otherwise the segments are walked in order. The first solid met ends the walk.
- Past the last segment: with
capturedtrue, opaque black. Withcapturedfalse the ray escapes: the last segment goes on to infinity along its direction.
FxSeg.oanddare local.dneed not be unit length.lenis local. Both ends belong to a segment, so a surface exactly on the join of two segments is met, once, by the earlier one. Each end is widened by about 4 millionths of the larger of its coordinates and, at the far end, the segment's length, so a segment can meet a surface that close past its nominal end or behind its start: withlen1e-8 a surface at 2e-6 is met, and at coordinates of 1e8 the tolerance is about 400 units. A segment need not start where the last one ended.shiftmultiplies the radiance seen along that segment, soFxSeg()shows black: write1.0for none. Alenat or below 0 skips the segment.- What a walk shows. A solid is shaded once, as reflections shade it: emission, every light with a shadow ray, ambient, the environment's reflection. A ray that escapes takes the environment when it is the background, and otherwise leaves the pixel transparent.
- Occlusion. A lens is depth-tested at its entry against what is already drawn. A solid nearer than the sphere stays in front of it, and a solid inside the sphere is met by the walk. Only pixels the lens writes change, and nearer lenses win, with no sort.
- Emission. Bloom sees what the lens shows: an emitter bent into the disc seeds bloom there in the same frame, and one bent away stops seeding at its straight position.
- Layers. A lens runs before layers and writes its depth at the entry. A
frontlayer nearer than it covers it. Abehindlayer past it is hidden inside the disc. With the camera inside the sphere, every layer is behind it. - Glass before a lens dims it by what the glass lets through, as for a layer. The pane's own highlight inside the disc is lost, since the pixel is replaced.
- Scene access.
bendreaches the same read-only ABI a post or layer entry reaches: helpers, lights, boundedfxVisible/fxShadow, resources, parameters. It has no pixel, no picture and no history. The walk is engine code that it cannot call. - Limits, per pixel.
- Segments:
min(32, budget.steps[tier]), 32 when undeclared.c.stepsreads the same value.c.tieris the prepared tier, 0 on this base. - Geometric visits, shared by every segment and shadow ray: up to 4096, less the entry's own loop visits, and less again as
costrises. Check the status: an entry that leaves under 64 is refused. - Scene: at most 8 lens parts, across all effects. The ninth fails with
Aggregate lens count exceeds 8on its part, and the rest stand.
- Segments:
- Failure inside the walk. Out of visits, or a segment with a non-finite or zero value: the pixel is opaque black. It never falls back to the straight picture, and it never makes a hole. Shadow rays that run out return shadowed. A negative or non-finite
shiftis 0, andcountis clamped. - Lifetime.
pending,failed, ascii, wireframe and no WebGPU leave your CPU hooks drawing, and removing the effect restores the picture on the next frame. - Limits.
- Volumes are integrated along the bent path. Fog in front of the lens shows over it, fog behind it on the straight ray does not incorrectly show through it, and media crossed by the bent path are integrated. This composition is charged against the media work budget and can make an over-budget batch fail; it is not a path-traced medium.
- Dots, particles, layers and other lenses are not geometry, so a bent ray does not see them.
- A lens is not in reflections, refractions or the path tracer's picture.
- It is drawn after the TAA, one sample a pixel, with no history. Its edge and what a strong bend compresses are aliased.
- A lit solid seen through a straight lens is shaded by the reflection path, so a seam against the denoised picture can show. Flat emissive colours agree.
- Glass on the walk is one surface showing the environment behind it, not a refraction. A shadow-catcher floor is not a surface.
- Any-hit and area-light sampling use a fixed sequence, so a stochastic blend through a lens is a stable pattern.
- A pixel hidden by a nearer object still pays for its call and its walk.
- The limits above are fault gates: a manifest at the ceiling over a large scene can cost far more than a frame has.
light: no WGSL
max (1–256) reserves slots, which you write with fx.light(part, index, value). A slot is off while its intensity is ≤ 0 (the initial state) and keeps its last written value. Effect lights join the scene's lights up to 32 in total.
FxLightValue field |
Meaning |
|---|---|
kind |
"point", "spot" or "directional" |
position |
World units (point, spot) |
direction |
Unit vector, normalised by the engine. Directional: towards the light. Spot: where it points |
color |
Linear RGB |
intensity |
Scale on color |
range, radius |
World units: where the light fades to nothing, and the emitter's radius for soft shadows |
angle |
Radians. Spot: half-angle of the cone. Directional: apparent diameter |
flare |
Show the light's disc in this frame's emission: bloom takes it, and the lens flare's image passes when ray.flare is on. It is not one of the flare's key sources |
Effect spots have no penumbra and always cast shadows.
Feeding the shader: FxWriter
f.fx exists only in ray mode, inside the effect's frame hook:
frame(f) {
const fx = f.fx;
if (!f.ray || !fx) return; // ascii, wireframe: no writer
fx.set("density", density); // a declared param, within its min/max
fx.transform("fogball", matrix); // 12 numbers, row-major 3x4, local → world: [a b c tx, d e f ty, g h i tz]
fx.light("lamp", 0, lamp);
fx.advection("fogball", 0.1, 0, 0);
}
- The writer copies what you give it, so reuse your arrays. It is owned by the scene, so do not keep it beyond the frame.
- An unknown name, a wrong length, a non-finite value or a value outside a param's
min/maxthrows when called outside a frame. Insideframeit is not thrown: the write is ignored and the effect's status gets the diagnosticInvalid effect writer value or name. Clamp before writing. - A singular transform disables that volume for the frame. On a
layerpart the same transform places the shape; ascreenignores it.
CPU policy and the fallback you write
The engine never turns your WGSL into ascii glyphs, effect dots or wireframe edges. What draws when the GPU version does not is whatever your CPU hooks draw (draw, glyph, offset, particles). The cpu policy decides which of them keep running while the GPU version is installed:
cpu |
Installed in ray mode | Not installed (ascii, wireframe, no WebGPU, pending, failed, unsupported, quarantined) |
|---|---|---|
"all" (default) |
draw, glyph and offset still run, alongside the GPU version |
They run |
"particles" |
draw, glyph and offset are suppressed. The scene has no separately gated particle hook on this base, so this currently behaves exactly like "none": particles you draw from draw (e.g. f.dots) are suppressed too |
They run |
"none" |
draw, glyph and offset are suppressed |
They run |
frame always runs, because it feeds the writer. trigger, set and mesh hooks are not gated by the policy either. The suppression switches together with the GPU batch: it starts when the batch is installed and stops when it is removed or lost. A manifest does not mean an equivalent fallback exists. If you want something to show in ascii, write it (the example draws a cluster of soft dots with f.projectWorld and f.dot).
Diagnostics: scene.stats().effects
scene.stats().effects is a readonly FxStatus[]: one entry per running effect that has a ray manifest, in the order of the running effects (scene effects, then the current stage's). Entries are created only when ray mode runs with a GPU device.
The engine's effect host (the manifest validator, the WGSL bindings and the trusted query cache) is loaded with import() the first time ray runs an effect that has a ray manifest; an ascii or wireframe page, or a ray scene with no manifest, never downloads it (with the <mote-scene> bundle it is the host-….js chunk and a chunk it shares with ray's side). While it loads, the effect is pending and its CPU hooks draw, as while it is validated and compiled. In ray, scene.ready also waits for the host to load when a scene effect or a stage's effect has a manifest, but not for the manifest to compile: wait for ready in stats().effects for that. ready never rejects, and a ready already handed out settles when the scene no longer needs the host (destroyed, switched away from ray, fallen back, its device lost, or no effect with a manifest left), as it does for ray's own device; the load itself goes on for the other scenes of the page. The stats().effects array and its entries published while the host loads are the ones the host then keeps up to date. If the host does not load (a network error, a chunk missing from the folder), the effect reads failed with the custom effect host did not load (…), its CPU hooks keep drawing, and the load is tried again the next time ray resumes. A scene that never reached ray (ascii, wireframe, or ray fell back) has an empty array: check scene.mode and stats().ray.fellBack. After a switch from ray to another mode, the entries stay and read failed until ray resumes and prepares them again. The array and its objects are reused, so copy what you want to keep.
type FxStatus = { state: "pending" | "ready" | "failed" | "quarantined" | "unsupported"; diagnostics: readonly FxDiagnostic[]; gpuMs: number | null };
type FxDiagnostic = { part: string; line: number; column: number; length: number; severity: "error" | "warning"; message: string };
| State | Meaning |
|---|---|
pending |
Being validated or compiled, or the engine's effect host is still loading |
ready |
Installed in the current GPU batch |
failed |
Rejected by the validator, the WGSL compiler, the media planner or the device, or the engine's effect host did not load. A failed reload of a new manifest leaves the previous installed version drawing |
unsupported |
Contains a part with no renderer consumer (simulate, or a layer with lit: true) |
quarantined |
The device was lost within 120 frames of installing this manifest. A new manifest object is needed to try again |
Where diagnostics come from:
- Validator (CPU):
line/columnare 1-based positions in yourwgsl.partnames the part whose entry caused the error when that is known (a missing or over-budget entry points at its own part); module-level failures fall back to the first part name. - WGSL compiler (GPU): its messages are mapped back to your source where the error is in your code. Errors in generated code are prefixed
[generated contract]. - Media planner / batch:
line0, withpart"media"or"", for exampleAggregate media user work … exceeds …. The lens cap names the lens part that overflowed. - Every accepted manifest also carries a warning
Static estimate: …. It describes the fault gate, not a measured cost.
For the example's deliberately broken manifest, the CPU validator gives:
error broken:2:65 Unknown or engine-private identifier 'anisotropy'
For its simulate manifest, the state is unsupported with simulate installation is unsupported in foundation phase 1 and This part has no installed renderer consumer; CPU fallback remains active.
To change the WGSL, give the effect a new manifest object (or replace the effect). Editing a manifest in place does not reload it.
Known limits on this base
These are explicit api: 1 limits, not silent fallbacks or promises of future support.
- Transmittance floor of about 1%. The march stops a ray once every channel of its transmittance is below 0.01, so a medium denser than an optical depth of about 4.6 (
-ln 0.01) does not reachexp(-tau): it can leave up to 1% of the background visible, and that value depends on the step count. An optical depth of 18.5 at 16 steps gives about 0.0098, not 1e-8. This is a limit of the integrator, not an analytic result. - Explicit
ultracan reject a volume;autoclamps to an admitted prefix. The media planner's aggregate user-work limit is 2^27. At tier 4 (ultra) the built-in clouds and this example's fog exceed it, and fixedquality: "ultra"reportsfailedwith theAggregate media user work …diagnostic; fixed tiers through"high"work for these manifests. (Those media are in the march toward the local lights, which is most of that charge; a part declaredlightMarch: falseis not charged it: see thevolumeentry above.) Forquality: "auto", setup preflights every tier and caps the active composition at the highest tier whose complete prefix 0…N is admitted. It therefore does not step from high into this failing ultra composition. The explicit-ultra rejection remains intentional, and a composition with no complete admitted prefix keeps the original admission behavior rather than hiding the failure. - A static
temporal: falsevolume beside other volumes can exceed the aggregate media bound. Atemporal: falsepart doubles the march step table, and the planner charges the generated per-volume light integration honestly (every volume's entry is evaluated once per march sample, plus, for the volumes in the march toward the local lights, once per local light per light step for every volume in that march through the shared extinction helper). A mix that fits at one tier can therefore be rejected at another even in a light-free frame: the bound reserves the worst case, because lights may appear without recompiling. The rejection is reported asAggregate media user work … exceeds …withpartmedia. - Volume budget fields are reserved as described above.
budget.resolutionis unused by all installed kinds.budget.stepsdoes not change a volume's engine-owned march table; it is consumed only by post and lens entries. Declaring either field is valid but does not promise volume control. - Entry names never collide with generated code. Your entry function may use any legal WGSL identifier, including
color,pix,porc; generated shims, guards and helpers use only reserved_fx…names that your code cannot declare. A collision reported by the WGSL compiler against such a name is an engine defect, not something to rename in your manifest. - Writer faults no longer mask other reasons. Only a frame write with no ready or pending staging (a manifest that is still being analysed before its staging exists, or is
unsupported,quarantinedorfailed) is dropped, and the status keeps the actual reason. A pending staging — or the previous ready staging while a replacement loads — still accepts valid writes, and a rejected value or name against such live staging still recordsInvalid effect writer value or name. - Owned
resourcesare filled only throughEffect.prepareRayResources(see resource uploads); there is no writer-hook path for them. simulateandlitlayers are not installed. There are no item shader materials.- Per-effect
gpuMsis alwaysnull. No per-effect timestamp attribution is implemented. This is separate fromscene.stats().ray.gpuMs, which measures the whole Ray frame. cpu: "particles"currently means the same as"none"in a scene. There is no separately gated particle hook, so particles emitted fromdraware suppressed with that hook while the GPU composition is installed (see the table above). It is not a promise to retain only particle drawing.
Public resource uploads
Effect.prepareRayResources(writer, signal) prepares buffer and texture content
outside frame hooks. It is called once for each demanded tier of each scene's
manifest version. It exposes no device, GPU resource or private packed offset.
The old composition stays installed during a replacement's preparation.
import type { Effect, FxResourceWriter } from "mote-engine";
const writers = new Set<FxResourceWriter>();
const effect: Effect = {
name: "resource-example",
ray: myManifest, // declares resources and their five tier sizes
async prepareRayResources(writer, signal) {
writers.add(writer);
signal.addEventListener("abort", () => writers.delete(writer), { once: true });
await writer.writeBuffer("gain", new Float32Array([0.5]));
await writer.writeTexture("image", rgbaBytes, {
origin: [0, 0, 0], size: [width, height, 1], bytesPerRow: width * 4,
});
},
};
resourcesdescribes the actual tier's names, kinds, formats/elements, sizes, byte lengths and strides. Trusted builtin bake textures remain private and are omitted; ordinary resources on the same effect remain uploadable. Its records and dimensions are frozen.tieris an index 0–4. Existing pointwise post resources use their prepared tier (currently 0); media use the renderer's actual tier. Their callbacks can therefore differ.versionis an opaque, frozen identity shared by the writers of one scene's manifest version. Group by identity when an effect object is used in multiple scenes. Capture writers per tier; updating one tier does not alter another tier's snapshot. Recovery, mode re-entry and named-item rebinding can also create a new installation version. Retired snapshots are not an application data store; the initializer must reconstruct current content from application state. A newrayobject creates a new version; changing the callback alone does not request a reload.writeBuffer(name, view, byteOffset = 0)takes raw bytes. Offset and length must be multiples of 4 within the resource. Avec3farray element has a 16-byte stride, including padding.writeTexturetakes raw bytes in the declared format, including IEEE half-float words for 16-bit float formats. Texture origin/size are three components; the default size is the whole texture. Rows are tight unlessbytesPerRow/rowsPerImagespecify padding. These are byte/row strides, not texel counts, and must fit an unsigned 32-bit integer even when a one-row/image region does not use the stride. R8 data need no artificial 256-byte rows.- Arguments are validated before mutation. Each call copies the caller's view synchronously before returning its promise; later caller mutations are safe. SharedArrayBuffer-backed views are rejected. Invalid arguments, retired capabilities, frame-hook calls and queue overflow throw synchronously. Scheduled work may reject asynchronously; await or handle every promise.
- A packet is at most 256 KiB, with at most 4 MiB / 64 operations queued per version. Split larger loads into sequential packets/texture regions and await them. Replays yield between packets. The 64 MiB CPU snapshot cap across all initialized tiers is separate from GPU allocation caps and queued copies; large multiple-tier content can be rejected rather than silently degraded.
statsis a reused, read-only view of CPU bytes, queued/peak bytes, attached consumer count, revision and maximum observed upload/replay CPU slice. It is not total heap or driver memory, or a whole-frame timing guarantee.- A resolved write has queued copies to that tier's still-live consumers. It is not a GPU completion fence. Writes preserve call order; initial/candidate replay is serialized with updates. One packet reaches all attached consumers before the next frame; a multi-packet load is not an atomic whole-resource change. Use a new manifest version for an atomic complete replacement. Media uploads invalidate held/temporal media history; post passes read the current image.
- The signal aborts on retirement/device loss/teardown; writers then reject even if retained by user code. Engine cleanup does not wait for a user initializer that ignores its signal. Consumers detach before GPU storage is destroyed. Author callbacks should still observe the signal and release their own work.
Resource uploads are covered by api: 1 and remain accepted in legacy api: 0 manifests. They do not make simulate, lit layers or item shader materials supported.
Candidate: surface (shells over one item)
A candidate part kind of api: 1: not covered by the stable matrix above and free to change before it is frozen. It installs and reports ready like the other kinds, and its status always carries the warning surface: candidate kind (api: 1 candidate; may change before it is frozen), from validateRayManifest on. FxStatus.state has no extra value for it.
| Part kind | Ray | ASCII | Wireframe | api: 1 state |
|---|---|---|---|---|
surface: engine-generated shells over one item; your WGSL decides each shell fragment |
Installed: shells drawn into the G-buffer, an engine-owned stand-in for traced rays | The item's base mesh, CPU hooks | The item's base mesh, CPU hooks | Candidate |
{ kind: "surface", name: "fur", fn: "strands", item: "creature", shells: 24, length: 0.15,
gravity: 0.35, density: 0.55, color: "#c98a4b" }
item: the scene item id (not"all"), resolved like a layer'splace.of: one that names no item, or one ambiguous across stages, fails the part withUnknown scene item …, and the item binding followssetStages. An item with no instance this frame (another stage) draws no shells; the state staysready.shells: 1 to 32 shells above the base surface. Shell 0 is the base, drawn as always and never passed to your function.length: the shells' total height in the item's normalised object units (the source is normalised to radius 1 before its transform), so it scales with the item.gravity(0 to 1, default 0): the tips droop along world −Y; the direction at heighthisnormalize(n + down · gravity · h).density(0 to 1, default 0.5),color(CSS, default#808080): the traced stand-in's coverage and colour (below).density: 0adds no stand-in.
surface: fn name(s: FxSurfaceIn, c: FxCtx) -> FxSurfaceOut
struct FxSurfaceIn { p: vec3f, rest: vec3f, n: vec3f, uv: vec2f, shell: u32, shells: u32, h: f32, item: u32, facing: f32 };
struct FxSurfaceOut { coverage: f32, albedo: vec3f, normal: vec3f, roughness: f32, occlusion: f32, emission: vec3f };
- Called once per shell fragment.
pis the shell point (world),restthe base surface's rest point under it in object space: the strand's root, the same on every shell, so a strand is the set of shells whose coverage at that root is 1.nis the base's world normal,uvits texture coordinate,shell1 toshells,h = shell / shells,itemthe instance's id asfxIdreports it.facingis |cos| of the angle between the base normal and the direction to the eye: near 0 the shells are seen edge on, at the silhouette, where a view ray crosses a long stretch of each shell's slab but samples it at one point. Raise the coverage there (and light it like the tips) or the silhouette shows the gaps between shells as a dark, jagged ring; the example doesmax(strand, (1 - smoothstep(0, 0.45, facing)) · …). coverage0 to 1 keeps the fragment by a hashed threshold that moves every frame (the TAA resolves it), so a soft edge antialiases and a sub-pixel strand still covers its share. There is no texture filtering in it: compute coverage procedurally (fxWorley3,fxNoise3) and the fur does not thin with distance.albedo(linear, 0 to 1),roughness,occlusion(0 to 1),emission(linear radiance, 0 to 60000) replace the base material's for that fragment; it is a dielectric, opaque fragment of the base triangle's material otherwise.normal(world) replaces the shading normal; a zero vector keeps the base's. Values are scrubbed as the other kinds' results are.- The ABI names
FxSurfaceInandFxSurfaceOutexist, and are reserved, only in a manifest that declares asurfacepart. - Rules: the entry cannot reach
fxDistance,fxSurfaceorfxId(the G-buffer is what the shell is drawn into) norfxVisible/fxShadow; lights,fxAmbient,fxSkyand the noise helpers work. A manifest with asurfacepart has novolumepart. The static work gate applies per shell fragment (one entry invocation, with a fixed charge for the generated fragment); a pixel runs at mostshellsof them.
Traced rays never run your WGSL. For each installed part the renderer adds a trace-only stand-in: the item's mesh pushed out along its normals by half of length, with a blended material of opacity density and colour color. Shadow rays take its fractional coverage (soft fur shadows on the floor and on the item, tips above it stay lit), reflections and the probe cache see it stochastically, and it is never rasterised.
The path tracer holds the hybrid picture wherever an item with shells, or its stand-in, is seen in a pixel or its 3 × 3 neighbours (the stand-in is rasterised into a mask for this, depth-tested against the hybrid's depth): the refined still keeps exactly the fur the hybrid frame drew (it neither disappears nor grows), while the rest of the picture refines as before. A hidden item has neither shells nor a stand-in. Each installed part keeps its own stand-in mesh for as long as it is installed: several parts on one item do not rebuild each other, and a part reinstalled with another length lets the old mesh go.
Limits of the candidate:
- The caller's unjittered targets (depth, distance, coverage) hold the base only: dots, layers and lenses meet the base silhouette, not the fur.
- Shells follow vertex normals: a flat-shaded mesh (split vertices) opens at its edges. A deforming item rebuilds its stand-in at every geometry revision.
- A held still frame does not run the entry again: animation that reads
c.time(wind) moves while the scene renders frames, not while it holds a picture. - Every triangle of the item gets shells; keep parts bare in WGSL (coverage 0 by
rest), as the example does for eyes and nose. - Example: the fur on motedrift.com is a
surfacepart.
Options
| Option | Default | |
|---|---|---|
stages |
the stages (required) | |
mode |
"ascii" |
how the objects are drawn: "ascii", "ray", "wireframe" or "custom" (see Render modes) |
glyphRenderer |
"auto" |
glyphs only: "auto", "webgpu", "gpu" or "canvas", what draws ASCII's characters and the effects' glyphs; live as scene.glyphRenderer |
renderer |
none | mode "custom" only: the renderer plugin, a registered id or a RendererPlugin |
plugins |
none | renderer plugins for this scene alone, before the page's under the same id |
ray |
{} |
how ray draws: quality, samples, exposure, toneMapping, floor, fallback, flare (see Ray; scene.setRay changes them while it runs) |
particleStyle |
{} |
independent emitters: size, bloom, focus, aperture, haze, sprites and adapter |
lights, shadows |
today's lights, none | the scene's lights (see Lights), and ASCII's shadow maps and floor shadow |
physics |
none | rigid bodies: gravity, floor, walls, colliders, grab (see Physics) |
orbit |
none | the view turned about the origin, { yaw, pitch } in degrees (see Orbit) |
particles |
16000 in ASCII and solid Ray, 40000 in Wireframe | the fewest particles drawing the objects; the scene adds more when objects cover more of the canvas (a big scale) and gives them back when they shrink (in ray, also as many as the solids' skins need) |
maxParticles |
200000 in ASCII, 48000 in solid Ray, 500000 on Wireframe GPU (50000 on Canvas) | the most particles; set it to particles for an exact count |
asciiScaleDensity |
true |
ASCII: an object larger on the screen than at its own size takes more samples (within maxParticles), so its surface stays as dense; false keeps each object at its share of particles (cheaper, a big object draws paler); live as scene.asciiScaleDensity |
hold, morph |
5, 3.8 | seconds a stage holds, and a morph takes; a stage can set its own hold |
autoplay |
true | move on by itself |
fontSize, lineHeight, fontFamily |
11, 14, a monospace stack | the character grid |
colors |
grey and blue | { text, accent } or a function; cssColors() reads CSS custom properties |
zoom, origin |
0.85, [0.5, 0.5] | size of a unit, and where the origin sits on the canvas |
camera |
12 | camera distance in units: larger is flatter |
light |
upper left, front | direction towards the light |
ramp |
.,:-=+*#%@ |
characters from dark to bright |
halo |
1 | the glyphs flickering around the objects and flying off them, 0 to 1 |
trails |
true | short trails behind fast particles |
smoke |
"rise" |
how the smoke moves in a morph: "rise" or "sideways" |
morphStyle |
"smoke" |
how a morph looks: "smoke", "direct", "swirl", "explode" |
interactive, pointerTarget |
true, the canvas's parent | clicks and pointer moves drop ripples (and grab and throw bodies, with physics) |
click |
"ripple" |
what a click does: ripples, "none", effects (explode(), holes(), shockwave()…), several in a list |
ambientRipples |
true | a ripple now and then on its own |
keepClear |
elements (or boxes) the scene keeps clear of, such as a heading over the canvas: the characters and the dots leave them, and in ray the solids fade under them on the screen | |
clearFloor |
0 | how much still shows over what keepClear keeps clear (0 to 1): a little lets the figures and the effects pass faintly under a heading, so the clear area does not read as a solid panel |
ambientFps |
30 | frames per second while nothing moves fast; the display's full rate during morphs and interaction |
reducedMotion |
"static" |
with the system's reduce motion, draw still frames (in ray the still frame is drawn again at the idle rate, so the path tracer refines it: nothing in it moves); "ignore" animates anyway. The system's setting is followed as it changes, without a rebuild: scene.still says which it is, and scene.reducedMotion changes this option on a running scene |
sliceLayout |
false | sample the stages again a few milliseconds at a time between frames, the stages on screen first, when the particles, the mode, the glyph size, the renderer or the size change (the picture keeps its points until the new ones are in, a few frames later); ray makes a new sky, and the surfaces of the stages not on screen, a slice at a time, and smoke spreads its warm-up over its first frames. The demo, with it on: no settings change makes a task over 50 ms on an M3 Max, the GPU 18–98 % busy with other work (a known issue aside: the Tornado scene, whose effect took 40–95 ms every frame, measured in the dots mode removed in 0.30.0). Off, every stage at once in the call |
onFrame |
called every frame with the time in seconds | |
onState |
called with the scene when stage, stageCount, paused or still change, whoever changed them: it needs no frame, so it keeps a page's text in step on a still or paused scene |
|
paused |
false |
start paused with one picture (scene.pause() alone never draws a first one) |
clock |
none (the time runs) | { time }: the scene's time fixed at time seconds, so two pictures of it can be compared: the stage that time selects, animations where they end, no time passing for the effects and the physics, the same random numbers every frame (scene.setTime moves it; there is no way back to the running time); { time, step }: a stepped clock, see The stepped clock) |
scene.mode says how the objects are drawn and scene.setMode("ascii" | "ray" | "wireframe" | "custom") changes it (setMode("custom", renderer) with a plugin) (in TypeScript a SceneMode; a scene made from options written inline without ray, no mode: "ray" and no ray options, is typed as before ray came, its mode a RenderMode, "ascii" | "wireframe": give ray: {} to switch it to ray later; a scene made from a SceneOptions variable, or held in a variable typed Scene, may be in ray, and its mode is a SceneMode). scene.particles, scene.maxParticles, scene.fontSize, scene.zoom, scene.morph and scene.morphStyle can be changed while the scene runs (scene.particles = undefined and scene.maxParticles = undefined give the mode's own back). scene.ready resolves when the sources, the physics world and, in ray, ray's side and device are there (one promise until one of them changes). Other methods: scene.ripple(x, y), scene.setColors(...), scene.refreshColors() (after a theme change), scene.zoom = 1.2, scene.resize(), scene.pause() and scene.resume() (no frame comes, Ray's refinement stops too; a picture that is up stays, drawn again once when something makes it stale; a scene paused before its first frame draws nothing, and the paused option starts one paused with a picture; scene.paused says so; scene time goes on, so the frame after resume() shows the time it is then, and goTo() while paused asks for a morph that waits for resume(), where show() puts the stage on the picture), scene.capture({ space, refined, samples }) (a promise of the next frame's picture: as displayed, 8-bit sRGB, or in ray the linear picture before the tone map, float RGBA premultiplied; in ray it can wait for the path tracer to refine it, refined: true: until stats().ray.refined, the hybrid's held picture at once where the path tracer is off), scene.setTime(seconds) (the time fixed there, as the clock option does: it cannot be undone; on a stepped clock a seek, below), scene.clock, scene.time, scene.frame and scene.step() (the stepped clock, below), and scene.stats(), which gives the grid, the particles in use, the points per stage, the density drawn, the frames drawn in the last second (fps), the time a frame takes (frameMs), whether the scene is resting at its ambient rate, what draws (backend) and, in ray, the GPU's time, the internal scale, the path tracer's samples and state, the probes and the solids (ray, which also says why ray fell back). Ray, lights, physics and the orbit add scene.ray, scene.setRay(options), scene.setLights(list), scene.setLight(i, partial), scene.shadows, item.material, item.body, scene.physics, scene.spawn(item), scene.remove(id) and scene.orbit.
A scene can also be written as JSON (schemas/scene.schema.json, which the package ships). sceneFromJson(doc) checks the document (no browser needed) and gives either:
- the options to make it with (
createScene(canvas, r.options), on a canvas ofr.camera.width×r.camera.heightCSS pixels), its camera, its render settings and its time; - or every error found, each with the field's JSON pointer.
A v2 stage item has id, optional shape, parent, transform and material, plus motion, visible, body and weights. weights is a list of 1 to 64 finite numbers passed to ItemSpec.weights, one for each morph target in the mesh's order; for example:
{ id: "face", shape: "sphere", weights: [0.5, 0.25] }
describe() writes an object's own weights back to its v2 document, so loading that document preserves them.
A hierarchy in Scene JSON
A version 2 object (a stage's item, and the object of an add operation) can have a parent, can be a group, and can be one node of a glTF file:
{
"version": 2,
"camera": { "position": [0, 1.6, 4.6], "target": [0, 0, 0], "fov": 40, "width": 640, "height": 480 },
"stages": [{
"items": [
{ "id": "crane", "transform": { "position": [0, -0.6, 0], "rotation": [0, 30, 0] }, "motion": { "spin": { "axis": [0, 1, 0], "speed": 10 } } },
{ "id": "mast", "parent": "crane", "shape": "box", "transform": { "position": [0, 0.7, 0], "scale": [0.12, 0.7, 0.12] } },
{ "id": "boom", "parent": "crane", "transform": { "position": [0, 1.4, 0], "rotation": [0, 0, 20] } },
{ "id": "arm", "parent": "boom", "shape": "box", "transform": { "position": [0.6, 0, 0], "scale": [0.6, 0.08, 0.08] } },
{ "id": "hook", "parent": "boom", "shape": { "gltf": "models/crane.glb", "node": "Hook" }, "transform": { "position": [1.2, -0.3, 0], "scale": 0.25 } }
]
}],
"lights": [{ "kind": "directional", "direction": [1, 1.2, 0.8] }],
"render": { "mode": "ray" }
}
parentis the id of an object of the same stage, before or after it in the list. The object'stransformis then in that object's own space, exactly asItemSpec.parent: turnboom(aset, a timeline trackitem:boom) and the arm and the hook go round with it.- A group is an object without a
shape(craneandboomabove). It has anid, an optionalparent, atransformand amotion; it draws nothing and has no body, somaterial,visible,bodyandweightson it are refused. - One node of a glTF file is the shape
{ "gltf": path, "node": index or name }: the node's own mesh, in the node's own space, asgltfTreegives a node its source. It is not fitted to the unit sphere, so it takes nonormalize(refused): where the whole model's fit is wanted, it is the transform of a group above its nodes, asgltfTreeItemsmakes one.nodeis the node's index in the file'snodes, or its name when one node alone has it. The file is fetched once for all the objects that name it, when the scene is drawn: loading the document fetches nothing. A node the file does not have, a name several nodes share and a node without triangles are errors then (scene.readyrejects, andcreateSceneFromJsonreturns the error with the field's pointer in its message). The node's skin and morph targets are not read: its mesh is drawn as the file has it, andweightsbeside such a shape is refused. - A child with a
bodyis carried at its composed place, as in any scene (a dynamic one is kinematic while it has a parent). - Refused, before anything is made, each at the object's
parentwith its JSON pointer and in the wordscreateSceneuses: a parent that is not an object of the stage (the error says so when it is one of another stage), an object that is its own parent, a cycle of parents (every object of the cycle is named), and more than 64 ancestors.
/stages/0/items/3/parent: the parent "bom" of "arm" is not an object of its stage.
/stages/0/items/2/parent: "boom" is its own ancestor (a cycle of parents).
/stages/0/items/1/body: an object without a shape is a group, which draws nothing and has no body: remove body, or give the object a shape.
scene.describe() writes a hierarchy as it is: a child with its parent and its own transform (the one item.transform reads, in its parent's space), a group as an object without a shape, an object made from a document's or an operation's { gltf, node } as that shape. Loading the document gives the same hierarchy, composed to the same matrices to the bit. What a document cannot say is reported in diagnostics, never written wrong:
kind |
What it says |
|---|---|
item-parent |
The object is written without its parent, with the transform that draws it on its own where it is now: its parent is not in the document (a source made by the page), or the object has more than 64 ancestors. |
item-skin |
The object has a skin (ItemSpec.skin). The document draws its mesh undeformed. |
item-morph |
The object is a glTF node with morph targets. The document draws it unmorphed, without weights. |
A tree loaded from a document or added by operations is written whole, and describe() stays complete. One the page made with gltfTreeItems(tree, { gltf: path }), which names the file each mesh node came from (A model as a tree), is written with the same hierarchy, transforms and meshes, but Scene JSON v2 cannot carry each node's glTF name and provenance: describe() lists them as unserializable and returns complete: false. Load the tree from a document to keep the description complete:
const doc = parseGltf(await (await fetch("/models/robot.glb")).arrayBuffer());
const { items } = gltfTreeItems(gltfTree(doc), { id: "robot", gltf: "models/robot.glb" });
const scene = createScene(canvas, { stages: [{ items }] });
const described = scene.describe(); // complete: false, with an `unserializable` diagnostic per node name/provenance
const again = sceneFromJson(described.document, { resolveUrl: (path) => new URL(path, location.href).href });
if (again.ok) createScene(otherCanvas, again.options); // the same hierarchy, composed to the same matrices, without glTF names/provenance
Without gltf, the tree's mesh nodes are sources the page made: describe() leaves them out as procedural-source, as it does any such source, and what hangs from one is written without its parent (item-parent).
In Scene JSON v2, a document that has physics needs physics.jointSolver: "chain" for a hinge's active drive, positive friction or positive damping, just as createScene does. With the solver omitted or set to "sequential", sceneFromJson refuses the document and points to each offending field, for example /stages/0/joints/0/drive. A complete valid hinge document is:
{
"version": 2,
"camera": { "position": [0, 0, 5], "target": [0, 0, 0], "fov": 40, "width": 640, "height": 480 },
"stages": [{
"items": [{ "id": "arm", "shape": "box", "body": { "mass": 0.2 } }],
"joints": [{
"id": "axle", "type": "hinge", "a": "arm", "anchor": [0, 0, 0], "axis": [0, 0, 1],
"drive": { "target": 0.2, "stiffness": 12, "damping": 0.05, "maxTorque": 7 },
"friction": 0.05, "damping": 0.02
}]
}],
"lights": [{ "kind": "directional", "direction": [1, 1, 1] }],
"physics": { "jointSolver": "chain" },
"render": { "mode": "wireframe" }
}
Zero-valued drive, friction and damping fields remain accepted with either solver.
The scene pauses while the canvas is off screen or the tab is hidden.
The stepped clock
clock: { time: 0, step: 1 / 60 } makes a stepped scene for reproducible animation: its time starts at time and moves only when scene.step(frames = 1) is called (1 to 600 frames a call). Each queued step advances the scene by exactly step seconds (k / 60 with k a whole number from 1 to 60, else a RangeError), is consumed by exactly one frame, and that frame is the only one on which the effects get a dt (exactly the step) and the physics world runs (exactly k fixed steps, onStep before each); tweens, morphs and autoplay run on the stepped time, and the random numbers are seeded by the frame's index (frame 0 draws what the fixed clock draws at the same time). Between two steps the scene is a fixed scene: frames keep coming (in ray the path tracer refines the still picture, capture({ refined: true }) works as it does), nothing moves and no CPU state changes. The same document and the same steps give the same transforms, bodies and CPU pictures bit for bit, and the same state as real time on the 1/60 grid.
scene.step() resolves with { frame, time } after the frame that consumed its last step; calls are serialized (Promise.all([scene.step(), scene.step()]) resolves frames 1 and 2 in order), wait for scene.ready (a step taken before the physics world is there would advance the time with no physics step), and reject with { kind, message }: "paused" (a pause rejects the steps queued), "destroyed", "load", "timeout" (a request at the head of the queue did not finish within 60 s per frame: a hidden page, a canvas of no size). scene.clock reads "real", "fixed" or "stepped"; scene.time and scene.frame read the last step applied. On a stepped scene, scene.setTime(seconds) and scene.seek(seconds) use the step queue for forward targets and resolve with { frame, time }. The time must be on the step grid, at or after the clock's starting time.
A backward seek replays up to 36,000 frames from the original declarative setup and the complete operations log. Success updates the original scene and canvas and discards the operations after the target. Item handles for IDs present on both sides continue to work. Scene observers and cues on the retained timeline stay subscribed. Advance with step() to continue on the new branch.
In-place rewind supports declarative scenes made with local primitives and built-in effects. An incomplete log, unrecorded edits, URL assets without retained bytes, renderer plugins and work still waiting at a frame boundary can cause { kind: "not-replayable" }. A newer seek supersedes one in progress, and destroy() releases its staging resources.
On a stepped scene:
- the pointer is ignored (
interactiveand the physicsgrabread false; a director triggers effects and ripples by the API); - ambient ripples and the halo's flying glyphs are off;
reducedMotion: "static"is not followed;sliceLayoutis ignored (every stage is prepared at once).
A canvas resize, a font's readiness, scene.resize(), scene.fontSize and scene.zoom are measured as they arrive but applied only at the next step's frame, before it is drawn (until then scene.fontSize and scene.zoom read what the frames draw with), and the DOM colliders of physics.colliders are measured again only on stepped frames. Each is recorded as a system operation in the scene's internal log (the director's replay, 0.40, re-applies them at the same frame).
Exporting a video
recordVideo turns a scene into an MP4 file, in the browser, with no server and no other library: it steps the scene frame by frame on its stepped clock, reads each picture, encodes it with the browser's own encoder (WebCodecs) and writes the file itself. A frame may take as long as it needs (a path-traced one, seconds): the video still plays at the scene's speed.
It is a module of its own, mote-engine/video: a page that does not import it downloads none of it.
import { createScene, box } from "mote-engine";
import { recordVideo } from "mote-engine/video";
// A stepped clock: the time moves only when a step is taken, 1/60 s each.
const scene = createScene(canvas, {
clock: { time: 0, step: 1 / 60 },
stages: [{ items: [{ id: "crate", source: box() }] }],
});
await scene.ready;
// What happens in the five seconds: here, a turn.
await scene.setTimeline({
version: 1, duration: 5,
tracks: [{ target: "item:crate", property: "rotation", keys: [{ t: 0, v: [0, 0, 0] }, { t: 5, v: [0, 180, 0], ease: "inOut" }] }],
});
const video = await recordVideo(scene, { seconds: 5, fps: 30, background: "#ffffff" });
// video.frames 150, video.seconds 5, video.codec such as "avc1.64001f", video.blob: the file
const link = document.createElement("a");
link.href = URL.createObjectURL(video.blob);
link.download = "scene.mp4";
link.click();
URL.revokeObjectURL(link.href);
The first picture is the scene as it stands at the frame it starts from; picture N is the scene's frame from + N × (clock rate / fps). When the promise resolves the scene stands at the last frame recorded, and can be stepped, captured or recorded again. Nothing else may step the scene while it records.
The picture is the canvas's, in device pixels: the canvas's CSS size times the pixel ratio is the video's size. A canvas is transparent where the scene draws nothing and a video has no transparency, so the picture is put over background. An odd width or height loses its last column or row (H.264 pictures have even sides; the other codecs are given the same picture).
Options (all optional but the length):
| Option | Default | Meaning |
|---|---|---|
seconds |
— | The video's length, rounded to whole frames. Give this or to. |
from |
the scene's frame | The scene's frame the video starts at (scene.frame's count). The scene is taken there first: ahead by stepping; behind by replaying the scene from its setup, which only a scene that can be replayed does (see the stepped clock). |
to |
— | The scene's last frame recorded, included. Give this or seconds. |
fps |
the clock's rate | Frames a second. It must divide the clock's rate: on a 60 Hz clock 60, 30, 20, 15, 12, 10…; every rate / fps-th frame of the scene is a picture. |
codec |
"avc" |
"avc" (H.264: it opens everywhere, video editors included), "vp9" or "av1", all in an MP4 file. |
bitrate |
0.2 bit a pixel a frame, from 1 to 80 Mbit/s | Bits a second asked of the encoder (12.4 Mbit/s for 1920 × 1080 at 30 fps). |
keyframeInterval |
two seconds' worth | A key frame every this many pictures (a player seeks to key frames). |
background |
"#000" |
The opaque CSS colour behind the scene. |
refined, samples |
false, ray.samples |
Ray: every picture path traced to samples before it is read (capture({ refined: true })). Slow: each frame waits for its refinement, so a minute of video can take hours. Without it Ray records its real-time picture. |
timeoutMs |
60000 | The longest one picture may take to be drawn and read. |
signal |
— | An AbortSignal: aborting rejects with its reason (an AbortError by default). |
onProgress |
— | Called with { frame, frames } after each picture is handed to the encoder. |
It resolves with { blob, mimeType, codec, width, height, fps, frames, seconds, bytes, hardwareAcceleration }: blob is the file (video/mp4), mimeType its type with the codec (video/mp4; codecs="avc1.640028"), codec the codec string of the stream as the encoder made it (its own profile and level), hardwareAcceleration the encoder that was asked of the browser (below).
Limits.
- The scene must have a stepped clock (
clock: { time, step }): on a real or fixed clockrecordVideorejects with aTypeErrorthat says so.fpsthat does not divide the clock's rate is aRangeError. - At most 10 000 pictures a recording, over at most 36 000 frames of the scene: record a longer video in parts.
- At most 16 777 216 pixels a picture; in Ray at most the 5.2 million it draws (a larger canvas would be a smaller picture enlarged).
- The canvas must be on screen and the page visible: a scene draws no frame while hidden, and the step it waits for times out.
- The canvas must keep its size while recording.
- No audio. One video track, constant frame rate. No transparency.
- The file is made in memory: the encoded video (not the raw frames) is held until it resolves. The encoder's queue is waited for, so only a few raw pictures exist at a time.
- The browser's software encoder is asked for first, and the browser's own choice (possibly a hardware encoder) only where it has no software one for the codec at that size. The recording says which:
hardwareAccelerationis"prefer-software"or"no-preference". Measured in Chrome with"prefer-software", H.264 bytes are identical across runs up to 640 × 360; at 720p and above the browser's encoder output can vary between runs even when frames and timing are equal. With"no-preference", two recordings may likewise differ (a hardware encoder does not promise the same output twice). There is no option to ask for a hardware encoder: a recording is not in a hurry. - The colours are the ones the browser's encoder writes for an sRGB picture (in Chrome: BT.709, full range), named in the file so that players and editors read them back as they were.
Browsers. It needs WebCodecs' VideoEncoder: Chrome and Edge 94 or later (H.264, VP9 and AV1, each where the browser and the machine encode it), Safari 16.4 or later for the codecs it encodes (H.264 on every Mac and iPhone), Firefox 130 or later on desktop. Before the first frame recordVideo asks the browser whether it encodes the codec at this size: where it does not, it rejects with a NotSupportedError whose message names the codecs it can (It can encode: "vp9", "av1"); where there is no VideoEncoder at all, with a NotSupportedError that says that.
However a recording ends (an abort, an error of the encoder, a scene paused or destroyed: the scene's own { kind, message }), the encoder and every frame are closed and the scene is left usable, at the frame it had reached.
From the command line
mote-engine video records a Scene JSON document in headless Chrome and writes an MP4. The mote-engine alias has the same subcommand. Chrome is found through CHROME_PATH or the usual installation places.
# Five seconds at 30 fps, with model and map paths relative to the current directory.
mote-engine video scene.json --seconds 5 --fps 30 --root . --out shot.mp4
# A guide video and its uncompressed first and last frames for an AI video model.
mote-engine video scene.json --preset ai-video --stills --out guide.mp4
# Portrait 1080p: 1080 × 1920, still at 24 fps.
mote-engine video scene.json --preset ai-video --hd --aspect 9:16 --seconds 8 --out portrait.mp4
--look clay requests a neutral matte guide; the equivalent director option is look: "clay". Bundle references select muted subject colours, inherited by every generated node of a glTF tree. Lights, shadows, geometry and material sidedness are kept. Emissive is zeroed and transmission and clearcoat are set to 0. Opaque materials become opaque clay; MASK and BLEND materials keep their alpha mode, cutoff, opacity factor and base-colour texture alpha (the texture's RGB is ignored), so their coverage is unchanged.
Starting with 0.56, clay also replaces the source fill materials of { "svg": "mark.svg", "depth": 0.1 } shapes. Multiple fills become the same neutral matte (or the subject's muted colour), while geometry, sidedness and per-fill opacity stay intact. With an SVG scene loaded in the director, export it with:
{ "name": "svg-guide", "seconds": 1, "stills": true, "look": "clay" }
Pass these arguments to render_video; the session returns to its original SVG fills afterwards.
Clay applies only to that render: afterwards a director session returns to its original scene and materials. describe_shot and the bundle's prompt files still describe the original document, including glass, metal and emissive materials rather than their temporary clay substitutes. The current implementation rejects Gaussian splats, and material-changing director histories must be cleared by reloading the scene.
Give --seconds, or --from and --to (the last scene frame is included). The starting frame defaults to 0. Other picture and encoding options are --fps, --width, --height, --mode ascii|ray|wireframe, --refined, --samples, --codec avc|vp9|av1, --bitrate and --background. --refined and --samples are Ray-only: in ASCII or Wireframe either is a usage error naming the selected mode. The width and height are the page canvas's size and therefore the picture's size; an odd side is cropped for the video as described above. --root locates model and environment-map files. The command and render_video sample the nearest stepped scene frame when a requested rate does not divide the clock's rate; direct recordVideo keeps its divisor rule.
A 1/24-second clock is not expressible on the stepped scene's whole-frame grid. At 24 fps from a 60 Hz scene, nearest-frame sampling therefore records positions 0, 3, 5, 8, 10, 13…: the steps alternate 3, 2 scene frames. The resulting 12.5 ms timing jitter can show as slight judder. For perfectly even motion use 30 or 60 fps, or 20/15/12 fps. The manifest records the exact positions as frames.positions and omits the misleading single render.stride for a sampled video.
The ai-video preset makes guide videos for AI video models that take a reference video and first/last frames. It fixes H.264 and 24 fps, chooses 1280 × 720 by default or 1920 × 1080 with --hd, and derives the bitrate from the duration: the smaller of a 12 Mbit/s quality ceiling and 90% of the byte-limit budget. The encoded file is checked again, so the limit is enforced even if the encoder overshoots its requested bitrate. The preset trades perfectly even motion for 24 fps compatibility.
--aspect |
720p (default) | 1080p (--hd) |
|---|---|---|
16:9 |
1280 × 720 | 1920 × 1080 |
9:16 |
720 × 1280 | 1080 × 1920 |
1:1 |
720 × 720 | 1080 × 1080 |
4:3 |
960 × 720 | 1440 × 1080 |
3:4 |
720 × 960 | 1080 × 1440 |
21:9 |
1680 × 720 | 2520 × 1080 |
A preset video lasts at most 30 seconds, is at most 50 MiB and has at least 17 frames. A different explicit frame rate or codec, an explicit bitrate, dimensions that contradict the selected geometry, an unsupported aspect, a longer duration or fewer frames is refused with a message naming the limit.
--stills writes <name>.start.png and <name>.end.png beside <name>.mp4. They are lossless PNGs of exactly capture() at the first and last recorded scene frames, at the canvas's full size and without video compression. In Ray both stills always equal capture({ refined: true }), whether or not --refined is given; that option controls refinement of the video frames, not the stills. These are the first/last images to supply with the guide video.
The destination is written only on success: encoding streams to temporary files in the destination's folder. Just before publication the command checks again that no target appeared unless --force was given, then renames the stills first and the video last, so the video's presence means the set is complete. A rename failure removes outputs renamed by that run. Chrome is closed and temporary output is removed on an error, SIGINT or SIGTERM. Existing video or still outputs require --force. Success prints one JSON summary with the paths, frame count, duration, size, codec, encoder and any fallback.
Exit codes are 0 for success; 2 for command-line, preset, Scene JSON or existing-output errors; 1 for Chrome, codec, recording or output failures; 130 for SIGINT and 143 for SIGTERM. A missing Chrome explains CHROME_PATH; an explicitly set CHROME_PATH naming a missing file is an error and is not ignored in favour of discovery. An unsupported codec names the encoders that Chrome supports; document diagnostics retain their JSON pointers. If Ray falls back because WebGPU is unavailable, the warning on stderr and the summary's fallback field say so explicitly.
From the director
After load_scene, the render_video tool takes the same length, rate, picture, codec, preset and still options, plus a required name and optional overwrite. It writes <out>/<name>/video.mp4; with stills: true, video.start.png and video.end.png; and video.json.
{
"name": "guide",
"seconds": 5,
"preset": "ai-video",
"stills": true
}
The answer contains those paths and the recording summary. The manifest includes the document, timeline, operations log, asset digests, engine version, requested and actual codec and size, frame rate, frames.count, seconds, bytes, hardwareAcceleration, preset and its limits, any fallback, and the stills' paths, frame times and refinement. For nearest-frame sampling, frames.positions records every sampled scene frame and render.stride is absent. render.refined and render.stillsRefined say what was actually refined, including when Ray fell back. Only one preview, sequence or video render runs at a time; other page-dependent calls answer busy meanwhile.
A bundle for AI video models
--bundle <dir> gathers everything a video model needs in one folder. It implies --preset ai-video and --stills; --aspect, --hd, --seconds/--from/--to, --mode and --refined work as they do for the preset. --style, --negative and --max-length go to the shot description. The flow is Blender or Scene JSON → mote → bundle → video model: the engine writes data only, calls no generation service and holds no service keys.
mote-engine video scene.json --seconds 5 --bundle handoff \
--style "cinematic, natural motion" --negative "no text, no watermark" \
--ref woman=references/face.png --ref car=references/car.jpg
The complete folder is:
handoff/
guide.mp4 # the guide video
start.png, end.png # its exact first and last scene frames
prompt.txt # describeShot().prompt
prompt-short.txt # describeShot().promptShort
shot.json # the whole shot description
refs/ # present only with references
1-woman.png # subject identity images, in the declared order
2-car.jpg
request.json # generic media roles and suggested parameters
bundle.json # engine/document/asset/video metadata and file digests
Each --ref <subject>=<image> names a scene object id and a PNG, JPEG or WebP file. There may be at most 9 references, each at most 20 MiB. The file's magic bytes, not just its extension, determine the accepted format. An unknown subject, an unreadable or unsupported image and a tenth reference are errors that name the offending input. The prompt ties every image to the same noun used for its scene subject: for example, The woman at the centre is the subject in reference image 1. A technical id uses its shape noun; a subject absent from the sampled frames is marked (appears later). These sentences are mandatory under --max-length: if they and the other mandatory prompt parts cannot fit, the command fails with the minimum length needed rather than dropping them. prompt-short.txt also includes a compact list such as reference images: 1 the woman, 2 the car when it fits; the short prompt omits that list where it does not.
request.json follows the published schemas/ai-video-request.schema.json (JSON Schema 2020-12). It records version: 1, the video's exact durationSeconds, aspectRatio and resolution, the prompts, and an ordered media list. The generic roles are:
| Role | File |
|---|---|
video_reference |
guide.mp4 |
start_image / end_image |
start.png / end.png |
image_reference |
one refs/ image per --ref, with its subject, in declaration order |
The uses field suggests two workflows. restyle lists video_reference (and image_reference when present): use the guide as a reference or for an edit, with the prompt and identity images, keeping its motion. keyframes lists start_image, end_image (and image_reference when present): generate from the first and last frames with the prompt and identity images. For example, a service that takes a reference video, first/last frames and reference images might map video_reference to its video_references field (or its video-edit input), the frame roles to start_image and end_image, and the identity entries to image_references. These names are examples, not a service dependency.
When describeShot resolves placeholders: true, prompt.txt and the request's full prompt contain the blocking-placeholder sentence, and uses.restyle also lists placeholders. This tells a restyle consumer to preserve figure paths, actions and timing but not copy stiff placeholder motion. The keyframes use is unchanged.
{
"version": 1,
"durationSeconds": 5,
"aspectRatio": "16:9",
"resolution": "720p",
"prompt": "Subject: woman … car … The woman at the centre is the subject in reference image 1. The car on the right is the subject in reference image 2.\nCamera: …\nKeep the guide video's composition and camera timing.",
"promptShort": "woman …; reference images: 1 the woman, 2 the car. Keep the guide video's composition and camera timing.",
"negative": "no text, no watermark",
"media": [
{ "role": "video_reference", "file": "guide.mp4" },
{ "role": "start_image", "file": "start.png" },
{ "role": "end_image", "file": "end.png" },
{ "role": "image_reference", "file": "refs/1-woman.png", "subject": "woman" },
{ "role": "image_reference", "file": "refs/2-car.jpg", "subject": "car" }
],
"uses": {
"restyle": ["video_reference", "image_reference"],
"keyframes": ["start_image", "end_image", "image_reference"]
}
}
From the director, pass bundle: true to render_video, with optional style, negative, placeholders, maxLength and refs: [{ subject, path }]. placeholders: true or false overrides the prompt's automatic blocking-placeholder choice; the command-line bundle accepts the same override as --placeholders true or --placeholders false. Reference paths must stay under the server's --root. The bundle is written as <out>/<name>/; the answer contains its paths and the parsed request.json, ready for an agent with access to a generation service.
{
"name": "handoff",
"seconds": 5,
"bundle": true,
"style": "cinematic, natural motion",
"refs": [{ "subject": "woman", "path": "references/face.png" }]
}
bundle.json includes the engine version, the document and asset digests, the video's recording fields, the options used, and every payload file's byte count and SHA-256 (the manifest itself is excluded). The bundle adds no timestamp fields and no absolute reference-source paths. Text, stills, copied references and request data are byte-identical across runs on the same scene and inputs. Measured in Chrome with the software H.264 encoder, guide bytes are identical across processes up to 640 × 360; at 720p and above the browser's encoder output can vary between runs while frame count, fps, duration and dimensions stay equal. Only guide.mp4, video.bytes, and the guide entry's bytes and sha256 in bundle.json vary with that output. video.hardwareAcceleration records the encoder policy, normally prefer-software, and any other value is explicitly visible there and in the command result.
The destination is staged privately and renamed only when the video, stills, prompt, references, request, manifest and scene restoration have all succeeded. An existing non-empty folder requires --force (an empty folder is accepted), and force replaces only a version-1 bundle made by this tool with no entries outside the bundle layout. A destination that is or contains the current directory, scene file, --root or a reference image is refused before rendering, using real paths so symlinks count. The old bundle moves aside until the new one is published and is restored on failure. MCP overwrite: true follows the same rules. An error, SIGINT or SIGTERM leaves no partial folder and closes Chrome. The preset's duration, frame-count, geometry and 50 MiB errors are unchanged.
muxMp4 is the file writer on its own, and needs no browser: given encoded pictures in order ({ data, key }, the first a key frame), their size, rate and codec string, and for H.264 the decoder configuration record WebCodecs gives (decoderConfig.description under avc: { format: "avc" }), it returns the file's bytes as parts, the index first so the file plays while it downloads (new Blob(muxMp4(input), { type: "video/mp4" })).
A still frame as text
renderText draws a source as plain text, without a browser:
import { renderText } from "mote-engine/text";
import { gltfSource } from "mote-engine/gltf";
console.log(renderText(gltfSource(bytes), { cols: 100, rows: 45, rotation: [20, -30, 0] }));
Live Director in an embedded scene
The application supplies intent batches on its own schedule. The runtime validates each batch synchronously, keeps up to 64 waiting batches per scene, and starts one at each drawing boundary. A receipt identifies the batch. Await applied(id) for its outcome.
import { createDirectorRuntime } from "mote-engine/director";
const director = await createDirectorRuntime(scene, { tickHz: 1 });
const receipt = director.intents([
{ op: "animate", target: "item:hero", property: "position", to: [0, 1, 0], seconds: 0.9 },
]);
if (receipt.ok) {
const outcome = await director.applied(receipt.id);
console.log(outcome);
}
observation() returns an owned scene description or changes since the previous call, with scene events. Each packet is capped at 64 KiB of UTF-8. After a packet marked truncated, the next call attempts a full description. stop() cancels waiting intents. A successful backward seek stops the attached Director, so attach a new one to continue on the new branch.
Code backdrop
import { createCodeBackdrop } from "mote-engine/backdrop";
const backdrop = createCodeBackdrop(canvas, {
keepClear: () => document.querySelectorAll(".hero > *"), // the code keeps clear of the heading
snippets: [myCode], // C# by default
keywords: ["fn", "let", "mut", "pub"], // the language's keywords
});
Columns of code cycle on their own clocks: readable, swept into glyphs (identifiers first, keywords and punctuation last), scrambled, then decoded into the next snippet. Keywords are drawn in the accent, strings and numbers in colors.string.
Performance
Applications can provide particleStyle.adapter to replace the emitter output device while
keeping the simulation and effects. stats().backend identifies the concrete
device; the existing glyphRenderer flag remains compatible. Native adapters are experimental; effect support depends on the host application.
glyphRenderer: "auto" | "webgpu" | "gpu" | "canvas" chooses what draws ASCII's characters and the effects' glyphs. "auto" (the default) uses WebGPU only when this scene already acquired a live device for Ray or Wireframe. A plain ASCII scene stays on WebGL2, then Canvas2D: it fetches no glyph WebGPU chunk and requests no device. "webgpu" explicitly requests WebGPU, with WebGL2 and Canvas2D fallbacks when unavailable or lost. "gpu" selects WebGL2 with Canvas2D fallback; "canvas" selects Canvas2D. Change it live with scene.glyphRenderer; reading it or stats().glyphRenderer reports "webgpu", "gpu" or "canvas". In ASCII, stats().backend identifies webgpu, webgl2 or canvas2d.
WebGPU glyphs load separately from Ray and share an existing Ray or Wireframe device. scene.ready and scene.capture() wait for the selected glyph pen’s preparation. The glyph atlas preserves coloured ink, transparency, draw order and integer pixel placement. Destroying a scene frees its glyph buffers, textures and canvas context; the last glyph-only user also releases the shared device. A device still owned by Ray remains available to other scenes. useGpu(false) makes the default glyph renderer use Canvas2D; an explicit "webgpu" or "gpu" overrides that default. Explicitly scaled effect glyphs retain their existing Canvas2D path. Standalone glyphPen() retains its WebGL2/Canvas2D default; { webgpu: true } opts into the same WebGPU preference.
In ray the CPU's frame is the particles (the skin, the effects' matter) and the scene's bookkeeping; the skins' presence grids are dilated on the GPU, every one that changed the same frame, and only the objects whose particles' skin changed are marked again. The GPU's frame is the tracing and the passes at the canvas's resolution, which auto holds by the internal resolution and the lighting tier; on this scene and this machine it settles at lowest (one shadow ray a pixel, no reflection in the catcher, a third to a half of the resolution per side), and under a heavier load still auto takes its last resort, the whole frame at half the canvas's pixels per side. A still picture is refined by the path tracer with what one frame's budget leaves, a sample spread over up to 256 frames on large canvases, painted at the scene's idle rate.
Memory
destroy() (and the function the page effects return) stops the frames, removes every listener and observer, and releases the glyph atlases and the WebGL context at once rather than at the next garbage collection: browsers keep only a few WebGL contexts alive, and an app that mounts and unmounts effects (a theme switched on and off) must not pile them up. Caches are bounded (glyph atlases refill when full, colours are capped), and every effect keeps its state in fixed-size pools.
In ray the GPU holds about 236 bytes a device pixel at high: the full-resolution targets 141 (the denoiser's accumulation among them, and the 8 of the light that glass lets through to the particles behind it), the denoiser's spatial stage 72 × the internal scale² (63 at high's largest, 72 at ultra), the held picture's copies 8, the path tracer's mean 24, and 8 more when the environment is the background. A canvas past 5.2 million device pixels (MAX_PIXELS, a fixed ceiling) is drawn at that size and stretched to the canvas, its projection kept (stats().ray.output says the share per side), so at high ray's frame holds about 1.23 GB at most:
| Canvas (device pixels) | Pixels | Drawn at | Memory at high |
|---|---|---|---|
| 1920 × 1080 | 2.07 M | whole | 0.49 GB |
| 2560 × 1440 | 3.69 M | whole | 0.87 GB |
| 2880 × 1800 | 5.18 M | whole | 1.22 GB |
| 3840 × 2160 | 8.29 M | 0.79 a side (5.2 M) | 1.23 GB |
Textures and models add their own (Heavy models).
scene.capture() also allocates temporary readback storage and the pixel array it returns, on demand. Those capture buffers are separate from the frame-target estimates above.
Effect reference
All controls below can be updated with effect.set({ parameter: value }). Appearance and support depend on the render mode. Numeric limits describe the recommended ranges for controls.
wind
| Parameter | Default | Range / choices |
|---|---|---|
strength |
1 |
0–3 |
angle |
0 |
-180–180 ° |
erosion |
1 |
0–3 |
gusts |
true |
true / false |
streaks |
true |
true / false |
vortex
| Parameter | Default | Range / choices |
|---|---|---|
style |
air |
air, water, energy |
strength |
1 |
0–3 |
radius |
1.1 |
0.2–3 |
x |
0.5 |
0–1 |
y |
0.5 |
0–1 |
core |
0.18 |
0.05–0.6 |
inflow |
1 |
0–3 × |
density |
1 |
0–3 × |
spin |
cw |
cw, ccw |
trail |
1 |
0–3 × |
magnet
| Parameter | Default | Range / choices |
|---|---|---|
mode |
repel |
repel, attract, ferrofluid |
radius |
0.35 |
0.05–1.5 |
strength |
1 |
0–3 |
spikes |
10 |
3–24 |
explode
| Parameter | Default | Range / choices |
|---|---|---|
kind |
fireball |
fireball, dust, classic |
power |
1 |
0.2–3 |
recover |
2.2 |
0.5–8 s |
debris |
true |
true / false |
fireball |
1 |
0–3 × |
smoke |
1 |
0–3 × |
flash |
1 |
0–3 × |
light |
1 |
0–3 × |
shockwave |
true |
true / false |
holes
| Parameter | Default | Range / choices |
|---|---|---|
kind |
burn |
burn, punch |
radius |
0.22 |
0.05–0.8 |
heal |
5 |
0.5–20 s |
speed |
1 |
0.1–4 × |
char |
1 |
0–3 × |
smoke |
1 |
0–3 × |
light |
1 |
0–3 × |
shockwave
| Parameter | Default | Range / choices |
|---|---|---|
style |
blast |
blast, energy |
speed |
1.8 |
0.3–5 |
width |
0.14 |
0.03–0.5 |
power |
1 |
0–3 |
dust |
1 |
0–3 × |
distortion |
1 |
0–3 × |
condensation |
1 |
0–3 × |
gravity
| Parameter | Default | Range / choices |
|---|---|---|
strength |
1 |
0–4 |
repose |
33 |
15–50 ° |
chunks |
0.5 |
0–1 |
dust |
1 |
0–3 |
bounce |
0.25 |
0–0.9 |
cycle |
0 |
0–10 s |
jelly
| Parameter | Default | Range / choices |
|---|---|---|
amplitude |
0.06 |
0–0.3 |
speed |
3 |
0–12 |
wavelength |
0.45 |
0.1–2 |
poke |
1 |
0–3 × |
damping |
2.2 |
0.2–8 /s |
blackHole
| Parameter | Default | Range / choices |
|---|---|---|
place |
beside |
beside, fixed |
x |
0.5 |
0–1 |
y |
0.5 |
0–1 |
strength |
1 |
0–3 |
radius |
1.4 |
0.3–3 |
duration |
8 |
2–20 |
size |
0.3 |
0.3–3 |
inclination |
80 |
0–90 ° |
tilt |
0 |
-180–180 ° |
diskInner |
3 |
1.5–8 Rs |
diskOuter |
14 |
6–24 Rs |
diskTemperature |
2100 |
1500–30000 K |
palette |
thermal |
thermal, lilac, blue |
hotspots |
0.7 |
0–2 |
turbulence |
1 |
0–2 |
spin |
1 |
-3–3 |
doppler |
0.15 |
0–1 |
rainbow
| Parameter | Default | Range / choices |
|---|---|---|
style |
spectrum |
spectrum, film, oil |
mode |
diagonal |
diagonal, radial, vertical, horizontal |
speed |
0.18 |
-1–1 |
scale |
1 |
0.2–5 |
saturation |
0.85 |
0–1 |
thickness |
500 |
60–900 nm |
drain |
1 |
0–1.5 |
swirl |
1 |
0–2 |
intensity |
1 |
0–1 |
glitch
| Parameter | Default | Range / choices |
|---|---|---|
intensity |
1 |
0–3 |
rate |
1 |
0–5 |
speed |
1 |
0–4 |
tear |
1 |
0–2 |
rgb |
0.7 |
0–2 |
blocks |
0.45 |
0–1 |
noise |
0.3 |
0–1 |
shake
| Parameter | Default | Range / choices |
|---|---|---|
amplitude |
0.05 |
0–0.3 |
decay |
0.6 |
0.1–3 s |
continuous |
0 |
0–1 |
frequency |
12 |
1–40 Hz |
axis |
both |
both, horizontal, vertical |
scanlines
| Parameter | Default | Range / choices |
|---|---|---|
strength |
0.5 |
0–1 |
speed |
0.25 |
0–2 |
flicker |
true |
true / false |
mask |
1 |
0–1 |
curvature |
1 |
0–3 × |
vignette |
1 |
0–2 × |
hum |
1 |
0–2 × |
interlace |
true |
true / false |
wobble |
1 |
0–3 × |
beam |
0.6 |
0–1 |
dissolve
| Parameter | Default | Range / choices |
|---|---|---|
style |
burn |
burn, dust, classic |
mode |
loop |
loop, out, in |
period |
7 |
1–20 s |
edge |
0.07 |
0.01–0.3 |
char |
1 |
0–2 × |
glow |
1 |
0–2 × |
smoke |
1 |
0–2 × |
light |
1 |
0–2 × |
drift |
1 |
0–3 × |
angle |
-30 |
-180–180 ° |
hologram
| Parameter | Default | Range / choices |
|---|---|---|
color |
#5ab8ff |
CSS hex colour |
jitter |
1 |
0–3 |
scan |
1 |
0–1 |
flicker |
1 |
0–1 |
noise |
1 |
0–3 × |
transparency |
0.35 |
0–0.9 |
cone |
true |
true / false |
glow |
1 |
0–3 × |
matrix
| Parameter | Default | Range / choices |
|---|---|---|
color |
#3cff7a |
CSS hex colour |
rain |
true |
true / false |
density |
1 |
0–3 |
size |
1.7 |
0.5–6 |
speed |
1 |
0–4 |
trail |
1 |
0–3 |
intensity |
1 |
0–3 |
mutation |
1 |
0–4 |
head |
1 |
0–2 |
surface |
1 |
0–1 |
charset |
kana |
kana, binary, latin |
neon
| Parameter | Default | Range / choices |
|---|---|---|
color |
#31b5ff |
CSS hex colour |
pulse |
0 |
0–3 |
failing |
true |
true / false |
glow |
1 |
0–3 × |
segments |
6 |
1–32 |
warmup |
true |
true / false |
tubes |
one |
one, two |
color2 |
#2af5ff |
CSS hex colour |
tube |
outline |
outline, fill |
heatHaze
| Parameter | Default | Range / choices |
|---|---|---|
amplitude |
1 |
0–3 |
from |
0.2 |
0–1 |
speed |
1 |
0–3 |
scale |
1 |
0.25–3 |
laser
| Parameter | Default | Range / choices |
|---|---|---|
style |
physical |
physical, code |
color |
#ff3b6b |
CSS hex colour |
speed |
0.45 |
0–3 |
width |
3 |
1–12 |
intensity |
1 |
0–3 |
angle |
0 |
-90–90 ° |
light |
0.6 |
0–3 |
fire
| Parameter | Default | Range / choices |
|---|---|---|
intensity |
1 |
0–3 |
height |
1 |
0.2–3 |
speed |
1 |
0–3 |
turbulence |
1 |
0–2 |
palette |
natural |
natural, blue, green, violet, red, custom |
color |
#ff9d32 |
CSS hex colour |
source |
objects |
objects, ground, pointer |
volume |
null |
CSS hex colour |
light |
0 |
0–2 |
smoke
| Parameter | Default | Range / choices |
|---|---|---|
density |
1 |
0–3 |
opacity |
0.85 |
0–1 |
source |
objects |
objects, ground, pointer |
volume |
null |
CSS hex colour |
color |
#aeb6c1 |
CSS hex colour |
speed |
1 |
0–3 |
rise |
1 |
0–3 |
turbulence |
1 |
0–3 |
scale |
1 |
0.25–3 |
wind |
0 |
-2–2 |
windAngle |
0 |
0–360 ° |
rain
| Parameter | Default | Range / choices |
|---|---|---|
density |
1 |
0–4 |
angle |
12 |
-60–60 ° |
opacity |
0.35 |
0–1 |
source |
sky |
clouds, sky |
splash |
true |
true / false |
color |
#dedede |
CSS hex colour |
snow
| Parameter | Default | Range / choices |
|---|---|---|
style |
natural |
natural, classic |
density |
1 |
0–4 |
speed |
1 |
0–3 |
size |
1 |
0.25–3 |
wind |
0.15 |
-3–3 |
gusts |
0.65 |
0–2 |
flutter |
0.8 |
0–2 |
pile |
true |
true / false |
melt |
0.02 |
0–0.5 |
sparks
| Parameter | Default | Range / choices |
|---|---|---|
style |
classic |
classic, grinder, welding |
rate |
1 |
0–5 |
source |
edges |
edges, pointer, point, contact |
x |
0.5 |
0–1 |
y |
0.5 |
0–1 |
direction |
-90 |
-180–180 ° |
spread |
1 |
0–3 × |
speed |
1 |
0–3 × |
gravity |
1 |
0–3 × |
bursts |
1 |
0–3 × |
trail |
1 |
0–3 × |
curl |
1 |
0–3 × |
bounce |
1 |
0–2 × |
settle |
1 |
0–3 × |
flash |
1 |
0–3 × |
light |
1 |
0–3 × |
smoke |
1 |
0–3 × |
palette |
steel |
steel, stainless, hot, custom |
color |
#ffb347 |
CSS hex colour |
bokeh |
1 |
0–3 × |
fireworks
| Parameter | Default | Range / choices |
|---|---|---|
rate |
0.7 |
0.1–4 |
type |
festival |
festival, peony, chrysanthemum, multi, kamuro, willow, palm, ring, crossette, senrin, strobe, niagara |
intensity |
1 |
0.2–3 |
finale |
30 |
0–120 s |
starfield
| Parameter | Default | Range / choices |
|---|---|---|
speed |
0.6 |
0–3 |
warp |
false |
true / false |
count |
420 |
0–3000 |
size |
1 |
0.25–8 |
brightness |
1 |
0–3 |
twinkle |
0.35 |
0–1 |
color |
#e8f0ff |
CSS hex colour |
bubbles
| Parameter | Default | Range / choices |
|---|---|---|
rate |
1 |
0–5 |
source |
ground |
objects, ground, pointer |
size |
1 |
0.25–3 |
speed |
1 |
0–3 |
rise |
1 |
0–3 |
wobble |
1 |
0–3 |
opacity |
0.75 |
0–1 |
iridescence |
0.65 |
0–1 |
color |
#e6f3ff |
CSS hex colour |
wind |
0 |
-2–2 |
windAngle |
0 |
0–360 ° |
water
| Parameter | Default | Range / choices |
|---|---|---|
level |
0.8 |
0.3–0.98 |
waves |
1 |
0–3 |
speed |
1 |
0–4 |
scale |
1 |
0.25–3 |
opacity |
0.7 |
0–1 |
reflection |
true |
true / false |
reflectivity |
0.8 |
0–1 |
distortion |
1 |
0–3 |
glints |
1 |
0–3 |
ior |
1.333 |
1–2.5 |
color |
#3fa7ff |
CSS hex colour |
lightning
| Parameter | Default | Range / choices |
|---|---|---|
interval |
3 |
0.5–10 s |
flash |
true |
true / false |
color |
#d8ecff |
CSS hex colour |
kind |
cloud-to-ground |
cloud-to-ground, cloud-to-cloud, forked, mixed |
branchiness |
0.5 |
0–1 |
restrikes |
2 |
0–4 |
slowmo |
1 |
0.5–10 × |
confetti
| Parameter | Default | Range / choices |
|---|---|---|
rate |
1 |
0–5 |
burst |
80 |
0–300 |
source |
sky |
sky, cannons |
interval |
2.5 |
0.5–10 s |
shape |
mixed |
mixed, rectangles, strips, discs, squares |
palette |
rainbow |
rainbow, party, pastel, gold, custom |
color |
#ff4f8b |
CSS hex colour |
size |
1 |
0.3–3 × |
speed |
1 |
0–3 × |
flutter |
1 |
0–3 × |
tumble |
1 |
0–3 × |
wind |
0 |
-3–3 m/s |
pile |
true |
true / false |
linger |
6 |
0–30 s |
aurora
| Parameter | Default | Range / choices |
|---|---|---|
intensity |
1 |
0–2 |
speed |
0.15 |
0–1 |
angle |
0 |
-180–180 ° |
rotation |
0 |
-180–180 ° |
waveSpeed |
1 |
0–3 |
raySpeed |
1 |
0–3 |
bands |
4 |
1–6 |
light |
1 |
0–2 |
colorMix |
1 |
0–1 |
fog
| Parameter | Default | Range / choices |
|---|---|---|
density |
0.6 |
0–1 |
speed |
0.12 |
0–1 |
height |
0.55 |
0.1–1 |
turbulence |
1 |
0–2 |
color |
#c4cdd3 |
CSS hex colour |
tornado
| Parameter | Default | Range / choices |
|---|---|---|
x |
0.3 |
0–1 |
width |
0.9 |
0.2–2.5 |
taper |
0.15 |
0.05–1 |
bend |
0.5 |
0–2 |
spin |
0.6 |
0–3 |
wander |
0.3 |
0–2 |
pull |
1 |
0–3 |
debris |
1 |
0–4 |
speed |
1 |
0–3 |
density |
1 |
0–2 |
detail |
1 |
0–2 |
flow |
1 |
0–3 |
sceneLight |
1 |
0–2 |
ground |
1 |
0.35–1 |
color |
#8e9aaa |
CSS hex colour |
debrisColor |
#52575e |
CSS hex colour |
clouds
| Parameter | Default | Range / choices |
|---|---|---|
style |
overcast |
overcast, cumulus, layers |
cover |
0.5 |
0–1 |
speed |
0.25 |
0–2 |
height |
0.6 |
0.1–1 |
scale |
1 |
0.3–3 |
detail |
1 |
0–2 |
thickness |
1 |
0–2 |
light |
1 |
0–2 |
sceneLight |
1 |
0–2 |
sunAngle |
-135 |
-180–180 ° |
color |
#9aa7b8 |
CSS hex colour |
nebula
| Parameter | Default | Range / choices |
|---|---|---|
density |
1 |
0–3 |
glow |
1 |
0–4 |
dust |
0.5 |
0–3 |
filaments |
1 |
0–2 |
scale |
1 |
0.25–4 |
speed |
0.05 |
0–1 |
seed |
1 |
0–9999 |
color |
#ff4fa3 |
CSS hex colour |
color2 |
#7a5cff |
CSS hex colour |
volume |
null |
CSS hex colour |
meteors
| Parameter | Default | Range / choices |
|---|---|---|
rate |
0.6 |
0–4 |
speed |
1 |
0–4 |
size |
1 |
0.25–10 |
trail |
1 |
0–3 |
intensity |
1 |
0–3 |
angle |
145 |
-180–180 ° |
spread |
12 |
0–90 ° |
fragmentation |
0.35 |
0–1 |
palette |
natural |
natural, ice, ember, custom |
color |
#78d5ff |
CSS hex colour |
light |
0 |
0–2 |
drip
| Parameter | Default | Range / choices |
|---|---|---|
rate |
1 |
0–5 |
speed |
1 |
0–3 |
size |
1 |
0.25–8 |
gravity |
1 |
0–3 |
opacity |
0.7 |
0–1 |
splash |
1 |
0–2 |
trail |
0.35 |
0–2 |
wind |
0 |
-2–2 |
color |
#bed1dc |
CSS hex colour |
halo
| Parameter | Default | Range / choices |
|---|---|---|
color |
#31b5ff |
CSS hex colour |
size |
0.16 |
0.05–1.2 |
intensity |
1 |
0–2 |
pulse |
0.35 |
0–3 |
rays |
0.5 |
0–1 |
spin |
6 |
-60–60 °/s |
rim |
0.5 |
0–1 |
orbit
| Parameter | Default | Range / choices |
|---|---|---|
count |
40 |
4–200 |
radius |
1.15 |
0.3–3 |
speed |
0.6 |
-3–3 |
tilt |
18 |
-90–90 ° |
bands |
3 |
1–5 |
rotation |
0 |
-180–180 ° |
eccentricity |
0.15 |
0–0.7 |
precession |
0.12 |
-1–1 |
trail |
0.8 |
0–3 |
size |
1 |
0.25–10 |
intensity |
1 |
0–3 |
color |
#31b5ff |
CSS hex colour |
disintegrate
| Parameter | Default | Range / choices |
|---|---|---|
amount |
0.38 |
0–1 |
angle |
160 |
-180–180 ° |
cut |
180 |
-180–180 ° |
rate |
1 |
0–4 |
shards |
0.18 |
0–1 |
speed |
1 |
0–4 |
erosion |
0 |
0–0.25 |
size |
1 |
0.25–6 |
turbulence |
1 |
0–3 |
gravity |
0.45 |
0–2 |
opacity |
0.85 |
0–1 |
ragged |
1 |
0–3 |
breathe |
0.06 |
0–0.4 |
ground |
true |
true / false |
metal |
true |
true / false |
dust |
#c6ccd5 |
CSS hex colour |
calm |
0.15 |
0–1 |