Spaces:
Running
Running
Download src/render/view.js from VectorW/xlerobot-sim: direct link, hf CLI and curl.
- Browser
- Download file 58.2 kB
-
https://huggingface.co/spaces/VectorW/xlerobot-sim/resolve/main/src/render/view.js
- Command line
-
hf download hf://spaces/VectorW/xlerobot-sim/src/render/view.js
-
curl -L -o view.js https://huggingface.co/spaces/VectorW/xlerobot-sim/resolve/main/src/render/view.js
58.2 kB
// three.js views of the simulation. Geoms are built from the compiled MuJoCo model and posed from
// data.geom_xpos / geom_xmat every frame, so every renderer style draws the same physics. The world keeps
// MuJoCo's z-up axes.
//
// Styles:
// - "toon": cel shading with ink outlines (toon.js) on a paper-coloured background;
// - "lit": PBR materials. Where the environment has a photographic room (tools/home, home.js) Lit draws that
// instead of the scenery's geoms: modelled and light-baked in Blender, the robot and the objects lit by probes
// captured from it. Where it has baked light (tools/bake_light.mjs, baked.js), a light map for the scenery,
// light probes and a soft shade from above for what moves, and furniture models in place of some scenery
// (dressing.json); elsewhere image-based lighting and soft shadows (after the Microduck simulator).
// The robot shows its real finish (materials.js);
// - "splat": the environment's 3D Gaussian splat from MuJoCo-GS-Web (Spark), with the robot and objects
// lit by the splat itself (an environment map rendered from it) and their shadows caught on its floor;
// - "pixel": pixel art (pixel.js) of the splat where the environment has one, of the Toon scene elsewhere.
//
// Environments with a splat also have a decor (tools/make_decor.py): a modelled stand-in for the splat that
// Toon and Lit show in place of MuJoCo-GS-Web's invisible collision boxes. Static geoms never move, so they
// are merged per material into a few meshes, with each geom's colour as a vertex colour.
//
// Walls (tall boxes in a body named like "walls") are kept apart: in the main view, a wall the camera is
// outside of is drawn as a low stub, so it never hides the room; the robot's cameras see whole walls.
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
import { OutputPass } from "three/addons/postprocessing/OutputPass.js";
import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js";
import { floorMaterial, lookFor, makeMaterial, robotLookFor, surfaceColour, worldUVs } from "./materials.js";
import { OCCLUDER, OUTLINED, PixelPass } from "./pixel.js";
import { OutlinePass } from "./toon.js";
import { GEOM, collectScenery, dressingMatrix, dressingTurn, geomMatrix, layoutLightmap } from "./statics.js";
import { MotionWatch, OCCLUSION_LAYER, bakeMoving, bakeScenery, loadBake } from "./baked.js";
import { download } from "../core/assets.js";
// A baked room stands on the page's own background: dark or light with the page's theme.
const BACKGROUND = { toon: 0xf1eee8, lit: 0xe3dfd8, splat: 0x202124, pixel: 0x0d1226, bakedDark: 0x1c1b1a, bakedLight: 0xe3dfd8 };
// What the robot's cameras see above the walls in a baked room, and what the room's reflections show
// there: the sky the bake lit it with (linear RGB, tools/bake_light.mjs).
const BAKED_SKY = [1.0, 0.98, 0.95];
// A baked room's tone mapping and exposure. AgX keeps the bake's soft gradations; the user preferred it, lit
// by the sky alone, to a sun with Khronos PBR Neutral (2026-11-17).
const BAKED_TONE = THREE.AgXToneMapping;
const BAKED_EXPOSURE = 1.6;
// Pixel over a splat lights the robot and the objects this much more: its palette deepens the mid greys,
// and they stand in a light scene without an ink line to set them off.
const PIXEL_GAIN = 1.2;
// Where the key light sits relative to the camera target, unless the environment says (its "lighting").
const KEY_OFFSET = [1.4, -1.1, 3.2];
/** Whether the page shows its dark theme: chosen (data-theme) or, unchosen, the system's. */
function darkTheme() {
const chosen = document.documentElement.dataset.theme;
return chosen ? chosen === "dark" : Boolean(window.matchMedia?.("(prefers-color-scheme: dark)").matches);
}
/**
* The rotation that shows an equirect sky made for a z-up world (Blender's, turned `degrees` about z) as three.js
* draws backgrounds: its lookup direction (x, y, z) -> (-x, z, y).
*/
function skyEuler(degrees) {
const turn = new THREE.Matrix4().makeRotationZ(THREE.MathUtils.degToRad(-degrees));
const axes = new THREE.Matrix4().set(-1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1);
return new THREE.Euler().setFromRotationMatrix(axes.multiply(turn));
}
export class SceneView {
constructor(canvas) {
this.canvas = canvas;
this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true, preserveDrawingBuffer: false });
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
this.renderer.shadowMap.type = THREE.PCFShadowMap;
this.renderer.shadowMap.autoUpdate = false; // drawn once per frame, see render()
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(45, 1, 0.02, 80);
this.camera.up.set(0, 0, 1);
this.controls = new OrbitControls(this.camera, canvas);
this.controls.enableDamping = true;
this.controls.maxPolarAngle = Math.PI * 0.495;
this.root = new THREE.Group();
this.scene.add(this.root);
this.#buildLights();
this.outline = new OutlinePass();
this.pixel = new PixelPass();
// 3DGS's resolution, as a fraction of the CSS resolution. Splats cost per pixel: at 66% a frame
// fills under half the pixels, about twice the frame rate, and the soft splats look much the same
// scaled up.
this.splatScale = 0.66;
// 3DGS shadows on the decor: a depth-only pass, then shadows on the nearest surface only.
this.catchers = {
depth: new THREE.MeshBasicMaterial({ colorWrite: false, transparent: true }),
shadow: new THREE.ShadowMaterial({ opacity: 0.3, transparent: true, depthWrite: false }),
};
this.meshes = []; // everything built for the scene
this.geoms = []; // the moving meshes, posed every frame
this.walls = []; // {mesh, stub, center, out}: walls cut down when the camera is outside them
this.views = [];
this.style = "lit";
this.splat = null;
this.home = null; // the environment's photographic room (home.js), drawn by Lit
this.drag = null;
this.#bindDrag();
this.#followTheme();
}
#owned = []; // geometries and materials of the current scene
#buildLights() {
// One key light casts the shadows in every style; each style adds its own fill. The key light's
// shadow box follows the camera target, so large rooms keep sharp shadows where you look.
this.key = new THREE.DirectionalLight(0xffffff, 2.4);
this.key.castShadow = true;
this.key.shadow.mapSize.set(2048, 2048);
Object.assign(this.key.shadow.camera, { left: -2.2, right: 2.2, top: 2.2, bottom: -2.2, near: 0.5, far: 12 });
this.key.shadow.bias = -0.0002;
this.key.shadow.normalBias = 0.002;
this.key.shadow.radius = 4;
this.scene.add(this.key, this.key.target);
// Lit: a cool fill and a warm rim, as in the Microduck simulator, and a room for reflections.
const lit = new THREE.Group();
const fill = new THREE.DirectionalLight(0xdfe8ff, 0.55);
fill.position.set(-2.0, 1.2, 1.8);
const rim = new THREE.DirectionalLight(0xffb366, 0.8);
rim.position.set(-0.5, 3.0, 1.6);
lit.add(fill, rim, new THREE.AmbientLight(0xffffff, 0.25));
// Toon: a warm sky over a greige ground, so shaded sides stay light.
const toon = new THREE.Group();
const sky = new THREE.HemisphereLight(0xfffaf2, 0xb9b2a7, 1.6);
sky.position.set(0, 0, 1);
toon.add(sky);
this.lights = { lit, toon };
this.scene.add(lit, toon);
const pmrem = new THREE.PMREMGenerator(this.renderer);
this.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
pmrem.dispose();
}
/**
* Build the view of a newly loaded scene. `robotRoots` are the robot's root body ids; `env` is the
* environment's registry entry; `cameras` the robot's camera definitions (robot.json). `colorSpaces`
* says how the rgba values of the robot and of the objects are meant: "srgb" (as MuJoCo shows them), or
* "linear" (MuJoCo-GS-Web's models, made in a viewer without colour management). `dressing` is the
* environment's models (dressing.json: furniture, appliances, objects), which loadDressing brings in for Lit.
*/
setScene(sim, { robotRoots = [], env = {}, cameras = {}, robot = null, colorSpaces = {}, dressing = null }) {
this.sim = sim;
this.env = env;
this.robot = robot;
this.colorSpaces = colorSpaces;
this.keyOffset = env.lighting?.key ?? KEY_OFFSET;
this.dressingList = dressing;
this.#dropLight();
this.#dropHome();
this.#disposeGeoms();
this.#buildGeoms(robotRoots);
this.#buildRobotCameras(cameras);
this.views = this.views.filter((n) => n in this.robotCameras);
this.#applyStyle();
}
/**
* The environment's baked light (tools/bake_light.mjs, src/render/baked.js), shown by Lit: a light map
* for the scenery, probes for what moves. Resolves to whether it applies to this scene.
*/
async loadLight(url) {
const layout = this.lightmapLayout;
this.#dropLight();
const bake = await loadBake(url, layout.hash);
if (!bake || this.lightmapLayout !== layout) {
bake?.dispose(); // baked for another layout, or the scene changed meanwhile
return false;
}
this.light = bake;
for (const mesh of this.meshes) {
const material = mesh.userData.lit;
if (!material || mesh.userData.role === "catcher") continue;
if (mesh.userData.geom !== undefined || mesh.userData.probed) bakeMoving(material, bake);
else if (mesh.geometry.attributes.uv1) bakeScenery(material, bake);
}
if (bake.meta.sun) this.#addSun(bake.meta.sun);
this.#applyStyle();
return true;
}
/**
* The environment's photographic room (tools/home/bake_home.py, home.js), drawn by Lit in place of the
* scenery's geoms. Resolves to whether it applies to this scene.
*/
async loadHome(url) {
const sim = this.sim;
const { HomeScene } = await import("./home.js");
const home = await HomeScene.load(url, sim);
if (this.sim !== sim) {
home.dispose();
return false;
}
this.#dropHome();
this.home = home;
this.root.add(home.root);
this.#applyStyle();
return true;
}
#dropHome() {
if (!this.home) return;
this.root.remove(this.home.root);
this.home.dispose(this.scene);
this.home = null;
}
/**
* The baked room's sun (tools/bake_light.mjs): a directional light whose irradiance is in the light
* map's units (both go through the same diffuse term), and its shadow map over the whole room, drawn
* again only when something moved. The walls cast none, as in the bake.
*/
#addSun({ direction, irradiance, color }) {
const sun = new THREE.DirectionalLight(new THREE.Color().setRGB(...color), irradiance);
const r = this.room ?? { x0: -3, x1: 3, y0: -3, y1: 3 };
const middle = new THREE.Vector3((r.x0 + r.x1) / 2, (r.y0 + r.y1) / 2, 1);
sun.position.copy(middle).addScaledVector(new THREE.Vector3(...direction), 10);
sun.target.position.copy(middle);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.bias = -0.0004;
sun.shadow.normalBias = 0.02;
sun.shadow.radius = 3;
// the shadow camera, fitted to the room's box as the sun sees it
const cam = sun.shadow.camera;
cam.position.copy(sun.position);
cam.lookAt(middle);
cam.updateMatrixWorld();
const box = new THREE.Box3();
for (const x of [r.x0, r.x1]) for (const y of [r.y0, r.y1]) for (const z of [0, 2.7]) box.expandByPoint(new THREE.Vector3(x, y, z).applyMatrix4(cam.matrixWorldInverse));
Object.assign(cam, { left: box.min.x, right: box.max.x, bottom: box.min.y, top: box.max.y, near: Math.max(0.1, -box.max.z - 0.5), far: -box.min.z + 0.5 });
cam.updateProjectionMatrix();
this.scene.add(sun, sun.target);
this.sun = sun;
this.sunWatch = new MotionWatch();
}
/**
* The environment's models (setScene's `dressing`; files under `base`), drawn by Lit: furniture and
* appliances in place of the scenery they stand in for, fitted to its bounds (statics.js,
* dressingMatrix), the appliances' doors on the doors' bodies (#addPartModel), and scanned objects on the
* objects' bodies, fitted to their shapes (#addObjectModel).
*/
async loadDressing(base) {
const list = this.dressingList;
const items = this.dressing;
if (!list || (!items?.length && !list.objects && !list.parts)) return false;
const { GLTFLoader } = await import("three/addons/loaders/GLTFLoader.js");
const loader = new GLTFLoader();
const models = {};
// only the models something here uses (a photographic room keeps the objects' alone)
const used = new Set([...(list.items ?? []), ...(list.parts ?? []), ...Object.values(list.objects ?? {})].map((x) => x.model));
await Promise.all(
Object.entries(list.models).filter(([name]) => used.has(name)).map(async ([name, m]) => {
const bytes = await download(`${base}${m.file}`);
models[name] = await loader.parseAsync(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), "");
}),
);
if (this.dressing !== items) return false; // the scene changed meanwhile
const owned = new Set();
items.forEach(({ item, box }, k) => {
if (box.isEmpty() || !models[item.model]) return;
const turned = new THREE.Group();
turned.matrixAutoUpdate = false;
turned.matrix.copy(dressingTurn(item));
turned.add(models[item.model].scene.clone(true));
turned.updateMatrixWorld(true);
const fit = dressingMatrix(item, new THREE.Box3().setFromObject(turned, true), box);
turned.matrix.copy(fit);
turned.updateMatrixWorld(true);
turned.traverse((o) => {
if (!o.isMesh) return;
o.castShadow = true;
o.receiveShadow = true;
o.userData = { role: "dressing", lit: o.material, dressing: k, probed: true };
owned.add(o.geometry);
owned.add(o.material);
for (const t of Object.values(o.material)) if (t?.isTexture) owned.add(t);
if (this.light) bakeMoving(o.material, this.light);
this.meshes.push(o);
});
this.root.add(turned);
this.dressingRoots.push(turned);
for (const mesh of this.meshes) if (mesh.userData.dressed === k) mesh.userData.replaced = true;
});
for (const part of list.parts ?? []) if (models[part.model]) this.#addPartModel(part, models[part.model].scene, owned);
for (const [name, { model }] of Object.entries(list.objects ?? {})) if (models[model]) this.#addObjectModel(name, models[model].scene, owned);
this.#owned.push(...owned);
this.#applyStyle();
return true;
}
/**
* A model (z up, in metres) drawn on object body `name` in place of its shapes: fitted to the shapes'
* bounds in the body's frame on each axis, posed with the body every frame (update). The shapes stay for
* the physics, for picking with the mouse, and for Toon and Pixel.
*/
#addObjectModel(name, scene, owned) {
const body = this.sim.id("body", name);
const shapes = this.geoms.filter((m) => m.userData.body === body && m.userData.role === "object");
if (body < 0 || !shapes.length) return;
const target = this.#bodyBounds(shapes);
const object = scene.clone(true);
const box = new THREE.Box3().setFromObject(object, true);
const scale = target.getSize(new THREE.Vector3()).divide(box.getSize(new THREE.Vector3()));
const shift = target.getCenter(new THREE.Vector3()).sub(box.getCenter(new THREE.Vector3()).multiply(scale));
const fit = new THREE.Matrix4().makeTranslation(shift.x, shift.y, shift.z).multiply(new THREE.Matrix4().makeScale(scale.x, scale.y, scale.z));
this.#attachModel(body, shapes, object, fit, owned);
}
/**
* A model (glTF: y up, front +z) of a moving part, an appliance's door (the dressing's `parts`), drawn on
* its body in place of the body's geoms whose names match the part's `geoms` (its panel): turned by its
* yaw and fitted to those geoms' bounds in the body's frame, as an item is to its region (dressingMatrix).
* The rest of the body stays as modelled: the handle the robot grasps, what is on the door's inside.
*/
#addPartModel(part, scene, owned) {
const body = this.sim.id("body", part.body);
const names = new RegExp(part.geoms);
const shapes = this.geoms.filter((m) => m.userData.body === body && names.test(this.sim.model.geom(m.userData.geom).name ?? ""));
if (body < 0 || !shapes.length) return;
const object = scene.clone(true);
const turned = new THREE.Group();
turned.matrixAutoUpdate = false;
turned.matrix.copy(dressingTurn(part));
turned.add(object);
turned.updateMatrixWorld(true);
const box = new THREE.Box3().setFromObject(turned, true);
turned.remove(object);
this.#attachModel(body, shapes, object, dressingMatrix(part, box, this.#bodyBounds(shapes)), owned);
}
/** The bounds of a body's geoms (meshes of this.geoms) in the body's frame. */
#bodyBounds(shapes) {
const { model } = this.sim;
const target = new THREE.Box3();
for (const m of shapes) {
const i = m.userData.geom;
const p = model.geom_pos.subarray(3 * i, 3 * i + 3);
const q = model.geom_quat.subarray(4 * i, 4 * i + 4);
const local = new THREE.Matrix4().compose(new THREE.Vector3(p[0], p[1], p[2]), new THREE.Quaternion(q[1], q[2], q[3], q[0]), new THREE.Vector3(1, 1, 1));
m.geometry.computeBoundingBox();
target.union(m.geometry.boundingBox.clone().applyMatrix4(local));
}
return target;
}
/**
* Draw `object` on body `body` (at `fit` in its frame), posed with it every frame (update), in place of
* `shapes`. They stay for the physics, for picking with the mouse, and for Toon and Pixel. As a moving
* thing it shades the baked room below it (the occlusion map, baked.js).
*/
#attachModel(body, shapes, object, fit, owned) {
const holder = new THREE.Group();
holder.matrixAutoUpdate = false;
holder.add(object);
holder.traverse((o) => {
if (!o.isMesh) return;
o.castShadow = true;
o.receiveShadow = true;
o.userData = { role: "dressing", lit: o.material, probed: true, moving: true };
owned.add(o.geometry);
owned.add(o.material);
for (const t of Object.values(o.material)) if (t?.isTexture) owned.add(t);
if (this.light) bakeMoving(o.material, this.light);
this.meshes.push(o);
});
this.root.add(holder);
this.dressingRoots.push(holder);
this.objectModels.push({ body, holder, fit });
for (const m of shapes) m.userData.replaced = true;
this.#poseObjectModels();
}
/** The models on moving bodies (objects, doors) where their bodies are now. */
#poseObjectModels() {
const { xpos: p, xmat: R } = this.sim.data;
for (const { body: b, holder, fit } of this.objectModels) {
holder.matrix.set(R[9 * b], R[9 * b + 1], R[9 * b + 2], p[3 * b], R[9 * b + 3], R[9 * b + 4], R[9 * b + 5], p[3 * b + 1], R[9 * b + 6], R[9 * b + 7], R[9 * b + 8], p[3 * b + 2], 0, 0, 0, 1).multiply(fit);
holder.matrixWorldNeedsUpdate = true;
}
}
#dropLight() {
this.light?.dispose();
this.light = null;
this.roomLight?.dispose();
this.roomLight = null;
if (this.sun) {
this.scene.remove(this.sun, this.sun.target);
this.sun.dispose();
this.sun = null;
}
}
/**
* The baked room's reflections: a cube map of it from the middle of the room, 1.3 m up, without the
* robot and the objects, under the sky it was baked with. Captured once, at the first frame that needs it.
*/
#captureRoom() {
const r = this.room;
const target = new THREE.WebGLCubeRenderTarget(128, { type: THREE.HalfFloatType });
const camera = new THREE.CubeCamera(0.05, 40, target);
camera.position.set(r ? (r.x0 + r.x1) / 2 : 0, r ? (r.y0 + r.y1) / 2 : 0, 1.3);
const saved = { environment: this.scene.environment, background: this.scene.background };
const hidden = [...this.geoms, ...this.objectModels.map((o) => o.holder)].filter((m) => m.visible);
for (const m of hidden) m.visible = false;
this.scene.environment = null;
this.scene.background = new THREE.Color().setRGB(...BAKED_SKY);
camera.update(this.renderer, this.scene);
Object.assign(this.scene, saved);
for (const m of hidden) m.visible = true;
const pmrem = new THREE.PMREMGenerator(this.renderer);
this.roomLight = pmrem.fromCubemap(target.texture).texture;
pmrem.dispose();
target.dispose();
}
#disposeGeoms() {
for (const r of this.dressingRoots ?? []) this.root.remove(r);
this.dressingRoots = [];
this.objectModels = [];
for (const mesh of this.meshes) this.root.remove(mesh);
for (const x of this.#owned) x.dispose();
this.#owned = [];
this.meshes = [];
this.geoms = [];
this.walls = [];
if (this.shadowCatcher) this.root.remove(this.shadowCatcher);
this.shadowCatcher = null;
}
#buildGeoms(robotRoots) {
const materials = new Map(); // moving geoms share materials by appearance
const scenery = collectScenery(this.sim, robotRoots, (i, role, matName, rgba, geometry) => this.#addMoving(i, role, matName, rgba, geometry, materials), this.dressingList);
// Where each surface lies in a light map (statics.js): baked light, where the environment has it.
this.lightmapLayout = layoutLightmap(scenery);
this.room = scenery.room;
this.dressing = scenery.dressing;
for (const g of scenery.meshCache.values()) this.#owned.push(g);
for (const group of scenery.groups) this.#addStatic(group);
for (const wall of scenery.walls) this.#addWall(wall);
for (const plane of scenery.planes) this.#addPlane(plane);
// what hangs on each wall goes when it is cut down (statics.js, attachedTo)
for (const mesh of this.meshes) if (mesh.userData.attached !== null && mesh.userData.attached !== undefined) this.walls[mesh.userData.attached].attached.push(mesh);
// In splat mode the floor is the splat's; this catches the robot's shadows on it.
this.shadowCatcher = new THREE.Mesh(new THREE.PlaneGeometry(40, 40), new THREE.ShadowMaterial({ opacity: 0.28 }));
this.shadowCatcher.receiveShadow = true;
this.shadowCatcher.position.z = 0.001;
this.shadowCatcher.visible = false;
this.#owned.push(this.shadowCatcher.geometry, this.shadowCatcher.material);
this.root.add(this.shadowCatcher);
}
/** A wall as its own mesh, and a low stub of it shown in its place when the camera is outside it. */
#addWall({ role, look, opacity, full, stub: stubGeometry, center, out }) {
const proxy = role === "proxy";
const make = (geometry, kind) => {
if (look?.map) worldUVs(geometry, look.size);
const options = { vertexColors: true, opacity, role: proxy ? "proxy" : "env" };
const lit = makeMaterial("lit", look, options);
const toon = makeMaterial("toon", look, options);
const mesh = new THREE.Mesh(geometry, lit);
mesh.matrixAutoUpdate = false;
mesh.castShadow = false;
mesh.receiveShadow = true;
mesh.userData = { role: proxy ? "proxy" : "env", lit, toon, casts: false, wall: kind };
this.#owned.push(geometry, lit, toon);
this.root.add(mesh);
this.meshes.push(mesh);
return mesh;
};
const mesh = make(full, "full");
const stub = make(stubGeometry, "stub");
stub.visible = false;
this.walls.push({ mesh, stub, center, out, attached: [] });
}
/** Walls the camera is outside of drawn as stubs, without what hangs on them; returns what puts them back. */
#cutWalls(camera) {
const cut = [];
const hidden = [];
const c = camera.position;
for (const w of this.walls) {
if (!w.mesh.visible) continue; // not shown in this style
if ((c.x - w.center.x) * w.out.x + (c.y - w.center.y) * w.out.y <= 0) continue;
w.mesh.visible = false;
w.stub.visible = true;
cut.push(w);
for (const m of w.attached) {
if (!m.visible) continue;
m.visible = false;
hidden.push(m);
}
}
return () => {
for (const w of cut) {
w.mesh.visible = true;
w.stub.visible = false;
}
for (const m of hidden) m.visible = true;
};
}
#addStatic({ role, look, opacity, parts, dressed = null, attached = null }) {
const geometry = mergeGeometries(parts, false);
for (const p of parts) p.dispose();
if (look?.map) worldUVs(geometry, look.size); // world-space UVs line textures up across boxes
const options = { vertexColors: true, opacity, role };
const lit = makeMaterial("lit", look, options);
const toon = makeMaterial("toon", look, options);
const mesh = new THREE.Mesh(geometry, lit);
mesh.matrixAutoUpdate = false;
// Walls and floors would shade whole rooms from a key light outside them; small things cost more
// in the shadow map than they add.
mesh.castShadow = role !== "proxy" && !look?.shell && !look?.small && opacity >= 0.5;
mesh.receiveShadow = true;
// Scenery a dressing model stands in for (statics.js) is not in the light map: lit by the probes, until
// the model is in (loadDressing) and Lit hides it.
mesh.userData = { role, lit, toon, casts: mesh.castShadow, dressed, probed: dressed !== null, attached };
this.#owned.push(geometry, lit, toon);
this.root.add(mesh);
this.meshes.push(mesh);
if (role === "decor" && !look?.small) {
// In 3DGS the decor stays as an invisible stand-in for the splat's surfaces, so the robot's shadows
// fall on the counters and walls too: it writes depth after the splat is drawn, then the front-most
// surface darkens where the shadow is (see #applyStyle).
const catcher = new THREE.Mesh(geometry, this.catchers.shadow);
catcher.matrixAutoUpdate = false;
catcher.receiveShadow = true;
catcher.renderOrder = 2;
catcher.visible = false;
catcher.userData = { role: "catcher" };
this.root.add(catcher);
this.meshes.push(catcher);
}
}
/** A plane: as far as MuJoCo draws it, and where there are walls also cut to the room (for baked light). */
#addPlane({ i, role, matName, rgba, room }) {
const { model } = this.sim;
const sx = model.geom_size[3 * i];
const sy = model.geom_size[3 * i + 1];
const look = lookFor(matName);
const make = (geometry, matrix, cut) => {
let lit;
let toon;
if (look) {
if (look.map) worldUVs(geometry, look.size);
const options = { color: surfaceColour(look, rgba), role };
lit = makeMaterial("lit", look, options);
toon = makeMaterial("toon", look, options);
} else {
lit = floorMaterial("lit");
toon = floorMaterial("toon");
}
const mesh = new THREE.Mesh(geometry, lit);
mesh.matrixAutoUpdate = false;
if (matrix) mesh.matrix.copy(matrix);
mesh.receiveShadow = true;
mesh.userData = { role, lit, toon, floor: cut ? "room" : "whole" };
this.#owned.push(geometry, lit, toon);
this.root.add(mesh);
this.meshes.push(mesh);
};
make(new THREE.PlaneGeometry(sx > 0 ? 2 * sx : 40, sy > 0 ? 2 * sy : 40), geomMatrix(this.sim.data, i), false);
if (room) make(room, null, true);
}
#addMoving(i, role, matName, rgba, geometry, materials) {
const { model } = this.sim;
const look = role === "robot" ? null : lookFor(matName);
if (look?.map && model.geom_type[i] === GEOM.BOX) worldUVs(geometry, look.size);
if (model.geom_type[i] !== GEOM.MESH) this.#owned.push(geometry);
const transparent = rgba[3] < 1;
// The robot's own finish in Lit and 3DGS (materials.js): its painted steel cart, its black plastic.
// Pixel keeps its model colours, which read better in a few pixels.
const finish = role === "robot" ? robotLookFor(matName) : null;
const key = `${role}|${look || finish ? matName : ""}|${rgba.map((v) => v.toFixed(3)).join(",")}`;
if (!materials.has(key)) {
const linear = this.colorSpaces?.[role] === "linear" && !look;
const color = linear ? new THREE.Color(rgba[0], rgba[1], rgba[2]) : surfaceColour(look, rgba);
const options = { color, opacity: transparent ? Math.max(rgba[3], 0.18) : 1, role };
const plain = makeMaterial("lit", look, options);
const lit = finish ? makeMaterial("lit", finish, { ...options, color: new THREE.Color(finish.color) }) : plain;
const set = { lit, toon: makeMaterial("toon", look, options), plain };
this.#owned.push(...new Set(Object.values(set)));
materials.set(key, set);
}
const { lit, toon, plain } = materials.get(key);
const mesh = new THREE.Mesh(geometry, lit);
mesh.matrixAutoUpdate = false;
mesh.castShadow = !(transparent && rgba[3] < 0.5);
mesh.receiveShadow = true;
mesh.userData = { geom: i, role, lit, toon, plain, body: model.geom_bodyid[i] };
this.root.add(mesh);
this.meshes.push(mesh);
this.geoms.push(mesh);
}
#buildRobotCameras(defs) {
this.#disposeCameraSparks();
this.robotCameras = {};
for (const [name, def] of Object.entries(defs)) {
const body = this.sim.id("body", def.body);
if (body < 0) continue;
const camera = new THREE.PerspectiveCamera(def.fovy ?? 70, 4 / 3, 0.01, 30);
camera.matrixAutoUpdate = false;
// Camera axes in the body frame: three.js cameras look along -z with +y up.
const f = new THREE.Vector3(...def.forward).normalize();
const u = new THREE.Vector3(...def.up).normalize();
const pitch = THREE.MathUtils.degToRad(def.pitch ?? 0);
const side = new THREE.Vector3().crossVectors(f, u).normalize(); // camera +x (right)
f.applyAxisAngle(side, pitch);
u.applyAxisAngle(side, pitch);
const local = new THREE.Matrix4().makeBasis(side, u, f.clone().negate());
if (def.pos) local.setPosition(...def.pos); // where on the body, in its frame
this.robotCameras[name] = { camera, body, local, label: def.label ?? name };
}
}
/**
* "toon", "lit", "splat" (falls back to lit without a splat) or "pixel" (of the splat, or of the Toon
* scene without one); onBytes reports the splat download.
*/
async setStyle(style, { onBytes } = {}) {
this.style = style === "simple" ? "toon" : style;
const splat = (this.style === "splat" || this.style === "pixel") && Boolean(this.env?.splat);
if (splat && this.style === "pixel") this.#applyStyle(); // the modelled scene in pixels while the splat downloads
if (splat) await this.#loadSplat(onBytes);
this.#applyStyle();
}
async #loadSplat(onBytes) {
const url = this.splatBase + this.env.splat;
if (this.splat?.userData.url === url) return;
this.#removeSplat();
// The page downloads the file: given a URL, Spark fetches it from a worker, whose requests do not
// carry the signed page URL that a private Space requires.
const bytes = download(url, onBytes);
bytes.catch(() => {}); // reported by the await below
const { SplatMesh, SparkRenderer } = await import("@sparkjsdev/spark"); // destructured: unused exports are left out
this.SparkRenderer = SparkRenderer;
const fileBytes = await bytes;
const current = () => Boolean(this.env?.splat) && this.splatBase + this.env.splat === url;
if (!current()) return; // the scene changed meanwhile
this.spark ??= new SparkRenderer({ renderer: this.renderer });
if (!this.spark.parent) this.scene.add(this.spark);
const splat = new SplatMesh({ fileBytes, fileName: this.env.splat });
// MuJoCo-GS-Web places its splats in a y-up three.js world; this world is z-up.
splat.rotation.set(Math.PI / 2, 0, 0);
splat.userData.url = url;
await splat.initialized;
if (!current() || this.splat) {
splat.dispose?.(); // the scene changed, or another load finished first
return;
}
this.splat = splat;
this.scene.add(splat);
await this.#captureSplatLight(url);
}
/**
* Light the robot and objects with the splat itself: render it into a cube map at the environment's
* light probe, the robot hidden, and use that as the environment map. Directions the splat leaves empty
* (above an open room) show the environment's `sky`, as a ceiling would.
*/
async #captureSplatLight(url) {
const lighting = this.env?.lighting ?? {};
const spark = new this.SparkRenderer({ renderer: this.renderer });
try {
const probe = new THREE.PerspectiveCamera();
probe.position.set(...(lighting.probe ?? [0, 0, 1]));
probe.updateMatrixWorld();
await spark.update({ scene: this.scene, camera: probe }); // a radial sort, good in every direction
if (this.splat?.userData.url !== url) return;
// The cube is drawn synchronously when update is false, so the sky and the shown splat last only for it.
const background = this.scene.background;
const visible = this.splat.visible;
this.scene.background = new THREE.Color(lighting.sky ?? 0x8a847c);
this.splat.visible = true;
const pending = spark.renderEnvMap({ scene: this.scene, worldCenter: probe.position, size: 128, hideObjects: [this.root], update: false });
this.scene.background = background;
this.splat.visible = visible;
const texture = await pending;
if (this.splat?.userData.url !== url) return texture.dispose();
this.splatLight?.texture.dispose();
this.splatLight = { url, texture };
} finally {
spark.dispose();
}
}
#removeSplat() {
if (!this.splat) return;
this.#disposeCameraSparks();
this.scene.remove(this.splat);
this.splat.dispose?.();
this.splat = null;
}
/**
* The Spark state that draws the splat for a robot camera, or null when no splat is shown. Spark sorts
* the splats for one camera at a time, and every render() call starts a new frame for it: drawn
* with the main view's state, each robot camera would redo the sort every frame, and the main view
* would show splats sorted for another camera.
*/
#sparkFor(cam) {
if (!this.splat?.visible || !this.SparkRenderer) return null;
cam.spark ??= new this.SparkRenderer({ renderer: this.renderer });
return cam.spark;
}
#disposeCameraSparks() {
for (const cam of Object.values(this.robotCameras ?? {})) {
cam.spark?.dispose();
cam.spark = null;
}
}
#applyStyle() {
const pixel = this.style === "pixel";
const loaded = Boolean(this.env?.splat) && this.splat?.userData.url === this.splatBase + this.env.splat;
const splat = (this.style === "splat" || pixel) && loaded;
const look = splat ? "splat" : this.style === "toon" || pixel ? "toon" : "lit";
// The splat replaces the floor, the collision boxes and the decor; elsewhere the decor replaces the
// floor and the boxes.
const decor = this.meshes.some((m) => m.userData.role === "decor");
// Lit with the environment's baked light (loadLight): no lamps, no shadow maps.
const baked = look === "lit" && Boolean(this.light);
// A photographic room (loadHome) stands in for every geom but the robot's and the objects', lit by its baked
// light in Lit, in flat colours in Toon and Pixel (where there is no splat).
const homeShown = Boolean(this.home) && (look === "lit" || look === "toon");
const home = look === "lit" && Boolean(this.home);
if (this.home) {
this.home.root.visible = homeShown;
if (homeShown) this.home.setLook(look, this.scene);
}
for (const mesh of this.meshes) {
const { role } = mesh.userData;
mesh.layers.set(0);
mesh.userData.homeHidden = homeShown && role !== "robot" && role !== "object" && role !== "dressing";
if (mesh.userData.homeHidden) {
mesh.visible = false;
continue;
}
if (role === "catcher") {
mesh.visible = splat;
continue;
}
if (role === "dressing") {
// furniture models (loadDressing): Lit only; Toon and Pixel keep the modelled scenery
mesh.visible = look === "lit";
if (mesh.userData.moving) mesh.layers.enable(OCCLUSION_LAYER); // in place of the shapes they hide
continue;
}
if (role === "decor") {
// In 3DGS, depth only (after the splat), for the shadow catchers drawn next.
mesh.material = splat ? this.catchers.depth : look === "toon" ? mesh.userData.toon : mesh.userData.lit;
mesh.renderOrder = splat ? 1 : 0;
mesh.castShadow = splat ? false : mesh.userData.casts;
mesh.visible = true;
// Pixel (pixel.js) gives each pixel to its nearest mesh, and in the modelled scenes draws an ink
// line around it; over a splat the decor only stands for the splat's surfaces.
mesh.layers.enable(splat ? OCCLUDER : OUTLINED);
continue;
}
mesh.layers.enable(OUTLINED);
if (mesh.userData.geom !== undefined) mesh.layers.enable(OCCLUSION_LAYER); // shades the baked room (baked.js)
mesh.material = look === "toon" ? mesh.userData.toon : pixel && mesh.userData.plain ? mesh.userData.plain : mesh.userData.lit;
const ground = role === "floor" || role === "proxy";
mesh.visible = mesh.userData.wall === "stub" ? false : splat ? !ground : !(decor && ground);
// With baked light, the floor stops at the walls (the light map covers the room only).
if (mesh.userData.floor && (mesh.userData.floor === "room") !== baked) mesh.visible = false;
if (mesh.userData.replaced && look === "lit") mesh.visible = false; // a dressing model stands there
}
if (this.splat) this.splat.visible = splat;
if (this.shadowCatcher) this.shadowCatcher.visible = splat && !decor;
// Splats cost per pixel, so 3DGS draws fewer pixels than the CSS resolution (splatScale) whatever the
// screen's device ratio, which would multiply the work by up to four. Pixel draws its few pixels
// whatever the screen, and scales them up on all of it.
// The photographic room costs per pixel (light map, probes, shadows): at most 1.5 device pixels per CSS pixel.
this.renderer.setPixelRatio(splat && !pixel ? this.splatScale : Math.min(window.devicePixelRatio, home ? 1.5 : 2));
// Ink lines where the whole scene is modelled, as in Toon; a splat has none, so its robot has none.
this.pixelEdges = { occluders: splat && decor, ink: !splat };
const gain = pixel && splat ? PIXEL_GAIN : 1;
if (pixel) this.pixel.reset(); // new colours for the new look
// Where the canvas is not a whole number of screen pixels (a 150% display), the browser stretches it.
this.canvas.style.imageRendering = pixel ? "pixelated" : "";
this.lights.lit.visible = look === "lit" && !baked;
this.lights.toon.visible = look === "toon";
// a baked room has its sun instead of the key light (and its shadows)
this.key.visible = !baked;
if (this.sun) this.sun.visible = baked;
this.sunWatch?.invalidate();
this.renderer.shadowMap.enabled = !baked || Boolean(this.sun);
const lighting = this.env?.lighting ?? {};
const key = { toon: [0xfff4e6, 1.7, 0.45], lit: [0xffffff, 2.4, 1], splat: [lighting.keyColor ?? 0xfff2e0, lighting.keyIntensity ?? 1.2, 1] }[look];
this.key.color.set(key[0]);
this.key.intensity = baked ? 0 : key[1] * gain;
this.key.shadow.intensity = key[2];
// Lit's exposure: the modelled rooms are light-coloured, and brighter washes them out. A baked room has
// its own (BAKED_TONE, BAKED_EXPOSURE).
this.renderer.toneMapping = baked ? BAKED_TONE : look === "lit" ? THREE.ACESFilmicToneMapping : THREE.NoToneMapping;
this.renderer.toneMappingExposure = baked ? BAKED_EXPOSURE : 0.8;
// In 3DGS the splat's own light; the baked room's (captured at the first frame) or RoomEnvironment
// (y-up) in Lit; Toon is lit by its sky.
const splatLight = splat && this.splatLight?.url === this.splat.userData.url ? this.splatLight.texture : null;
const own = splatLight ?? (baked ? this.roomLight : null);
this.scene.environment = look === "toon" ? null : baked ? this.roomLight : (splatLight ?? this.environment);
this.scene.environmentIntensity = (splatLight ? (lighting.ambient ?? 1) : 1) * gain;
this.scene.environmentRotation.set(own || baked ? 0 : Math.PI / 2, 0, 0);
this.scene.background = new THREE.Color(BACKGROUND[pixel ? "pixel" : baked ? (darkTheme() ? "bakedDark" : "bakedLight") : look]);
this.light?.occlusion.invalidate();
// the key light's shadow box: round where you look, smaller in the photographic room (what lies outside it skips
// the shadow lookup: the light map already has the room's own shadows)
const box = home ? 1.5 : 2.2;
if (this.key.shadow.camera.right !== box) {
Object.assign(this.key.shadow.camera, { left: -box, right: box, top: box, bottom: -box });
this.key.shadow.camera.updateProjectionMatrix();
}
if (home) {
// all light from the room: its light map, its probes, its reflections and a key light from its lamps
this.lights.lit.visible = false;
this.key.visible = true;
this.key.shadow.intensity = 1;
this.renderer.shadowMap.enabled = true;
this.renderer.toneMapping = THREE.AgXToneMapping;
this.renderer.toneMappingExposure = 2 ** this.home.meta.exposure;
this.scene.environment = this.home.reflection?.texture ?? null;
this.scene.environmentIntensity = 1;
this.scene.environmentRotation.set(0, 0, 0);
this.scene.background = new THREE.Color(BACKGROUND[darkTheme() ? "bakedDark" : "bakedLight"]);
}
}
/** Follow the page's theme (index.html sets data-theme; otherwise the system's) where it shows. */
#followTheme() {
const update = () => {
if (this.style === "lit" && (this.light || this.home)) this.#applyStyle();
};
new MutationObserver(update).observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
window.matchMedia?.("(prefers-color-scheme: dark)").addEventListener?.("change", update);
}
/** Point the camera at the robot from behind its right shoulder. */
frameRobot(pose, { distance = 2.2, height = 1.5 } = {}) {
const [x, y, yaw] = pose;
const back = [Math.cos(yaw), Math.sin(yaw)];
const right = [Math.sin(yaw), -Math.cos(yaw)];
this.controls.target.set(x + back[0] * 0.45, y + back[1] * 0.45, 0.75);
this.camera.position.set(x - back[0] * distance * 0.75 + right[0] * distance * 0.6, y - back[1] * distance * 0.75 + right[1] * distance * 0.6, height);
this.controls.update();
}
/** Light a geom up (a device's power light: `on`) or let it go dark again, in every style. */
setGlow(geomName, on, color = 0x4dff7a) {
this.home?.glow(geomName, on, color); // the photographic room's model of it
const id = this.sim?.id("geom", geomName) ?? -1;
const mesh = this.geoms.find((m) => m.userData.geom === id);
if (!mesh || mesh.userData.glow === on) return;
const d = mesh.userData;
if (!d.ownGlow) {
// its own materials: others may share these
const wasLit = mesh.material === d.lit;
d.lit = d.lit.clone();
d.toon = d.toon.clone();
if (this.light) bakeMoving(d.lit, this.light); // a clone has no shader changes
this.#owned.push(d.lit, d.toon);
d.base = d.lit.color?.clone();
d.ownGlow = true;
mesh.material = wasLit ? d.lit : d.toon;
}
for (const m of [d.lit, d.toon]) {
if (m.color) m.color.set(on ? color : d.base);
if (m.emissive) {
// filmic tone mapping turns a strong glow white: enough to light it, not more
m.emissive.set(on ? color : 0x000000);
m.emissiveIntensity = on ? 0.55 : 1;
}
}
d.glow = on;
}
setViews(names) {
this.views = names.filter((n) => n in (this.robotCameras ?? {}));
}
/** Copy the simulation's geom and camera poses into the scene. */
update() {
const { data } = this.sim;
const pos = data.geom_xpos;
const mat = data.geom_xmat;
for (const mesh of this.geoms) {
const i = mesh.userData.geom;
const r = 9 * i;
const p = 3 * i;
mesh.matrix.set(mat[r], mat[r + 1], mat[r + 2], pos[p], mat[r + 3], mat[r + 4], mat[r + 5], pos[p + 1], mat[r + 6], mat[r + 7], mat[r + 8], pos[p + 2], 0, 0, 0, 1);
mesh.matrixWorldNeedsUpdate = true;
}
this.#poseObjectModels();
this.home?.update(data);
const bpos = data.xpos;
const bmat = data.xmat;
const world = new THREE.Matrix4();
for (const cam of Object.values(this.robotCameras)) {
const b = cam.body;
world.set(bmat[9 * b], bmat[9 * b + 1], bmat[9 * b + 2], bpos[3 * b], bmat[9 * b + 3], bmat[9 * b + 4], bmat[9 * b + 5], bpos[3 * b + 1], bmat[9 * b + 6], bmat[9 * b + 7], bmat[9 * b + 8], bpos[3 * b + 2], 0, 0, 0, 1);
cam.camera.matrixWorld.multiplyMatrices(world, cam.local);
cam.camera.matrixWorldInverse.copy(cam.camera.matrixWorld).invert();
}
// Shadows follow where the user looks.
const t = this.controls.target;
const [kx, ky, kz] = this.keyOffset ?? KEY_OFFSET;
this.key.target.position.copy(t);
this.key.position.set(t.x + kx, t.y + ky, t.z + kz);
}
viewRects() {
const w = this.canvas.clientWidth;
const h = this.canvas.clientHeight;
const pw = Math.round(Math.min(260, w * 0.28));
const ph = Math.round((pw * 3) / 4);
const gap = 12;
return this.views.map((name, k) => ({ name, label: this.robotCameras[name].label, x: gap, y: h - (k + 1) * (ph + gap), w: pw, h: ph }));
}
render() {
const { renderer, canvas } = this;
const w = canvas.clientWidth;
const h = canvas.clientHeight;
if (!w || !h) return;
if (canvas.width !== Math.floor(w * renderer.getPixelRatio()) || canvas.height !== Math.floor(h * renderer.getPixelRatio())) {
renderer.setSize(w, h, false);
this.camera.aspect = w / h;
this.camera.updateProjectionMatrix();
}
this.controls.update();
// The robot cameras below reuse this frame's shadow map. A baked room's sun shadows only change when
// something moves: drawn again then (at most 30 times a second), else kept.
const bakedSun = this.style === "lit" && this.light && this.sun;
renderer.shadowMap.needsUpdate = bakedSun ? this.sunWatch.changed(this.geoms) : true;
const homeShown = Boolean(this.home?.root.visible);
if (this.style === "toon") {
const uncut = this.#cutWalls(this.camera);
if (homeShown) this.home.cut(this.camera);
this.outline.render(renderer, this.scene, this.camera, "main");
if (homeShown) this.home.uncut();
uncut();
for (const rect of this.viewRects()) this.outline.render(renderer, this.scene, this.robotCameras[rect.name].camera, rect.name, rect);
return;
}
if (this.style === "pixel") {
const edges = this.pixelEdges;
const scale = this.pixel.scale(renderer);
const uncut = this.#cutWalls(this.camera);
if (homeShown) this.home.cut(this.camera);
this.pixel.render(renderer, this.scene, this.camera, "main", null, { scale, edges });
if (homeShown) this.home.uncut();
uncut();
// The robot cameras are small: half-size pixels keep them readable.
for (const rect of this.viewRects()) {
const cam = this.robotCameras[rect.name];
const spark = this.#sparkFor(cam);
const draw = spark ? () => spark.render(this.scene, cam.camera) : null;
this.pixel.render(renderer, this.scene, cam.camera, rect.name, rect, { scale: Math.max(1, Math.round(scale / 2)), edges, draw });
}
return;
}
if (this.style === "lit" && this.home) {
this.#renderHome(w, h);
return;
}
const baked = this.style === "lit" && Boolean(this.light);
if (baked && !this.roomLight) {
this.#captureRoom();
this.#applyStyle();
}
renderer.setScissorTest(false);
renderer.setViewport(0, 0, w, h);
// what moves, seen from above: the shade it casts in the baked room (baked.js, SkyOcclusion)
if (baked) this.light.occlusion.update(renderer, this.scene, this.geoms);
const uncut = this.#cutWalls(this.camera);
renderer.render(this.scene, this.camera);
uncut();
renderer.setScissorTest(true);
// The robot's cameras see the sky above the walls of a baked room.
const background = this.scene.background;
if (baked) this.scene.background = this.bakedSky ??= new THREE.Color().setRGB(...BAKED_SKY);
for (const rect of this.viewRects()) {
const cam = this.robotCameras[rect.name];
const y = h - rect.y - rect.h;
renderer.setViewport(rect.x, y, rect.w, rect.h);
renderer.setScissor(rect.x, y, rect.w, rect.h);
const spark = this.#sparkFor(cam);
if (spark) spark.render(this.scene, cam.camera);
else renderer.render(this.scene, cam.camera);
}
this.scene.background = background;
renderer.setScissorTest(false);
}
/** Show the sky behind the windows (the robot's cameras are in the room); #unsky() puts the background back. */
#sky() {
const { scene, home } = this;
if (!home.sky || this.skySaved) return;
this.skySaved = { background: scene.background, intensity: scene.backgroundIntensity };
scene.background = home.sky;
scene.backgroundIntensity = home.meta.sky.scale;
scene.backgroundRotation.copy(this.skyRotation ??= skyEuler(home.meta.sky.rotation ?? 0));
}
#unsky() {
if (!this.skySaved) return;
this.scene.background = this.skySaved.background;
this.scene.backgroundIntensity = this.skySaved.intensity;
this.skySaved = null;
}
/** A frame of the photographic room (loadHome): its captures first, then the views. Allocates nothing per frame. */
#renderHome(w, h) {
const { renderer, scene, home } = this;
if (!home.ready) {
// what the captures must not see: the robot, the objects and their models (only until they are done)
home.prepare(renderer, scene, [...this.geoms, ...this.objectModels.map((o) => o.holder)]);
}
const env = home.reflection?.texture ?? null;
if (scene.environment !== env) scene.environment = env;
home.placeKey(this.key, this.controls.target);
// the key light's shadows (of what moves) are drawn again only when something moved or the light did
const was = (this.keyWas ??= { p: new THREE.Vector3(Infinity, 0, 0), t: new THREE.Vector3() });
const keyMoved = was.p.distanceToSquared(this.key.position) > 1e-6 || was.t.distanceToSquared(this.key.target.position) > 1e-6;
if (keyMoved) {
was.p.copy(this.key.position);
was.t.copy(this.key.target.position);
}
renderer.shadowMap.needsUpdate = (this.homeWatch ??= new MotionWatch()).changed(this.geoms) || keyMoved;
renderer.setScissorTest(false);
renderer.setViewport(0, 0, w, h);
if (home.inside(this.camera.position)) this.#sky();
home.cut(this.camera);
renderer.render(scene, this.camera);
home.uncut();
this.#unsky();
if (!this.views.length) return;
renderer.setScissorTest(true);
this.#sky();
for (const rect of this.viewRects()) {
const cam = this.robotCameras[rect.name];
const y = h - rect.y - rect.h;
renderer.setViewport(rect.x, y, rect.w, rect.h);
renderer.setScissor(rect.x, y, rect.w, rect.h);
renderer.render(scene, cam.camera);
}
this.#unsky();
renderer.setScissorTest(false);
}
/**
* A robot camera's image as a JPEG data URL (for vision models), `width` pixels wide, as the screen shows
* it: three.js tone-maps only what it draws on the canvas, so the scene goes into a linear target first
* and OutputPass applies the tone mapping, the exposure and the sRGB encoding.
*/
async snapshot(name, width = 512) {
const cam = this.robotCameras[name];
if (!cam) return null;
const spark = this.#sparkFor(cam);
if (spark) await spark.update({ scene: this.scene, camera: cam.camera }); // sorts the splats for this camera
const height = Math.round((width * 3) / 4);
const linear = new THREE.WebGLRenderTarget(width, height, { type: THREE.HalfFloatType });
const target = new THREE.WebGLRenderTarget(width, height);
cam.camera.aspect = width / height;
const background = this.scene.background;
if (this.style === "lit" && this.light) this.scene.background = this.bakedSky ??= new THREE.Color().setRGB(...BAKED_SKY);
if (this.style === "lit" && this.home) this.#sky();
this.renderer.setRenderTarget(linear);
if (spark) spark.render(this.scene, cam.camera);
else this.renderer.render(this.scene, cam.camera);
this.#unsky();
this.scene.background = background;
(this.outputPass ??= new OutputPass()).render(this.renderer, target, linear);
const pixels = new Uint8Array(width * height * 4);
this.renderer.readRenderTargetPixels(target, 0, 0, width, height, pixels);
this.renderer.setRenderTarget(null);
linear.dispose();
target.dispose();
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
const image = ctx.createImageData(width, height);
for (let y = 0; y < height; y++) image.data.set(pixels.subarray((height - 1 - y) * width * 4, (height - y) * width * 4), y * width * 4);
ctx.putImageData(image, 0, 0);
return canvas.toDataURL("image/jpeg", 0.85);
}
/**
* A robot camera's pose and lens for a picture `width` pixels wide (snapshot's size): {matrix (camera to
* world, 16 numbers, column-major, looking along -z), fovy (degrees), aspect, width, height}.
*/
cameraFrame(name, width = 512) {
const cam = this.robotCameras[name];
if (!cam) return null;
const height = Math.round((width * 3) / 4);
// the lens as the projection has it (snapshot sets the aspect without remaking the projection)
const p = cam.camera.projectionMatrix.elements;
const fovy = (2 * Math.atan(1 / p[5]) * 180) / Math.PI;
return { matrix: Array.from(cam.camera.matrixWorld.elements), fovy, aspect: p[5] / p[0], width, height };
}
/**
* The main view as the person watching the page sees it, as a JPEG data URL at most `width` pixels wide:
* drawn now and read at once, before the browser shows the frame (the canvas keeps no copy of it).
*/
capture(width = 768) {
this.render();
const source = this.renderer.domElement;
if (!source.width || !source.height) return null;
const canvas = document.createElement("canvas");
canvas.width = Math.min(width, source.width);
canvas.height = Math.round((canvas.width * source.height) / source.width);
canvas.getContext("2d").drawImage(source, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL("image/jpeg", 0.85);
}
// ------------------------------------------------------------------------------------------------
// Dragging objects with the mouse: a spring pulls the grabbed point toward the cursor on a plane
// facing the camera, applied as an external force in the physics (data.xfrc_applied).
#bindDrag() {
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const toPointer = (e) => {
const r = this.canvas.getBoundingClientRect();
pointer.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);
raycaster.setFromCamera(pointer, this.camera);
};
this.canvas.addEventListener("pointerdown", (e) => {
if (e.button !== 0 || !this.geoms) return;
toPointer(e);
// (an object drawn as a model in Lit is picked by its hidden shapes)
const pickable = this.geoms.filter((m) => (m.userData.role === "object" || m.userData.role === "part") && (m.visible || m.userData.replaced || m.userData.homeHidden));
const hit = raycaster.intersectObjects(pickable, false)[0];
if (!hit) return;
const body = hit.object.userData.body;
const p = this.sim.bodyPos(body);
const R = this.sim.bodyMat(body);
const d = [hit.point.x - p[0], hit.point.y - p[1], hit.point.z - p[2]];
const local = [0, 1, 2].map((k) => R[k] * d[0] + R[3 + k] * d[1] + R[6 + k] * d[2]);
const plane = new THREE.Plane().setFromNormalAndCoplanarPoint(this.camera.getWorldDirection(new THREE.Vector3()).negate(), hit.point);
this.drag = { body, local, plane, target: hit.point.clone() };
this.controls.enabled = false;
this.canvas.setPointerCapture(e.pointerId);
});
this.canvas.addEventListener("pointermove", (e) => {
if (!this.drag) return;
toPointer(e);
raycaster.ray.intersectPlane(this.drag.plane, this.drag.target);
});
const end = () => {
if (!this.drag) return;
this.drag = null;
this.controls.enabled = true;
this.sim?.data.xfrc_applied.fill(0);
};
this.canvas.addEventListener("pointerup", end);
this.canvas.addEventListener("pointercancel", end);
}
/** The drag spring's force, written to xfrc_applied; call before stepping the physics. */
applyDrag() {
if (!this.drag || !this.sim) return;
const { model, data } = this.sim;
const { body, local, target } = this.drag;
const p = this.sim.bodyPos(body);
const R = this.sim.bodyMat(body);
const r = [0, 1, 2].map((k) => R[3 * k] * local[0] + R[3 * k + 1] * local[1] + R[3 * k + 2] * local[2]);
const point = [p[0] + r[0], p[1] + r[1], p[2] + r[2]];
// Spring on the grabbed point, damping on the body's velocity, scaled by the body's mass.
const m = Math.max(0.05, model.body_subtreemass[body]);
const vel = data.cvel.subarray(6 * body + 3, 6 * body + 6);
const f = [0, 1, 2].map((k) => m * (300 * (target.getComponent(k) - point[k]) - 12 * vel[k]));
const torque = [r[1] * f[2] - r[2] * f[1], r[2] * f[0] - r[0] * f[2], r[0] * f[1] - r[1] * f[0]];
data.xfrc_applied.set([...f, ...torque], 6 * body);
}
}
// three.js views of the simulation. Geoms are built from the compiled MuJoCo model and posed from
// data.geom_xpos / geom_xmat every frame, so every renderer style draws the same physics. The world keeps
// MuJoCo's z-up axes.
//
// Styles:
// - "toon": cel shading with ink outlines (toon.js) on a paper-coloured background;
// - "lit": PBR materials. Where the environment has a photographic room (tools/home, home.js) Lit draws that
// instead of the scenery's geoms: modelled and light-baked in Blender, the robot and the objects lit by probes
// captured from it. Where it has baked light (tools/bake_light.mjs, baked.js), a light map for the scenery,
// light probes and a soft shade from above for what moves, and furniture models in place of some scenery
// (dressing.json); elsewhere image-based lighting and soft shadows (after the Microduck simulator).
// The robot shows its real finish (materials.js);
// - "splat": the environment's 3D Gaussian splat from MuJoCo-GS-Web (Spark), with the robot and objects
// lit by the splat itself (an environment map rendered from it) and their shadows caught on its floor;
// - "pixel": pixel art (pixel.js) of the splat where the environment has one, of the Toon scene elsewhere.
//
// Environments with a splat also have a decor (tools/make_decor.py): a modelled stand-in for the splat that
// Toon and Lit show in place of MuJoCo-GS-Web's invisible collision boxes. Static geoms never move, so they
// are merged per material into a few meshes, with each geom's colour as a vertex colour.
//
// Walls (tall boxes in a body named like "walls") are kept apart: in the main view, a wall the camera is
// outside of is drawn as a low stub, so it never hides the room; the robot's cameras see whole walls.
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
import { OutputPass } from "three/addons/postprocessing/OutputPass.js";
import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js";
import { floorMaterial, lookFor, makeMaterial, robotLookFor, surfaceColour, worldUVs } from "./materials.js";
import { OCCLUDER, OUTLINED, PixelPass } from "./pixel.js";
import { OutlinePass } from "./toon.js";
import { GEOM, collectScenery, dressingMatrix, dressingTurn, geomMatrix, layoutLightmap } from "./statics.js";
import { MotionWatch, OCCLUSION_LAYER, bakeMoving, bakeScenery, loadBake } from "./baked.js";
import { download } from "../core/assets.js";
// A baked room stands on the page's own background: dark or light with the page's theme.
const BACKGROUND = { toon: 0xf1eee8, lit: 0xe3dfd8, splat: 0x202124, pixel: 0x0d1226, bakedDark: 0x1c1b1a, bakedLight: 0xe3dfd8 };
// What the robot's cameras see above the walls in a baked room, and what the room's reflections show
// there: the sky the bake lit it with (linear RGB, tools/bake_light.mjs).
const BAKED_SKY = [1.0, 0.98, 0.95];
// A baked room's tone mapping and exposure. AgX keeps the bake's soft gradations; the user preferred it, lit
// by the sky alone, to a sun with Khronos PBR Neutral (2026-11-17).
const BAKED_TONE = THREE.AgXToneMapping;
const BAKED_EXPOSURE = 1.6;
// Pixel over a splat lights the robot and the objects this much more: its palette deepens the mid greys,
// and they stand in a light scene without an ink line to set them off.
const PIXEL_GAIN = 1.2;
// Where the key light sits relative to the camera target, unless the environment says (its "lighting").
const KEY_OFFSET = [1.4, -1.1, 3.2];
/** Whether the page shows its dark theme: chosen (data-theme) or, unchosen, the system's. */
function darkTheme() {
const chosen = document.documentElement.dataset.theme;
return chosen ? chosen === "dark" : Boolean(window.matchMedia?.("(prefers-color-scheme: dark)").matches);
}
/**
* The rotation that shows an equirect sky made for a z-up world (Blender's, turned `degrees` about z) as three.js
* draws backgrounds: its lookup direction (x, y, z) -> (-x, z, y).
*/
function skyEuler(degrees) {
const turn = new THREE.Matrix4().makeRotationZ(THREE.MathUtils.degToRad(-degrees));
const axes = new THREE.Matrix4().set(-1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1);
return new THREE.Euler().setFromRotationMatrix(axes.multiply(turn));
}
export class SceneView {
constructor(canvas) {
this.canvas = canvas;
this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true, preserveDrawingBuffer: false });
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
this.renderer.shadowMap.type = THREE.PCFShadowMap;
this.renderer.shadowMap.autoUpdate = false; // drawn once per frame, see render()
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(45, 1, 0.02, 80);
this.camera.up.set(0, 0, 1);
this.controls = new OrbitControls(this.camera, canvas);
this.controls.enableDamping = true;
this.controls.maxPolarAngle = Math.PI * 0.495;
this.root = new THREE.Group();
this.scene.add(this.root);
this.#buildLights();
this.outline = new OutlinePass();
this.pixel = new PixelPass();
// 3DGS's resolution, as a fraction of the CSS resolution. Splats cost per pixel: at 66% a frame
// fills under half the pixels, about twice the frame rate, and the soft splats look much the same
// scaled up.
this.splatScale = 0.66;
// 3DGS shadows on the decor: a depth-only pass, then shadows on the nearest surface only.
this.catchers = {
depth: new THREE.MeshBasicMaterial({ colorWrite: false, transparent: true }),
shadow: new THREE.ShadowMaterial({ opacity: 0.3, transparent: true, depthWrite: false }),
};
this.meshes = []; // everything built for the scene
this.geoms = []; // the moving meshes, posed every frame
this.walls = []; // {mesh, stub, center, out}: walls cut down when the camera is outside them
this.views = [];
this.style = "lit";
this.splat = null;
this.home = null; // the environment's photographic room (home.js), drawn by Lit
this.drag = null;