feat: release v0.5 with shared interactive arenas and textured RP1

Unify lighting and line-colour controls across robots, replace the football with a shared layout of draggable physical props, and import the supplied RP1 GLBs without changing trained physics or policies.

Include reproducible visual import/provenance, regression coverage and verification records. Verified 66 unit tests, 55 browser tests and production-build checks.
This commit is contained in:
2026-10-30 14:14:03 +08:00
parent 57b3108ab3
commit a8be5e0134
69 changed files with 5125 additions and 317 deletions
+151
View File
@@ -0,0 +1,151 @@
import * as THREE from "three";
const TYPES = ["box", "sphere", "cylinder", "capsule"];
const COLORS = [
0xffb52e, 0x81cbb7, 0xb4a4d4, 0x83bfff, 0xf2efe8, 0xff7a2f, 0xf09caf,
];
// One layout per runtime, shared by both locomotion models. A shuffled,
// jittered lattice gives random placement without overlaps or retry loops.
export function generateInteractiveProps({
halfExtent,
spawn,
avoid = [],
random = Math.random,
}) {
const count = 5 + Math.floor(random() * 3);
const candidates = [];
const limit = halfExtent - 0.2;
for (
let x = Math.max(-limit, spawn[0] - 0.4);
x <= Math.min(limit, spawn[0] + 1.8);
x += 0.4
) {
for (let y = -Math.min(limit, 1.2); y <= Math.min(limit, 1.2); y += 0.4) {
const px = x + (random() - 0.5) * 0.06;
const py = y + (random() - 0.5) * 0.06;
if (
[spawn, ...avoid].every(([x, y]) => Math.hypot(px - x, py - y) > 0.34)
)
candidates.push([px, py]);
}
}
for (let i = candidates.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[candidates[i], candidates[j]] = [candidates[j], candidates[i]];
}
// Keep at least one toy within immediate walking / kicking reach.
const near = candidates.findIndex(
([x, y]) =>
x > spawn[0] + 0.3 &&
x < spawn[0] + 0.85 &&
Math.abs(y - spawn[1]) < 0.42,
);
if (near > 0)
[candidates[0], candidates[near]] = [candidates[near], candidates[0]];
if (candidates.length < count)
throw new Error("Arena too small for interactive props");
const offset = Math.floor(random() * TYPES.length);
return candidates.slice(0, count).map(([x, y], i) => {
const type = TYPES[(i + offset) % TYPES.length];
const r = 0.045 + random() * 0.015;
const h = 0.045 + random() * 0.02;
const size =
type === "box" ? [r, r * 0.85, h] : type === "sphere" ? [r] : [r, h];
const bottom = type === "sphere" ? r : type === "capsule" ? r + h : h;
const yaw = random() * Math.PI * 2;
return {
name: `interactive_${i}`,
type,
size,
pos: [x, y, bottom + 0.006],
quat: [Math.cos(yaw / 2), 0, 0, Math.sin(yaw / 2)],
mass: 0.04 + random() * 0.04,
color: COLORS[i % COLORS.length],
};
});
}
export function resolvePropAddresses(mujoco, model, specs) {
return specs.map((spec) => {
const jointId = mujoco.mj_name2id(
model,
mujoco.mjtObj.mjOBJ_JOINT.value,
`${spec.name}_joint`,
);
const bodyId = mujoco.mj_name2id(
model,
mujoco.mjtObj.mjOBJ_BODY.value,
spec.name,
);
return {
bodyId,
qAdr: model.jnt_qposadr[jointId],
dofAdr: model.jnt_dofadr[jointId],
mass: model.body_mass[bodyId],
};
});
}
export function resetProp(data, address, spec, parked = false, index = 0) {
const q = data.qpos,
v = data.qvel;
q.set(parked ? [50 + index, 0, spec.pos[2]] : spec.pos, address.qAdr);
q.set(spec.quat, address.qAdr + 3);
v.fill(0, address.dofAdr, address.dofAdr + 6);
}
export function createInteractivePropVisuals(specs) {
const root = new THREE.Group();
root.name = "interactive-props";
root.rotation.x = -Math.PI / 2; // MJCF Z-up -> Three Y-up
const meshes = specs.map((spec, index) => {
const [r, h, z] = spec.size;
let geometry;
if (spec.type === "box")
geometry = new THREE.BoxGeometry(2 * r, 2 * h, 2 * z);
else if (spec.type === "sphere")
geometry = new THREE.SphereGeometry(r, 24, 16);
else {
geometry =
spec.type === "cylinder"
? new THREE.CylinderGeometry(r, r, 2 * h, 24)
: new THREE.CapsuleGeometry(r, 2 * h, 8, 16);
geometry.rotateX(Math.PI / 2);
}
const mesh = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color: spec.color,
roughness: 0.38,
metalness: 0.08,
}),
);
mesh.name = spec.name;
mesh.userData.interactiveIndex = index;
mesh.position.fromArray(spec.pos);
mesh.quaternion.set(spec.quat[1], spec.quat[2], spec.quat[3], spec.quat[0]);
root.add(mesh);
return mesh;
});
return {
root,
meshes,
dispose() {
root.removeFromParent();
meshes.forEach((mesh) => {
mesh.geometry.dispose();
mesh.material.dispose();
});
},
sync(data, addresses, visible = true) {
root.visible = visible;
const q = data.qpos;
meshes.forEach((mesh, i) => {
const a = addresses[i].qAdr;
mesh.position.set(q[a], q[a + 1], q[a + 2]);
mesh.quaternion.set(q[a + 4], q[a + 5], q[a + 6], q[a + 3]);
});
},
};
}
+11 -18
View File
@@ -1,9 +1,8 @@
import { propColliders } from "../../props.js";
import { appendInteractivePhysics } from "./session-environment.js";
import { arenaWalls } from "../../../platform/worlds/arena.js";
import {
ARENA_HALF,
BALL_PARK_POS,
BALL_RADIUS,
RELIEF_GRID,
RELIEF_HMAX,
RELIEF_SINK,
@@ -17,6 +16,8 @@ export function composeArenaPhysics(
jointNames,
defaultPose,
spawn,
interactiveProps = [],
floor,
boundary = {
half_extent: ARENA_HALF,
wall_height: 0.25,
@@ -30,7 +31,11 @@ export function composeArenaPhysics(
for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
return e;
};
root.appendChild(el("option", { timestep: String(timestep) }));
// Adding free toys can cross MuJoCo's automatic sparse-Jacobian cutoff
// (nv >= 60). Keep the original small-robot dense path in both modes.
root.appendChild(
el("option", { timestep: String(timestep), jacobian: "dense" }),
);
const body = doc.querySelector("worldbody");
body.appendChild(
el("geom", {
@@ -38,6 +43,7 @@ export function composeArenaPhysics(
type: "plane",
size: "0 0 0.05",
pos: "0 0 0",
...(floor?.friction ? { friction: floor.friction.join(" ") } : {}),
}),
);
for (const wall of arenaWalls(boundary))
@@ -54,20 +60,7 @@ export function composeArenaPhysics(
if (c.euler) attrs.euler = c.euler;
body.appendChild(el("geom", attrs));
}
const ball = el("body", { name: "ball", pos: BALL_PARK_POS });
ball.appendChild(el("freejoint", { name: "ball_freejoint" }));
ball.appendChild(
el("geom", {
name: "ball_geom",
type: "sphere",
size: String(BALL_RADIUS),
mass: "0.03",
friction: "0.4 0.01 0.003",
solref: "0.03 0.4",
condim: "6",
}),
);
body.appendChild(ball);
appendInteractivePhysics(doc, interactiveProps, { group: 0 });
doc.querySelector("asset").appendChild(
el("hfield", {
name: "terrain",
@@ -93,7 +86,7 @@ export function composeArenaPhysics(
keyframe.appendChild(
el("key", {
name: "STAND",
qpos: `${qposFree} ${qposJoints} ${BALL_PARK_POS} 1 0 0 0`,
qpos: `${qposFree} ${qposJoints} ${interactiveProps.map((p) => [...p.pos, ...p.quat].join(" ")).join(" ")}`,
ctrl: Array.from(defaultPose).join(" "),
}),
);
+15
View File
@@ -0,0 +1,15 @@
import * as THREE from "three";
import { VARIANT_SWATCH_HEX } from "../../variants.js";
// The existing four HUD swatches now tint both the floor and enclosure.
// Keep minor lines quieter than section lines, without touching reveal/fade.
export function setArenaLineColor(materials, name) {
const hex = VARIANT_SWATCH_HEX[name];
if (!hex) return false;
const color = new THREE.Color(hex);
for (const material of materials) {
material.uniforms.uSectionColor.value.copy(color);
material.uniforms.uCellColor.value.copy(color).multiplyScalar(0.55);
}
return true;
}
@@ -1,5 +1,6 @@
import * as THREE from "three";
import { makeInfiniteGrid, makeArenaWalls } from "./render.js";
import { setArenaLineColor } from "./line-color.js";
import { arenaWalls } from "../../../platform/worlds/arena.js";
// Shared appearance; physical collision boxes come only from the World composer.
export function createArenaFloorPresentation({ sim, rig, world }) {
@@ -43,6 +44,8 @@ export function createArenaFloorPresentation({ sim, rig, world }) {
root,
grid,
walls: wallMeshes,
setLineColor: (name) =>
setArenaLineColor([grid.material, ...wallMats], name),
update(position) {
grid.position.set(position.x, 0, position.z);
grid.material.uniforms.uFocus.value.copy(position);
@@ -0,0 +1,75 @@
import { generateInteractiveProps } from "../../interactive-props.js";
// One random arrangement for the whole browser session, not one per robot.
// Positions/sizes share the arena's existing robot-relative scale. Reserve
// both bundled spawn anchors so changing robots never starts inside a toy.
export function createSessionEnvironment(random = Math.random) {
let template;
return {
propsFor(world) {
if (world.presentation !== "arena-grid" || !world.boundary) return [];
template ??= generateInteractiveProps({
halfExtent: 2.25,
spawn: [-0.6, 0],
avoid: [[0, 0]],
random,
});
const scale = world.boundary.half_extent / 2.25;
return template.map((spec) => ({
...spec,
pos: spec.pos.map((v) => v * scale),
size: spec.size.map((v) => v * scale),
quat: [...spec.quat],
// Keep larger robots' toys readily pushable, rather than scaling
// mass cubically into heavy obstacles for the humanoid.
mass: spec.mass * scale * scale,
}));
},
};
}
let seed = 123456789;
const testRandom = () =>
(seed = (1664525 * seed + 1013904223) >>> 0) / 4294967296;
const session = createSessionEnvironment(
typeof location !== "undefined" &&
new URLSearchParams(location.search).get("test") === "1"
? testRandom
: Math.random,
);
export const sharedInteractiveProps = (world) => session.propsFor(world);
export function appendInteractivePhysics(doc, specs, { group = 5 } = {}) {
const body = doc.querySelector("worldbody");
const el = (tag, attrs) => {
const node = doc.createElement(tag);
for (const [key, value] of Object.entries(attrs))
node.setAttribute(key, value);
return node;
};
for (const spec of specs) {
if (doc.querySelector(`[name="${spec.name}"]`))
throw new Error(`World name collision: ${spec.name}`);
const prop = el("body", {
name: spec.name,
pos: spec.pos.join(" "),
quat: spec.quat.join(" "),
});
prop.appendChild(el("freejoint", { name: `${spec.name}_joint` }));
prop.appendChild(
el("geom", {
name: `${spec.name}_geom`,
type: spec.type,
size: spec.size.join(" "),
mass: String(spec.mass),
friction: spec.friction ?? "0.5 0.01 0.003",
solref: spec.solref ?? "0.02 1",
condim: "6",
contype: "1",
conaffinity: "1",
group: String(group),
}),
);
body.appendChild(prop);
}
}
+158
View File
@@ -0,0 +1,158 @@
import * as THREE from "three";
// Same mass-scaled spring perturbation as Microduck, applied every physics
// substep. Shared by generic robots for both their body and the arena toys.
export class PhysicsDrag {
constructor({
sim,
camera,
controls,
canvas,
objects,
addressFor,
enabled,
halfExtent,
scale = 1,
}) {
Object.assign(this, {
sim,
camera,
controls,
canvas,
objects,
addressFor,
enabled,
halfExtent,
scale,
});
this.ray = new THREE.Raycaster();
this.ndc = new THREE.Vector2();
this.plane = new THREE.Plane();
this.point = new THREE.Vector3();
this.direction = new THREE.Vector3();
this.listeners = [];
const listen = (type, fn, capture = false) => {
window.addEventListener(type, fn, capture);
this.listeners.push(() => window.removeEventListener(type, fn, capture));
};
listen(
"pointerdown",
(e) => {
if (
e.target !== canvas ||
e.pointerType !== "mouse" ||
e.button !== 0 ||
!enabled()
)
return;
this.setRay(e);
const hit = this.pick();
if (!hit) return;
const address = addressFor(hit.object);
if (!address) return;
this.grab = { ...address, target: [0, 0, 0] };
camera.getWorldDirection(this.direction);
this.plane.setFromNormalAndCoplanarPoint(
this.direction.negate(),
hit.point,
);
this.updateTarget();
controls.enabled = false;
canvas.style.cursor = "grabbing";
this.pointerId = e.pointerId;
try {
canvas.setPointerCapture(e.pointerId);
} catch {
/* unavailable */
}
},
true,
);
listen("pointermove", (e) => {
if (this.grab) {
this.setRay(e);
this.updateTarget();
return;
}
if (
e.target !== canvas ||
e.pointerType !== "mouse" ||
e.buttons ||
!enabled()
)
return;
if (performance.now() - (this.hoverAt ?? 0) < 80) return;
this.hoverAt = performance.now();
this.setRay(e);
canvas.style.cursor = this.pick() ? "grab" : "";
});
for (const type of ["pointerup", "pointercancel", "blur"])
listen(type, () => this.release());
canvas.addEventListener(
"lostpointercapture",
(this.lostCapture = () => this.release()),
);
}
setRay(e) {
const rect = this.canvas.getBoundingClientRect();
this.ndc.set(
((e.clientX - rect.left) / rect.width) * 2 - 1,
-((e.clientY - rect.top) / rect.height) * 2 + 1,
);
this.ray.setFromCamera(this.ndc, this.camera);
}
pick() {
return this.ray.intersectObjects(this.objects(), true).find((hit) => {
for (let o = hit.object; o; o = o.parent) if (!o.visible) return false;
return !!this.addressFor(hit.object);
});
}
updateTarget() {
if (!this.ray.ray.intersectPlane(this.plane, this.point)) return;
const lim = (this.halfExtent ?? 100) - 0.05 * this.scale;
this.grab.target = [
Math.max(-lim, Math.min(lim, this.point.x)),
Math.max(-lim, Math.min(lim, -this.point.z)),
Math.max(0.02 * this.scale, Math.min(0.45 * this.scale, this.point.y)),
];
}
apply() {
const g = this.grab;
if (!g) return;
const { data } = this.sim,
force = [];
for (let i = 0; i < 3; i++)
force[i] =
100 * (g.target[i] - data.qpos[g.qAdr + i]) -
10 * data.qvel[g.dofAdr + i];
const norm = Math.hypot(...force),
clamp = Math.min(1, 200 / (norm || 1));
for (let i = 0; i < 3; i++)
data.xfrc_applied[g.bodyId * 6 + i] = g.mass * force[i] * clamp;
}
release() {
if (this.grab)
this.sim.data.xfrc_applied.fill(
0,
this.grab.bodyId * 6,
this.grab.bodyId * 6 + 6,
);
this.grab = null;
this.controls.enabled = true;
this.canvas.style.cursor = "";
const id = this.pointerId;
this.pointerId = undefined;
if (id !== undefined) {
try {
this.canvas.releasePointerCapture(id);
} catch {
/* already released */
}
}
}
dispose() {
this.release();
this.listeners.forEach((remove) => remove());
this.canvas.removeEventListener("lostpointercapture", this.lostCapture);
}
}
+1
View File
@@ -51,6 +51,7 @@ export class BodyVisuals {
visuals.scenes.push(...gltf.scenes);
const frame = new THREE.Group();
frame.name = `body-visual:${spec.body}`;
frame.userData.bodyId = ids[i];
gltf.scene.position.fromArray(spec.position ?? [0, 0, 0]);
gltf.scene.quaternion.fromArray(spec.quaternion ?? [0, 0, 0, 1]);
frame.add(gltf.scene);
+75 -1
View File
@@ -16,6 +16,8 @@ import { SkillManager } from "../skills/SkillManager.js";
import { InputRouter } from "../input/InputRouter.js";
import { RigRenderer } from "../render/RigRenderer.js";
import { ChaseCamera } from "../render/ChaseCamera.js";
import { PhysicsDrag } from "../input/PhysicsDrag.js";
import { createInteractivePropVisuals } from "../../game/interactive-props.js";
export class RobotRuntime {
static async load(options) {
@@ -175,7 +177,14 @@ export class RobotRuntime {
},
});
this.scene.add(this.rig.root);
if (this.worldPresentation) this.scene.add(this.worldPresentation.root);
this.lineColor = this.environmentSettings?.lineColor ?? "classic";
if (this.worldPresentation) {
this.scene.add(this.worldPresentation.root);
this.worldPresentation.setLineColor(this.lineColor);
}
this.propsVisuals = createInteractivePropVisuals(this.sim.interactiveSpecs);
this.scene.add(this.propsVisuals.root);
this.syncProps();
this.follow = new THREE.Vector3();
}
activate({ paused = false } = {}) {
@@ -192,6 +201,35 @@ export class RobotRuntime {
this.config.render.camera,
);
this.restoreCamera();
this.drag = new PhysicsDrag({
sim: this.sim,
camera: this.camera,
controls: this.controls,
canvas: this.renderer.domElement,
objects: () => [this.rig.root, this.propsVisuals.root],
enabled: () => this.active && this.scheduler.running && !this.disposed,
halfExtent: this.world.boundary?.half_extent,
scale: this.world.scale ?? 1,
addressFor: (object) => {
const index = object.userData.interactiveIndex;
if (Number.isInteger(index)) return this.sim.propAddresses[index];
const id = object.userData.geomId;
let visualBody = false;
for (let node = object; node; node = node.parent)
if (node.userData.bodyId > 0) visualBody = true;
if (
!visualBody &&
(id === undefined || this.sim.model.geom_bodyid[id] === 0)
)
return null;
return {
bodyId: this.sim.root,
qAdr: this.sim.rootQpos,
dofAdr: this.sim.rootDof,
mass: this.sim.model.body_subtreemass[this.sim.root],
};
},
});
this.input.init();
if (!paused) this.resume();
else this.onStatus({ paused: true });
@@ -213,6 +251,11 @@ export class RobotRuntime {
}
status() {
return {
lineColor: this.lineColor,
runtimeCapabilities: {
environmentControls: !!this.worldPresentation,
physicalDrag: true,
},
policyStatus: this.policyStatus(),
actuationLabel:
this.config.actuation.type === "joint_pd"
@@ -220,6 +263,18 @@ export class RobotRuntime {
: "",
};
}
setLineColor(name) {
if (!this.worldPresentation?.setLineColor(name)) return;
this.lineColor = name;
this.onStatus({ lineColor: name });
}
syncProps() {
this.propsVisuals.sync(
this.sim.data,
this.sim.propAddresses,
!this.sim.propsParked,
);
}
policyStatus() {
return this.policyState.episodes.size
? `Skill: ${this.policyState.active} · ${this.policyState.state}`
@@ -241,6 +296,7 @@ export class RobotRuntime {
if (!paused) this.resume();
}
async pause() {
this.drag?.release();
this.input.clear();
await this.scheduler.pause();
this.onStatus({ paused: true });
@@ -260,6 +316,7 @@ export class RobotRuntime {
async #reset() {
const running = this.scheduler.running;
await this.scheduler.pause();
this.drag?.release();
this.input.clear();
this.ctx.command.fill(0);
for (const policy of this.policies.values()) policy.reset();
@@ -278,6 +335,7 @@ export class RobotRuntime {
this.onStatus({ fallen: false });
this.publishPolicyStatus();
this.rig.sync();
this.syncProps();
if (running) this.scheduler.start();
}
triggerAction(action) {
@@ -313,8 +371,10 @@ export class RobotRuntime {
}
for (let i = 0; i < this.config.sim.decimation; i++) {
this.actuation.apply();
this.drag?.apply();
this.sim.step();
}
this.sim.restoreEscapedProps(this.world.boundary?.half_extent);
const q = this.sim.data.qpos,
a = this.sim.rootQpos,
quat = this.sim.data.xquat,
@@ -356,6 +416,7 @@ export class RobotRuntime {
frame() {
if (this.disposed) return;
this.rig.sync();
this.syncProps();
if (this.chaseCamera) {
const yaw = this.cameraPose();
this.worldPresentation?.update(this.follow);
@@ -395,6 +456,17 @@ export class RobotRuntime {
},
scene: this.scene,
world: this.world,
get interactiveProps() {
return self.sim.interactiveSpecs.map((spec, i) => ({
...spec,
...self.sim.propAddresses[i],
}));
},
setPropsParked: (parked) => {
this.drag?.release();
this.sim.setPropsParked(parked);
this.syncProps();
},
command: this.input.command,
get lastAction() {
return self.policies.get(self.activePolicy).ctx.lastAction;
@@ -444,6 +516,8 @@ export class RobotRuntime {
this.active = false;
await this.scheduler.dispose();
this.input.dispose();
this.drag?.dispose();
this.propsVisuals.dispose();
this.chaseCamera?.dispose();
this.controls?.dispose();
this.worldPresentation?.dispose();
@@ -82,6 +82,9 @@ export class RuntimeManager {
camera,
renderer: this.renderer,
autoStart: false,
environmentSettings: {
lineColor: this.getState().lineColor ?? "classic",
},
publish,
onStatus: publish,
onTelemetry: (telemetry) => publish({ telemetry }),
+4 -1
View File
@@ -1,5 +1,6 @@
import { arenaWalls } from "../worlds/arena.js";
export function composeScene(xml, config, world) {
import { appendInteractivePhysics } from "../../game/worlds/arena/session-environment.js";
export function composeScene(xml, config, world, interactiveProps = []) {
const doc = new DOMParser().parseFromString(xml, "text/xml");
if (
doc.querySelector("parsererror") ||
@@ -9,6 +10,7 @@ export function composeScene(xml, config, world) {
const option =
doc.querySelector("mujoco > option") ?? doc.createElement("option");
option.setAttribute("timestep", String(config.sim.timestep));
if (interactiveProps.length) option.setAttribute("jacobian", "dense");
if (!option.parentNode) doc.documentElement.append(option);
if (world.type !== "flat")
throw new Error(`World ${world.id}: generic composer requires flat World`);
@@ -44,5 +46,6 @@ export function composeScene(xml, config, world) {
worldbody.append(geom);
}
}
appendInteractivePhysics(doc, interactiveProps);
return new XMLSerializer().serializeToString(doc);
}
+47 -3
View File
@@ -1,5 +1,10 @@
import { fetchChecked } from "../loader/PackageLoader.js";
import { composeScene } from "./SceneComposer.js";
import { sharedInteractiveProps } from "../../game/worlds/arena/session-environment.js";
import {
resolvePropAddresses,
resetProp,
} from "../../game/interactive-props.js";
export function resolveAddresses(mujoco, model, names) {
const joints = new Map();
for (const name of names) {
@@ -42,14 +47,23 @@ export class SimCore {
pkg.config.assets.forEach((a, i) =>
vfs.addBuffer(a.vfs, new Uint8Array(buffers[i])),
);
const interactiveSpecs = sharedInteractiveProps(world);
const xml = composeScene(
await fetchChecked(pkg.asset(pkg.config.model)),
pkg.config,
world,
interactiveSpecs,
);
model = mujoco.MjModel.from_xml_string(xml, vfs);
data = new mujoco.MjData(model);
return new SimCore(mujoco, model, data, vfs, pkg.config);
return new SimCore(
mujoco,
model,
data,
vfs,
pkg.config,
interactiveSpecs,
);
} catch (error) {
data?.delete();
model?.delete();
@@ -57,8 +71,10 @@ export class SimCore {
throw error;
}
}
constructor(mujoco, model, data, vfs, config) {
Object.assign(this, { mujoco, model, data, vfs, config });
constructor(mujoco, model, data, vfs, config, interactiveSpecs = []) {
Object.assign(this, { mujoco, model, data, vfs, config, interactiveSpecs });
this.propAddresses = resolvePropAddresses(mujoco, model, interactiveSpecs);
this.propsParked = false;
const names = [...new Set(Object.values(config.joints.groups).flat())];
this.joints = resolveAddresses(mujoco, model, names);
for (const [name, j] of this.joints) {
@@ -119,8 +135,36 @@ export class SimCore {
for (const [name, joint] of this.joints)
data.qpos[joint.qpos] =
config.base.initial?.[name] ?? defaults.get(name) ?? 0;
this.resetProps();
mujoco.mj_forward(model, data);
}
resetProps() {
this.interactiveSpecs.forEach((spec, i) =>
resetProp(this.data, this.propAddresses[i], spec, this.propsParked, i),
);
}
setPropsParked(parked) {
this.propsParked = parked;
this.resetProps();
this.mujoco.mj_forward(this.model, this.data);
}
restoreEscapedProps(halfExtent) {
if (this.propsParked || !halfExtent) return;
let restored = false;
this.interactiveSpecs.forEach((spec, i) => {
const a = this.propAddresses[i].qAdr,
q = this.data.qpos;
if (
Math.abs(q[a]) > halfExtent + 0.1 ||
Math.abs(q[a + 1]) > halfExtent + 0.1 ||
q[a + 2] < -0.2
) {
resetProp(this.data, this.propAddresses[i], spec);
restored = true;
}
});
if (restored) this.mujoco.mj_forward(this.model, this.data);
}
step() {
this.mujoco.mj_step(this.model, this.data);
}
+107 -199
View File
@@ -38,8 +38,6 @@ import { ObservationPipeline } from "../../platform/policy/ObservationPipeline.j
import { ActionPipeline } from "../../platform/policy/ActionPipeline.js";
import { NativeActuation } from "../../platform/sim/actuation/JointPdActuation.js";
import {
BALL_RADIUS,
BALL_PARK_POS,
ARENA_HALF as LEGACY_ARENA_HALF,
SPAWN_X,
SPAWN_Y,
@@ -91,7 +89,13 @@ import {
playLineBlip,
setRumble,
} from "../../game/audio.js";
import { createBallActor } from "../../game/ball-actor.js";
import {
resolvePropAddresses,
resetProp,
createInteractivePropVisuals,
} from "../../game/interactive-props.js";
import { setArenaLineColor } from "../../game/worlds/arena/line-color.js";
import { sharedInteractiveProps } from "../../game/worlds/arena/session-environment.js";
import {
loadCustomPolicy as loadCustomPolicyModule,
scriptCommandAt,
@@ -100,7 +104,6 @@ import {
makeInfiniteGrid,
makeArenaWalls,
} from "../../game/worlds/arena/render.js";
import { createBallVisual } from "../../game/ball-visual.js";
import {
useGame,
gameApi,
@@ -133,6 +136,7 @@ export async function bootGame({
world,
autoStart = true,
publish,
environmentSettings,
}) {
const scope = new Disposables();
try {
@@ -149,6 +153,7 @@ export async function bootGame({
world,
autoStart,
publish,
environmentSettings,
});
} catch (err) {
await scope.dispose().catch(console.error);
@@ -167,6 +172,7 @@ async function boot({
world,
autoStart,
publish,
environmentSettings,
}) {
const robot = pkg.config;
const boundary = world.boundary ?? {
@@ -175,6 +181,14 @@ async function boot({
wall_thickness: 0.05,
};
const ARENA_HALF = boundary.half_extent;
const params = new URLSearchParams(location.search);
const testMode = params.get("test") === "1";
const legacyOracle = testMode && params.get("oracle") === "legacy";
const interactiveSpecs = legacyOracle
? (await import("./test-oracle.js")).originalPhysicsProbe()
: sharedInteractiveProps(world);
let propsParked = false;
let propVisuals = null;
const rollerPkg = await loadPackage(
`${import.meta.env.BASE_URL}robots/microduck-rollers/robot.json`,
);
@@ -214,7 +228,6 @@ async function boot({
const bootHalt = (detail) => {
if (!publish) globalBootHalt(detail);
};
const testMode = new URLSearchParams(location.search).get("test") === "1";
const clock = new SimulationClock();
const listen = (target, event, callback, options) =>
scope.listen(target, event, callback, options);
@@ -295,6 +308,8 @@ async function boot({
jointNames: JOINT_NAMES,
defaultPose: DEFAULT_POSE,
spawn: robot.base.spawn,
interactiveProps: interactiveSpecs,
floor: legacyOracle ? undefined : world.floor,
boundary,
});
}
@@ -344,8 +359,10 @@ async function boot({
doneMeshes(`${meshFiles.length} FILES`);
const sessions = {};
// Always boot on the classic (orange) colourway; the quickbar re-skins live.
// The robot retains its palette; the quickbar now tints arena lines.
let currentVariant = DEFAULT_VARIANT;
let lineColor =
environmentSettings?.lineColor ?? store().lineColor ?? DEFAULT_VARIANT;
const rigPromise = (async () => {
const doneRig = bootLine("RENDER RIG");
try {
@@ -566,8 +583,7 @@ async function boot({
mujoco.mjtObj.mjOBJ_KEY.value,
"STAND",
),
ballQposAdr: model.jnt_qposadr[jointId("ball_freejoint")],
ballDofAdr: model.jnt_dofadr[jointId("ball_freejoint")],
propAddresses: resolvePropAddresses(mujoco, model, interactiveSpecs),
// Foot bodies for the footstep audio heuristic (-1 when a variant
// has no ankles, e.g. if a future model renames them).
ankleIds: ["ankle_left", "ankle_right"].map((n) =>
@@ -594,8 +610,7 @@ async function boot({
gyroAdr,
trunkId,
standKeyId,
ballQposAdr,
ballDofAdr,
propAddresses,
extraJoints,
ankleIds,
} = resolveAddrs(model, k);
@@ -651,11 +666,10 @@ async function boot({
// Right-stick camera state, read by the telemetry before the camera-orbit
// section below has evaluated.
let padOrbitLive = false;
// Robot input gate: twist commands, mode changes, rolls, kicks and ball
// spawns all stay inert until the entrance sequence has fully played out.
// Robot input gate: twist commands, mode changes, rolls and kicks
// stay inert until the entrance sequence has fully played out.
let inputLocked = true;
let ceremony = null;
let ball = null;
let stickers = null; // comic popups, currently disabled
let mode = "walk"; // "walk" | "sitstand" | "roll" | "kickL" | "kickR" | "crouch" | "groundpick"
@@ -678,9 +692,6 @@ async function boot({
const HEAD_SIGNS = new Float32Array([1, -1, 1, -1]);
const headTarget = new Float32Array(4);
const headSmooth = new Float32Array(4);
// Local-only kickable ball: false while parked at the keyframe spot
// (mesh hidden), true once popped in front of the duck.
let ballActive = false;
// The twist the policy actually receives. Mid-roll every movement input
// is ignored (zero twist) until the roll hands back to walk on its own.
@@ -823,74 +834,26 @@ async function boot({
headTarget.fill(0);
headSmooth.fill(0);
mujoco.mj_resetDataKeyframe(model, data, standKeyId);
interactiveSpecs.forEach((spec, i) =>
resetProp(data, propAddresses[i], spec, propsParked, i),
);
mujoco.mj_forward(model, data);
lastAction.fill(0);
sitFlag = 0;
// Park the ball in physics immediately; if it was on screen, the
// reverse scan peels it away at its last pose. A queued B-respawn is
// cancelled: a reset means no ball.
ball?.despawn({ cancelQueued: true, parkPhysics: parkBallPhysics });
ballActive = false;
propVisuals?.sync(data, propAddresses, !propsParked);
syncButtons();
if (!testMode && ceremony) {
startCameraReset();
spawnBall({ fromQueue: true });
}
if (!testMode && ceremony) startCameraReset();
}
resetSim();
function parkBallPhysics() {
const qpos = data.qpos,
qvel = data.qvel;
qpos[ballQposAdr] = 50;
qpos[ballQposAdr + 1] = 0;
qpos[ballQposAdr + 2] = BALL_RADIUS;
qpos[ballQposAdr + 3] = 1;
qpos[ballQposAdr + 4] = 0;
qpos[ballQposAdr + 5] = 0;
qpos[ballQposAdr + 6] = 0;
for (let i = 0; i < 6; i++) qvel[ballDofAdr + i] = 0;
mujoco.mj_forward(model, data);
ballActive = false;
}
// Pop / respawn the ball ~0.35 m in front of the duck, with a small
// random heading + distance jitter. If the ball is already on screen,
// peel it away first (reverse scan) and pop the new one when that
// finishes - same appear/disappear pair as the duck's wireframe ceremony.
function spawnBall(opts = {}) {
if (inputLocked && !opts.fromQueue) return;
if (!ball) return;
if (ball.visual !== "hidden") {
ball.queueRespawn();
ball.despawn({ parkPhysics: parkBallPhysics });
return;
}
const qpos = data.qpos,
qvel = data.qvel;
const yaw = Math.atan2(
2 * (qpos[3] * qpos[6] + qpos[4] * qpos[5]),
1 - 2 * (qpos[5] * qpos[5] + qpos[6] * qpos[6]),
function setPropsParked(parked) {
endGrabHook();
propsParked = parked;
interactiveSpecs.forEach((spec, i) =>
resetProp(data, propAddresses[i], spec, parked, i),
);
const heading = yaw + (Math.random() - 0.5) * 0.7;
const dist = 0.35 + (Math.random() - 0.5) * 0.1;
const lim = ARENA_HALF - BALL_RADIUS - 0.05;
const clamp = (v) => Math.min(lim, Math.max(-lim, v));
qpos[ballQposAdr] = clamp(qpos[0] + Math.cos(heading) * dist);
qpos[ballQposAdr + 1] = clamp(qpos[1] + Math.sin(heading) * dist);
qpos[ballQposAdr + 2] = BALL_RADIUS + 0.02;
qpos[ballQposAdr + 3] = 1;
qpos[ballQposAdr + 4] = 0;
qpos[ballQposAdr + 5] = 0;
qpos[ballQposAdr + 6] = 0;
for (let i = 0; i < 6; i++) qvel[ballDofAdr + i] = 0;
mujoco.mj_forward(model, data);
ballActive = true;
// Snap the mesh to the new pose BEFORE the scan starts: the FX
// recomputes its bbox from the live mesh.
ball.poseFromQpos(qpos, ballQposAdr);
ball.appear();
stickers?.pop("spawn");
propVisuals?.sync(data, propAddresses, !parked);
}
// ── Observation ─────────────────────────────────────────────────────
@@ -1015,14 +978,13 @@ async function boot({
return null;
}
// ── Sim-driven audio (footsteps / roller rumble / ball impacts) ──────
// ── Sim-driven audio (footsteps / roller rumble / body bumps) ───────
// Footsteps use a per-foot height heuristic instead of MuJoCo contacts
// (the WASM bindings expose no contact array): each ankle's height
// RELATIVE to the lower ankle (the planted foot approximates the local
// ground, so the measure self-calibrates on the relief terrain), with
// lift/contact hysteresis and a per-foot debounce. Tap gain scales with
// the landing speed. Rollers get a speed-following rumble loop instead,
// and the ball thumps on velocity deltas between control steps.
// the landing speed. Rollers get a speed-following rumble loop instead.
const STEP_LIFT = 0.012; // m above the planted foot = foot in swing
const STEP_CONTACT = 0.005; // m: dropping below this while in swing = step
const STEP_DEBOUNCE_MS = 130;
@@ -1031,18 +993,11 @@ async function boot({
{ air: false, prevZ: 0, lastAt: 0 },
];
const duckEmitter = createEmitter({ refDistance: 0.5 });
const ballEmitter = createEmitter({ refDistance: 0.5 });
scope.add(() => {
duckEmitter.node.disconnect();
ballEmitter.node.disconnect();
});
const ballPrevV = [0, 0, 0];
let ballPrevValid = false;
let ballThumpAt = 0;
scope.add(() => duckEmitter.node.disconnect());
// Body bumps: trunk velocity deltas gated on obstacle proximity (walls
// or prop collider footprints) so the walking gait's own accelerations
// (comparable in magnitude to a slow wall hit) never false-trigger.
// Duller than the ball thumps: same samples pitched way down.
// Low-pitched impact samples for body bumps.
const BUMP_DV = 0.35; // m/s per control step
const BUMP_DEBOUNCE_MS = 300; // rubbing a wall must not machine-gun
const BUMP_WALL_PAD = 0.16; // trunk half-width-ish reach to a wall
@@ -1126,7 +1081,7 @@ async function boot({
const u = Math.min(1, (dv - BUMP_DV) / 1.5);
playSfx("thump", {
gain: 0.12 + 0.3 * u,
rate: 0.55 + 0.15 * u + Math.random() * 0.06, // way below the ball's range
rate: 0.55 + 0.15 * u + Math.random() * 0.06, // low-pitched body impact
out: duckEmitter.node,
});
haptics.pulse("bump", 0.5 + 0.5 * u); // shove felt in the hands
@@ -1139,42 +1094,6 @@ async function boot({
} else {
bumpPrevValid = false;
}
// Ball impacts: |dv| between control steps. Gravity alone accounts for
// ~0.2 m/s per 20 ms step; the 0.5 threshold clears it and rolling noise.
if (ballActive) {
const v = data.qvel;
const b = ballDofAdr;
if (ballPrevValid) {
const dv = Math.hypot(
v[b] - ballPrevV[0],
v[b + 1] - ballPrevV[1],
v[b + 2] - ballPrevV[2],
);
if (dv > 0.5 && now - ballThumpAt > 90) {
ballThumpAt = now;
const u = Math.min(1, (dv - 0.5) / 3.5); // full at kick-grade hits
playSfx("thump", {
gain: 0.14 + 0.4 * u,
rate: 1.25 - 0.45 * u + Math.random() * 0.08,
out: ballEmitter.node,
});
// Haptics only when the duck plausibly caused/received the hit:
// a far bounce off a wall shouldn't shake the hands.
const bq = ballQposAdr;
const dBall = Math.hypot(
data.qpos[bq] - data.qpos[0],
data.qpos[bq + 1] - data.qpos[1],
);
if (dBall < 0.6) haptics.pulse("ballHit", 0.4 + 0.6 * u);
}
}
ballPrevV[0] = v[b];
ballPrevV[1] = v[b + 1];
ballPrevV[2] = v[b + 2];
ballPrevValid = true;
} else {
ballPrevValid = false;
}
// Haptic channel scheduler: keeps the roller bed alive between pulses
// and cuts the motors when it falls silent. 50 Hz, like everything here.
haptics.tick();
@@ -1220,7 +1139,7 @@ async function boot({
applyGrabForce(); // mouse perturbation, fresh velocity every substep
mujoco.mj_step(model, data);
}
stepAudioSim(); // footsteps / rumble / ball thumps off the fresh state
stepAudioSim(); // footsteps / rumble / body bumps off the fresh state
// Command script clock: 50 Hz like everything here. A non-looping
// script ends on its own; a looping one runs until R (or a reset).
@@ -1317,14 +1236,22 @@ async function boot({
fallenSince = null;
}
// Ball respawn watchdog: outside the arena bounds means "escaped
// through a solver glitch", bring it back near the duck.
if (ballActive) {
const q = data.qpos;
const escaped =
Math.abs(q[ballQposAdr]) > ARENA_HALF + 0.1 ||
Math.abs(q[ballQposAdr + 1]) > ARENA_HALF + 0.1;
if (escaped) spawnBall();
// Return escaped toys individually without disturbing the robot or peers.
if (!propsParked) {
let restored = false;
interactiveSpecs.forEach((spec, i) => {
const a = propAddresses[i].qAdr,
q = data.qpos;
if (
Math.abs(q[a]) > ARENA_HALF + 0.1 ||
Math.abs(q[a + 1]) > ARENA_HALF + 0.1 ||
q[a + 2] < -0.2
) {
resetProp(data, propAddresses[i], spec);
restored = true;
}
});
if (restored) mujoco.mj_forward(model, data);
}
if (postKickLock > 0 && mode === "walk") postKickLock--;
@@ -1469,7 +1396,7 @@ async function boot({
// Released before models/sessions, even when boot or a later lazy load fails.
scope.add(() => scheduler.dispose());
// ── Scene wiring (grid, walls, rig, ball, arcade row) ────────────────
// ── Scene wiring (grid, walls, rig, interactive toys, arcade row) ────
// The grid/walls carry ceremony-driven uReveal uniforms and per-frame
// focus updates, so the game owns them; lights and environment live in
// the R3F layer.
@@ -1478,6 +1405,11 @@ async function boot({
reliefGridMat = grid.material; // relief drive mirrors uTopoScale into it
const { wallMats, wallMeshes } = makeArenaWalls(boundary);
for (const m of wallMeshes) scene.add(m);
grid.name = "arena-grid";
setArenaLineColor([grid.material, ...wallMats], lineColor);
propVisuals = createInteractivePropVisuals(interactiveSpecs);
scene.add(propVisuals.root);
propVisuals.sync(data, propAddresses, !propsParked);
let rig = await rigPromise;
scene.add(rig.placer);
@@ -1493,9 +1425,9 @@ async function boot({
gyroAdr,
trunkId,
standKeyId,
ballQposAdr,
ballDofAdr,
propAddresses,
extraJoints,
ankleIds,
};
// ── Locomotion variant switching (legs <-> rollers) ──────────────────
@@ -1572,8 +1504,7 @@ async function boot({
gyroAdr,
trunkId,
standKeyId,
ballQposAdr,
ballDofAdr,
propAddresses,
extraJoints,
ankleIds,
} = L);
@@ -1664,10 +1595,6 @@ async function boot({
setLocked: (v) => {
inputLocked = v;
controller.setLocked(v);
// A ball is always in play: pop one the moment the entrance or a
// respawn ceremony hands control back.
if (!v && ball && !ballActive && !testMode)
spawnBall({ fromQueue: true });
},
flashReset: () => {},
// Audio twins of the wireframe materialize FX (entrance and respawns):
@@ -1693,19 +1620,6 @@ async function boot({
{ fireImmediately: true },
);
const { group: ballGroup, mesh: ballMesh } = createBallVisual(renderer);
scene.add(ballGroup);
ball = createBallActor({
THREE,
scene,
camera,
renderer,
fxModule: fx,
mesh: ballMesh,
group: ballGroup,
});
scope.add(() => ball.dispose());
// ── Prop library (wall/corner dressing + entrance FX) ────────────────
// Every enabled def in props.js: loaded, real-size scaled, floor
// snapped, wireframe-materialized with the ceremony (staggered after
@@ -1876,7 +1790,7 @@ async function boot({
}
// ── Mouse grab, pointer side (pick + drag target + cursor) ────────────
// Pointer-down on the duck (or the live ball) grabs it; anywhere else
// Pointer-down on the duck or an interactive toy grabs it; anywhere else
// falls through to OrbitControls untouched. The pick is a three.js
// raycast against the render rig (the WASM bindings expose no
// mjv_select, and the rig IS the duck's collision-accurate silhouette
@@ -1902,13 +1816,19 @@ async function boot({
}
function grabPick() {
const duckHit = _grabRaycaster.intersectObject(rig.placer, true)[0];
const ballHit = ballActive
? _grabRaycaster.intersectObject(ballMesh, true)[0]
const propHit = !propsParked
? _grabRaycaster.intersectObjects(propVisuals.meshes, false)[0]
: undefined;
if (duckHit && (!ballHit || duckHit.distance <= ballHit.distance)) {
if (duckHit && (!propHit || duckHit.distance <= propHit.distance)) {
return { kind: "duck", point: duckHit.point };
}
return ballHit ? { kind: "ball", point: ballHit.point } : null;
return propHit
? {
kind: "prop",
point: propHit.point,
index: propHit.object.userData.interactiveIndex,
}
: null;
}
function updateGrabTarget() {
if (!_grabRaycaster.ray.intersectPlane(_grabPlane, _grabHit)) return;
@@ -1956,18 +1876,7 @@ async function boot({
dofAdr: 0,
mass: model.body_subtreemass[trunkId],
}
: {
bodyId: mujoco.mj_name2id(
model,
mujoco.mjtObj.mjOBJ_BODY.value,
"ball",
),
qAdr: ballQposAdr,
dofAdr: ballDofAdr,
mass: model.body_mass[
mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY.value, "ball")
],
};
: propAddresses[pick.index];
camera.getWorldDirection(_grabCamDir);
_grabPlane.setFromNormalAndCoplanarPoint(
_grabCamDir.negate(),
@@ -2050,8 +1959,7 @@ async function boot({
setJoint(rig, JOINT_NAMES[j], qpos[qposAdr[j]]);
// Passive hinges (roller wheels): purely visual, driven straight from qpos.
for (const ej of extraJoints) setJoint(rig, ej.name, qpos[ej.adr]);
// Ball: live follows qpos; ghost freeze is owned by the ball actor.
if (ball) ball.sync(qpos, ballQposAdr, ballActive);
propVisuals?.sync(data, propAddresses, !propsParked);
// Follow cam: ease the orbit target toward the trunk and translate the
// camera by the same delta, so the camera-to-duck distance and viewing
// angle stay constant while the duck walks. Paused while the reset
@@ -2372,18 +2280,9 @@ async function boot({
syncRig();
syncJaw();
ghosts?.update();
// Spatial audio follows the movers: listener on the camera, emitters
// on the duck trunk and the ball (MJCF Z-up -> three Y-up).
// Spatial audio: listener on the camera, emitter on the duck trunk.
updateListener(camera);
duckEmitter.setPosition(data.qpos[0], data.qpos[2], -data.qpos[1]);
if (ballActive) {
const q = data.qpos;
ballEmitter.setPosition(
q[ballQposAdr],
q[ballQposAdr + 2],
-q[ballQposAdr + 1],
);
}
controls.update();
updateChaseCam();
if (helperCamera !== camera) {
@@ -2391,7 +2290,6 @@ async function boot({
helperCamera.copy(camera);
}
ceremony.drive();
ball.drive(() => spawnBall({ fromQueue: true }));
waypointMarker.update(dt, waypointSource.target);
renderTelemetry();
}
@@ -2408,7 +2306,6 @@ async function boot({
controller.on("reset", () => gameApi.reset?.());
controller.on("reset", () => waypointSource.cancel());
controller.on("spawnBall", () => spawnBall());
controller.on("headToggle", () => toggleHeadMode());
controller.on("chaseToggle", () => startCameraReset());
controller.on("locoToggle", () => toggleLoco());
@@ -2604,7 +2501,7 @@ async function boot({
mode = foot === "left" ? "kickL" : "kickR";
sitFlag = 0;
kickRun = { steps: 0 };
haptics.pulse("kick"); // swing launch; ball contact adds ballHit
haptics.pulse("kick"); // swing launch
syncButtons();
stickers?.pop("kick");
return true;
@@ -2634,7 +2531,6 @@ async function boot({
? "Drive"
: "Run";
if (store().modeLabel !== label) setStore({ modeLabel: label });
if (store().ballActive !== ballActive) setStore({ ballActive });
}
// ── Public surface for the React UI ──────────────────────────────────
@@ -2666,9 +2562,14 @@ async function boot({
loco,
locoWant: loco,
variant: currentVariant,
lineColor,
modeLabel: store().modeLabel,
inputBindings: robot.input.bindings,
runtimeCapabilities: { duckControls: true, physicalDrag: true },
runtimeCapabilities: {
duckControls: true,
environmentControls: true,
physicalDrag: true,
},
}),
triggerAction: (action) => {
if (
@@ -2678,7 +2579,10 @@ async function boot({
)
kbSource.onAction(action);
},
saveSettings: () => ({ variant: currentVariant, loco: store().locoWant }),
saveSettings: () => ({
variant: currentVariant,
loco: store().locoWant,
}),
restoreSettings: async (settings) => {
if (settings?.variant) runtime.setVariant(settings.variant);
if (settings?.loco)
@@ -2727,13 +2631,17 @@ async function boot({
applyVariant(rig, name);
setStore({ variant: name });
},
setLineColor: (name) => {
if (!setArenaLineColor([grid.material, ...wallMats], name)) return;
lineColor = name;
setStore({ lineColor: name });
},
requestLoco: (name) => {
if (name !== "legs" && name !== "rollers") return;
setStore({ locoWant: name });
reconcileLoco();
},
resetSim,
spawnBall: () => spawnBall(),
startEntrance: () => ceremony.startEntrance(),
loadCustomPolicy: (ref) => loadCustomPolicyIntoGame(ref),
clearCustomPolicy: () => revertCustomPolicy(),
@@ -2768,7 +2676,13 @@ async function boot({
controller,
kbSource,
padSource,
spawnBall,
get interactiveProps() {
return interactiveSpecs.map((spec, i) => ({
...spec,
...propAddresses[i],
}));
},
setPropsParked,
triggerKick,
triggerRoll,
sessions,
@@ -2828,12 +2742,6 @@ async function boot({
toggleHeadMode,
headTarget,
headSmooth,
get ballActive() {
return ballActive;
},
get ballQposAdr() {
return ballQposAdr;
},
get chaseCam() {
return chaseCam;
},
@@ -2884,7 +2792,7 @@ async function boot({
await scheduler.pause();
ceremony.setReveal(1);
ceremony.setFx(1);
parkBallPhysics();
setPropsParked(true);
inputLocked = false;
controller.setLocked(false);
}
+20
View File
@@ -0,0 +1,20 @@
// Archived policy goldens were recorded with exactly one parked sphere.
// Extra free DOFs change MuJoCo floating-point accumulation (especially
// wheel contact), even when the new toys are parked far away. Reproduce
// that original laboratory world ONLY for ?test=1&oracle=legacy. Normal
// simulation and scene-interaction tests always use the 5–7 toy layout.
export function originalPhysicsProbe() {
return [
{
name: "interactive_0",
type: "sphere",
size: [0.05],
pos: [50, 0, 0.05],
quat: [1, 0, 0, 0],
mass: 0.03,
friction: "0.4 0.01 0.003",
solref: "0.03 0.4",
color: 0xf2efe8,
},
];
}
+8 -7
View File
@@ -17,7 +17,7 @@ function Game() {
room.dispose();
pmrem.dispose();
scene.environment = environment.texture;
scene.environmentIntensity = 0.45;
scene.environmentIntensity = 0.7;
bootLog.length = 0;
const manager = new RuntimeManager({
scene,
@@ -44,7 +44,7 @@ function Game() {
for (const method of [
"setVariant",
"requestLoco",
"spawnBall",
"setLineColor",
"loadCustomPolicy",
"clearCustomPolicy",
"triggerAction",
@@ -68,20 +68,21 @@ function Game() {
}, [scene, camera, gl]);
useEffect(() => {
scene.background = new THREE.Color(
theme === "neutral" ? 0x18202b : 0x08080c,
theme === "neutral" ? 0x18202b : 0x151923,
);
gl.setClearColor(scene.background, 1);
}, [scene, gl, theme]);
useFrame((_, dt) => gameApi.frame?.(Math.min(dt, 0.05)));
return (
<>
<ambientLight intensity={0.6} />
<directionalLight position={[2, 4, 2]} intensity={1.6} />
<directionalLight position={[-2, 2, 1.5]} intensity={0.4} />
<ambientLight intensity={0.85} />
<hemisphereLight args={[0xe4edff, 0x66605a, 0.75]} />
<directionalLight position={[2, 4, 2]} intensity={2.0} />
<directionalLight position={[-2, 2, 1.5]} intensity={0.8} />
<directionalLight
color={theme === "neutral" ? 0xbcdcff : 0xffb366}
position={[0, 3, -2]}
intensity={0.7}
intensity={0.85}
/>
</>
);
+1 -1
View File
@@ -38,6 +38,7 @@ export const useGame = create(
locoSwitching: false,
rollersLoading: false, // OSD line while the roller stack streams in
variant: "classic",
lineColor: "classic",
// Community move: null = all-official slots. Written by the game
// (game.js loadCustomPolicyIntoGame / the watchdog) and by App.jsx for
// the boot-time ?move= request.
@@ -47,7 +48,6 @@ export const useGame = create(
customPolicy: null,
padConnected: false,
touchMode: false,
ballActive: false,
// Throttled telemetry block (4 Hz), bottom-right OSD
telemetry: { fps: 0, ctrlHz: 0, speed: 0, odo: 0, peers: 0 },
})),
+1 -1
View File
@@ -125,7 +125,7 @@ export default function ControlsHelp() {
{physicalDrag && (
<>
<br />
Drag robot / ball: apply force
Drag robot / geometry: apply force
</>
)}
</div>
+88 -59
View File
@@ -182,7 +182,8 @@ const hudHitSx = {
};
function Quickbar() {
const variant = useGame((s) => s.variant);
const lineColor = useGame((s) => s.lineColor);
const duckControls = useGame((s) => s.runtimeCapabilities.duckControls);
const locoWant = useGame((s) => s.locoWant);
return (
<Box
@@ -198,10 +199,10 @@ function Quickbar() {
maxWidth: "calc(100vw - 14.5rem)",
}}
>
<HudPlate caption="Color">
<HudPlate caption="Line color">
<Box
role="group"
aria-label="Duck colours"
aria-label="Scene line colours"
sx={{
display: "inline-flex",
alignItems: "stretch",
@@ -210,17 +211,20 @@ function Quickbar() {
}}
>
{Object.entries(VARIANT_SWATCH_HEX).map(([name, hex]) => {
const selected = name === variant;
const selected = name === lineColor;
const label = VARIANT_LABELS[name] ?? name;
return (
<Box
key={name}
component="button"
type="button"
title={label}
aria-label={`${label} colours`}
title={`${label} scene lines`}
aria-label={`${label} scene lines`}
aria-pressed={selected}
onClick={() => { uiClick(); gameApi.setVariant?.(name); }}
onClick={() => {
uiClick();
gameApi.setLineColor?.(name);
}}
sx={{
appearance: "none",
width: CELL_H, // square cell inside frame + padding
@@ -241,55 +245,64 @@ function Quickbar() {
outline: `2px dashed ${CREAM}`,
outlineOffset: -5,
},
"@media (prefers-reduced-motion: reduce)": { animation: "none" },
"@media (prefers-reduced-motion: reduce)": {
animation: "none",
},
}}
/>
);
})}
</Box>
</HudPlate>
<HudPlate caption="Mode">
<Box
role="group"
aria-label="Locomotion mode"
sx={{
display: "inline-flex",
alignItems: "stretch",
height: "100%",
gap: `${CELL_GAP}px`,
}}
>
{[
{ name: "legs", label: "Feet" },
{ name: "rollers", label: "Rollers" },
].map(({ name, label }) => {
const selected = locoWant === name;
return (
<Box
key={name}
component="button"
type="button"
aria-pressed={selected}
onClick={() => { uiClick(); gameApi.requestLoco?.(name); }}
sx={{
...hudHitSx,
px: "1.05rem",
background: selected ? ORANGE : "transparent",
color: selected ? COMIC_INK : "rgba(250, 248, 242, 0.72)",
"&:hover": {
color: selected ? COMIC_INK : CREAM,
background: selected ? ORANGE : "rgba(255, 122, 47, 0.12)",
},
"&:active": { filter: "brightness(0.92)" },
}}
>
{label}
</Box>
);
})}
</Box>
</HudPlate>
<PolicyChip />
{duckControls && (
<HudPlate caption="Mode">
<Box
role="group"
aria-label="Locomotion mode"
sx={{
display: "inline-flex",
alignItems: "stretch",
height: "100%",
gap: `${CELL_GAP}px`,
}}
>
{[
{ name: "legs", label: "Feet" },
{ name: "rollers", label: "Rollers" },
].map(({ name, label }) => {
const selected = locoWant === name;
return (
<Box
key={name}
component="button"
type="button"
aria-pressed={selected}
onClick={() => {
uiClick();
gameApi.requestLoco?.(name);
}}
sx={{
...hudHitSx,
px: "1.05rem",
background: selected ? ORANGE : "transparent",
color: selected ? COMIC_INK : "rgba(250, 248, 242, 0.72)",
"&:hover": {
color: selected ? COMIC_INK : CREAM,
background: selected
? ORANGE
: "rgba(255, 122, 47, 0.12)",
},
"&:active": { filter: "brightness(0.92)" },
}}
>
{label}
</Box>
);
})}
</Box>
</HudPlate>
)}
{duckControls && <PolicyChip />}
{/* Sound is fully disabled for now (SOUND_DISABLED in audio.js) -
the mute toggle comes back with the finished sound design. */}
{/* <SoundToggle /> */}
@@ -307,10 +320,15 @@ function PolicyChip() {
if (cp?.status !== "active") return null;
const title = cp.title || cp.name;
const by = cp.author ? ` by ${cp.author}` : "";
const hint = cp.slot === "trick" || cp.slot === "script" || cp.slot === "sitstand" ? " \u00b7 R" : "";
const hint =
cp.slot === "trick" || cp.slot === "script" || cp.slot === "sitstand"
? " \u00b7 R"
: "";
return (
<HudPlate caption="Playing" captionFill="orange">
<Box sx={{ display: "inline-flex", alignItems: "stretch", height: "100%" }}>
<Box
sx={{ display: "inline-flex", alignItems: "stretch", height: "100%" }}
>
<Box
sx={{
...hudHitSx,
@@ -331,7 +349,10 @@ function PolicyChip() {
component="button"
type="button"
aria-label={`Unload move ${cp.name}`}
onClick={() => { uiClick(); gameApi.clearCustomPolicy?.(); }}
onClick={() => {
uiClick();
gameApi.clearCustomPolicy?.();
}}
sx={{
...hudHitSx,
px: "0.6rem",
@@ -388,7 +409,8 @@ function SoundToggle() {
function Telemetry() {
const t = useGame((s) => s.telemetry);
const odo = t.odo < 1000 ? `${t.odo.toFixed(1)}M` : `${(t.odo / 1000).toFixed(2)}KM`;
const odo =
t.odo < 1000 ? `${t.odo.toFixed(1)}M` : `${(t.odo / 1000).toFixed(2)}KM`;
const lines = [];
if (t.peers) lines.push(`${t.peers + 1} ONLINE`);
lines.push(`${t.speed.toFixed(2)}M/S \u00b7 ODO ${odo}`);
@@ -446,7 +468,11 @@ function OsdLoad() {
{l}
<Box
component="span"
sx={{ display: "inline-block", ml: "0.15em", animation: `${recBlink} 0.8s steps(1) infinite` }}
sx={{
display: "inline-block",
ml: "0.15em",
animation: `${recBlink} 0.8s steps(1) infinite`,
}}
>
{"\u2588"}
</Box>
@@ -500,19 +526,22 @@ function PolicyToast() {
}
export default function Hud() {
const ready = useGame((s) => s.runtimePhase === 'ready');
const ready = useGame((s) => s.runtimePhase === "ready");
const touchMode = useGame((s) => s.touchMode);
const duckControls = useGame((s) => s.runtimeCapabilities.duckControls);
const environmentControls = useGame(
(s) => s.runtimeCapabilities.environmentControls,
);
if (!ready) return null;
if (!duckControls) return <Telemetry />;
if (!duckControls && !environmentControls) return <Telemetry />;
return (
<>
{!touchMode && (
<>
<Quickbar />
<Telemetry />
<OsdLoad />
<PolicyToast />
{duckControls && <OsdLoad />}
{duckControls && <PolicyToast />}
</>
)}
</>