feat: release v0.2 multi-robot simulator

Add declarative robot packages, shared simulation lifecycle and Microban ONNX/PD walking with independent head control.

Unify comic UI and chase camera; default robot packages to a 4.5m arena with real collision walls. Include regression tests, asset provenance/licenses and verification evidence.
This commit is contained in:
2026-10-28 14:00:26 +08:00
parent 44d3681726
commit fa089d5f0c
179 changed files with 28087 additions and 4997 deletions
+37 -72
View File
@@ -1,89 +1,54 @@
// App shell: layers in z order - scene canvas (1), halftone (2), CRT (5),
// HUD + touch overlay (9-12), BIOS readout (20), title menu (30). Also owns
// the pre-game device detection (gamepad, touch) and the title -> enter
// flow. The title menu carries its own loading gate (single central
// spinner), so no separate preboot veil.
// A single simulation surface: loading, errors and pause are inline states,
// never separate title/pause/BIOS screens.
import { useEffect } from "react";
import GameCanvas from "./scene/GameCanvas.jsx";
import { Halftone, CrtOverlay } from "./ui/Overlays.jsx";
import Hud from "./ui/Hud.jsx";
import TouchOverlay from "./ui/TouchOverlay.jsx";
import BiosOverlay from "./ui/BiosOverlay.jsx";
import TitleMenu from "./ui/TitleMenu.jsx";
import { useGame } from "./store.js";
import SimulationToolbar from "./ui/SimulationToolbar.jsx";
import ControlsHelp from "./ui/ControlsHelp.jsx";
import RuntimeStatus from "./ui/RuntimeStatus.jsx";
import { useGame, gameApi } from "./store.js";
export default function App() {
const comic = useGame((s) => s.presentationTheme === "comic");
useEffect(() => {
const params = new URLSearchParams(location.search);
// Gamepad presence for the tutorial variant, before the game controller
// takes over polling (the game loop keeps mirroring it afterwards).
const pollPad = () => {
const gp = [...(navigator.getGamepads?.() ?? [])].find((p) => p && p.connected);
useGame.setState({ padConnected: !!gp });
};
window.addEventListener("gamepadconnected", pollPad);
window.addEventListener("gamepaddisconnected", pollPad);
pollPad();
// Touch detection, latching: (pointer: coarse) OR any real touch proves
// the device (DevTools device modes and hybrid laptops often fail the
// media query). __microduckTouched hands the proof to controls/touch.js
// which boots later. ?touch=1 forces the thumbs on any device.
const coarse = matchMedia("(pointer: coarse)");
const armTouch = () => {
window.__microduckTouched = true;
useGame.setState({ touchMode: true });
};
const onCoarse = () => coarse.matches && armTouch();
if (coarse.matches) armTouch();
else coarse.addEventListener("change", onCoarse);
window.addEventListener("touchstart", armTouch, { once: true, passive: true });
if (params.get("touch") === "1") armTouch();
// ?move=<ref>: request a community move (Academy D7). ref is an
// "org/repo" Hub move, "session:<id>[:<round>]" (a private Academy run,
// served same-origin) or a direct .onnx URL. ?policy= is the legacy
// alias, and ?session=<id>[&round=<r>] is sugar for move=session:<id>:<r>.
// Only the request is recorded here; the game loads it after boot
// (never blocking it) and flips the status to active/error itself.
let moveRef = params.get("move") || params.get("policy");
if (!moveRef && params.get("session")) {
const round = params.get("round");
moveRef = `session:${params.get("session")}${round ? `:${round}` : ""}`;
}
if (moveRef) {
useGame.setState({
customPolicy: { ref: moveRef, name: moveRef, status: "loading" },
});
}
// The title menu opens right away and holds its own loading gate
// (central spinner) until logo, fonts, duck stage and game boot are
// in. ?boot=1 skips the title entirely - testing hook.
if (params.get("boot") === "1") {
useGame.setState({ prebootDone: true, entered: true, menuOpen: false });
} else {
useGame.setState({ prebootDone: true, menuOpen: true });
}
return () => {
window.removeEventListener("gamepadconnected", pollPad);
window.removeEventListener("gamepaddisconnected", pollPad);
coarse.removeEventListener("change", onCoarse);
window.removeEventListener("touchstart", armTouch);
let ref = params.get("move") || params.get("policy");
if (!ref && params.get("session"))
ref = `session:${params.get("session")}${params.get("round") ? `:${params.get("round")}` : ""}`;
if (ref)
useGame.setState({ customPolicy: { ref, name: ref, status: "loading" } });
const onKey = (event) => {
if (
event.code !== "Escape" ||
event.repeat ||
event.target?.closest?.(
'input,textarea,select,[contenteditable="true"]',
)
)
return;
event.preventDefault();
if (useGame.getState().runtimePhase === "ready") {
if (useGame.getState().paused) gameApi.resume?.();
else gameApi.pause?.();
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, []);
return (
<>
<GameCanvas />
<Halftone />
<CrtOverlay />
{comic && (
<>
<Halftone />
<CrtOverlay />
</>
)}
<Hud />
<TouchOverlay />
<BiosOverlay />
<TitleMenu />
<SimulationToolbar />
<ControlsHelp />
<RuntimeStatus />
</>
);
}
+2 -301
View File
@@ -1,301 +1,2 @@
// Arena visuals: the infinite Tron grid floor and the four wall grid
// planes, ported verbatim from the pre-React rl.js. Both carry a uReveal
// uniform for the entrance draw-in (driven by ceremony.js).
import * as THREE from "three";
import {
ARENA_HALF, ARENA_WALL_H, ARENA_WALL_T, GRID_SECTION, RELIEF_BUMPS,
} from "./constants.js";
// Infinite shader grid, ported from drei's <Grid>: anti-aliased world-space
// lines at cell/section frequencies with a radial fade around the duck.
// Lines derive from world coordinates, so re-centering the mesh under the
// camera target every frame makes the grid effectively infinite without any
// visible swimming.
export function makeInfiniteGrid() {
const material = new THREE.ShaderMaterial({
transparent: true,
depthWrite: false,
uniforms: {
uCell: { value: 0.1 },
uSection: { value: GRID_SECTION },
uCellColor: { value: new THREE.Color(0x8e8371) },
uSectionColor: { value: new THREE.Color(0xffb366) },
uFadeDist: { value: 3.0 },
uFocus: { value: new THREE.Vector3() },
// Entrance draw-in progress; 1 = steady state (branch skipped).
// Starts at 0: the world stays hidden behind the welcome modal and
// the BIOS readout until playBios cues startEntrance.
uReveal: { value: 0.0 },
// Relief: 0 = flat, 1 = bumps at full height. Driven by the game's
// relief toggle, mirroring the MuJoCo heightfield's z-size so the
// visual surface and the physics surface are the same function.
uTopoScale: { value: 0.0 },
// (cx, cz, height, radius) per bump, in three.js world coords
// (MJCF y -> -z done here once).
uBumps: {
value: RELIEF_BUMPS.map(
([cx, cy, h, r]) => new THREE.Vector4(cx, -cy, h, r),
),
},
},
vertexShader: /* glsl */ `
#define NBUMPS ${RELIEF_BUMPS.length}
varying vec3 vWorld;
uniform float uTopoScale;
uniform vec4 uBumps[NBUMPS];
// Same analytic relief as the physics heightfield (game.js topoH):
// a sum of cosine bumps, displacing the grid surface itself so the
// floor genuinely deforms - lines flow up the slopes for free since
// the fragment shader draws them from world xz.
float topoH(vec2 p) {
float H = 0.0;
for (int i = 0; i < NBUMPS; i++) {
float u = distance(p, uBumps[i].xy) / uBumps[i].w;
if (u < 1.0) H += uBumps[i].z * (0.5 + 0.5 * cos(3.14159265 * u));
}
return H;
}
void main() {
vec4 w = modelMatrix * vec4(position, 1.0);
if (uTopoScale > 0.0) w.y += topoH(w.xz) * uTopoScale;
vWorld = w.xyz;
gl_Position = projectionMatrix * viewMatrix * w;
}
`,
fragmentShader: /* glsl */ `
varying vec3 vWorld;
uniform float uCell, uSection, uFadeDist, uReveal;
uniform vec3 uCellColor, uSectionColor, uFocus;
// Tron-style line: a thicker antialiased core plus a faint, much
// wider halo added on top (squared falloff keeps it a whisper of a
// glow rather than a bloom wash).
float lineProf(float g) {
float core = 1.0 - smoothstep(0.0, 1.8, g);
float halo = 1.0 - smoothstep(0.0, 7.0, g);
return core + halo * halo * 0.22;
}
float gridLine(vec2 p, float size) {
vec2 r = p / size;
vec2 g = abs(fract(r - 0.5) - 0.5) / fwidth(r);
return lineProf(min(g.x, g.y));
}
// Entrance draw-in: one family of parallel lines, drawn line by line.
// id picks the line, "along" runs down its length. Each line waits
// out its own hashed delay, then extends from the origin outward with
// a hard front. Returns (mask, head): head marks the bright segment
// right behind the draw front while the line is still growing.
vec2 drawLine(float id, float along, float t0, float spread, float dur, float maxLen) {
float jit = fract(sin(id * 127.1) * 43758.5453);
float grow = clamp((uReveal - t0 - jit * spread) / dur, 0.0, 1.0);
float len = grow * maxLen;
float a = abs(along);
float mask = 1.0 - smoothstep(len - 0.05, len, a);
float head = (1.0 - smoothstep(0.0, 0.6, len - a)) * mask
* step(0.001, grow) * (1.0 - step(0.999, grow));
return vec2(mask, head);
}
void main() {
float cell = gridLine(vWorld.xz, uCell);
// Section lattice shifted half a cell: with 5 sections across the
// 3 m arena (odd count) this centers a CELL on the origin and puts
// section lines exactly on the walls at +-1.5.
vec2 pSec = vWorld.xz + 0.5 * uSection;
float section = gridLine(pSec, uSection);
float d = distance(vWorld.xz, uFocus.xz);
float fade = pow(clamp(1.0 - d / uFadeDist, 0.0, 1.0), 1.6);
vec3 col = mix(uCellColor, uSectionColor, clamp(section, 0.0, 1.0));
float alpha = min(max(section * 0.6, cell * 0.4) * fade, 1.0);
// Entrance: only the bright section lines get the line-by-line draw
// (staggered, with a hot draw head); the fine cells just fade in
// over the reveal's second half - drawing every small line reads as
// visual noise. lineProf(min(gx, gy)) == max of per-axis profiles
// (profile is monotonic) and the cell fade lands on exactly the
// steady-state cell term, so at uReveal 1 this branch equals the
// formula above exactly (and is skipped).
if (uReveal < 1.0) {
vec2 rs = pSec / uSection;
vec2 gs = abs(fract(rs - 0.5) - 0.5) / fwidth(rs);
// Const-x lines run along z and vice versa; the offset
// decorrelates the two families' hashed delays.
vec2 sx = drawLine(floor(rs.x + 0.5), vWorld.z, 0.00, 0.30, 0.35, 8.0);
vec2 sz = drawLine(floor(rs.y + 0.5) + 57.0, vWorld.x, 0.05, 0.30, 0.35, 8.0);
float secR = max(lineProf(gs.x) * sx.x, lineProf(gs.y) * sz.x);
float cellR = cell * smoothstep(0.5, 1.0, uReveal);
float headGlow = max(lineProf(gs.x) * sx.y, lineProf(gs.y) * sz.y);
col = mix(uCellColor, uSectionColor, clamp(secR, 0.0, 1.0));
alpha = min(max(secR * 0.6, cellR * 0.4) * fade, 1.0);
// Bright draw head: a short white-hot tip sells the "drawing" read.
headGlow = clamp(headGlow, 0.0, 1.0);
col = mix(col, vec3(1.0, 0.86, 0.55), headGlow * 0.8);
alpha = min(alpha + headGlow * fade * 0.5, 1.0);
}
if (alpha < 0.004) discard;
gl_FragColor = vec4(col, alpha);
}
`,
});
// Subdivided so the relief displacement has vertices to push: ~12 cm
// steps, plenty for the gentle bump radii (>= 0.5 m). The displacement
// is computed in world space, so the per-frame recentering under the
// camera target doesn't move the bumps.
const mesh = new THREE.Mesh(new THREE.PlaneGeometry(30, 30, 256, 256), material);
mesh.rotation.x = -Math.PI / 2;
return mesh;
}
// Arena walls, drawn in the same grid language as the floor: identical
// cell/section lines from world coordinates, same radial fade around the
// duck, plus a vertical fade toward the top edge so the walls read as a
// light enclosure instead of solid slabs.
function makeWallGridMaterial(alongX) {
return new THREE.ShaderMaterial({
transparent: true,
depthWrite: false,
side: THREE.DoubleSide,
uniforms: {
uCell: { value: 0.1 },
uSection: { value: GRID_SECTION },
uCellColor: { value: new THREE.Color(0x8e8371) },
uSectionColor: { value: new THREE.Color(0xffb366) },
// Gentler radial fade than the floor: the walls sit 1.5+ m from the
// duck by construction and would vanish with the floor's 3 m fade.
uFadeDist: { value: 5.0 },
uFocus: { value: new THREE.Vector3() },
uWallH: { value: ARENA_WALL_H },
uAlongX: { value: alongX ? 1.0 : 0.0 },
// Entrance draw-in progress; 1 = steady state (branch skipped).
// Starts at 0, same as the floor grid: hidden until startEntrance.
uReveal: { value: 0.0 },
},
vertexShader: /* glsl */ `
varying vec3 vWorld;
void main() {
vec4 w = modelMatrix * vec4(position, 1.0);
vWorld = w.xyz;
gl_Position = projectionMatrix * viewMatrix * w;
}
`,
fragmentShader: /* glsl */ `
varying vec3 vWorld;
uniform float uCell, uSection, uFadeDist, uWallH, uAlongX, uReveal;
uniform vec3 uCellColor, uSectionColor, uFocus;
// Same Tron-style core + faint halo as the floor grid.
float lineProf(float g) {
float core = 1.0 - smoothstep(0.0, 1.8, g);
float halo = 1.0 - smoothstep(0.0, 7.0, g);
return core + halo * halo * 0.22;
}
float gridLine(vec2 p, float size) {
vec2 r = p / size;
vec2 g = abs(fract(r - 0.5) - 0.5) / fwidth(r);
return lineProf(min(g.x, g.y));
}
// Same line-by-line draw as the floor grid (see its comments).
vec2 drawLine(float id, float along, float t0, float spread, float dur, float maxLen) {
float jit = fract(sin(id * 127.1) * 43758.5453);
float grow = clamp((uReveal - t0 - jit * spread) / dur, 0.0, 1.0);
float len = grow * maxLen;
float a = abs(along);
float mask = 1.0 - smoothstep(len - 0.05, len, a);
float head = (1.0 - smoothstep(0.0, 0.35, len - a)) * mask
* step(0.001, grow) * (1.0 - step(0.999, grow));
return vec2(mask, head);
}
void main() {
// Wall surface coords: the in-plane horizontal world axis + height.
float h = mix(vWorld.z, vWorld.x, uAlongX);
vec2 p = vec2(h, vWorld.y);
float cell = gridLine(p, uCell);
// Horizontal axis shifted half a section to match the floor's odd
// lattice (vertical section lines meet the floor's at the base);
// the height axis keeps its base line at y = 0.
vec2 pSec = vec2(p.x + 0.5 * uSection, p.y);
float section = gridLine(pSec, uSection);
float d = distance(vWorld.xz, uFocus.xz);
float fade = pow(clamp(1.0 - d / uFadeDist, 0.0, 1.0), 1.6);
float vert = 1.0 - clamp(vWorld.y / uWallH, 0.0, 1.0);
vec3 col = mix(uCellColor, uSectionColor, clamp(section, 0.0, 1.0));
float alpha = min(max(section * 0.9, cell * 0.6) * fade * (0.3 + 0.7 * vert), 1.0);
// Entrance: section lines only - horizontals zip out from the
// wall's center, verticals rise from the ground, each with a
// hashed delay; the fine cells fade in over the reveal's second
// half. Same steady-state equivalence argument as the floor grid.
if (uReveal < 1.0) {
vec2 rs = pSec / uSection;
vec2 gs = abs(fract(rs - 0.5) - 0.5) / fwidth(rs);
// Const-height lines run along h (grow from center outward);
// const-h lines run along y (grow up from the ground).
vec2 sh = drawLine(floor(rs.y + 0.5), p.x, 0.00, 0.30, 0.40, 2.0);
vec2 sv = drawLine(floor(rs.x + 0.5) + 31.0, p.y, 0.30, 0.30, 0.30, uWallH);
float secR = max(lineProf(gs.y) * sh.x, lineProf(gs.x) * sv.x);
float cellR = cell * smoothstep(0.5, 1.0, uReveal);
float headGlow = max(lineProf(gs.y) * sh.y, lineProf(gs.x) * sv.y);
col = mix(uCellColor, uSectionColor, clamp(secR, 0.0, 1.0));
alpha = min(max(secR * 0.9, cellR * 0.6) * fade * (0.3 + 0.7 * vert), 1.0);
headGlow = clamp(headGlow, 0.0, 1.0);
col = mix(col, vec3(1.0, 0.86, 0.55), headGlow * 0.8);
alpha = min(alpha + headGlow * fade * 0.5, 1.0);
}
if (alpha < 0.004) discard;
gl_FragColor = vec4(col, alpha);
}
`,
});
}
// Entrance draw-in cue schedule, for the ceremony's per-line audio blips.
// Replicates the shaders' hashed stagger EXACTLY (same hash, same t0 /
// spread constants, same line ids as drawLine's floor(rs + 0.5)), so each
// blip lands the instant its line starts drawing. Times are normalized to
// the respective reveal (0..1); the ceremony maps them to seconds with its
// own grid/wall reveal durations. `u` is the line's jitter, reused by the
// audio side for per-line pitch variation. The four walls share one id
// space, so their lines draw (and blip) in unison - one cue each.
const jitHash = (x) => {
const s = Math.sin(x * 127.1) * 43758.5453;
return s - Math.floor(s);
};
export function entranceLineCues() {
const grid = [];
const walls = [];
// Floor: 6 section lines per axis (world x in {-1.5..1.5} step 0.6 maps
// to ids -2..3); the z family is offset by 57 in the shader.
for (let i = -2; i <= 3; i++) {
const jx = jitHash(i);
const jz = jitHash(i + 57);
grid.push({ at: 0.00 + jx * 0.30, u: jx });
grid.push({ at: 0.05 + jz * 0.30, u: jz });
}
// Walls: one horizontal section line (the y = 0 base, id 0) and 6
// verticals (ids -2..3 offset by 31), per the 0.25 m wall height.
walls.push({ at: 0.00 + jitHash(0) * 0.30, u: jitHash(0) });
for (let i = -2; i <= 3; i++) {
const j = jitHash(i + 31);
walls.push({ at: 0.30 + j * 0.30, u: j });
}
return { grid, walls };
}
// The four wall planes at their inner faces (three coords: MJCF x -> x,
// MJCF y -> -z). Returns the meshes plus their materials (the ceremony and
// the per-frame focus update both need the material list).
export function makeArenaWalls() {
const wallMats = [];
const wallMeshes = [];
const wallLen = 2 * (ARENA_HALF + ARENA_WALL_T);
const wallDefs = [
{ x: ARENA_HALF, z: 0, rotY: -Math.PI / 2, alongX: false },
{ x: -ARENA_HALF, z: 0, rotY: Math.PI / 2, alongX: false },
{ x: 0, z: ARENA_HALF, rotY: Math.PI, alongX: true },
{ x: 0, z: -ARENA_HALF, rotY: 0, alongX: true },
];
for (const w of wallDefs) {
const mat = makeWallGridMaterial(w.alongX);
wallMats.push(mat);
const mesh = new THREE.Mesh(new THREE.PlaneGeometry(wallLen, ARENA_WALL_H), mat);
mesh.position.set(w.x, ARENA_WALL_H / 2, w.z);
mesh.rotation.y = w.rotY;
wallMeshes.push(mesh);
}
return { wallMats, wallMeshes };
}
// Compatibility surface for Microduck effects; World rendering lives with arena.
export * from './worlds/arena/render.js';
+1
View File
@@ -98,5 +98,6 @@ export function createBallActor({ THREE, scene, camera, renderer, fxModule, mesh
sync,
drive,
get visual() { return visual; },
dispose: () => fx.dispose(),
};
}
+19 -111
View File
@@ -1,117 +1,25 @@
// Shared sim constants, lifted verbatim from the pre-React rl.js.
export const POLICY_DIR = "./policies";
export const POLICIES = {
walk: `${POLICY_DIR}/BEST_alpha_walking.onnx`,
sitstand: `${POLICY_DIR}/BEST_alpha_sitstand.onnx`,
roll: `${POLICY_DIR}/roulade.onnx`,
// Blind one-shot kicks (the operator aims the robot, no ball in obs):
// the runtime swaps these in for a 0.5 s window, commands zeroed.
kickL: `${POLICY_DIR}/ball_kick_left.onnx`,
kickR: `${POLICY_DIR}/ball_kick_right.onnx`,
// One-shot ground pick (runtime A button): peck the ground and stand
// back up, phase-driven via [cos, sin, 0] in the command vel slots.
groundpick: `${POLICY_DIR}/alpha_ground_pick.onnx`,
// Get-up policy for the automatic fall recovery (runtime --fall-detect):
// same 61D obs layout as the other alpha policies, commands all zeroed.
stand: `${POLICY_DIR}/BEST_alpha_stand.onnx`,
// Roller variant (lazy-loaded on first switch, never at boot):
// drive = velocity-tracking skating, crouch = one-shot crouch-glide
// driven by a phase encoding in the command slots (ground-pick style).
drive: `${POLICY_DIR}/BEST_roller.onnx`,
crouch: `${POLICY_DIR}/BEST_roller_crouch.onnx`,
};
// From the ONNX metadata (identical for all alpha policies) and the STAND
// keyframe in mjlab's scene_walk.xml. Order matches the actuators in
// the MJCF.
export const JOINT_NAMES = [
"left_hip_yaw", "left_hip_roll", "left_hip_pitch", "left_knee", "left_ankle",
"neck_pitch", "head_pitch", "head_yaw", "head_roll",
"right_hip_yaw", "right_hip_roll", "right_hip_pitch", "right_knee", "right_ankle",
];
export const DEFAULT_POSE = new Float32Array([
0, -0.08726646259971647, -0.457924, -0.004940, 0.452984,
0.3490658503988659, 0.3490658503988659, 0, 0,
0, 0.08726646259971647, 0.457924, 0.004940, -0.452984,
]);
export const NUM_JOINTS = 14;
export const OBS_SIZE = 61;
export const CMD_SIZE = 13;
export const ACTION_SCALE = 1.0;
export const TIMESTEP = 0.005;
export const DECIMATION = 4;
export const CTRL_DT = TIMESTEP * DECIMATION; // 50 Hz
// Velocity command limits, same as infer_policy.py's keyboard mapping.
// No strafe input anymore: the lateral cmd slot stays zeroed for the obs.
export const VEL_FWD = 0.25, VEL_BACK = -0.2, VEL_ANG = 1.0;
// Roller mode limits, from the runtime's roller branch: asymmetric vx
// (0.6 push / 0.5 brake), no lateral. The real runtime launches rollers
// with --max-angular-vel 0.3: faster commanded turns tip the robot over,
// so the playground clamps wz the same way.
export const RVEL_FWD = 0.6, RVEL_BACK = -0.5, RVEL_ANG = 0.3;
// Crouch-glide one-shot: command = [cos(2pi*phase), sin(2pi*phase), 0],
// phase advancing at 1/CROUCH_PERIOD_S per second and the cycle exiting
// at 0.7 - exactly the runtime's ground-pick slot the policy was trained
// against (mjlab CROUCH_PERIOD = 5.0, cycle end 0.7 => 3.5 s gesture).
export const CROUCH_PERIOD_S = 5.0;
export const CROUCH_END_PHASE = 0.7;
// Ground-pick one-shot (legs): same phase encoding, from the runtime's
// defaults (--ground-pick-period 4.0, cycle exiting at 0.7 => ~2.8 s
// gesture, action scale and kP untouched at their 1.0 defaults).
export const GROUND_PICK_PERIOD_S = 4.0;
export const GROUND_PICK_END_PHASE = 0.7;
// Kickable ball: radius and parking spot (far away = hidden by default).
// Arena-only compatibility constants. Robot parameters live in robot.json.
export const BALL_RADIUS = 0.05;
export const BALL_PARK_POS = "50 0 0.05";
// Square arena boxing the play area: static walls at +-ARENA_HALF keep
// the ball (and the duck) inside. Tall enough that neither steps over.
export const ARENA_HALF = 1.5; // inner half-size, m
export const BALL_PARK_POS = '50 0 0.05';
export const ARENA_HALF = 1.5;
export const ARENA_WALL_H = 0.25;
export const ARENA_WALL_T = 0.05;
// Section grid: 5 cells across the 3 m arena (ODD, so a true middle
// column/row of cells exists; the lattice is shifted half a cell in the
// shaders so the walls land exactly on section lines).
export const GRID_SECTION = (2 * ARENA_HALF) / 5; // 0.6 m
// Arcade cabinet row: three cabinets side by side against the front (+X)
// wall, screens facing the arena. Consumed by the prop library (props.js
// "arcade" def - currently benched, enabled: false) for both the clone
// placements and the row's single static collision box. Proportions
// measured from the GLB's natural size (0.524 x 0.587 x 1.0 m, w x d x h).
// Slightly surreal scale: ~2.8x the 0.25 m duck (a real 1.73 m cabinet
// felt overwhelming in the 3 m arena). Big enough to read as oversized
// furniture, small enough that the row (~1.15 m wide, 0.41 m deep)
// leaves the play area open.
export const ARCADE_H = 0.7; // target height, m
export const ARCADE_W = ARCADE_H * 0.524; // footprint width, ~0.22 m
export const ARCADE_D = ARCADE_H * 0.5876; // footprint depth, ~0.247 m
export const ARCADE_GAP = 0.02; // gap between neighbouring cabinets
export const ARCADE_WALL_GAP = 0.01; // clearance between backs and the wall
// Relief (prototype): gentle cosine bumps baked into the level itself.
// One shared analytic height function drives BOTH the physics (a MuJoCo
// heightfield covering the arena) and the visuals (vertex displacement
// of the grid floor shader), so the grid genuinely deforms instead of
// boxes popping out of it. Entries are [cx, cy, height, radius] in MJCF
// coords; slopes stay mild (max grade ~20%) so the blind walking policy
// has a chance, and the spawn cell + arcade row stay flat.
export const GRID_SECTION = (2 * ARENA_HALF) / 5;
export const ARCADE_H = 0.7;
export const ARCADE_W = ARCADE_H * 0.524;
export const ARCADE_D = ARCADE_H * 0.5876;
export const ARCADE_GAP = 0.02;
export const ARCADE_WALL_GAP = 0.01;
// Same analytic bumps drive the arena shader and physics heightfield.
export const RELIEF_BUMPS = [
[0.3, -0.9, 0.06, 0.55],
[-0.9, 0.75, 0.05, 0.5],
[0.6, 0.9, 0.07, 0.55],
[0.3,-0.9,0.06,0.55],
[-0.9,0.75,0.05,0.5],
[0.6,0.9,0.07,0.55],
];
export const RELIEF_HMAX = 0.07; // tallest bump, scales the hfield z-size
export const RELIEF_GRID = 65; // hfield rows/cols over the 3x3 m arena
export const RELIEF_SINK = 0.003; // hfield geom buried below the floor
export const RELIEF_RATE = 0.6; // raise/sink rate, scale units per second
// Spawn: center of the middle section cell in the SECOND ROW FROM THE
// BACK wall. The duck faces +X (identity freejoint quat, walks toward
// local +X), so "back" is the -X wall: row centers sit at x = -1.2,
// -0.6, 0, 0.6, 1.2 -> second row is -0.6; middle column is y = 0.
// MJCF coordinates (three.js: x -> x, y -> -z).
export const SPAWN_X = -ARENA_HALF + 1.5 * GRID_SECTION; // -0.6
export const RELIEF_HMAX = 0.07;
export const RELIEF_GRID = 65;
export const RELIEF_SINK = 0.003;
export const RELIEF_RATE = 0.6;
// Second row from the back; keep arithmetic unchanged for golden snapshots.
export const SPAWN_X = -ARENA_HALF + 1.5 * GRID_SECTION;
export const SPAWN_Y = 0;
+1 -1
View File
@@ -78,7 +78,7 @@
// headToggle HEAD mode on/off (pad Y): sticks drive the head
// sitToggle sit <-> stand (game gates it to legs mode)
// locoToggle legs <-> rollers switch
// chaseToggle chase camera on/off
// chaseToggle restore rear chase camera (legacy action name)
// reset full sim reset (Space)
// walk back to the walk/run mode (pad DpadUp short press)
// quack chirp + jaw flap (pad RT edge, Schmitt-triggered)
+3 -118
View File
@@ -1,118 +1,3 @@
// Keyboard input source (see controller.js for the source interface
// contract). Hold-to-command movement keys plus one-shot action keys.
//
// e.code is the PHYSICAL key position, so one map covers QWERTY and AZERTY:
// arrows / WASD (ZQSD) run + turn. No strafe - vy stays 0.
const KEYMAP = {
ArrowUp: "fwd", KeyW: "fwd",
ArrowDown: "back", KeyS: "back",
ArrowLeft: "turnl", KeyA: "turnl",
ArrowRight: "turnr", KeyD: "turnr",
};
// One-shot keys -> controller actions. Physical Q/E (A/E on AZERTY) are the
// explicit left / right kicks, mirroring the pad's LB / RB; F alternates.
// R sits (crouch-glide in roller mode - the game decides, same way the
// roll action used to). Nothing dispatches "roll" any more.
const ACTION_KEYS = {
KeyC: "chaseToggle",
KeyG: "groundPick",
KeyM: "locoToggle",
KeyR: "sitToggle",
KeyQ: "kickL",
KeyE: "kickR",
KeyF: "alternateKick",
};
export class KeyboardSource {
id = "keyboard";
connected = true; // a keyboard is always assumed present
command = new Float32Array(3); // [vx, 0, wz], scaled to velocity limits
axes = { jaw: 0, orbitX: 0, orbitY: 0 }; // keyboard drives none of these
pressed = { fwd: false, back: false, turnl: false, turnr: false };
onAction = () => {}; // assigned by the Controller at registration
#held = new Set();
#getVelocityLimits;
// Limits snapshot so poll() only re-maps held keys when they actually
// change (the legs <-> rollers switch); event handlers do the live work.
#lims = [NaN, NaN, NaN];
#onKeyDown = null;
#onKeyUp = null;
#onBlur = null;
constructor({ getVelocityLimits }) {
this.#getVelocityLimits = getVelocityLimits;
}
init() {
this.#onKeyDown = (e) => {
if (e.repeat) return;
// Space always resets, and must not scroll the page.
if (e.code === "Space") {
e.preventDefault();
this.onAction("reset");
return;
}
const action = ACTION_KEYS[e.code];
if (action) {
this.onAction(action);
return;
}
const move = KEYMAP[e.code];
if (!move) return;
e.preventDefault();
this.#held.add(move);
this.#refresh();
};
this.#onKeyUp = (e) => {
const move = KEYMAP[e.code];
if (!move) return;
this.#held.delete(move);
this.#refresh();
};
// Losing window focus drops every held key (keyup events are missed).
this.#onBlur = () => {
this.#held.clear();
this.#refresh();
};
window.addEventListener("keydown", this.#onKeyDown);
window.addEventListener("keyup", this.#onKeyUp);
window.addEventListener("blur", this.#onBlur);
}
dispose() {
window.removeEventListener("keydown", this.#onKeyDown);
window.removeEventListener("keyup", this.#onKeyUp);
window.removeEventListener("blur", this.#onBlur);
}
// Claims twist authority while any movement key is held.
isActive() {
return this.#held.size > 0;
}
// The command is event-driven (recomputed on keydown/keyup/blur, so a
// press lands the same tick, not on the next frame); poll only re-maps
// held keys onto fresh velocity limits after a locomotion switch.
poll() {
const [limF, limB, limA] = this.#getVelocityLimits();
if (limF !== this.#lims[0] || limB !== this.#lims[1] || limA !== this.#lims[2]) {
this.#refresh();
}
}
#refresh() {
const lims = this.#getVelocityLimits();
const [limF, limB, limA] = lims;
this.#lims = lims;
const held = this.#held;
this.command[0] = held.has("fwd") ? limF : held.has("back") ? limB : 0;
this.command[2] = held.has("turnl") ? limA : held.has("turnr") ? -limA : 0;
this.pressed.fwd = held.has("fwd");
this.pressed.back = held.has("back");
this.pressed.turnl = held.has("turnl");
this.pressed.turnr = held.has("turnr");
}
}
// Compatibility name for the old Microduck controller. Bindings and hints
// now share the Robot Package and the generic keyboard router.
export { InputRouter as KeyboardSource, isEditingTarget } from '../../platform/input/InputRouter.js';
+4 -2
View File
@@ -42,6 +42,7 @@ export class WaypointSource {
#getVelocityLimits;
#getDuckPose; // () => [x, y, yaw] MJCF ground pose
#isSuppressed; // () => true while a click must not arm (grabbing, locked, wrong mode)
#getArenaHalf;
#getManualOverride; // () => true while another source is actively driving
#target = null; // [x, y] MJCF, or null when idle
#active = false;
@@ -52,13 +53,14 @@ export class WaypointSource {
#onDown = null;
#onUp = null;
constructor({ camera, renderer, getVelocityLimits, getDuckPose, isSuppressed, getManualOverride }) {
constructor({ camera, renderer, getVelocityLimits, getDuckPose, isSuppressed, getManualOverride, getArenaHalf=()=>ARENA_HALF }) {
this.#camera = camera;
this.#renderer = renderer;
this.#getVelocityLimits = getVelocityLimits;
this.#getDuckPose = getDuckPose;
this.#isSuppressed = isSuppressed;
this.#getManualOverride = getManualOverride;
this.#getArenaHalf = getArenaHalf;
}
init() {
@@ -144,7 +146,7 @@ export class WaypointSource {
);
this.#raycaster.setFromCamera(this.#ndc, this.#camera);
if (!this.#raycaster.ray.intersectPlane(FLOOR_PLANE, this.#hit)) return;
const lim = ARENA_HALF - 0.05;
const lim = this.#getArenaHalf() - 0.05;
this.#target = [
Math.min(lim, Math.max(-lim, this.#hit.x)),
Math.min(lim, Math.max(-lim, -this.#hit.z)), // three -> MJCF
+12 -9
View File
@@ -16,7 +16,7 @@
// manifestIncompatibility are reusable by standalone pages without pulling
// the game bundle in.
import { OBS_SIZE, NUM_JOINTS, CMD_SIZE } from "./constants.js";
// Dimensions are supplied by the active Robot Package, never global constants.
const HUB_BASE = "https://huggingface.co";
// Same-origin Academy endpoints (backend/play_api.py) for private moves.
@@ -39,7 +39,7 @@ export function slotForManifest(manifest) {
// Manifest claims the sim cannot satisfy (schema 2). Only present-and-wrong
// claims reject: an absent field is trusted to match the microduck defaults.
// Returns a human-readable reason, or null when the manifest is acceptable.
export function manifestIncompatibility(manifest) {
export function manifestIncompatibility(manifest, {obsSize:OBS_SIZE,actionSize:NUM_JOINTS}={}) {
if (!manifest || typeof manifest !== "object") return null;
if (Array.isArray(manifest.policies)) {
return "multi-policy set: not loadable in v1 (pick a single-policy repo)";
@@ -187,7 +187,8 @@ async function fetchOptionalManifest(url) {
// Command script (kind "script"): {duration_s, loop, keyframes:[{t, cmd[13]}]}.
// Keyframes are sorted by t and every cmd is padded/truncated to CMD_SIZE.
export function normalizeMoveScript(raw) {
export function normalizeMoveScript(raw, CMD_SIZE) {
if(!Number.isInteger(CMD_SIZE)||CMD_SIZE<1)throw new Error('Robot command size required');
if (!raw || typeof raw !== "object" || !Array.isArray(raw.keyframes) || !raw.keyframes.length) {
throw new Error("move_script.json has no keyframes");
}
@@ -221,7 +222,7 @@ export function scriptCommandAt(script, t, out) {
const a = keyframes[i], b = keyframes[i + 1];
if (tt >= a.t && tt <= b.t) {
const u = (tt - a.t) / Math.max(b.t - a.t, 1e-6);
for (let c = 0; c < CMD_SIZE; c++) out[c] = (1 - u) * a.cmd[c] + u * b.cmd[c];
for (let c = 0; c < out.length; c++) out[c] = (1 - u) * a.cmd[c] + u * b.cmd[c];
return out;
}
}
@@ -232,7 +233,7 @@ export function scriptCommandAt(script, t, out) {
// Publish-pipeline smoke run: 1 input / 1 output, a zeros pass plus two
// small-noise passes; every output must be [1,14], finite, and the noisy
// passes must not produce identical actions (a constant net is a dud).
async function validateSession(ort, session) {
async function validateSession(ort, session, {obsSize:OBS_SIZE,actionSize:NUM_JOINTS}) {
const { inputNames, outputNames } = session;
if (inputNames.length !== 1 || outputNames.length !== 1) {
throw new Error(
@@ -279,7 +280,8 @@ async function fetchOrThrow(url, what) {
//
// Result: { kind, slot, name, title, author, academy, ref, actionScale,
// durationS, session?, inputName?, outputName?, script? }
export async function loadCustomPolicy(ref, { ort, onProgress = () => {} } = {}) {
export async function loadCustomPolicy(ref, { ort, dimensions, onProgress = () => {} } = {}) {
if(!dimensions||!['obsSize','actionSize','commandSize'].every(k=>Number.isInteger(dimensions[k])&&dimensions[k]>0))throw new Error('Active Robot Package dimensions required');
const resolved = resolvePolicyRef(ref);
let name = resolved.name;
let author = resolved.author;
@@ -303,7 +305,7 @@ export async function loadCustomPolicy(ref, { ort, onProgress = () => {} } = {})
}
}
if (manifest) {
const reason = manifestIncompatibility(manifest);
const reason = manifestIncompatibility(manifest,dimensions);
if (reason) throw new Error(reason);
if (typeof manifest.name === "string" && manifest.name) name = manifest.name;
if (Number.isFinite(manifest.action_scale)) actionScale = manifest.action_scale;
@@ -331,7 +333,7 @@ export async function loadCustomPolicy(ref, { ort, onProgress = () => {} } = {})
} catch {
throw new Error("move_script.json is not valid JSON");
}
const script = normalizeMoveScript(raw);
const script = normalizeMoveScript(raw,dimensions.commandSize);
return { ...base, script, durationS: script.durationS };
}
@@ -348,7 +350,8 @@ export async function loadCustomPolicy(ref, { ort, onProgress = () => {} } = {})
}
onProgress("validate");
await validateSession(ort, session);
try { await validateSession(ort, session, dimensions); }
catch(error){await session.release();throw error;}
const claimed = Number(manifest?.duration_s ?? manifest?.episode_s ?? manifest?.episode?.duration_s);
const durationS = slot === "trick"
+14 -2
View File
@@ -80,7 +80,7 @@ export function loadGlbGeometries() {
if (o.name && o.name !== name) map.set(o.name, entry);
});
return map;
});
}).catch(error=>{glbGeomsPromise=null;throw error;});
}
return glbGeomsPromise;
}
@@ -277,7 +277,19 @@ export async function buildRig(k, opts = {}) {
}
await Promise.all(pending);
const rig = { placer, root, bodies, joints };
placer.userData.robotRig = true;
const rig = { placer, root, bodies, joints,
dispose: async () => {
for (const material of matCache.values()) material.dispose();
inkMat?.dispose();
for (const geometry of edgeCache.values()) geometry.dispose();
for (const promise of extraStlCache.values()) {
const entry=await promise.catch(()=>null);
entry?.display.dispose(); entry?.welded.dispose();
}
placer.removeFromParent();
},
};
setupJawPivot(rig);
return rig;
}
+3 -2311
View File
File diff suppressed because it is too large Load Diff
+9
View File
@@ -316,6 +316,14 @@ function driveFades() {
fadeRaf = fades.size ? requestAnimationFrame(driveFades) : 0;
}
export function disposeVariantFades(rig) {
rig.root.traverse(mesh => {
const fade=fades.get(mesh);
if(fade){ fades.delete(mesh); fade.mat.dispose(); }
});
if(!fades.size&&fadeRaf){cancelAnimationFrame(fadeRaf);fadeRaf=0;}
}
export function applyVariant(rig, variant) {
const v = typeof variant === "string" ? VARIANTS[variant] : variant;
const map = meshMaterialsFor(v);
@@ -332,6 +340,7 @@ export function applyVariant(rig, variant) {
// Already resting on the target material and not mid-fade: no-op.
if (o.material === target && !fades.has(o)) return;
const from = o.material;
fades.get(o)?.mat.dispose();
const m = target.clone();
m.color.copy(from.color);
m.roughness = from.roughness;
+107
View File
@@ -0,0 +1,107 @@
import { propColliders } from "../../props.js";
import { arenaWalls } from "../../../platform/worlds/arena.js";
import {
ARENA_HALF,
BALL_PARK_POS,
BALL_RADIUS,
RELIEF_GRID,
RELIEF_HMAX,
RELIEF_SINK,
} from "../../constants.js";
// World contribution only. The adapter has already selected/stripped its
// Robot MJCF. Preserve insertion order for existing Microduck keyframes.
export function composeArenaPhysics(
doc,
{
timestep,
jointNames,
defaultPose,
spawn,
boundary = {
half_extent: ARENA_HALF,
wall_height: 0.25,
wall_thickness: 0.05,
},
},
) {
const root = doc.documentElement;
const el = (tag, attrs) => {
const e = doc.createElement(tag);
for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v);
return e;
};
root.appendChild(el("option", { timestep: String(timestep) }));
const body = doc.querySelector("worldbody");
body.appendChild(
el("geom", {
name: "floor",
type: "plane",
size: "0 0 0.05",
pos: "0 0 0",
}),
);
for (const wall of arenaWalls(boundary))
body.appendChild(
el("geom", {
name: wall.name,
type: "box",
pos: wall.pos.join(" "),
size: wall.size.join(" "),
}),
);
for (const c of propColliders()) {
const attrs = { name: c.name, type: "box", pos: c.pos, size: c.size };
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);
doc.querySelector("asset").appendChild(
el("hfield", {
name: "terrain",
nrow: String(RELIEF_GRID),
ncol: String(RELIEF_GRID),
size: `${boundary.half_extent} ${boundary.half_extent} ${RELIEF_HMAX} 0.1`,
}),
);
body.appendChild(
el("geom", {
name: "terrain",
type: "hfield",
hfield: "terrain",
pos: `0 0 ${-RELIEF_SINK}`,
}),
);
const poseByName = new Map(jointNames.map((n, i) => [n, defaultPose[i]]));
const qposJoints = [...doc.querySelectorAll("body > joint")]
.map((j) => poseByName.get(j.getAttribute("name")) ?? 0)
.join(" ");
const qposFree = `${spawn.pos.join(" ")} ${Math.cos(spawn.yaw / 2)} 0 0 ${Math.sin(spawn.yaw / 2)}`;
const keyframe = doc.createElement("keyframe");
keyframe.appendChild(
el("key", {
name: "STAND",
qpos: `${qposFree} ${qposJoints} ${BALL_PARK_POS} 1 0 0 0`,
ctrl: Array.from(defaultPose).join(" "),
}),
);
root.appendChild(keyframe);
return {
xml: new XMLSerializer().serializeToString(doc),
meshFiles: [...doc.querySelectorAll("asset > mesh")].map((m) =>
m.getAttribute("file"),
),
};
}
+63
View File
@@ -0,0 +1,63 @@
import * as THREE from "three";
import { makeInfiniteGrid, makeArenaWalls } from "./render.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 }) {
const names = [
"platform_floor",
...(world?.boundary ? arenaWalls(world.boundary).map((w) => w.name) : []),
];
const hidden = [];
for (const name of names) {
const id = sim.model.geom(name).id,
mesh = rig.items.find((item) => item.id === id)?.mesh;
if (mesh) hidden.push({ mesh, visible: mesh.visible });
else if (name === "platform_floor")
throw new Error(
"arena-grid presentation requires a rendered flat World floor",
);
}
const root = new THREE.Group();
root.name = "arena-floor-presentation";
const grid = makeInfiniteGrid({ subdivisions: 1 });
grid.name = "arena-grid";
grid.material.uniforms.uReveal.value = 1;
grid.material.uniforms.uTopoScale.value = 0;
root.add(grid);
const { wallMeshes, wallMats } = world?.boundary
? makeArenaWalls(world.boundary)
: { wallMeshes: [], wallMats: [] };
wallMeshes.forEach((mesh, i) => {
mesh.name = `arena-boundary-${i}`;
root.add(mesh);
});
wallMats.forEach((mat) => {
mat.uniforms.uReveal.value = 1;
});
hidden.forEach(({ mesh }) => {
mesh.visible = false;
});
let disposed = false;
return {
root,
grid,
walls: wallMeshes,
update(position) {
grid.position.set(position.x, 0, position.z);
grid.material.uniforms.uFocus.value.copy(position);
wallMats.forEach((mat) => mat.uniforms.uFocus.value.copy(position));
},
dispose() {
if (disposed) return;
disposed = true;
root.removeFromParent();
for (const mesh of [grid, ...wallMeshes]) {
mesh.geometry.dispose();
mesh.material.dispose();
}
hidden.forEach(({ mesh, visible }) => {
mesh.visible = visible;
});
},
};
}
+316
View File
@@ -0,0 +1,316 @@
// Arena visuals: the infinite Tron grid floor and the four wall grid
// planes, ported verbatim from the pre-React rl.js. Both carry a uReveal
// uniform for the entrance draw-in (driven by ceremony.js).
import * as THREE from "three";
import {
ARENA_HALF,
ARENA_WALL_H,
ARENA_WALL_T,
GRID_SECTION,
RELIEF_BUMPS,
} from "../../constants.js";
// Infinite shader grid, ported from drei's <Grid>: anti-aliased world-space
// lines at cell/section frequencies with a radial fade around the duck.
// Lines derive from world coordinates, so re-centering the mesh under the
// camera target every frame makes the grid effectively infinite without any
// visible swimming.
export function makeInfiniteGrid({ subdivisions = 256 } = {}) {
const material = new THREE.ShaderMaterial({
transparent: true,
depthWrite: false,
uniforms: {
uCell: { value: 0.1 },
uSection: { value: GRID_SECTION },
uCellColor: { value: new THREE.Color(0x8e8371) },
uSectionColor: { value: new THREE.Color(0xffb366) },
uFadeDist: { value: 3.0 },
uFocus: { value: new THREE.Vector3() },
// Entrance draw-in progress; 1 = steady state (branch skipped).
// Starts at 0: the world stays hidden behind the welcome modal and
// the BIOS readout until playBios cues startEntrance.
uReveal: { value: 0.0 },
// Relief: 0 = flat, 1 = bumps at full height. Driven by the game's
// relief toggle, mirroring the MuJoCo heightfield's z-size so the
// visual surface and the physics surface are the same function.
uTopoScale: { value: 0.0 },
// (cx, cz, height, radius) per bump, in three.js world coords
// (MJCF y -> -z done here once).
uBumps: {
value: RELIEF_BUMPS.map(
([cx, cy, h, r]) => new THREE.Vector4(cx, -cy, h, r),
),
},
},
vertexShader: /* glsl */ `
#define NBUMPS ${RELIEF_BUMPS.length}
varying vec3 vWorld;
uniform float uTopoScale;
uniform vec4 uBumps[NBUMPS];
// Same analytic relief as the physics heightfield (game.js topoH):
// a sum of cosine bumps, displacing the grid surface itself so the
// floor genuinely deforms - lines flow up the slopes for free since
// the fragment shader draws them from world xz.
float topoH(vec2 p) {
float H = 0.0;
for (int i = 0; i < NBUMPS; i++) {
float u = distance(p, uBumps[i].xy) / uBumps[i].w;
if (u < 1.0) H += uBumps[i].z * (0.5 + 0.5 * cos(3.14159265 * u));
}
return H;
}
void main() {
vec4 w = modelMatrix * vec4(position, 1.0);
if (uTopoScale > 0.0) w.y += topoH(w.xz) * uTopoScale;
vWorld = w.xyz;
gl_Position = projectionMatrix * viewMatrix * w;
}
`,
fragmentShader: /* glsl */ `
varying vec3 vWorld;
uniform float uCell, uSection, uFadeDist, uReveal;
uniform vec3 uCellColor, uSectionColor, uFocus;
// Tron-style line: a thicker antialiased core plus a faint, much
// wider halo added on top (squared falloff keeps it a whisper of a
// glow rather than a bloom wash).
float lineProf(float g) {
float core = 1.0 - smoothstep(0.0, 1.8, g);
float halo = 1.0 - smoothstep(0.0, 7.0, g);
return core + halo * halo * 0.22;
}
float gridLine(vec2 p, float size) {
vec2 r = p / size;
vec2 g = abs(fract(r - 0.5) - 0.5) / fwidth(r);
return lineProf(min(g.x, g.y));
}
// Entrance draw-in: one family of parallel lines, drawn line by line.
// id picks the line, "along" runs down its length. Each line waits
// out its own hashed delay, then extends from the origin outward with
// a hard front. Returns (mask, head): head marks the bright segment
// right behind the draw front while the line is still growing.
vec2 drawLine(float id, float along, float t0, float spread, float dur, float maxLen) {
float jit = fract(sin(id * 127.1) * 43758.5453);
float grow = clamp((uReveal - t0 - jit * spread) / dur, 0.0, 1.0);
float len = grow * maxLen;
float a = abs(along);
float mask = 1.0 - smoothstep(len - 0.05, len, a);
float head = (1.0 - smoothstep(0.0, 0.6, len - a)) * mask
* step(0.001, grow) * (1.0 - step(0.999, grow));
return vec2(mask, head);
}
void main() {
float cell = gridLine(vWorld.xz, uCell);
// Section lattice shifted half a cell: with 5 sections across the
// 3 m arena (odd count) this centers a CELL on the origin and puts
// section lines exactly on the walls at +-1.5.
vec2 pSec = vWorld.xz + 0.5 * uSection;
float section = gridLine(pSec, uSection);
float d = distance(vWorld.xz, uFocus.xz);
float fade = pow(clamp(1.0 - d / uFadeDist, 0.0, 1.0), 1.6);
vec3 col = mix(uCellColor, uSectionColor, clamp(section, 0.0, 1.0));
float alpha = min(max(section * 0.6, cell * 0.4) * fade, 1.0);
// Entrance: only the bright section lines get the line-by-line draw
// (staggered, with a hot draw head); the fine cells just fade in
// over the reveal's second half - drawing every small line reads as
// visual noise. lineProf(min(gx, gy)) == max of per-axis profiles
// (profile is monotonic) and the cell fade lands on exactly the
// steady-state cell term, so at uReveal 1 this branch equals the
// formula above exactly (and is skipped).
if (uReveal < 1.0) {
vec2 rs = pSec / uSection;
vec2 gs = abs(fract(rs - 0.5) - 0.5) / fwidth(rs);
// Const-x lines run along z and vice versa; the offset
// decorrelates the two families' hashed delays.
vec2 sx = drawLine(floor(rs.x + 0.5), vWorld.z, 0.00, 0.30, 0.35, 8.0);
vec2 sz = drawLine(floor(rs.y + 0.5) + 57.0, vWorld.x, 0.05, 0.30, 0.35, 8.0);
float secR = max(lineProf(gs.x) * sx.x, lineProf(gs.y) * sz.x);
float cellR = cell * smoothstep(0.5, 1.0, uReveal);
float headGlow = max(lineProf(gs.x) * sx.y, lineProf(gs.y) * sz.y);
col = mix(uCellColor, uSectionColor, clamp(secR, 0.0, 1.0));
alpha = min(max(secR * 0.6, cellR * 0.4) * fade, 1.0);
// Bright draw head: a short white-hot tip sells the "drawing" read.
headGlow = clamp(headGlow, 0.0, 1.0);
col = mix(col, vec3(1.0, 0.86, 0.55), headGlow * 0.8);
alpha = min(alpha + headGlow * fade * 0.5, 1.0);
}
if (alpha < 0.004) discard;
gl_FragColor = vec4(col, alpha);
}
`,
});
// Subdivided so the relief displacement has vertices to push: ~12 cm
// steps, plenty for the gentle bump radii (>= 0.5 m). The displacement
// is computed in world space, so the per-frame recentering under the
// camera target doesn't move the bumps.
const mesh = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30, subdivisions, subdivisions),
material,
);
mesh.rotation.x = -Math.PI / 2;
return mesh;
}
// Arena walls, drawn in the same grid language as the floor: identical
// cell/section lines from world coordinates, same radial fade around the
// duck, plus a vertical fade toward the top edge so the walls read as a
// light enclosure instead of solid slabs.
function makeWallGridMaterial(alongX, wallHeight = ARENA_WALL_H) {
return new THREE.ShaderMaterial({
transparent: true,
depthWrite: false,
side: THREE.DoubleSide,
uniforms: {
uCell: { value: 0.1 },
uSection: { value: GRID_SECTION },
uCellColor: { value: new THREE.Color(0x8e8371) },
uSectionColor: { value: new THREE.Color(0xffb366) },
// Gentler radial fade than the floor: the walls sit 1.5+ m from the
// duck by construction and would vanish with the floor's 3 m fade.
uFadeDist: { value: 5.0 },
uFocus: { value: new THREE.Vector3() },
uWallH: { value: wallHeight },
uAlongX: { value: alongX ? 1.0 : 0.0 },
// Entrance draw-in progress; 1 = steady state (branch skipped).
// Starts at 0, same as the floor grid: hidden until startEntrance.
uReveal: { value: 0.0 },
},
vertexShader: /* glsl */ `
varying vec3 vWorld;
void main() {
vec4 w = modelMatrix * vec4(position, 1.0);
vWorld = w.xyz;
gl_Position = projectionMatrix * viewMatrix * w;
}
`,
fragmentShader: /* glsl */ `
varying vec3 vWorld;
uniform float uCell, uSection, uFadeDist, uWallH, uAlongX, uReveal;
uniform vec3 uCellColor, uSectionColor, uFocus;
// Same Tron-style core + faint halo as the floor grid.
float lineProf(float g) {
float core = 1.0 - smoothstep(0.0, 1.8, g);
float halo = 1.0 - smoothstep(0.0, 7.0, g);
return core + halo * halo * 0.22;
}
float gridLine(vec2 p, float size) {
vec2 r = p / size;
vec2 g = abs(fract(r - 0.5) - 0.5) / fwidth(r);
return lineProf(min(g.x, g.y));
}
// Same line-by-line draw as the floor grid (see its comments).
vec2 drawLine(float id, float along, float t0, float spread, float dur, float maxLen) {
float jit = fract(sin(id * 127.1) * 43758.5453);
float grow = clamp((uReveal - t0 - jit * spread) / dur, 0.0, 1.0);
float len = grow * maxLen;
float a = abs(along);
float mask = 1.0 - smoothstep(len - 0.05, len, a);
float head = (1.0 - smoothstep(0.0, 0.35, len - a)) * mask
* step(0.001, grow) * (1.0 - step(0.999, grow));
return vec2(mask, head);
}
void main() {
// Wall surface coords: the in-plane horizontal world axis + height.
float h = mix(vWorld.z, vWorld.x, uAlongX);
vec2 p = vec2(h, vWorld.y);
float cell = gridLine(p, uCell);
// Horizontal axis shifted half a section to match the floor's odd
// lattice (vertical section lines meet the floor's at the base);
// the height axis keeps its base line at y = 0.
vec2 pSec = vec2(p.x + 0.5 * uSection, p.y);
float section = gridLine(pSec, uSection);
float d = distance(vWorld.xz, uFocus.xz);
float fade = pow(clamp(1.0 - d / uFadeDist, 0.0, 1.0), 1.6);
float vert = 1.0 - clamp(vWorld.y / uWallH, 0.0, 1.0);
vec3 col = mix(uCellColor, uSectionColor, clamp(section, 0.0, 1.0));
float alpha = min(max(section * 0.9, cell * 0.6) * fade * (0.3 + 0.7 * vert), 1.0);
// Entrance: section lines only - horizontals zip out from the
// wall's center, verticals rise from the ground, each with a
// hashed delay; the fine cells fade in over the reveal's second
// half. Same steady-state equivalence argument as the floor grid.
if (uReveal < 1.0) {
vec2 rs = pSec / uSection;
vec2 gs = abs(fract(rs - 0.5) - 0.5) / fwidth(rs);
// Const-height lines run along h (grow from center outward);
// const-h lines run along y (grow up from the ground).
vec2 sh = drawLine(floor(rs.y + 0.5), p.x, 0.00, 0.30, 0.40, 2.0);
vec2 sv = drawLine(floor(rs.x + 0.5) + 31.0, p.y, 0.30, 0.30, 0.30, uWallH);
float secR = max(lineProf(gs.y) * sh.x, lineProf(gs.x) * sv.x);
float cellR = cell * smoothstep(0.5, 1.0, uReveal);
float headGlow = max(lineProf(gs.y) * sh.y, lineProf(gs.x) * sv.y);
col = mix(uCellColor, uSectionColor, clamp(secR, 0.0, 1.0));
alpha = min(max(secR * 0.9, cellR * 0.6) * fade * (0.3 + 0.7 * vert), 1.0);
headGlow = clamp(headGlow, 0.0, 1.0);
col = mix(col, vec3(1.0, 0.86, 0.55), headGlow * 0.8);
alpha = min(alpha + headGlow * fade * 0.5, 1.0);
}
if (alpha < 0.004) discard;
gl_FragColor = vec4(col, alpha);
}
`,
});
}
// Entrance draw-in cue schedule, for the ceremony's per-line audio blips.
// Replicates the shaders' hashed stagger EXACTLY (same hash, same t0 /
// spread constants, same line ids as drawLine's floor(rs + 0.5)), so each
// blip lands the instant its line starts drawing. Times are normalized to
// the respective reveal (0..1); the ceremony maps them to seconds with its
// own grid/wall reveal durations. `u` is the line's jitter, reused by the
// audio side for per-line pitch variation. The four walls share one id
// space, so their lines draw (and blip) in unison - one cue each.
const jitHash = (x) => {
const s = Math.sin(x * 127.1) * 43758.5453;
return s - Math.floor(s);
};
export function entranceLineCues() {
const grid = [];
const walls = [];
// Floor: 6 section lines per axis (world x in {-1.5..1.5} step 0.6 maps
// to ids -2..3); the z family is offset by 57 in the shader.
for (let i = -2; i <= 3; i++) {
const jx = jitHash(i);
const jz = jitHash(i + 57);
grid.push({ at: 0.0 + jx * 0.3, u: jx });
grid.push({ at: 0.05 + jz * 0.3, u: jz });
}
// Walls: one horizontal section line (the y = 0 base, id 0) and 6
// verticals (ids -2..3 offset by 31), per the 0.25 m wall height.
walls.push({ at: 0.0 + jitHash(0) * 0.3, u: jitHash(0) });
for (let i = -2; i <= 3; i++) {
const j = jitHash(i + 31);
walls.push({ at: 0.3 + j * 0.3, u: j });
}
return { grid, walls };
}
// The four wall planes at their inner faces (three coords: MJCF x -> x,
// MJCF y -> -z). Returns the meshes plus their materials (the ceremony and
// the per-frame focus update both need the material list).
export function makeArenaWalls({
half_extent = ARENA_HALF,
wall_height = ARENA_WALL_H,
wall_thickness = ARENA_WALL_T,
} = {}) {
const wallMats = [];
const wallMeshes = [];
const wallLen = 2 * (half_extent + wall_thickness);
const wallDefs = [
{ x: half_extent, z: 0, rotY: -Math.PI / 2, alongX: false },
{ x: -half_extent, z: 0, rotY: Math.PI / 2, alongX: false },
{ x: 0, z: half_extent, rotY: Math.PI, alongX: true },
{ x: 0, z: -half_extent, rotY: 0, alongX: true },
];
for (const [index, w] of wallDefs.entries()) {
const mat = makeWallGridMaterial(w.alongX, wall_height);
wallMats.push(mat);
const mesh = new THREE.Mesh(
new THREE.PlaneGeometry(wallLen, wall_height),
mat,
);
mesh.name = `arena-boundary-${index}`;
mesh.position.set(w.x, wall_height / 2, w.z);
mesh.rotation.y = w.rotY;
wallMeshes.push(mesh);
}
return { wallMats, wallMeshes };
}
+5 -3
View File
@@ -1,3 +1,4 @@
import "@fontsource/anton/latin-400.css";
import { lazy, Suspense } from "react";
import { createRoot } from "react-dom/client";
import { ThemeProvider } from "@mui/material/styles";
@@ -6,9 +7,10 @@ import { theme } from "./theme.js";
// ?soundboard=1: standalone audio A/B experiment page instead of the game
// (lazy on both sides so the soundboard never pulls the game bundle in).
const App = new URLSearchParams(location.search).get("soundboard") === "1"
? lazy(() => import("./ui/Soundboard.jsx"))
: lazy(() => import("./App.jsx"));
const App =
new URLSearchParams(location.search).get("soundboard") === "1"
? lazy(() => import("./ui/Soundboard.jsx"))
: lazy(() => import("./App.jsx"));
// Build tag: bump to change the bundle's content hash, e.g. to bust a stale
// edge-cached asset URL on the HF Space.
+83
View File
@@ -0,0 +1,83 @@
export function isEditingTarget(target, code) {
if (
target?.closest?.(
'input, textarea, select, [contenteditable]:not([contenteditable="false"])',
)
)
return true;
return (
(code === "Space" || code === "Enter") && !!target?.closest?.("button")
);
}
const moves = {
move_forward: "fwd",
move_backward: "back",
turn_left: "turnl",
turn_right: "turnr",
};
export class InputRouter {
id = "keyboard";
connected = true;
command = new Float32Array(3);
axes = { jaw: 0, orbitX: 0, orbitY: 0 };
pressed = { fwd: false, back: false, turnl: false, turnr: false };
onAction = () => {};
#held = new Set();
#handlers = [];
#limits = [NaN, NaN, NaN];
constructor({ bindings, getVelocityLimits, isEnabled = () => true }) {
Object.assign(this, { bindings, getVelocityLimits, isEnabled });
this.byCode = new Map(
bindings.flatMap((b) => b.codes.map((code) => [code, b.action])),
);
}
init(target = window) {
const listen = (type, cb) => {
target.addEventListener(type, cb);
this.#handlers.push(() => target.removeEventListener(type, cb));
};
listen("keydown", (e) => {
if (e.repeat || isEditingTarget(e.target, e.code)) return;
const action = this.byCode.get(e.code);
if (!action || action === "pause" || !this.isEnabled(action)) return;
e.preventDefault();
if (moves[action]) {
this.#held.add(e.code);
this.#refresh();
} else this.onAction(action);
});
listen("keyup", (e) => {
this.#held.delete(e.code);
this.#refresh();
});
listen("blur", () => this.clear());
}
poll() {
const limits = this.getVelocityLimits();
if (limits.some((v, i) => v !== this.#limits[i])) this.#refresh();
}
#refresh() {
for (const key of Object.keys(this.pressed)) this.pressed[key] = false;
for (const code of this.#held) {
const name = moves[this.byCode.get(code)];
if (name) this.pressed[name] = true;
}
const [fwd, back, ang] = this.getVelocityLimits(),
p = this.pressed;
this.#limits = [fwd, back, ang];
this.command[0] = p.fwd ? fwd : p.back ? back : 0;
this.command[1] = 0;
this.command[2] = p.turnl ? ang : p.turnr ? -ang : 0;
}
isActive() {
return this.#held.size > 0;
}
clear() {
this.#held.clear();
this.#refresh();
}
dispose() {
for (const off of this.#handlers.splice(0)) off();
this.clear();
}
}
+56
View File
@@ -0,0 +1,56 @@
import { validatePackage, validateWorld } from "./SchemaValidator.js";
import { DEFAULT_WORLD } from "../worlds/arena.js";
export function assetUrl(path, base, location = globalThis.location) {
const url = new URL(path, base);
if (location && url.origin !== location.origin)
throw new Error(`External asset origin not allowed: ${url.origin}`);
const sign = location
? new URLSearchParams(location.search).get("__sign")
: null;
if (sign) url.searchParams.set("__sign", sign);
return url.href;
}
export async function fetchChecked(url, kind = "text") {
const response = await fetch(url);
if (!response.ok)
throw new Error(`${url.split("?")[0]}: HTTP ${response.status}`);
return kind === "json"
? response.json()
: kind === "bytes"
? response.arrayBuffer()
: response.text();
}
export async function loadPackage(url) {
const config = validatePackage(
await fetchChecked(assetUrl(url, document.baseURI), "json"),
);
const base = new URL(".", new URL(url, document.baseURI)).href;
return {
config,
base,
url: assetUrl(url, document.baseURI),
asset: (path) => assetUrl(path, base),
};
}
export async function loadIndex() {
const base = new URL(`${import.meta.env.BASE_URL}robots/`, location.origin)
.href;
const entries = await fetchChecked(assetUrl("index.json", base), "json");
if (!Array.isArray(entries) || !entries.length)
throw new Error("robots/index.json: nonempty list required");
return entries.map((entry) => ({
...entry,
url: assetUrl(entry.manifest, base),
}));
}
export async function loadWorld(id = DEFAULT_WORLD) {
const base = new URL(
`${import.meta.env.BASE_URL}worlds/${id}/`,
location.origin,
).href;
const world = await fetchChecked(assetUrl("world.json", base), "json");
validateWorld(world);
if (world.id !== id)
throw new Error(`worlds/${id}: unsupported World schema`);
return world;
}
+116
View File
@@ -0,0 +1,116 @@
import Ajv from "ajv";
import schema from "./robot.schema.json" with { type: "json" };
import worldSchema from "./world.schema.json" with { type: "json" };
const ajv = new Ajv({ allErrors: true, strict: true }),
check = ajv.compile(schema),
checkWorld = ajv.compile(worldSchema);
function assertSchema(check, value, label) {
if (!check(value))
throw new Error(
`${label}: ${check.errors.map((e) => `${e.instancePath || "/"} ${e.message}`).join("; ")}`,
);
}
export function validateWorld(world) {
assertSchema(checkWorld, world, "world.json");
if (world.boundary && world.type !== "flat")
throw new Error("world.json /boundary: requires a flat World");
if (world.type === "flat" && !world.floor)
throw new Error("world.json /floor: required for flat World");
if (world.presentation && world.type !== "flat")
throw new Error("world.json /presentation: requires a flat World");
if (world.type === "adapter" && !world.adapter)
throw new Error("world.json /adapter: required for adapter World");
return world;
}
export function validatePackage(config) {
assertSchema(check, config, "robot.json");
const groups = config.joints.groups;
const owners = new Set(
config.skills
.filter((s) => s.kind === "primary")
.flatMap((s) => groups[s.owns] ?? []),
),
ids = new Set();
let primaries = 0;
for (const skill of config.skills) {
if (ids.has(skill.id)) throw new Error(`skills: duplicate ${skill.id}`);
ids.add(skill.id);
if (!groups[skill.owns])
throw new Error(`skills.${skill.id}.owns: unknown group ${skill.owns}`);
if (skill.controller.type === "onnx" && !skill.controller.policy)
throw new Error(`skills.${skill.id}.controller.policy: required`);
if (skill.kind === "primary") primaries++;
if (skill.kind === "overlay")
for (const joint of groups[skill.owns]) {
if (owners.has(joint))
throw new Error(`skills: overlapping ownership of ${joint}`);
owners.add(joint);
}
}
if (
config.adapter === "generic" &&
(primaries !== 1 ||
config.skills.some((s) => !["primary", "overlay"].includes(s.kind)))
)
throw new Error(
"generic runtime requires one primary and disjoint overlays",
);
for (const obs of Object.values(config.observations))
for (const term of obs.terms) {
if (term.group && !groups[term.group])
throw new Error(`observations: unknown group ${term.group}`);
if (
["joint_pos_rel", "joint_vel", "last_action"].includes(term.type) &&
!term.group
)
throw new Error(`${term.type}: group required`);
if (term.type === "gyro" && !term.sensor)
throw new Error("gyro: sensor required");
if (term.type === "projected_gravity" && !term.body)
throw new Error("projected_gravity: body required");
if (
term.type === "command" &&
(!term.size || term.size > config.commands.size)
)
throw new Error(
"observations.command: size missing or exceeds command buffer",
);
}
for (const action of config.actions)
if (!groups[action.group])
throw new Error(`actions: unknown group ${action.group}`);
if (
config.actuation.type === "joint_pd" &&
!["kp", "kd", "torque_limit"].every((k) =>
Number.isFinite(config.actuation[k]),
)
)
throw new Error("actuation: PD gains and torque_limit required");
const codes = new Set();
for (const binding of config.input.bindings) {
if (
config.adapter === "generic" &&
![
"move_forward",
"move_backward",
"turn_left",
"turn_right",
"reset",
"pause",
"chaseToggle",
...config.skills
.filter((s) => s.kind === "overlay")
.map((s) => `toggle:${s.id}`),
].includes(binding.action)
)
throw new Error(`input: unsupported action ${binding.action}`);
for (const code of binding.codes) {
if (codes.has(code)) throw new Error(`input: duplicate ${code}`);
codes.add(code);
}
}
if (config.adapter === "generic" && config.render.source !== "mjcf_visual")
throw new Error("render.source: generic runtime requires mjcf_visual");
return config;
}
export { schema as robotSchema };
+77
View File
@@ -0,0 +1,77 @@
// ONNX ModelProto.metadata_props (field 14). Parse only protobuf wire
// framing; no graph deserialization or dependency on Python at runtime.
export function readOnnxMetadata(buffer) {
const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
const decoder = new TextDecoder();
if (
decoder.decode(bytes.subarray(0, 40)).startsWith("version https://git-lfs")
)
throw new Error("ONNX is a Git LFS pointer: run git lfs pull");
const fields = (start, end) => {
let cursor = start;
const varint = () => {
let value = 0,
shift = 0;
while (cursor < end && shift <= 49) {
const byte = bytes[cursor++];
value += (byte & 127) * 2 ** shift;
if (!(byte & 128)) return value;
shift += 7;
}
throw new Error("Invalid ONNX protobuf varint");
};
const result = [];
while (cursor < end) {
const tag = varint(),
id = Math.floor(tag / 8),
wire = tag & 7;
if (wire === 0) {
varint();
continue;
}
if (wire === 1 || wire === 5) {
cursor += wire === 1 ? 8 : 4;
} else if (wire === 2) {
const size = varint(),
begin = cursor;
cursor += size;
if (cursor > end) throw new Error("Truncated ONNX protobuf");
result.push({ id, begin, end: cursor });
} else throw new Error(`Unsupported ONNX protobuf wire type ${wire}`);
if (cursor > end) throw new Error("Truncated ONNX protobuf");
}
return result;
};
const metadata = Object.create(null);
for (const entry of fields(0, bytes.length).filter((f) => f.id === 14)) {
const pair = fields(entry.begin, entry.end);
const key = pair.find((f) => f.id === 1),
val = pair.find((f) => f.id === 2);
if (!key || !val) throw new Error("Invalid ONNX metadata entry");
const name = decoder.decode(bytes.subarray(key.begin, key.end));
if (Object.hasOwn(metadata, name))
throw new Error(`Duplicate ONNX metadata ${name}`);
metadata[name] = decoder.decode(bytes.subarray(val.begin, val.end));
}
return metadata;
}
export function resolveJointDefaults(metadata, group) {
const names = metadata.joint_names?.split(",").map((n) => n.trim());
const values = metadata.default_joint_pos?.split(",").map(Number);
if (
!names ||
!values ||
names.some((n) => !n) ||
metadata.default_joint_pos.split(",").some((v) => !v.trim()) ||
names.length !== values.length ||
new Set(names).size !== names.length ||
!values.every(Number.isFinite)
) {
throw new Error("Invalid ONNX joint_names/default_joint_pos metadata");
}
return group.map((name) => {
const index = names.indexOf(name);
if (index < 0) throw new Error(`ONNX metadata missing joint ${name}`);
return values[index];
});
}
+409
View File
@@ -0,0 +1,409 @@
{
"type": "object",
"additionalProperties": false,
"required": [
"schema",
"id",
"name",
"family",
"adapter",
"model",
"assets",
"base",
"sim",
"joints",
"observations",
"actions",
"actuation",
"commands",
"skills",
"input",
"render",
"presentation",
"termination",
"license"
],
"properties": {
"schema": {
"const": 1
},
"id": {
"type": "string",
"pattern": "^[a-z0-9-]+$"
},
"name": {
"type": "string"
},
"family": {
"type": "string"
},
"adapter": {
"enum": ["generic", "microduck"]
},
"model": {
"type": "string"
},
"assets": {
"type": "array",
"items": {
"type": "object",
"required": ["path", "vfs"],
"additionalProperties": false,
"properties": {
"path": {
"type": "string"
},
"vfs": {
"type": "string",
"pattern": "^(?!/)(?!.*\\.\\.)[^\\\\]+$"
}
}
}
},
"base": {
"type": "object",
"required": ["type", "root_body", "freejoint", "spawn"],
"additionalProperties": false,
"properties": {
"type": {
"const": "floating"
},
"root_body": {
"type": "string"
},
"freejoint": {
"type": "string"
},
"spawn": {
"type": "object",
"required": ["pos", "yaw"],
"additionalProperties": false,
"properties": {
"pos": {
"type": "array",
"items": {
"type": "number"
},
"minItems": 3,
"maxItems": 3
},
"yaw": {
"type": "number"
}
}
},
"initial": {
"type": "object",
"additionalProperties": {
"type": "number"
}
}
}
},
"sim": {
"type": "object",
"required": ["timestep", "decimation"],
"additionalProperties": false,
"properties": {
"timestep": {
"type": "number",
"exclusiveMinimum": 0
},
"decimation": {
"type": "integer",
"minimum": 1
}
}
},
"joints": {
"type": "object",
"required": ["groups", "defaults"],
"additionalProperties": false,
"properties": {
"source": {
"const": "onnx_metadata"
},
"groups": {
"type": "object",
"required": ["policy"],
"properties": {
"policy": {
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"uniqueItems": true
}
},
"additionalProperties": {
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"uniqueItems": true
}
},
"defaults": {
"type": "object",
"additionalProperties": {
"type": "number"
}
}
}
},
"observations": {
"type": "object",
"minProperties": 1,
"additionalProperties": {
"type": "object",
"required": ["terms"],
"additionalProperties": false,
"properties": {
"terms": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"required": ["type"],
"additionalProperties": false,
"properties": {
"type": {
"enum": [
"gyro",
"projected_gravity",
"joint_pos_rel",
"joint_vel",
"last_action",
"command"
]
},
"sensor": {
"type": "string"
},
"body": {
"type": "string"
},
"group": {
"type": "string"
},
"size": {
"type": "integer",
"minimum": 1
}
}
}
}
}
}
},
"actions": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"required": ["type", "group", "scale", "offset"],
"additionalProperties": false,
"properties": {
"type": {
"const": "joint_position"
},
"group": {
"type": "string"
},
"scale": {
"type": "number"
},
"offset": {
"const": "default"
}
}
}
},
"actuation": {
"type": "object",
"required": ["type"],
"additionalProperties": false,
"properties": {
"type": {
"enum": ["native_position", "joint_pd"]
},
"kp": {
"type": "number",
"minimum": 0
},
"kd": {
"type": "number",
"minimum": 0
},
"torque_limit": {
"type": "number",
"exclusiveMinimum": 0
}
}
},
"commands": {
"type": "object",
"required": ["size", "limits"],
"additionalProperties": false,
"properties": {
"size": {
"type": "integer",
"minimum": 3
},
"limits": {
"type": "array",
"items": {
"type": "number"
},
"minItems": 3,
"maxItems": 3
}
}
},
"skills": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"required": ["id", "kind", "owns", "controller"],
"additionalProperties": false,
"properties": {
"id": {
"type": "string"
},
"kind": {
"enum": ["primary", "overlay", "episodic", "recovery"]
},
"owns": {
"type": "string"
},
"controller": {
"type": "object",
"required": ["type"],
"additionalProperties": false,
"properties": {
"type": {
"enum": ["onnx", "oscillator"]
},
"policy": {
"type": "string"
},
"frequency": {
"type": "number",
"exclusiveMinimum": 0
},
"amplitude": {
"type": "number",
"minimum": 0
},
"blend": {
"type": "number",
"exclusiveMinimum": 0
}
}
}
}
}
},
"input": {
"type": "object",
"required": ["bindings"],
"additionalProperties": false,
"properties": {
"bindings": {
"type": "array",
"items": {
"type": "object",
"required": ["action", "codes", "label"],
"additionalProperties": false,
"properties": {
"action": {
"type": "string"
},
"codes": {
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"uniqueItems": true
},
"label": {
"type": "string"
}
}
}
}
}
},
"render": {
"type": "object",
"required": ["source", "camera"],
"additionalProperties": false,
"properties": {
"source": {
"enum": ["glb", "mjcf_visual"]
},
"groups": {
"type": "array",
"items": {
"type": "integer",
"minimum": 0
}
},
"camera": {
"type": "object",
"required": ["distance"],
"additionalProperties": false,
"properties": {
"distance": {
"type": "number",
"exclusiveMinimum": 0
}
}
}
}
},
"presentation": {
"type": "object",
"required": ["theme"],
"additionalProperties": false,
"properties": {
"world": {
"type": "string",
"pattern": "^[a-z0-9-]+$"
},
"theme": {
"enum": ["comic", "neutral"]
}
}
},
"termination": {
"type": "object",
"required": ["tilt_z", "min_height", "on_fall"],
"additionalProperties": false,
"properties": {
"tilt_z": {
"type": "number",
"minimum": -1,
"maximum": 1
},
"min_height": {
"type": "number"
},
"on_fall": {
"enum": ["recovery", "hold"]
}
}
},
"legacy": {
"type": "object"
},
"license": {
"type": "string",
"minLength": 1
}
}
}
+51
View File
@@ -0,0 +1,51 @@
{
"type": "object",
"additionalProperties": false,
"required": ["schema", "id", "type"],
"properties": {
"schema": { "const": 1 },
"id": { "type": "string", "pattern": "^[a-z0-9-]+$" },
"type": { "enum": ["flat", "adapter"] },
"adapter": { "type": "string", "minLength": 1 },
"presentation": { "enum": ["arena-grid"] },
"boundary": {
"type": "object",
"additionalProperties": false,
"required": ["half_extent", "wall_height", "wall_thickness"],
"properties": {
"half_extent": {"type":"number","exclusiveMinimum":0},
"wall_height": {"type":"number","exclusiveMinimum":0},
"wall_thickness": {"type":"number","exclusiveMinimum":0}
}
},
"floor": {
"type": "object",
"additionalProperties": false,
"required": ["rgba", "friction"],
"properties": {
"grid": {
"type": "object",
"required": ["size", "divisions", "color"],
"additionalProperties": false,
"properties": {
"size": { "type": "number", "exclusiveMinimum": 0 },
"divisions": { "type": "integer", "minimum": 1, "maximum": 1000 },
"color": { "type": "string", "pattern": "^#[0-9a-fA-F]{6}$" }
}
},
"rgba": {
"type": "array",
"minItems": 4,
"maxItems": 4,
"items": { "type": "number", "minimum": 0, "maximum": 1 }
},
"friction": {
"type": "array",
"minItems": 3,
"maxItems": 3,
"items": { "type": "number", "minimum": 0 }
}
}
}
}
}
+37
View File
@@ -0,0 +1,37 @@
import { actionTerms } from "./TermRegistry.js";
export class ActionPipeline {
constructor(specs, ctx, { registry = actionTerms } = {}) {
this.ctx = ctx;
this.ops = [];
for (const spec of specs)
this.ops.push(
...registry.get(spec.type ?? "joint_position").compile(spec, ctx),
);
this.size = this.ops.length;
this.pending = new Float64Array(this.size);
if (new Set(this.ops.map((op) => op.name)).size !== this.size)
throw new Error("actions: duplicate joint ownership");
if (
this.ops.some(
(op) => !Number.isFinite(op.scale) || !Number.isFinite(op.offset),
)
)
throw new Error("actions: invalid scale/default");
}
apply(action, scaleOverride) {
if (action.length !== this.size)
throw new Error(`actions: expected ${this.size}, got ${action.length}`);
if (!action.every(Number.isFinite))
throw new Error("actions: non-finite tensor");
for (let i = 0; i < this.ops.length; i++) {
const op = this.ops[i],
value = op.offset + action[i] * (scaleOverride ?? op.scale);
if (!Number.isFinite(value))
throw new Error(`actions.${op.name}: non-finite target`);
this.pending[i] = value;
}
for (let i = 0; i < this.ops.length; i++)
this.ctx.targets.set(this.ops[i].name, this.pending[i]);
this.ctx.lastAction.set(action);
}
}
@@ -0,0 +1,78 @@
import { observationTerms } from "./TermRegistry.js";
// Compiled term writers keep the policy joint order independent of model order.
export class ObservationPipeline {
constructor(specs, ctx, { buffers = {}, registry = observationTerms } = {}) {
this.ctx = ctx;
this.inputs = {};
this.ops = [];
this.details = {};
for (const [name, spec] of Object.entries(specs)) {
let offset = 0;
const terms = [];
for (const term of spec.terms) {
const names = term.group ? ctx.config.joints.groups[term.group] : null;
const implementation = registry.get(term.type),
size = implementation.size(term, ctx, names);
let sensor, body;
if (term.type === "gyro") {
const id = ctx.sim.mujoco.mj_name2id(
ctx.sim.model,
ctx.sim.mujoco.mjtObj.mjOBJ_SENSOR.value,
term.sensor,
);
if (id < 0)
throw new Error(
`observations.${name}: missing sensor ${term.sensor}`,
);
sensor = {
adr: ctx.sim.model.sensor_adr[id],
dim: ctx.sim.model.sensor_dim[id],
};
if (sensor.dim !== 3)
throw new Error(
`observations.${name}: gyro ${term.sensor} must have dimension 3`,
);
}
if (term.type === "projected_gravity") {
body = ctx.sim.mujoco.mj_name2id(
ctx.sim.model,
ctx.sim.mujoco.mjtObj.mjOBJ_BODY.value,
term.body,
);
if (body < 0)
throw new Error(`observations.${name}: missing body ${term.body}`);
}
const indices =
term.type === "last_action"
? names.map((n) => ctx.policyNames.indexOf(n))
: null;
if (indices?.some((i) => i < 0))
throw new Error(
`observations.${name}: last_action group is not actor-controlled`,
);
terms.push({ ...term, size, offset });
this.ops.push({
name,
term,
names,
sensorAdr: sensor?.adr,
body,
indices,
offset,
implementation,
...implementation.init?.(term, ctx),
});
offset += size;
}
if (buffers[name] && buffers[name].length !== offset)
throw new Error(`Observation buffer ${name}: incorrect size`);
this.inputs[name] = buffers[name] ?? new Float32Array(offset);
this.details[name] = terms;
}
}
write() {
for (const op of this.ops)
op.implementation.write(this.inputs[op.name], op.offset, this.ctx, op);
return this.inputs;
}
}
+74
View File
@@ -0,0 +1,74 @@
export class TermRegistry {
constructor(entries = []) {
this.terms = new Map(entries);
}
register(type, implementation) {
if (this.terms.has(type)) throw new Error(`Duplicate term ${type}`);
this.terms.set(type, implementation);
return this;
}
get(type) {
const term = this.terms.get(type);
if (!term) throw new Error(`Unsupported term ${type}`);
return term;
}
clone() {
return new TermRegistry(this.terms);
}
}
export const actionTerms = new TermRegistry();
actionTerms.register("joint_position", {
compile: (spec, ctx) =>
ctx.config.joints.groups[spec.group].map((name) => ({
name,
scale: spec.scale,
offset: ctx.defaults.get(name),
})),
});
export const observationTerms = new TermRegistry();
observationTerms.register("gyro", {
size: () => 3,
write: (out, offset, c, op) => {
for (let i = 0; i < 3; i++)
out[offset + i] = c.sim.data.sensordata[op.sensorAdr + i];
},
});
observationTerms.register("projected_gravity", {
size: () => 3,
write: (out, offset, c, op) => {
if (c.gravityWriter) {
c.gravityWriter(out, offset, op.body);
return;
}
const q = c.sim.data.xquat,
a = op.body * 4,
w = q[a],
x = q[a + 1],
y = q[a + 2],
z = q[a + 3];
out[offset] = 2 * (w * y - x * z);
out[offset + 1] = -2 * (y * z + w * x);
out[offset + 2] = -(1 - 2 * (x * x + y * y));
},
});
observationTerms.register("command", {
size: (term) => term.size,
write: (out, offset, c, op) => {
for (let i = 0; i < op.term.size; i++) out[offset + i] = c.command[i];
},
});
for (const type of ["joint_pos_rel", "joint_vel", "last_action"])
observationTerms.register(type, {
size: (_term, _ctx, names) => names.length,
write: (out, offset, c, op) => {
for (let i = 0; i < op.names.length; i++) {
const joint = c.sim.joints.get(op.names[i]);
out[offset + i] =
type === "joint_pos_rel"
? c.sim.data.qpos[joint.qpos] - c.defaults.get(op.names[i])
: type === "joint_vel"
? c.sim.data.qvel[joint.dof]
: c.lastAction[op.indices[i]];
}
},
});
@@ -0,0 +1,50 @@
export class OnnxController {
constructor(ort, session, observations, actionSize) {
this.session = session;
this.feeds = {};
const groups = Object.keys(observations.inputs);
if (session.inputNames.length !== groups.length)
throw new Error(
`ONNX inputs: expected ${groups.length}, got ${session.inputNames.length}`,
);
for (const name of session.inputNames) {
const group = Object.hasOwn(observations.inputs, name)
? name
: groups.length === 1
? groups[0]
: null;
if (!group)
throw new Error(`ONNX input ${name}: missing observation group`);
const input = observations.inputs[group],
meta = session.inputMetadata.find((m) => m.name === name);
if (
!meta?.isTensor ||
meta.type !== "float32" ||
meta.shape.length !== 2 ||
typeof meta.shape[1] !== "number" ||
meta.shape[1] !== input.length
)
throw new Error(
`ONNX input ${name}: ${JSON.stringify(meta?.shape)} vs terms ${JSON.stringify(observations.details[group])}`,
);
this.feeds[name] = new ort.Tensor("float32", input, [1, input.length]);
}
this.output = session.outputNames[0];
const meta = session.outputMetadata[0];
if (
!meta?.isTensor ||
meta.type !== "float32" ||
meta.shape.length !== 2 ||
meta.shape[1] !== actionSize
)
throw new Error(
`ONNX output ${this.output}: expected [1,${actionSize}], got ${JSON.stringify(meta?.shape)}`,
);
}
async run() {
return (await this.session.run(this.feeds))[this.output].data;
}
dispose() {
return this.session.release();
}
}
+75
View File
@@ -0,0 +1,75 @@
import * as THREE from "three";
const wrapPi = (angle) => Math.atan2(Math.sin(angle), Math.cos(angle));
// Same rear framing and yaw hysteresis as Microduck. Only presentation state:
// mouse orbit detaches; restoring never toggles follow off or touches physics.
export class ChaseCamera {
constructor(camera, controls, { distance, pitch = 0.42 }) {
Object.assign(this, { camera, controls, distance, pitch });
this.enabled = true;
this.previous = new THREE.Vector3();
this.delta = new THREE.Vector3();
this.goal = new THREE.Vector3();
this.direction = new THREE.Vector3();
this.detach = () => {
this.enabled = false;
};
controls.domElement.addEventListener("pointerdown", this.detach);
}
restore(position, yaw) {
const damping = this.controls.enableDamping;
this.controls.enableDamping = false;
this.controls.update(); // consume any residual orbit inertia before restoring
this.controls.enableDamping = damping;
this.previous.copy(position);
this.controls.target.copy(position);
this.smoothYaw = this.followYaw = yaw;
this.tracking = false;
this.enabled = true;
this.#behind(yaw, this.distance);
this.camera.position.copy(this.goal);
this.controls.update();
this.camera.lookAt(this.controls.target);
}
#behind(yaw, distance) {
const horizontal = distance * Math.cos(this.pitch);
this.goal
.copy(this.controls.target)
.add(
this.direction.set(
-Math.cos(yaw) * horizontal,
distance * Math.sin(this.pitch),
Math.sin(yaw) * horizontal,
),
);
}
update(position, yaw, { turning = false } = {}) {
this.delta.copy(position).sub(this.previous);
this.camera.position.add(this.delta);
this.controls.target.add(this.delta);
this.previous.copy(position);
this.controls.update();
if (!this.enabled) return;
this.smoothYaw = wrapPi(
this.smoothYaw + wrapPi(yaw - this.smoothYaw) * (turning ? 0.5 : 0.04),
);
const error = wrapPi(this.smoothYaw - this.followYaw);
if (turning || Math.abs(error) > 0.17) this.tracking = true;
if (this.tracking) {
this.followYaw = wrapPi(this.followYaw + error * (turning ? 0.5 : 0.1));
if (!turning && Math.abs(error) < 0.03) this.tracking = false;
}
const distance = this.camera.position.distanceTo(this.controls.target);
this.#behind(this.followYaw, distance);
this.camera.position.lerp(this.goal, 0.05);
this.direction.copy(this.camera.position).sub(this.controls.target);
const length = this.direction.length();
if (length > 1e-6)
this.camera.position
.copy(this.controls.target)
.addScaledVector(this.direction, distance / length);
this.camera.lookAt(this.controls.target);
}
dispose() {
this.controls.domElement.removeEventListener("pointerdown", this.detach);
}
}
+129
View File
@@ -0,0 +1,129 @@
import * as THREE from "three";
import { applyWorldGrid } from "./WorldRenderer.js";
// Geometry is compiled MuJoCo geometry, not raw STL: compiler-applied mesh
// scale/centering is already represented by vertices + geom transforms.
export class RigRenderer {
constructor(model, data, { groups = [2], world } = {}) {
this.model = model;
this.data = data;
this.root = new THREE.Group();
this.root.rotation.x = -Math.PI / 2;
this.geometries = new Map();
this.materials = [];
this.items = [];
this.matrix = new THREE.Matrix4();
try {
for (let id = 0; id < model.ngeom; id++) {
if (!groups.includes(model.geom_group[id]) && model.geom_type[id] !== 0)
continue;
const type = model.geom_type[id],
size = Array.from(model.geom_size.slice(id * 3, id * 3 + 3));
let geometry,
key = type === 7 ? `mesh:${model.geom_dataid[id]}` : `geom:${id}`;
geometry = this.geometries.get(key);
if (!geometry) {
if (type === 7) {
const mesh = model.geom_dataid[id],
v0 = model.mesh_vertadr[mesh] * 3,
vn = model.mesh_vertnum[mesh] * 3;
const f0 = model.mesh_faceadr[mesh] * 3,
fn = model.mesh_facenum[mesh] * 3;
geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(
new Float32Array(model.mesh_vert.slice(v0, v0 + vn)),
3,
),
);
geometry.setIndex(
new THREE.BufferAttribute(
new Uint32Array(model.mesh_face.slice(f0, f0 + fn)),
1,
),
);
geometry.computeVertexNormals();
} else if (type === 0) geometry = new THREE.PlaneGeometry(200, 200);
else if (type === 2)
geometry = new THREE.SphereGeometry(size[0], 20, 12);
else if (type === 6)
geometry = new THREE.BoxGeometry(...size.map((v) => v * 2));
else if (type === 4) {
geometry = new THREE.SphereGeometry(1, 20, 12);
geometry.scale(...size);
} else if (type === 5) {
geometry = new THREE.CylinderGeometry(
size[0],
size[0],
size[1] * 2,
20,
);
geometry.rotateX(Math.PI / 2);
} else if (type === 3) {
geometry = new THREE.CapsuleGeometry(size[0], size[1] * 2, 6, 12);
geometry.rotateX(Math.PI / 2);
} else throw new Error(`RigRenderer: unsupported geom type ${type}`);
this.geometries.set(key, geometry);
}
const mat = model.geom_matid[id],
rgba =
mat >= 0
? model.mat_rgba.slice(mat * 4, mat * 4 + 4)
: model.geom_rgba.slice(id * 4, id * 4 + 4);
const material = new THREE.MeshStandardMaterial({
color: new THREE.Color(rgba[0], rgba[1], rgba[2]),
opacity: rgba[3],
transparent: rgba[3] < 1,
roughness: 0.65,
metalness: 0.05,
side: type === 0 ? THREE.DoubleSide : THREE.FrontSide,
});
if (type === 0) applyWorldGrid(material, world?.floor?.grid);
this.materials.push(material);
const mesh = new THREE.Mesh(geometry, material);
mesh.userData.geomId = id;
this.root.add(mesh);
this.items.push({ id, mesh });
}
this.sync();
} catch (error) {
this.dispose();
throw error;
}
}
sync() {
const p = this.data.geom_xpos,
r = this.data.geom_xmat,
m = this.matrix;
for (const { id, mesh } of this.items) {
mesh.position.set(p[id * 3], p[id * 3 + 1], p[id * 3 + 2]);
const a = id * 9;
m.set(
r[a],
r[a + 1],
r[a + 2],
0,
r[a + 3],
r[a + 4],
r[a + 5],
0,
r[a + 6],
r[a + 7],
r[a + 8],
0,
0,
0,
0,
1,
);
mesh.quaternion.setFromRotationMatrix(m);
}
}
dispose() {
for (const g of this.geometries.values()) g.dispose();
for (const m of this.materials) m.dispose();
this.geometries.clear();
this.materials = [];
this.root.removeFromParent();
}
}
+32
View File
@@ -0,0 +1,32 @@
import * as THREE from "three";
// Shade the compiled World floor itself instead of overlaying long GL lines.
// This preserves robot occlusion and avoids line-clipping/depth artifacts at
// the tiny scale of these robots. It has no effect on the physical floor.
export function applyWorldGrid(material, spec) {
if (!spec) return;
material.onBeforeCompile = (shader) => {
shader.uniforms.uPlatformGridSpacing = {
value: spec.size / spec.divisions,
};
shader.uniforms.uPlatformGridColor = { value: new THREE.Color(spec.color) };
shader.vertexShader =
"varying vec2 vPlatformGrid;\n" +
shader.vertexShader.replace(
"#include <project_vertex>",
"#include <project_vertex>\nvPlatformGrid = (modelMatrix * vec4(transformed, 1.0)).xz;",
);
shader.fragmentShader =
"varying vec2 vPlatformGrid;\nuniform float uPlatformGridSpacing;\nuniform vec3 uPlatformGridColor;\n" +
shader.fragmentShader.replace(
"#include <color_fragment>",
`#include <color_fragment>
vec2 platformCell = vPlatformGrid / uPlatformGridSpacing;
vec2 platformWidth = max(fwidth(platformCell), vec2(0.00001));
vec2 platformDistance = abs(fract(platformCell - 0.5) - 0.5) / platformWidth;
float platformLine = 1.0 - min(min(platformDistance.x, platformDistance.y), 1.0);
diffuseColor.rgb = mix(diffuseColor.rgb, uPlatformGridColor, platformLine * 0.7);
`,
);
};
material.customProgramCacheKey = () => "platform-world-grid-v1";
}
+23
View File
@@ -0,0 +1,23 @@
// Dispose per-instance World geometry/materials, but leave shared Robot GLB
// caches alone. Robot adapters own their own rig-specific resources.
export function disposeWorld(root) {
const geometries = new Set(),
materials = new Set(),
textures = new Set();
root.traverse((object) => {
for (let p = object; p; p = p.parent) if (p.userData.robotRig) return;
if (object.geometry) geometries.add(object.geometry);
if (object.userData.fxWireGeometry)
geometries.add(object.userData.fxWireGeometry);
for (const material of [object.material].flat().filter(Boolean))
materials.add(material);
});
for (const material of materials) {
for (const value of Object.values(material))
if (value?.isTexture) textures.add(value);
material.dispose();
}
for (const geometry of geometries) geometry.dispose();
for (const texture of textures) texture.dispose();
root.clear();
}
@@ -0,0 +1,71 @@
// One owner for async control ticks. Pausing drains the current tick; it
// never abandons an inference halfway through a physics control interval.
export class ControlScheduler {
#tick;
#dt;
#onError;
#timer = null;
#tail = Promise.resolve();
#running = false;
#disposed = false;
#generation = 0;
constructor(tick, { dt = 0.02, onError = console.error } = {}) {
if (!(dt > 0 && Number.isFinite(dt))) throw new Error("Invalid control dt");
this.#tick = tick;
this.#dt = dt * 1000;
this.#onError = onError;
}
get running() {
return this.#running;
}
start() {
if (this.#disposed) throw new Error("Scheduler disposed");
if (this.#running) return;
this.#running = true;
const generation = ++this.#generation;
const run = async () => {
if (!this.#running || generation !== this.#generation) return;
const begin = performance.now();
try {
await this.#enqueue(1);
} catch (error) {
this.#running = false;
this.#onError(error);
return;
}
if (this.#running && generation === this.#generation) {
this.#timer = setTimeout(
run,
Math.max(0, this.#dt - (performance.now() - begin)),
);
}
};
// Queueing also prevents start() from racing a previously queued step.
this.#timer = setTimeout(run, 0);
}
async pause() {
this.#running = false;
this.#generation++;
clearTimeout(this.#timer);
this.#timer = null;
await this.#tail;
}
async step(count = 1) {
if (this.#disposed) throw new Error("Scheduler disposed");
if (this.#running) throw new Error("Must pause before manual stepping");
if (!Number.isInteger(count) || count < 0)
throw new Error("Invalid step count");
await this.#enqueue(count);
}
#enqueue(count) {
const next = this.#tail.then(async () => {
for (let i = 0; i < count; i++) await this.#tick();
});
this.#tail = next.catch(() => {});
return next;
}
async dispose() {
this.#disposed = true;
await this.pause();
}
}
+37
View File
@@ -0,0 +1,37 @@
// LIFO ownership scope. Async resources acquired after disposal are released
// immediately too, so failed/cancelled boot cannot strand late sessions.
export class Disposables {
#callbacks = [];
#disposed = false;
#pending;
get disposed() {
return this.#disposed;
}
add(callback) {
if (this.#disposed) return Promise.resolve().then(callback);
this.#callbacks.push(callback);
return callback;
}
listen(target, event, callback, options) {
target.addEventListener(event, callback, options);
this.add(() => target.removeEventListener(event, callback, options));
return callback;
}
dispose() {
if (this.#pending) return this.#pending;
this.#disposed = true;
this.#pending = (async () => {
const errors = [];
for (const release of this.#callbacks.splice(0).reverse()) {
try {
await release();
} catch (error) {
errors.push(error);
}
}
if (errors.length)
throw new AggregateError(errors, "Resource cleanup failed");
})();
return this.#pending;
}
}
+383
View File
@@ -0,0 +1,383 @@
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { loadRuntimes } from "./runtimes.js";
import { ControlScheduler } from "./ControlScheduler.js";
import { fetchChecked } from "../loader/PackageLoader.js";
import { readOnnxMetadata, resolveJointDefaults } from "../loader/metadata.js";
import { SimCore } from "../sim/SimCore.js";
import {
JointPdActuation,
NativeActuation,
} from "../sim/actuation/JointPdActuation.js";
import { ObservationPipeline } from "../policy/ObservationPipeline.js";
import { ActionPipeline } from "../policy/ActionPipeline.js";
import { OnnxController } from "../policy/controllers/OnnxController.js";
import { SkillManager } from "../skills/SkillManager.js";
import { InputRouter } from "../input/InputRouter.js";
import { RigRenderer } from "../render/RigRenderer.js";
import { ChaseCamera } from "../render/ChaseCamera.js";
export class RobotRuntime {
static async load(options) {
const { pkg, world } = options,
config = pkg.config,
{ mujoco, ort } = await loadRuntimes();
let sim, session, rig, worldPresentation;
try {
sim = await SimCore.load(mujoco, pkg, world);
const primary = config.skills.find((s) => s.kind === "primary");
if (primary.controller.type !== "onnx")
throw new Error("Primary controller must be ONNX");
const bytes = await fetchChecked(
pkg.asset(primary.controller.policy),
"bytes",
);
const metadata = readOnnxMetadata(bytes),
names = [...sim.joints.keys()];
const values =
config.joints.source === "onnx_metadata"
? resolveJointDefaults(metadata, names)
: names.map((n) => config.joints.defaults[n]);
const defaults = new Map(names.map((n, i) => [n, values[i]]));
for (const [name, value] of Object.entries(config.joints.defaults)) {
if (defaults.has(name) && Math.abs(defaults.get(name) - value) > 1e-6)
throw new Error(`joints.defaults.${name}: metadata conflict`);
defaults.set(name, value);
}
if ([...defaults.values()].some((v) => !Number.isFinite(v)))
throw new Error("joints.defaults: missing/invalid reference pose");
sim.reset(defaults);
session = await ort.InferenceSession.create(bytes, {
executionProviders: ["wasm"],
});
const ctx = {
sim,
config,
defaults,
policyNames: config.joints.groups[primary.owns],
lastAction: new Float32Array(config.joints.groups[primary.owns].length),
command: new Float32Array(config.commands.size),
targets: new Map(
names.map((n) => [n, sim.data.qpos[sim.joints.get(n).qpos]]),
),
};
const obs = new ObservationPipeline(config.observations, ctx),
actions = new ActionPipeline(config.actions, ctx);
const controller = new OnnxController(ort, session, obs, actions.size);
obs.write();
const smoke = await controller.run();
if (smoke.length !== actions.size || !smoke.every(Number.isFinite))
throw new Error("ONNX: standing-pose smoke test failed");
rig = new RigRenderer(sim.model, sim.data, { ...config.render, world });
worldPresentation = await options.createWorldPresentation?.({
sim,
rig,
world,
});
return new RobotRuntime({
...options,
config,
sim,
ctx,
obs,
actions,
controller,
rig,
worldPresentation,
});
} catch (error) {
worldPresentation?.dispose();
rig?.dispose();
await session?.release();
sim?.dispose();
throw error;
}
}
constructor(options) {
Object.assign(this, options);
this.onStatus ??= () => {};
this.onTelemetry ??= () => {};
this.fallen = false;
this.odo = 0;
this.lastPosition = new Float64Array(
this.sim.data.qpos.slice(this.sim.rootQpos, this.sim.rootQpos + 2),
);
this.disposed = false;
this.active = false;
this.positions = new Map();
this.skills = new SkillManager(this.config);
this.actuation =
this.config.actuation.type === "joint_pd"
? new JointPdActuation(
this.sim,
this.ctx.targets,
this.config.actuation,
)
: new NativeActuation(this.sim, this.ctx.targets);
this.input = new InputRouter({
bindings: this.config.input.bindings,
getVelocityLimits: () => this.config.commands.limits,
isEnabled: (action) =>
this.active &&
(action === "reset" ||
action === "chaseToggle" ||
(this.scheduler.running && !this.fallen)),
});
this.input.onAction = (action) => {
if (action === "reset")
this.reset().catch((error) =>
this.onStatus({ runtimeError: error.message }),
);
else if (action === "chaseToggle") this.restoreCamera();
else if (action.startsWith("toggle:")) this.toggle(action.slice(7));
};
this.tickCount = 0;
this.hzAt = performance.now();
this.ctrlHz = 0;
this.frames = 0;
this.fpsAt = this.hzAt;
this.telemetryAt = 0;
this.scheduler = new ControlScheduler(() => this.controlStep(), {
dt: this.config.sim.timestep * this.config.sim.decimation,
onError: (error) => {
this.input.clear();
this.onStatus({
runtimeError: error.message,
paused: true,
runtimePhase: "error",
});
},
});
this.scene.add(this.rig.root);
if (this.worldPresentation) this.scene.add(this.worldPresentation.root);
this.follow = new THREE.Vector3();
}
activate({ paused = false } = {}) {
if (this.disposed) throw new Error("Runtime disposed");
this.active = true;
this.controls = new OrbitControls(this.camera, this.renderer.domElement);
this.controls.enableDamping = true;
this.controls.minDistance = 0.2;
this.controls.maxDistance = 4;
this.controls.maxPolarAngle = Math.PI / 2 - 0.02;
this.chaseCamera = new ChaseCamera(
this.camera,
this.controls,
this.config.render.camera,
);
this.restoreCamera();
this.input.init();
if (!paused) this.resume();
else this.onStatus({ paused: true });
}
cameraPose() {
const q = this.sim.data.qpos,
a = this.sim.rootQpos,
quat = this.sim.data.xquat,
b = this.sim.root * 4;
this.follow.set(q[a], q[a + 2], -q[a + 1]);
return Math.atan2(
2 * (quat[b] * quat[b + 3] + quat[b + 1] * quat[b + 2]),
1 - 2 * (quat[b + 2] ** 2 + quat[b + 3] ** 2),
);
}
restoreCamera() {
const yaw = this.cameraPose();
this.chaseCamera.restore(this.follow, yaw);
}
status() {
return {
actuationLabel:
this.config.actuation.type === "joint_pd"
? "Simplified actuation · joint PD"
: "",
};
}
async deactivate() {
this.active = false;
await this.pause();
}
reactivate({ paused = false } = {}) {
this.active = true;
if (!paused) this.resume();
}
async pause() {
this.input.clear();
await this.scheduler.pause();
this.onStatus({ paused: true });
}
resume() {
if (this.disposed) return;
this.active = true;
this.input.clear();
this.scheduler.start();
this.onStatus({ paused: false });
}
reset() {
return (this.resetPending ??= this.#reset().finally(() => {
this.resetPending = null;
}));
}
async #reset() {
const running = this.scheduler.running;
await this.scheduler.pause();
this.input.clear();
this.ctx.command.fill(0);
this.ctx.lastAction.fill(0);
this.skills.reset();
this.sim.reset(this.ctx.defaults);
this.odo = 0;
this.actuation.resetStats?.();
this.lastPosition.set(
this.sim.data.qpos.subarray(this.sim.rootQpos, this.sim.rootQpos + 2),
);
for (const [name, joint] of this.sim.joints)
this.ctx.targets.set(name, this.sim.data.qpos[joint.qpos]);
this.fallen = false;
this.onStatus({ fallen: false });
this.rig.sync();
if (running) this.scheduler.start();
}
triggerAction(action) {
if (this.input.isEnabled(action)) this.input.onAction(action);
}
toggle(id) {
for (const [name, j] of this.sim.joints)
this.positions.set(name, this.sim.data.qpos[j.qpos]);
this.skills.toggle(id, this.sim.data.time, this.positions);
}
async controlStep() {
if (!this.fallen) {
this.ctx.command.set(this.input.command);
this.obs.write();
this.actions.apply(await this.controller.run());
this.skills.update(this.sim.data.time, this.ctx.targets);
}
for (let i = 0; i < this.config.sim.decimation; i++) {
this.actuation.apply();
this.sim.step();
}
const q = this.sim.data.qpos,
a = this.sim.rootQpos,
quat = this.sim.data.xquat,
b = this.sim.root * 4,
x = quat[b + 1],
y = quat[b + 2];
const gz = -(1 - 2 * (x * x + y * y));
if (
!q.every(Number.isFinite) ||
!this.sim.data.qvel.every(Number.isFinite) ||
!Number.isFinite(gz)
)
throw new Error("Physics produced non-finite state");
if (
!this.fallen &&
(gz > this.config.termination.tilt_z ||
q[a + 2] < this.config.termination.min_height)
) {
this.fallen = true;
this.input.clear();
for (const [name, j] of this.sim.joints)
this.ctx.targets.set(name, q[j.qpos]);
this.onStatus({ fallen: true });
}
this.odo += Math.hypot(
q[a] - this.lastPosition[0],
q[a + 1] - this.lastPosition[1],
);
this.lastPosition[0] = q[a];
this.lastPosition[1] = q[a + 1];
this.tickCount++;
const now = performance.now();
if (now - this.hzAt >= 1000) {
this.ctrlHz = Math.round((this.tickCount * 1000) / (now - this.hzAt));
this.tickCount = 0;
this.hzAt = now;
}
}
frame() {
if (this.disposed) return;
this.rig.sync();
if (this.chaseCamera) {
const yaw = this.cameraPose();
this.worldPresentation?.update(this.follow);
this.chaseCamera.update(this.follow, yaw, {
turning: Math.abs(this.input.command[2]) > 0.05,
});
}
const now = performance.now();
this.frames++;
if (now - this.telemetryAt > 250) {
const v = this.sim.data.qvel,
a = this.sim.rootDof;
this.onTelemetry({
fps: Math.round((this.frames * 1000) / (now - this.fpsAt)),
ctrlHz: this.ctrlHz,
speed: Math.hypot(v[a], v[a + 1]),
odo: this.odo,
peers: 0,
});
this.telemetryAt = now;
}
}
debug() {
const self = this;
return {
get model() {
return self.sim.model;
},
get data() {
return self.sim.data;
},
mujoco: this.sim.mujoco,
camera: this.camera,
controls: this.controls,
get chaseCam() {
return self.chaseCamera.enabled;
},
scene: this.scene,
world: this.world,
command: this.input.command,
lastAction: this.ctx.lastAction,
skills: this.skills,
buildObs: () => {
this.ctx.command.set(this.input.command);
return Object.values(this.obs.write())[0];
},
pause: () => this.pause(),
resume: () => this.resume(),
step: (n) => this.scheduler.step(n),
resetSim: () => this.reset(),
toggle: (id) => this.toggle(id),
get fallen() {
return self.fallen;
},
get actuationStats() {
const a = self.actuation;
return {
samples: a.samples ?? 0,
saturated: a.saturated ?? 0,
saturationRatio: a.samples ? a.saturated / a.samples : 0,
longestSaturatedSeconds:
(a.maxStreak ?? 0) * self.config.sim.timestep,
};
},
get running() {
return self.scheduler.running;
},
};
}
async dispose() {
if (this.disposed) return;
this.disposed = true;
this.active = false;
await this.scheduler.dispose();
this.input.dispose();
this.chaseCamera?.dispose();
this.controls?.dispose();
this.worldPresentation?.dispose();
this.rig.dispose();
await this.controller.dispose();
this.sim.dispose();
}
}
+189
View File
@@ -0,0 +1,189 @@
import * as THREE from "three";
import { loadIndex, loadPackage, loadWorld } from "../loader/PackageLoader.js";
import { resolveWorldId } from "../worlds/arena.js";
// Factories are registered by the application, not selected by robot-id checks.
export class RuntimeManager {
constructor({
scene,
camera,
renderer,
factories,
publish,
getState,
runOnReady = true,
}) {
Object.assign(this, {
scene,
camera,
renderer,
factories,
publish,
getState,
runOnReady,
});
this.active = null;
this.busy = false;
this.disposed = false;
this.generation = 0;
this.memory = new Map();
this.pending = Promise.resolve();
}
async init() {
this.entries = await loadIndex();
if (this.disposed) return;
this.publish({ robots: this.entries });
return this.switchTo(this.entries[0].id);
}
switchTo(id) {
if (this.busy || this.disposed) return Promise.resolve(false);
this.busy = true;
this.retryId = id;
this.pending = this.#switch(id).finally(() => {
this.busy = false;
});
return this.pending;
}
async #switch(id) {
const token = ++this.generation,
old = this.active,
{ paused, fallen } = this.getState();
let candidate, root;
const previousCamera = this.camera.clone();
this.publish({
runtimePhase: old ? "switching" : "loading",
runtimeError: null,
fallen: false,
bootFailed: false,
});
try {
if (old) {
this.memory.set(old.pkg.config.family, old.runtime.saveSettings?.());
await old.runtime.deactivate?.();
await old.runtime.pause();
}
this.publish({ paused });
const entry = this.entries.find((e) => e.id === id);
if (!entry) throw new Error(`Unknown Package ${id}`);
const pkg = await loadPackage(entry.url),
world = await loadWorld(resolveWorldId(pkg.config));
const factory = this.factories[pkg.config.adapter];
if (!factory)
throw new Error(`Unregistered adapter ${pkg.config.adapter}`);
root = new THREE.Group();
const camera = this.camera.clone();
const publish = (patch) => {
if (!this.disposed && !this.busy && this.active?.runtime === candidate)
this.publish(patch);
};
candidate = await factory({
pkg,
world,
scene: root,
camera,
renderer: this.renderer,
autoStart: false,
publish,
onStatus: publish,
onTelemetry: (telemetry) => publish({ telemetry }),
});
await candidate.restoreSettings?.(this.memory.get(pkg.config.family));
if (this.disposed || token !== this.generation) {
await candidate.dispose();
return false;
}
// Nothing rendering/controlling the candidate was made visible until now.
this.camera.copy(camera);
candidate.bindCamera?.(this.camera);
if (!candidate.bindCamera) candidate.camera = this.camera;
this.scene.add(root);
this.active = { runtime: candidate, root, pkg };
candidate.activate({ paused: true });
window.rl = candidate.debug();
this.publish({
runtimePhase: old ? "switching" : "loading",
runtimeError: null,
bootDone: true,
bootFailed: false,
paused,
robotId: pkg.config.id,
presentationTheme: pkg.config.presentation.theme,
robotLicense: pkg.config.license,
inputBindings: pkg.config.input.bindings,
runtimeCapabilities: {},
actuationLabel: "",
fallen: false,
...candidate.status?.(),
});
if (old) {
old.root.removeFromParent();
await old.runtime
.dispose()
.catch((error) => console.error("[retired cleanup]", error));
}
if (this.disposed) return false;
this.publish({ runtimePhase: "ready" });
if (!paused && this.runOnReady) candidate.resume();
return true;
} catch (error) {
if (candidate) await candidate.dispose().catch(console.error);
root?.removeFromParent();
this.active = old;
if (this.disposed) return false;
this.camera.copy(previousCamera);
// Keep a known-good instance even when compilation or inference failed.
if (old) {
this.active = old;
old.runtime.reactivate({ paused });
window.rl = old.runtime.debug();
}
this.publish({
runtimePhase: old ? "ready" : "error",
paused,
runtimeError: error.message,
fallen,
bootFailed: !old,
bootDone: !!old,
});
console.error("[package load]", error);
return false;
}
}
frame(dt) {
this.active?.runtime.frame?.(dt);
}
async pause() {
if (this.busy || this.disposed) return;
await this.active?.runtime.pause();
this.publish({ paused: true });
}
resume() {
if (this.busy || this.disposed) return;
this.active?.runtime.resume();
this.publish({ paused: false });
}
async reset() {
if (this.busy || this.disposed) return;
try {
await this.active?.runtime.reset();
} catch (e) {
this.publish({ runtimeError: e.message });
}
}
retry() {
return this.entries
? this.switchTo(this.retryId ?? this.entries[0]?.id)
: this.init();
}
async dispose() {
if (this.disposed) return;
this.disposed = true;
this.generation++;
await this.pending;
const active = this.active;
this.active = null;
if (active) {
active.root.removeFromParent();
await active.runtime.dispose();
}
}
}
@@ -0,0 +1,30 @@
// Timers advance only with simulation control intervals. UI/render clocks
// remain wall-clock driven and are deliberately not part of this class.
export class SimulationClock {
time = 0;
#next = 0;
#timers = new Map();
setTimeout(callback, milliseconds) {
const id = ++this.#next;
this.#timers.set(id, { due: this.time + milliseconds, callback });
return id;
}
clearTimeout(id) {
this.#timers.delete(id);
}
advance(seconds) {
if (!(seconds >= 0 && Number.isFinite(seconds)))
throw new Error("Invalid clock dt");
this.time += seconds * 1000;
for (const [id, timer] of [...this.#timers]) {
if (timer.due <= this.time + 1e-8) {
this.#timers.delete(id);
timer.callback();
}
}
}
reset() {
this.time = 0;
this.#timers.clear();
}
}
+20
View File
@@ -0,0 +1,20 @@
import mujocoWasmUrl from "@mujoco/mujoco/mujoco.wasm?url";
import ortWasmUrl from "onnxruntime-web/ort-wasm-simd-threaded.wasm?url";
let pending;
export function loadRuntimes() {
return (pending ??= (async () => {
const [{ default: factory }, ort] = await Promise.all([
import("@mujoco/mujoco"),
import("onnxruntime-web/wasm"),
]);
ort.env.wasm.wasmPaths = { wasm: ortWasmUrl };
ort.env.wasm.numThreads = 1;
const mujoco = await factory({
locateFile: (p) => (p.endsWith(".wasm") ? mujocoWasmUrl : p),
});
return { mujoco, ort };
})().catch((error) => {
pending = null;
throw error;
}));
}
+48
View File
@@ -0,0 +1,48 @@
import { arenaWalls } from "../worlds/arena.js";
export function composeScene(xml, config, world) {
const doc = new DOMParser().parseFromString(xml, "text/xml");
if (
doc.querySelector("parsererror") ||
doc.documentElement.tagName !== "mujoco"
)
throw new Error("model: invalid MJCF XML");
const option =
doc.querySelector("mujoco > option") ?? doc.createElement("option");
option.setAttribute("timestep", String(config.sim.timestep));
if (!option.parentNode) doc.documentElement.append(option);
if (world.type !== "flat")
throw new Error(`World ${world.id}: generic composer requires flat World`);
const worldbody = doc.querySelector("mujoco > worldbody");
if (!worldbody) throw new Error("model: worldbody missing");
if (doc.querySelector('[name="platform_floor"]'))
throw new Error("World name collision: platform_floor");
const floor = doc.createElement("geom");
for (const [key, value] of Object.entries({
name: "platform_floor",
type: "plane",
size: "0 0 0.05",
rgba: world.floor.rgba.join(" "),
friction: world.floor.friction.join(" "),
}))
floor.setAttribute(key, value);
worldbody.append(floor);
if (world.boundary) {
for (const wall of arenaWalls(world.boundary)) {
if (doc.querySelector(`[name="${wall.name}"]`))
throw new Error(`World name collision: ${wall.name}`);
const geom = doc.createElement("geom");
for (const [key, value] of Object.entries({
name: wall.name,
type: "box",
pos: wall.pos.join(" "),
size: wall.size.join(" "),
contype: "1",
conaffinity: "1",
group: "0",
}))
geom.setAttribute(key, value);
worldbody.append(geom);
}
}
return new XMLSerializer().serializeToString(doc);
}
+134
View File
@@ -0,0 +1,134 @@
import { fetchChecked } from "../loader/PackageLoader.js";
import { composeScene } from "./SceneComposer.js";
export function resolveAddresses(mujoco, model, names) {
const joints = new Map();
for (const name of names) {
const id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_JOINT.value, name);
if (id < 0) throw new Error(`joints: missing ${name}`);
if (![2, 3].includes(model.jnt_type[id]))
throw new Error(
`joints.${name}: only scalar slide/hinge joints are supported`,
);
const actuators = [];
for (let a = 0; a < model.nu; a++)
if (model.actuator_trnid[a * 2] === id && model.actuator_trntype[a] <= 1)
actuators.push(a);
if (actuators.length !== 1)
throw new Error(
`joints.${name}: expected one actuator, found ${actuators.length}`,
);
if (model.actuator_gear[actuators[0] * 6] !== 1)
throw new Error(
`joints.${name}: non-unit actuator gear requires an explicit backend`,
);
joints.set(name, {
id,
qpos: model.jnt_qposadr[id],
dof: model.jnt_dofadr[id],
actuator: actuators[0],
range: [model.jnt_range[id * 2], model.jnt_range[id * 2 + 1]],
});
}
return joints;
}
export class SimCore {
static async load(mujoco, pkg, world) {
const vfs = new mujoco.MjVFS();
let model, data;
try {
const buffers = await Promise.all(
pkg.config.assets.map((a) => fetchChecked(pkg.asset(a.path), "bytes")),
);
pkg.config.assets.forEach((a, i) =>
vfs.addBuffer(a.vfs, new Uint8Array(buffers[i])),
);
const xml = composeScene(
await fetchChecked(pkg.asset(pkg.config.model)),
pkg.config,
world,
);
model = mujoco.MjModel.from_xml_string(xml, vfs);
data = new mujoco.MjData(model);
return new SimCore(mujoco, model, data, vfs, pkg.config);
} catch (error) {
data?.delete();
model?.delete();
vfs.delete();
throw error;
}
}
constructor(mujoco, model, data, vfs, config) {
Object.assign(this, { mujoco, model, data, vfs, config });
const names = [...new Set(Object.values(config.joints.groups).flat())];
this.joints = resolveAddresses(mujoco, model, names);
for (const [name, j] of this.joints) {
const a = j.actuator,
gain = model.actuator_gainprm[a * 10];
if (
config.actuation.type === "joint_pd" &&
(model.actuator_gaintype[a] !== 0 ||
model.actuator_biastype[a] !== 0 ||
gain !== 1 ||
model.actuator_dyntype[a] !== 0)
)
throw new Error(
`actuation.${name}: joint_pd requires a unit-gain torque motor`,
);
if (
config.actuation.type === "native_position" &&
(model.actuator_biastype[a] !== 1 ||
gain <= 0 ||
Math.abs(model.actuator_biasprm[a * 10 + 1] + gain) > 1e-8)
)
throw new Error(
`actuation.${name}: native_position requires a position servo`,
);
}
this.root = mujoco.mj_name2id(
model,
mujoco.mjtObj.mjOBJ_BODY.value,
config.base.root_body,
);
if (this.root < 0)
throw new Error(`base.root_body: missing ${config.base.root_body}`);
const rootJoint = mujoco.mj_name2id(
model,
mujoco.mjtObj.mjOBJ_JOINT.value,
config.base.freejoint,
);
if (rootJoint < 0 || model.jnt_type[rootJoint] !== 0)
throw new Error(
`base.freejoint: missing/freejoint expected ${config.base.freejoint}`,
);
this.rootQpos = model.jnt_qposadr[rootJoint];
this.rootDof = model.jnt_dofadr[rootJoint];
}
reset(defaults) {
const { mujoco, model, data, config } = this;
mujoco.mj_resetData(model, data);
data.qpos.set(config.base.spawn.pos, this.rootQpos);
data.qpos.set(
[
Math.cos(config.base.spawn.yaw / 2),
0,
0,
Math.sin(config.base.spawn.yaw / 2),
],
this.rootQpos + 3,
);
for (const [name, joint] of this.joints)
data.qpos[joint.qpos] =
config.base.initial?.[name] ?? defaults.get(name) ?? 0;
mujoco.mj_forward(model, data);
}
step() {
this.mujoco.mj_step(this.model, this.data);
}
dispose() {
if (this.disposed) return;
this.disposed = true;
this.data.delete();
this.model.delete();
this.vfs.delete();
}
}
@@ -0,0 +1,60 @@
export class JointPdActuation {
constructor(sim, targets, { kp, kd, torque_limit }) {
Object.assign(this, { sim, targets, kp, kd, limit: torque_limit });
this.pending = new Float64Array(sim.joints.size);
this.clipped = new Uint8Array(sim.joints.size);
this.streaks = new Uint32Array(sim.joints.size);
this.resetStats();
}
resetStats() {
this.samples = 0;
this.saturated = 0;
this.maxStreak = 0;
this.streaks.fill(0);
}
apply() {
const d = this.sim.data,
q = d.qpos,
v = d.qvel,
ctrl = d.ctrl;
let i = 0;
for (const [name, j] of this.sim.joints) {
const target = this.targets.get(name);
if (!Number.isFinite(target))
throw new Error(`actuation.${name}: non-finite target`);
const torque = this.kp * (target - q[j.qpos]) - this.kd * v[j.dof];
if (!Number.isFinite(torque))
throw new Error(`actuation.${name}: non-finite torque`);
this.clipped[i] = Math.abs(torque) > this.limit ? 1 : 0;
this.pending[i++] = Math.max(-this.limit, Math.min(this.limit, torque));
}
i = 0;
for (const j of this.sim.joints.values()) {
this.samples++;
if (this.clipped[i]) {
this.saturated++;
this.streaks[i]++;
this.maxStreak = Math.max(this.maxStreak, this.streaks[i]);
} else this.streaks[i] = 0;
ctrl[j.actuator] = this.pending[i++];
}
}
}
export class NativeActuation {
constructor(sim, targets) {
Object.assign(this, { sim, targets });
this.pending = new Float64Array(sim.joints.size);
}
apply() {
let i = 0;
for (const [name] of this.sim.joints) {
const target = this.targets.get(name);
if (!Number.isFinite(target))
throw new Error(`actuation.${name}: invalid target`);
this.pending[i++] = target;
}
i = 0;
for (const j of this.sim.joints.values())
this.sim.data.ctrl[j.actuator] = this.pending[i++];
}
}
+60
View File
@@ -0,0 +1,60 @@
// Primary owns actor joints; independent scripted overlays own disjoint groups.
export class SkillManager {
constructor(config) {
this.config = config;
this.primary = config.skills.find((s) => s.kind === "primary");
this.overlays = new Map();
for (const skill of config.skills.filter((s) => s.kind === "overlay")) {
if (skill.controller.type !== "oscillator")
throw new Error(
`Unsupported overlay controller ${skill.controller.type}`,
);
this.overlays.set(skill.id, {
skill,
state: "off",
enabled: false,
start: 0,
from: new Map(),
});
}
}
toggle(id, time, positions) {
const overlay = this.overlays.get(id);
if (!overlay) throw new Error(`Unknown overlay ${id}`);
overlay.enabled = !overlay.enabled;
overlay.state = overlay.enabled ? "starting" : "stopping";
overlay.start = time;
for (const name of this.config.joints.groups[overlay.skill.owns])
overlay.from.set(name, positions.get(name));
}
update(time, targets) {
for (const o of this.overlays.values()) {
const p = o.skill.controller,
elapsed = Math.max(0, time - o.start);
for (const name of this.config.joints.groups[o.skill.owns]) {
let target = 0;
if (o.state === "starting" || o.state === "stopping")
target =
(o.from.get(name) ?? 0) * (1 - Math.min(1, elapsed / p.blend));
else if (o.state === "active")
target = p.amplitude * Math.sin(2 * Math.PI * p.frequency * elapsed);
targets.set(name, target);
}
if (
(o.state === "starting" || o.state === "stopping") &&
elapsed >= p.blend
) {
o.state = o.enabled ? "active" : "off";
o.start = time;
}
}
}
reset() {
for (const o of this.overlays.values()) {
o.enabled = false;
o.state = "off";
o.start = 0;
o.from.clear();
}
}
}
+16
View File
@@ -0,0 +1,16 @@
// Shared physical boundary layout. Extents are measured at the INNER faces.
export const DEFAULT_WORLD = "arena";
export const resolveWorldId = (config) =>
config.presentation?.world ?? DEFAULT_WORLD;
export function arenaWalls({ half_extent, wall_height, wall_thickness }) {
const ht = wall_thickness / 2,
hh = wall_height / 2,
off = half_extent + ht,
span = half_extent + wall_thickness;
return [
{ name: "wall_px", pos: [off, 0, hh], size: [ht, span, hh] },
{ name: "wall_nx", pos: [-off, 0, hh], size: [ht, span, hh] },
{ name: "wall_py", pos: [0, off, hh], size: [span, ht, hh] },
{ name: "wall_ny", pos: [0, -off, hh], size: [span, ht, hh] },
];
}
File diff suppressed because it is too large Load Diff
+20
View File
@@ -0,0 +1,20 @@
// Trusted, bundled extension registry. No Package-provided JavaScript URLs.
const worldPresentations = {
"arena-grid": async (options) =>
(
await import("../game/worlds/arena/presentation.js")
).createArenaFloorPresentation(options),
};
export const runtimeFactories = {
microduck: async (options) =>
(await import("./microduck/runtime.js")).bootGame(options),
generic: async (options) => {
const style = options.world.presentation;
const createWorldPresentation = worldPresentations[style];
if (style && !createWorldPresentation)
throw new Error(`Unregistered World presentation ${style}`);
return (
await import("../platform/runtime/RobotRuntime.js")
).RobotRuntime.load({ ...options, createWorldPresentation });
},
};
+72 -31
View File
@@ -1,61 +1,102 @@
// R3F shell around the imperative game core. The Canvas owns the renderer,
// default camera and the rAF loop; <Game> boots the core once and drives it
// from useFrame. Lights and environment are declarative; the grid, walls,
// duck rig, ball and props are added to the scene by the core (they carry
// ceremony-driven shader state).
import { useEffect } from "react";
import * as THREE from "three";
import { Canvas, useThree, useFrame } from "@react-three/fiber";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
import { bootGame } from "../game/game.js";
import { gameApi } from "../store.js";
import { SPAWN_X, SPAWN_Y } from "../game/constants.js";
import { runtimeFactories } from "../robots/registry.js";
import { RuntimeManager } from "../platform/runtime/RuntimeManager.js";
import { useGame, gameApi, bootLog } from "../store.js";
import CrtDistortion, { CRT_DISTORTION_ENABLED } from "./CrtDistortion.jsx";
function Game() {
const { scene, camera, gl } = useThree();
const theme = useGame((s) => s.presentationTheme);
useEffect(() => {
scene.background = new THREE.Color(0x08080c);
gl.setClearColor(0x08080c, 1);
const pmrem = new THREE.PMREMGenerator(gl);
scene.environment = pmrem.fromScene(new RoomEnvironment()).texture;
const pmrem = new THREE.PMREMGenerator(gl),
room = new RoomEnvironment(),
environment = pmrem.fromScene(room);
room.dispose();
pmrem.dispose();
scene.environment = environment.texture;
scene.environmentIntensity = 0.45;
bootGame({ scene, camera, renderer: gl });
bootLog.length = 0;
const manager = new RuntimeManager({
scene,
camera,
renderer: gl,
factories: runtimeFactories,
publish: (patch) => useGame.setState(patch),
getState: useGame.getState,
runOnReady: new URLSearchParams(location.search).get("test") !== "1",
});
const api = {
frame: (dt) => manager.frame(dt),
pause: () => manager.pause(),
resume: () => manager.resume(),
reset: () => manager.reset(),
retry: () => manager.retry(),
switchRobot: (id) => manager.switchTo(id),
diagnostics: () => ({
memory: { ...gl.info.memory },
sceneChildren: scene.children.length,
busy: manager.busy,
}),
};
for (const method of [
"setVariant",
"requestLoco",
"spawnBall",
"loadCustomPolicy",
"clearCustomPolicy",
"triggerAction",
])
api[method] = (...args) => manager.active?.runtime[method]?.(...args);
Object.assign(gameApi, api);
manager.init().catch((error) =>
useGame.setState({
runtimePhase: "error",
runtimeError: error.message,
bootFailed: true,
}),
);
return () => {
if (gameApi.frame === api.frame)
for (const key of Object.keys(gameApi)) delete gameApi[key];
manager.dispose().catch(console.error);
environment.dispose();
if (scene.environment === environment.texture) scene.environment = null;
};
}, [scene, camera, gl]);
// dt clamped so a background-tab stall can't slingshot the camera orbit.
useFrame((_, dt) => {
gameApi.frame?.(Math.min(dt, 0.05));
});
useEffect(() => {
scene.background = new THREE.Color(
theme === "neutral" ? 0x18202b : 0x08080c,
);
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} />
<directionalLight color={0xffb366} position={[0, 3, -2]} intensity={0.7} />
<directionalLight
color={theme === "neutral" ? 0xbcdcff : 0xffb366}
position={[0, 3, -2]}
intensity={0.7}
/>
</>
);
}
export default function GameCanvas() {
const theme = useGame((s) => s.presentationTheme);
return (
<Canvas
style={{ position: "fixed", inset: 0, zIndex: 1 }}
dpr={[1, 2]}
gl={{ antialias: true, alpha: true }}
// Boot framing translated onto the spawn cell (the orbit target
// follows), so the follow-cam has nothing to drift toward during boot.
camera={{
fov: 40,
near: 0.02,
far: 30,
position: [SPAWN_X + 0.55, 0.35, -SPAWN_Y + 0.7],
}}
camera={{ fov: 40, near: 0.02, far: 250, position: [-0.05, 0.35, 0.7] }}
>
<Game />
{CRT_DISTORTION_ENABLED && <CrtDistortion />}
{theme === "comic" && CRT_DISTORTION_ENABLED && <CrtDistortion />}
</Canvas>
);
}
+27 -18
View File
@@ -5,20 +5,28 @@
// milestones). Written via useGame.setState from game code;
// high-frequency values (telemetry) are throttled at the
// producer so React never re-renders at frame rate.
// UI -> gameApi intents (set colour, switch loco, reset, open/close
// menu side effects). gameApi is a plain object populated
// once the game boots; optional-chained calls make the UI
// safe to interact with before that.
// UI -> gameApi intents (robot selection, colour, locomotion, pause,
// reset). The application binds it to RuntimeManager;
// optional chaining keeps early-loading UI safe.
import { create } from "zustand";
import { subscribeWithSelector } from "zustand/middleware";
export const useGame = create(
subscribeWithSelector(() => ({
// Boot lifecycle
prebootDone: false, // title assets ready, grey veil dropped
entered: false, // first "Waddle in" clicked (latches)
menuOpen: false, // title / pause overlay up (opened by App after preboot)
biosVisible: false, // BIOS readout playing over the scene
// Explicit simulation-shell lifecycle (legacy flags remain adapter-only).
runtimePhase: "loading",
paused: false,
runtimeError: null,
helpOpen: true,
robotId: "microduck-legs",
robots: [],
inputBindings: [],
presentationTheme: "comic",
runtimeCapabilities: {},
actuationLabel: '',
robotLicense: "",
fallen: false,
// Adapter-compatible boot diagnostics (no alternate boot screen).
bootDone: false,
bootFailed: false,
@@ -44,8 +52,7 @@ export const useGame = create(
})),
);
// Imperative game surface, assigned by game/game.js once booted. The UI
// only ever optional-chains into it.
// Imperative surface routed to the currently committed runtime.
export const gameApi = {};
// Debug handles for the console / automated QA (same spirit as window.rl).
@@ -54,9 +61,8 @@ if (typeof window !== "undefined") {
window.__gameApi = gameApi;
}
// BIOS/POST milestone log. Plain module state on purpose: the readout
// component polls it inside its own paced replay loop (same as the old
// playBios), so no reactivity is needed and log spam never re-renders React.
// Boot diagnostic log, shown on demand in the inline error panel.
// Keeping it non-reactive avoids a render for every individual asset.
// Entries: { label, status, raw, halt, progress } - status null = pending.
export const bootLog = [];
@@ -76,12 +82,15 @@ export const bootNote = (label) => {
bootLog.push({ label, status: "", raw: true });
};
// Fatal boot failure: freeze the BIOS on the halt screen (the readout is
// the diagnostic surface). Drops the title overlay if still up.
// Compatibility error helper for direct adapter callers; no alternate screen.
export function bootHalt(detail) {
const s = useGame.getState();
if (s.bootFailed || s.bootDone) return;
if (s.bootFailed) return;
bootNote(`>> ${detail}`);
bootLog.push({ label: "SYSTEM HALTED", status: "", raw: true, halt: true });
useGame.setState({ bootFailed: true, menuOpen: false, biosVisible: true });
useGame.setState({
bootFailed: true,
runtimePhase: "error",
runtimeError: detail,
});
}
-195
View File
@@ -1,195 +0,0 @@
// BIOS/POST boot readout. The real load runs silently behind the title
// overlay and only RECORDS milestones into bootLog (store.js); the readout
// itself plays after the first "Waddle in": a rapid-fire replay when
// everything already finished, or an honest live tracker (cursor blinking
// on the pending line) when the user enters mid-load. Never slows the
// actual boot. The line pacing is imperative DOM on purpose - it is a
// character-level animation, not UI state.
import { useEffect, useRef, useState } from "react";
import Box from "@mui/material/Box";
import { keyframes } from "@mui/material/styles";
import { useGame, gameApi, bootLog } from "../store.js";
import { playBiosBeep, playBiosTick } from "../game/audio.js";
import { INK, MONO } from "../theme.js";
const postBlink = keyframes`
0%, 55% { opacity: 1; }
56%, 100% { opacity: 0; }
`;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const lineText = (e) => {
if (e.raw) return e.label;
// Pending line: bare label, plus a live counter when the stage reports
// progress (e.g. "LOADING POLICIES [3/5]").
if (e.status === null) return e.progress ? `${e.label} [${e.progress}]` : e.label;
return `${e.label} `.padEnd(26, ".") + ` ${e.status}`;
};
export default function BiosOverlay() {
const entered = useGame((s) => s.entered);
const bootFailed = useGame((s) => s.bootFailed);
const postRef = useRef(null);
const startedRef = useRef(false);
const [visible, setVisible] = useState(false);
const [off, setOff] = useState(false);
useEffect(() => {
// Only the initial entry triggers the replay (startedRef latches);
// a fatal boot failure forces it up regardless (the halt screen IS
// the diagnostic surface).
if ((!entered && !bootFailed) || startedRef.current) return;
startedRef.current = true;
playBios();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [entered, bootFailed]);
async function playBios() {
const store = useGame.getState;
setVisible(true);
useGame.setState({ biosVisible: true });
// POST beep: the replay only starts after the enter click (the audio
// unlock gesture), and the synth no-ops if the context is still locked
// (gamepad-only entry).
playBiosBeep();
const postEl = postRef.current;
// Seeded LCG: the replay rhythm is random-feeling but identical on
// every load - real POST screens burst through most checks and stall
// on a few.
let seed = 11;
const rand = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
const els = new Map(); // entry -> element
let i = 0;
for (;;) {
const { bootDone, bootFailed: failed } = store();
if (i < bootLog.length) {
const entry = bootLog[i++];
const el = document.createElement("div");
if (entry.halt) el.className = "halt";
postEl.appendChild(el);
els.set(entry, el);
playBiosTick(); // whisper-level teletype tick per printed line
if (entry.status === null && !bootDone && !failed) {
// Honest mode: show the stage label and hold while it's really
// in flight, cursor blinking via CSS.
el.textContent = lineText(entry);
while (entry.status === null && !store().bootDone && !store().bootFailed) {
await sleep(60);
el.textContent = lineText(entry); // live [n/m] counter
}
await sleep(90);
el.textContent = lineText(entry);
} else if (entry.raw || entry.status === null) {
// Header / note lines: quick, no dotted leader to animate.
el.textContent = lineText(entry);
await sleep(20 + 60 * rand());
} else {
// Finished check: bursty POST pacing. Most lines snap in nearly
// instantly; the occasional one stalls on a "slow check" - and
// on a stall the dotted leader types out one dot at a time
// before the status lands.
const r = rand();
const stall = r < 0.75 ? 20 * rand() : 150 + 250 * rand();
if (stall < 45) {
el.textContent = lineText(entry);
await sleep(stall);
} else {
const prefix = `${entry.label} `;
const nDots = Math.max(26 - prefix.length, 3);
el.textContent = prefix;
const per = stall / nDots;
for (let d = 0; d < nDots; d++) {
await sleep(per);
el.textContent += ".";
}
await sleep(40);
el.textContent = lineText(entry);
}
}
} else if (bootDone) {
break;
} else {
// Waiting for the next real stage. On a failed boot this parks the
// console forever: everything queued (FAIL line, error detail,
// SYSTEM HALTED) has been printed and nothing more will come.
await sleep(failed ? 500 : 60);
}
}
const ready = document.createElement("div");
ready.textContent = "READY.";
postEl.appendChild(ready);
playBiosTick();
await sleep(500);
setOff(true);
// Wait out the 0.45 s opacity transition BEFORE cueing the draw-in:
// starting it under the fading overlay hides the first (and busiest)
// part of the animation and only the tail end shows.
await sleep(500);
setVisible(false);
useGame.setState({ biosVisible: false });
// Cue the world draw-in + duck scan-up on a fully black screen.
gameApi.startEntrance?.();
}
return (
<Box
sx={{
position: "fixed",
inset: 0,
display: visible ? "flex" : "none",
// POST readout sits bottom-left like a real BIOS, not centered
alignItems: "flex-end",
justifyContent: "flex-start",
p: "2.2rem 2.4rem",
background: INK,
zIndex: 20,
pointerEvents: "none",
opacity: off ? 0 : 1,
transition: "opacity 0.45s ease",
}}
>
<Box
ref={postRef}
sx={{
minWidth: "min(380px, 84vw)",
// Grow upward from the bottom-left anchor; when the log outgrows
// the viewport, clip the OLDEST lines at the top so the newest
// line + cursor stay visible.
maxHeight: "calc(100vh - 4.4rem)",
display: "flex",
flexDirection: "column",
justifyContent: "flex-end",
overflow: "hidden",
// Raw 90s POST look: small, tight, unsmoothed monospace.
fontFamily: MONO,
fontSize: "12px",
fontWeight: 400,
lineHeight: 1.55,
letterSpacing: 0,
textTransform: "uppercase",
textAlign: "left",
// Robot orange (classic duck's BRIGHT_ORANGE, #ff7a2f in sRGB)
color: "rgba(255, 122, 47, 0.92)",
whiteSpace: "pre-wrap",
overflowWrap: "break-word",
"& > div:first-of-type": {
color: "rgba(255, 255, 255, 0.85)",
marginBottom: "0.55em",
},
// Blinking block cursor at the end of the newest line
"& > div:last-of-type::after": {
content: '"\\2588"',
marginLeft: "0.15em",
animation: `${postBlink} 1s steps(1) infinite`,
},
// Fatal boot failure: SYSTEM HALTED blinks like an old POST fault
"& > div.halt": {
color: "rgba(255, 82, 47, 0.95)",
animation: `${postBlink} 1s steps(1) infinite`,
},
}}
/>
</Box>
);
}
+143
View File
@@ -0,0 +1,143 @@
import { useEffect, useState } from "react";
import Box from "@mui/material/Box";
import { useGame, gameApi } from "../store.js";
import { readLayoutMap, resolveKeycaps } from "./keyboard-layout.js";
const caps = {
ArrowUp: "↑",
ArrowDown: "↓",
ArrowLeft: "←",
ArrowRight: "→",
Space: "Space",
Escape: "Esc",
};
export default function ControlsHelp() {
const open = useGame((s) => s.helpOpen),
bindings = useGame((s) => s.inputBindings),
neutral = useGame((s) => s.presentationTheme === "neutral"),
physicalDrag = useGame((s) => s.runtimeCapabilities.physicalDrag),
blocked = useGame((s) => s.runtimePhase !== "ready");
const disabled = useGame(
(s) => s.runtimePhase !== "ready" || s.paused || s.fallen,
),
license = useGame((s) => s.robotLicense);
const [map, setMap] = useState(null);
useEffect(() => {
let cancelled = false;
const update = async () => {
const next = await readLayoutMap();
if (!cancelled) setMap(next);
};
update();
navigator.keyboard?.addEventListener?.("layoutchange", update);
return () => {
cancelled = true;
navigator.keyboard?.removeEventListener?.("layoutchange", update);
};
}, []);
const { labels } = resolveKeycaps(
bindings.flatMap((b) => b.codes.filter((c) => c.startsWith("Key"))),
map,
);
return (
<Box
component="aside"
aria-label="Keyboard controls"
sx={{
position: "fixed",
right: 24,
top: 20,
zIndex: 12,
maxWidth: 300,
maxHeight: "calc(100vh - 140px)",
overflowY: "auto",
color: "#faf8f2",
background: "rgba(8,8,12,.82)",
border: "1px solid #777",
fontFamily: "monospace",
fontSize: 12,
p: 1.5,
}}
>
<button
type="button"
aria-expanded={open}
onClick={() => useGame.setState({ helpOpen: !open })}
style={{
font: "inherit",
background: "none",
border: 0,
color: "inherit",
cursor: "pointer",
padding: 0,
}}
>
Keyboard controls {open ? "−" : "+"}
</button>
{open && (
<Box sx={{ display: "grid", gap: 1, mt: 1.5 }}>
{bindings.map((row) => {
const clickable = ![
"move_forward",
"move_backward",
"turn_left",
"turn_right",
"reset",
"pause",
].includes(row.action);
return (
<Box
key={row.action}
component={clickable ? "button" : "div"}
type={clickable ? "button" : undefined}
disabled={
clickable
? row.action === "chaseToggle"
? blocked
: disabled
: undefined
}
onClick={
clickable
? () => gameApi.triggerAction?.(row.action)
: undefined
}
sx={{
font: "inherit",
color: "inherit",
textAlign: "left",
background: "none",
border: 0,
p: 0,
cursor: clickable ? "pointer" : "default",
"&:disabled": { opacity: 0.45 },
"&:focus-visible": { outline: "2px solid #83bfff" },
}}
>
<strong style={{ color: neutral ? "#83bfff" : "#ff9a55" }}>
{row.codes.map((c) => caps[c] ?? labels[c] ?? c).join(" / ")}
</strong>
<br />
{row.label}
</Box>
);
})}
<div>
Mouse drag: orbit · wheel: zoom
{physicalDrag && (
<>
<br />
Drag robot / ball: apply force
</>
)}
</div>
{license && (
<details>
<summary>Asset license</summary>
<small>{license}</small>
</details>
)}
</Box>
)}
</Box>
);
}
+4 -48
View File
@@ -151,25 +151,6 @@ function SpeakerIcon({ muted }) {
);
}
function BackArrowIcon() {
return (
<Box
component="svg"
viewBox="0 0 24 24"
aria-hidden
fill="none"
stroke="currentColor"
strokeWidth={2.25}
strokeLinecap="square"
strokeLinejoin="miter"
sx={{ width: "0.95em", height: "0.95em", display: "block", flex: "none" }}
>
<path d="M20 12H6" />
<path d="M12 5l-7 7 7 7" />
</Box>
);
}
const hudHitSx = {
appearance: "none",
display: "inline-flex",
@@ -200,31 +181,6 @@ const hudHitSx = {
},
};
function BackButton() {
return (
<HudPlate
caption="Nav"
sx={{ position: "fixed", top: "1.25rem", left: "1.5rem", zIndex: 10 }}
>
<Box
component="button"
type="button"
onClick={() => { uiClick(); useGame.setState({ menuOpen: true }); }}
sx={{
...hudHitSx,
"&:hover": {
color: ORANGE,
background: "rgba(255, 122, 47, 0.12)",
},
"&:active": { filter: "brightness(0.92)" },
}}
>
<BackArrowIcon /> Back
</Box>
</HudPlate>
);
}
function Quickbar() {
const variant = useGame((s) => s.variant);
const locoWant = useGame((s) => s.locoWant);
@@ -544,13 +500,13 @@ function PolicyToast() {
}
export default function Hud() {
const entered = useGame((s) => s.entered);
const menuOpen = useGame((s) => s.menuOpen);
const ready = useGame((s) => s.runtimePhase === 'ready');
const touchMode = useGame((s) => s.touchMode);
if (!entered || menuOpen) return null;
const duckControls = useGame((s) => s.runtimeCapabilities.duckControls);
if (!ready) return null;
if (!duckControls) return <Telemetry />;
return (
<>
<BackButton />
{!touchMode && (
<>
<Quickbar />
-350
View File
@@ -1,350 +0,0 @@
// Title-menu duck stage: the simulated twin, sitting on the title screen
// like the vitrine landing's colour module - head aims at the pointer
// (idle glances at the camera when it's quiet), click/tap quacks. No
// physics, no policies: just the shared rig posed and micro-animated.
//
// Why a separate rig instead of showing the game scene: the boot
// dramaturgy keeps the in-game duck hidden until the BIOS readout cues
// the entrance scan-up, so the title screen needs its own duck. Geometry
// is free anyway - duck.js caches the GLB module-wide, so this rig and
// the game's share the same buffers.
//
// The stage is a lazy module singleton: built once on first open, then
// re-attached on every pause. The rAF loop only runs while attached.
import { useEffect, useRef } from "react";
import Box from "@mui/material/Box";
import * as THREE from "three";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
import {
loadKinematics, buildRig, setJoint, setJawOpen, applyPose,
SITTING_POSE, groundFullBody, MODEL_DIR,
} from "../game/duck.js";
import { VARIANTS, DEFAULT_VARIANT, materialHookFor, applyVariant } from "../game/variants.js";
import { createWireframeFx } from "../game/fx/fx-wireframe.js";
import { playUrl } from "../game/audio.js";
import { signed } from "../game/signed.js";
import { useGame } from "../store.js";
// Aim calibration, verbatim from the vitrine's duck3d/scene.js: positive
// head_pitch is head-down on the mjlab model, so screen-up subtracts.
const SIGN_YAW = 1;
const SIGN_PITCH = -1;
const SPREAD_YAW = 0.55; // rad of head yaw across half the stage width
const SPREAD_PITCH = 0.32; // rad of head pitch across half the stage height
// Quack envelope: openness eases toward a target instead of replaying a
// fixed curve, so clicking mid-quack never snaps the jaw backwards.
const QUACK_HOLD_S = 0.3;
const QUACK_ATTACK_TAU = 0.04;
const QUACK_RELEASE_TAU = 0.09;
// The vitrine's aim framing, loosened for the menu column: the duck fills
// ~2/3 of the frame height instead of edge to edge. The look height is
// tuned WITH the zoom to put the feet (y=0) ~18% above the frame's bottom
// edge - floating well clear of the shortcut strip.
const CAM_POS = [0.28, 0.2, 0.43];
const CAM_LOOK = [0, 0.122, 0];
const CAM_ZOOM = 0.78;
const FOV_DEG = 32;
// Same voice banks as the game's quack (game.js VOICE_BANK).
const VOICE_BANK = { classic: "duck1", charcoal: "duck2", purple: "duck3", blue: "duck4" };
const CHIRP_TAKES = "abcdefghijkl";
const clamp = (x, a, b) => Math.min(b, Math.max(a, x));
const rand = (a, b) => a + Math.random() * (b - a);
let stagePromise = null;
let liveStage = null;
let stageReady = false;
function getStage() {
if (!stagePromise) {
stagePromise = buildStage()
.then((s) => {
liveStage = s;
stageReady = true;
return s;
})
.catch((e) => {
// Still flip ready: the title screen must not spin forever when
// WebGL / assets fail - it just shows without the duck.
stageReady = true;
throw e;
});
}
return stagePromise;
}
// Title-screen loading gate: the menu holds a spinner until the stage's
// assets are in (kinematics + GLB + rig build), so the content reveal
// and the duck's entrance scan cue together instead of the duck popping
// into an already-settled screen.
export const preloadMenuDuck = () => getStage();
export const isMenuDuckReady = () => stageReady;
async function buildStage() {
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(FOV_DEG, 1, 0.05, 20);
camera.position.set(
...CAM_LOOK.map((l, i) => l + (CAM_POS[i] - l) / CAM_ZOOM),
);
camera.lookAt(...CAM_LOOK);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setClearColor(0x000000, 0);
renderer.setPixelRatio(Math.min(2, window.devicePixelRatio));
// Same output pipeline the variant palette was calibrated against.
renderer.toneMapping = THREE.ACESFilmicToneMapping;
const el = renderer.domElement;
el.style.position = "absolute";
el.style.inset = "0";
el.style.width = "100%";
el.style.height = "100%";
// Anti-flicker: invisible until the first frame has been presented.
el.style.opacity = "0";
el.style.transition = "opacity 0.45s ease";
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment()).texture;
scene.environmentIntensity = 0.25;
// Vitrine light rig: strong white key, soft fill, warm orange rim.
scene.add(new THREE.AmbientLight(0xffffff, 0.45));
const key = new THREE.DirectionalLight(0xffffff, 1.25);
key.position.set(2, 4, 2);
scene.add(key);
const fill = new THREE.DirectionalLight(0xffffff, 0.4);
fill.position.set(-2, 2, 1.5);
scene.add(fill);
const rim = new THREE.DirectionalLight(0xffb366, 0.7);
rim.position.set(0, 3, -2);
scene.add(rim);
const k = await loadKinematics(`${MODEL_DIR}/kinematics.json`);
let appliedVariant = useGame.getState().variant ?? DEFAULT_VARIANT;
if (!VARIANTS[appliedVariant]) appliedVariant = DEFAULT_VARIANT;
const rig = await buildRig(k, {
materialForMesh: materialHookFor(VARIANTS[appliedVariant]),
});
// Face the camera: MJCF forward is +X; the placer yaw turns it to +Z.
rig.placer.rotation.y = -Math.PI / 2;
scene.add(rig.placer);
applyPose(rig, SITTING_POSE);
groundFullBody(rig);
// Vitrine-style entrance: the duck materializes with the wireframe
// scan-up the first time the menu shows. Hidden (clip at floor level)
// until the stage is attached, then start() cues the scan; once done
// the fx restores the real materials and is dropped for good - pause
// reopens show the solid duck immediately.
//
// Shader pre-warm: the scan cycles through three material states, each
// compiling its GPU program on the frame it first renders - the plain
// PBR originals (restored when the scan finishes), the per-mesh clip
// clones (unique customProgramCacheKey each, so ~30 separate PBR
// compiles), and the wireframe ShaderMaterial (only drawn once the
// scan is running). Left alone, those compiles land mid-animation as
// driver-timed freezes. The canvas is still detached and invisible
// here, so render each state once now: solid first, then a mid-scan
// frame (wires on, clones clipping), then rewind to hidden.
renderer.render(scene, camera);
let entranceFx = createWireframeFx();
entranceFx.init({ THREE, scene, root: rig.placer, camera, renderer, hidden: true });
entranceFx.setProgress(0.5);
renderer.render(scene, camera);
entranceFx.setProgress(0);
let entranceStarted = false;
const headPivot = rig.joints.get("head_yaw").body;
const headWorld = new THREE.Vector3();
const camDir = new THREE.Vector3();
// ── Pointer → aim state ───────────────────────────────────────────────
const ndc = new THREE.Vector2(0, 0);
let mountEl = null;
let lastT = 0;
let lastMouseT = -Infinity;
let hasFocus = document.hasFocus();
let mouseInside = true;
let az = 0, el2 = 0;
let attention = 0;
const o1 = rand(0, 6.3), o2 = rand(0, 6.3);
let quackHoldUntil = -Infinity;
let quackOpen = 0;
const onPointerMove = (e) => {
if (!mountEl) return;
const r = mountEl.getBoundingClientRect();
if (!r.width || !r.height) return;
ndc.x = clamp(((e.clientX - r.left) / r.width) * 2 - 1, -2, 2);
ndc.y = clamp(-(((e.clientY - r.top) / r.height) * 2 - 1), -2, 2);
lastMouseT = lastT;
mouseInside = true;
};
const onBlur = () => { hasFocus = false; };
const onFocus = () => { hasFocus = true; };
const onMouseLeave = () => { mouseInside = false; };
const onMouseEnter = () => { mouseInside = true; };
// Any click on the title screen quacks, not just the stage box: the
// overlay owns the whole viewport while the menu is up, and the quack
// never swallows the event (buttons underneath still do their thing).
const onPointerDown = () => quack();
function quack() {
quackHoldUntil = lastT + QUACK_HOLD_S;
const bank = VOICE_BANK[appliedVariant] ?? "duck1";
const take = CHIRP_TAKES[(Math.random() * CHIRP_TAKES.length) | 0];
// The click that lands here is a user gesture, so this also unlocks
// the shared AudioContext on the very first interaction.
playUrl(signed(`./assets/voices/${bank}/chirp_${take}.wav`), { gain: 0.7 });
}
function step(dt, t) {
lastT = t;
headPivot.getWorldPosition(headWorld);
camDir.copy(camera.position).sub(headWorld);
const azCam = Math.atan2(camDir.x, camDir.z);
const elCam = Math.atan2(camDir.y, Math.hypot(camDir.x, camDir.z));
// Attention 0..1: eases toward 1 while the page is focused, the
// pointer is around and moved recently; lazy camera glances otherwise.
const engaged = hasFocus && mouseInside && t - lastMouseT < 3.0;
attention += ((engaged ? 1 : 0) - attention) * (1 - Math.exp(-dt / 0.3));
const azAim = azCam + ndc.x * SPREAD_YAW;
const elAim = elCam * 0.5 + ndc.y * SPREAD_PITCH;
const azIdle = azCam + 0.45 * Math.sin(0.21 * t + o1) * Math.sin(0.09 * t + o2) * 2;
const elIdle = elCam * 0.5 + 0.1 * Math.sin(0.4 * t + o2);
const azT = azIdle + (azAim - azIdle) * attention;
const elT = elIdle + (elAim - elIdle) * attention;
const kSmooth = 1 - Math.exp(-dt * (2.5 + 7.5 * attention));
az += (azT - az) * kSmooth;
el2 += (elT - el2) * kSmooth;
const breathe = Math.sin(t * 1.4) * 0.025;
setJoint(rig, "neck_pitch", SITTING_POSE.neck_pitch + breathe);
setJoint(rig, "head_yaw", SIGN_YAW * az);
setJoint(rig, "head_pitch", SITTING_POSE.head_pitch + SIGN_PITCH * el2);
setJoint(rig, "head_roll", 0.3 * SIGN_YAW * (az - azCam));
const quackTarget = t < quackHoldUntil ? 1 : 0;
const tau = quackTarget > quackOpen ? QUACK_ATTACK_TAU : QUACK_RELEASE_TAU;
quackOpen += (quackTarget - quackOpen) * (1 - Math.exp(-dt / tau));
setJawOpen(rig, quackOpen);
if (entranceFx) {
if (!entranceStarted) {
entranceFx.start();
entranceStarted = true;
}
entranceFx.update(dt);
if (entranceFx.isDone()) {
entranceFx.dispose();
entranceFx = null;
}
}
// Colourway follows the in-game duck (store.variant), fading live.
// Deferred while the entrance scan holds its clip-material clones:
// an applyVariant mid-scan would repaint clones that get thrown away
// on restore. The sync lands on the first frame after the scan.
const v = useGame.getState().variant;
if (!entranceFx && v !== appliedVariant && VARIANTS[v]) {
appliedVariant = v;
applyVariant(rig, v);
}
renderer.render(scene, camera);
if (el.style.opacity === "0") el.style.opacity = "1";
}
// ── Attach / detach (rAF only runs while a mount hosts the canvas) ────
let raf = 0;
let prevNow = 0;
const loop = (now) => {
raf = requestAnimationFrame(loop);
const dt = Math.min((now - prevNow) / 1000, 0.05);
prevNow = now;
step(dt, now / 1000);
};
function resize() {
if (!mountEl) return;
const w = mountEl.clientWidth;
const h = mountEl.clientHeight;
if (!w || !h) return;
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.setSize(w, h);
}
const resizeObserver = new ResizeObserver(resize);
function attach(mount) {
if (!mount || mountEl === mount) return;
detach();
mountEl = mount;
mount.appendChild(el);
resizeObserver.observe(mount);
resize();
window.addEventListener("pointermove", onPointerMove);
window.addEventListener("pointerdown", onPointerDown);
window.addEventListener("blur", onBlur);
window.addEventListener("focus", onFocus);
document.addEventListener("mouseleave", onMouseLeave);
document.addEventListener("mouseenter", onMouseEnter);
prevNow = performance.now();
raf = requestAnimationFrame(loop);
}
function detach() {
if (!mountEl) return;
cancelAnimationFrame(raf);
resizeObserver.disconnect();
window.removeEventListener("pointermove", onPointerMove);
window.removeEventListener("pointerdown", onPointerDown);
window.removeEventListener("blur", onBlur);
window.removeEventListener("focus", onFocus);
document.removeEventListener("mouseleave", onMouseLeave);
document.removeEventListener("mouseenter", onMouseEnter);
el.remove();
mountEl = null;
}
const stage = { attach, detach, quack, step };
// Deterministic hook for automated verification, same spirit as the
// game's window.rl: rAF pauses in background tabs, so tests drive
// frames by hand.
window.__menuDuck = stage;
return stage;
}
export default function MenuDuck({ sx }) {
const hostRef = useRef(null);
useEffect(() => {
let disposed = false;
getStage()
.then((stage) => {
if (disposed) return;
if (hostRef.current) stage.attach(hostRef.current);
})
.catch((e) => console.warn("menu duck disabled:", e));
return () => {
disposed = true;
liveStage?.detach();
};
}, []);
return (
<Box
ref={hostRef}
aria-hidden
sx={{
position: "relative",
touchAction: "manipulation",
userSelect: "none",
...sx,
}}
/>
);
}
+57
View File
@@ -0,0 +1,57 @@
import Box from "@mui/material/Box";
import { useGame, gameApi, bootLog } from "../store.js";
export default function RuntimeStatus() {
const phase = useGame((s) => s.runtimePhase),
paused = useGame((s) => s.paused),
error = useGame((s) => s.runtimeError),
fallen = useGame((s) => s.fallen),
actuationLabel = useGame((s) => s.actuationLabel);
if (phase === "ready" && !paused && !error && !fallen && !actuationLabel)
return null;
return (
<Box
role={error ? "alert" : "status"}
sx={{
position: "fixed",
left: 24,
top: 92,
zIndex: 12,
maxWidth: "min(520px,90vw)",
p: 2,
color: error ? "#ff9988" : "#faf8f2",
background: "rgba(8,8,12,.9)",
border: "1px solid #777",
fontFamily: "monospace",
fontSize: 13,
}}
>
{error ? (
<>
<strong>Simulation error</strong>
<p>{error}</p>
<button type="button" onClick={() => gameApi.retry?.()}>
Retry
</button>
<details>
<summary>Diagnostics</summary>
<pre style={{ whiteSpace: "pre-wrap" }}>
{bootLog.map((e) => `${e.label} ${e.status ?? "…"}`).join("\n")}
</pre>
</details>
</>
) : fallen ? (
"Robot fallen · Space or Reset to restart"
) : phase === "switching" ? (
"Switching robot…"
) : phase === "ready" ? (
paused ? (
"Paused · Esc to continue"
) : (
actuationLabel
)
) : (
"Loading simulation…"
)}
</Box>
);
}
+89
View File
@@ -0,0 +1,89 @@
import Box from "@mui/material/Box";
import { useGame, gameApi } from "../store.js";
export const toolbarStyle = {
position: "fixed",
top: 20,
left: 24,
zIndex: 12,
display: "flex",
alignItems: "center",
gap: 10,
background: "rgba(8,8,12,.86)",
border: "2px solid #faf8f2",
padding: "8px 12px",
color: "#faf8f2",
fontFamily: "monospace",
boxShadow: "3px 3px 0 #08080c",
"& button, & select": {
font: "inherit",
color: "inherit",
border: "1px solid #777",
background: "#202028",
padding: "6px 10px",
cursor: "pointer",
},
"& button:disabled": { opacity: 0.4, cursor: "default" },
"& button:focus-visible, & select:focus-visible": {
outline: "2px solid #ff7a2f",
outlineOffset: 2,
},
};
export default function SimulationToolbar() {
const phase = useGame((s) => s.runtimePhase),
paused = useGame((s) => s.paused),
robots = useGame((s) => s.robots),
robotId = useGame((s) => s.robotId),
neutral = useGame((s) => s.presentationTheme === "neutral");
const ready = phase === "ready",
families = [
...new Map(
robots.map((r) => [
r.family,
{ ...r, id: robots.find((e) => e.family === r.family).id },
]),
).values(),
];
const family =
robots.find((r) => r.id === robotId)?.family ?? families[0]?.family ?? "";
return (
<Box
component="nav"
aria-label="Simulation controls"
sx={{
...toolbarStyle,
border: neutral ? "1px solid #657891" : toolbarStyle.border,
}}
>
<label>
Robot{" "}
<select
aria-label="Robot"
value={family}
disabled={phase === "loading" || phase === "switching"}
onChange={(event) =>
gameApi.switchRobot?.(
families.find((r) => r.family === event.target.value).id,
)
}
>
{families.map((r) => (
<option key={r.family} value={r.family}>
{r.name}
</option>
))}
</select>
</label>
<button
type="button"
disabled={!ready}
aria-pressed={paused}
onClick={() => (paused ? gameApi.resume?.() : gameApi.pause?.())}
>
{paused ? "Continue" : "Pause"}
</button>
<button type="button" disabled={!ready} onClick={() => gameApi.reset?.()}>
Reset
</button>
</Box>
);
}
-744
View File
@@ -1,744 +0,0 @@
// Title / pause overlay: a full-page ink screen printed in the landing's
// comic DA - big Anton title with the ink-drop + cyan/magenta aberration
// treatment, a comic-block CTA on an acid plate, and an orange halftone
// ramp pooling in the top-left corner. Colour and locomotion live in the
// in-game HUD quickbar, so the intro's only action is Waddle in.
//
// The first "Waddle in" cues the BIOS; later Esc / the in-game Back button
// reopen the overlay as pause ("Resume"). The ?boot=1 bypass lives in
// App.jsx and never mounts this component.
import { useEffect, useRef, useState } from "react";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { keyframes, styled } from "@mui/material/styles";
import { useGame } from "../store.js";
import { signed } from "../game/signed.js";
import { playConfirmBloop } from "../game/audio.js";
import { INK, ORANGE, MONO } from "../theme.js";
import { ComicButton, ComicTitle, HalftoneRamp, ANTON, CREAM } from "./comic.jsx";
import MenuDuck, { preloadMenuDuck, isMenuDuckReady } from "./MenuDuck.jsx";
import { readLayoutMap, resolveKeycaps } from "./keyboard-layout.js";
const rowIn = keyframes`
from { transform: translateY(12px); opacity: 0; }
to { transform: none; opacity: 1; }
`;
const brandIn = keyframes`
from { transform: translateY(10px) scale(0.94); opacity: 0; }
to { transform: none; opacity: 1; }
`;
// Title-screen blink for the "press Enter" prompt - a soft pulse, not a
// hard arcade strobe, so it invites rather than nags.
const promptPulse = keyframes`
from { opacity: 0.8; }
to { opacity: 0.18; }
`;
const spin = keyframes`
to { transform: rotate(360deg); }
`;
// One soft ease, small travel, ~80 ms between rows - staged, not showy.
const row = (delay, name = rowIn) => ({
animation: `${name} 0.55s cubic-bezier(0.22, 1, 0.36, 1) both`,
animationDelay: `${delay}s`,
"@media (prefers-reduced-motion: reduce)": { animation: "none" },
});
const Kbd = styled("kbd")(({ round }) => ({
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
minWidth: round ? "1.9rem" : "1.65rem",
height: "1.65rem",
padding: "0 0.45rem",
font: "inherit",
fontSize: "0.68rem",
fontWeight: 600,
color: "#fff",
background: "#14141c",
border: `2px solid ${INK}`,
borderRadius: round ? "50%" : 8,
boxShadow: "0 0 0 2px rgba(255, 255, 255, 0.82)",
}));
// Arcade-style cheat strip pinned at the bottom of the title screen: one
// keycap group + label per move, scannable in a second. The CTA is the
// screen's centre of gravity - players enter first and learn in game.
// Controls bind physical KeyboardEvent.code positions, so letter keycaps
// carry `codes` and get their printed label resolved for the active layout
// (QWERTY fallback where the Keyboard Map API is unavailable).
const SHORTCUTS = {
kb: [
{ caps: ["\u2191\u2190\u2193\u2192"], name: "Move" },
{ codes: ["KeyQ", "KeyE"], name: "Kick" },
{ codes: ["KeyR"], name: "Sit" },
{ codes: ["KeyG"], name: "Pick up" },
{ codes: ["KeyC"], name: "Camera" },
{ caps: ["Space"], name: "Reset" },
],
pad: [
{ caps: ["LS"], name: "Move" },
{ caps: ["LB", "RB"], name: "Kick" },
{ caps: ["Y"], name: "Head" },
{ caps: ["RS"], name: "Camera" },
{ caps: ["X", "\u2193"], name: "Sit" },
],
touch: [
{ caps: ["Stick"], name: "Move" },
{ caps: ["A"], round: true, name: "Kick" },
{ caps: ["B"], round: true, name: "Quack" },
],
};
// kb's hint is built at render time from the resolved layout (see kbHint).
const HINTS = {
pad: "A ground pick \u00b7 RT quack \u00b7 hold LT wheee \u00b7 R3 chase",
touch: "drag to orbit \u00b7 pinch to zoom",
};
// Per-colourway screen accent: the title fill and the halftone pool
// follow the duck on stage. Cream keeps the landing's brand orange (the
// classic duck's trim colour); lavender and sky use the press-kit swatch
// hexes (shared with the vitrine picker); graphite's swatch is too dark
// for type on ink, so it wears the palette's light warm gray instead.
const VARIANT_ACCENTS = {
classic: ORANGE,
charcoal: "#b9b5ae",
purple: "#bfa9cf",
blue: "#a9dbe8",
};
// #rrggbb -> rgba() at the halftone's alpha.
const tint = (hex, a) =>
`rgba(${parseInt(hex.slice(1, 3), 16)}, ${parseInt(hex.slice(3, 5), 16)}, ${parseInt(hex.slice(5, 7), 16)}, ${a})`;
const KB_CODES = SHORTCUTS.kb.flatMap((t) => t.codes ?? []);
function useKeycaps(enabled) {
const [keycaps, setKeycaps] = useState(() => resolveKeycaps(KB_CODES, null));
useEffect(() => {
if (!enabled) return;
let cancelled = false;
let latest = 0;
const read = async () => {
const ticket = ++latest;
const map = await readLayoutMap();
// Overlapping reads can settle out of order; only the newest paints.
if (!cancelled && ticket === latest) setKeycaps(resolveKeycaps(KB_CODES, map));
};
read();
const keyboard = navigator.keyboard;
keyboard?.addEventListener?.("layoutchange", read);
return () => {
cancelled = true;
keyboard?.removeEventListener?.("layoutchange", read);
};
}, [enabled]);
return keycaps;
}
function closeMenu() {
useGame.setState({ menuOpen: false });
if (!useGame.getState().entered) useGame.setState({ entered: true });
// Menu-confirm bloop. On the first entry the `entered` latch above has
// just created the shared AudioContext inside this very gesture, so the
// bloop rides the unlock (the synth resume-retries if still suspended).
playConfirmBloop();
}
export default function TitleMenu() {
const menuOpen = useGame((s) => s.menuOpen);
const entered = useGame((s) => s.entered);
const padConnected = useGame((s) => s.padConnected);
const touchMode = useGame((s) => s.touchMode);
const variant = useGame((s) => s.variant);
const bootDone = useGame((s) => s.bootDone);
const bootFailed = useGame((s) => s.bootFailed);
const [closing, setClosing] = useState(false);
const prevOpen = useRef(menuOpen);
// A plugged-in gamepad wins over the touch tutorial.
const tutorialVariant = padConnected ? "pad" : touchMode ? "touch" : "kb";
const { labels, moveHint } = useKeycaps(tutorialVariant === "kb");
// Touch devices and narrow (mobile-sized) screens skip the 3D stage
// entirely: no duck column, and the GLB is never even downloaded. The
// width check matches the layout's md breakpoint, so the stage never
// renders where the column would stack under the text anyway. Everyone
// else holds a spinner until the stage's assets are in, so the content
// reveal and the duck's entrance scan cue together. The stage is a
// module singleton, so pause reopens resolve instantly (no second
// spinner).
const [wide, setWide] = useState(
() => window.matchMedia("(min-width: 900px)").matches,
);
useEffect(() => {
const mq = window.matchMedia("(min-width: 900px)");
const onChange = () => setWide(mq.matches);
mq.addEventListener("change", onChange);
return () => mq.removeEventListener("change", onChange);
}, []);
const showDuck = !touchMode && wide;
const [duckReady, setDuckReady] = useState(isMenuDuckReady);
useEffect(() => {
if (!showDuck || duckReady) return;
let on = true;
preloadMenuDuck()
.catch(() => {})
.then(() => { if (on) setDuckReady(true); });
return () => { on = false; };
}, [showDuck, duckReady]);
// The display face too: Anton is the screen's voice (title, CTA,
// strip) and would otherwise FOUT in after the reveal. It loads
// lazily on first use, so nudge it explicitly - the content is gated
// and would never request it. Timeout so a stuck font never wedges
// the menu behind the spinner.
const [fontsReady, setFontsReady] = useState(
() => !!document.fonts?.check?.("1rem Anton"),
);
useEffect(() => {
if (fontsReady) return;
let on = true;
const done = () => { if (on) setFontsReady(true); };
const anton = document.fonts?.load
? document.fonts.load("1rem Anton")
: Promise.resolve();
const allFonts = document.fonts?.ready ?? Promise.resolve();
Promise.all([anton, allFonts]).then(done, done);
const t = setTimeout(done, 4000);
return () => { on = false; clearTimeout(t); };
}, [fontsReady]);
// The brand lockup images too (formerly the preboot veil's job): the
// corner chrome is part of the gated reveal, so the logo must not pop
// in after it. Capped so a broken asset never wedges the menu.
const [brandReady, setBrandReady] = useState(false);
useEffect(() => {
if (brandReady) return;
let on = true;
const done = () => { if (on) setBrandReady(true); };
const load = (src) =>
new Promise((res) => {
const img = new Image();
img.src = signed(src);
if (img.complete && img.naturalWidth) res();
else {
img.addEventListener("load", res, { once: true });
img.addEventListener("error", res, { once: true });
}
});
Promise.all([
load("./assets/duck-head-mark.webp"),
load("./assets/duck-head-mark-open.webp"),
]).then(done, done);
const t = setTimeout(done, 2500);
return () => { on = false; clearTimeout(t); };
}, [brandReady]);
// The game core too: it boots eagerly behind the title screen (MuJoCo
// WASM, scene geometry, policy sessions), saturating the main thread
// in ~10-40 ms chunks for a couple of seconds. Revealing the menu
// mid-boot made the duck's entrance scan stutter (profiled: the scan
// window sat inside the boot's busy region), so the spinner holds
// until the boot settles - the reveal then animates on a free thread
// and Waddle-in is instant. bootFailed releases the gate: the halt
// screen owns the viewport at that point.
const ready =
(duckReady || !showDuck) &&
fontsReady &&
brandReady &&
(bootDone || bootFailed);
// Keep the overlay mounted through the 0.35 s closing fade.
useEffect(() => {
const was = prevOpen.current;
prevOpen.current = menuOpen;
if (was && !menuOpen) {
setClosing(true);
const t = setTimeout(() => setClosing(false), 380);
return () => clearTimeout(t);
}
}, [menuOpen]);
// Enter enters / resumes; Esc toggles the pause menu (never over the
// BIOS readout).
useEffect(() => {
const onKey = (e) => {
const s = useGame.getState();
if (e.code === "Enter" && s.menuOpen) {
if (e.target instanceof HTMLButtonElement && e.target.dataset.cta !== "1") return;
e.preventDefault();
closeMenu();
return;
}
if (e.code !== "Escape") return;
if (s.biosVisible) return;
if (s.menuOpen) {
if (s.entered) closeMenu();
return;
}
if (s.entered) useGame.setState({ menuOpen: true });
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, []);
// Gamepad twin of the handler above: A (button 0) enters / resumes
// through the same closeMenu() as the CTA click; Start (9) or Select (8)
// reopens the overlay in-game, like Escape. Polled with a light rAF loop
// because the game's own gamepad source only exists once the core has
// booted (and its actions are game-facing). Edge state persists across
// the open/close transition, so one press fires exactly one action.
useEffect(() => {
const prev = { enter: false, menu: false };
// The A press that closes the menu is applied one frame LATE on
// purpose: closing unlocks the game inputs synchronously, and the
// in-game gamepad source polls in the same rAF round - if it sees the
// press only after the unlock, its own A edge fires (groundPick). The
// one-frame delay guarantees it polls the press at least once while
// the pause lock still gates it, so by the unlock frame its edge
// state already knows the button is down and the entering press is
// swallowed.
let enterPending = false;
let raf;
const poll = () => {
raf = requestAnimationFrame(poll);
if (enterPending) {
enterPending = false;
if (useGame.getState().menuOpen) closeMenu();
}
// Same pad preference as controls/gamepad.js: standard mapping first.
const pads = [...(navigator.getGamepads?.() ?? [])].filter((p) => p && p.connected);
const gp = pads.find((p) => p.mapping === "standard") ?? pads[0];
if (!gp) {
prev.enter = false;
prev.menu = false;
return;
}
const enter = !!gp.buttons[0]?.pressed;
const menu = !!(gp.buttons[9]?.pressed || gp.buttons[8]?.pressed);
const enterEdge = enter && !prev.enter;
const menuEdge = menu && !prev.menu;
prev.enter = enter;
prev.menu = menu;
const s = useGame.getState();
if (enterEdge && s.menuOpen) {
enterPending = true;
return;
}
if (menuEdge && !s.menuOpen && s.entered && !s.biosVisible)
useGame.setState({ menuOpen: true });
};
raf = requestAnimationFrame(poll);
return () => cancelAnimationFrame(raf);
}, []);
if (!menuOpen && !closing) return null;
// Letter keycaps resolved for the active layout (QWERTY fallback).
const shortcuts =
tutorialVariant === "kb"
? SHORTCUTS.kb.map((t) =>
t.codes ? { ...t, caps: t.codes.map((code) => labels[code]) } : t,
)
: SHORTCUTS[tutorialVariant];
// The strip's footnote names the letter movement cluster for the active
// layout too ("ZQSD works too" reads wrong on QWERTY and Dvorak).
const kbHint = `${moveHint.replace(/^arrows or /, "")} works too \u00b7 drag to orbit \u00b7 scroll to zoom`;
const ctaLabel = entered ? "Resume" : "Waddle in";
// Blinking key prompt under the CTA; touch has no key to press.
const enterHint = padConnected ? "press A" : touchMode ? null : "press Enter";
const accent = VARIANT_ACCENTS[variant] ?? ORANGE;
return (
<Box
role="dialog"
aria-modal="true"
aria-label="Microduck"
sx={{
position: "fixed",
inset: 0,
zIndex: 30,
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
p: "2.4rem 1.4rem 1.8rem",
background: INK,
opacity: menuOpen ? 1 : 0,
pointerEvents: menuOpen ? "auto" : "none",
overflowY: "auto",
transition: "opacity 0.35s ease, background 0.4s ease",
}}
>
{/* Theme-orange halftone pooling in the top-left corner, dots
growing toward it - the landing's screen-tone on ink ground. */}
<HalftoneRamp
color={tint(accent, 0.16)}
size={20}
corner="top-left"
reach={60}
/>
{/* Corner branding, shared with the vitrine header (drawn duck
head, top-left). Gated with the rest of the reveal so the
loading state is a single centered spinner on bare ink. */}
{ready && (
<Box
aria-hidden
sx={{
position: "absolute",
top: "1.25rem",
left: "1.5rem",
zIndex: 1,
display: "flex",
alignItems: "center",
gap: "0.65rem",
userSelect: "none",
...row(0, brandIn),
"&:hover .duck-closed": { opacity: 0 },
"&:hover .duck-open": { opacity: 1 },
}}
>
<Box
component="span"
sx={{
position: "relative",
display: "block",
height: "2.1rem",
filter: "drop-shadow(2px 2px 0 rgba(0, 0, 0, 0.5))",
}}
>
<Box
component="img"
className="duck-closed"
alt=""
src={signed("./assets/duck-head-mark.webp")}
sx={{ display: "block", height: "100%", width: "auto" }}
/>
{/* The open frame's canvas (460x333) is a hair wider/taller
than the closed one (454x269); offsets pin the head while
the jaw hangs below. */}
<Box
component="img"
className="duck-open"
alt=""
src={signed("./assets/duck-head-mark-open.webp")}
sx={{
position: "absolute",
top: "-0.75%",
left: "-1.1%",
width: "101.3%",
maxWidth: "none",
height: "auto",
opacity: 0,
}}
/>
</Box>
<Box
component="span"
sx={{
fontFamily: ANTON,
fontSize: "1rem",
letterSpacing: "0.05em",
textTransform: "uppercase",
color: "#fff",
display: { xs: "none", sm: "block" },
}}
>
Microduck
</Box>
</Box>
)}
{/* Loading gate: one centered spinner on bare ink until logo,
fonts, the duck stage's assets and the game boot are all in -
then the whole composition (corner chrome included) reveals at
once (row stagger + entrance scan). */}
{!ready && (
<Box
role="status"
aria-label="Loading"
sx={{
m: "auto",
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: "1.1rem",
}}
>
<Box
aria-hidden
sx={{
width: "2.4rem",
height: "2.4rem",
borderRadius: "50%",
border: "3px solid rgba(255, 255, 255, 0.14)",
borderTopColor: accent,
animation: `${spin} 0.8s linear infinite`,
}}
/>
<Typography
sx={{
fontFamily: MONO,
fontSize: "0.64rem",
fontWeight: 600,
letterSpacing: "0.16em",
textTransform: "uppercase",
color: "rgba(255, 255, 255, 0.5)",
}}
>
Loading
</Typography>
</Box>
)}
{/* Split title screen: brand + CTA column on the left, the live
duck stage on the right (stacked on narrow screens). The row
stretches to fill the space between the corner chrome and the
bottom strip, so the duck stands ON the strip's rule - the
screen has a floor instead of elements floating mid-air. */}
{ready && (
<>
<Box
sx={{
position: "relative",
display: "flex",
flexDirection: { xs: "column", md: "row" },
alignItems: "stretch",
justifyContent: "center",
gap: { xs: "0.4rem", md: "1.5rem" },
width: "100%",
maxWidth: "min(66rem, 94vw)",
flex: "1 1 auto",
minHeight: 0,
pt: { xs: "2.6rem", md: 0 },
}}
>
<Box
sx={{
position: "relative",
flex: { md: "0 1 33rem" },
width: "100%",
maxWidth: { xs: "min(48rem, 92vw)", md: "none" },
mx: { xs: "auto", md: 0 },
// Game-menu grammar: the text block rides the column's vertical
// centre on desktop; left-anchored there, centered when stacked
// or when the duck column is absent (touch mode).
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: { xs: "center", md: showDuck ? "flex-start" : "center" },
textAlign: { xs: "center", md: showDuck ? "left" : "center" },
}}
>
{/* The landing hero's mistracked-VHS treatment: orange fill with
ink drop + chroma ghosts, hollow echo line below. */}
<ComicTitle
component="h1"
tone="dark"
accent={accent}
fontSize="clamp(3.4rem, 9vw, 6.2rem)"
lines={[
{ text: "Microduck" },
{ text: "Simulator", variant: "outline", scale: 0.78 },
]}
sx={{ ...row(0.08) }}
/>
<Typography
sx={{
mx: { xs: "auto", md: 0 },
mt: "1.1rem",
"@media (max-height: 700px)": { mt: "0.8rem" },
maxWidth: "34ch",
fontSize: { xs: "0.95rem", sm: "1.05rem" },
lineHeight: 1.5,
letterSpacing: "-0.012em",
color: "rgba(255, 255, 255, 0.72)",
textWrap: "balance",
...row(0.24),
}}
>
The exact same trained policies that drive the real robot,
live in your browser.
</Typography>
{/* CTA + key prompt travel as one block so the prompt stays
centred under the button whatever the column's alignment. */}
<Box
sx={{
display: "inline-flex",
flexDirection: "column",
alignItems: "center",
mt: "2rem",
"@media (max-height: 700px)": { mt: "1.3rem" },
...row(0.32),
}}
>
<ComicButton
scheme="orange"
size="medium"
onDark
data-cta="1"
onClick={closeMenu}
>
{/* Pad prompt: ink circle with the A face button, shown while a
gamepad is connected - it mirrors the A-to-enter binding of
the poll loop above. Decorative; the text label carries the
meaning. */}
{padConnected && (
<Box
component="span"
aria-hidden
sx={{
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
width: "1.5em",
height: "1.5em",
borderRadius: "50%",
background: INK,
color: CREAM,
fontSize: "0.72em",
lineHeight: 1,
}}
>
A
</Box>
)}
{ctaLabel}
</ComicButton>
{enterHint && (
<Typography
aria-hidden
sx={{
mt: "0.85rem",
fontFamily: MONO,
fontSize: "0.66rem",
fontWeight: 600,
letterSpacing: "0.14em",
textTransform: "uppercase",
color: "rgba(255, 255, 255, 0.6)",
...row(0.4),
}}
>
<Box
component="span"
sx={{
display: "inline-block",
animation: `${promptPulse} 0.95s ease-in-out infinite alternate`,
"@media (prefers-reduced-motion: reduce)": {
animation: "none",
opacity: 0.6,
},
}}
>
{enterHint}
</Box>
</Typography>
)}
</Box>
</Box>
{/* Right column: the duck's simulated twin, live - head follows the
pointer, click quacks. Its colourway tracks the in-game duck. No
backdrop, no fake shadow: the render alone, standing on the
bottom strip's rule like a character select. Touch devices skip
the stage entirely (no column, no GLB download). */}
{showDuck && (
<Box
sx={{
position: "relative",
flex: { xs: "1 1 auto", md: "1 1 22rem" },
width: "100%",
minHeight: { xs: "min(30vh, 16rem)", md: 0 },
...row(0.16, brandIn),
}}
>
<MenuDuck sx={{ position: "absolute", inset: 0 }} />
</Box>
)}
</Box>
{/* Bottom cheat strip: every move on one wrapping line, arcade
instruction-card style. Reference material, not the main event -
it sits at the screen's bottom edge, out of the CTA's way. */}
<Box
sx={{
position: "relative",
width: "100%",
textAlign: "center",
mt: "1.2rem",
pt: "1.15rem",
borderTop: "1px solid rgba(255, 255, 255, 0.08)",
...row(0.5),
}}
>
<Box
sx={{
display: "flex",
flexWrap: "wrap",
justifyContent: "center",
alignItems: "center",
gap: "0.55rem 1.25rem",
// Strip keycaps are a notch smaller than the CTA scale.
"& kbd": {
minWidth: "1.45rem",
height: "1.45rem",
p: "0 0.34rem",
fontSize: "0.6rem",
},
}}
>
{shortcuts.map((s) => (
<Box
key={s.name}
sx={{
display: "inline-flex",
alignItems: "center",
gap: "0.45rem",
}}
>
<Box sx={{ display: "inline-flex", gap: "0.22rem" }}>
{/* Index keys: exotic layouts can print the same glyph twice. */}
{s.caps.map((c, i) => (
<Kbd key={i} round={s.round ? 1 : 0}>{c}</Kbd>
))}
</Box>
<Box
component="span"
sx={{
fontFamily: ANTON,
fontSize: "0.74rem",
letterSpacing: "0.07em",
textTransform: "uppercase",
color: "rgba(255, 255, 255, 0.88)",
}}
>
{s.name}
</Box>
</Box>
))}
</Box>
<Typography
sx={{
mt: "0.7rem",
fontFamily: MONO,
fontSize: "0.62rem",
fontWeight: 600,
letterSpacing: "0.12em",
textTransform: "uppercase",
color: "rgba(255, 255, 255, 0.34)",
}}
>
{tutorialVariant === "kb" ? kbHint : HINTS[tutorialVariant]}
</Typography>
</Box>
</>
)}
</Box>
);
}
-128
View File
@@ -1,128 +0,0 @@
// Touch overlay: Game Boy thumbs. Left thumb = floating virtual stick
// (the whole lower-left quadrant grabs it, the base re-anchors under the
// finger), right thumb = A/B caps on the classic diagonal.
//
// The DOM here is deliberately plain and keyed by ids: controls/touch.js
// binds pointer events to #touch-zone / #touch-stick / #touch-a / #touch-b
// at controller init and toggles the .live/.down classes itself. React
// only owns the wrapper's visibility, so it never fights those mutations -
// which is also why this component must stay mounted at all times.
import Box from "@mui/material/Box";
import { useGame } from "../store.js";
import { INK, ORANGE } from "../theme.js";
export default function TouchOverlay() {
const touchMode = useGame((s) => s.touchMode);
const entered = useGame((s) => s.entered);
const menuOpen = useGame((s) => s.menuOpen);
const visible = touchMode && entered && !menuOpen;
return (
<Box
id="touch-ui"
sx={{
display: visible ? "block" : "none",
// Floating-stick zone: sits BELOW the back button in z so its tap
// still lands; the resting stick inside marks the zone when idle.
"& #touch-zone": {
position: "fixed",
left: 0,
right: "50%",
top: "30%",
bottom: 0,
zIndex: 9,
touchAction: "none",
},
"& #touch-stick": {
position: "absolute",
left: "1.3rem",
bottom: "2rem",
width: "8.2rem",
height: "8.2rem",
borderRadius: "50%",
border: "1px solid rgba(255, 255, 255, 0.18)",
background: "rgba(8, 8, 12, 0.4)",
pointerEvents: "none", // the zone owns the pointer
},
"& #touch-stick .nub": {
position: "absolute",
left: "50%",
top: "50%",
width: "3.6rem",
height: "3.6rem",
margin: "-1.8rem 0 0 -1.8rem",
borderRadius: "50%",
border: "1px solid rgba(255, 255, 255, 0.35)",
background: "rgba(255, 255, 255, 0.14)",
pointerEvents: "none",
},
"& #touch-stick.live": { borderColor: "rgba(255, 122, 47, 0.55)" },
"& #touch-stick.live .nub": {
background: "rgba(255, 122, 47, 0.45)",
borderColor: ORANGE,
},
"& #touch-btns": {
position: "fixed",
right: "1.3rem",
bottom: "2.2rem",
zIndex: 12,
width: "9.4rem",
height: "8.4rem",
},
"& .capwrap": {
position: "absolute",
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: "0.3rem",
},
"& .cap-a": { right: 0, top: 0 },
"& .cap-b": { left: 0, bottom: 0 },
"& #touch-btns button": {
appearance: "none",
width: "4.2rem",
height: "4.2rem",
borderRadius: "50%",
border: "1px solid rgba(255, 255, 255, 0.22)",
background: "rgba(8, 8, 12, 0.5)",
color: "rgba(255, 255, 255, 0.85)",
font: "inherit",
fontSize: "1.3rem",
fontWeight: 700,
cursor: "pointer",
touchAction: "none",
userSelect: "none",
WebkitUserSelect: "none",
},
"& #touch-btns button.down": {
background: ORANGE,
borderColor: ORANGE,
color: INK,
},
"& .capwrap span": {
fontSize: "0.55rem",
fontWeight: 600,
letterSpacing: "0.18em",
textTransform: "uppercase",
color: "rgba(255, 255, 255, 0.45)",
},
}}
>
<div id="touch-zone">
<div id="touch-stick">
<div className="nub" />
</div>
</div>
<div id="touch-btns">
<div className="capwrap cap-a">
<button type="button" id="touch-a" aria-label="Kick">A</button>
<span>Kick</span>
</div>
<div className="capwrap cap-b">
<button type="button" id="touch-b" aria-label="Quack">B</button>
<span>Quack</span>
</div>
</div>
</Box>
);
}