feat: comic-panel HUD, runtime-faithful pad mapping, props + wheee voices

- HUD chrome reworked as comic panels: cream keyline frames with 1px ink
  inset, caption cartouches (NAV / SHOP / COLOR / MODE), inner glass
  padding and square gapped colour swatches
- drop the T relief toggle and B ball-respawn keyboard bindings; gamepad
  Y becomes HEAD mode, A ground pick, LT rides the looping wheee
- decor props row + CRT distortion pass, per-duck wheee voice sets,
  ground-pick and stand policies, updated robot meshes, title menu
  refresh; README controls updated

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
tfrere
2026-08-25 14:38:12 +02:00
parent fdc3820099
commit 89f539959e
79 changed files with 2059 additions and 556 deletions
+1
View File
@@ -0,0 +1 @@
.env
-2
View File
@@ -40,7 +40,6 @@ and [apirrone/mjlab_microduck](https://github.com/apirrone/mjlab_microduck).
- M: switch legs <-> rollers
- Q / E (A / E on AZERTY): kick left / right (legs only)
- R: roll (legs) / crouch-glide (rollers)
- B: pop / respawn a kickable ball in front of the duck
- C: toggle the chase camera (on by default; dragging detaches it)
- Space: reset
- Drag to orbit, scroll to zoom
@@ -69,7 +68,6 @@ Plug in a controller and the same mapping as the real robot runtime applies:
- Right stick: orbit the camera (detaches the chase cam)
- R3 (right stick click): toggle the chase cam back on
- X: roll (legs) / crouch-glide (rollers)
- Y: pop / respawn the ball
- RB / LB: right / left kick (legs only)
- D-pad down: sit / stand toggle (legs only)
- D-pad up: hold ~1 s to switch legs <-> rollers (the real robot uses a 3 s hold)
+8
View File
@@ -4,6 +4,14 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Microduck</title>
<!-- Anton: the landing's brutal print display voice (FancyTitle /
ComicButton on the pollen-website Microduck pages). -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Anton&display=swap"
rel="stylesheet"
/>
<style>
:root {
--ink: #08080c;
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+21 -10
View File
@@ -9,6 +9,12 @@ export const POLICIES = {
// 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).
@@ -51,6 +57,11 @@ export const RVEL_FWD = 0.6, RVEL_BACK = -0.5, RVEL_ANG = 0.3;
// 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).
export const BALL_RADIUS = 0.05;
@@ -65,16 +76,16 @@ export const ARENA_WALL_T = 0.05;
// 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 back (-X)
// wall, screens facing the arena. Shared between the visual (game.js
// places the GLB clones) and the physics (buildPhysicsXml adds ONE static
// collision box covering the whole row). Proportions measured from the
// GLB's natural size (0.524 x 0.587 x 1.0 m, w x d x h).
// Real-world size: a classic upright cabinet is ~1.73 m tall. Next to
// the 0.25 m duck they tower like furniture around a real Microduck -
// that's the point. The row of three (each ~0.91 m wide) spans ~2.76 m,
// just fitting along the 3 m wall.
export const ARCADE_H = 1.73; // target height, 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
+3 -1
View File
@@ -69,9 +69,11 @@
//
// ── Actions ──────────────────────────────────────────────────────────────
// roll one-shot roll (crouch-glide in roller mode; game decides)
// groundPick one-shot ground pick cycle (pad A / keyboard G)
// kickL, kickR one-shot kicks, explicit foot
// alternateKick one-shot kick, feet alternated by the game
// spawnBall pop / respawn the kickable ball
// spawnBall pop / respawn the kickable ball (no bound key; game/API)
// 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
+94 -28
View File
@@ -6,8 +6,15 @@
// Right stick camera orbit rate (reported raw in axes.orbitX/Y; the
// velocity smoothing / coasting lives downstream in the
// camera code). R3 toggles the chase cam.
// A ground pick: one-shot pick-up-from-the-ground cycle
// (runtime-faithful; game gates it to walk mode)
// X roll (crouch-glide in roller mode - game decides)
// Y ball spawn/respawn
// Y HEAD mode toggle (runtime-faithful). While the game sets
// `headMode`, locomotion is parked and BOTH sticks drive
// the head instead: left = head pitch/yaw, right = neck
// pitch/head roll (reported in `head`, deflections in
// [-1, 1], up/left positive). The right stick stops
// orbiting the camera for the duration.
// RB / LB right / left kick
// DpadDown sit <-> stand
// DpadUp short press = back to run; HOLD ~1 s = legs <-> rollers
@@ -15,14 +22,19 @@
// RT / LT analog jaw (max of both); RT edge quacks through a
// Schmitt trigger (fire at >= 0.35, re-arm below 0.2 - a
// single threshold re-fires on jitter, which is how one
// squeeze used to quack several times).
// squeeze used to quack several times). LT additionally
// rides the looping "wheee" (runtime behavior): start on
// the rising edge, stop the instant it releases - same
// Schmitt hysteresis so jitter can't restart the ride.
// The two are mutually exclusive: RT edges are ignored
// while the ride is open, LT edges while RT is engaged.
const PAD_DEADZONE = 0.15;
const PAD_ALPHA = 0.12; // EMA smoothing toward the stick target
const dz = (v) => (Math.abs(v) < PAD_DEADZONE ? 0 : v);
// Standard-mapping button indices.
const BTN_X = 2, BTN_Y = 3, BTN_LB = 4, BTN_RB = 5, BTN_LT = 6, BTN_RT = 7;
const BTN_A = 0, BTN_X = 2, BTN_Y = 3, BTN_LB = 4, BTN_RB = 5, BTN_LT = 6, BTN_RT = 7;
const BTN_R3 = 11, BTN_DPAD_UP = 12, BTN_DPAD_DOWN = 13;
const DPAD_UP_HOLD_MS = 1000; // hold-to-switch-loco duration
@@ -32,8 +44,12 @@ export class GamepadSource {
connected = false;
command = new Float32Array(3); // [vx, 0, wz], EMA-smoothed
axes = { jaw: 0, orbitX: 0, orbitY: 0 };
// Head-mode routing flag, owned by the game (mode state machine lives
// there); while true the sticks fill `head` instead of command/orbit.
headMode = false;
head = { neckPitch: 0, pitch: 0, yaw: 0, roll: 0 }; // stick deflections
pressed = {
x: false, y: false, rb: false, lb: false, r3: false,
a: false, x: false, y: false, rb: false, lb: false, r3: false,
dpadDown: false, dpadUp: false,
};
onAction = () => {}; // assigned by the Controller at registration
@@ -43,6 +59,8 @@ export class GamepadSource {
#dpadUpAt = 0; // wall-clock of the current DpadUp press
#dpadUpFired = false; // latch: one loco switch per hold
#rtArmed = true; // Schmitt trigger state for the RT quack
#ltDown = false; // LT physical Schmitt state (edge detection)
#ltRide = false; // wheee ride currently open (LT edge that wasn't blocked)
constructor({ getVelocityLimits }) {
this.#getVelocityLimits = getVelocityLimits;
@@ -67,25 +85,54 @@ export class GamepadSource {
}
this.axes.orbitX = 0;
this.axes.orbitY = 0;
this.#zeroHead();
// A pad yanked mid-ride must not leave the wheee looping forever.
if (this.#ltRide) {
this.#ltRide = false;
this.#ltDown = false;
this.onAction("wheeeStop");
}
return;
}
const now = performance.now();
// Left stick only: vertical = forward/back, horizontal = turn.
// (No strafe; the right stick doesn't drive movement.)
const lx = dz(gp.axes[0] ?? 0), ly = dz(gp.axes[1] ?? 0);
const up = -ly; // browser sticks report up as -1
const rx = dz(gp.axes[2] ?? 0), ry = dz(gp.axes[3] ?? 0);
const [limF, limB, limA] = this.#getVelocityLimits();
const target = [
up >= 0 ? up * limF : up * -limB,
0,
-lx * limA,
];
let target;
if (this.headMode) {
// HEAD mode: locomotion parks (EMA settles to zero), the camera
// orbit is frozen, and the sticks report head deflections instead
// (up/left positive; sign-to-joint mapping lives in the game).
target = [0, 0, 0];
this.head.pitch = -ly;
this.head.yaw = -lx;
this.head.neckPitch = -ry;
this.head.roll = -rx;
this.axes.orbitX = 0;
this.axes.orbitY = 0;
} else {
// Left stick only: vertical = forward/back, horizontal = turn.
// (No strafe; the right stick doesn't drive movement.)
const up = -ly; // browser sticks report up as -1
target = [
up >= 0 ? up * limF : up * -limB,
0,
-lx * limA,
];
this.#zeroHead();
// Right stick: raw (deadzoned) orbit rate. Reported every frame -
// the downstream camera step needs the zeros too so a released
// stick coasts to a stop.
this.axes.orbitX = rx;
this.axes.orbitY = ry;
}
for (let i = 0; i < 3; i++) this.command[i] += PAD_ALPHA * (target[i] - this.command[i]);
// Sticks grab command authority on first input, release when back at
// rest (then the keyboard takes over again through the Controller's
// arbitration).
const stickInput = lx !== 0 || ly !== 0;
// arbitration). In head mode the sticks belong to the head, so they
// never claim the twist.
const stickInput = !this.headMode && (lx !== 0 || ly !== 0);
if (stickInput) this.#active = true;
else if (
this.#active &&
@@ -95,23 +142,21 @@ export class GamepadSource {
this.command.fill(0);
}
// Right stick: raw (deadzoned) orbit rate. Reported every frame - the
// downstream camera step needs the zeros too so a released stick
// coasts to a stop.
this.axes.orbitX = dz(gp.axes[2] ?? 0);
this.axes.orbitY = dz(gp.axes[3] ?? 0);
// R3 (right stick click): chase-cam toggle, gamepad twin of KeyC.
const r3 = !!gp.buttons[BTN_R3]?.pressed;
if (r3 && !prev.r3) this.onAction("chaseToggle");
prev.r3 = r3;
const a = !!gp.buttons[BTN_A]?.pressed;
if (a && !prev.a) this.onAction("groundPick");
prev.a = a;
const x = !!gp.buttons[BTN_X]?.pressed;
if (x && !prev.x) this.onAction("roll");
prev.x = x;
const y = !!gp.buttons[BTN_Y]?.pressed;
if (y && !prev.y) this.onAction("spawnBall");
if (y && !prev.y) this.onAction("headToggle");
prev.y = y;
const rb = !!gp.buttons[BTN_RB]?.pressed;
@@ -138,16 +183,37 @@ export class GamepadSource {
}
prev.dpadUp = dpadUp;
// Triggers drive the mouth (max of both); RT quacks on its
// Schmitt-triggered rising edge.
// Triggers drive the mouth (max of both, like the runtime). Physical
// Schmitt edges are detected first, then the actions are gated so the
// two triggers stay mutually exclusive: an RT edge squeezed while the
// wheee ride is open, or an LT edge while RT is engaged, is CONSUMED -
// releasing the blocker never retro-fires the suppressed action.
const rt = gp.buttons[BTN_RT]?.value ?? 0;
const lt = gp.buttons[BTN_LT]?.value ?? 0;
this.axes.jaw = Math.max(rt, lt);
if (this.#rtArmed && rt >= 0.35) {
this.onAction("quack");
this.#rtArmed = false;
} else if (!this.#rtArmed && rt < 0.2) {
this.#rtArmed = true;
const rtEdge = this.#rtArmed && rt >= 0.35;
if (rtEdge) this.#rtArmed = false;
else if (!this.#rtArmed && rt < 0.2) this.#rtArmed = true;
const ltEdge = !this.#ltDown && lt >= 0.3;
if (ltEdge) this.#ltDown = true;
else if (this.#ltDown && lt < 0.2) this.#ltDown = false;
// RT quack, blocked while the wheee ride is open.
if (rtEdge && !this.#ltRide) this.onAction("quack");
// LT wheee ride: open on the rising edge (runtime threshold ~0.3)
// unless RT is engaged; cut the instant LT drops below the low rail.
if (ltEdge && this.#rtArmed) {
this.#ltRide = true;
this.onAction("wheeeStart");
} else if (this.#ltRide && !this.#ltDown) {
this.#ltRide = false;
this.onAction("wheeeStop");
}
}
#zeroHead() {
this.head.neckPitch = 0;
this.head.pitch = 0;
this.head.yaw = 0;
this.head.roll = 0;
}
}
+1 -1
View File
@@ -14,8 +14,8 @@ const KEYMAP = {
// 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.
const ACTION_KEYS = {
KeyB: "spawnBall",
KeyC: "chaseToggle",
KeyG: "groundPick",
KeyM: "locoToggle",
KeyR: "roll",
KeyQ: "kickL",
+102 -32
View File
@@ -4,14 +4,13 @@
// local rotations driven by setJointAngles / setJoint.
import * as THREE from "three";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { STLLoader } from "three/addons/loaders/STLLoader.js";
import { mergeVertices, toCreasedNormals } from "three/addons/utils/BufferGeometryUtils.js";
// Cache-busting version appended to every STL request. python http.server
// sends no Cache-Control, so browsers apply heuristic caching keyed on
// Last-Modified and can keep serving stale mesh bytes even after the files
// change on disk. Bump this whenever the mesh files are regenerated.
export const MESH_VERSION = "8";
// Cache-busting version appended to the GLB / kinematics / leftover STL
// fetches. Bump whenever microduck.glb is regenerated.
export const MESH_VERSION = "11";
// Default model directory: the complete mjlab export (converted from
// robot_walk.xml by tools/mjcf_to_kinematics.py). robot/v1.5/ and
@@ -31,7 +30,7 @@ import { signed } from "./signed.js";
const HIDDEN_MESHES = new Set([]);
export async function loadKinematics(url) {
// Same cache-buster as the STLs: force-cache would otherwise keep
// Same cache-buster as the GLB: force-cache would otherwise keep
// serving a stale kinematics.json after the mesh list changes.
const r = await fetch(signed(`${url}?v=${MESH_VERSION}`), { cache: "force-cache" });
if (!r.ok) throw new Error(`kinematics fetch ${r.status}`);
@@ -45,6 +44,81 @@ export async function loadKinematics(url) {
return k;
}
// One GLB, named meshes matching kinematics geom.mesh (e.g. "left_shell.stl").
// Positions are already welded (same 1e-4 m hash as mergeVertices). STL
// facet normals are omitted on purpose: creased normals are rebuilt here.
const GLB_URL = `${MODEL_DIR}/microduck.glb`;
const CREASE = Math.PI / 5; // 36 deg
let glbGeomsPromise = null;
export function loadGlbGeometries() {
if (!glbGeomsPromise) {
glbGeomsPromise = new GLTFLoader()
.loadAsync(signed(`${GLB_URL}?v=${MESH_VERSION}`))
.then((gltf) => {
const map = new Map();
gltf.scene.traverse((o) => {
if (!o.isMesh || !o.geometry) return;
const name = o.userData.meshFile || o.name || o.geometry.name;
if (!name || map.has(name)) return;
const welded = o.geometry;
welded.deleteAttribute("normal");
// toCreasedNormals hashes on a 0.01-unit grid. Meshes are in
// metres, so scale a clone to mm (10 um grid) then back.
const scaled = welded.clone();
scaled.scale(1000, 1000, 1000);
const display = toCreasedNormals(scaled, CREASE);
display.scale(1e-3, 1e-3, 1e-3);
const entry = { display, welded };
map.set(name, entry);
if (o.name && o.name !== name) map.set(o.name, entry);
});
return map;
});
}
return glbGeomsPromise;
}
// MuJoCo's WASM compiler still wants binary STL in its VFS. Rebuild from
// the already-loaded GLB so the browser never re-downloads the mesh files.
export function geometryToBinaryStl(geometry) {
const pos = geometry.attributes.position;
const idx = geometry.index;
const triCount = (idx ? idx.count : pos.count) / 3;
const buf = new ArrayBuffer(84 + triCount * 50);
const view = new DataView(buf);
view.setUint32(80, triCount, true);
let off = 84;
const vx = (i) => {
const j = idx ? idx.getX(i) : i;
return [pos.getX(j), pos.getY(j), pos.getZ(j)];
};
for (let t = 0; t < triCount; t++) {
const a = vx(t * 3);
const b = vx(t * 3 + 1);
const c = vx(t * 3 + 2);
const nx = (b[1] - a[1]) * (c[2] - a[2]) - (b[2] - a[2]) * (c[1] - a[1]);
const ny = (b[2] - a[2]) * (c[0] - a[0]) - (b[0] - a[0]) * (c[2] - a[2]);
const nz = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
const len = Math.hypot(nx, ny, nz) || 1;
view.setFloat32(off, nx / len, true);
view.setFloat32(off + 4, ny / len, true);
view.setFloat32(off + 8, nz / len, true);
view.setFloat32(off + 12, a[0], true);
view.setFloat32(off + 16, a[1], true);
view.setFloat32(off + 20, a[2], true);
view.setFloat32(off + 24, b[0], true);
view.setFloat32(off + 28, b[1], true);
view.setFloat32(off + 32, b[2], true);
view.setFloat32(off + 36, c[0], true);
view.setFloat32(off + 40, c[1], true);
view.setFloat32(off + 44, c[2], true);
view.setUint16(off + 48, 0, true);
off += 50;
}
return buf;
}
// Materials are PBR (MeshStandardMaterial), same family as the Reachy
// mobile app's glb viewer. Optional silhouette outlines via three's
// OutlineEffect - see main.js.
@@ -61,25 +135,16 @@ export async function buildRig(k, opts = {}) {
const bodies = new Map();
const joints = new Map();
const loader = new STLLoader();
// STL files carry per-facet normals, which shade as a faceted mess.
// Weld vertices, then rebuild normals with a crease angle: curved
// surfaces smooth out, machined edges stay hard - the cel look needs
// both. Two scale/attribute pitfalls here:
// - mergeVertices hashes ALL attributes, so the per-facet STL normals
// must be dropped first or coincident vertices never merge.
// - toCreasedNormals groups vertices on a fixed 0.01-unit hash grid.
// Our meshes are in meters, so that grid is 1 cm: normals of vertices
// up to a centimeter apart get averaged together, which shades like a
// heavily decimated mesh. Scaling to mm makes the grid 10 um.
const CREASE = Math.PI / 5; // 36 deg
const meshCache = new Map();
const geomByName = await loadGlbGeometries();
// Roller-only meshes (tire, rim, ...) are not in the shared landing GLB.
const extraStlCache = new Map();
const loadMesh = (name) => {
if (!meshCache.has(name)) {
meshCache.set(
const entry = geomByName.get(name);
if (entry) return Promise.resolve(entry);
if (!extraStlCache.has(name)) {
extraStlCache.set(
name,
loader.loadAsync(signed(`${k.mesh_dir}/${name}?v=${MESH_VERSION}`)).then((raw) => {
new STLLoader().loadAsync(signed(`${k.mesh_dir}/${name}?v=${MESH_VERSION}`)).then((raw) => {
raw.deleteAttribute("normal");
const welded = mergeVertices(raw, 1e-4);
welded.scale(1000, 1000, 1000);
@@ -90,7 +155,7 @@ export async function buildRig(k, opts = {}) {
}),
);
}
return meshCache.get(name);
return extraStlCache.get(name);
};
for (const b of k.bodies) {
@@ -215,13 +280,19 @@ export async function buildRig(k, opts = {}) {
// The mjlab model has no passive jaw joints: jaw.stl / jaw_soft.stl are
// rigid geoms of the head body (named "jaw_soft" in the MJCF, it carries
// the head_roll joint). The quack re-creates the hinge in JS: both jaw
// meshes are reparented into a "jaw_pivot" group
// whose origin sits on the rear top edge of their combined bounding box
// (the physical hinge line), and setJawOpen rotates that pivot about the
// robot's left-right axis so the beak tip swings down.
// meshes are reparented into a "jaw_pivot" group whose origin sits on the
// physical hinge, and setJawOpen rotates that pivot about the robot's
// left-right axis so the beak tip swings down.
const JAW_MESH_NAMES = new Set(["jaw.stl", "jaw_soft.stl"]);
export const JAW_MAX_OPEN = 0.32; // rad at openness 1
// The physical hinge: jaw.stl ends in a circular boss (8 mm ring with the
// axle hole at its center) on each side, hole axis along mesh-local X (the
// robot's left-right). Circle fitted offline on the STL's hole-wall
// vertices (RANSAC, 68 inliers, < 0.15 mm spread); x = 0 sits mid-way
// between the two bosses, on the hinge line.
const JAW_HINGE_LOCAL = new THREE.Vector3(0, 0.00004, 0.0075);
function setupJawPivot(rig) {
const meshes = [];
rig.root.traverse((o) => {
@@ -232,9 +303,8 @@ function setupJawPivot(rig) {
// The placer is still untransformed right after buildRig, so world
// coords == placer coords here: robot forward is +X, up is +Y.
rig.placer.updateWorldMatrix(true, true);
const box = new THREE.Box3();
for (const m of meshes) box.expandByObject(m);
const hingeW = new THREE.Vector3(box.min.x, box.max.y, (box.min.z + box.max.z) / 2);
const jawMesh = meshes.find((m) => m.userData.meshName === "jaw.stl") ?? meshes[0];
const hingeW = jawMesh.localToWorld(JAW_HINGE_LOCAL.clone());
// +angle about -Z rotates the +X beak tip toward -Y (down).
const axisW = new THREE.Vector3(0, 0, -1);
const bodyQuatInv = body.getWorldQuaternion(new THREE.Quaternion()).invert();
@@ -280,7 +350,7 @@ export function applyPose(rig, pose) {
for (const [name, ang] of Object.entries(pose)) setJoint(rig, name, ang);
}
// Deep-clone a built rig without re-parsing the STL files: Object3D.clone
// Deep-clone a built rig without re-parsing the GLB: Object3D.clone
// shares geometry and materials, so N clones cost almost nothing on top of
// the first buildRig. The bodies/joints maps are rebuilt by looking up the
// cloned nodes by name (body names are unique in the MJCF).
+391 -117
View File
@@ -30,15 +30,17 @@ import {
ACTION_SCALE, TIMESTEP, DECIMATION, CTRL_DT,
VEL_FWD, VEL_BACK, VEL_ANG, RVEL_FWD, RVEL_BACK, RVEL_ANG,
CROUCH_PERIOD_S, CROUCH_END_PHASE,
GROUND_PICK_PERIOD_S, GROUND_PICK_END_PHASE,
BALL_RADIUS, BALL_PARK_POS, ARENA_HALF, SPAWN_X, SPAWN_Y,
ARCADE_H, ARCADE_W, ARCADE_D, ARCADE_GAP, ARCADE_WALL_GAP,
RELIEF_BUMPS, RELIEF_HMAX, RELIEF_GRID, RELIEF_SINK, RELIEF_RATE,
} from "./constants.js";
import { loadProps, propColliders } from "./props.js";
import {
buildRig, cloneRig, loadKinematics, setJoint, setJawOpen, MODEL_DIR, MESH_VERSION,
loadGlbGeometries, geometryToBinaryStl,
} from "./duck.js";
import {
VARIANTS, VARIANT_NAMES, materialHookFor, DEFAULT_VARIANT, applyVariant, specToHex,
VARIANTS, materialHookFor, DEFAULT_VARIANT, applyVariant,
} from "./variants.js";
import { Controller } from "./controls/controller.js";
import { KeyboardSource } from "./controls/keyboard.js";
@@ -59,19 +61,19 @@ import { useGame, gameApi, bootLine, bootNote, bootHalt } from "../store.js";
const MUJOCO_URL = "https://cdn.jsdelivr.net/npm/@mujoco/mujoco@3.11.0/mujoco.js";
const ORT_URL = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.27.0/dist/ort.min.mjs";
// Colour dot shown per variant in the quickbar. Variants can force theirs
// with a `swatch` spec (purple does: its head is warm gray but its
// identity is the purple accents).
const SWATCH_SLOT = { classic: "feet", charcoal: "headDome", purple: "feet", blue: "facePlate" };
export const VARIANT_SWATCHES = Object.fromEntries(
VARIANT_NAMES.map((name) => {
const v = VARIANTS[name];
return [name, specToHex(v.swatch ?? v[SWATCH_SLOT[name] ?? "bodyShell"])];
}),
);
let bootStarted = false;
// HMR teardown for the ghost session: invalidating this module (directly or
// via an edit to ghosts.js) used to stack a live 15 Hz broadcast interval
// plus a ghost room per reload (the historical "stale module" bug class).
const liveGhostSessions = new Set();
if (import.meta.hot) {
import.meta.hot.dispose(() => {
for (const g of liveGhostSessions) g.destroy();
liveGhostSessions.clear();
});
}
export async function bootGame({ scene, camera, renderer }) {
if (bootStarted) return;
bootStarted = true;
@@ -176,17 +178,15 @@ async function boot({ scene, camera, renderer }) {
el("geom", { name: w.name, type: "box", pos: w.pos, size: w.size }),
);
}
// Arcade cabinet row: one static box covering all three cabinets so
// the duck and ball can't clip through them. The row sits against the
// front (+X) wall, centered on y = 0 (three.js z = 0), axis-aligned.
const rowHalfW = (3 * ARCADE_W + 2 * ARCADE_GAP) / 2;
doc.querySelector("worldbody").appendChild(
el("geom", {
name: "arcade_row", type: "box",
pos: `${ARENA_HALF - ARCADE_WALL_GAP - ARCADE_D / 2} 0 ${ARCADE_H / 2}`,
size: `${ARCADE_D / 2} ${rowHalfW} ${ARCADE_H / 2}`,
}),
);
// Prop library colliders: one static box per enabled prop
// (declared in props.js next to the visual placement, optionally
// yawed via euler to match off-axis staging) so the duck and ball
// can't clip through the dressing.
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;
doc.querySelector("worldbody").appendChild(el("geom", attrs));
}
// Kickable ball: a light free sphere (beach-ball feel). MuJoCo has no
// restitution parameter - the bounce comes from solref damping < 1, and
// the rolling-friction term makes it come to rest. Appended AFTER the
@@ -251,16 +251,21 @@ async function boot({ scene, camera, renderer }) {
const doneMeshes = bootLine("MESH ASSETS");
const vfs = new mujoco.MjVFS();
// One shared VFS for both variants; already-loaded files are skipped so
// the roller lazy-load only fetches its 5 new meshes.
// the roller lazy-load only fetches its leftover meshes.
const vfsFiles = new Set();
async function addMeshesToVfs(files) {
const geoms = await loadGlbGeometries();
await Promise.all(
files.map(async (f) => {
if (vfsFiles.has(f)) return;
vfsFiles.add(f);
// Same cache-busted URL as duck.js so the browser reuses the render
// meshes instead of downloading the collision subset a second time.
const buf = await (await fetch(signed(`${MODEL_DIR}/meshes/${f}?v=${MESH_VERSION}`), { cache: "force-cache" })).arrayBuffer();
// Legs/body meshes live in the visual GLB: rebuild binary STL in
// memory so MuJoCo never triggers a second download. Roller-only
// files (not in the GLB) still fetch as STL.
const entry = geoms.get(f);
const buf = entry
? geometryToBinaryStl(entry.welded)
: await (await fetch(signed(`${MODEL_DIR}/meshes/${f}?v=${MESH_VERSION}`), { cache: "force-cache" })).arrayBuffer();
// meshdir="assets" in the MJCF, so the compiler looks up "assets/<f>".
vfs.addBuffer(`assets/${f}`, new Uint8Array(buf));
}),
@@ -290,30 +295,33 @@ async function boot({ scene, camera, renderer }) {
throw err;
}
})();
// Boot policies with a live [n/5] counter on the BIOS line.
// Boot policies with a live [n/7] counter on the BIOS line.
const donePolicies = bootLine("LOADING POLICIES");
const sessionOpts = { executionProviders: ["wasm"] };
let policiesLoaded = 0;
const bootPolicy = (url) =>
ort.InferenceSession.create(signed(url), sessionOpts).then((s) => {
donePolicies.progress(`${++policiesLoaded}/5`);
donePolicies.progress(`${++policiesLoaded}/7`);
return s;
});
try {
[sessions.walk, sessions.sitstand, sessions.roll, sessions.kickL, sessions.kickR] =
[sessions.walk, sessions.sitstand, sessions.roll, sessions.kickL, sessions.kickR,
sessions.groundpick, sessions.stand] =
await Promise.all([
bootPolicy(POLICIES.walk),
bootPolicy(POLICIES.sitstand),
bootPolicy(POLICIES.roll),
bootPolicy(POLICIES.kickL),
bootPolicy(POLICIES.kickR),
bootPolicy(POLICIES.groundpick),
bootPolicy(POLICIES.stand),
]);
} catch (err) {
donePolicies("FAILED");
bootHalt(err?.message || String(err));
throw err;
}
donePolicies("5/5");
donePolicies("7/7");
const doneCompile = bootLine("COMPILING PHYSICS");
let model, data;
@@ -379,23 +387,44 @@ async function boot({ scene, camera, renderer }) {
let ball = null;
let stickers = null; // comic popups, currently disabled
let mode = "walk"; // "walk" | "sitstand" | "roll" | "kickL" | "kickR" | "crouch"
let mode = "walk"; // "walk" | "sitstand" | "roll" | "kickL" | "kickR" | "crouch" | "groundpick"
let sitFlag = 0;
const isKick = () => mode === "kickL" || mode === "kickR";
// HEAD mode (runtime-faithful, pad Y): locomotion is zeroed and both
// sticks drive the head command slots cmd[3..6] = [neck_pitch,
// head_pitch, head_yaw, head_roll]. Targets are stick * HEAD_MAX,
// EMA-smoothed at 50 Hz in buildObs like the runtime (alpha 0.2).
// Offsets PERSIST when leaving head mode; only a sim reset zeroes them.
let headMode = false;
const HEAD_MAX = 2.5; // rad at full deflection (runtime head_max)
const HEAD_ALPHA = 0.2;
// Stick-to-joint polarity (deflections come in up/left = +1), tuned
// visually in the sim: cmd + means UP for neck_pitch but DOWN for
// head_pitch, LEFT for head_yaw but RIGHT-tilt for head_roll - hence
// the mixed signs, so stick up = look up, stick left = turn/tilt left.
// Order matches cmd[3..6] = [neck_pitch, head_pitch, head_yaw, head_roll].
const HEAD_SIGNS = new Float32Array([1, -1, 1, -1]);
const headTarget = new Float32Array(4);
const headSmooth = new Float32Array(4);
// Local-only kickable ball: false while parked at the keyframe spot
// (mesh hidden), true once popped in front of the duck.
let ballActive = false;
// The twist the policy actually receives. Mid-roll every movement input
// is ignored (zero twist) until the roll hands back to walk on its own.
// HEAD mode also zeroes it: the runtime stops the robot while the
// sticks drive the head.
const ZERO_CMD = new Float32Array(3);
function effectiveCmd() {
if (inputLocked || mode === "roll" || mode === "crouch" || isKick() || postKickLock > 0)
if (inputLocked || headMode || mode === "roll" || mode === "crouch" ||
mode === "groundpick" || isKick() || postKickLock > 0 || recovery)
return ZERO_CMD;
return controller.getCommand();
}
let rollRun = null;
let crouchRun = null;
let pickRun = null;
let kickRun = null;
let KICK_STEPS = 25;
// Post-kick grace: keep commands zeroed for a beat after the kick window
@@ -407,6 +436,23 @@ async function boot({ scene, camera, renderer }) {
let sitTimer = null;
let standTimer = null;
let fallenSince = null;
// ── Automatic fall recovery (legs walk mode only) ────────────────────
// Mirrors the runtime's --fall-detect state machine (main.rs ~3658):
// a debounced tip (gz > -0.5 for 0.2 s) freezes ctrl on the current
// pose for a short settle (the runtime goes limp), then hands the duck
// to the stand policy with all commands zeroed until it's been upright
// (gz < -0.85) for a full second. If it can't get up within 6 s, fall
// back to the old kill: resetSim + materialization. Rollers keep the
// plain kill (the runtime declares fall-detect roller-incompatible),
// and so do sit/roll/kick/crouch/groundpick and the entrance lock.
const FALL_DEBOUNCE_STEPS = 10; // 0.2 s of gz > -0.5 before triggering
const FALL_SETTLE_STEPS = 15; // 0.3 s ctrl freeze once triggered
const RECOVER_UPRIGHT_STEPS = 50; // 1 s of gz < -0.85 to declare recovered
const RECOVER_GIVEUP_STEPS = 300; // 6 s of stand attempts before reset
let recovery = null; // null | { state: "fallen"|"recovering", steps, uprightSteps }
let fallDebounce = 0;
function clearModeTimers() {
clearTimeout(sitTimer); sitTimer = null;
clearTimeout(standTimer); standTimer = null;
@@ -418,9 +464,17 @@ async function boot({ scene, camera, renderer }) {
rollRun = null;
kickRun = null;
crouchRun = null;
pickRun = null;
postKickLock = 0;
fallenSince = null;
recovery = null;
fallDebounce = 0;
mode = "walk";
// Head mode exits and its offsets DO reset here (the one place).
headMode = false;
padSource.headMode = false;
headTarget.fill(0);
headSmooth.fill(0);
mujoco.mj_resetDataKeyframe(model, data, standKeyId);
mujoco.mj_forward(model, data);
lastAction.fill(0);
@@ -513,28 +567,58 @@ async function boot({ scene, camera, renderer }) {
const a = 2 * Math.PI * crouchRun.phase;
cmd[0] = Math.cos(a);
cmd[1] = Math.sin(a);
} else if (mode === "groundpick" && pickRun) {
const a = 2 * Math.PI * pickRun.phase;
cmd[0] = Math.cos(a);
cmd[1] = Math.sin(a);
} else {
const c = effectiveCmd();
cmd[0] = c[0]; cmd[1] = c[1]; cmd[2] = c[2];
}
// Head slots cmd[3..6]: EMA toward the stick targets at 50 Hz (this
// runs once per control step), exactly the runtime's smoothing. Kept
// filled outside head mode too - offsets persist like on the robot.
for (let h = 0; h < 4; h++) headSmooth[h] += HEAD_ALPHA * (headTarget[h] - headSmooth[h]);
// Ground pick parity: the runtime zero-pads the head (and body) slots
// for its obs (mjlab's zero_command_padding), so persisted head
// offsets must not leak into the pick policy's command buffer. Fall
// recovery zeroes them too: the stand policy gets an all-zero command.
const gpZero = mode === "groundpick" || recovery !== null;
cmd[3] = gpZero ? 0 : headSmooth[0]; cmd[4] = gpZero ? 0 : headSmooth[1];
cmd[5] = gpZero ? 0 : headSmooth[2]; cmd[6] = gpZero ? 0 : headSmooth[3];
for (let c = 0; c < CMD_SIZE; c++) obs[i++] = cmd[c];
return obs;
}
// The ONNX session for the current mode: in the roller variant the main
// velocity mode runs the drive (skating) policy instead of the walker.
const activeSession = () =>
sessions[loco === "rollers" && mode === "walk" ? "drive" : mode];
// velocity mode runs the drive (skating) policy instead of the walker,
// and the fall-recovery state machine overrides everything with the
// get-up policy while it owns the duck.
const activeSession = () => {
if (recovery?.state === "recovering") return sessions.stand;
return sessions[loco === "rollers" && mode === "walk" ? "drive" : mode];
};
// ── Control loop (50 Hz, async because ONNX inference is async) ──────
let ctrlHz = 0;
// Dead pose: walk/sitstand have no get-up skill, so a kill here is just
// a resetSim. "fallen" = trunk tilted past ~60 deg or sunk below the
// Fresh projected-gravity z straight from the trunk pose (buildObs is
// skipped during the fall-recovery settle, so obs[5] can go stale).
function projGravZ() {
const xq = data.body(trunkId).xquat; // [w, x, y, z]
_q.set(xq[1], xq[2], xq[3], xq[0]).conjugate();
_g.set(0, 0, -1).applyQuaternion(_q);
return _g.z;
}
// Dead pose: "fallen" = trunk tilted past ~60 deg or sunk below the
// floor. NaN/Inf is a solver explosion: no grace, reset on the spot.
// In legs walk mode a debounced fall now goes to the recovery state
// machine instead of the kill; everywhere else (rollers, sit, one-shots,
// entrance lock) the old grace-then-reset behavior stands.
function poseIsDead() {
const z = data.qpos[2];
const gz = obs[5]; // projected gravity z, from the last obs
const gz = projGravZ();
if (!Number.isFinite(z) || !Number.isFinite(gz)) return "exploded";
if (gz > -0.5 || z < 0.02) return "fallen";
return null;
@@ -542,23 +626,62 @@ async function boot({ scene, camera, renderer }) {
async function controlStep() {
driveRelief(CTRL_DT); // kinematic terrain, written before the physics steps
const feeds = { obs: new ort.Tensor("float32", buildObs(), [1, OBS_SIZE]) };
const out = await activeSession().run(feeds);
const act = out.actions.data;
lastAction.set(act);
const ctrl = data.ctrl;
for (let j = 0; j < NUM_JOINTS; j++) ctrl[j] = DEFAULT_POSE[j] + act[j] * ACTION_SCALE;
// Settle phase: ctrl frozen on the pose held at the fall (approximates
// the runtime's limp beat), physics keeps stepping, no inference.
if (recovery?.state !== "fallen") {
const feeds = { obs: new ort.Tensor("float32", buildObs(), [1, OBS_SIZE]) };
const out = await activeSession().run(feeds);
const act = out.actions.data;
lastAction.set(act);
const ctrl = data.ctrl;
for (let j = 0; j < NUM_JOINTS; j++) ctrl[j] = DEFAULT_POSE[j] + act[j] * ACTION_SCALE;
}
for (let s = 0; s < DECIMATION; s++) mujoco.mj_step(model, data);
const death = poseIsDead();
if (death === "exploded") {
resetSim();
} else if (recovery) {
// Recovery state machine owns the duck: settle -> stand policy ->
// hysteresis exit (upright for a full second) or 6 s give-up reset.
recovery.steps++;
if (recovery.state === "fallen") {
if (recovery.steps >= FALL_SETTLE_STEPS) {
recovery = { state: "recovering", steps: 0, uprightSteps: 0 };
lastAction.fill(0);
syncButtons();
}
} else {
recovery.uprightSteps = projGravZ() < -0.85 ? recovery.uprightSteps + 1 : 0;
if (recovery.uprightSteps >= RECOVER_UPRIGHT_STEPS) {
recovery = null;
mode = "walk";
lastAction.fill(0);
syncButtons();
} else if (recovery.steps >= RECOVER_GIVEUP_STEPS) {
resetSim();
}
}
} else if (death === "fallen") {
const now = performance.now();
const graceMs = mode === "roll" ? 5000 : 1000;
fallenSince ??= now;
if (now - fallenSince > graceMs) resetSim();
const recoverable = loco === "legs" && mode === "walk" &&
!inputLocked && postKickLock === 0 && !standTimer;
if (recoverable) {
fallenSince = null;
if (++fallDebounce >= FALL_DEBOUNCE_STEPS) {
fallDebounce = 0;
exitHeadMode();
recovery = { state: "fallen", steps: 0 };
syncButtons();
}
} else {
fallDebounce = 0;
const now = performance.now();
const graceMs = mode === "roll" ? 5000 : 1000;
fallenSince ??= now;
if (now - fallenSince > graceMs) resetSim();
}
} else {
fallDebounce = 0;
fallenSince = null;
}
@@ -597,6 +720,17 @@ async function boot({ scene, camera, renderer }) {
}
}
// Ground-pick one-shot: same phase-clock pattern as the crouch, ending
// at the runtime's cycle end (phase 0.7 of a 4 s period, ~2.8 s).
if (mode === "groundpick" && pickRun) {
pickRun.phase += CTRL_DT / GROUND_PICK_PERIOD_S;
if (pickRun.phase >= GROUND_PICK_END_PHASE) {
pickRun = null;
mode = "walk";
syncButtons();
}
}
// One-shot roll, step-counted like the robot runtime: hand back to
// walking once the trunk has tipped over and is upright again, or
// after a hard window if the roll never initiated.
@@ -626,7 +760,7 @@ async function boot({ scene, camera, renderer }) {
// sinking the terrain = ramping one scalar that scales the hfield
// z-size and the shader uniform together, so physics and visuals stay
// the same surface at every moment of the transition. Trigger for now:
// window.rl.setRelief(bool) or the T key (prototype - no UI yet).
// window.rl.setRelief(bool) (prototype - no UI yet).
let reliefOn = false;
let reliefScale = 0;
let reliefGridMat = null; // assigned at scene wiring (grid built below)
@@ -664,11 +798,6 @@ async function boot({ scene, camera, renderer }) {
model.hfield_size[2] = Math.max(reliefScale * RELIEF_HMAX, 1e-4);
if (reliefGridMat) reliefGridMat.uniforms.uTopoScale.value = reliefScale;
}
// Prototype trigger (no UI yet): T toggles the terrain.
window.addEventListener("keydown", (e) => {
if (e.code === "KeyT" && !e.repeat) reliefOn = !reliefOn;
});
let running = true;
(async function controlLoop() {
let next = performance.now();
@@ -751,7 +880,8 @@ async function boot({ scene, camera, renderer }) {
async function setLoco(name, { force = false } = {}) {
if (name !== "legs" && name !== "rollers") return;
if (loco === name || locoSwitching) return;
if (!force && (inputLocked || rollRun || kickRun || crouchRun || standTimer)) return;
if (!force && (inputLocked || rollRun || kickRun || crouchRun || pickRun ||
standTimer || recovery)) return;
locoSwitching = true;
setStore({ locoSwitching: true });
try {
@@ -813,56 +943,14 @@ async function boot({ scene, camera, renderer }) {
THREE, scene, camera, renderer, fxModule: fx, mesh: ballMesh, group: ballGroup,
});
// ── Arcade cabinets (wall dressing + static collision box) ──────────
// assets/props/arcade.glb carries two meshes: the ~9k-tri render mesh
// and a 500-tri "arcade_wire" stand-in used only by the hologram pass
// (same fxWireGeometry escape hatch as the ball). Three clones line up
// against the front (+X) wall - the one the duck faces at spawn - backs
// to the wall, screens toward the player; each materializes with the
// duck's ceremony, staggered, and replays on every respawn.
// Physics-side, buildPhysicsXml plants one static box covering the
// whole row (constants ARCADE_*).
let arcadeGroups = null;
try {
const gltf = await new GLTFLoader().loadAsync(
signed(`./assets/props/arcade.glb?v=1`),
);
const proto = gltf.scene;
const wire = proto.getObjectByName("arcade_wire");
wire.removeFromParent();
const box3 = new THREE.Box3().setFromObject(proto);
const scale = ARCADE_H / (box3.max.y - box3.min.y);
proto.scale.setScalar(scale);
proto.position.y = -box3.min.y * scale;
arcadeGroups = [];
for (let i = 0; i < 3; i++) {
// clone(true) shares geometry/materials; userData doesn't survive
// Object3D.copy (JSON round-trip), so tag the wire geometry after.
const cab = proto.clone(true);
cab.traverse((o) => {
if (o.isMesh) o.userData.fxWireGeometry = wire.geometry;
});
const group = new THREE.Group();
group.add(cab);
// Row centered on the front wall's middle, one cabinet-width apart,
// back faces almost touching the wall. The GLB fronts +Z; the row
// must front -X (toward the spawn), hence the -90 deg yaw.
group.position.set(
ARENA_HALF - ARCADE_D / 2 - ARCADE_WALL_GAP,
0,
(i - 1) * (ARCADE_W + ARCADE_GAP),
);
group.rotation.y = -Math.PI / 2;
scene.add(group);
arcadeGroups.push(group);
const cabFx = fx.createWireframeFx();
cabFx.init({ THREE, scene, root: group, camera, renderer, hidden: true });
ceremony.addPropFx(cabFx, 0.25 + i * 0.12);
}
} catch (err) {
// Decorative only: a missing/broken GLB must never halt the boot.
console.warn("[game] arcade props disabled:", err);
}
// ── Prop library (wall/corner dressing + entrance FX) ────────────────
// Every enabled def in props.js: loaded, real-size scaled, floor
// snapped, wireframe-materialized with the ceremony (staggered after
// the duck's scan cue). Physics-side, buildPhysicsXml planted one
// static box per declared collider.
const propGroups = await loadProps({
THREE, GLTFLoader, signed, scene, camera, renderer, fx, ceremony,
});
// ── Camera: orbit controls + chase cam + reset glide ─────────────────
const controls = new OrbitControls(camera, renderer.domElement);
@@ -912,6 +1000,10 @@ async function boot({ scene, camera, renderer }) {
if (t >= 1) camResetT0 = null;
return;
}
// Head mode: the camera freezes where it is. It keeps looking at the
// duck for free - syncRig translates camera and target by the same
// delta, and the duck isn't walking anyway (twist zeroed).
if (headMode) return;
if (!chaseCam) return;
const qpos = data.qpos;
let rawYaw;
@@ -1067,15 +1159,116 @@ async function boot({ scene, camera, renderer }) {
playChirp();
stickers?.pop("quack");
};
// Ground-pick jaw: on the robot the pick policy drives the mouth itself
// (mouth is part of its action space); the sim's ONNX exports have no
// mouth channel (all heads are 14 actions), so the peck is re-created
// here on the same phase clock. Keyed to the measured cycle: the beak
// reaches the ground ~phase 0.16-0.42 and the head scoops back up
// 0.40-0.50 - open on approach, snap shut on the scoop (the grab).
const PICK_JAW_KEYS = [[0.10, 0], [0.20, 1], [0.40, 1], [0.50, 0]];
function pickJawNow() {
const phase = mode === "groundpick" ? pickRun?.phase : null;
if (phase == null) return 0;
const K = PICK_JAW_KEYS;
if (phase <= K[0][0] || phase >= K[K.length - 1][0]) return 0;
for (let i = 1; i < K.length; i++) {
if (phase > K[i][0]) continue;
const [p0, v0] = K[i - 1];
const [p1, v1] = K[i];
const t = (phase - p0) / (p1 - p0);
return v0 + (v1 - v0) * (1 - Math.cos(Math.PI * t)) / 2; // eased
}
return 0;
}
function jawOpenNow() {
const t = (performance.now() - quackAt) / QUACK_MS;
const flap = t >= 0 && t < 1 ? Math.sin(Math.PI * t) : 0;
return Math.max(flap, padJaw);
// Runtime mouth-mode rule (main.rs: motor_targets[MOUTH] += offset):
// the policy's jaw is the BASE and the trigger/quack opening is an
// additive offset on top, clamped - it never fights the pick motion.
return Math.min(1, pickJawNow() + Math.max(flap, padJaw));
}
function syncJaw() {
setJawOpen(rig, jawOpenNow());
}
// ── Wheee: LT-held looping ride (runtime behavior) ────────────────────
// start → loop (repeated while the trigger is held) → end, from the same
// per-colourway voice bank as the chirps. Web Audio instead of <audio>:
// the loop segment is crossfade-authored to wrap sample-exactly and the
// start→loop handoff needs sample-accurate scheduling - HTMLAudio's loop
// is neither gap-free nor schedulable.
const WHEEE_TAKES = "ab";
let wheeeCtx = null;
const wheeeBufCache = new Map();
let wheeeRide = null; // current ride, null while the trigger is up
function wheeeBuffer(url) {
let p = wheeeBufCache.get(url);
if (!p) {
p = fetch(url)
.then((r) => r.arrayBuffer())
.then((ab) => wheeeCtx.decodeAudioData(ab));
wheeeBufCache.set(url, p);
}
return p;
}
async function startWheee() {
stopWheee({ silent: true }); // a re-press replaces the current ride
wheeeCtx ??= new (window.AudioContext ?? window.webkitAudioContext)();
if (wheeeCtx.state === "suspended") wheeeCtx.resume().catch(() => {});
const bank = VOICE_BANK[currentVariant] ?? "duck1";
const take = WHEEE_TAKES[(Math.random() * WHEEE_TAKES.length) | 0];
const ride = { bank, take, startSrc: null, loopSrc: null, gain: null };
wheeeRide = ride;
const seg = (name) =>
wheeeBuffer(signed(`./assets/voices/${bank}/wheee_${name}_${take}.wav`));
let startBuf, loopBuf;
try {
// The end segment is fetched too so it's decoded by release time.
[startBuf, loopBuf] = await Promise.all([seg("start"), seg("loop"), seg("end")]);
} catch {
return; // asset missing / fetch failed: ride silently never starts
}
if (wheeeRide !== ride) return; // released (or replaced) during decode
const gain = wheeeCtx.createGain();
gain.gain.value = 0.7;
gain.connect(wheeeCtx.destination);
const t0 = wheeeCtx.currentTime + 0.02;
const startSrc = wheeeCtx.createBufferSource();
startSrc.buffer = startBuf;
startSrc.connect(gain);
startSrc.start(t0);
const loopSrc = wheeeCtx.createBufferSource();
loopSrc.buffer = loopBuf;
loopSrc.loop = true;
loopSrc.connect(gain);
loopSrc.start(t0 + startBuf.duration);
Object.assign(ride, { startSrc, loopSrc, gain });
}
function stopWheee({ silent = false } = {}) {
const ride = wheeeRide;
if (!ride) return;
wheeeRide = null;
try { ride.startSrc?.stop(); } catch { /* already ended */ }
try { ride.loopSrc?.stop(); } catch { /* already ended */ }
ride.gain?.disconnect();
// No tail if nothing was heard (released mid-decode) or on replace.
if (silent || !ride.gain) return;
// The end segment has its own onset, playable from any loop point.
wheeeBuffer(signed(`./assets/voices/${ride.bank}/wheee_end_${ride.take}.wav`))
.then((buf) => {
const gain = wheeeCtx.createGain();
gain.gain.value = 0.7;
gain.connect(wheeeCtx.destination);
const src = wheeeCtx.createBufferSource();
src.buffer = buf;
src.connect(gain);
src.onended = () => gain.disconnect();
src.start();
})
.catch(() => {});
}
// ── Telemetry (throttled into the store) ─────────────────────────────
// FPS EMA is per-frame; the store write is 4 Hz so React re-renders
// stay far away from frame rate. Odometer integrates horizontal trunk
@@ -1151,9 +1344,21 @@ async function boot({ scene, camera, renderer }) {
touchWasConnected = touchSource.connected;
setStore({ touchMode: touchSource.connected });
}
// Head mode: sticks steer the head targets (stick * HEAD_MAX, signed
// per joint); the EMA toward them runs in buildObs at 50 Hz. Without
// a pad the targets stay put (and are debug-writable via window.rl).
if (headMode && padSource.connected) {
const h = padSource.head;
headTarget[0] = HEAD_SIGNS[0] * h.neckPitch * HEAD_MAX;
headTarget[1] = HEAD_SIGNS[1] * h.pitch * HEAD_MAX;
headTarget[2] = HEAD_SIGNS[2] * h.yaw * HEAD_MAX;
headTarget[3] = HEAD_SIGNS[3] * h.roll * HEAD_MAX;
}
// Camera orbit runs every frame while a pad is present (the coasting
// needs the zero-deflection frames too); without a pad, park the state.
if (padSource.connected) {
// needs the zero-deflection frames too); without a pad, park the
// state. Head mode parks it too: the right stick belongs to the head
// and the camera must freeze in place (no leftover coasting).
if (padSource.connected && !headMode) {
padOrbitStep(controller.getAxes().orbitX, controller.getAxes().orbitY, dt);
} else {
padOrbitLive = false;
@@ -1180,9 +1385,11 @@ async function boot({ scene, camera, renderer }) {
controller.on("reset", () => resetSim());
controller.on("spawnBall", () => spawnBall());
controller.on("headToggle", () => toggleHeadMode());
controller.on("chaseToggle", () => { chaseCam = !chaseCam; });
controller.on("locoToggle", () => toggleLoco());
controller.on("roll", ({ source }) => triggerRoll(srcTag(source)));
controller.on("groundPick", ({ source }) => triggerGroundPick(srcTag(source)));
controller.on("kickL", ({ source }) => triggerKick("left", srcTag(source)));
controller.on("kickR", ({ source }) => triggerKick("right", srcTag(source)));
controller.on("alternateKick", ({ source }) => {
@@ -1201,16 +1408,45 @@ async function boot({ scene, camera, renderer }) {
if (mode !== "walk" && mode !== "roll" && mode !== "crouch") setMode("walk");
});
controller.on("quack", () => quackLoud());
controller.on("wheeeStart", () => startWheee());
controller.on("wheeeStop", () => stopWheee());
// Leaving head mode keeps the head offsets (runtime behavior): only
// resetSim zeroes headTarget/headSmooth.
function exitHeadMode() {
if (!headMode) return;
headMode = false;
padSource.headMode = false;
syncButtons();
}
function toggleHeadMode() {
if (headMode) return exitHeadMode();
// Enterable from walk or sit only - never during one-shots (roll /
// kick / crouch), the post-kick grace, a stand-up hand-back, a fall
// recovery, or while the entrance/respawn lock holds the inputs.
if (inputLocked || (mode !== "walk" && mode !== "sitstand") || postKickLock > 0 ||
standTimer || recovery)
return;
headMode = true;
padSource.headMode = true;
syncButtons();
}
function setMode(next, { force = false } = {}) {
if (!force && inputLocked) return;
// No policy switching mid-roll or mid-kick: both end on their own and
// return to walk - switching now would floor the duck.
if ((mode === "roll" && rollRun) || (isKick() && kickRun) || (mode === "crouch" && crouchRun)) return;
// return to walk - switching now would floor the duck. Same while the
// fall-recovery state machine owns the duck.
if (recovery) return;
if ((mode === "roll" && rollRun) || (isKick() && kickRun) ||
(mode === "crouch" && crouchRun) || (mode === "groundpick" && pickRun)) return;
if (next === "sit" && loco === "rollers") return;
exitHeadMode(); // posture changes exit head mode (offsets kept)
clearModeTimers();
rollRun = null;
crouchRun = null;
pickRun = null;
if (next !== "sit") {
// Leaving a sit: let the sitstand policy stand the duck back up first.
if (mode === "sitstand" && sitFlag === 1) {
@@ -1246,7 +1482,8 @@ async function boot({ scene, camera, renderer }) {
// policy switches, and the roll initiates more reliably mid-gait.
function triggerRoll(source = "kb") {
if (loco === "rollers") return triggerCrouch(source);
if (inputLocked || mode !== "walk" || standTimer) return;
if (inputLocked || mode !== "walk" || standTimer || recovery) return;
exitHeadMode();
clearModeTimers();
mode = "roll";
sitFlag = 0;
@@ -1257,7 +1494,8 @@ async function boot({ scene, camera, renderer }) {
// Roller-only one-shot: crouch, glide low, stand back up (phase-driven).
function triggerCrouch(source = "kb") {
if (inputLocked || mode !== "walk" || locoSwitching) return;
if (inputLocked || mode !== "walk" || locoSwitching || recovery) return;
exitHeadMode();
clearModeTimers();
mode = "crouch";
crouchRun = { phase: 0 };
@@ -1265,12 +1503,28 @@ async function boot({ scene, camera, renderer }) {
stickers?.pop("roll");
}
// One-shot ground pick (runtime A button): peck the ground and stand
// back up, phase-driven like the roller crouch (same cos/sin encoding in
// the command vel slots). Legs-only, from walk, and never during another
// one-shot / a stand-up hand-back / the entrance lock.
function triggerGroundPick(source = "kb") {
if (loco !== "legs") return;
if (inputLocked || mode !== "walk" || standTimer || recovery) return;
exitHeadMode();
clearModeTimers();
mode = "groundpick";
sitFlag = 0;
pickRun = { phase: 0 };
syncButtons();
}
// One blind kick (the duck can't see any ball - it's a scripted boot).
// Returns whether the kick actually launched so the keyboard's foot
// alternation only advances on real kicks.
function triggerKick(foot, source = "kb") {
if (loco === "rollers") return false;
if (inputLocked || mode !== "walk" || standTimer) return false;
if (inputLocked || mode !== "walk" || standTimer || recovery) return false;
exitHeadMode();
clearModeTimers();
mode = foot === "left" ? "kickL" : "kickR";
sitFlag = 0;
@@ -1283,9 +1537,12 @@ async function boot({ scene, camera, renderer }) {
function syncButtons() {
const sitting = mode === "sitstand" && sitFlag === 1;
const label =
mode === "roll" ? "Roll"
recovery ? "Recovery"
: mode === "roll" ? "Roll"
: mode === "crouch" ? "Crouch"
: mode === "groundpick" ? "Pick"
: isKick() ? "Kick"
: headMode ? "Head"
: sitting ? "Sit"
: loco === "rollers" ? "Drive"
: "Run";
@@ -1329,13 +1586,25 @@ async function boot({ scene, camera, renderer }) {
toggleLoco, setLoco, ensureRollers,
triggerCrouch,
get crouchPhase() { return crouchRun?.phase ?? null; },
triggerGroundPick,
get groundPickPhase() { return pickRun?.phase ?? null; },
get kickSteps() { return KICK_STEPS; },
set kickSteps(v) { KICK_STEPS = v; },
get recovery() { return recovery?.state ?? null; },
// Debug shove for fall-recovery testing: an instantaneous trunk
// velocity kick (free-joint dofs are qvel[0..5]).
debugPush: (vx = 0, vy = 0, vz = 0, wx = 0, wy = 0, wz = 0) => {
const qvel = data.qvel;
qvel[0] += vx; qvel[1] += vy; qvel[2] += vz;
qvel[3] += wx; qvel[4] += wy; qvel[5] += wz;
},
get headMode() { return headMode; },
toggleHeadMode, headTarget, headSmooth,
get ballActive() { return ballActive; },
get ballQposAdr() { return ballQposAdr; },
get chaseCam() { return chaseCam; },
set chaseCam(v) { chaseCam = !!v; },
get arcades() { return arcadeGroups; },
get props() { return propGroups; },
get relief() { return reliefOn; },
setRelief: (v) => { reliefOn = !!v; },
get camResetActive() { return camResetT0 !== null; },
@@ -1377,6 +1646,10 @@ async function boot({ scene, camera, renderer }) {
ghosts = await initGhosts({
scene, rig, cloneRig, setJoint, setJawOpen, applyVariant,
jointNames: JOINT_NAMES,
// Payload sanitizing: ghosts.js coerces unknown peer variants to the
// default instead of letting applyVariant throw on a bad key.
variantNames: Object.keys(VARIANTS),
defaultVariant: DEFAULT_VARIANT,
// Ghost rig per locomotion flag: peers in roller mode clone the
// roller rig once this tab has built it, and fall back to the leg
// rig until then. Known v1 limitation, documented in the README.
@@ -1394,6 +1667,7 @@ async function boot({ scene, camera, renderer }) {
};
},
});
liveGhostSessions.add(ghosts);
if (ghosts.room) ghosts.room.onPeerJoin = () => stickers?.pop("hi");
} catch (e) {
window.__ghostErr = String((e && e.stack) || e);
+79 -7
View File
@@ -44,8 +44,20 @@ const hasMoved = (spawn, p) => {
return Math.abs(Math.atan2(Math.sin(dyaw), Math.cos(dyaw))) > REVEAL_YAW;
};
// Instances not yet destroyed, so a dev-server hot swap of this module can
// tear down the previous one's interval/room instead of stacking them.
const liveInstances = new Set();
if (import.meta.hot) {
import.meta.hot.dispose(() => {
for (const g of [...liveInstances]) g.destroy();
});
}
export async function initGhosts(env) {
const noop = { update() {}, peerCount: () => 0, ghostCount: () => 0, debug: () => [], mapDots: () => [] };
const noop = {
update() {}, peerCount: () => 0, ghostCount: () => 0, debug: () => [],
mapDots: () => [], destroy() {}, injectState: () => false,
};
let room;
try {
const { joinRoom } = await import(/* @vite-ignore */ TRYSTERO_URL);
@@ -56,6 +68,11 @@ export async function initGhosts(env) {
}
const { scene, cloneRig, setJoint, setJawOpen, applyVariant, jointNames, getLocalState } = env;
// Variant whitelist supplied by the host (this module imports nothing from
// variants.js, see header). Unknown names from remote peers are coerced to
// the default so applyVariant never sees a key it can't resolve.
const knownVariants = env.variantNames ? new Set(env.variantNames) : null;
const defaultVariant = env.defaultVariant ?? env.variantNames?.[0];
// Locomotion-variant rig source: state.l 1 = rollers, 0/absent = legs
// (old clients never send it). Falls back to the leg rig when the local
// tab hasn't built the roller rig yet - known v1 limitation.
@@ -132,6 +149,7 @@ export async function initGhosts(env) {
};
const ghosts = new Map(); // peerId -> ghost
let destroyed = false; // set by destroy(): drops any late messages
// Interpolation snapshot: the pose parts of a state message, stamped
// with the local arrival time.
const snapOf = (state) => ({ p: state.p, j: state.j, w: state.w ?? 0, at: performance.now() });
@@ -164,9 +182,33 @@ export async function initGhosts(env) {
ghosts.delete(peerId);
};
// The lobby is public over Nostr relays, so any peer can send anything:
// validate the payload shape before touching it, and never let a hostile
// or buggy message throw out of the handler.
const finiteArray = (a, n) => Array.isArray(a) && a.length === n && a.every(Number.isFinite);
const validState = (state) =>
typeof state === "object" && state !== null &&
finiteArray(state.p, 7) &&
finiteArray(state.j, jointNames.length) &&
(state.w == null || Number.isFinite(state.w)) &&
typeof state.v === "string";
const warnedPeers = new Set(); // one malformed-payload warn per peer
// Handler signature in this build: (payload, context) where context is
// { peerId } - NOT the bare peerId string of classic trystero.
act.onMessage = (state, { peerId }) => {
const handleState = (state, peerId) => {
if (destroyed) return;
if (!validState(state)) {
if (!warnedPeers.has(peerId)) {
warnedPeers.add(peerId);
console.warn("ghosts: dropping malformed state from peer", peerId);
}
return;
}
// Sanitize the free-form fields in place (state is a fresh deserialized
// object, never shared): unknown variant -> default, loco flag -> 0|1.
if (knownVariants && !knownVariants.has(state.v)) state.v = defaultVariant;
state.l = state.l ? 1 : 0;
let g = ghosts.get(peerId);
if (!g) {
if (ghosts.size >= MAX_GHOSTS) return; // room stays open, rendering capped
@@ -193,7 +235,7 @@ export async function initGhosts(env) {
// Peer switched legs <-> rollers: rebuild its ghost on the other rig
// (cheap - cloneRig shares geometry). The snapshot buffer carries over
// so the interpolated motion stays continuous across the swap.
if ((state.l ?? 0) !== g.loco) {
if (state.l !== g.loco) {
const { lastSeen, spawn, revealed, buf } = g;
removeGhost(peerId);
g = makeGhost(state);
@@ -208,14 +250,28 @@ export async function initGhosts(env) {
ghostify(g.rig);
}
};
const onState = (state, { peerId }) => {
try {
handleState(state, peerId);
} catch (e) {
// Shape-valid but still poisonous payload, or an internal error: drop
// the message, keep the handler alive for the next one.
if (!warnedPeers.has(peerId)) {
warnedPeers.add(peerId);
console.warn("ghosts: error handling state from peer", peerId, e);
}
}
};
act.onMessage = onState;
// Same setter-style registration as onMessage.
room.onPeerLeave = (peerId) => removeGhost(peerId);
// Graceful exit so other tabs drop this ghost immediately...
window.addEventListener("pagehide", () => {
const onPagehide = () => {
try { room.leave(); } catch {}
});
};
window.addEventListener("pagehide", onPagehide);
// ...and a staleness sweep for peers that vanished without leaving
// (crashed tab, dropped connection): 5 s without a state packet means
// the peer is gone, not just lagging (even background-throttled tabs
@@ -224,7 +280,7 @@ export async function initGhosts(env) {
// Broadcast + stale sweep on setInterval (not rAF) so both keep running
// in occluded tabs.
setInterval(() => {
const tickId = setInterval(() => {
const s = getLocalState();
if (s) sendState(s);
const now = performance.now();
@@ -237,8 +293,22 @@ export async function initGhosts(env) {
// instances, cloned here from any node of the already-built local rig.
const _qa = env.rig.placer.quaternion.clone();
const _qb = env.rig.placer.quaternion.clone();
return {
const api = {
room,
// Full teardown: without it, every HMR reload of this module stacked a
// live 15 Hz interval plus a ghost room that kept broadcasting.
destroy() {
if (destroyed) return;
destroyed = true;
liveInstances.delete(api);
clearInterval(tickId);
window.removeEventListener("pagehide", onPagehide);
try { room.leave(); } catch {}
for (const peerId of [...ghosts.keys()]) removeGhost(peerId);
},
// Debug/test hook: feed a payload through the exact same guarded path
// as a network message (console QA of the validation layer).
injectState: (state, peerId = "__debug") => onState(state, { peerId }),
peerCount: () => Object.keys(room.getPeers()).length,
ghostCount: () => ghosts.size,
// Minimap feed: revealed ghosts' arena positions in raw MJCF coords
@@ -285,4 +355,6 @@ export async function initGhosts(env) {
}
},
};
liveInstances.add(api);
return api;
}
+338
View File
@@ -0,0 +1,338 @@
// Prop library: every decorative GLB the arena can dress itself with.
//
// Each entry is fully declarative; adding a prop = dropping a GLB in
// public/assets/props/ and appending a def here, removing one from the
// scene = enabled: false (the asset stays in the repo - that's the
// library). The scene loads every enabled prop, snaps it to the floor,
// gives it a wireframe materialization FX and registers it with the
// entrance/respawn ceremony.
//
// Def shape:
// id unique key (also the group key in the loaded map)
// glb file under ./assets/props/ (cache-bust with ?v=N)
// enabled false = stays in the library, never touches the scene
// size { axis: "x"|"y"|"z"|"max", m } - the NATURAL bbox extent
// along that axis is scaled to m meters (three.js axes:
// y up). Robust to re-exported assets of any raw size.
// rotation [rx, ry, rz] euler (rad) applied to the model
// rotationOrder optional three.js euler order (default "XYZ")
// position [x, z] floor coords; y is auto-snapped so the posed
// bbox rests on the floor
// lift optional extra y (m) on top of the floor snap, for
// props staged on top of another prop (boombox on the
// skateboard deck)
// fxDelay seconds after the duck's scan cue (see ceremony.addPropFx)
// wireNode optional mesh name inside the GLB used as a coarser
// stand-in for the hologram pass (fxWireGeometry escape
// hatch, see fx-wireframe.js)
// instances optional [{ position, rotation?, fxDelay? }] to place
// several clones sharing geometry/materials (arcade row)
// collider optional static MJCF box(es) so the duck/ball can't
// clip through: { pos: [x,y,z], size: [hx,hy,hz],
// euler?: [rx,ry,rz] } in MJCF coords (z up, radians;
// three.js z = -mjcf y, three.js yaw = mjcf z-yaw) or
// an array
//
// World context for placements (see constants.js): 3 x 3 m arena,
// walls at +-1.5 m and only 0.25 m tall, duck spawns at (-0.6, 0)
// facing +X, relief bumps at MJCF (0.3,-0.9) (-0.9,0.75) (0.6,0.9)
// r ~0.55. Props are REAL-WORLD size on purpose: the 0.25 m duck lives
// in a 90s kid's room among human-scale objects.
//
// NOTE: skateboard/crt-tv/boombox/lavalamp/sneakers/segaconsole GLBs
// were remodeled in Blender to the arcade cabinet's quality bar
// (~3-9k tris each, chunky bevels, same orange/mint/cream palette;
// Tripo still had no credits - scripts in microduck-props/scripts/).
// Each GLB embeds a coarse <name>_wire mesh (~500 tris) used via
// wireNode for the hologram pass, like arcade_wire. The walkman was
// remodeled separately (low-poly, palette-matched).
import { ARCADE_H, ARCADE_W, ARCADE_D } from "./constants.js";
// Master switch: false = the whole library stays benched (no prop in the
// scene, no prop collider), regardless of per-def `enabled` flags.
export const PROPS_ENABLED = false;
// ── Vignette anchors ──────────────────────────────────────────────────
// "Someone parked their music ride": skateboard flat on its wheels in
// the back-left pocket (three.js [-1.08, 1.02], clear of the duck spawn
// at [-0.6, 0] and of every relief bump), yawed ~26 deg off the back
// wall, with the boombox resting on the deck facing the arena center.
const BOARD_POS = [-1.08, 1.02]; // three.js [x, z]
const BOARD_YAW = Math.PI / 2 + 0.45; // ~26 deg off the -X wall axis
const BOOMBOX_YAW = BOARD_YAW + 0.05; // slightly askew, still on the deck
// Deck surface height measured from the GLB (flat between the kicktails
// for |x| < 0.28 m scaled - the 0.55 m boombox fits exactly) after the
// 0.79 m size normalization: wheels on the floor, deck top at 0.118 m.
const DECK_TOP = 0.118;
// CRT corner-ish on the front wall, screen swivelled toward the center.
const TV_YAW = -Math.PI / 2 + 0.28; // GLB fronts +Z; -PI/2 faces -X
// Arcade cabinet anchoring the front-south corner at 45 deg, jukebox
// style (no jukebox GLB in the library; the cabinet plays that role).
const ARCADE_YAW = -3 * (Math.PI / 4); // front +Z toward the arena center
export const PROP_DEFS = [
{
// Back from the bench: a single cabinet anchoring the front-south
// corner like a jukebox (the 3-cabinet row stays retired).
id: "arcade",
glb: "arcade.glb?v=1",
enabled: true,
size: { axis: "y", m: ARCADE_H },
wireNode: "arcade_wire",
rotation: [0, ARCADE_YAW, 0],
position: [1.13, 1.13],
fxDelay: 0.85,
collider: {
pos: [1.13, -1.13, ARCADE_H / 2],
size: [ARCADE_W / 2, ARCADE_D / 2, ARCADE_H / 2],
euler: [0, 0, ARCADE_YAW],
},
},
{
// Real-size board (~0.79 m) flat on its wheels in the back-left
// pocket, casually yawed off the wall grid - the boombox's ride.
id: "skateboard",
glb: "skateboard.glb?v=3",
enabled: true,
size: { axis: "x", m: 0.79 },
wireNode: "skateboard_wire",
rotation: [0, BOARD_YAW, 0],
position: BOARD_POS,
fxDelay: 0.25,
// Main box tops out at the flat deck (0.118 m); the kicktails rise
// to ~0.16 m over local |x| 0.32-0.395, so each tail gets its own
// small box. The boombox stack is untouched: its visual lift and
// its own static collider both key off DECK_TOP, not these boxes.
collider: [
{
pos: [BOARD_POS[0], -BOARD_POS[1], 0.059],
size: [0.395, 0.166, 0.059],
euler: [0, 0, BOARD_YAW],
},
...[1, -1].map((side) => ({
pos: [
BOARD_POS[0] + side * 0.357 * Math.cos(BOARD_YAW),
-BOARD_POS[1] + side * 0.357 * Math.sin(BOARD_YAW),
0.138,
],
size: [0.038, 0.15, 0.022],
euler: [0, 0, BOARD_YAW],
})),
],
},
{
// Benched to the library (scene declutter): parked ON the skateboard
// deck (lift = deck surface height), speakers facing the arena.
id: "boombox",
glb: "boombox.glb?v=2",
enabled: false,
size: { axis: "x", m: 0.55 },
wireNode: "boombox_wire",
rotation: [0, BOOMBOX_YAW, 0], // GLB fronts +Z; face the center
position: BOARD_POS,
lift: DECK_TOP,
fxDelay: 0.55,
collider: {
pos: [BOARD_POS[0], -BOARD_POS[1], DECK_TOP + 0.17],
size: [0.275, 0.098, 0.17],
euler: [0, 0, BOOMBOX_YAW],
},
},
{
// Benched to the library (scene declutter): 90s CRT near the front
// wall, swivelled toward the center like it's watching the duck.
id: "crt-tv",
glb: "crt-tv.glb?v=3",
enabled: false,
size: { axis: "x", m: 0.45 },
wireNode: "crt_tv_wire",
rotation: [0, TV_YAW, 0],
position: [1.23, -0.42],
fxDelay: 0.7,
// Body top measured at 0.426 m world (0.416 raw x 0.45/0.44 scale);
// the antenna (up to 0.61 m) stays out on purpose - decorative.
collider: {
pos: [1.23, 0.42, 0.213],
size: [0.225, 0.211, 0.213],
euler: [0, 0, TV_YAW],
},
},
{
// Casually dropped on its back next to the lava lamp in the
// front-left corner, window facing the ceiling. YXZ order: lie
// flat (x +90 deg) first, then yaw in the floor plane. Natural
// bbox 0.096 x 0.124 x 0.054 -> lying footprint ~0.10 x 0.135,
// 0.059 m thick once normalized to 0.135 m tall.
id: "walkman",
glb: "walkman.glb?v=4",
enabled: true,
size: { axis: "y", m: 0.135 },
rotation: [Math.PI / 2, 0.6, 0],
rotationOrder: "YXZ",
position: [1.22, -1.0],
fxDelay: 0.4,
collider: {
pos: [1.22, 1.0, 0.03],
size: [0.055, 0.07, 0.03],
euler: [0, 0, 0.6],
},
},
{
// Classic 45 cm board, palette-remapped sectors (dark/cream
// singles, orange/mint rings), 3 darts stuck in. Not hung yet:
// resting on the floor, leaning against the left (-Z) wall in the
// FRONT corner. That's the only pose the boot chase-cam can see:
// it pitches 24 deg down at the duck with a 20 deg vertical
// half-FOV, so wall points above ~0.37 m are always clipped -
// a duck-height mount can never be in the boot frame. Visible
// left-wall window at boot: x in [1.03, 1.5], y < 0.37 m. GLB
// fronts +Z; x-tilt -0.12 leans the top into the wall, floor
// snap keeps the bottom rim grounded. On the floor the ball can
// reach it, so it gets a thin box collider (upright: the 7 deg
// lean offset is ~1 cm at ball height, not worth an euler).
id: "dartboard",
glb: "dartboard.glb?v=1",
enabled: true,
size: { axis: "x", m: 0.47 },
wireNode: "dartboard_wire",
rotation: [-0.12, 0, 0],
position: [1.2, -1.42],
fxDelay: 0.6,
collider: {
pos: [1.2, 1.42, 0.235],
size: [0.235, 0.06, 0.235],
},
},
{
// Mood light in the FRONT-LEFT corner of the arena: mint hourglass
// base and dome cap, translucent orange vessel with baked emissive
// lava blobs (concept prop-lava-lamp-concept-v2). 0.25 m off both
// walls, clear of the (0.6, -0.9) relief bump. 0.377 m tall.
id: "lavalamp",
glb: "lavalamp.glb?v=2",
enabled: true,
size: { axis: "y", m: 0.38 },
wireNode: "lavalamp_wire",
rotation: [0, 0, 0],
position: [1.25, -1.25],
fxDelay: 0.9,
collider: { pos: [1.25, 1.25, 0.19], size: [0.072, 0.072, 0.19] },
},
{
// Benched to the library (scene declutter): orange canvas high-top
// pair, one upright, one tipped on its side (poses baked in the
// GLB). Cream laces/toe caps/sole, mint eyelets + foxing stripe,
// generic 4-point-star ankle patch - no trademark art (concept
// prop-sneakers-concept-v2). Each shoe ~0.28 m long.
id: "sneakers",
glb: "sneakers.glb?v=2",
enabled: false,
size: { axis: "x", m: 0.41 },
wireNode: "sneakers_wire",
rotation: [0, 2.35, 0],
position: [-1.22, -0.22],
fxDelay: 0.35,
collider: {
pos: [-1.22, 0.22, 0.09],
size: [0.205, 0.15, 0.09],
euler: [0, 0, 2.35],
},
},
{
// Benched to the library (scene declutter, like its CRT): Genesis
// -like 16-bit console with two wired mint pads (concept
// prop-console-concept-v2b, no logos). Collider covers the 0.30 m
// body slab only - pads, cables and plinth stay decorative.
id: "segaconsole",
glb: "segaconsole.glb?v=2",
enabled: false,
size: { axis: "x", m: 0.3 },
wireNode: "segaconsole_wire",
rotation: [0, TV_YAW, 0],
position: [0.87, -0.38],
fxDelay: 0.5,
collider: {
pos: [0.87, 0.38, 0.031],
size: [0.15, 0.105, 0.031],
euler: [0, 0, TV_YAW],
},
},
];
// Static MJCF collision boxes for every enabled prop, consumed by
// buildPhysicsXml. Purely declarative: no GLB needs to be loaded.
export function propColliders() {
if (!PROPS_ENABLED) return [];
const out = [];
for (const def of PROP_DEFS) {
if (!def.enabled || !def.collider) continue;
const boxes = Array.isArray(def.collider) ? def.collider : [def.collider];
boxes.forEach((c, i) => {
out.push({
name: boxes.length > 1 ? `prop_${def.id}_${i}` : `prop_${def.id}`,
pos: c.pos.join(" "),
size: c.size.join(" "),
euler: c.euler?.join(" "),
});
});
}
return out;
}
// Load every enabled prop into the scene and register its wireframe
// materialization with the ceremony. Returns { id: [group, ...] }.
// Props are decorative: a missing/broken GLB never halts the boot.
export async function loadProps({
THREE, GLTFLoader, signed, scene, camera, renderer, fx, ceremony,
}) {
if (!PROPS_ENABLED) return {};
const loader = new GLTFLoader();
const groups = {};
await Promise.all(PROP_DEFS.filter((d) => d.enabled).map(async (def) => {
try {
const gltf = await loader.loadAsync(signed(`./assets/props/${def.glb}`));
const proto = gltf.scene;
const wire = def.wireNode ? proto.getObjectByName(def.wireNode) : null;
wire?.removeFromParent();
const nat = new THREE.Box3().setFromObject(proto);
const natSize = nat.getSize(new THREE.Vector3());
const extent = def.size.axis === "max"
? Math.max(natSize.x, natSize.y, natSize.z)
: natSize[def.size.axis];
proto.scale.setScalar(def.size.m / extent);
const instances = def.instances
?? [{ position: def.position, rotation: def.rotation }];
groups[def.id] = instances.map((inst, i) => {
// clone(true) shares geometry/materials; userData doesn't
// survive Object3D.copy, so the wire tag is applied per clone.
const node = i === 0 ? proto : proto.clone(true);
if (wire) {
node.traverse((o) => {
if (o.isMesh) o.userData.fxWireGeometry = wire.geometry;
});
}
const rot = inst.rotation ?? def.rotation ?? [0, 0, 0];
node.quaternion.setFromEuler(
new THREE.Euler(...rot, def.rotationOrder ?? "XYZ"),
);
const group = new THREE.Group();
group.add(node);
// Floor snap: whatever the GLB's pivot, the posed bbox rests
// on the ground at the declared floor coords; `lift` raises it
// on top of another prop (boombox on the skateboard deck).
const posed = new THREE.Box3().setFromObject(group);
const lift = inst.lift ?? def.lift ?? 0;
group.position.set(inst.position[0], -posed.min.y + lift, inst.position[1]);
scene.add(group);
const propFx = fx.createWireframeFx();
propFx.init({ THREE, scene, root: group, camera, renderer, hidden: true });
ceremony.addPropFx(propFx, inst.fxDelay ?? def.fxDelay ?? 0.3);
return group;
});
} catch (err) {
console.warn(`[props] "${def.id}" disabled:`, err);
}
}));
return groups;
}
+21
View File
@@ -133,6 +133,27 @@ export const VARIANTS = {
export const VARIANT_NAMES = Object.keys(VARIANTS);
export const DEFAULT_VARIANT = "classic";
// Official colourway display names, for tooltips/labels only - the
// internal variant keys above stay unchanged.
export const VARIANT_LABELS = {
classic: "Cream",
charcoal: "Graphite",
purple: "Lavender",
blue: "Sky",
};
// UI swatch hexes for the HUD colour picker: the press-kit sRGB shell
// targets, pinned as literals. The sim's material specs above predate the
// press-kit recalibration, so the picker does NOT derive from them - this
// table is shared verbatim with the pollen-website landing picker so both
// show byte-identical chips.
export const VARIANT_SWATCH_HEX = {
classic: "#f7e6cb",
charcoal: "#6c6a68",
purple: "#bfa9cf",
blue: "#a9dbe8",
};
export const randomVariantName = () =>
VARIANT_NAMES[Math.floor(Math.random() * VARIANT_NAMES.length)];
+154
View File
@@ -0,0 +1,154 @@
// CRT barrel distortion post-process: the one part of the old-TV treatment
// that CSS can't fake (Overlays.jsx owns the scanlines / noise / vignette,
// which stay flat on the glass - this warps the picture tube behind them).
//
// Hand-rolled RTT pass, no postprocessing dep: the scene is rendered into a
// multisampled target, then blitted to the canvas through one fullscreen-
// triangle shader that applies barrel warp, a per-channel chromatic fringe
// at the far edges and a touch of corner darkening.
//
// Wiring: mounting this component registers a useFrame subscriber with
// priority 1, which switches R3F to manual rendering - the game update
// subscriber (priority 0, in GameCanvas) still runs first each frame.
//
// Color fidelity: three r152+ skips tone mapping + sRGB output when
// rendering into a render target, so a naive linear RT visibly brightens
// every alpha/additive-blended element (the arena grid) because blending
// then happens in linear space instead of on display-encoded values like
// the canvas. Fix: flag the target as isXRRenderTarget (the WebXR path),
// which makes materials tone-map + sRGB-encode straight into the RT, while
// internalFormat RGBA8 keeps the storage linear so the hardware never
// double-encodes. The RT then holds the exact canvas image and this pass
// only moves pixels around - zero color shift (verified against a live
// direct-render bypass).
//
// Entrance FX (wireframe materialization, glitch, grid draw-in) live in
// scene materials and are captured by the RTT pass untouched. HUD / DOM
// overlays sit above the canvas and are never distorted.
import { useEffect, useMemo } from "react";
import * as THREE from "three";
import { useThree, useFrame } from "@react-three/fiber";
// ── Tuning ───────────────────────────────────────────────────────────────
export const CRT_DISTORTION_ENABLED = true;
const BARREL = 0.055; // curvature strength (0 = flat, ~0.1 = heavy fishbowl)
const ABERRATION = 0.05; // RGB fringe, fraction of the barrel shift (~1-2px at edges)
const CORNER_DARKEN = 0.12; // shader-side corner falloff (CSS vignette adds more)
const EDGE_FEATHER = 0.0025; // anti-aliased feather on the curved border, in uv
const MSAA_SAMPLES = 4; // multisampling on the scene target (matches canvas AA)
const VERT = /* glsl */ `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4(position.xy, 0.0, 1.0);
}
`;
const FRAG = /* glsl */ `
uniform sampler2D tScene;
uniform float uBarrel, uAberration, uDarken, uFeather;
varying vec2 vUv;
vec2 warp(vec2 uv, float k) {
vec2 cc = uv - 0.5;
return 0.5 + cc * (1.0 + k * dot(cc, cc));
}
void main() {
vec2 uvG = warp(vUv, uBarrel);
vec2 uvR = warp(vUv, uBarrel * (1.0 + uAberration));
vec2 uvB = warp(vUv, uBarrel * (1.0 - uAberration));
vec3 col = vec3(
texture2D(tScene, uvR).r,
texture2D(tScene, uvG).g,
texture2D(tScene, uvB).b
);
// Outside the warped frame = beyond the tube, fade to black with a thin
// feather so the curved border stays anti-aliased.
vec2 d = min(uvG, 1.0 - uvG);
col *= smoothstep(0.0, uFeather, min(d.x, d.y));
// Gentle corner falloff, like light dying on curved glass.
vec2 cc = vUv - 0.5;
col *= 1.0 - uDarken * 2.0 * dot(cc, cc);
// tScene already holds tone-mapped, sRGB-encoded values (see header):
// write them through untouched.
gl_FragColor = vec4(col, 1.0);
}
`;
export default function CrtDistortion() {
const { size, viewport } = useThree();
const { target, quadScene, quadCamera, material, geometry } = useMemo(() => {
const target = new THREE.WebGLRenderTarget(1, 1, { samples: MSAA_SAMPLES });
// WebXR-path flag: tone mapping + output color space apply when
// rendering into this target (see header comment).
target.isXRRenderTarget = true;
target.texture.colorSpace = THREE.SRGBColorSpace;
// Linear storage: the shader already encodes, the hardware must not.
target.texture.internalFormat = "RGBA8";
// Fullscreen triangle (one primitive, no diagonal seam).
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array([-1, -1, 0, 3, -1, 0, -1, 3, 0]), 3),
);
geometry.setAttribute(
"uv",
new THREE.BufferAttribute(new Float32Array([0, 0, 2, 0, 0, 2]), 2),
);
const material = new THREE.ShaderMaterial({
vertexShader: VERT,
fragmentShader: FRAG,
uniforms: {
tScene: { value: target.texture },
uBarrel: { value: BARREL },
uAberration: { value: ABERRATION },
uDarken: { value: CORNER_DARKEN },
uFeather: { value: EDGE_FEATHER },
},
depthTest: false,
depthWrite: false,
});
const quad = new THREE.Mesh(geometry, material);
quad.frustumCulled = false;
const quadScene = new THREE.Scene();
quadScene.add(quad);
const quadCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
// Dev-only tuning hook: tweak uniforms live from the console, e.g.
// __crtDistortion.uBarrel.value = 0.08
if (import.meta.env.DEV) window.__crtDistortion = material.uniforms;
return { target, quadScene, quadCamera, material, geometry };
}, []);
// Track canvas size and DPR (R3F clamps dpr to [1, 2]).
useEffect(() => {
const dpr = viewport.dpr;
target.setSize(Math.round(size.width * dpr), Math.round(size.height * dpr));
}, [target, size.width, size.height, viewport.dpr]);
useEffect(() => {
return () => {
target.dispose();
material.dispose();
geometry.dispose();
};
}, [target, material, geometry]);
// Priority 1: takes over rendering from R3F (runs after the priority-0
// game update). Scene -> RT, then RT -> canvas through the warp shader.
useFrame(({ gl: renderer, scene, camera }) => {
if (import.meta.env.DEV && window.__crtBypass) {
renderer.setRenderTarget(null);
renderer.render(scene, camera);
return;
}
renderer.setRenderTarget(target);
renderer.render(scene, camera);
renderer.setRenderTarget(null);
renderer.render(quadScene, quadCamera);
}, 1);
return null;
}
+2
View File
@@ -10,6 +10,7 @@ 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 CrtDistortion, { CRT_DISTORTION_ENABLED } from "./CrtDistortion.jsx";
function Game() {
const { scene, camera, gl } = useThree();
@@ -54,6 +55,7 @@ export default function GameCanvas() {
}}
>
<Game />
{CRT_DISTORTION_ENABLED && <CrtDistortion />}
</Canvas>
);
}
+297 -159
View File
@@ -1,17 +1,26 @@
// In-game HUD: Back (top-left), mode readout (top-right, Matrix-style
// letter scramble on change), quickbar (bottom-left: live colour dots +
// legs/rollers segment), telemetry stack (bottom-right) and the
// LOADING ROLLERS line while the roller stack streams in.
// In-game HUD: Back (top-left), pre-order button (top-right, label flips
// to "Pre-order pack" while rollers are selected - the rollers ship in the
// accessory pack), quickbar (bottom-left: colour palette + loco switch),
// telemetry stack (bottom-right) and the LOADING ROLLERS line while the
// roller stack streams in.
//
// Chrome reads as small comic PANELS: each group sits in a thick cream
// keyline frame on a dark glass plate (1px ink inset between glass and
// frame), with a caption box (cartouche) overlapping the frame's corner -
// flat cream (orange for the shop CTA) fill, ink keyline, hard 2px offset
// shadow, half in / half out like a caption on a comic panel's edge. Same
// tokens as the landing (Anton, orange, cream), zero radius everywhere.
// Title-menu CTAs stay ComicButton.
//
// Whole HUD is hidden while the title/pause overlay is up; touch mode
// strips it down to the thumbs + Back.
import { useEffect, useRef, useState } from "react";
import Box from "@mui/material/Box";
import ButtonBase from "@mui/material/ButtonBase";
import { keyframes } from "@mui/material/styles";
import { useGame, gameApi } from "../store.js";
import { VARIANT_SWATCHES } from "../game/game.js";
import { INK, ORANGE, MONO } from "../theme.js";
import { VARIANT_LABELS, VARIANT_SWATCH_HEX } from "../game/variants.js";
import { ORANGE, MONO } from "../theme.js";
import { ANTON, COMIC_INK, CREAM } from "./comic.jsx";
// Matrix-style letter scramble: on change every glyph flips through random
// charset entries, then locks to its target left-to-right over ~0.45 s.
@@ -31,7 +40,6 @@ function useScramble(target) {
const rnd = () => SCRAMBLE_GLYPHS[(Math.random() * SCRAMBLE_GLYPHS.length) | 0];
const t0 = performance.now();
timer.current = setInterval(() => {
// Letters 0..k-1 are locked; the rest keep boiling.
const k = Math.floor(((performance.now() - t0) / DUR) * n);
if (k >= n) {
clearInterval(timer.current);
@@ -53,184 +61,319 @@ const recBlink = keyframes`
59%, 100% { opacity: 0.12; }
`;
function BackButton() {
const chipPop = keyframes`
0% { transform: scale(0.86); }
55% { transform: scale(1.1); }
100% { transform: scale(1); }
`;
const HUD_H = 48;
const FRAME_W = 2; // cream keyline thickness
const PANEL_PAD = 5; // air between the frame and the printed content
// Height left for the cells inside frame + padding; colour swatches use it
// as their width too so they stay square.
const CELL_H = HUD_H - 2 * (FRAME_W + PANEL_PAD);
const CELL_GAP = 4; // gap between cells; the glass ground shows through
const FRAME = "rgba(250, 248, 242, 0.9)";
const GLASS = "rgba(8, 8, 12, 0.6)";
// The panel frame: a thick cream keyline (comic ink weight, HUD read)
// around a dark glass plate, with a 1px ink inset between frame and glass
// so it reads like a printed panel, and a few px of glass padding so the
// content has air inside the frame (the glass ground fills the padding).
// The inset is a pseudo-element so it draws over the cells (an inset
// box-shadow would be painted under them). Overflow clipping lives on the
// inner content wrapper, not the plate, so the caption box can hang over
// the frame's corner.
const plateSx = {
position: "relative",
display: "inline-flex",
height: HUD_H,
boxSizing: "border-box",
border: `${FRAME_W}px solid ${FRAME}`,
padding: `${PANEL_PAD}px`,
borderRadius: 0,
background: GLASS,
"&::after": {
content: '""',
position: "absolute",
inset: 0,
pointerEvents: "none",
zIndex: 2,
boxShadow: `inset 0 0 0 1px ${COMIC_INK}`,
},
};
// Caption box (cartouche) printed over the panel's top corner, half in /
// half out - the landing's print language: flat fill, ink keyline, hard
// offset shadow, zero radius. Decorative only: no pointer events, no
// layout footprint (absolute over the frame).
const CAPTION_FILLS = { cream: CREAM, orange: ORANGE };
const captionBaseSx = {
position: "absolute",
top: -9,
zIndex: 3,
pointerEvents: "none",
userSelect: "none",
whiteSpace: "nowrap",
fontFamily: ANTON,
fontSize: "0.58rem",
letterSpacing: "0.09em",
textTransform: "uppercase",
lineHeight: 1,
padding: "3px 6px 2px",
color: COMIC_INK,
border: `2px solid ${COMIC_INK}`,
borderRadius: 0,
boxShadow: `2px 2px 0 ${COMIC_INK}`,
};
function HudPlate({ caption, captionSide = "left", captionFill = "cream", children, sx }) {
return (
<ButtonBase
onClick={() => useGame.setState({ menuOpen: true })}
sx={{
position: "fixed",
top: "1.4rem",
left: "1.6rem",
zIndex: 10,
display: "inline-flex",
alignItems: "center",
gap: "0.45em",
border: "1px solid rgba(255, 255, 255, 0.16)",
background: "rgba(8, 8, 12, 0.55)",
color: "rgba(255, 255, 255, 0.75)",
font: "inherit",
fontSize: "0.8rem",
fontWeight: 600,
letterSpacing: "0.14em",
textTransform: "uppercase",
p: "0.6rem 1.15rem",
borderRadius: "999px",
transition: "color 0.15s ease, background 0.15s ease, border-color 0.15s ease",
"&:hover": {
color: "#fff",
borderColor: "rgba(255, 255, 255, 0.4)",
background: "rgba(255, 255, 255, 0.06)",
},
"&.Mui-focusVisible": {
outline: `2px solid ${ORANGE}`,
outlineOffset: 2,
},
}}
>
{"\u2190"} Back
</ButtonBase>
<Box sx={{ ...plateSx, ...sx }}>
<Box
sx={{
display: "inline-flex",
alignItems: "stretch",
height: "100%",
overflow: "hidden",
}}
>
{children}
</Box>
{caption ? (
<Box
aria-hidden
sx={{
...captionBaseSx,
background: CAPTION_FILLS[captionFill],
...(captionSide === "right" ? { right: -8 } : { left: -8 }),
}}
>
{caption}
</Box>
) : null}
</Box>
);
}
// Active policy/mode readout, top-right: bright orange caption over a big
// white monospace name.
function ModeReadout() {
const modeLabel = useGame((s) => s.modeLabel);
const text = useScramble(modeLabel);
function BackArrowIcon() {
return (
<Box
sx={{
position: "fixed",
top: "1.4rem",
right: "1.6rem",
zIndex: 10,
fontFamily: MONO,
pointerEvents: "none",
textAlign: "right",
}}
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",
alignItems: "center",
justifyContent: "center",
gap: "0.45em",
height: "100%",
px: "0.95rem",
margin: 0,
border: "none",
borderRadius: 0,
background: "transparent",
color: CREAM,
cursor: "pointer",
fontFamily: ANTON,
fontSize: "0.92rem",
letterSpacing: "0.08em",
textTransform: "uppercase",
textDecoration: "none",
lineHeight: 1,
whiteSpace: "nowrap",
WebkitTapHighlightColor: "transparent",
userSelect: "none",
transition: "background 0.15s ease, color 0.15s ease, filter 0.15s ease",
"&:focus-visible": {
outline: `2px dashed ${CREAM}`,
outlineOffset: -5,
},
};
function BackButton() {
return (
<HudPlate
caption="Nav"
sx={{ position: "fixed", top: "1.25rem", left: "1.5rem", zIndex: 10 }}
>
<Box
component="span"
component="button"
type="button"
onClick={() => useGame.setState({ menuOpen: true })}
sx={{
display: "block",
mb: "0.35rem",
fontSize: "0.78rem",
fontWeight: 600,
letterSpacing: "0.24em",
textTransform: "uppercase",
color: ORANGE,
textShadow: "0 0 10px rgba(255, 122, 47, 0.35)",
...hudHitSx,
"&:hover": {
color: ORANGE,
background: "rgba(255, 122, 47, 0.12)",
},
"&:active": { filter: "brightness(0.92)" },
}}
>
Mode
<BackArrowIcon /> Back
</Box>
</HudPlate>
);
}
const SHOP_URL = "https://pollen-robotics.myshopify.com/products/microduck";
function PreorderButton() {
const locoWant = useGame((s) => s.locoWant);
const text = useScramble(locoWant === "rollers" ? "Pre-order pack" : "Pre-order");
return (
<HudPlate
caption="Shop"
captionSide="right"
captionFill="orange"
sx={{ position: "fixed", top: "1.25rem", right: "1.5rem", zIndex: 10 }}
>
<Box
component="a"
href={SHOP_URL}
target="_blank"
rel="noopener noreferrer"
sx={{
minWidth: "8ch",
minHeight: "1.2em",
fontSize: "1.7rem",
fontWeight: 600,
letterSpacing: "0.16em",
textTransform: "uppercase",
color: "rgba(255, 255, 255, 0.95)",
textAlign: "right",
textShadow: "0 0 12px rgba(255, 255, 255, 0.28)",
lineHeight: 1.2,
...hudHitSx,
background: ORANGE,
color: COMIC_INK,
"&:hover": { filter: "brightness(1.07)" },
"&:active": { filter: "brightness(0.92)" },
}}
>
{text}
</Box>
</Box>
</HudPlate>
);
}
// In-game quick picks, bottom-left: colour dots + legs/rollers, live.
// Same pill language as the vitrine DuckPlayground.
function Quickbar() {
const variant = useGame((s) => s.variant);
const locoWant = useGame((s) => s.locoWant);
const pill = {
display: "inline-flex",
gap: "0.24rem",
p: "0.26rem",
border: "1px solid rgba(255, 255, 255, 0.14)",
borderRadius: "999px",
background: "rgba(8, 8, 12, 0.55)",
};
return (
<Box
sx={{
position: "fixed",
bottom: "1.4rem",
left: "1.6rem",
bottom: "1.25rem",
left: "1.5rem",
zIndex: 10,
display: "flex",
flexWrap: "wrap",
alignItems: "center",
gap: "0.6rem",
alignItems: "flex-end",
gap: "0.85rem",
maxWidth: "calc(100vw - 14.5rem)",
}}
>
<Box role="group" aria-label="Duck colours" sx={pill}>
{Object.entries(VARIANT_SWATCHES).map(([name, hex]) => (
<ButtonBase
key={name}
aria-label={`${name} colours`}
aria-pressed={name === variant}
onClick={() => gameApi.setVariant?.(name)}
sx={{
height: { xs: "2rem", sm: "2.3rem" },
px: { xs: "0.42rem", sm: "0.5rem" },
borderRadius: "999px",
"&.Mui-focusVisible": { outline: `2px solid ${ORANGE}`, outlineOffset: 2 },
"&:hover .dot": { opacity: 1 },
}}
>
<Box
className="dot"
sx={{
width: { xs: "1.2rem", sm: "1.4rem" },
height: { xs: "1.2rem", sm: "1.4rem" },
borderRadius: "50%",
background: hex,
opacity: name === variant ? 1 : 0.45,
transform: name === variant ? "scale(1.15)" : "none",
transition: "transform 0.2s ease, opacity 0.2s ease",
}}
/>
</ButtonBase>
))}
</Box>
<Box role="group" aria-label="Locomotion mode" sx={pill}>
{["legs", "rollers"].map((name) => (
<ButtonBase
key={name}
aria-pressed={locoWant === name}
onClick={() => gameApi.requestLoco?.(name)}
sx={{
height: { xs: "2rem", sm: "2.3rem" },
px: { xs: "0.8rem", sm: "1.05rem" },
borderRadius: "999px",
font: "inherit",
fontSize: { xs: "0.68rem", sm: "0.76rem" },
fontWeight: 600,
letterSpacing: "0.14em",
textTransform: "uppercase",
color: locoWant === name ? ORANGE : "rgba(255, 255, 255, 0.45)",
background: locoWant === name ? "rgba(255, 122, 47, 0.14)" : "transparent",
transition: "color 0.2s ease, background 0.2s ease",
"&.Mui-focusVisible": { outline: `2px solid ${ORANGE}`, outlineOffset: 2 },
}}
>
{name === "legs" ? "Legs" : "Rollers"}
</ButtonBase>
))}
</Box>
<HudPlate caption="Color">
<Box
role="group"
aria-label="Duck colours"
sx={{
display: "inline-flex",
alignItems: "stretch",
height: "100%",
gap: `${CELL_GAP}px`,
}}
>
{Object.entries(VARIANT_SWATCH_HEX).map(([name, hex]) => {
const selected = name === variant;
const label = VARIANT_LABELS[name] ?? name;
return (
<Box
key={name}
component="button"
type="button"
title={label}
aria-label={`${label} colours`}
aria-pressed={selected}
onClick={() => gameApi.setVariant?.(name)}
sx={{
appearance: "none",
width: CELL_H, // square cell inside frame + padding
height: "100%",
p: 0,
background: hex,
border: "none",
borderRadius: 0,
cursor: "pointer",
WebkitTapHighlightColor: "transparent",
boxShadow: selected ? `inset 0 0 0 2px ${CREAM}` : "none",
opacity: selected ? 1 : 0.7,
animation: selected ? `${chipPop} 0.28s ease` : "none",
transition: "opacity 0.15s ease, box-shadow 0.15s ease",
"&:hover": { opacity: 1 },
"&:active": { animation: "none", filter: "brightness(0.92)" },
"&:focus-visible": {
outline: `2px dashed ${CREAM}`,
outlineOffset: -5,
},
"@media (prefers-reduced-motion: reduce)": { animation: "none" },
}}
/>
);
})}
</Box>
</HudPlate>
<HudPlate caption="Mode">
<Box
role="group"
aria-label="Locomotion mode"
sx={{
display: "inline-flex",
alignItems: "stretch",
height: "100%",
gap: `${CELL_GAP}px`,
}}
>
{[
{ name: "legs", label: "Feet" },
{ name: "rollers", label: "Rollers" },
].map(({ name, label }) => {
const selected = locoWant === name;
return (
<Box
key={name}
component="button"
type="button"
aria-pressed={selected}
onClick={() => gameApi.requestLoco?.(name)}
sx={{
...hudHitSx,
px: "1.05rem",
background: selected ? ORANGE : "transparent",
color: selected ? COMIC_INK : "rgba(250, 248, 242, 0.72)",
"&:hover": {
color: selected ? COMIC_INK : CREAM,
background: selected ? ORANGE : "rgba(255, 122, 47, 0.12)",
},
"&:active": { filter: "brightness(0.92)" },
}}
>
{label}
</Box>
);
})}
</Box>
</HudPlate>
</Box>
);
}
// Telemetry stack, bottom-right: peers / speed + odometer / loop rates,
// one line each, quietest at the bottom.
function Telemetry() {
const t = useGame((s) => s.telemetry);
const odo = t.odo < 1000 ? `${t.odo.toFixed(1)}M` : `${(t.odo / 1000).toFixed(2)}KM`;
@@ -242,8 +385,8 @@ function Telemetry() {
<Box
sx={{
position: "fixed",
bottom: "1.4rem",
right: "1.6rem",
bottom: "1.25rem",
right: "1.5rem",
zIndex: 10,
pointerEvents: "none",
fontFamily: MONO,
@@ -263,7 +406,6 @@ function Telemetry() {
);
}
// BIOS-style line while the roller variant streams in on first switch.
function OsdLoad() {
const rollersLoading = useGame((s) => s.rollersLoading);
if (!rollersLoading) return null;
@@ -271,8 +413,8 @@ function OsdLoad() {
<Box
sx={{
position: "fixed",
top: "6.1rem", // below the mode readout
right: "1.6rem",
top: "5.2rem",
right: "1.5rem",
zIndex: 10,
fontFamily: MONO,
fontSize: "0.68rem",
@@ -296,17 +438,13 @@ export default function Hud() {
const entered = useGame((s) => s.entered);
const menuOpen = useGame((s) => s.menuOpen);
const touchMode = useGame((s) => s.touchMode);
// HUD stays off until the first enter and while the title overlay is up
// (the BIOS readout simply covers it during boot, same as before).
if (!entered || menuOpen) return null;
return (
<>
<BackButton />
{/* Touch mode strips the HUD down to the thumbs: no quickbar, no
mode readout, no telemetry. Back stays to reach the menu. */}
<PreorderButton />
{!touchMode && (
<>
<ModeReadout />
<Quickbar />
<Telemetry />
<OsdLoad />
+114 -148
View File
@@ -1,16 +1,20 @@
// Single-page title / pause menu: vitrine brand lockup, pitch, controls
// tutorial (keyboard / gamepad / touch variant) and the CTA. The first
// "Waddle in" cues the BIOS; later Esc / the in-game Back button reopen it
// as pause. Rows fade up once, in reading order - the stagger replays on
// every open because the component remounts.
// 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 ButtonBase from "@mui/material/ButtonBase";
import { keyframes, styled } from "@mui/material/styles";
import { useGame } from "../store.js";
import { signed } from "../game/signed.js";
import { INK, ORANGE } from "../theme.js";
import { INK, ORANGE, MONO } from "../theme.js";
import { ComicButton, ComicTitle, HalftoneRamp, ANTON } from "./comic.jsx";
const rowIn = keyframes`
from { transform: translateY(12px); opacity: 0; }
@@ -50,7 +54,7 @@ const TILES = {
{ caps: "cluster-arrows", name: "Move", hint: "arrows or ZQSD" },
{ caps: ["A", "E"], name: "Kick", hint: "left / right" },
{ caps: ["R"], name: "Roll", hint: "barrel roll" },
{ caps: ["B"], name: "Ball", hint: "pop a fresh one" },
{ caps: ["G"], name: "Pick up", hint: "beak to the ground" },
{ caps: ["C"], name: "Camera", hint: "toggle chase" },
{ caps: ["Space"], name: "Reset", hint: "fresh start" },
],
@@ -58,9 +62,9 @@ const TILES = {
{ caps: ["LS"], name: "Move", hint: "left stick" },
{ caps: ["LB", "RB"], name: "Kick", hint: "left / right" },
{ caps: ["X"], name: "Roll", hint: "barrel roll" },
{ caps: ["Y"], name: "Ball", hint: "pop a fresh one" },
{ caps: ["Y"], name: "Head", hint: "sticks move the head" },
{ caps: ["RS"], name: "Camera", hint: "orbit" },
{ caps: ["\u2193"], name: "Sit", hint: "stand up" },
{ caps: ["\u2193"], name: "Sit", hint: "tap again to stand" },
],
touch: [
{ caps: ["Stick"], name: "Move", hint: "left thumb" },
@@ -70,7 +74,7 @@ const TILES = {
};
const HINTS = {
kb: "drag to orbit \u00b7 scroll to zoom",
pad: "R3 chase \u00b7 RT quack",
pad: "A ground pick \u00b7 RT quack \u00b7 hold LT wheee \u00b7 R3 chase",
touch: "drag to orbit \u00b7 pinch to zoom",
};
@@ -124,8 +128,9 @@ export default function TitleMenu() {
if (!menuOpen && !closing) return null;
// A plugged-in gamepad wins over the touch tutorial.
const variant = padConnected ? "pad" : touchMode ? "touch" : "kb";
const tiles = TILES[variant];
const tutorialVariant = padConnected ? "pad" : touchMode ? "touch" : "kb";
const tiles = TILES[tutorialVariant];
const ctaLabel = entered ? "Resume" : "Waddle in";
return (
<Box
@@ -148,10 +153,26 @@ export default function TitleMenu() {
transition: "opacity 0.35s ease, background 0.4s ease",
}}
>
<Box sx={{ width: "100%", maxWidth: "min(48rem, 92vw)", textAlign: "center" }}>
{/* Vitrine brand lockup, centered above the title: drawn duck head
+ name. Hovering swaps to the open-beak frame, same hard sprite
swap as the vitrine header. */}
{/* Theme-orange halftone pooling in the top-left corner, dots
growing toward it - the landing's screen-tone on ink ground. */}
<HalftoneRamp
color="rgba(255, 122, 47, 0.16)"
size={20}
corner="top-left"
reach={60}
/>
<Box
sx={{
position: "relative",
width: "100%",
maxWidth: "min(48rem, 92vw)",
textAlign: "center",
m: "auto 0",
}}
>
{/* Vitrine brand lockup: drawn duck head + name. Hovering swaps to
the open-beak frame, same hard sprite swap as the vitrine. */}
<Box
aria-hidden
sx={{
@@ -159,8 +180,8 @@ export default function TitleMenu() {
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: "0.55rem",
mb: "1.3rem",
gap: "0.5rem",
mb: "1.15rem",
userSelect: "none",
...row(0, brandIn),
"&:hover .duck-closed": { opacity: 0 },
@@ -173,6 +194,7 @@ export default function TitleMenu() {
position: "relative",
display: "block",
height: { xs: "2.4rem", sm: "3rem" },
filter: "drop-shadow(3px 3px 0 rgba(0, 0, 0, 0.5))",
}}
>
<Box
@@ -183,9 +205,8 @@ export default function TitleMenu() {
sx={{ display: "block", height: "100%", width: "auto" }}
/>
{/* The open frame's canvas (460x333) is a hair wider/taller
than the closed one (454x269): the dropped jaw sticks out
past the head. Offsets pin the head in place while the jaw
hangs below. */}
than the closed one (454x269); offsets pin the head while
the jaw hangs below. */}
<Box
component="img"
className="duck-open"
@@ -202,69 +223,29 @@ export default function TitleMenu() {
}}
/>
</Box>
<Box
component="span"
sx={{
fontWeight: 700,
letterSpacing: "-0.03em",
fontSize: { xs: "1.3rem", sm: "1.6rem" },
color: "#fff",
}}
>
MicroDuck
</Box>
</Box>
<Box
sx={{
display: "flex",
flexWrap: "wrap",
alignItems: "center",
justifyContent: "center",
gap: "0.6rem",
mb: "1.15rem",
fontSize: "0.72rem",
fontWeight: 600,
letterSpacing: "0.14em",
textTransform: "uppercase",
color: "rgba(255, 255, 255, 0.78)",
...row(0.08),
"& span:not(:last-child)::after": {
content: '"\u00b7"',
color: ORANGE,
pl: "0.6em",
},
}}
>
<span>MuJoCo physics</span>
<span>ONNX policies at 50 Hz</span>
</Box>
{/* Landing-grade h1: same type conventions as the vitrine hero. */}
<Typography
{/* The landing hero's mistracked-VHS treatment: orange fill with
ink drop + chroma ghosts, hollow echo line below. */}
<ComicTitle
component="h1"
sx={{
m: "0 auto",
maxWidth: "24ch",
fontSize: { xs: "2rem", sm: "clamp(2.4rem, 5vw, 3.75rem)" },
fontWeight: 600,
letterSpacing: "-0.03em",
color: "#fff",
lineHeight: 1.02,
textWrap: "balance",
...row(0.16),
}}
>
The Microduck simulator, live in your browser
</Typography>
tone="dark"
accent={ORANGE}
fontSize="clamp(3.1rem, 10vw, 5.4rem)"
lines={[
{ text: "Microduck" },
{ text: "Simulator", variant: "outline", scale: 0.6 },
]}
sx={{ ...row(0.08) }}
/>
<Typography
sx={{
mx: "auto",
mt: "1.25rem",
mb: 0,
"@media (max-height: 700px)": { mt: "0.85rem" },
mt: "1.1rem",
"@media (max-height: 700px)": { mt: "0.8rem" },
maxWidth: "36ch",
fontSize: { xs: "0.95rem", sm: "clamp(1.05rem, 1.5vw, 1.3rem)" },
fontSize: { xs: "0.95rem", sm: "1.05rem" },
lineHeight: 1.5,
letterSpacing: "-0.012em",
color: "rgba(255, 255, 255, 0.72)",
@@ -272,18 +253,22 @@ export default function TitleMenu() {
...row(0.24),
}}
>
The exact same trained policies that drive the real robot.
The exact same trained policies that drive the real robot,
live in your browser.
</Typography>
<Box
sx={{
display: "grid",
gridTemplateColumns: {
xs: variant === "touch" ? "repeat(3, 1fr)" : "repeat(2, 1fr)",
sm: "repeat(3, 1fr)",
// Three columns from ~500px up (two rows of tiles); narrow
// phones fall back to two.
gridTemplateColumns:
tutorialVariant === "touch" ? "repeat(3, 1fr)" : "repeat(2, 1fr)",
"@media (min-width: 500px)": {
gridTemplateColumns: "repeat(3, 1fr)",
},
gap: "0.55rem",
m: "1.4rem auto 0",
m: "1.35rem auto 0",
maxWidth: "36rem",
...row(0.32),
}}
@@ -292,9 +277,8 @@ export default function TitleMenu() {
<Box
key={t.name}
sx={{
p: { xs: "0.65rem 0.35rem 0.6rem", sm: "0.85rem 0.45rem 0.75rem" },
border: "1px solid rgba(255, 255, 255, 0.08)",
borderRadius: "18px",
p: { xs: "0.65rem 0.35rem 0.6rem", sm: "0.8rem 0.45rem 0.7rem" },
border: "1px solid rgba(255, 255, 255, 0.09)",
background: "rgba(255, 255, 255, 0.035)",
}}
>
@@ -306,7 +290,8 @@ export default function TitleMenu() {
justifyContent: "center",
gap: "0.2rem",
height: { xs: "2.8rem", sm: "3.3rem" },
// Arrow cluster keycaps are a notch smaller so two rows fit
// Arrow-cluster keycaps are a notch smaller so two rows
// fit.
"& .cluster kbd": {
minWidth: "1.4rem",
height: "1.4rem",
@@ -318,7 +303,12 @@ export default function TitleMenu() {
{t.caps === "cluster-arrows" ? (
<Box
className="cluster"
sx={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "0.2rem" }}
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: "0.2rem",
}}
>
<Box sx={{ display: "flex", gap: "0.22rem", justifyContent: "center" }}>
<Kbd>{"\u2191"}</Kbd>
@@ -339,10 +329,11 @@ export default function TitleMenu() {
</Box>
<Box
sx={{
mt: "0.55rem",
fontSize: "0.72rem",
fontWeight: 600,
letterSpacing: "-0.01em",
mt: "0.5rem",
fontFamily: ANTON,
fontSize: "0.8rem",
letterSpacing: "0.06em",
textTransform: "uppercase",
color: "#fff",
}}
>
@@ -350,10 +341,10 @@ export default function TitleMenu() {
</Box>
<Box
sx={{
mt: "0.18rem",
fontSize: "0.62rem",
mt: "0.16rem",
fontSize: "0.6rem",
fontWeight: 600,
letterSpacing: "0.12em",
letterSpacing: "0.11em",
textTransform: "uppercase",
color: ORANGE,
}}
@@ -366,63 +357,38 @@ export default function TitleMenu() {
<Typography
sx={{
mt: "1rem",
fontSize: "0.68rem",
mt: "0.85rem",
fontFamily: MONO,
fontSize: "0.64rem",
fontWeight: 600,
letterSpacing: "0.08em",
color: "rgba(255, 255, 255, 0.4)",
letterSpacing: "0.12em",
textTransform: "uppercase",
color: "rgba(255, 255, 255, 0.38)",
...row(0.4),
}}
>
{HINTS[tutorialVariant]}
</Typography>
<Box
sx={{
display: "flex",
justifyContent: "center",
mt: "1.7rem",
"@media (max-height: 700px)": { mt: "1.2rem" },
...row(0.48),
}}
>
{HINTS[variant]}
</Typography>
</Box>
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: "1rem",
mt: "1.6rem",
"@media (max-height: 700px)": { mt: "1.1rem" },
width: "100%",
...row(0.56),
}}
>
<ButtonBase
data-cta="1"
onClick={closeMenu}
focusRipple
sx={{
border: `3px solid ${INK}`,
background: ORANGE,
color: INK,
font: "inherit",
fontSize: { xs: "0.95rem", sm: "1.02rem" },
fontWeight: 600,
letterSpacing: "-0.01em",
p: { xs: "0.75rem 1.5rem", sm: "0.85rem 1.9rem" },
borderRadius: "999px",
boxShadow: "0 0 0 3px #fff",
cursor: "pointer",
transition: "transform 0.2s ease, box-shadow 0.2s ease",
"&:hover": {
transform: "translateY(-2px)",
boxShadow: "0 0 0 3px #fff, 0 10px 26px rgba(255, 122, 47, 0.3)",
},
"&:active": {
transform: "translateY(1px)",
boxShadow: "0 0 0 3px #fff",
},
"&.Mui-focusVisible": {
outline: "2px solid #fff",
outlineOffset: "4px",
},
}}
>
{entered ? "Resume" : "Waddle in"}
</ButtonBase>
<ComicButton
scheme="orange"
size="medium"
onDark
data-cta="1"
onClick={closeMenu}
>
{ctaLabel}
</ComicButton>
</Box>
</Box>
</Box>
);
+277
View File
@@ -0,0 +1,277 @@
// Comic-DA primitives, ported from the pollen-website Microduck landing
// (ComicButton.tsx / FancyTitle.tsx): brutal print blocks - a flat face,
// a thick ink keyline and a hard offset plate - plus the Anton display
// voice with the mistracked-VHS title treatment. Lightweight JSX
// reimplementation for the sim; no code is shared across repos on purpose.
import Box from "@mui/material/Box";
export const COMIC_INK = "#101018";
export const CREAM = "#faf8f2";
export const COMIC_ORANGE = "#FF7A2F";
export const COMIC_YELLOW = "#FFD23F";
// The MTV experiment's acid plate colours: on ink grounds the offset plate
// swaps to these so it still reads (ink on ink would vanish).
export const ACID_MAGENTA = "#FF2FA8";
export const ACID_CYAN = "#2FF0E6";
export const ANTON = "'Anton', 'Arial Narrow', Impact, sans-serif";
// Colour presets, same tuning as the landing: `bg` face, `text` label,
// `edge` keyline, `shadow` plate on paper grounds, `shadowOnDark` the acid
// swap for ink grounds.
const SCHEMES = {
orange: { bg: COMIC_ORANGE, text: COMIC_INK, edge: COMIC_INK, shadow: COMIC_INK, shadowOnDark: ACID_MAGENTA },
yellow: { bg: COMIC_YELLOW, text: COMIC_INK, edge: COMIC_INK, shadow: COMIC_INK, shadowOnDark: ACID_CYAN },
ink: { bg: COMIC_INK, text: CREAM, edge: COMIC_INK, shadow: COMIC_ORANGE, shadowOnDark: COMIC_ORANGE },
paper: { bg: CREAM, text: COMIC_INK, edge: COMIC_INK, shadow: COMIC_INK, shadowOnDark: COMIC_ORANGE },
};
// One size step below the landing's "medium": the sim's HUD and modal run
// tighter than a marketing page. "xs" is for persistent HUD controls.
const METRICS = {
xs: { fontSize: "0.78rem", padding: "7px 14px", border: 2, shadow: 4, hoverShadow: 6 },
small: { fontSize: "0.92rem", padding: "9px 20px", border: 3, shadow: 5, hoverShadow: 7 },
medium: { fontSize: "1.15rem", padding: "13px 30px", border: 4, shadow: 7, hoverShadow: 10 },
};
/**
* The landing's CTA button: flat face, thick ink keyline, hard offset
* plate. Hover lifts the face off the plate; pressing sinks it flat onto
* it. `variant="outline"` is the ghost tier - a bare keyline that earns
* its fill and plate on hover. Set `onDark` on ink grounds so the plate
* swaps to the scheme's acid colour.
*/
export function ComicButton({
children,
href,
target,
rel,
onClick,
variant = "filled",
scheme = "orange",
size = "small",
onDark = false,
sx,
...rest
}) {
const colors = SCHEMES[scheme];
const metrics = METRICS[size];
const plate = onDark ? colors.shadowOnDark : colors.shadow;
const isOutline = variant === "outline";
const restShadow = `${metrics.shadow}px ${metrics.shadow}px 0 ${plate}`;
const hoverShadow = `${metrics.hoverShadow}px ${metrics.hoverShadow}px 0 ${plate}`;
const pressedShadow = `0px 0px 0 ${plate}`;
const rootSx = {
position: "relative",
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
gap: "0.5em",
boxSizing: "border-box",
fontFamily: ANTON,
fontWeight: 400,
fontSize: metrics.fontSize,
lineHeight: 1.15,
whiteSpace: "nowrap",
letterSpacing: "0.07em",
textTransform: "uppercase",
textDecoration: "none",
textAlign: "center",
padding: metrics.padding,
border: `${metrics.border}px solid`,
borderRadius: 0,
cursor: "pointer",
WebkitTapHighlightColor: "transparent",
userSelect: "none",
transition:
"transform 0.12s ease, box-shadow 0.12s ease, background-color 0.12s ease, color 0.12s ease",
...(isOutline
? {
background: "transparent",
color: colors.bg,
borderColor: colors.bg,
boxShadow: "none",
"&:hover": {
background: colors.bg,
color: colors.text,
borderColor: colors.edge,
transform: "translate(-2px, -2px)",
boxShadow: restShadow,
},
"&:active": {
background: colors.bg,
color: colors.text,
borderColor: colors.edge,
transform: "translate(2px, 2px)",
boxShadow: pressedShadow,
},
}
: {
background: colors.bg,
color: colors.text,
borderColor: colors.edge,
boxShadow: restShadow,
"&:hover": {
transform: "translate(-2px, -2px)",
boxShadow: hoverShadow,
},
"&:active": {
transform: `translate(${metrics.shadow}px, ${metrics.shadow}px)`,
boxShadow: pressedShadow,
},
}),
"&:focus-visible": {
outline: `3px dashed ${onDark ? CREAM : COMIC_INK}`,
outlineOffset: "5px",
},
"@media (prefers-reduced-motion: reduce)": { transition: "none" },
};
const combinedSx = [rootSx, ...(Array.isArray(sx) ? sx : sx ? [sx] : [])];
return href ? (
<Box component="a" href={href} target={target} rel={rel} onClick={onClick} sx={combinedSx} {...rest}>
{children}
</Box>
) : (
<Box component="button" type="button" onClick={onClick} sx={combinedSx} {...rest}>
{children}
</Box>
);
}
// The MTV stack's knocked-askew per-line rotation cycle, in degrees.
const ROTATIONS = [-1.5, 0.75, -1];
/**
* FancyTitle, compressed: stacked Anton lines with the landing's two
* recipes. `tone="light"` (the cartridge label's cream ground) prints ink
* fill over a hard accent drop plate, outline echoes in bare ink;
* `tone="dark"` adds the cyan/magenta chromatic ghosts. Lines:
* `{ text, variant: "fill" | "outline", color?, scale? }` or plain strings.
*/
export function ComicTitle({ component = "h2", tone = "light", accent = COMIC_ORANGE, fontSize = "2.4rem", lines, sx }) {
const list = lines.map((l) => (typeof l === "string" ? { text: l } : l));
const lineSx = (line, i) => {
const rotate = ROTATIONS[i % ROTATIONS.length];
const outline = line.variant === "outline";
if (tone === "dark") {
return outline
? {
color: "transparent",
WebkitTextStroke: `0.032em ${line.color ?? "#ffffff"}`,
textShadow: `-0.03em 0 0 ${ACID_MAGENTA}`,
transform: `rotate(${rotate}deg)`,
}
: {
color: line.color ?? accent,
textShadow: `0.06em 0.06em 0 ${COMIC_INK}, -0.035em 0 0 ${ACID_CYAN}, 0.035em 0 0 ${ACID_MAGENTA}`,
transform: `rotate(${rotate}deg)`,
};
}
return outline
? {
color: "transparent",
WebkitTextStroke: `0.03em ${line.color ?? COMIC_INK}`,
transform: `rotate(${rotate}deg)`,
}
: {
color: line.color ?? COMIC_INK,
textShadow: `0.05em 0.05em 0 ${accent}`,
transform: `rotate(${rotate}deg)`,
};
};
return (
<Box
component={component}
sx={[
{
m: 0,
fontFamily: ANTON,
fontWeight: 400,
lineHeight: 0.95,
letterSpacing: "normal",
textTransform: "uppercase",
fontSize,
},
...(Array.isArray(sx) ? sx : sx ? [sx] : []),
]}
>
{list.map((line, i) => (
<Box
key={i}
component="span"
className="comic-title-line"
sx={{
display: "block",
...(line.scale ? { fontSize: `${line.scale}em` } : {}),
...lineSx(line, i),
}}
>
{line.text}
</Box>
))}
</Box>
);
}
// Where the ink pools: the ramp runs from that corner/edge toward the
// opposite one (gradient start = densest dots).
const RAMP_DIRECTIONS = {
top: "to bottom",
bottom: "to top",
"top-left": "to bottom right",
"top-right": "to bottom left",
"bottom-left": "to top right",
"bottom-right": "to top left",
};
/**
* Halftone dot ramp, ported from the landing's HalftoneBackdrop: one layer
* per dot size, each masked by a triangle band centred on its own slice of
* the ramp, so the screen frequency never changes - only the dots grow
* toward the `corner`. Decorative only: absolutely positioned over its
* nearest positioned ancestor, pointer-transparent.
*/
export function HalftoneRamp({
color = "rgba(16, 16, 24, 0.06)",
size = 14,
corner = "bottom",
reach = 55,
dots = [3.1, 2.55, 2.05, 1.6, 1.15, 0.7],
sx,
}) {
const towards = RAMP_DIRECTIONS[corner];
const band = reach / dots.length;
return (
<Box
aria-hidden
sx={[
{ position: "absolute", inset: 0, pointerEvents: "none", overflow: "hidden" },
...(Array.isArray(sx) ? sx : sx ? [sx] : []),
]}
>
{dots.map((radius, i) => {
const centre = band * i;
const mask =
i === 0
? `linear-gradient(${towards}, #000 0%, transparent ${centre + band}%)`
: `linear-gradient(${towards}, transparent ${centre - band}%, #000 ${centre}%, transparent ${centre + band}%)`;
return (
<Box
key={radius}
sx={{
position: "absolute",
inset: 0,
backgroundImage: `radial-gradient(${color} ${radius}px, transparent ${radius + 0.7}px)`,
backgroundSize: `${size}px ${size}px`,
maskImage: mask,
WebkitMaskImage: mask,
}}
/>
);
})}
</Box>
);
}