RemiFabre commited on
Commit
2be68c2
Β·
1 Parent(s): 36f3737

Reachy: soft follow cam for scripted scenes, audio lines for the wobbler, URL-driven scripted runs

Browse files

- Follow cam (?camera=follow or {"action":"camera","value":"follow"}): the orbit target eases
from the midpoint between the two robots a little toward whoever speaks or acts, with a
slight dolly, over ~1.5 s; both robots stay in frame.
- A say action may carry "audio" (a wav under public/): the line plays through Web Audio and
the official head wobbler taps its real samples (one offset per 50 ms hop, on the audio
clock); without it the browser voice keeps the synthetic taps.
- ?script=<name>&autoplay=1[&record=1][&ambient=0] runs public/scripts/<name>.json after the
entrance; record=1 keeps the run (canvas + audio) in window.__recording for a headless
recorder.

source/src/game/audio.js CHANGED
@@ -21,7 +21,7 @@ import { signed } from "./signed.js";
21
  // point early-returns, master gain pinned to 0, context never resumed).
22
  // Node-returning helpers (busNode, createEmitter) keep building their
23
  // graph either way so callers stay untouched.
24
- const SOUND_DISABLED = false;
25
 
26
  // ── Context, master, buses ────────────────────────────────────────────
27
  const MASTER_LEVEL = 0.9;
@@ -40,16 +40,16 @@ function unlockOnce() {
40
  export function audioCtx() {
41
  if (ctx) return ctx;
42
  ctx = new (window.AudioContext ?? window.webkitAudioContext)();
43
- master = ctx.createGain();
44
- master.gain.value = SOUND_DISABLED || muted ? 0 : MASTER_LEVEL;
45
- master.connect(ctx.destination);
46
- // Expose a monitor stream for recordings. It mirrors the master mix while
47
- // leaving the normal speaker output unchanged.
48
- try {
49
- const capture = ctx.createMediaStreamDestination();
50
- master.connect(capture);
51
- window.__audioCaptureStream = capture.stream;
52
- } catch { /* MediaStreamDestination is unavailable in a few browsers. */ }
53
  for (const [name, level] of Object.entries(BUS_LEVELS)) {
54
  const g = ctx.createGain();
55
  g.gain.value = level;
@@ -89,7 +89,7 @@ export function setMuted(next) {
89
  const SFX_TAKES = { step: 5, thump: 3, click: 2 };
90
  const bufCache = new Map(); // url -> Promise<AudioBuffer>
91
 
92
- function bufferFor(url) {
93
  let p = bufCache.get(url);
94
  if (!p) {
95
  p = fetch(url)
@@ -149,6 +149,28 @@ export function playUrl(url, { bus = "voice", gain = 1, rate = 1 } = {}) {
149
  }).catch(() => {});
150
  }
151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  export function uiClick() {
153
  playSfx("click", { gain: 0.16, rate: 0.95 + Math.random() * 0.1 });
154
  }
 
21
  // point early-returns, master gain pinned to 0, context never resumed).
22
  // Node-returning helpers (busNode, createEmitter) keep building their
23
  // graph either way so callers stay untouched.
24
+ const SOUND_DISABLED = false;
25
 
26
  // ── Context, master, buses ────────────────────────────────────────────
27
  const MASTER_LEVEL = 0.9;
 
40
  export function audioCtx() {
41
  if (ctx) return ctx;
42
  ctx = new (window.AudioContext ?? window.webkitAudioContext)();
43
+ master = ctx.createGain();
44
+ master.gain.value = SOUND_DISABLED || muted ? 0 : MASTER_LEVEL;
45
+ master.connect(ctx.destination);
46
+ // Expose a monitor stream for recordings. It mirrors the master mix while
47
+ // leaving the normal speaker output unchanged.
48
+ try {
49
+ const capture = ctx.createMediaStreamDestination();
50
+ master.connect(capture);
51
+ window.__audioCaptureStream = capture.stream;
52
+ } catch { /* MediaStreamDestination is unavailable in a few browsers. */ }
53
  for (const [name, level] of Object.entries(BUS_LEVELS)) {
54
  const g = ctx.createGain();
55
  g.gain.value = level;
 
89
  const SFX_TAKES = { step: 5, thump: 3, click: 2 };
90
  const bufCache = new Map(); // url -> Promise<AudioBuffer>
91
 
92
+ export function bufferFor(url) {
93
  let p = bufCache.get(url);
94
  if (!p) {
95
  p = fetch(url)
 
149
  }).catch(() => {});
150
  }
151
 
152
+ // A decoded buffer, started now; returns the audio clock it started on, so a caller can keep
153
+ // something (the head wobbler) in step with the playback.
154
+ export function playBufferTimed(buf, { bus = "voice", gain = 1 } = {}) {
155
+ if (SOUND_DISABLED) return null;
156
+ const c = audioCtx();
157
+ if (c.state === "suspended") c.resume().catch(() => {});
158
+ const src = c.createBufferSource();
159
+ src.buffer = buf;
160
+ const g = c.createGain();
161
+ g.gain.value = gain;
162
+ src.connect(g);
163
+ g.connect(buses[bus]);
164
+ const ended = new Promise((resolve) => { src.onended = () => { g.disconnect(); resolve(buf.duration); }; });
165
+ src.start();
166
+ return { ctx: c, startedAt: c.currentTime, duration: buf.duration, ended };
167
+ }
168
+
169
+ export function setBusLevel(name, level) {
170
+ audioCtx();
171
+ if (buses[name]) buses[name].gain.value = level;
172
+ }
173
+
174
  export function uiClick() {
175
  playSfx("click", { gain: 0.16, rate: 0.95 + Math.random() * 0.1 });
176
  }
source/src/game/emotions/emotionController.js CHANGED
@@ -1,8 +1,8 @@
1
  import { playMicroduckEmotion } from "../microduck/microduckEmotions.js";
2
  import { EMOTIONS, loadReachyEmotion } from "./emotions.js";
3
- import { playUrl } from "../audio.js";
4
  import { signed } from "../signed.js";
5
- import { createSyntheticSpeech } from "../reachy/headWobbler.js";
6
 
7
  let selectedReachyVoice = null;
8
 
@@ -84,6 +84,31 @@ export function createEmotionController({ runtime, reachy, setState }) {
84
  return runTask("reachy", async () => { setState({ emotionStage: "reachy" }); await playReachy(emotion, definition); });
85
  },
86
  say: (text) => reachySay(text, reachy),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  };
88
 
89
  async function playReachy(emotion, definition) {
 
1
  import { playMicroduckEmotion } from "../microduck/microduckEmotions.js";
2
  import { EMOTIONS, loadReachyEmotion } from "./emotions.js";
3
+ import { playUrl, bufferFor, playBufferTimed } from "../audio.js";
4
  import { signed } from "../signed.js";
5
+ import { analyseLine, offsetsAt, ZERO_OFFSETS, createSyntheticSpeech } from "../reachy/headWobbler.js";
6
 
7
  let selectedReachyVoice = null;
8
 
 
84
  return runTask("reachy", async () => { setState({ emotionStage: "reachy" }); await playReachy(emotion, definition); });
85
  },
86
  say: (text) => reachySay(text, reachy),
87
+ // A rendered line (a wav under public/): plays the file with the official head wobbler on the
88
+ // line's own samples (one offset per 50 ms hop, applied against the audio clock), then waits
89
+ // `tail` seconds. Composes with a move.
90
+ sayAudio: (url, tail = 0.3) => runTask(`say:${url}`, async () => {
91
+ setState({ emotionStage: "reachy-say" });
92
+ let played = 0;
93
+ try {
94
+ const buf = await bufferFor(signed(url));
95
+ const hops = await analyseLine(buf);
96
+ const play = playBufferTimed(buf, { gain: 1.0 });
97
+ if (play) {
98
+ let raf = 0;
99
+ const tick = () => {
100
+ const t = play.ctx.currentTime - play.startedAt;
101
+ reachy?.setSpeechOffsets?.(offsetsAt(hops, t));
102
+ if (t < play.duration + 0.1) raf = requestAnimationFrame(tick);
103
+ };
104
+ raf = requestAnimationFrame(tick);
105
+ try { played = await play.ended; } finally { cancelAnimationFrame(raf); reachy?.setSpeechOffsets?.(ZERO_OFFSETS); }
106
+ }
107
+ } catch (e) { console.warn(`[say] ${url}: ${e?.message || e}`); }
108
+ finally { reachy?.setSpeechOffsets?.(ZERO_OFFSETS); }
109
+ if (!played) console.warn(`[say] ${url}: no audio played (decode / context suspended?)`);
110
+ if (tail > 0) await runtime.timeline.wait(tail);
111
+ }),
112
  };
113
 
114
  async function playReachy(emotion, definition) {
source/src/game/game.js CHANGED
@@ -21,14 +21,14 @@
21
  // - UI state flows out through the zustand store (throttled), UI intents
22
  // flow back in through gameApi.
23
 
24
- import * as THREE from "three";
25
- import { loadReachyAssets, registerReachyAssets, attachReachy, captureReachyState, restoreReachyState } from "./reachy/reachyWorld.js";
26
- import { buildReachyRig } from "./reachy/reachyRig.js";
27
- import { createReachyController } from "./reachy/reachyController.js";
28
- import { INITIAL_MOTOR_POSITIONS, MOTOR_NAMES } from "./reachy/reachyKinematics.js";
29
- import { createEmotionController } from "./emotions/emotionController.js";
30
- import { createScriptController } from "./scriptController.js";
31
- import { createSimulationTimeline } from "./simulationTimeline.js";
32
  import { OrbitControls } from "three/addons/controls/OrbitControls.js";
33
  import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
34
  import { signed } from "./signed.js";
@@ -60,7 +60,7 @@ import { createCeremony, CAM_RESET_S } from "./ceremony.js";
60
  import {
61
  audioCtx, busNode, preloadSfx, playSfx, playUrl, updateListener,
62
  createEmitter, startAmbient, setAmbientDucked, playEntranceSweep,
63
- playPropSweep, playLineBlip, setRumble,
64
  } from "./audio.js";
65
  import { createBallActor } from "./ball-actor.js";
66
  import { initGhosts } from "./ghosts.js";
@@ -250,39 +250,39 @@ async function boot({ scene, camera, renderer }) {
250
  name: "terrain", type: "hfield", hfield: "terrain",
251
  pos: `0 0 ${-RELIEF_SINK}`,
252
  }));
253
- // Populate STAND by resolved addresses after native attachment compiles,
254
- // including passive ball-joint quaternions from model.qpos0.
255
  const kf = doc.createElement("keyframe");
256
  kf.appendChild(el("key", {
257
  name: "STAND",
258
  }));
259
- root.appendChild(kf);
260
- attachReachy(doc);
261
  const meshFiles = [...doc.querySelectorAll("asset > mesh")].map((m) => m.getAttribute("file"));
262
  return { xml: new XMLSerializer().serializeToString(doc), meshFiles };
263
  }
264
 
265
  // ── Boot physics + policy in parallel with the render rig ────────────
266
- const [mujoco, { xml, meshFiles }, k, reachyAssets] = await Promise.all([
267
  traced("MUJOCO WASM", loadMujocoFactory({
268
  // Emscripten sidecar resolution: point at the Vite-emitted asset
269
  // instead of a path relative to the module's own URL.
270
  locateFile: (p) => (p.endsWith(".wasm") ? mujocoWasmUrl : p),
271
  })),
272
  traced("PHYSICS MJCF", buildPhysicsXml("robot_allcollisions.xml")),
273
- traced("KINEMATICS", loadKinematics(`${MODEL_DIR}/kinematics.json`)),
274
- traced("REACHY MINI", loadReachyAssets()),
275
  ]);
276
 
277
  const doneMeshes = bootLine("MESH ASSETS");
278
- const vfs = new mujoco.MjVFS();
279
- registerReachyAssets(vfs, reachyAssets);
280
- const reachyRig = buildReachyRig(reachyAssets);
281
- scene.add(reachyRig.root);
282
- // Expose the official visual rig as soon as its assets are ready. The
283
- // title screen can then mount its render-only Reachy stage while the rest
284
- // of MuJoCo and the policies continue compiling.
285
- window.rl = { ...(window.rl ?? {}), reachyRig };
286
  // One shared VFS for both variants; already-loaded files are skipped so
287
  // the roller lazy-load only fetches its leftover meshes.
288
  const vfsFiles = new Set();
@@ -359,83 +359,94 @@ async function boot({ scene, camera, renderer }) {
359
  const doneCompile = bootLine("COMPILING PHYSICS");
360
  let model, data;
361
  try {
362
- model = mujoco.MjModel.from_xml_string(xml, vfs);
363
- initializeStand(model);
364
  data = new mujoco.MjData(model);
365
  } catch (err) {
366
  doneCompile("FAILED");
367
  bootHalt(err?.message || String(err));
368
  throw err;
369
  }
370
- doneCompile("COMPILED");
371
- const timeline = createSimulationTimeline();
372
- const reachy = createReachyController({
373
- mujoco, getWorld: () => ({ model, data }), calibration: reachyAssets.calibration,
374
- timeline, isLocked: () => !!store().emotionBusy,
375
- onState: (state) => setStore({ reachy: { ...store().reachy, ...state } }),
376
- });
377
- const emotionRuntime = {
378
- timeline,
379
- start: () => { emotionOverride = true; emotionCommand.fill(0); setInputLock(true); },
380
- finish: () => { emotionCommand.fill(0); emotionOverride = false; setInputLock(false); headTarget.fill(0); },
381
- drive: (forward = 0, turn = 0) => { emotionCommand[0] = forward; emotionCommand[2] = turn; },
382
- head: (values) => headTarget.set(values),
383
- mode: (next) => setMode(next, { force: true }),
384
- quack: (...args) => quackLoud(...args),
385
- get currentMode() { return mode; },
386
- get sitFlag() { return sitFlag; },
387
- };
388
- const emotions = createEmotionController({ runtime: emotionRuntime, reachy, setState: (patch) => setStore(patch) });
389
- const scripts = createScriptController({ setState: (patch) => setStore(patch) });
390
- scripts.bindWait((seconds) => timeline.wait(seconds));
391
- scripts.bindResolver((entry = {}) => {
392
- const robot = String(entry.robot || entry.actor || "").toLowerCase();
393
- const action = String(entry.action || entry.type || "").toLowerCase();
394
- if (robot === "reachy-mini" || robot === "reachy") {
395
- if (["say", "speech", "speak"].includes(action)) {
396
- const text = String(entry.text || entry.value || "");
397
- return { label: `Reachy says: ${text}`, run: () => emotions.say(text) };
398
- }
399
- if (["emotion", "emotions"].includes(action)) {
400
- const emotion = String(entry.value || entry.emotion || "joy").toLowerCase();
401
- return { label: `Reachy ${emotion}`, run: () => emotions.playReachy(emotion) };
402
- }
403
- }
404
- if (robot === "microduck" || robot === "duck") {
405
- if (["emotion", "emotions"].includes(action)) {
406
- const emotion = String(entry.value || entry.emotion || "joy").toLowerCase();
407
- return { label: `Microduck ${emotion}`, run: () => emotions.playMicroduck(emotion) };
408
- }
409
- if (["wait", "pause"].includes(action)) {
410
- const seconds = Math.max(0, Number(entry.seconds ?? entry.duration ?? 1));
411
- return { label: `Microduck wait ${seconds}s`, run: () => timeline.wait(seconds) };
412
- }
413
- }
414
- if (["wait", "pause"].includes(action)) {
415
- const seconds = Math.max(0, Number(entry.seconds ?? entry.duration ?? 1));
416
- return { label: `Wait ${seconds}s`, run: () => timeline.wait(seconds) };
417
- }
418
- return null;
419
- });
420
-
421
- function initializeStand(m) {
422
- const key = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_KEY.value, "STAND");
423
- const q = Array.from(m.qpos0);
424
- q.splice(0, 7, SPAWN_X, SPAWN_Y, 0.12, 0, 0, 0, 1);
425
- JOINT_NAMES.forEach((name, i) => { q[m.jnt(name).qposadr] = DEFAULT_POSE[i]; });
426
- MOTOR_NAMES.forEach((name, i) => {
427
- const joint = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_JOINT.value, `reachy/${name}`);
428
- if (joint >= 0) q[m.jnt_qposadr[joint]] = INITIAL_MOTOR_POSITIONS[i];
429
- });
430
- const ctrl = new Float64Array(m.nu);
431
- // Resolve by transmission joint: actuator names vary between exports.
432
- for (let i = 0; i < m.nu; i++) {
433
- const jid = m.actuator_trnid[i * 2];
434
- ctrl[i] = q[m.jnt_qposadr[jid]];
435
- }
436
- m.key_qpos.set(q, key * m.nq);
437
- m.key_ctrl.set(ctrl, key * m.nu);
438
- }
 
 
 
 
 
 
 
 
 
 
 
439
 
440
  // Addresses resolved once per compiled variant. qpos/qvel/sensordata
441
  // views are re-read at each use: the WASM heap can grow and detach
@@ -444,12 +455,12 @@ async function boot({ scene, camera, renderer }) {
444
  function resolveAddrs(model, kin) {
445
  return {
446
  qposAdr: JOINT_NAMES.map((n) => model.jnt(n).qposadr),
447
- dofAdr: JOINT_NAMES.map((n) => model.jnt(n).dofadr),
448
- actuatorAdr: JOINT_NAMES.map((n) => {
449
- const joint = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_JOINT.value, n);
450
- for (let id = 0; id < model.nu; id++) if (model.actuator_trnid[id * 2] === joint) return id;
451
- throw new Error(`Missing Microduck actuator for ${n}`);
452
- }),
453
  gyroAdr: model.sensor("imu_ang_vel").adr,
454
  trunkId: mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY.value, "trunk_base"),
455
  standKeyId: mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_KEY.value, "STAND"),
@@ -467,7 +478,7 @@ async function boot({ scene, camera, renderer }) {
467
  };
468
  }
469
  // Active-variant address block, swapped wholesale by activateLoco.
470
- let { qposAdr, dofAdr, actuatorAdr, gyroAdr, trunkId, standKeyId, ballQposAdr, ballDofAdr, extraJoints,
471
  ankleIds } = resolveAddrs(model, k);
472
 
473
  // Locomotion variants stay resident once built (model + data + rig +
@@ -502,11 +513,11 @@ async function boot({ scene, camera, renderer }) {
502
  getManualOverride: () => padSource.isActive() || touchSource.isActive() || kbSource.isActive(),
503
  });
504
  // Keyboard, pad and touch preempt by priority; waypoint is the fallback.
505
- const panelSource = {
506
- id: "panel", command: new Float32Array(3),
507
- isActive() { return this.command[0] !== 0 || this.command[2] !== 0; },
508
- };
509
- const controller = new Controller({ sources: [padSource, touchSource, kbSource, panelSource, waypointSource] });
510
  // Right-stick camera state, read by the telemetry before the camera-orbit
511
  // section below has evaluated.
512
  let padOrbitLive = false;
@@ -545,12 +556,12 @@ async function boot({ scene, camera, renderer }) {
545
  // is ignored (zero twist) until the roll hands back to walk on its own.
546
  // HEAD mode also zeroes it: the runtime stops the robot while the
547
  // sticks drive the head.
548
- const ZERO_CMD = new Float32Array(3);
549
- const emotionCommand = new Float32Array(3);
550
- let emotionOverride = false;
551
- function effectiveCmd() {
552
- if (emotionOverride) return emotionCommand;
553
- if (inputLocked || headMode || mode === "roll" || mode === "crouch" ||
554
  mode === "groundpick" || isKick() || postKickLock > 0 || recovery)
555
  return ZERO_CMD;
556
  return controller.getCommand();
@@ -642,8 +653,8 @@ async function boot({ scene, camera, renderer }) {
642
  grab = null;
643
  }
644
 
645
- function resetSim() {
646
- const reachyState = captureReachyState(mujoco, model, data);
647
  // A live grab must not survive a reset: the per-step spring would
648
  // immediately yank the respawned duck toward the stale cursor target.
649
  endGrabHook();
@@ -663,9 +674,9 @@ async function boot({ scene, camera, renderer }) {
663
  padSource.headMode = false;
664
  headTarget.fill(0);
665
  headSmooth.fill(0);
666
- mujoco.mj_resetDataKeyframe(model, data, standKeyId);
667
- restoreReachyState(model, data, reachyState);
668
- reachy.write();
669
  mujoco.mj_forward(model, data);
670
  lastAction.fill(0);
671
  sitFlag = 0;
@@ -693,9 +704,9 @@ async function boot({ scene, camera, renderer }) {
693
  ballActive = false;
694
  }
695
 
696
- // Pop / respawn the ball in the far corner of the arena. Keeping it away
697
- // from the two robots makes the shared staging area readable; it remains
698
- // available as a separate ball interaction target. If the ball is already on screen,
699
  // peel it away first (reverse scan) and pop the new one when that
700
  // finishes - same appear/disappear pair as the duck's wireframe ceremony.
701
  function spawnBall(opts = {}) {
@@ -707,10 +718,10 @@ async function boot({ scene, camera, renderer }) {
707
  return;
708
  }
709
  const qpos = data.qpos, qvel = data.qvel;
710
- const lim = ARENA_HALF - BALL_RADIUS - 0.05;
711
- const clamp = (v) => Math.min(lim, Math.max(-lim, v));
712
- qpos[ballQposAdr] = clamp(0.95 + (Math.random() - 0.5) * 0.12);
713
- qpos[ballQposAdr + 1] = clamp(0.75 + (Math.random() - 0.5) * 0.12);
714
  qpos[ballQposAdr + 2] = BALL_RADIUS + 0.02;
715
  qpos[ballQposAdr + 3] = 1;
716
  qpos[ballQposAdr + 4] = 0;
@@ -943,23 +954,23 @@ async function boot({ scene, camera, renderer }) {
943
  haptics.tick();
944
  }
945
 
946
- async function controlStep() {
947
- const stepModel = model;
948
- timeline.tick(CTRL_DT);
949
  driveRelief(CTRL_DT); // kinematic terrain, written before the physics steps
950
  // Settle phase: ctrl frozen on the pose held at the fall (approximates
951
  // the runtime's limp beat), physics keeps stepping, no inference.
952
  if (recovery?.state !== "fallen") {
953
  const feeds = { obs: new ort.Tensor("float32", buildObs(), [1, OBS_SIZE]) };
954
- const out = await activeSession().run(feeds);
955
- if (model !== stepModel) return; // a locomotion switch occurred during inference
956
  const act = out.actions.data;
957
  lastAction.set(act);
958
  const ctrl = data.ctrl;
959
- for (let j = 0; j < NUM_JOINTS; j++) ctrl[actuatorAdr[j]] = DEFAULT_POSE[j] + act[j] * ACTION_SCALE;
960
  }
961
- for (let s = 0; s < DECIMATION; s++) {
962
- reachy.write();
963
  applyGrabForce(); // mouse perturbation, fresh velocity every substep
964
  mujoco.mj_step(model, data);
965
  }
@@ -1168,7 +1179,7 @@ async function boot({ scene, camera, renderer }) {
1168
  let trunkGroup = rig.bodies.get("trunk_base");
1169
  locos.legs = {
1170
  model, data, rig, trunkGroup,
1171
- qposAdr, dofAdr, actuatorAdr, gyroAdr, trunkId, standKeyId, ballQposAdr, ballDofAdr, extraJoints, ankleIds,
1172
  };
1173
 
1174
  // ── Locomotion variant switching (legs <-> rollers) ──────────────────
@@ -1189,8 +1200,8 @@ async function boot({ scene, camera, renderer }) {
1189
  ]);
1190
  sessions.drive = sDrive;
1191
  sessions.crouch = sCrouch;
1192
- const rModel = mujoco.MjModel.from_xml_string(rXml, vfs);
1193
- initializeStand(rModel);
1194
  const rData = new mujoco.MjData(rModel);
1195
  locos.rollers = {
1196
  model: rModel, data: rData, rig: rRig, trunkGroup: rRig.bodies.get("trunk_base"),
@@ -1221,18 +1232,18 @@ async function boot({ scene, camera, renderer }) {
1221
  });
1222
  }
1223
 
1224
- function activateLoco(name) {
1225
- const reachyState = captureReachyState(mujoco, model, data);
1226
  const L = locos[name];
1227
  loco = name;
1228
  scene.remove(rig.placer);
1229
- ({ model, data, rig, trunkGroup, qposAdr, dofAdr, actuatorAdr, gyroAdr, trunkId,
1230
  standKeyId, ballQposAdr, ballDofAdr, extraJoints, ankleIds } = L);
1231
  // The rig may have been built (or last shown) under another colourway.
1232
  applyVariant(rig, currentVariant);
1233
  scene.add(rig.placer);
1234
- setStore({ loco: name });
1235
- restoreReachyState(model, data, reachyState);
1236
  resetSim();
1237
  }
1238
 
@@ -1335,19 +1346,104 @@ async function boot({ scene, camera, renderer }) {
1335
 
1336
  // ── Camera: orbit controls + chase cam + reset glide ─────────────────
1337
  const controls = new OrbitControls(camera, renderer.domElement);
1338
- controls.target.set(0, 0.15, 0);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1339
  controls.enableDamping = true;
1340
  controls.dampingFactor = 0.08;
1341
  controls.minDistance = 0.25;
1342
  controls.maxDistance = 3;
1343
  controls.maxPolarAngle = Math.PI / 2 - 0.03;
1344
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1345
  // Chase cam (default ON): each frame the camera eases toward a point
1346
  // behind the duck's heading at the current orbit distance, while the
1347
  // orbit target keeps easing to the trunk in syncRig. Implemented by
1348
  // overwriting camera.position AFTER controls.update() so we never fight
1349
  // OrbitControls' own spherical bookkeeping.
1350
- let chaseCam = false;
1351
  const CHASE_PITCH = 0.42; // rad above horizontal, keeps the floor in view
1352
  const CHASE_EASE = 0.05;
1353
  const _chasePos = new THREE.Vector3();
@@ -1438,13 +1534,13 @@ async function boot({ scene, camera, renderer }) {
1438
  let camResetT0 = null;
1439
  const _camFrom = new THREE.Vector3(), _camTo = new THREE.Vector3();
1440
  const _tgtFrom = new THREE.Vector3(), _tgtTo = new THREE.Vector3();
1441
- function startCameraReset() {
1442
- if (!chaseCam) {
1443
- camera.position.set(0, 0.85, 1.8);
1444
- controls.target.set(0, 0.15, 0);
1445
- camera.lookAt(controls.target);
1446
- return;
1447
- }
1448
  const qpos = data.qpos;
1449
  const yaw = duckYaw(qpos);
1450
  chaseHeldYaw = yaw;
@@ -1585,8 +1681,8 @@ async function boot({ scene, camera, renderer }) {
1585
  // trunk group can take the freejoint pose in raw MJCF coordinates.
1586
  const _target = new THREE.Vector3();
1587
  const _follow = new THREE.Vector3();
1588
- function syncRig() {
1589
- reachyRig.sync(mujoco, model, data);
1590
  const qpos = data.qpos;
1591
  trunkGroup.position.set(qpos[0], qpos[1], qpos[2]);
1592
  trunkGroup.quaternion.set(qpos[4], qpos[5], qpos[6], qpos[3]);
@@ -1599,7 +1695,7 @@ async function boot({ scene, camera, renderer }) {
1599
  // camera by the same delta, so the camera-to-duck distance and viewing
1600
  // angle stay constant while the duck walks. Paused while the reset
1601
  // glide owns the camera.
1602
- if (camResetT0 === null && chaseCam) {
1603
  _target.set(qpos[0], qpos[2], -qpos[1]);
1604
  _follow.copy(_target).sub(controls.target);
1605
  // Horizontal follow at the usual rate; vertical much slower so the
@@ -1887,6 +1983,7 @@ async function boot({ scene, camera, renderer }) {
1887
  }
1888
  controls.update();
1889
  updateChaseCam();
 
1890
  ceremony.drive();
1891
  ball.drive(() => spawnBall({ fromQueue: true }));
1892
  const wpTarget = waypointSource.target;
@@ -2078,29 +2175,29 @@ async function boot({ scene, camera, renderer }) {
2078
  }
2079
 
2080
  // ── Public surface for the React UI ──────────────────────────────────
2081
- Object.assign(gameApi, {
2082
- reachy,
2083
- setDrive: (forward, turn) => {
2084
- const [fwd, back, ang] = velLims();
2085
- panelSource.command[0] = inputLocked ? 0 : forward >= 0 ? Math.min(1, forward) * fwd : Math.min(1, -forward) * back;
2086
- panelSource.command[2] = inputLocked ? 0 : Math.max(-1, Math.min(1, turn)) * ang;
2087
- },
2088
- setMode,
2089
- triggerRoll,
2090
- triggerKick,
2091
- triggerCrouch,
2092
- triggerGroundPick,
2093
- toggleHeadMode,
2094
- quack: quackLoud,
2095
- toggleCamera: () => { chaseCam = !chaseCam; },
2096
- sharedCamera: () => { chaseCam = false; startCameraReset(); },
2097
- setHead: (values) => { if (!inputLocked) headTarget.set(values); },
2098
- emotionRuntime,
2099
- playEmotion: (emotion) => emotions.play(emotion),
2100
- playMicroduckEmotion: (emotion) => emotions.playMicroduck(emotion),
2101
- playReachyEmotion: (emotion) => emotions.playReachy(emotion),
2102
- reachySay: (text) => emotions.say(text),
2103
- script: scripts,
2104
  frame,
2105
  setVariant: (name) => {
2106
  if (!VARIANTS[name] || name === currentVariant) return;
@@ -2123,8 +2220,8 @@ async function boot({ scene, camera, renderer }) {
2123
  window.rl = {
2124
  get model() { return model; },
2125
  get data() { return data; },
2126
- mujoco, camera, controls, reachyRig,
2127
- reachy, timeline,
2128
  get mode() { return mode; },
2129
  get sitFlag() { return sitFlag; },
2130
  buildObs, cmd,
@@ -2186,17 +2283,17 @@ async function boot({ scene, camera, renderer }) {
2186
  setStore({ bootDone: true });
2187
 
2188
  // ── Multiplayer ghosts (WebRTC, serverless signaling) ────────────────
2189
- // Broadcast this duck's pose and render up to 3 other visitors live as
2190
- // translucent ducks. Fire-and-forget: any failure just means no ghosts.
2191
- const r3 = (x) => Math.round(x * 1000) / 1000;
2192
- // Ghost networking is opt-in. Public relay replay can contain stale
2193
- // visitors from another tab/session, which looks like duplicate Microducks
2194
- // in a local simulator. Add ?ghosts=1 when multiplayer ghosts are desired.
2195
- if (new URLSearchParams(location.search).get("ghosts") !== "1") {
2196
- ghosts = { update() {}, peerCount: () => 0, ghostCount: () => 0, debug: () => [], mapDots: () => [], destroy() {} };
2197
- return;
2198
- }
2199
- try {
2200
  // Ghosts only join once the entrance has fully played: the world (and
2201
  // this duck) must stay hidden until then, translucent peers included.
2202
  await ceremony.entranceFinished;
 
21
  // - UI state flows out through the zustand store (throttled), UI intents
22
  // flow back in through gameApi.
23
 
24
+ import * as THREE from "three";
25
+ import { loadReachyAssets, registerReachyAssets, attachReachy, captureReachyState, restoreReachyState, REACHY_POSITION } from "./reachy/reachyWorld.js";
26
+ import { buildReachyRig } from "./reachy/reachyRig.js";
27
+ import { createReachyController } from "./reachy/reachyController.js";
28
+ import { INITIAL_MOTOR_POSITIONS, MOTOR_NAMES } from "./reachy/reachyKinematics.js";
29
+ import { createEmotionController } from "./emotions/emotionController.js";
30
+ import { createScriptController } from "./scriptController.js";
31
+ import { createSimulationTimeline } from "./simulationTimeline.js";
32
  import { OrbitControls } from "three/addons/controls/OrbitControls.js";
33
  import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
34
  import { signed } from "./signed.js";
 
60
  import {
61
  audioCtx, busNode, preloadSfx, playSfx, playUrl, updateListener,
62
  createEmitter, startAmbient, setAmbientDucked, playEntranceSweep,
63
+ playPropSweep, playLineBlip, setRumble, setBusLevel,
64
  } from "./audio.js";
65
  import { createBallActor } from "./ball-actor.js";
66
  import { initGhosts } from "./ghosts.js";
 
250
  name: "terrain", type: "hfield", hfield: "terrain",
251
  pos: `0 0 ${-RELIEF_SINK}`,
252
  }));
253
+ // Populate STAND by resolved addresses after native attachment compiles,
254
+ // including passive ball-joint quaternions from model.qpos0.
255
  const kf = doc.createElement("keyframe");
256
  kf.appendChild(el("key", {
257
  name: "STAND",
258
  }));
259
+ root.appendChild(kf);
260
+ attachReachy(doc);
261
  const meshFiles = [...doc.querySelectorAll("asset > mesh")].map((m) => m.getAttribute("file"));
262
  return { xml: new XMLSerializer().serializeToString(doc), meshFiles };
263
  }
264
 
265
  // ── Boot physics + policy in parallel with the render rig ────────────
266
+ const [mujoco, { xml, meshFiles }, k, reachyAssets] = await Promise.all([
267
  traced("MUJOCO WASM", loadMujocoFactory({
268
  // Emscripten sidecar resolution: point at the Vite-emitted asset
269
  // instead of a path relative to the module's own URL.
270
  locateFile: (p) => (p.endsWith(".wasm") ? mujocoWasmUrl : p),
271
  })),
272
  traced("PHYSICS MJCF", buildPhysicsXml("robot_allcollisions.xml")),
273
+ traced("KINEMATICS", loadKinematics(`${MODEL_DIR}/kinematics.json`)),
274
+ traced("REACHY MINI", loadReachyAssets()),
275
  ]);
276
 
277
  const doneMeshes = bootLine("MESH ASSETS");
278
+ const vfs = new mujoco.MjVFS();
279
+ registerReachyAssets(vfs, reachyAssets);
280
+ const reachyRig = buildReachyRig(reachyAssets);
281
+ scene.add(reachyRig.root);
282
+ // Expose the official visual rig as soon as its assets are ready. The
283
+ // title screen can then mount its render-only Reachy stage while the rest
284
+ // of MuJoCo and the policies continue compiling.
285
+ window.rl = { ...(window.rl ?? {}), reachyRig };
286
  // One shared VFS for both variants; already-loaded files are skipped so
287
  // the roller lazy-load only fetches its leftover meshes.
288
  const vfsFiles = new Set();
 
359
  const doneCompile = bootLine("COMPILING PHYSICS");
360
  let model, data;
361
  try {
362
+ model = mujoco.MjModel.from_xml_string(xml, vfs);
363
+ initializeStand(model);
364
  data = new mujoco.MjData(model);
365
  } catch (err) {
366
  doneCompile("FAILED");
367
  bootHalt(err?.message || String(err));
368
  throw err;
369
  }
370
+ doneCompile("COMPILED");
371
+ const timeline = createSimulationTimeline();
372
+ const reachy = createReachyController({
373
+ mujoco, getWorld: () => ({ model, data }), calibration: reachyAssets.calibration,
374
+ timeline, isLocked: () => !!store().emotionBusy,
375
+ onState: (state) => setStore({ reachy: { ...store().reachy, ...state } }),
376
+ });
377
+ const emotionRuntime = {
378
+ timeline,
379
+ start: () => { emotionOverride = true; emotionCommand.fill(0); setInputLock(true); },
380
+ finish: () => { emotionCommand.fill(0); emotionOverride = false; setInputLock(false); headTarget.fill(0); },
381
+ drive: (forward = 0, turn = 0) => { emotionCommand[0] = forward; emotionCommand[2] = turn; },
382
+ head: (values) => headTarget.set(values),
383
+ mode: (next) => setMode(next, { force: true }),
384
+ quack: (...args) => quackLoud(...args),
385
+ get currentMode() { return mode; },
386
+ get sitFlag() { return sitFlag; },
387
+ };
388
+ const emotions = createEmotionController({ runtime: emotionRuntime, reachy, setState: (patch) => setStore(patch) });
389
+ const scripts = createScriptController({ setState: (patch) => setStore(patch) });
390
+ scripts.bindWait((seconds) => timeline.wait(seconds));
391
+ scripts.bindResolver((entry = {}) => {
392
+ const robot = String(entry.robot || entry.actor || "").toLowerCase();
393
+ const action = String(entry.action || entry.type || "").toLowerCase();
394
+ if (robot === "reachy-mini" || robot === "reachy") {
395
+ if (["say", "speech", "speak"].includes(action)) {
396
+ const text = String(entry.text || entry.value || "");
397
+ // A rendered wav (`audio`, a path under public/): the head wobbles with the voice's own
398
+ // samples; without it, the browser's speech synthesis.
399
+ if (entry.audio) {
400
+ const tail = Math.max(0, Number(entry.tail ?? 0.3));
401
+ return { label: `Reachy says: ${text}`, run: () => (focusOn("reachy"), emotions.sayAudio(`./${String(entry.audio).replace(/^\.?\//, "")}`, tail)) };
402
+ }
403
+ return { label: `Reachy says: ${text}`, run: () => (focusOn("reachy"), emotions.say(text)) };
404
+ }
405
+ if (["emotion", "emotions"].includes(action)) {
406
+ const emotion = String(entry.value || entry.emotion || "joy").toLowerCase();
407
+ return { label: `Reachy ${emotion}`, run: () => (focusOn("reachy"), emotions.playReachy(emotion)) };
408
+ }
409
+ }
410
+ if (robot === "microduck" || robot === "duck") {
411
+ if (["emotion", "emotions"].includes(action)) {
412
+ const emotion = String(entry.value || entry.emotion || "joy").toLowerCase();
413
+ return { label: `Microduck ${emotion}`, run: () => (focusOn("duck"), emotions.playMicroduck(emotion)) };
414
+ }
415
+ if (["wait", "pause"].includes(action)) {
416
+ const seconds = Math.max(0, Number(entry.seconds ?? entry.duration ?? 1));
417
+ return { label: `Microduck wait ${seconds}s`, run: () => timeline.wait(seconds) };
418
+ }
419
+ }
420
+ if (["wait", "pause"].includes(action)) {
421
+ const seconds = Math.max(0, Number(entry.seconds ?? entry.duration ?? 1));
422
+ return { label: `Wait ${seconds}s`, run: () => timeline.wait(seconds) };
423
+ }
424
+ if (action === "camera") {
425
+ // {"action":"camera","value":"follow"|"fixed"}: the soft pan toward whoever acts.
426
+ const value = String(entry.value ?? "follow").toLowerCase();
427
+ return { label: `Camera ${value}`, run: async () => { setCameraFollow(value === "follow"); } };
428
+ }
429
+ return null;
430
+ });
431
+
432
+ function initializeStand(m) {
433
+ const key = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_KEY.value, "STAND");
434
+ const q = Array.from(m.qpos0);
435
+ q.splice(0, 7, SPAWN_X, SPAWN_Y, 0.12, 0, 0, 0, 1);
436
+ JOINT_NAMES.forEach((name, i) => { q[m.jnt(name).qposadr] = DEFAULT_POSE[i]; });
437
+ MOTOR_NAMES.forEach((name, i) => {
438
+ const joint = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_JOINT.value, `reachy/${name}`);
439
+ if (joint >= 0) q[m.jnt_qposadr[joint]] = INITIAL_MOTOR_POSITIONS[i];
440
+ });
441
+ const ctrl = new Float64Array(m.nu);
442
+ // Resolve by transmission joint: actuator names vary between exports.
443
+ for (let i = 0; i < m.nu; i++) {
444
+ const jid = m.actuator_trnid[i * 2];
445
+ ctrl[i] = q[m.jnt_qposadr[jid]];
446
+ }
447
+ m.key_qpos.set(q, key * m.nq);
448
+ m.key_ctrl.set(ctrl, key * m.nu);
449
+ }
450
 
451
  // Addresses resolved once per compiled variant. qpos/qvel/sensordata
452
  // views are re-read at each use: the WASM heap can grow and detach
 
455
  function resolveAddrs(model, kin) {
456
  return {
457
  qposAdr: JOINT_NAMES.map((n) => model.jnt(n).qposadr),
458
+ dofAdr: JOINT_NAMES.map((n) => model.jnt(n).dofadr),
459
+ actuatorAdr: JOINT_NAMES.map((n) => {
460
+ const joint = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_JOINT.value, n);
461
+ for (let id = 0; id < model.nu; id++) if (model.actuator_trnid[id * 2] === joint) return id;
462
+ throw new Error(`Missing Microduck actuator for ${n}`);
463
+ }),
464
  gyroAdr: model.sensor("imu_ang_vel").adr,
465
  trunkId: mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY.value, "trunk_base"),
466
  standKeyId: mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_KEY.value, "STAND"),
 
478
  };
479
  }
480
  // Active-variant address block, swapped wholesale by activateLoco.
481
+ let { qposAdr, dofAdr, actuatorAdr, gyroAdr, trunkId, standKeyId, ballQposAdr, ballDofAdr, extraJoints,
482
  ankleIds } = resolveAddrs(model, k);
483
 
484
  // Locomotion variants stay resident once built (model + data + rig +
 
513
  getManualOverride: () => padSource.isActive() || touchSource.isActive() || kbSource.isActive(),
514
  });
515
  // Keyboard, pad and touch preempt by priority; waypoint is the fallback.
516
+ const panelSource = {
517
+ id: "panel", command: new Float32Array(3),
518
+ isActive() { return this.command[0] !== 0 || this.command[2] !== 0; },
519
+ };
520
+ const controller = new Controller({ sources: [padSource, touchSource, kbSource, panelSource, waypointSource] });
521
  // Right-stick camera state, read by the telemetry before the camera-orbit
522
  // section below has evaluated.
523
  let padOrbitLive = false;
 
556
  // is ignored (zero twist) until the roll hands back to walk on its own.
557
  // HEAD mode also zeroes it: the runtime stops the robot while the
558
  // sticks drive the head.
559
+ const ZERO_CMD = new Float32Array(3);
560
+ const emotionCommand = new Float32Array(3);
561
+ let emotionOverride = false;
562
+ function effectiveCmd() {
563
+ if (emotionOverride) return emotionCommand;
564
+ if (inputLocked || headMode || mode === "roll" || mode === "crouch" ||
565
  mode === "groundpick" || isKick() || postKickLock > 0 || recovery)
566
  return ZERO_CMD;
567
  return controller.getCommand();
 
653
  grab = null;
654
  }
655
 
656
+ function resetSim() {
657
+ const reachyState = captureReachyState(mujoco, model, data);
658
  // A live grab must not survive a reset: the per-step spring would
659
  // immediately yank the respawned duck toward the stale cursor target.
660
  endGrabHook();
 
674
  padSource.headMode = false;
675
  headTarget.fill(0);
676
  headSmooth.fill(0);
677
+ mujoco.mj_resetDataKeyframe(model, data, standKeyId);
678
+ restoreReachyState(model, data, reachyState);
679
+ reachy.write();
680
  mujoco.mj_forward(model, data);
681
  lastAction.fill(0);
682
  sitFlag = 0;
 
704
  ballActive = false;
705
  }
706
 
707
+ // Pop / respawn the ball in the far corner of the arena. Keeping it away
708
+ // from the two robots makes the shared staging area readable; it remains
709
+ // available as a separate ball interaction target. If the ball is already on screen,
710
  // peel it away first (reverse scan) and pop the new one when that
711
  // finishes - same appear/disappear pair as the duck's wireframe ceremony.
712
  function spawnBall(opts = {}) {
 
718
  return;
719
  }
720
  const qpos = data.qpos, qvel = data.qvel;
721
+ const lim = ARENA_HALF - BALL_RADIUS - 0.05;
722
+ const clamp = (v) => Math.min(lim, Math.max(-lim, v));
723
+ qpos[ballQposAdr] = clamp(0.95 + (Math.random() - 0.5) * 0.12);
724
+ qpos[ballQposAdr + 1] = clamp(0.75 + (Math.random() - 0.5) * 0.12);
725
  qpos[ballQposAdr + 2] = BALL_RADIUS + 0.02;
726
  qpos[ballQposAdr + 3] = 1;
727
  qpos[ballQposAdr + 4] = 0;
 
954
  haptics.tick();
955
  }
956
 
957
+ async function controlStep() {
958
+ const stepModel = model;
959
+ timeline.tick(CTRL_DT);
960
  driveRelief(CTRL_DT); // kinematic terrain, written before the physics steps
961
  // Settle phase: ctrl frozen on the pose held at the fall (approximates
962
  // the runtime's limp beat), physics keeps stepping, no inference.
963
  if (recovery?.state !== "fallen") {
964
  const feeds = { obs: new ort.Tensor("float32", buildObs(), [1, OBS_SIZE]) };
965
+ const out = await activeSession().run(feeds);
966
+ if (model !== stepModel) return; // a locomotion switch occurred during inference
967
  const act = out.actions.data;
968
  lastAction.set(act);
969
  const ctrl = data.ctrl;
970
+ for (let j = 0; j < NUM_JOINTS; j++) ctrl[actuatorAdr[j]] = DEFAULT_POSE[j] + act[j] * ACTION_SCALE;
971
  }
972
+ for (let s = 0; s < DECIMATION; s++) {
973
+ reachy.write();
974
  applyGrabForce(); // mouse perturbation, fresh velocity every substep
975
  mujoco.mj_step(model, data);
976
  }
 
1179
  let trunkGroup = rig.bodies.get("trunk_base");
1180
  locos.legs = {
1181
  model, data, rig, trunkGroup,
1182
+ qposAdr, dofAdr, actuatorAdr, gyroAdr, trunkId, standKeyId, ballQposAdr, ballDofAdr, extraJoints, ankleIds,
1183
  };
1184
 
1185
  // ── Locomotion variant switching (legs <-> rollers) ──────────────────
 
1200
  ]);
1201
  sessions.drive = sDrive;
1202
  sessions.crouch = sCrouch;
1203
+ const rModel = mujoco.MjModel.from_xml_string(rXml, vfs);
1204
+ initializeStand(rModel);
1205
  const rData = new mujoco.MjData(rModel);
1206
  locos.rollers = {
1207
  model: rModel, data: rData, rig: rRig, trunkGroup: rRig.bodies.get("trunk_base"),
 
1232
  });
1233
  }
1234
 
1235
+ function activateLoco(name) {
1236
+ const reachyState = captureReachyState(mujoco, model, data);
1237
  const L = locos[name];
1238
  loco = name;
1239
  scene.remove(rig.placer);
1240
+ ({ model, data, rig, trunkGroup, qposAdr, dofAdr, actuatorAdr, gyroAdr, trunkId,
1241
  standKeyId, ballQposAdr, ballDofAdr, extraJoints, ankleIds } = L);
1242
  // The rig may have been built (or last shown) under another colourway.
1243
  applyVariant(rig, currentVariant);
1244
  scene.add(rig.placer);
1245
+ setStore({ loco: name });
1246
+ restoreReachyState(model, data, reachyState);
1247
  resetSim();
1248
  }
1249
 
 
1346
 
1347
  // ── Camera: orbit controls + chase cam + reset glide ─────────────────
1348
  const controls = new OrbitControls(camera, renderer.domElement);
1349
+
1350
+ // ── Scripted runs from the URL ────────────────────────────────────────
1351
+ // ?script=<name> loads public/scripts/<name>.json; &autoplay=1 runs it once the entrance is
1352
+ // over; &record=1 records the run (canvas + the audio monitor) into window.__recording
1353
+ // (base64 webm) for a Playwright recorder; &ambient=0 mutes the ambient bed;
1354
+ // &camera=follow turns the follow cam on.
1355
+ let recording = null;
1356
+ {
1357
+ const params = new URLSearchParams(location.search);
1358
+ const scriptName = params.get("script");
1359
+ if (params.get("ambient") === "0") setBusLevel("ambient", 0);
1360
+ if (params.get("camera") === "follow") {
1361
+ // Once the entrance is over (it owns the camera until then).
1362
+ (async () => { while (!ceremony?.entranceDone) await new Promise((res) => setTimeout(res, 200)); setCameraFollow(true); })();
1363
+ }
1364
+ if (scriptName) {
1365
+ (async () => {
1366
+ try {
1367
+ const r = await fetch(signed(`./scripts/${scriptName}.json`));
1368
+ if (!r.ok) throw new Error(`script ${scriptName}: HTTP ${r.status}`);
1369
+ scripts.load(await r.json());
1370
+ if (params.get("autoplay") !== "1") return;
1371
+ while (!ceremony?.entranceDone) await new Promise((res) => setTimeout(res, 200));
1372
+ await new Promise((res) => setTimeout(res, 1500));
1373
+ if (params.get("record") === "1") {
1374
+ const chunks = [];
1375
+ const stream = renderer.domElement.captureStream(30);
1376
+ const audio = window.__audioCaptureStream;
1377
+ if (audio) audio.getAudioTracks().forEach((t) => stream.addTrack(t));
1378
+ const mime = ["video/webm;codecs=vp9,opus", "video/webm;codecs=vp8,opus", "video/webm"].find((m) => MediaRecorder.isTypeSupported(m));
1379
+ recording = new MediaRecorder(stream, { mimeType: mime, videoBitsPerSecond: 6_000_000 });
1380
+ recording.ondataavailable = (e) => { if (e.data.size) chunks.push(e.data); };
1381
+ recording.onstop = async () => {
1382
+ const blob = new Blob(chunks, { type: mime });
1383
+ const buf = new Uint8Array(await blob.arrayBuffer());
1384
+ let bin = "";
1385
+ for (let i = 0; i < buf.length; i += 0x8000) bin += String.fromCharCode.apply(null, buf.subarray(i, i + 0x8000));
1386
+ window.__recording = btoa(bin);
1387
+ window.__recordingDone = true;
1388
+ };
1389
+ recording.start(500);
1390
+ window.__recordingStartedAt = performance.now();
1391
+ }
1392
+ await scripts.run();
1393
+ window.__scriptDone = true;
1394
+ if (recording) { await new Promise((res) => setTimeout(res, 1500)); recording.stop(); }
1395
+ } catch (error) {
1396
+ console.error("scripted run failed", error);
1397
+ window.__scriptError = error?.message || String(error);
1398
+ window.__scriptDone = true;
1399
+ if (recording?.state === "recording") recording.stop();
1400
+ }
1401
+ })();
1402
+ }
1403
+ }
1404
+ controls.target.set(0, 0.15, 0);
1405
  controls.enableDamping = true;
1406
  controls.dampingFactor = 0.08;
1407
  controls.minDistance = 0.25;
1408
  controls.maxDistance = 3;
1409
  controls.maxPolarAngle = Math.PI / 2 - 0.03;
1410
 
1411
+ // ── Follow cam for scripted scenes ────────────────────────────────────
1412
+ // A soft pan toward whoever speaks or acts: the orbit target eases from the midpoint between
1413
+ // the two robots a little toward the active one, and the camera dollies in slightly, over
1414
+ // ~1.5 s; both robots stay in frame. `?camera=follow` or the script action
1415
+ // {"action":"camera","value":"follow"}. Replaces the chase cam while on.
1416
+ let cameraFollow = false;
1417
+ let focusWho = null;
1418
+ const FOLLOW_BIAS = 0.32; // how far from the midpoint toward the active robot
1419
+ const FOLLOW_DOLLY = 0.9; // camera distance factor when focused
1420
+ const FOLLOW_EASE = 0.035; // per frame at 60 Hz: ~1.5 s to settle
1421
+ const FOLLOW_OFFSET = new THREE.Vector3(0, 0.7, 1.8); // the home framing, relative to the target
1422
+ const _fTarget = new THREE.Vector3(), _fCam = new THREE.Vector3(), _fDuck = new THREE.Vector3(), _fReachy = new THREE.Vector3(), _fMid = new THREE.Vector3();
1423
+ function setCameraFollow(on) { cameraFollow = !!on; if (on) chaseCam = false; }
1424
+ function focusOn(who) { focusWho = who; }
1425
+ function updateFollowCam() {
1426
+ if (!cameraFollow || camResetT0 !== null) return;
1427
+ const qpos = data.qpos;
1428
+ _fDuck.set(qpos[0], 0.12, -qpos[1]);
1429
+ _fReachy.set(REACHY_POSITION[0], 0.22, -REACHY_POSITION[1]);
1430
+ _fMid.lerpVectors(_fDuck, _fReachy, 0.5);
1431
+ const active = focusWho === "duck" ? _fDuck : focusWho === "reachy" ? _fReachy : null;
1432
+ _fTarget.copy(_fMid);
1433
+ if (active) _fTarget.lerp(active, FOLLOW_BIAS);
1434
+ _fTarget.y = 0.15;
1435
+ _fCam.copy(_fTarget).addScaledVector(FOLLOW_OFFSET, active ? FOLLOW_DOLLY : 1.0);
1436
+ controls.target.lerp(_fTarget, FOLLOW_EASE);
1437
+ camera.position.lerp(_fCam, FOLLOW_EASE);
1438
+ camera.lookAt(controls.target);
1439
+ }
1440
+
1441
  // Chase cam (default ON): each frame the camera eases toward a point
1442
  // behind the duck's heading at the current orbit distance, while the
1443
  // orbit target keeps easing to the trunk in syncRig. Implemented by
1444
  // overwriting camera.position AFTER controls.update() so we never fight
1445
  // OrbitControls' own spherical bookkeeping.
1446
+ let chaseCam = false;
1447
  const CHASE_PITCH = 0.42; // rad above horizontal, keeps the floor in view
1448
  const CHASE_EASE = 0.05;
1449
  const _chasePos = new THREE.Vector3();
 
1534
  let camResetT0 = null;
1535
  const _camFrom = new THREE.Vector3(), _camTo = new THREE.Vector3();
1536
  const _tgtFrom = new THREE.Vector3(), _tgtTo = new THREE.Vector3();
1537
+ function startCameraReset() {
1538
+ if (!chaseCam) {
1539
+ camera.position.set(0, 0.85, 1.8);
1540
+ controls.target.set(0, 0.15, 0);
1541
+ camera.lookAt(controls.target);
1542
+ return;
1543
+ }
1544
  const qpos = data.qpos;
1545
  const yaw = duckYaw(qpos);
1546
  chaseHeldYaw = yaw;
 
1681
  // trunk group can take the freejoint pose in raw MJCF coordinates.
1682
  const _target = new THREE.Vector3();
1683
  const _follow = new THREE.Vector3();
1684
+ function syncRig() {
1685
+ reachyRig.sync(mujoco, model, data);
1686
  const qpos = data.qpos;
1687
  trunkGroup.position.set(qpos[0], qpos[1], qpos[2]);
1688
  trunkGroup.quaternion.set(qpos[4], qpos[5], qpos[6], qpos[3]);
 
1695
  // camera by the same delta, so the camera-to-duck distance and viewing
1696
  // angle stay constant while the duck walks. Paused while the reset
1697
  // glide owns the camera.
1698
+ if (camResetT0 === null && chaseCam) {
1699
  _target.set(qpos[0], qpos[2], -qpos[1]);
1700
  _follow.copy(_target).sub(controls.target);
1701
  // Horizontal follow at the usual rate; vertical much slower so the
 
1983
  }
1984
  controls.update();
1985
  updateChaseCam();
1986
+ updateFollowCam();
1987
  ceremony.drive();
1988
  ball.drive(() => spawnBall({ fromQueue: true }));
1989
  const wpTarget = waypointSource.target;
 
2175
  }
2176
 
2177
  // ── Public surface for the React UI ──────────────────────────────────
2178
+ Object.assign(gameApi, {
2179
+ reachy,
2180
+ setDrive: (forward, turn) => {
2181
+ const [fwd, back, ang] = velLims();
2182
+ panelSource.command[0] = inputLocked ? 0 : forward >= 0 ? Math.min(1, forward) * fwd : Math.min(1, -forward) * back;
2183
+ panelSource.command[2] = inputLocked ? 0 : Math.max(-1, Math.min(1, turn)) * ang;
2184
+ },
2185
+ setMode,
2186
+ triggerRoll,
2187
+ triggerKick,
2188
+ triggerCrouch,
2189
+ triggerGroundPick,
2190
+ toggleHeadMode,
2191
+ quack: quackLoud,
2192
+ toggleCamera: () => { chaseCam = !chaseCam; },
2193
+ sharedCamera: () => { chaseCam = false; startCameraReset(); },
2194
+ setHead: (values) => { if (!inputLocked) headTarget.set(values); },
2195
+ emotionRuntime,
2196
+ playEmotion: (emotion) => emotions.play(emotion),
2197
+ playMicroduckEmotion: (emotion) => emotions.playMicroduck(emotion),
2198
+ playReachyEmotion: (emotion) => emotions.playReachy(emotion),
2199
+ reachySay: (text) => emotions.say(text),
2200
+ script: scripts,
2201
  frame,
2202
  setVariant: (name) => {
2203
  if (!VARIANTS[name] || name === currentVariant) return;
 
2220
  window.rl = {
2221
  get model() { return model; },
2222
  get data() { return data; },
2223
+ mujoco, camera, controls, reachyRig,
2224
+ reachy, timeline,
2225
  get mode() { return mode; },
2226
  get sitFlag() { return sitFlag; },
2227
  buildObs, cmd,
 
2283
  setStore({ bootDone: true });
2284
 
2285
  // ── Multiplayer ghosts (WebRTC, serverless signaling) ────────────────
2286
+ // Broadcast this duck's pose and render up to 3 other visitors live as
2287
+ // translucent ducks. Fire-and-forget: any failure just means no ghosts.
2288
+ const r3 = (x) => Math.round(x * 1000) / 1000;
2289
+ // Ghost networking is opt-in. Public relay replay can contain stale
2290
+ // visitors from another tab/session, which looks like duplicate Microducks
2291
+ // in a local simulator. Add ?ghosts=1 when multiplayer ghosts are desired.
2292
+ if (new URLSearchParams(location.search).get("ghosts") !== "1") {
2293
+ ghosts = { update() {}, peerCount: () => 0, ghostCount: () => 0, debug: () => [], mapDots: () => [], destroy() {} };
2294
+ return;
2295
+ }
2296
+ try {
2297
  // Ghosts only join once the entrance has fully played: the world (and
2298
  // this duck) must stay hidden until then, translucent peers included.
2299
  await ceremony.entranceFinished;