chore(app): refresh npm lockfile metadata

This commit is contained in:
2026-10-27 16:54:17 +08:00
commit 13dfcfba13
212 changed files with 20071 additions and 0 deletions
+89
View File
@@ -0,0 +1,89 @@
// App shell: layers in z order - scene canvas (1), halftone (2), CRT (5),
// HUD + touch overlay (9-12), BIOS readout (20), title menu (30). Also owns
// the pre-game device detection (gamepad, touch) and the title -> enter
// flow. The title menu carries its own loading gate (single central
// spinner), so no separate preboot veil.
import { useEffect } from "react";
import GameCanvas from "./scene/GameCanvas.jsx";
import { Halftone, CrtOverlay } from "./ui/Overlays.jsx";
import Hud from "./ui/Hud.jsx";
import TouchOverlay from "./ui/TouchOverlay.jsx";
import BiosOverlay from "./ui/BiosOverlay.jsx";
import TitleMenu from "./ui/TitleMenu.jsx";
import { useGame } from "./store.js";
export default function App() {
useEffect(() => {
const params = new URLSearchParams(location.search);
// Gamepad presence for the tutorial variant, before the game controller
// takes over polling (the game loop keeps mirroring it afterwards).
const pollPad = () => {
const gp = [...(navigator.getGamepads?.() ?? [])].find((p) => p && p.connected);
useGame.setState({ padConnected: !!gp });
};
window.addEventListener("gamepadconnected", pollPad);
window.addEventListener("gamepaddisconnected", pollPad);
pollPad();
// Touch detection, latching: (pointer: coarse) OR any real touch proves
// the device (DevTools device modes and hybrid laptops often fail the
// media query). __microduckTouched hands the proof to controls/touch.js
// which boots later. ?touch=1 forces the thumbs on any device.
const coarse = matchMedia("(pointer: coarse)");
const armTouch = () => {
window.__microduckTouched = true;
useGame.setState({ touchMode: true });
};
const onCoarse = () => coarse.matches && armTouch();
if (coarse.matches) armTouch();
else coarse.addEventListener("change", onCoarse);
window.addEventListener("touchstart", armTouch, { once: true, passive: true });
if (params.get("touch") === "1") armTouch();
// ?move=<ref>: request a community move (Academy D7). ref is an
// "org/repo" Hub move, "session:<id>[:<round>]" (a private Academy run,
// served same-origin) or a direct .onnx URL. ?policy= is the legacy
// alias, and ?session=<id>[&round=<r>] is sugar for move=session:<id>:<r>.
// Only the request is recorded here; the game loads it after boot
// (never blocking it) and flips the status to active/error itself.
let moveRef = params.get("move") || params.get("policy");
if (!moveRef && params.get("session")) {
const round = params.get("round");
moveRef = `session:${params.get("session")}${round ? `:${round}` : ""}`;
}
if (moveRef) {
useGame.setState({
customPolicy: { ref: moveRef, name: moveRef, status: "loading" },
});
}
// The title menu opens right away and holds its own loading gate
// (central spinner) until logo, fonts, duck stage and game boot are
// in. ?boot=1 skips the title entirely - testing hook.
if (params.get("boot") === "1") {
useGame.setState({ prebootDone: true, entered: true, menuOpen: false });
} else {
useGame.setState({ prebootDone: true, menuOpen: true });
}
return () => {
window.removeEventListener("gamepadconnected", pollPad);
window.removeEventListener("gamepaddisconnected", pollPad);
coarse.removeEventListener("change", onCoarse);
window.removeEventListener("touchstart", armTouch);
};
}, []);
return (
<>
<GameCanvas />
<Halftone />
<CrtOverlay />
<Hud />
<TouchOverlay />
<BiosOverlay />
<TitleMenu />
</>
);
}
+301
View File
@@ -0,0 +1,301 @@
// Arena visuals: the infinite Tron grid floor and the four wall grid
// planes, ported verbatim from the pre-React rl.js. Both carry a uReveal
// uniform for the entrance draw-in (driven by ceremony.js).
import * as THREE from "three";
import {
ARENA_HALF, ARENA_WALL_H, ARENA_WALL_T, GRID_SECTION, RELIEF_BUMPS,
} from "./constants.js";
// Infinite shader grid, ported from drei's <Grid>: anti-aliased world-space
// lines at cell/section frequencies with a radial fade around the duck.
// Lines derive from world coordinates, so re-centering the mesh under the
// camera target every frame makes the grid effectively infinite without any
// visible swimming.
export function makeInfiniteGrid() {
const material = new THREE.ShaderMaterial({
transparent: true,
depthWrite: false,
uniforms: {
uCell: { value: 0.1 },
uSection: { value: GRID_SECTION },
uCellColor: { value: new THREE.Color(0x8e8371) },
uSectionColor: { value: new THREE.Color(0xffb366) },
uFadeDist: { value: 3.0 },
uFocus: { value: new THREE.Vector3() },
// Entrance draw-in progress; 1 = steady state (branch skipped).
// Starts at 0: the world stays hidden behind the welcome modal and
// the BIOS readout until playBios cues startEntrance.
uReveal: { value: 0.0 },
// Relief: 0 = flat, 1 = bumps at full height. Driven by the game's
// relief toggle, mirroring the MuJoCo heightfield's z-size so the
// visual surface and the physics surface are the same function.
uTopoScale: { value: 0.0 },
// (cx, cz, height, radius) per bump, in three.js world coords
// (MJCF y -> -z done here once).
uBumps: {
value: RELIEF_BUMPS.map(
([cx, cy, h, r]) => new THREE.Vector4(cx, -cy, h, r),
),
},
},
vertexShader: /* glsl */ `
#define NBUMPS ${RELIEF_BUMPS.length}
varying vec3 vWorld;
uniform float uTopoScale;
uniform vec4 uBumps[NBUMPS];
// Same analytic relief as the physics heightfield (game.js topoH):
// a sum of cosine bumps, displacing the grid surface itself so the
// floor genuinely deforms - lines flow up the slopes for free since
// the fragment shader draws them from world xz.
float topoH(vec2 p) {
float H = 0.0;
for (int i = 0; i < NBUMPS; i++) {
float u = distance(p, uBumps[i].xy) / uBumps[i].w;
if (u < 1.0) H += uBumps[i].z * (0.5 + 0.5 * cos(3.14159265 * u));
}
return H;
}
void main() {
vec4 w = modelMatrix * vec4(position, 1.0);
if (uTopoScale > 0.0) w.y += topoH(w.xz) * uTopoScale;
vWorld = w.xyz;
gl_Position = projectionMatrix * viewMatrix * w;
}
`,
fragmentShader: /* glsl */ `
varying vec3 vWorld;
uniform float uCell, uSection, uFadeDist, uReveal;
uniform vec3 uCellColor, uSectionColor, uFocus;
// Tron-style line: a thicker antialiased core plus a faint, much
// wider halo added on top (squared falloff keeps it a whisper of a
// glow rather than a bloom wash).
float lineProf(float g) {
float core = 1.0 - smoothstep(0.0, 1.8, g);
float halo = 1.0 - smoothstep(0.0, 7.0, g);
return core + halo * halo * 0.22;
}
float gridLine(vec2 p, float size) {
vec2 r = p / size;
vec2 g = abs(fract(r - 0.5) - 0.5) / fwidth(r);
return lineProf(min(g.x, g.y));
}
// Entrance draw-in: one family of parallel lines, drawn line by line.
// id picks the line, "along" runs down its length. Each line waits
// out its own hashed delay, then extends from the origin outward with
// a hard front. Returns (mask, head): head marks the bright segment
// right behind the draw front while the line is still growing.
vec2 drawLine(float id, float along, float t0, float spread, float dur, float maxLen) {
float jit = fract(sin(id * 127.1) * 43758.5453);
float grow = clamp((uReveal - t0 - jit * spread) / dur, 0.0, 1.0);
float len = grow * maxLen;
float a = abs(along);
float mask = 1.0 - smoothstep(len - 0.05, len, a);
float head = (1.0 - smoothstep(0.0, 0.6, len - a)) * mask
* step(0.001, grow) * (1.0 - step(0.999, grow));
return vec2(mask, head);
}
void main() {
float cell = gridLine(vWorld.xz, uCell);
// Section lattice shifted half a cell: with 5 sections across the
// 3 m arena (odd count) this centers a CELL on the origin and puts
// section lines exactly on the walls at +-1.5.
vec2 pSec = vWorld.xz + 0.5 * uSection;
float section = gridLine(pSec, uSection);
float d = distance(vWorld.xz, uFocus.xz);
float fade = pow(clamp(1.0 - d / uFadeDist, 0.0, 1.0), 1.6);
vec3 col = mix(uCellColor, uSectionColor, clamp(section, 0.0, 1.0));
float alpha = min(max(section * 0.6, cell * 0.4) * fade, 1.0);
// Entrance: only the bright section lines get the line-by-line draw
// (staggered, with a hot draw head); the fine cells just fade in
// over the reveal's second half - drawing every small line reads as
// visual noise. lineProf(min(gx, gy)) == max of per-axis profiles
// (profile is monotonic) and the cell fade lands on exactly the
// steady-state cell term, so at uReveal 1 this branch equals the
// formula above exactly (and is skipped).
if (uReveal < 1.0) {
vec2 rs = pSec / uSection;
vec2 gs = abs(fract(rs - 0.5) - 0.5) / fwidth(rs);
// Const-x lines run along z and vice versa; the offset
// decorrelates the two families' hashed delays.
vec2 sx = drawLine(floor(rs.x + 0.5), vWorld.z, 0.00, 0.30, 0.35, 8.0);
vec2 sz = drawLine(floor(rs.y + 0.5) + 57.0, vWorld.x, 0.05, 0.30, 0.35, 8.0);
float secR = max(lineProf(gs.x) * sx.x, lineProf(gs.y) * sz.x);
float cellR = cell * smoothstep(0.5, 1.0, uReveal);
float headGlow = max(lineProf(gs.x) * sx.y, lineProf(gs.y) * sz.y);
col = mix(uCellColor, uSectionColor, clamp(secR, 0.0, 1.0));
alpha = min(max(secR * 0.6, cellR * 0.4) * fade, 1.0);
// Bright draw head: a short white-hot tip sells the "drawing" read.
headGlow = clamp(headGlow, 0.0, 1.0);
col = mix(col, vec3(1.0, 0.86, 0.55), headGlow * 0.8);
alpha = min(alpha + headGlow * fade * 0.5, 1.0);
}
if (alpha < 0.004) discard;
gl_FragColor = vec4(col, alpha);
}
`,
});
// Subdivided so the relief displacement has vertices to push: ~12 cm
// steps, plenty for the gentle bump radii (>= 0.5 m). The displacement
// is computed in world space, so the per-frame recentering under the
// camera target doesn't move the bumps.
const mesh = new THREE.Mesh(new THREE.PlaneGeometry(30, 30, 256, 256), material);
mesh.rotation.x = -Math.PI / 2;
return mesh;
}
// Arena walls, drawn in the same grid language as the floor: identical
// cell/section lines from world coordinates, same radial fade around the
// duck, plus a vertical fade toward the top edge so the walls read as a
// light enclosure instead of solid slabs.
function makeWallGridMaterial(alongX) {
return new THREE.ShaderMaterial({
transparent: true,
depthWrite: false,
side: THREE.DoubleSide,
uniforms: {
uCell: { value: 0.1 },
uSection: { value: GRID_SECTION },
uCellColor: { value: new THREE.Color(0x8e8371) },
uSectionColor: { value: new THREE.Color(0xffb366) },
// Gentler radial fade than the floor: the walls sit 1.5+ m from the
// duck by construction and would vanish with the floor's 3 m fade.
uFadeDist: { value: 5.0 },
uFocus: { value: new THREE.Vector3() },
uWallH: { value: ARENA_WALL_H },
uAlongX: { value: alongX ? 1.0 : 0.0 },
// Entrance draw-in progress; 1 = steady state (branch skipped).
// Starts at 0, same as the floor grid: hidden until startEntrance.
uReveal: { value: 0.0 },
},
vertexShader: /* glsl */ `
varying vec3 vWorld;
void main() {
vec4 w = modelMatrix * vec4(position, 1.0);
vWorld = w.xyz;
gl_Position = projectionMatrix * viewMatrix * w;
}
`,
fragmentShader: /* glsl */ `
varying vec3 vWorld;
uniform float uCell, uSection, uFadeDist, uWallH, uAlongX, uReveal;
uniform vec3 uCellColor, uSectionColor, uFocus;
// Same Tron-style core + faint halo as the floor grid.
float lineProf(float g) {
float core = 1.0 - smoothstep(0.0, 1.8, g);
float halo = 1.0 - smoothstep(0.0, 7.0, g);
return core + halo * halo * 0.22;
}
float gridLine(vec2 p, float size) {
vec2 r = p / size;
vec2 g = abs(fract(r - 0.5) - 0.5) / fwidth(r);
return lineProf(min(g.x, g.y));
}
// Same line-by-line draw as the floor grid (see its comments).
vec2 drawLine(float id, float along, float t0, float spread, float dur, float maxLen) {
float jit = fract(sin(id * 127.1) * 43758.5453);
float grow = clamp((uReveal - t0 - jit * spread) / dur, 0.0, 1.0);
float len = grow * maxLen;
float a = abs(along);
float mask = 1.0 - smoothstep(len - 0.05, len, a);
float head = (1.0 - smoothstep(0.0, 0.35, len - a)) * mask
* step(0.001, grow) * (1.0 - step(0.999, grow));
return vec2(mask, head);
}
void main() {
// Wall surface coords: the in-plane horizontal world axis + height.
float h = mix(vWorld.z, vWorld.x, uAlongX);
vec2 p = vec2(h, vWorld.y);
float cell = gridLine(p, uCell);
// Horizontal axis shifted half a section to match the floor's odd
// lattice (vertical section lines meet the floor's at the base);
// the height axis keeps its base line at y = 0.
vec2 pSec = vec2(p.x + 0.5 * uSection, p.y);
float section = gridLine(pSec, uSection);
float d = distance(vWorld.xz, uFocus.xz);
float fade = pow(clamp(1.0 - d / uFadeDist, 0.0, 1.0), 1.6);
float vert = 1.0 - clamp(vWorld.y / uWallH, 0.0, 1.0);
vec3 col = mix(uCellColor, uSectionColor, clamp(section, 0.0, 1.0));
float alpha = min(max(section * 0.9, cell * 0.6) * fade * (0.3 + 0.7 * vert), 1.0);
// Entrance: section lines only - horizontals zip out from the
// wall's center, verticals rise from the ground, each with a
// hashed delay; the fine cells fade in over the reveal's second
// half. Same steady-state equivalence argument as the floor grid.
if (uReveal < 1.0) {
vec2 rs = pSec / uSection;
vec2 gs = abs(fract(rs - 0.5) - 0.5) / fwidth(rs);
// Const-height lines run along h (grow from center outward);
// const-h lines run along y (grow up from the ground).
vec2 sh = drawLine(floor(rs.y + 0.5), p.x, 0.00, 0.30, 0.40, 2.0);
vec2 sv = drawLine(floor(rs.x + 0.5) + 31.0, p.y, 0.30, 0.30, 0.30, uWallH);
float secR = max(lineProf(gs.y) * sh.x, lineProf(gs.x) * sv.x);
float cellR = cell * smoothstep(0.5, 1.0, uReveal);
float headGlow = max(lineProf(gs.y) * sh.y, lineProf(gs.x) * sv.y);
col = mix(uCellColor, uSectionColor, clamp(secR, 0.0, 1.0));
alpha = min(max(secR * 0.9, cellR * 0.6) * fade * (0.3 + 0.7 * vert), 1.0);
headGlow = clamp(headGlow, 0.0, 1.0);
col = mix(col, vec3(1.0, 0.86, 0.55), headGlow * 0.8);
alpha = min(alpha + headGlow * fade * 0.5, 1.0);
}
if (alpha < 0.004) discard;
gl_FragColor = vec4(col, alpha);
}
`,
});
}
// Entrance draw-in cue schedule, for the ceremony's per-line audio blips.
// Replicates the shaders' hashed stagger EXACTLY (same hash, same t0 /
// spread constants, same line ids as drawLine's floor(rs + 0.5)), so each
// blip lands the instant its line starts drawing. Times are normalized to
// the respective reveal (0..1); the ceremony maps them to seconds with its
// own grid/wall reveal durations. `u` is the line's jitter, reused by the
// audio side for per-line pitch variation. The four walls share one id
// space, so their lines draw (and blip) in unison - one cue each.
const jitHash = (x) => {
const s = Math.sin(x * 127.1) * 43758.5453;
return s - Math.floor(s);
};
export function entranceLineCues() {
const grid = [];
const walls = [];
// Floor: 6 section lines per axis (world x in {-1.5..1.5} step 0.6 maps
// to ids -2..3); the z family is offset by 57 in the shader.
for (let i = -2; i <= 3; i++) {
const jx = jitHash(i);
const jz = jitHash(i + 57);
grid.push({ at: 0.00 + jx * 0.30, u: jx });
grid.push({ at: 0.05 + jz * 0.30, u: jz });
}
// Walls: one horizontal section line (the y = 0 base, id 0) and 6
// verticals (ids -2..3 offset by 31), per the 0.25 m wall height.
walls.push({ at: 0.00 + jitHash(0) * 0.30, u: jitHash(0) });
for (let i = -2; i <= 3; i++) {
const j = jitHash(i + 31);
walls.push({ at: 0.30 + j * 0.30, u: j });
}
return { grid, walls };
}
// The four wall planes at their inner faces (three coords: MJCF x -> x,
// MJCF y -> -z). Returns the meshes plus their materials (the ceremony and
// the per-frame focus update both need the material list).
export function makeArenaWalls() {
const wallMats = [];
const wallMeshes = [];
const wallLen = 2 * (ARENA_HALF + ARENA_WALL_T);
const wallDefs = [
{ x: ARENA_HALF, z: 0, rotY: -Math.PI / 2, alongX: false },
{ x: -ARENA_HALF, z: 0, rotY: Math.PI / 2, alongX: false },
{ x: 0, z: ARENA_HALF, rotY: Math.PI, alongX: true },
{ x: 0, z: -ARENA_HALF, rotY: 0, alongX: true },
];
for (const w of wallDefs) {
const mat = makeWallGridMaterial(w.alongX);
wallMats.push(mat);
const mesh = new THREE.Mesh(new THREE.PlaneGeometry(wallLen, ARENA_WALL_H), mat);
mesh.position.set(w.x, ARENA_WALL_H / 2, w.z);
mesh.rotation.y = w.rotY;
wallMeshes.push(mesh);
}
return { wallMats, wallMeshes };
}
+581
View File
@@ -0,0 +1,581 @@
// Game audio: one shared AudioContext behind a master gain, three buses
// (ambient / sfx / voice). Plain functions and maps, no classes, matching
// the imperative game core. The voice bus carries the existing quack and
// wheee (the stars of the mix); sfx carries footsteps / ball thumps / UI
// clicks / the entrance sweep; ambient carries the arcade-room hum bed.
//
// Samples (CC0, Kenney.nl): footsteps and ball thumps from "Impact Sounds",
// UI clicks from "Interface Sounds" - trimmed to mono 22.05 kHz wav in
// public/assets/sfx/. The CRT entrance sweep, the ambient hum and the
// roller rumble are synthesized (oscillators + filtered noise): zero
// payload and a better fit for the retro DA.
//
// Spatialization is plain Web Audio: the context listener follows the
// camera every frame and cheap equalpower PannerNodes act as emitters on
// the duck and the ball (footsteps, thumps and the roller rumble pan and
// attenuate with the chase cam). Voice and UI stay non-spatial.
import { signed } from "./signed.js";
// ── Master kill switch ────────────────────────────────────────────────
// Kill switch: flip to true to silence the whole mix (every public entry
// point early-returns, master gain pinned to 0, context never resumed).
// Node-returning helpers (busNode, createEmitter) keep building their
// graph either way so callers stay untouched.
const SOUND_DISABLED = true;
// ── Context, master, buses ────────────────────────────────────────────
const MASTER_LEVEL = 0.9;
const BUS_LEVELS = { ambient: 1, sfx: 0.9, voice: 1 };
const MUTE_KEY = "microduck-muted";
let ctx = null;
let master = null;
const buses = {}; // name -> GainNode
let muted = false;
try { muted = localStorage.getItem(MUTE_KEY) === "1"; } catch { /* private mode */ }
function unlockOnce() {
if (ctx?.state === "suspended") ctx.resume().catch(() => {});
}
export function audioCtx() {
if (ctx) return ctx;
ctx = new (window.AudioContext ?? window.webkitAudioContext)();
master = ctx.createGain();
master.gain.value = SOUND_DISABLED || muted ? 0 : MASTER_LEVEL;
master.connect(ctx.destination);
for (const [name, level] of Object.entries(BUS_LEVELS)) {
const g = ctx.createGain();
g.gain.value = level;
g.connect(master);
buses[name] = g;
}
// Autoplay policy: resume on the first user gesture (the Waddle-in
// click normally lands here; keyboard covers the ?boot=1 test path).
// While sound is disabled the context is never resumed, so the
// suspended-state guards below keep every one-shot silent too.
if (!SOUND_DISABLED) {
window.addEventListener("pointerdown", unlockOnce, { passive: true });
window.addEventListener("keydown", unlockOnce);
}
return ctx;
}
export function busNode(name) {
audioCtx();
return buses[name];
}
// ── Master mute (HUD toggle, persisted) ───────────────────────────────
// Ramped over ~50 ms instead of a hard cut; the sources keep running so
// unmuting picks the mix back up exactly where it was.
export const isMuted = () => muted;
export function setMuted(next) {
if (SOUND_DISABLED) return;
muted = !!next;
try { localStorage.setItem(MUTE_KEY, muted ? "1" : "0"); } catch { /* private mode */ }
if (!ctx) return;
master.gain.setTargetAtTime(muted ? 0 : MASTER_LEVEL, ctx.currentTime, 0.017);
}
// ── Sample bank (decode-once cache, random takes per name) ────────────
const SFX_TAKES = { step: 5, thump: 3, click: 2 };
const bufCache = new Map(); // url -> Promise<AudioBuffer>
function bufferFor(url) {
let p = bufCache.get(url);
if (!p) {
p = fetch(url)
.then((r) => r.arrayBuffer())
.then((ab) => audioCtx().decodeAudioData(ab));
bufCache.set(url, p);
}
return p;
}
const takeUrl = (name, i) => signed(`./assets/sfx/${name}_${"abcde"[i]}.wav`);
export function preloadSfx() {
if (SOUND_DISABLED) return;
for (const [name, n] of Object.entries(SFX_TAKES)) {
for (let i = 0; i < n; i++) bufferFor(takeUrl(name, i)).catch(() => {});
}
}
// Fire-and-forget one-shot. `out` routes to an emitter panner (spatial);
// otherwise the sound lands on the flat sfx bus.
export function playSfx(name, { gain = 1, rate = 1, out = null } = {}) {
if (SOUND_DISABLED) return;
const c = audioCtx();
if (c.state === "suspended") return; // pre-gesture: stay silent, don't queue
const take = (Math.random() * SFX_TAKES[name]) | 0;
bufferFor(takeUrl(name, take)).then((buf) => {
const src = c.createBufferSource();
src.buffer = buf;
src.playbackRate.value = rate;
const g = c.createGain();
g.gain.value = gain;
src.connect(g);
g.connect(out ?? buses.sfx);
src.onended = () => g.disconnect();
src.start();
}).catch(() => {});
}
// Decoded playback for arbitrary URLs (the colourway voice banks): same
// cache, routed to a bus - replaces the old HTMLAudio chirp path so the
// quack sits behind the master gain like everything else.
export function playUrl(url, { bus = "voice", gain = 1, rate = 1 } = {}) {
if (SOUND_DISABLED) return;
const c = audioCtx();
if (c.state === "suspended") return;
bufferFor(url).then((buf) => {
const src = c.createBufferSource();
src.buffer = buf;
src.playbackRate.value = rate;
const g = c.createGain();
g.gain.value = gain;
src.connect(g);
g.connect(buses[bus]);
src.onended = () => g.disconnect();
src.start();
}).catch(() => {});
}
export function uiClick() {
playSfx("click", { gain: 0.16, rate: 0.95 + Math.random() * 0.1 });
}
// ── Spatial listener + emitters ───────────────────────────────────────
// Listener follows the three.js camera (three world coords). Emitters are
// equalpower panners: cheap, and plenty for "the duck is over there".
const _fwd = { x: 0, y: 0, z: -1 };
export function updateListener(camera) {
if (!ctx || ctx.state === "suspended") return;
const l = ctx.listener;
const e = camera.matrixWorld.elements;
// Camera forward = -Z column of the world matrix, up = +Y column.
_fwd.x = -e[8]; _fwd.y = -e[9]; _fwd.z = -e[10];
const t = ctx.currentTime;
if (l.positionX) {
l.positionX.setTargetAtTime(e[12], t, 0.02);
l.positionY.setTargetAtTime(e[13], t, 0.02);
l.positionZ.setTargetAtTime(e[14], t, 0.02);
l.forwardX.setTargetAtTime(_fwd.x, t, 0.02);
l.forwardY.setTargetAtTime(_fwd.y, t, 0.02);
l.forwardZ.setTargetAtTime(_fwd.z, t, 0.02);
l.upX.setTargetAtTime(e[4], t, 0.02);
l.upY.setTargetAtTime(e[5], t, 0.02);
l.upZ.setTargetAtTime(e[6], t, 0.02);
} else {
l.setPosition(e[12], e[13], e[14]);
l.setOrientation(_fwd.x, _fwd.y, _fwd.z, e[4], e[5], e[6]);
}
}
export function createEmitter({ refDistance = 0.6 } = {}) {
const c = audioCtx();
const panner = c.createPanner();
panner.panningModel = "equalpower";
panner.distanceModel = "inverse";
panner.refDistance = refDistance;
panner.rolloffFactor = 1.1;
panner.connect(buses.sfx);
return {
node: panner,
setPosition(x, y, z) {
if (panner.positionX) {
const t = c.currentTime;
panner.positionX.setTargetAtTime(x, t, 0.03);
panner.positionY.setTargetAtTime(y, t, 0.03);
panner.positionZ.setTargetAtTime(z, t, 0.03);
} else {
panner.setPosition(x, y, z);
}
},
};
}
// ── Ambient bed (synthesized arcade-room hum) ─────────────────────────
// Mains hum (60 Hz + weak 120 Hz octave) plus a slow-breathing bed of
// lowpassed noise. Sits VERY low in the mix. The whole bed runs through a
// duck filter + duck gain automated when the pause/title overlay opens.
const AMBIENT_LEVEL = 0.05;
const AMBIENT_DUCKED = 0.018;
let ambient = null; // { duckGain, duckFilter }
export function startAmbient() {
if (SOUND_DISABLED || ambient) return;
const c = audioCtx();
const duckFilter = c.createBiquadFilter();
duckFilter.type = "lowpass";
duckFilter.frequency.value = 18000;
const duckGain = c.createGain();
duckGain.gain.value = 0; // fade in below
duckFilter.connect(duckGain);
duckGain.connect(buses.ambient);
const hum = c.createOscillator();
hum.type = "sine";
hum.frequency.value = 60;
const humG = c.createGain();
humG.gain.value = 0.5;
hum.connect(humG);
humG.connect(duckFilter);
const hum2 = c.createOscillator();
hum2.type = "triangle";
hum2.frequency.value = 120;
const hum2G = c.createGain();
hum2G.gain.value = 0.14;
hum2.connect(hum2G);
hum2G.connect(duckFilter);
const noise = c.createBufferSource();
noise.buffer = noiseBuffer(c, 2.0);
noise.loop = true;
const noiseF = c.createBiquadFilter();
noiseF.type = "lowpass";
noiseF.frequency.value = 260;
const noiseG = c.createGain();
noiseG.gain.value = 0.5;
noise.connect(noiseF);
noiseF.connect(noiseG);
noiseG.connect(duckFilter);
// Slow breathing on the noise bed (~0.08 Hz) so the room feels alive.
const lfo = c.createOscillator();
lfo.frequency.value = 0.08;
const lfoG = c.createGain();
lfoG.gain.value = 0.15;
lfo.connect(lfoG);
lfoG.connect(noiseG.gain);
hum.start();
hum2.start();
noise.start();
lfo.start();
duckGain.gain.setTargetAtTime(AMBIENT_LEVEL, c.currentTime, 1.2);
ambient = { duckGain, duckFilter };
}
export function setAmbientDucked(ducked) {
if (!ambient) return;
const t = ctx.currentTime;
ambient.duckGain.gain.setTargetAtTime(ducked ? AMBIENT_DUCKED : AMBIENT_LEVEL, t, 0.25);
ambient.duckFilter.frequency.setTargetAtTime(ducked ? 300 : 18000, t, 0.25);
}
function noiseBuffer(c, seconds) {
const n = (c.sampleRate * seconds) | 0;
const buf = c.createBuffer(1, n, c.sampleRate);
const d = buf.getChannelData(0);
for (let i = 0; i < n; i++) d[i] = Math.random() * 2 - 1;
return buf;
}
// ── Materialize sweeps (phase-locked to the wireframe FX) ─────────────
// fx-wireframe.js runs two overlapping passes over totalS seconds (duck:
// 0.9 s): a wireframe scan line over the first 2/3 and a trailing
// solidify line over the last 2/3, BOTH driven by the same ease-out
// (1 - (1-x)^2): the line launches at full speed and decelerates into
// the top. The pitch of each layer follows that exact curve (sampled
// into setValueCurveAtTime), so the sweep rushes then settles exactly
// like the line the player watches - not a straight climb through it.
//
// scan [0 .. 2/3 T] square, 150 -> 1500 Hz along the fx ease
// solid [1/3 T .. T] triangle an octave down, same curve, trailing
// T resolve: sine drop thunk + soft high ping
//
// Props reuse the same voice via playPropSweep: their fx stretches the
// timeline by sqrt(size) (see fx-wireframe REF_SPAN), so the duration
// itself encodes the target's size - the sweep divides its pitch by
// that stretch, and big objects (arcade cabinet) materialize DEEPER
// and longer while small ones chirp through quickly.
const FX_EASE = (x) => 1 - (1 - x) * (1 - x); // fx-wireframe's ease()
const FX_BASE_S = 0.9; // fx TOTAL_S before size stretch
function easedPitchCurve(f0, f1, n = 48) {
const arr = new Float32Array(n);
for (let i = 0; i < n; i++) arr[i] = f0 * (f1 / f0) ** FX_EASE(i / (n - 1));
return arr;
}
// One materialize voice. level scales every layer; pitchK divides the
// whole sweep's register (bigger target = lower); shimmer + ping are the
// duck's hero garnish, props skip them.
function materializeSweep(c, { totalS, level = 1, pitchK = 1, hero = true }) {
const T = Math.max(0.3, totalS);
const t0 = c.currentTime + 0.01;
const scanEnd = t0 + T * (2 / 3);
const solidStart = t0 + T * (1 / 3);
const tEnd = t0 + T;
const k = 1 / pitchK;
const out = c.createGain();
out.gain.value = level;
const tone = c.createBiquadFilter();
tone.type = "lowpass";
tone.frequency.value = 5200; // tame the squares' buzz, keep the bite
tone.connect(out);
out.connect(buses.sfx);
// Static tick right as the scan cues.
const tick = c.createBufferSource();
tick.buffer = noiseBuffer(c, 0.06);
const tickF = c.createBiquadFilter();
tickF.type = "highpass";
tickF.frequency.value = 2500;
const tickG = c.createGain();
tickG.gain.setValueAtTime(0.1, t0);
tickG.gain.exponentialRampToValueAtTime(0.001, t0 + 0.06);
tick.connect(tickF);
tickF.connect(tickG);
tickG.connect(out);
tick.start(t0);
// Scan pass: rising square riding the scan line's exact ease-out.
const scan = c.createOscillator();
scan.type = "square";
scan.frequency.setValueCurveAtTime(
easedPitchCurve(150 * k, 1500 * k), t0, T * (2 / 3),
);
const scanG = c.createGain();
scanG.gain.setValueAtTime(0, t0);
scanG.gain.linearRampToValueAtTime(0.14, t0 + 0.03);
scanG.gain.setValueAtTime(0.14, scanEnd - 0.05);
scanG.gain.exponentialRampToValueAtTime(0.001, scanEnd + 0.08);
scan.connect(scanG);
scanG.connect(tone);
scan.start(t0);
scan.stop(scanEnd + 0.1);
// Solidify pass: same eased climb an octave down, trailing like the
// second line, swelling as the target fills in solid.
const solid = c.createOscillator();
solid.type = "triangle";
solid.frequency.setValueCurveAtTime(
easedPitchCurve(85 * k, 760 * k), solidStart, T * (2 / 3),
);
const solidG = c.createGain();
solidG.gain.setValueAtTime(0, solidStart);
solidG.gain.linearRampToValueAtTime(0.08, solidStart + 0.06);
solidG.gain.linearRampToValueAtTime(0.16, tEnd - 0.05);
solidG.gain.exponentialRampToValueAtTime(0.001, tEnd + 0.06);
solid.connect(solidG);
solidG.connect(tone);
solid.start(solidStart);
solid.stop(tEnd + 0.1);
if (hero) {
// Hologram shimmer: airy bandpassed noise, centre frequency easing
// up with the reveal like everything else.
const shimmer = c.createBufferSource();
shimmer.buffer = noiseBuffer(c, T);
const shimF = c.createBiquadFilter();
shimF.type = "bandpass";
shimF.frequency.setValueCurveAtTime(
easedPitchCurve(1800 * k, 5200 * k), t0, T,
);
shimF.Q.value = 1.2;
const shimG = c.createGain();
shimG.gain.setValueAtTime(0, t0);
shimG.gain.linearRampToValueAtTime(0.05, t0 + 0.1);
shimG.gain.setValueAtTime(0.05, tEnd - 0.15);
shimG.gain.linearRampToValueAtTime(0, tEnd);
shimmer.connect(shimF);
shimF.connect(shimG);
shimG.connect(out);
shimmer.start(t0);
}
// Resolve: pitch-drop thunk right when the solidify line clears the
// top and the real materials land. Deeper for bigger targets.
const thunk = c.createOscillator();
thunk.type = "sine";
thunk.frequency.setValueAtTime(170 * k, tEnd);
thunk.frequency.exponentialRampToValueAtTime(62 * k, tEnd + 0.13);
const thunkG = c.createGain();
thunkG.gain.setValueAtTime(hero ? 0.3 : 0.22, tEnd);
thunkG.gain.exponentialRampToValueAtTime(0.001, tEnd + 0.22);
thunk.connect(thunkG);
thunkG.connect(out);
thunk.start(tEnd);
thunk.stop(tEnd + 0.25);
if (hero) {
const ping = c.createOscillator();
ping.type = "sine";
ping.frequency.value = 1320;
const pingG = c.createGain();
pingG.gain.setValueAtTime(0.07, tEnd);
pingG.gain.exponentialRampToValueAtTime(0.001, tEnd + 0.3);
ping.connect(pingG);
pingG.connect(out);
ping.start(tEnd);
ping.stop(tEnd + 0.32);
ping.onended = () => out.disconnect();
} else {
thunk.onended = () => out.disconnect();
}
}
// The duck's hero sweep (entrance and every respawn scan-up).
export function playEntranceSweep(totalS = 0.9) {
if (SOUND_DISABLED) return;
const c = audioCtx();
if (c.state === "suspended") return;
materializeSweep(c, { totalS, level: 1, pitchK: 1, hero: true });
}
// One prop materializing (arcade cabinet, boombox...). The fx stretches
// its timeline by sqrt(size), so recover that stretch from the duration
// and drop the register by it: a 2.2 s cabinet sweeps ~2.5x deeper than
// the duck, a duck-sized prop sounds like a quieter duck. A tiny random
// detune keeps staggered props from phasing into one thick chord.
export function playPropSweep(totalS = 0.9) {
if (SOUND_DISABLED) return;
const c = audioCtx();
if (c.state === "suspended") return;
const durK = Math.max(1, totalS / FX_BASE_S);
const detune = 2 ** ((Math.random() - 0.5) * 0.16);
materializeSweep(c, {
totalS,
level: 0.4,
pitchK: durK * detune,
hero: false,
});
}
// ── BIOS / menu one-shots (synthesized, retro POST language) ──────────
// All guarded on a suspended context: the BIOS replay only starts after
// the enter click (the unlock gesture), but a gamepad-only entry can
// leave the context locked - then these simply stay silent.
// Single POST beep, the classic "one beep = all good".
export function playBiosBeep() {
if (SOUND_DISABLED) return;
const c = audioCtx();
if (c.state === "suspended") return;
const t0 = c.currentTime + 0.01;
const osc = c.createOscillator();
osc.type = "square";
osc.frequency.value = 940;
const g = c.createGain();
g.gain.setValueAtTime(0, t0);
g.gain.linearRampToValueAtTime(0.08, t0 + 0.008);
g.gain.setValueAtTime(0.08, t0 + 0.1);
g.gain.exponentialRampToValueAtTime(0.001, t0 + 0.16);
osc.connect(g);
g.connect(buses.sfx);
osc.start(t0);
osc.stop(t0 + 0.18);
osc.onended = () => g.disconnect();
}
// Teletype tick, one per printed POST line. Whisper-level.
export function playBiosTick() {
if (SOUND_DISABLED) return;
const c = audioCtx();
if (c.state === "suspended") return;
const t0 = c.currentTime;
const osc = c.createOscillator();
osc.type = "square";
osc.frequency.value = 1750 + Math.random() * 350;
const g = c.createGain();
g.gain.setValueAtTime(0.02, t0);
g.gain.exponentialRampToValueAtTime(0.001, t0 + 0.018);
osc.connect(g);
g.connect(buses.sfx);
osc.start(t0);
osc.stop(t0 + 0.02);
osc.onended = () => g.disconnect();
}
// Menu-confirm bloop (Waddle in / Resume / pad A): two rising square
// notes, C5 -> G5. This rides the very gesture that unlocks the context,
// so a suspended context gets one resume-then-play attempt.
export function playConfirmBloop() {
if (SOUND_DISABLED) return;
const c = audioCtx();
if (c.state === "suspended") {
c.resume().then(() => confirmNow(c)).catch(() => {});
return;
}
confirmNow(c);
}
function confirmNow(c) {
const t0 = c.currentTime + 0.01;
const tone = c.createBiquadFilter();
tone.type = "lowpass";
tone.frequency.value = 4200;
tone.connect(buses.sfx);
const osc = c.createOscillator();
osc.type = "square";
osc.frequency.setValueAtTime(523, t0);
osc.frequency.setValueAtTime(784, t0 + 0.07);
const g = c.createGain();
g.gain.setValueAtTime(0, t0);
g.gain.linearRampToValueAtTime(0.13, t0 + 0.01);
g.gain.setValueAtTime(0.13, t0 + 0.12);
g.gain.exponentialRampToValueAtTime(0.001, t0 + 0.2);
osc.connect(g);
g.connect(tone);
osc.start(t0);
osc.stop(t0 + 0.22);
osc.onended = () => tone.disconnect();
}
// ── Entrance line blips ───────────────────────────────────────────────
// One tiny tick per grid/wall section line as it starts drawing in. `u`
// is the line's own draw jitter (0..1), reused as pitch variation so the
// flurry chirps instead of machine-gunning. Very low in the mix.
export function playLineBlip(u = 0.5) {
if (SOUND_DISABLED) return;
const c = audioCtx();
if (c.state === "suspended") return;
const t0 = c.currentTime;
const osc = c.createOscillator();
osc.type = "triangle";
osc.frequency.value = 1400 * 2 ** (u * 0.9); // ~1.4-2.6 kHz across lines
const g = c.createGain();
g.gain.setValueAtTime(0.05, t0);
g.gain.exponentialRampToValueAtTime(0.001, t0 + 0.05);
osc.connect(g);
g.connect(buses.sfx);
osc.start(t0);
osc.stop(t0 + 0.06);
osc.onended = () => g.disconnect();
}
// ── Roller rumble (synthesized rolling-noise loop) ────────────────────
// Bandpassed noise on the duck emitter; gain and a slight pitch follow
// ground speed, silent at rest. Built lazily on first use.
let rumble = null; // { gain, src }
export function setRumble(level, out = null) {
if (SOUND_DISABLED) return;
const c = audioCtx();
if (!rumble) {
if (level <= 0) return;
const src = c.createBufferSource();
src.buffer = noiseBuffer(c, 1.5);
src.loop = true;
const f = c.createBiquadFilter();
f.type = "bandpass";
f.frequency.value = 110;
f.Q.value = 0.8;
const g = c.createGain();
g.gain.value = 0;
src.connect(f);
f.connect(g);
g.connect(out?.node ?? buses.sfx);
src.start();
rumble = { gain: g, src };
}
const t = c.currentTime;
rumble.gain.gain.setTargetAtTime(Math.min(1, level) * 0.22, t, 0.08);
rumble.src.playbackRate.setTargetAtTime(0.85 + 0.5 * Math.min(1, level), t, 0.12);
}
+102
View File
@@ -0,0 +1,102 @@
// Ball actor: physics stays in rl.js, this owns the mesh + wireframe FX.
//
// visual:
// hidden parked, mesh off
// live following qpos, optional appear scan playing
// ghost physics already parked; mesh frozen at last pose while the
// reverse scan peels it away
//
// spawn while live/ghost queues a pop: despawn finishes, then the caller
// places physics and appear()s.
// Appear/disappear speed. The shared wireframe FX timeline lasts
// fx.TOTAL_S (0.9 s, tuned for the duck's ceremony); the ball plays the
// same timeline time-scaled to these snappier durations.
const BALL_APPEAR_S = 0.35; // spawn pop-in (scan up)
const BALL_DISAPPEAR_S = 0.25; // despawn/park peel-away (reverse scan)
export function createBallActor({ THREE, scene, camera, renderer, fxModule, mesh, group }) {
const fx = fxModule.createWireframeFx();
fx.init({ THREE, scene, root: group, camera, renderer, hidden: false });
let visual = "hidden"; // hidden | live | ghost
let ghost = null;
let pendingSpawn = false;
let fxPrev = null;
function appear() {
visual = "live";
ghost = null;
mesh.visible = true;
fx.start();
fxPrev = performance.now();
}
function despawn({ cancelQueued = false, parkPhysics }) {
if (cancelQueued) pendingSpawn = false;
if (visual === "hidden") return;
if (visual === "live") {
ghost = {
pos: mesh.position.clone(),
quat: mesh.quaternion.clone(),
};
visual = "ghost";
}
parkPhysics();
fx.startReverse();
fxPrev = performance.now();
}
function queueRespawn() {
pendingSpawn = true;
}
function poseFromQpos(qpos, adr) {
mesh.position.set(qpos[adr], qpos[adr + 1], qpos[adr + 2]);
mesh.quaternion.set(qpos[adr + 4], qpos[adr + 5], qpos[adr + 6], qpos[adr + 3]);
}
function sync(qpos, adr, physicsLive) {
if (visual === "ghost" && ghost) {
mesh.visible = true;
mesh.position.copy(ghost.pos);
mesh.quaternion.copy(ghost.quat);
} else if (physicsLive) {
mesh.visible = true;
poseFromQpos(qpos, adr);
} else {
mesh.visible = false;
}
}
function drive(onQueuedSpawn) {
if (fx.playing) {
const now = performance.now();
if (fxPrev === null) fxPrev = now;
const dt = Math.min((now - fxPrev) / 1000, 0.25);
fxPrev = now;
// Time-scale the FX so the ball pops in/out at its own speed.
const speed = fx.TOTAL_S / (fx.reversing ? BALL_DISAPPEAR_S : BALL_APPEAR_S);
fx.update(dt * speed);
}
if (visual === "ghost" && fx.isDone()) {
mesh.visible = false;
visual = "hidden";
ghost = null;
fx.restore();
const queued = pendingSpawn;
pendingSpawn = false;
if (queued) onQueuedSpawn();
}
}
return {
appear,
despawn,
queueRespawn,
poseFromQpos,
sync,
drive,
get visual() { return visual; },
};
}
+149
View File
@@ -0,0 +1,149 @@
// Ball visuals: procedural soccer-ball texture + the render mesh, ported
// verbatim from the pre-React rl.js.
import * as THREE from "three";
import { BALL_RADIUS } from "./constants.js";
// Soccer-ball look computed per pixel on the sphere itself, so there is
// no pole or seam special case by design. The truncated icosahedron is
// reconstructed as a spherical Voronoi diagram over 32 sites: the 12
// icosahedron vertices (black pentagon centers, one sitting at each
// pole) and its 20 face centers (white hexagon centers). A pixel is
// black when its nearest site is a pentagon center and it sits clear of
// the cell boundary by a seam margin - which yields big flat-edged black
// pentagons separated from the white hexagons by thin seams, corners
// almost touching, exactly like the real panel layout.
function makeSoccerBallTexture(renderer) {
const W = 1024, H = 512;
const c = document.createElement("canvas");
c.width = W;
c.height = H;
const ctx = c.getContext("2d");
// 12 icosahedron vertices: 2 poles + two staggered rings of 5 at
// latitude +-atan(1/2) (~26.57 deg) - the pentagon centers.
const sites = [];
const addSite = (v, isPent) => {
const n = Math.hypot(v[0], v[1], v[2]);
sites.push({ x: v[0] / n, y: v[1] / n, z: v[2] / n, pent: isPent });
};
const verts = [[0, 0, 1], [0, 0, -1]];
const latR = Math.atan(0.5), cr = Math.cos(latR), sr = Math.sin(latR);
for (let i = 0; i < 5; i++) {
const a = (i * 72 * Math.PI) / 180;
const b = ((i * 72 + 36) * Math.PI) / 180;
verts.push([cr * Math.cos(a), cr * Math.sin(a), sr]);
verts.push([cr * Math.cos(b), cr * Math.sin(b), -sr]);
}
for (const v of verts) addSite(v, true);
// 20 face centers (hexagon centers): normalized centroids of every
// mutually-adjacent vertex triple (adjacent pairs have dot = 1/sqrt(5)).
const adj = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2] > 0.3;
for (let i = 0; i < 12; i++) {
for (let j = i + 1; j < 12; j++) {
if (!adj(verts[i], verts[j])) continue;
for (let k = j + 1; k < 12; k++) {
if (adj(verts[i], verts[k]) && adj(verts[j], verts[k])) {
addSite([
verts[i][0] + verts[j][0] + verts[k][0],
verts[i][1] + verts[j][1] + verts[k][1],
verts[i][2] + verts[j][2] + verts[k][2],
], false);
}
}
}
}
// Seam half-width and anti-alias band, in radians of arc.
const SEAM = (1.6 * Math.PI) / 180;
const AA = (0.35 * Math.PI) / 180;
// Groove reach for the bump map: a touch wider than the painted seam so
// the recess shoulders catch light on both sides of the line.
const GROOVE = SEAM * 1.5;
const BG = [233, 231, 224], INK = [23, 23, 29], STITCH = [200, 197, 188];
const img = ctx.createImageData(W, H);
const px = img.data;
// Height map sharing the same panel construction: seams become recessed
// grooves, plus a very fine leather/PVC grain over the whole surface.
const bc = document.createElement("canvas");
bc.width = W;
bc.height = H;
const bctx = bc.getContext("2d");
const bimg = bctx.createImageData(W, H);
const bpx = bimg.data;
for (let row = 0; row < H; row++) {
const lat = Math.PI / 2 - ((row + 0.5) / H) * Math.PI;
const cl = Math.cos(lat), sl = Math.sin(lat);
for (let col = 0; col < W; col++) {
const lon = ((col + 0.5) / W) * 2 * Math.PI - Math.PI;
const dx = cl * Math.cos(lon), dy = cl * Math.sin(lon), dz = sl;
let best = -2, second = -2, bestPent = false;
for (const s of sites) {
const d = dx * s.x + dy * s.y + dz * s.z;
if (d > best) { second = best; best = d; bestPent = s.pent; }
else if (d > second) second = d;
}
// Signed distance to the Voronoi cell boundary along the geodesic.
const halfGap = (Math.acos(Math.min(1, second)) - Math.acos(Math.min(1, best))) / 2;
// Black panel: inside a pentagon cell, clear of the seam margin.
const black = bestPent ? Math.min(1, Math.max(0, (halfGap - SEAM) / AA)) : 0;
// Subtle stitch line on every remaining cell boundary so the white
// hexagons read as panels too.
const stitch = Math.min(1, Math.max(0, 1 - halfGap / (SEAM * 0.6))) * (1 - black);
const o = (row * W + col) * 4;
for (let ch = 0; ch < 3; ch++) {
const base = BG[ch] + (STITCH[ch] - BG[ch]) * stitch;
px[o + ch] = base + (INK[ch] - base) * black;
}
px[o + 3] = 255;
// Bump: quadratic groove profile (soft shoulders, no golf-ball
// embossing) + grain noise.
const groove = Math.max(0, 1 - halfGap / GROOVE) ** 2;
const hgt = 205 - groove * 115 + (Math.random() - 0.5) * 14;
const h8 = Math.max(0, Math.min(255, hgt));
bpx[o] = h8; bpx[o + 1] = h8; bpx[o + 2] = h8;
bpx[o + 3] = 255;
}
}
ctx.putImageData(img, 0, 0);
bctx.putImageData(bimg, 0, 0);
const finish = (canvas, srgb) => {
const tex = new THREE.CanvasTexture(canvas);
// The bump map stays linear; only the color map is sRGB.
if (srgb) tex.colorSpace = THREE.SRGBColorSpace;
// Texel footprints get extremely anamorphic near the UV poles; without
// anisotropy the cap edge visibly scallops at close range.
tex.anisotropy = renderer.capabilities.getMaxAnisotropy();
return tex;
};
return { map: finish(c, true), bumpMap: finish(bc, false) };
}
// Same Z-up -> Y-up trick as the duck rig: the group takes the axis fix,
// the mesh inside takes the raw MJCF free-joint pose.
export function createBallVisual(renderer) {
const group = new THREE.Group();
group.rotation.x = -Math.PI / 2;
const tex = makeSoccerBallTexture(renderer);
const mesh = new THREE.Mesh(
// 48x32 segments: the coarser default makes the UV interpolation near
// the poles visibly scallop the round cap edge of the texture.
new THREE.SphereGeometry(BALL_RADIUS, 48, 32),
// Physical material for the waxed vintage-leather look: matte-ish base
// with a whisper of clearcoat so highlights ride the seam grooves.
new THREE.MeshPhysicalMaterial({
map: tex.map,
bumpMap: tex.bumpMap,
bumpScale: 0.0012,
metalness: 0,
roughness: 0.55,
clearcoat: 0.2,
clearcoatRoughness: 0.35,
}),
);
mesh.userData.meshName = "ball";
// The 48x32 render sphere is far too dense for the wireframe scan (it
// reads as a solid glowing blob); the FX overlay uses this geodesic
// stand-in instead - 80 triangles, clean hologram lines.
mesh.userData.fxWireGeometry = new THREE.IcosahedronGeometry(BALL_RADIUS, 1);
mesh.visible = false;
group.add(mesh);
return { group, mesh };
}
+267
View File
@@ -0,0 +1,267 @@
// Cutscene layer: page-load entrance and every later respawn.
//
// Physics (resetSim) snaps the duck to the stand keyframe; this module
// owns what the player sees around that snap. Two mutually exclusive
// timelines share the duck's wireframe FX:
//
// entrance (once) grid + walls draw in, then the duck scans up
// respawn (every kill / Space / loco switch)
// 0.00 duck clipped away, camera glides home from the kill view
// 0.80 camera almost settled -> duck scan-up cues
// 0.90 camera lands
// 1.70 scan done, inputs unlock
//
// rl.js injects the world (rig, grid, camera reset) and the lock/flash
// callbacks; this file never touches MuJoCo.
import { entranceLineCues } from "./arena.js";
export const CAM_RESET_S = 0.9;
export const RESPAWN_SCAN_AT = 0.8; // cue scan-up at 80% of the camera glide
const ENTRANCE_GRID_S = 1.1;
const ENTRANCE_WALL_DELAY_S = 0.35;
const ENTRANCE_WALL_S = 0.9;
const ENTRANCE_FX_START_S = 0.6;
const clamp01 = (x) => Math.min(Math.max(x, 0), 1);
export function createCeremony({
THREE, scene, camera, renderer, fx,
getRig, grid, wallMats,
syncRig, startCameraReset,
setLocked, flashReset,
onScanCue = () => {},
onLineCue = () => {},
onPropCue = () => {},
}) {
const ENTRANCE_TOTAL_S = Math.max(
ENTRANCE_GRID_S,
ENTRANCE_WALL_DELAY_S + ENTRANCE_WALL_S,
ENTRANCE_FX_START_S + fx.TOTAL_S,
);
// Per-line audio cues for the entrance draw-in: normalized reveal times
// from arena.js (exact same hashed stagger as the shaders), mapped onto
// this timeline's grid/wall reveal windows. Entrance-only: respawns
// never redraw the arena.
const cues = entranceLineCues();
const lineCues = [
...cues.grid.map((c) => ({ at: c.at * ENTRANCE_GRID_S, u: c.u })),
...cues.walls.map((c) => ({
at: ENTRANCE_WALL_DELAY_S + c.at * ENTRANCE_WALL_S, u: c.u,
})),
].sort((a, b) => a.at - b.at);
let lineCueIdx = lineCues.length; // parked until startEntrance
let fxRig = null;
let fxPrev = null;
// Decorative props (addPropFx): each owns a wireframe FX bound to its
// own root. They cue whenever the duck's scan cues (entrance and every
// respawn), offset by their stagger, and drive on their OWN clock so a
// late-finishing prop never extends the input lock or the ceremony's
// completion checks.
const props = []; // { fx, delayS, at, started, prev }
let entranceT0 = null;
let entranceFxCued = false;
let entranceDone = false;
let respawn = null; // { t0, scanCued } | null
let entranceFinishedResolve;
const entranceFinished = new Promise((r) => { entranceFinishedResolve = r; });
function bind() {
const rig = getRig();
if (fxRig === rig) return;
fx.dispose();
fx.init({ THREE, scene, rig, camera, renderer });
rig.placer.traverse((o) => {
if (o.isMesh && !o.userData.meshName) o.userData.fxOverlay = true;
});
fxRig = rig;
}
function fxStart() {
bind();
fx.start();
fxPrev = performance.now();
propsCue();
// Sound cue riding the same trigger as the visual scan; the duration
// lets the sweep span the materialize exactly.
onScanCue(fx.TOTAL_S);
}
function propsCue() {
const now = performance.now();
for (const p of props) {
p.at = now + p.delayS * 1000;
p.started = false;
p.prev = null;
}
}
function propsHide() {
for (const p of props) {
p.fx.setProgress(0);
p.at = null;
p.started = false;
}
}
function propsFinish() {
for (const p of props) {
if (!p.started) p.fx.start();
p.fx.update(1e3);
p.at = null;
}
}
// Deterministic screenshot/test hook (setFx): park every prop at the
// same scan progress as the duck, detached from the timed driver.
function propsSetProgress(v) {
for (const p of props) {
p.fx.setProgress(v);
p.at = null;
p.started = false;
}
}
function driveProps() {
const now = performance.now();
for (const p of props) {
if (p.at === null || now < p.at) continue;
if (!p.started) {
p.fx.start();
// Audio twin, cued the frame this prop's scan actually starts;
// TOTAL_S carries the size-stretched duration so the sound can
// match both length and register.
onPropCue(p.fx.TOTAL_S);
p.started = true;
p.prev = now;
continue;
}
if (p.fx.isDone()) continue;
const dt = Math.min((now - p.prev) / 1000, 0.25);
p.prev = now;
p.fx.update(dt);
}
}
function fxDrive() {
if (fxPrev === null || fx.isDone()) return;
const now = performance.now();
const dt = Math.min((now - fxPrev) / 1000, 0.25);
fxPrev = now;
fx.update(dt);
}
function fxForceFinish() {
if (!fx.isDone()) fx.update(1e3);
}
function startEntrance() {
if (entranceT0 !== null || entranceDone) return;
entranceT0 = performance.now();
entranceFxCued = false;
lineCueIdx = 0;
grid.material.uniforms.uReveal.value = 0;
for (const m of wallMats) m.uniforms.uReveal.value = 0;
}
function driveEntrance() {
if (entranceT0 === null) return;
const t = (performance.now() - entranceT0) / 1000;
// Fire the per-line blips as their lines start drawing in.
while (lineCueIdx < lineCues.length && lineCues[lineCueIdx].at <= t) {
onLineCue(lineCues[lineCueIdx].u);
lineCueIdx++;
}
grid.material.uniforms.uReveal.value = clamp01(t / ENTRANCE_GRID_S);
const wallR = clamp01((t - ENTRANCE_WALL_DELAY_S) / ENTRANCE_WALL_S);
for (const m of wallMats) m.uniforms.uReveal.value = wallR;
if (t >= ENTRANCE_FX_START_S && !entranceFxCued) {
entranceFxCued = true;
fxStart();
}
fxDrive();
if (t >= ENTRANCE_TOTAL_S) {
if (!fx.isDone() && t < ENTRANCE_TOTAL_S + 0.5) return;
fxForceFinish();
entranceT0 = null;
entranceDone = true;
grid.material.uniforms.uReveal.value = 1;
for (const m of wallMats) m.uniforms.uReveal.value = 1;
setLocked(false);
entranceFinishedResolve();
}
}
function playRespawn() {
if (!entranceDone) return;
setLocked(true);
flashReset();
bind();
startCameraReset();
syncRig();
fx.setProgress(0);
propsHide();
respawn = { t0: performance.now(), scanCued: false };
}
function driveRespawn() {
if (!respawn) return;
const u = (performance.now() - respawn.t0) / 1000 / CAM_RESET_S;
if (!respawn.scanCued && u >= RESPAWN_SCAN_AT) {
respawn.scanCued = true;
fxStart();
}
if (respawn.scanCued) fxDrive();
if (respawn.scanCued && fx.isDone()) {
respawn = null;
setLocked(false);
}
}
function drive() {
driveEntrance();
driveRespawn();
driveProps();
}
function setReveal(floor, wall = floor) {
entranceT0 = null;
grid.material.uniforms.uReveal.value = floor;
for (const m of wallMats) m.uniforms.uReveal.value = wall;
}
function setFx(p) {
entranceT0 = null;
respawn = null;
bind();
if (p >= 1) {
fx.start();
fxForceFinish();
propsFinish();
setLocked(false);
entranceFinishedResolve();
} else {
fx.setProgress(p);
propsSetProgress(p);
}
}
// Register a decorative prop's wireframe FX (already init'd on its own
// root, hidden). It materializes delayS after each duck scan cue.
function addPropFx(propFx, delayS = 0) {
props.push({ fx: propFx, delayS, at: null, started: false, prev: null });
}
// Boot hidden: clip parked below the feet from the first frame.
bind();
return {
CAM_RESET_S,
startEntrance,
playRespawn,
drive,
bind,
setReveal,
setFx,
addPropFx,
entranceFinished,
get entranceDone() { return entranceDone; },
get respawnActive() { return respawn !== null; },
};
}
+117
View File
@@ -0,0 +1,117 @@
// Shared sim constants, lifted verbatim from the pre-React rl.js.
export const POLICY_DIR = "./policies";
export const POLICIES = {
walk: `${POLICY_DIR}/BEST_alpha_walking.onnx`,
sitstand: `${POLICY_DIR}/BEST_alpha_sitstand.onnx`,
roll: `${POLICY_DIR}/roulade.onnx`,
// Blind one-shot kicks (the operator aims the robot, no ball in obs):
// the runtime swaps these in for a 0.5 s window, commands zeroed.
kickL: `${POLICY_DIR}/ball_kick_left.onnx`,
kickR: `${POLICY_DIR}/ball_kick_right.onnx`,
// One-shot ground pick (runtime A button): peck the ground and stand
// back up, phase-driven via [cos, sin, 0] in the command vel slots.
groundpick: `${POLICY_DIR}/alpha_ground_pick.onnx`,
// Get-up policy for the automatic fall recovery (runtime --fall-detect):
// same 61D obs layout as the other alpha policies, commands all zeroed.
stand: `${POLICY_DIR}/BEST_alpha_stand.onnx`,
// Roller variant (lazy-loaded on first switch, never at boot):
// drive = velocity-tracking skating, crouch = one-shot crouch-glide
// driven by a phase encoding in the command slots (ground-pick style).
drive: `${POLICY_DIR}/BEST_roller.onnx`,
crouch: `${POLICY_DIR}/BEST_roller_crouch.onnx`,
};
// From the ONNX metadata (identical for all alpha policies) and the STAND
// keyframe in mjlab's scene_walk.xml. Order matches the actuators in
// the MJCF.
export const JOINT_NAMES = [
"left_hip_yaw", "left_hip_roll", "left_hip_pitch", "left_knee", "left_ankle",
"neck_pitch", "head_pitch", "head_yaw", "head_roll",
"right_hip_yaw", "right_hip_roll", "right_hip_pitch", "right_knee", "right_ankle",
];
export const DEFAULT_POSE = new Float32Array([
0, -0.08726646259971647, -0.457924, -0.004940, 0.452984,
0.3490658503988659, 0.3490658503988659, 0, 0,
0, 0.08726646259971647, 0.457924, 0.004940, -0.452984,
]);
export const NUM_JOINTS = 14;
export const OBS_SIZE = 61;
export const CMD_SIZE = 13;
export const ACTION_SCALE = 1.0;
export const TIMESTEP = 0.005;
export const DECIMATION = 4;
export const CTRL_DT = TIMESTEP * DECIMATION; // 50 Hz
// Velocity command limits, same as infer_policy.py's keyboard mapping.
// No strafe input anymore: the lateral cmd slot stays zeroed for the obs.
export const VEL_FWD = 0.25, VEL_BACK = -0.2, VEL_ANG = 1.0;
// Roller mode limits, from the runtime's roller branch: asymmetric vx
// (0.6 push / 0.5 brake), no lateral. The real runtime launches rollers
// with --max-angular-vel 0.3: faster commanded turns tip the robot over,
// so the playground clamps wz the same way.
export const RVEL_FWD = 0.6, RVEL_BACK = -0.5, RVEL_ANG = 0.3;
// Crouch-glide one-shot: command = [cos(2pi*phase), sin(2pi*phase), 0],
// phase advancing at 1/CROUCH_PERIOD_S per second and the cycle exiting
// at 0.7 - exactly the runtime's ground-pick slot the policy was trained
// against (mjlab CROUCH_PERIOD = 5.0, cycle end 0.7 => 3.5 s gesture).
export const CROUCH_PERIOD_S = 5.0;
export const CROUCH_END_PHASE = 0.7;
// Ground-pick one-shot (legs): same phase encoding, from the runtime's
// defaults (--ground-pick-period 4.0, cycle exiting at 0.7 => ~2.8 s
// gesture, action scale and kP untouched at their 1.0 defaults).
export const GROUND_PICK_PERIOD_S = 4.0;
export const GROUND_PICK_END_PHASE = 0.7;
// Kickable ball: radius and parking spot (far away = hidden by default).
export const BALL_RADIUS = 0.05;
export const BALL_PARK_POS = "50 0 0.05";
// Square arena boxing the play area: static walls at +-ARENA_HALF keep
// the ball (and the duck) inside. Tall enough that neither steps over.
export const ARENA_HALF = 1.5; // inner half-size, m
export const ARENA_WALL_H = 0.25;
export const ARENA_WALL_T = 0.05;
// Section grid: 5 cells across the 3 m arena (ODD, so a true middle
// column/row of cells exists; the lattice is shifted half a cell in the
// shaders so the walls land exactly on section lines).
export const GRID_SECTION = (2 * ARENA_HALF) / 5; // 0.6 m
// Arcade cabinet row: three cabinets side by side against the front (+X)
// wall, screens facing the arena. Consumed by the prop library (props.js
// "arcade" def - currently benched, enabled: false) for both the clone
// placements and the row's single static collision box. Proportions
// measured from the GLB's natural size (0.524 x 0.587 x 1.0 m, w x d x h).
// Slightly surreal scale: ~2.8x the 0.25 m duck (a real 1.73 m cabinet
// felt overwhelming in the 3 m arena). Big enough to read as oversized
// furniture, small enough that the row (~1.15 m wide, 0.41 m deep)
// leaves the play area open.
export const ARCADE_H = 0.7; // target height, m
export const ARCADE_W = ARCADE_H * 0.524; // footprint width, ~0.22 m
export const ARCADE_D = ARCADE_H * 0.5876; // footprint depth, ~0.247 m
export const ARCADE_GAP = 0.02; // gap between neighbouring cabinets
export const ARCADE_WALL_GAP = 0.01; // clearance between backs and the wall
// Relief (prototype): gentle cosine bumps baked into the level itself.
// One shared analytic height function drives BOTH the physics (a MuJoCo
// heightfield covering the arena) and the visuals (vertex displacement
// of the grid floor shader), so the grid genuinely deforms instead of
// boxes popping out of it. Entries are [cx, cy, height, radius] in MJCF
// coords; slopes stay mild (max grade ~20%) so the blind walking policy
// has a chance, and the spawn cell + arcade row stay flat.
export const RELIEF_BUMPS = [
[0.3, -0.9, 0.06, 0.55],
[-0.9, 0.75, 0.05, 0.5],
[0.6, 0.9, 0.07, 0.55],
];
export const RELIEF_HMAX = 0.07; // tallest bump, scales the hfield z-size
export const RELIEF_GRID = 65; // hfield rows/cols over the 3x3 m arena
export const RELIEF_SINK = 0.003; // hfield geom buried below the floor
export const RELIEF_RATE = 0.6; // raise/sink rate, scale units per second
// Spawn: center of the middle section cell in the SECOND ROW FROM THE
// BACK wall. The duck faces +X (identity freejoint quat, walks toward
// local +X), so "back" is the -X wall: row centers sit at x = -1.2,
// -0.6, 0, 0.6, 1.2 -> second row is -0.6; middle column is y = 0.
// MJCF coordinates (three.js: x -> x, y -> -z).
export const SPAWN_X = -ARENA_HALF + 1.5 * GRID_SECTION; // -0.6
export const SPAWN_Y = 0;
+194
View File
@@ -0,0 +1,194 @@
// Controller: the video-game-style input core. Aggregates pluggable input
// SOURCES (keyboard, gamepad, later touch) into one game-facing surface:
//
// - a continuous COMMAND: the [vx, vy, wz] twist the policy tracks, plus
// auxiliary analog AXES (jaw 0..1, camera-orbit rates -1..1);
// - discrete ACTIONS: edge-triggered events (roll, kicks, ball spawn...)
// dispatched to subscribers the moment a source fires them;
// - HUD support: per-source pressed-state snapshots and activity info so
// the hint keycaps can light up per physical control and per device.
//
// The game code (rl.js) instantiates the sources, registers them here,
// calls update(dt) once per render frame, reads getCommand()/getAxes()
// where it builds the policy observation, and subscribes its trigger
// functions with on(action, cb).
//
// ── Source interface contract ────────────────────────────────────────────
// Every input source module (keyboard.js, gamepad.js, a future touch.js
// with a virtual joystick + buttons) implements:
//
// id Unique string ("keyboard", "gamepad", "touch"...). Action
// subscribers receive it as meta.source, so game code can
// attribute HUD flashes / keycap lighting to the right device.
// connected Boolean hardware presence. Keyboard: always true. Gamepad:
// a pad is currently reported by navigator.getGamepads().
// command Float32Array(3) [vx, vy, wz], ALREADY scaled to the game's
// velocity limits (sources take a getVelocityLimits() callback
// returning [fwd, back, ang], so limits can change at runtime,
// e.g. the legs <-> rollers switch). Must be a stable array
// reference updated in place: getCommand() hands it out
// without copying, and the control loop reads it between
// render frames.
// axes { jaw, orbitX, orbitY, ride } - auxiliary continuous
// channels. jaw in [0, 1] (mouth opening), orbit axes in
// [-1, 1] (camera orbit rate; the inertia/smoothing lives
// downstream in the camera code, sources report raw
// deflection), ride in [0, 1] (LT squeeze pressure, bends
// the wheee note's pitch). Stable object reference, updated
// in place. Channels a source does not drive may be omitted
// (merged as 0).
// pressed Plain object of booleans (stable reference) mirroring which
// physical controls are currently down. HUD highlighting
// only - never game logic.
// isActive() Whether the source currently claims authority over the
// continuous command. Keyboard: any move key held. Gamepad:
// stick deflected, and it keeps the claim until its smoothed
// command settles back to ~zero.
// init() Attach event listeners / hardware hooks. Called by
// Controller.init(), NOT at construction (rl.js constructs
// the sources early but arms the listeners at the same point
// in the boot where they historically went live).
// dispose() Detach everything init() attached.
// poll(dt) Per-frame tick (dt in seconds, clamped by the caller).
// Read the hardware, update command/axes/pressed in place,
// and fire edge-triggered actions via this.onAction(name).
// onAction (name, meta?) => void, assigned by the Controller at
// registration. Sources may call it from poll() (gamepad
// button edges) or straight from event handlers (keyboard:
// keeps the historical press-to-effect latency).
//
// ── Arbitration ──────────────────────────────────────────────────────────
// Continuous command: sources are registered in PRIORITY order (first =
// highest). Each frame the first source reporting isActive() owns the
// twist; when none is active the LAST registered source's command is used
// as the fallback (it reads zero when idle). With [gamepad, keyboard] this
// reproduces the historical `padActive ? padCmd : velCmd` exactly: live
// sticks win over held keys, and the keyboard takes back over once the
// pad's smoothed command has settled.
// Aux axes are merged across ALL sources regardless of who owns the twist
// (the pad triggers drive the jaw even while walking on the keyboard):
// jaw = max over sources, orbit = largest-magnitude value per axis.
//
// ── 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 (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
// reset full sim reset (Space)
// walk back to the walk/run mode (pad DpadUp short press)
// quack chirp + jaw flap (pad RT edge, Schmitt-triggered)
//
// ── Input lock ───────────────────────────────────────────────────────────
// setLocked(true) zeroes getCommand() - the twist gate used while the
// entrance/respawn ceremony plays. Discrete actions still dispatch: each
// game trigger applies its own lock policy (e.g. Space-reset and the
// chase-cam toggle historically work while locked, kicks don't).
const ZERO_CMD = new Float32Array(3);
export class Controller {
#sources = [];
#listeners = new Map(); // action -> Set(cb)
#locked = false;
#axes = { jaw: 0, orbitX: 0, orbitY: 0, ride: 0 };
constructor({ sources = [] } = {}) {
for (const s of sources) this.addSource(s);
}
// Register in priority order (first registered wins arbitration ties).
addSource(source) {
source.onAction = (action, meta) =>
this.#dispatch(action, { source: source.id, ...meta });
this.#sources.push(source);
}
// Read-only source list, for advanced per-source queries the merged view
// can't answer (e.g. "is ANY source commanding a turn right now?").
get sources() {
return this.#sources;
}
// Arm every source's listeners/hardware hooks.
init() {
for (const s of this.#sources) s.init?.();
}
dispose() {
for (const s of this.#sources) s.dispose?.();
}
// Per-frame tick: poll every source (they fire their edge actions from
// inside poll), then merge the aux axes.
update(dt) {
for (const s of this.#sources) s.poll?.(dt);
let jaw = 0, ox = 0, oy = 0, ride = 0;
for (const s of this.#sources) {
const a = s.axes;
if (!a) continue;
jaw = Math.max(jaw, a.jaw ?? 0);
ride = Math.max(ride, a.ride ?? 0);
if (Math.abs(a.orbitX ?? 0) > Math.abs(ox)) ox = a.orbitX;
if (Math.abs(a.orbitY ?? 0) > Math.abs(oy)) oy = a.orbitY;
}
this.#axes.jaw = jaw;
this.#axes.orbitX = ox;
this.#axes.orbitY = oy;
this.#axes.ride = ride;
}
setLocked(v) {
this.#locked = !!v;
}
get locked() {
return this.#locked;
}
// Merged continuous twist [vx, vy, wz] (see the arbitration notes above).
// Returns live source arrays without copying - treat as read-only.
getCommand() {
if (this.#locked) return ZERO_CMD;
for (const s of this.#sources) if (s.isActive()) return s.command;
const fallback = this.#sources[this.#sources.length - 1];
return fallback ? fallback.command : ZERO_CMD;
}
// Merged aux axes { jaw, orbitX, orbitY }, refreshed by update().
getAxes() {
return this.#axes;
}
// Any source claiming twist authority (HUD "user is driving" signal).
anyActive() {
return this.#sources.some((s) => s.isActive());
}
// Per-source pressed snapshots for HUD keycap highlighting:
// { keyboard: {...}, gamepad: {...} }.
getPressed() {
const out = {};
for (const s of this.#sources) out[s.id] = s.pressed ?? {};
return out;
}
// Subscribe to a discrete action; cb(meta) with meta.source = source id.
// Returns an unsubscribe function.
on(action, cb) {
let set = this.#listeners.get(action);
if (!set) this.#listeners.set(action, (set = new Set()));
set.add(cb);
return () => set.delete(cb);
}
#dispatch(action, meta) {
const set = this.#listeners.get(action);
if (!set) return;
for (const cb of set) cb(meta);
}
}
+250
View File
@@ -0,0 +1,250 @@
// Gamepad input source (see controller.js for the source interface
// contract). Same mapping as the robot runtime (pollen-robotics/microduck):
//
// Left stick vertical = vx (asymmetric fwd/back), horizontal = turn,
// EMA-smoothed like the runtime's cmd_alpha.
// 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 sit <-> stand (crouch-glide in roller mode - game decides).
// The pad can no longer launch a roll at all.
// 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
// (like the robot's 3 s hold, shortened for the web)
// RT analog jaw + quack on the rising edge, 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).
// LT rides the looping "wheee": start on the rising edge, cut
// the instant it releases - same Schmitt hysteresis so
// jitter can't restart the ride. The analog pressure is
// reported continuously in `axes.ride` so the game can
// pick the note with the squeeze (pentatonic steps over
// one octave - the trigger is a tiny instrument).
// The two are mutually exclusive: an edge on one trigger
// is CONSUMED while the other is physically down, so one
// squeeze can never fire both sounds - even on pads that
// mirror a combined trigger channel onto both button
// slots (see the trigger block for the tie-break).
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_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
// The one pad-picking rule, shared by poll() and the haptics engine
// (haptics.js): prefer a standard-mapping pad - the button indices above
// are only guaranteed by the "standard" layout - and fall back to
// whatever is connected.
export function pickPad() {
const pads = [...(navigator.getGamepads?.() ?? [])].filter((p) => p && p.connected);
return pads.find((p) => p.mapping === "standard") ?? pads[0];
}
export class GamepadSource {
id = "gamepad";
connected = false;
command = new Float32Array(3); // [vx, 0, wz], EMA-smoothed
axes = { jaw: 0, orbitX: 0, orbitY: 0, ride: 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 = {
a: false, x: false, y: false, rb: false, lb: false, r3: false,
dpadDown: false, dpadUp: false,
};
onAction = () => {}; // assigned by the Controller at registration
#getVelocityLimits;
#active = false; // owns twist authority (stick input, until EMA settles)
#dpadUpAt = 0; // wall-clock of the current DpadUp press
#dpadUpFired = false; // latch: one loco switch per hold
#rtDown = false; // RT physical Schmitt state (edge detection + gating)
#ltDown = false; // LT physical Schmitt state (edge detection + gating)
#ltRide = false; // wheee ride currently open (LT edge that wasn't blocked)
constructor({ getVelocityLimits }) {
this.#getVelocityLimits = getVelocityLimits;
}
init() {} // poll-based: nothing to attach
dispose() {}
isActive() {
return this.#active;
}
poll() {
const prev = this.pressed;
// A non-standard pad (mapping "") is a last-resort fallback in
// pickPad - its indices are firmware-defined and some mirror one
// combined trigger channel onto both trigger slots.
const gp = pickPad();
this.connected = !!gp;
if (!gp) {
if (this.#active) {
this.#active = false;
this.command.fill(0);
this.axes.jaw = 0;
}
this.axes.orbitX = 0;
this.axes.orbitY = 0;
this.axes.ride = 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();
const lx = dz(gp.axes[0] ?? 0), ly = dz(gp.axes[1] ?? 0);
const rx = dz(gp.axes[2] ?? 0), ry = dz(gp.axes[3] ?? 0);
const [limF, limB, limA] = this.#getVelocityLimits();
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). 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 &&
Math.abs(this.command[0]) + Math.abs(this.command[1]) + Math.abs(this.command[2]) < 0.01
) {
this.#active = false;
this.command.fill(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("sitToggle");
prev.x = x;
const y = !!gp.buttons[BTN_Y]?.pressed;
if (y && !prev.y) this.onAction("headToggle");
prev.y = y;
const rb = !!gp.buttons[BTN_RB]?.pressed;
if (rb && !prev.rb) this.onAction("kickR");
prev.rb = rb;
const lb = !!gp.buttons[BTN_LB]?.pressed;
if (lb && !prev.lb) this.onAction("kickL");
prev.lb = lb;
const dpadDown = !!gp.buttons[BTN_DPAD_DOWN]?.pressed;
if (dpadDown && !prev.dpadDown) this.onAction("sitToggle");
prev.dpadDown = dpadDown;
// DpadUp: short press = back to run; hold fires ONE loco switch.
const dpadUp = !!gp.buttons[BTN_DPAD_UP]?.pressed;
if (dpadUp && !prev.dpadUp) {
this.#dpadUpAt = now;
this.#dpadUpFired = false;
this.onAction("walk");
}
if (dpadUp && !this.#dpadUpFired && now - this.#dpadUpAt >= DPAD_UP_HOLD_MS) {
this.#dpadUpFired = true; // latch: one switch per hold
this.onAction("locoToggle");
}
prev.dpadUp = dpadUp;
// Triggers. Both open the beak analogically - the duck sings the
// wheee with its mouth, wider with the squeeze (jaw is purely visual:
// no sound and no policy input ever reads it, so this can't re-open
// the cross-talk fixed below). Physical Schmitt edges are detected
// first - state must advance even for blocked edges, so releasing a
// blocker never retro-fires the suppressed action - then the actions
// are gated so the two triggers stay mutually exclusive.
const rt = gp.buttons[BTN_RT]?.value ?? 0;
const lt = gp.buttons[BTN_LT]?.value ?? 0;
this.axes.jaw = Math.max(rt, lt);
this.axes.ride = lt; // raw squeeze, consumed per-frame for the wheee pitch
const rtEdge = !this.#rtDown && rt >= 0.35;
if (rtEdge) this.#rtDown = true;
else if (this.#rtDown && rt < 0.2) this.#rtDown = false;
const ltEdge = !this.#ltDown && lt >= 0.3;
if (ltEdge) this.#ltDown = true;
else if (this.#ltDown && lt < 0.2) this.#ltDown = false;
// LT wheee ride first: blocked only if RT was already down BEFORE
// this frame. On pads that mirror one combined trigger channel onto
// both button slots a squeeze raises rt and lt together; treating the
// same-frame rt rise as "engaged" would hand the race to the quack
// (the old bug: LT presses fired RT's sound). The LT edge wins the
// tie deterministically; cut the ride the instant LT drops below the
// low rail.
const rtWasDown = this.#rtDown && !rtEdge;
if (ltEdge && !rtWasDown) {
this.#ltRide = true;
this.onAction("wheeeStart");
} else if (this.#ltRide && !this.#ltDown) {
this.#ltRide = false;
this.onAction("wheeeStop");
}
// RT quack: consumed while LT is down or the ride is open. In the
// mirrored case above the lt rise opened the ride and set #ltDown in
// the same frame, so the phantom rt edge always lands here.
if (rtEdge && !this.#ltDown && !this.#ltRide) this.onAction("quack");
}
#zeroHead() {
this.head.neckPitch = 0;
this.head.pitch = 0;
this.head.yaw = 0;
this.head.roll = 0;
}
}
+118
View File
@@ -0,0 +1,118 @@
// Keyboard input source (see controller.js for the source interface
// contract). Hold-to-command movement keys plus one-shot action keys.
//
// e.code is the PHYSICAL key position, so one map covers QWERTY and AZERTY:
// arrows / WASD (ZQSD) run + turn. No strafe - vy stays 0.
const KEYMAP = {
ArrowUp: "fwd", KeyW: "fwd",
ArrowDown: "back", KeyS: "back",
ArrowLeft: "turnl", KeyA: "turnl",
ArrowRight: "turnr", KeyD: "turnr",
};
// One-shot keys -> controller actions. Physical Q/E (A/E on AZERTY) are the
// explicit left / right kicks, mirroring the pad's LB / RB; F alternates.
// R sits (crouch-glide in roller mode - the game decides, same way the
// roll action used to). Nothing dispatches "roll" any more.
const ACTION_KEYS = {
KeyC: "chaseToggle",
KeyG: "groundPick",
KeyM: "locoToggle",
KeyR: "sitToggle",
KeyQ: "kickL",
KeyE: "kickR",
KeyF: "alternateKick",
};
export class KeyboardSource {
id = "keyboard";
connected = true; // a keyboard is always assumed present
command = new Float32Array(3); // [vx, 0, wz], scaled to velocity limits
axes = { jaw: 0, orbitX: 0, orbitY: 0 }; // keyboard drives none of these
pressed = { fwd: false, back: false, turnl: false, turnr: false };
onAction = () => {}; // assigned by the Controller at registration
#held = new Set();
#getVelocityLimits;
// Limits snapshot so poll() only re-maps held keys when they actually
// change (the legs <-> rollers switch); event handlers do the live work.
#lims = [NaN, NaN, NaN];
#onKeyDown = null;
#onKeyUp = null;
#onBlur = null;
constructor({ getVelocityLimits }) {
this.#getVelocityLimits = getVelocityLimits;
}
init() {
this.#onKeyDown = (e) => {
if (e.repeat) return;
// Space always resets, and must not scroll the page.
if (e.code === "Space") {
e.preventDefault();
this.onAction("reset");
return;
}
const action = ACTION_KEYS[e.code];
if (action) {
this.onAction(action);
return;
}
const move = KEYMAP[e.code];
if (!move) return;
e.preventDefault();
this.#held.add(move);
this.#refresh();
};
this.#onKeyUp = (e) => {
const move = KEYMAP[e.code];
if (!move) return;
this.#held.delete(move);
this.#refresh();
};
// Losing window focus drops every held key (keyup events are missed).
this.#onBlur = () => {
this.#held.clear();
this.#refresh();
};
window.addEventListener("keydown", this.#onKeyDown);
window.addEventListener("keyup", this.#onKeyUp);
window.addEventListener("blur", this.#onBlur);
}
dispose() {
window.removeEventListener("keydown", this.#onKeyDown);
window.removeEventListener("keyup", this.#onKeyUp);
window.removeEventListener("blur", this.#onBlur);
}
// Claims twist authority while any movement key is held.
isActive() {
return this.#held.size > 0;
}
// The command is event-driven (recomputed on keydown/keyup/blur, so a
// press lands the same tick, not on the next frame); poll only re-maps
// held keys onto fresh velocity limits after a locomotion switch.
poll() {
const [limF, limB, limA] = this.#getVelocityLimits();
if (limF !== this.#lims[0] || limB !== this.#lims[1] || limA !== this.#lims[2]) {
this.#refresh();
}
}
#refresh() {
const lims = this.#getVelocityLimits();
const [limF, limB, limA] = lims;
this.#lims = lims;
const held = this.#held;
this.command[0] = held.has("fwd") ? limF : held.has("back") ? limB : 0;
this.command[2] = held.has("turnl") ? limA : held.has("turnr") ? -limA : 0;
this.pressed.fwd = held.has("fwd");
this.pressed.back = held.has("back");
this.pressed.turnl = held.has("turnl");
this.pressed.turnr = held.has("turnr");
}
}
+180
View File
@@ -0,0 +1,180 @@
// Touch input source (see controller.js for the source interface
// contract). Game Boy layout, two thumbs:
//
// Left thumb FLOATING analog stick: the lower-left quadrant of the
// screen (#touch-zone) is the grab area, and the stick base
// (#touch-stick) re-anchors under the finger wherever it
// lands - so the thumb never has to find a fixed circle -
// then snaps back to its resting spot on release. Vertical
// = vx (asymmetric fwd/back limits), horizontal = turn. The
// nub tracks the finger clamped to the base circle; the
// command is EMA-smoothed like the gamepad's so releases
// don't snap.
// Right thumb two round caps: A (#touch-a) fires alternateKick - the
// game alternates feet; B (#touch-b) quacks on press and
// holds the beak open (axes.jaw = 1) while held.
//
// The overlay DOM lives in index.html (#touch-ui); this module only wires
// pointer events to it. `connected` (mirrored onto body.touch-mode by
// rl.js, which is what actually shows the overlay) arms two ways:
// - (pointer: coarse) matches: phones/tablets, before any touch;
// - OR the first real touch anywhere: catches DevTools device modes and
// hybrid laptops the media query misses. Latching, like a gamepad.
const TOUCH_ALPHA = 0.18; // EMA smoothing toward the stick target
const TOUCH_DEADZONE = 0.12; // normalized deflection ignored around center
export class TouchSource {
id = "touch";
connected = false;
command = new Float32Array(3); // [vx, 0, wz], EMA-smoothed
axes = { jaw: 0, orbitX: 0, orbitY: 0 };
pressed = { stick: false, a: false, b: false };
onAction = () => {}; // assigned by the Controller at registration
#getVelocityLimits;
#active = false; // owns twist authority (stick engaged, until EMA settles)
#target = [0, 0]; // normalized deflection [x, right+] [y, up+]
#mq = null;
#onMq = null;
#disposers = [];
constructor({ getVelocityLimits }) {
this.#getVelocityLimits = getVelocityLimits;
}
init() {
this.#mq = window.matchMedia("(pointer: coarse)");
// Latching: once a device has proven it can touch, keep the thumbs.
// __microduckTouched carries a touch seen by the title page before
// this module booted.
if (window.__microduckTouched) this.connected = true;
this.#onMq = () => { this.connected = this.connected || this.#mq.matches; };
this.#mq.addEventListener("change", this.#onMq);
this.#onMq();
const armTouch = () => { this.connected = true; };
window.addEventListener("touchstart", armTouch, { once: true, passive: true });
this.#disposers.push(() => window.removeEventListener("touchstart", armTouch));
const zone = document.getElementById("touch-zone");
const stick = document.getElementById("touch-stick");
const nub = stick?.querySelector(".nub");
if (zone && stick && nub) this.#bindStick(zone, stick, nub);
this.#bindButton("touch-a", "a", () => this.onAction("alternateKick"));
this.#bindButton("touch-b", "b", () => this.onAction("quack"));
}
dispose() {
this.#mq?.removeEventListener("change", this.#onMq);
for (const off of this.#disposers) off();
this.#disposers = [];
}
isActive() {
return this.#active;
}
poll() {
const [x, y] = this.#target;
const [limF, limB, limA] = this.#getVelocityLimits();
const tvx = y >= 0 ? y * limF : y * -limB;
const twz = -x * limA;
this.command[0] += TOUCH_ALPHA * (tvx - this.command[0]);
this.command[2] += TOUCH_ALPHA * (twz - this.command[2]);
// Same authority rule as the gamepad sticks: grab on input, release
// once the smoothed command has settled back to ~zero.
if (this.pressed.stick) this.#active = true;
else if (this.#active && Math.abs(this.command[0]) + Math.abs(this.command[2]) < 0.01) {
this.#active = false;
this.command.fill(0);
}
// B holds the beak open; quack itself fired on the press edge.
this.axes.jaw = this.pressed.b ? 1 : 0;
}
#on(el, type, fn) {
el.addEventListener(type, fn);
this.#disposers.push(() => el.removeEventListener(type, fn));
}
#bindStick(zone, stick, nub) {
let pointerId = null;
let center = null; // stick center while grabbed, zone-local px
const setFrom = (e) => {
const zr = zone.getBoundingClientRect();
const R = stick.offsetWidth / 2;
const travel = R * 0.62; // max nub travel inside the base circle
let dx = e.clientX - zr.left - center.x;
let dy = e.clientY - zr.top - center.y;
const d = Math.hypot(dx, dy);
if (d > travel) { dx *= travel / d; dy *= travel / d; }
nub.style.transform = `translate(${dx}px, ${dy}px)`;
const nx = dx / travel, ny = -dy / travel; // up is +y
const mag = Math.hypot(nx, ny);
const live = mag >= TOUCH_DEADZONE;
this.#target[0] = live ? nx : 0;
this.#target[1] = live ? ny : 0;
};
const release = () => {
pointerId = null;
center = null;
this.pressed.stick = false;
stick.classList.remove("live");
nub.style.transform = "";
// Back to the CSS resting spot until the next grab.
stick.style.left = "";
stick.style.top = "";
stick.style.bottom = "";
this.#target[0] = 0;
this.#target[1] = 0;
};
this.#on(zone, "pointerdown", (e) => {
e.preventDefault();
pointerId = e.pointerId;
// Anchor the base exactly under the finger - a clamped anchor would
// start the stick with a phantom deflection near the zone edges. The
// circle clipping off-screen there is the standard floating-stick
// look, and it takes no pointer events anyway.
const zr = zone.getBoundingClientRect();
const R = stick.offsetWidth / 2;
center = { x: e.clientX - zr.left, y: e.clientY - zr.top };
stick.style.left = `${center.x - R}px`;
stick.style.top = `${center.y - R}px`;
stick.style.bottom = "auto";
this.pressed.stick = true;
stick.classList.add("live");
setFrom(e); // zero deflection at grab
// Last: capture can throw on exotic pointers and must not eat the
// press state above.
try { zone.setPointerCapture(e.pointerId); } catch {}
});
this.#on(zone, "pointermove", (e) => {
if (e.pointerId === pointerId) setFrom(e);
});
this.#on(zone, "pointerup", (e) => {
if (e.pointerId === pointerId) release();
});
this.#on(zone, "pointercancel", (e) => {
if (e.pointerId === pointerId) release();
});
}
#bindButton(elId, key, fire) {
const el = document.getElementById(elId);
if (!el) return;
this.#on(el, "pointerdown", (e) => {
e.preventDefault();
this.pressed[key] = true;
el.classList.add("down");
fire(); // on the press edge, not the release: arcade latency
try { el.setPointerCapture(e.pointerId); } catch {}
});
const release = () => {
this.pressed[key] = false;
el.classList.remove("down");
};
this.#on(el, "pointerup", release);
this.#on(el, "pointercancel", release);
}
}
+153
View File
@@ -0,0 +1,153 @@
// Waypoint input source (see controller.js for the source interface
// contract). PLAN.md Project 1 Phase A: click a point on the arena floor,
// the duck walks there. No new policy - this only turns a click into the
// same [vx, vy, wz] twist the walking policy already tracks.
//
// Click, not drag-follow: the mouse already drives OrbitControls (camera
// orbit) and the duck/ball grab-drag, so a live cursor-follow twist would
// fight both. A plain click (small movement, short hold) on empty floor
// is otherwise unclaimed input, and reads naturally as "go here" - the
// same gesture Project 5's tile grid uses.
//
// Arbitration: registered LAST in game.js's source list, so it is the
// Controller's fallback exactly like the keyboard source used to be -
// any keyboard/pad/touch input immediately preempts it (see
// controller.js's arbitration notes), and getManualOverride() cancels the
// pending target outright so releasing manual input doesn't snap the duck
// back onto a stale click.
import * as THREE from "three";
import { ARENA_HALF } from "../constants.js";
const WAYPOINT_ARRIVE_RADIUS = 0.12; // m, dead zone - commands zero inside it
const WAYPOINT_TURN_GAIN = 2.2; // rad/s commanded per rad of heading error, pre-clamp
const WAYPOINT_SMOOTH_ALPHA = 0.15; // EMA toward the steered command, per render frame
const WAYPOINT_CLICK_SLOP = 6; // px, pointerdown -> pointerup movement budget for a "click"
const WAYPOINT_CLICK_MS = 500; // ms, pointerdown -> pointerup duration budget
const wrapPi = (a) => Math.atan2(Math.sin(a), Math.cos(a));
// Three world (x, y, z) -> MJCF ground (x, -z); floor sits at three y = 0.
const FLOOR_PLANE = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
export class WaypointSource {
id = "waypoint";
connected = true; // a mouse is assumed present, like the keyboard
command = new Float32Array(3); // [vx, 0, wz], EMA-smoothed toward the target
axes = { jaw: 0, orbitX: 0, orbitY: 0 }; // drives none of these
pressed = {};
onAction = () => {}; // assigned by the Controller at registration
#camera;
#renderer;
#getVelocityLimits;
#getDuckPose; // () => [x, y, yaw] MJCF ground pose
#isSuppressed; // () => true while a click must not arm (grabbing, locked, wrong mode)
#getManualOverride; // () => true while another source is actively driving
#target = null; // [x, y] MJCF, or null when idle
#active = false;
#downAt = null; // { x, y, t } pointerdown snapshot, for the click-vs-drag check
#raycaster = new THREE.Raycaster();
#ndc = new THREE.Vector2();
#hit = new THREE.Vector3();
#onDown = null;
#onUp = null;
constructor({ camera, renderer, getVelocityLimits, getDuckPose, isSuppressed, getManualOverride }) {
this.#camera = camera;
this.#renderer = renderer;
this.#getVelocityLimits = getVelocityLimits;
this.#getDuckPose = getDuckPose;
this.#isSuppressed = isSuppressed;
this.#getManualOverride = getManualOverride;
}
init() {
this.#onDown = (e) => {
if (e.pointerType !== "mouse" || e.button !== 0) return;
if (e.target !== this.#renderer.domElement) return;
if (this.#isSuppressed()) return;
this.#downAt = { x: e.clientX, y: e.clientY, t: performance.now() };
};
this.#onUp = (e) => {
if (!this.#downAt || e.pointerType !== "mouse" || e.button !== 0) { this.#downAt = null; return; }
const { x, y, t } = this.#downAt;
this.#downAt = null;
if (this.#isSuppressed()) return;
const moved = Math.hypot(e.clientX - x, e.clientY - y);
const held = performance.now() - t;
// A drag (orbit or grab) shows up as either more movement than a
// click budget allows, or a slow deliberate press - either way, not
// a click.
if (moved > WAYPOINT_CLICK_SLOP || held > WAYPOINT_CLICK_MS) return;
this.#setTargetFromEvent(e);
};
window.addEventListener("pointerdown", this.#onDown);
window.addEventListener("pointerup", this.#onUp);
}
dispose() {
window.removeEventListener("pointerdown", this.#onDown);
window.removeEventListener("pointerup", this.#onUp);
}
isActive() {
return this.#active;
}
// Current target in MJCF ground coords, or null - read by game.js to
// place the click marker. Read-only.
get target() {
return this.#target;
}
// Cancel a pending target without walking it down (sim reset, mode
// change out from under it).
cancel() {
this.#target = null;
this.#active = false;
this.command.fill(0);
}
poll() {
if (this.#target && this.#getManualOverride()) this.#target = null;
if (!this.#target) {
this.command.fill(0);
this.#active = false;
return;
}
const [px, py, yaw] = this.#getDuckPose();
const dx = this.#target[0] - px, dy = this.#target[1] - py;
const dist = Math.hypot(dx, dy);
if (dist < WAYPOINT_ARRIVE_RADIUS) {
this.#target = null;
this.command.fill(0);
this.#active = false;
return;
}
const err = wrapPi(Math.atan2(dy, dx) - yaw);
const [limF, , limA] = this.#getVelocityLimits();
const wz = Math.min(limA, Math.max(-limA, err * WAYPOINT_TURN_GAIN));
// Forward speed falls off with heading error so the duck turns in
// place first rather than strafing (there is no strafe) toward a
// target that's behind it.
const vx = limF * Math.max(0, Math.cos(err));
this.command[0] += WAYPOINT_SMOOTH_ALPHA * (vx - this.command[0]);
this.command[2] += WAYPOINT_SMOOTH_ALPHA * (wz - this.command[2]);
this.#active = true;
}
#setTargetFromEvent(e) {
const r = this.#renderer.domElement.getBoundingClientRect();
this.#ndc.set(
((e.clientX - r.left) / r.width) * 2 - 1,
-((e.clientY - r.top) / r.height) * 2 + 1,
);
this.#raycaster.setFromCamera(this.#ndc, this.#camera);
if (!this.#raycaster.ray.intersectPlane(FLOOR_PLANE, this.#hit)) return;
const lim = ARENA_HALF - 0.05;
this.#target = [
Math.min(lim, Math.max(-lim, this.#hit.x)),
Math.min(lim, Math.max(-lim, -this.#hit.z)), // three -> MJCF
];
}
}
+365
View File
@@ -0,0 +1,365 @@
// Community move loading: resolve a move ref (Hub repo id, Academy session
// ref or a direct .onnx URL) into a validated onnxruntime session (or a
// command script) the game can drop into one of its slots. Mirrors the
// official publish pipeline's smoke run: shape checks, a zeros inference
// and two noisy inferences that must produce finite, non-constant actions
// before the session ever touches the duck.
//
// Slots (manifest schema 2, Academy decision D7):
// kind "perpetual" (gait) -> "walk" (default) or "sitstand" (slot field)
// kind "episodic" (trick) -> "trick": a one-shot on the R key
// kind "script" -> "script": a 13-D command timeline played on
// the base walker while R is toggled on
//
// The module is deliberately framework-free (no game imports): the caller
// hands in the `ort` namespace it already booted, and pure helpers like
// manifestIncompatibility are reusable by standalone pages without pulling
// the game bundle in.
import { OBS_SIZE, NUM_JOINTS, CMD_SIZE } from "./constants.js";
const HUB_BASE = "https://huggingface.co";
// Same-origin Academy endpoints (backend/play_api.py) for private moves.
const PLAY_API = "/api/play";
export const SUPPORTED_KINDS = ["perpetual", "episodic", "script"];
// Default one-shot length for an episodic trick without a duration claim.
const DEFAULT_TRICK_S = 5.0;
// Game slot a manifest mounts into (see the header). A missing manifest is
// a plain walk policy, exactly like v1.
export function slotForManifest(manifest) {
const kind = manifest?.kind ?? "perpetual";
if (kind === "script") return "script";
if (kind === "episodic") return "trick";
const slot = String(manifest?.slot ?? "walk").toLowerCase();
return slot === "sitstand" || slot === "sit" ? "sitstand" : "walk";
}
// Manifest claims the sim cannot satisfy (schema 2). Only present-and-wrong
// claims reject: an absent field is trusted to match the microduck defaults.
// Returns a human-readable reason, or null when the manifest is acceptable.
export function manifestIncompatibility(manifest) {
if (!manifest || typeof manifest !== "object") return null;
if (Array.isArray(manifest.policies)) {
return "multi-policy set: not loadable in v1 (pick a single-policy repo)";
}
if (manifest.model_api != null && manifest.model_api > 2) {
return `model_api ${manifest.model_api} is newer than this sim supports`;
}
const robotModel = manifest.robot?.model;
if (robotModel != null && robotModel !== "microduck") {
return `targets robot "${robotModel}", not microduck`;
}
const kind = manifest.kind ?? "perpetual";
if (!SUPPORTED_KINDS.includes(kind)) {
return `"${manifest.kind}" policies are not supported (kinds: ${SUPPORTED_KINDS.join(", ")})`;
}
// A script drives the built-in walker: no network claims to check.
if (kind === "script") return null;
if (manifest.obs_len != null && manifest.obs_len !== OBS_SIZE) {
return `expects ${manifest.obs_len} observations (sim provides ${OBS_SIZE})`;
}
if (manifest.action_len != null && manifest.action_len !== NUM_JOINTS) {
return `outputs ${manifest.action_len} actions (sim drives ${NUM_JOINTS})`;
}
if (kind === "perpetual") {
const slot = manifest.slot != null ? String(manifest.slot).toLowerCase() : null;
if (slot != null && !["walk", "sitstand", "sit"].includes(slot)) {
return `perpetual slot "${manifest.slot}" is not supported (walk or sitstand)`;
}
const encoding = manifest.command?.encoding;
if (encoding != null && encoding !== "constant") {
return `command encoding "${encoding}" is not supported yet`;
}
if (manifest.mode != null && manifest.mode !== "walk" && slot !== "sitstand" && slot !== "sit") {
return `mode "${manifest.mode}" is not supported yet (walk-slot only)`;
}
}
// Episodic tricks: every slot (stand, roulade, kick_left, ground_pick,
// R, ...) mounts on the R key as a zero-command one-shot.
return null;
}
// Parse the "session:<id>[:<round>]" ref form. Returns null when `r` is not
// a session ref. `round` is null when absent.
function parseSessionRef(r) {
const m = /^session:([\w.-]+)(?::([\w.-]+))?$/i.exec(r);
return m ? { id: m[1], round: m[2] ?? null } : null;
}
// Build a same-origin Academy URL for a private session artifact.
function sessionApiUrl(endpoint, { id, round }, extra = {}) {
const q = new URLSearchParams({ session: id });
if (round != null) q.set("round", String(round));
for (const [k, v] of Object.entries(extra)) q.set(k, v);
return `${PLAY_API}/${endpoint}?${q}`;
}
// A move ref is one of:
// "org/repo" a Hub move repo (manifest + policy.onnx)
// "session:<id>[:<round>]" a private Academy run, served same-origin
// "https://.../x.onnx" a direct URL (sibling manifest probed)
// Resolves to the URLs of the three artifacts the loader may need.
export function resolvePolicyRef(ref) {
const r = String(ref || "").trim();
if (/^https?:\/\//i.test(r)) {
let manifestUrl = null;
let scriptUrl = null;
try {
const u = new URL(r);
const name = u.pathname.split("/").pop() || "";
if (/\.onnx$/i.test(name)) {
const dir = u.pathname.slice(0, -name.length);
u.pathname = `${dir}manifest.json`;
manifestUrl = u.href;
u.pathname = `${dir}move_script.json`;
scriptUrl = u.href;
}
} catch { /* unparsable: no manifest probe */ }
return {
kind: "url",
name: r.split("/").pop()?.split("?")[0] || r,
author: null,
onnxUrl: r,
manifestUrl,
scriptUrl,
manifestOptional: true,
};
}
const sess = parseSessionRef(r);
if (sess) {
return {
kind: "session",
name: sess.round != null ? `session ${sess.id} (round ${sess.round})` : `session ${sess.id}`,
author: null,
onnxUrl: sessionApiUrl("policy", sess),
manifestUrl: sessionApiUrl("manifest", sess),
scriptUrl: sessionApiUrl("file", sess, { path: "move_script.json" }),
manifestOptional: true,
};
}
if (!/^[\w.-]+\/[\w.-]+$/.test(r)) {
throw new Error(`invalid move ref "${r}" (expected org/repo, session:<id> or a .onnx URL)`);
}
return {
kind: "hub",
name: r,
author: r.split("/")[0],
repoId: r,
onnxUrl: `${HUB_BASE}/${r}/resolve/main/policy.onnx`,
manifestUrl: `${HUB_BASE}/${r}/resolve/main/manifest.json`,
scriptUrl: `${HUB_BASE}/${r}/resolve/main/move_script.json`,
};
}
// Manifest fetch for the loader (and any future policy-browsing page):
// 404 (no manifest) resolves to null, network/parse failures throw.
export async function fetchPolicyManifest(repoId) {
const res = await fetch(`${HUB_BASE}/${repoId}/resolve/main/manifest.json`);
if (res.status === 404) return null;
// The Hub answers 401 for repos that don't exist (or are private).
if (res.status === 401 || res.status === 403) {
throw new Error(`repo "${repoId}" not found on the Hub (or private)`);
}
if (!res.ok) throw new Error(`manifest fetch failed (HTTP ${res.status})`);
return res.json();
}
// Optional sibling manifest (direct URL / Academy session): 404 = none.
// A 401 from the Academy means the visitor is not signed in - that one is
// worth surfacing instead of silently playing nothing.
async function fetchOptionalManifest(url) {
let res;
try {
res = await fetch(url);
} catch {
return null;
}
if (res.status === 401) throw new Error("sign in to the Academy to play a private move");
if (!res.ok) return null;
try {
return await res.json();
} catch {
return null;
}
}
// Command script (kind "script"): {duration_s, loop, keyframes:[{t, cmd[13]}]}.
// Keyframes are sorted by t and every cmd is padded/truncated to CMD_SIZE.
export function normalizeMoveScript(raw) {
if (!raw || typeof raw !== "object" || !Array.isArray(raw.keyframes) || !raw.keyframes.length) {
throw new Error("move_script.json has no keyframes");
}
const keyframes = raw.keyframes.map((k, i) => {
const t = Number(k?.t);
if (!Number.isFinite(t) || t < 0) throw new Error(`keyframe ${i}: bad time`);
const src = Array.isArray(k?.cmd) ? k.cmd : [];
const cmd = new Float32Array(CMD_SIZE);
for (let c = 0; c < CMD_SIZE; c++) {
const v = Number(src[c] ?? 0);
if (!Number.isFinite(v)) throw new Error(`keyframe ${i}: non-finite command`);
cmd[c] = v;
}
return { t, cmd };
});
keyframes.sort((a, b) => a.t - b.t);
const last = keyframes[keyframes.length - 1].t;
const durationS = Number.isFinite(Number(raw.duration_s)) && Number(raw.duration_s) > 0
? Math.max(Number(raw.duration_s), last)
: Math.max(last, 0.02);
return { keyframes, durationS, loop: raw.loop !== false, description: raw.description || "" };
}
// Linearly interpolated command at time t (loop-aware), written into `out`.
export function scriptCommandAt(script, t, out) {
const { keyframes, durationS, loop } = script;
let tt = t;
if (loop && durationS > 0) tt = ((t % durationS) + durationS) % durationS;
if (tt <= keyframes[0].t) { out.set(keyframes[0].cmd); return out; }
for (let i = 0; i < keyframes.length - 1; i++) {
const a = keyframes[i], b = keyframes[i + 1];
if (tt >= a.t && tt <= b.t) {
const u = (tt - a.t) / Math.max(b.t - a.t, 1e-6);
for (let c = 0; c < CMD_SIZE; c++) out[c] = (1 - u) * a.cmd[c] + u * b.cmd[c];
return out;
}
}
out.set(keyframes[keyframes.length - 1].cmd);
return out;
}
// Publish-pipeline smoke run: 1 input / 1 output, a zeros pass plus two
// small-noise passes; every output must be [1,14], finite, and the noisy
// passes must not produce identical actions (a constant net is a dud).
async function validateSession(ort, session) {
const { inputNames, outputNames } = session;
if (inputNames.length !== 1 || outputNames.length !== 1) {
throw new Error(
`expected 1 input / 1 output, got ${inputNames.length}/${outputNames.length}`,
);
}
const runOnce = async (fill) => {
const buf = new Float32Array(OBS_SIZE);
if (fill) for (let i = 0; i < OBS_SIZE; i++) buf[i] = (Math.random() - 0.5) * 0.1;
const feeds = { [inputNames[0]]: new ort.Tensor("float32", buf, [1, OBS_SIZE]) };
const out = (await session.run(feeds))[outputNames[0]];
const dims = out.dims;
if (dims.length !== 2 || dims[0] !== 1 || dims[1] !== NUM_JOINTS) {
throw new Error(`bad output shape [${dims.join(",")}] (expected [1,${NUM_JOINTS}])`);
}
const act = out.data;
for (let j = 0; j < NUM_JOINTS; j++) {
if (!Number.isFinite(act[j])) throw new Error("non-finite actions in smoke run");
}
return Float32Array.from(act);
};
await runOnce(false);
const a = await runOnce(true);
const b = await runOnce(true);
let maxDiff = 0;
for (let j = 0; j < NUM_JOINTS; j++) maxDiff = Math.max(maxDiff, Math.abs(a[j] - b[j]));
if (maxDiff < 1e-9) throw new Error("constant output in smoke run (dead policy)");
}
async function fetchOrThrow(url, what) {
const res = await fetch(url);
if (!res.ok) {
if (res.status === 401) throw new Error("sign in to the Academy to play a private move");
throw new Error(
res.status === 404 ? `no ${what} found at ${url}` : `${what} download failed (HTTP ${res.status})`,
);
}
return res;
}
// Load + validate a community move. Resolves to everything the game needs
// to mount it in its slot; throws with a clear message on any failure.
// onProgress receives coarse stages for the HUD loading line.
//
// Result: { kind, slot, name, title, author, academy, ref, actionScale,
// durationS, session?, inputName?, outputName?, script? }
export async function loadCustomPolicy(ref, { ort, onProgress = () => {} } = {}) {
const resolved = resolvePolicyRef(ref);
let name = resolved.name;
let author = resolved.author;
let actionScale = 1.0;
let manifest = null;
if (resolved.manifestUrl) {
onProgress("manifest");
if (resolved.manifestOptional) {
// Sibling manifest of a direct URL / session: 404 or a network error
// just means "no manifest" (a plain walk policy), exactly like before
// the probe existed. Only present-and-incompatible manifests reject.
manifest = await fetchOptionalManifest(resolved.manifestUrl);
} else {
try {
manifest = await fetchPolicyManifest(resolved.repoId);
} catch (e) {
// TypeError = the fetch itself failed (offline, CORS); anything else
// already carries a specific message (missing repo, bad status).
throw e instanceof TypeError ? new Error(`could not reach the Hub: ${e.message}`) : e;
}
}
if (manifest) {
const reason = manifestIncompatibility(manifest);
if (reason) throw new Error(reason);
if (typeof manifest.name === "string" && manifest.name) name = manifest.name;
if (Number.isFinite(manifest.action_scale)) actionScale = manifest.action_scale;
if (typeof manifest.academy?.author === "string" && manifest.academy.author) {
author = manifest.academy.author;
}
}
}
const slot = slotForManifest(manifest);
const kind = manifest?.kind ?? "perpetual";
const academy = manifest?.academy && typeof manifest.academy === "object" ? manifest.academy : null;
// HUD plate text: the Academy prompt when there is one, else the name
// (descriptions are paragraphs, too long for the chip).
const title = academy?.prompt || name;
const base = { kind, slot, name, title, author, academy, ref: String(ref), actionScale };
if (slot === "script") {
if (!resolved.scriptUrl) throw new Error("script moves need a manifest with a sibling move_script.json");
onProgress("script");
const res = await fetchOrThrow(resolved.scriptUrl, "move_script.json");
let raw;
try {
raw = await res.json();
} catch {
throw new Error("move_script.json is not valid JSON");
}
const script = normalizeMoveScript(raw);
return { ...base, script, durationS: script.durationS };
}
onProgress("download");
const res = await fetchOrThrow(resolved.onnxUrl, "policy.onnx");
const bytes = new Uint8Array(await res.arrayBuffer());
onProgress("session");
let session;
try {
session = await ort.InferenceSession.create(bytes, { executionProviders: ["wasm"] });
} catch (e) {
throw new Error(`not a loadable ONNX model: ${e?.message || e}`);
}
onProgress("validate");
await validateSession(ort, session);
const claimed = Number(manifest?.duration_s ?? manifest?.episode_s ?? manifest?.episode?.duration_s);
const durationS = slot === "trick"
? (Number.isFinite(claimed) && claimed > 0 ? Math.min(claimed, 30) : DEFAULT_TRICK_S)
: null;
return {
...base,
session,
durationS,
inputName: session.inputNames[0],
outputName: session.outputNames[0],
};
}
+415
View File
@@ -0,0 +1,415 @@
// Standalone JS port of microduck_app's src/duck/kinematics.ts.
// Loads kinematics.json (built from the MJCF by build_kinematics.py) and
// builds an Object3D tree with one Group per body. Joints become per-body
// 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 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
// robot/alpha/ stay on disk for reference but the code no longer
// targets them.
export const MODEL_DIR = "./robot/mjlab";
// On a private HF Space, asset requests carry the ?__sign JWT (auth
// cookies may be blocked in the hub iframe). Identity everywhere else.
import { signed } from "./signed.js";
// Meshes fully occluded inside the shells at every demo camera angle,
// verified empirically by per-mesh pixel-diff (front 3/4, back, low
// front close-up): hiding each changes exactly 0 pixels. Skipped at
// load time so their bytes are never fetched. Load everything with
// `?all=1` for debugging.
const HIDDEN_MESHES = new Set([]);
export async function loadKinematics(url) {
// 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}`);
const k = await r.json();
// The exported mesh_dir is root-absolute ("/robot/mjlab/meshes"), which
// breaks when the app is served under a prefix (/play/). Rebase it like
// every other asset URL (MODEL_DIR is "./robot/mjlab").
if (typeof k.mesh_dir === "string" && k.mesh_dir.startsWith("/")) {
k.mesh_dir = `.${k.mesh_dir}`;
}
// Full-resolution meshes by default (the reduction will be redone
// interactively in Blender later). `?lite=1` opts into a decimated
// meshes-lite/ sibling if present.
if (new URLSearchParams(location.search).get("lite") === "1") {
k.mesh_dir = k.mesh_dir.replace(/\/meshes$/, "/meshes-lite");
}
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.
export async function buildRig(k, opts = {}) {
// placer holds world-space position + yaw (no axis-conversion).
const placer = new THREE.Group();
placer.name = "duck_placer";
// root applies the MJCF +Z up -> three.js +Y up convention fix.
const root = new THREE.Group();
root.name = "duck_root";
root.rotation.x = -Math.PI / 2;
placer.add(root);
const bodies = new Map();
const joints = 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) => {
const entry = geomByName.get(name);
if (entry) return Promise.resolve(entry);
if (!extraStlCache.has(name)) {
extraStlCache.set(
name,
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);
const display = toCreasedNormals(welded, CREASE);
display.scale(1e-3, 1e-3, 1e-3);
welded.scale(1e-3, 1e-3, 1e-3);
return { display, welded };
}),
);
}
return extraStlCache.get(name);
};
for (const b of k.bodies) {
const g = new THREE.Group();
g.name = b.name;
g.position.set(b.pos[0], b.pos[1], b.pos[2]);
g.quaternion.set(b.quat[1], b.quat[2], b.quat[3], b.quat[0]);
bodies.set(b.name, g);
}
for (const b of k.bodies) {
const g = bodies.get(b.name);
if (b.parent && bodies.has(b.parent)) bodies.get(b.parent).add(g);
else root.add(g);
}
for (const b of k.bodies) {
if (!b.joint || (b.joint.type && b.joint.type !== "hinge")) continue;
const g = bodies.get(b.name);
joints.set(b.joint.name, {
body: g,
axis: new THREE.Vector3(...b.joint.axis).normalize(),
baseQuat: g.quaternion.clone(),
range: b.joint.range ?? null,
});
}
// Cache materials by their resolved PBR props so identical parts share
// one GPU material instance.
const matCache = new Map();
// Optional (meshName, bodyName, rgba) -> material spec hook. A spec is
// { color: [r,g,b], roughness, metalness, opacity? }; plain rgba arrays
// are also accepted for backwards compat.
const materialForMesh = opts.materialForMesh ?? null;
const matFor = (spec) => {
const color = spec.color;
const roughness = spec.roughness ?? 0.5;
const metalness = spec.metalness ?? 0.0;
const opacity = spec.opacity ?? 1;
const key = `${color.join(",")}|${roughness}|${metalness}|${opacity}`;
const cached = matCache.get(key);
if (cached) return cached;
const m = new THREE.MeshStandardMaterial({
color: new THREE.Color(...color),
roughness,
metalness,
transparent: opacity < 1,
opacity,
});
matCache.set(key, m);
return m;
};
const toSpec = (v, fallbackRgba) => {
if (!v) return { color: fallbackRgba.slice(0, 3), opacity: fallbackRgba[3] ?? 1 };
if (Array.isArray(v)) return { color: v.slice(0, 3), opacity: v[3] ?? 1 };
return v;
};
// Optional interior ink lines: hard edges above the threshold angle
// drawn as line segments, comic style. Cached per mesh file.
const inkOpts = opts.inkEdges ?? null;
const inkMat = inkOpts
? new THREE.LineBasicMaterial({
color: inkOpts.color ?? 0x0a0a0e,
transparent: true,
opacity: inkOpts.opacity ?? 0.55,
})
: null;
const edgeCache = new Map();
const edgesFor = (name, welded) => {
if (!edgeCache.has(name)) {
edgeCache.set(name, new THREE.EdgesGeometry(welded, inkOpts.threshold ?? 40));
}
return edgeCache.get(name);
};
const pending = [];
const loadAll = new URLSearchParams(location.search).get("all") === "1";
// The MJCF lists a few geoms twice with identical transforms (visual +
// collision copies of power_support, soles, legs); drawing both would
// only z-fight, so exact duplicates are skipped.
const seenGeoms = new Set();
for (const b of k.bodies) {
const g = bodies.get(b.name);
if (!g) continue;
for (const geom of b.geoms) {
if (geom.type && geom.type !== "mesh") continue;
if (!geom.mesh) continue;
if (!loadAll && HIDDEN_MESHES.has(geom.mesh)) continue;
const dupKey = `${b.name}|${geom.mesh}|${geom.pos}|${geom.quat}`;
if (seenGeoms.has(dupKey)) continue;
seenGeoms.add(dupKey);
pending.push(
loadMesh(geom.mesh).then(({ display, welded }) => {
const rgba = geom.color
? [geom.color[0], geom.color[1], geom.color[2], geom.color[3] ?? 1]
: [0.85, 0.85, 0.85, 1];
const spec = toSpec(materialForMesh?.(geom.mesh, b.name, rgba), rgba);
const m = new THREE.Mesh(display, matFor(spec));
// Mesh filename tag so callers can re-skin materials in place
// (survives cloneRig: Object3D.copy deep-copies userData).
m.userData.meshName = geom.mesh;
if (geom.pos) m.position.set(...geom.pos);
if (geom.quat) m.quaternion.set(geom.quat[1], geom.quat[2], geom.quat[3], geom.quat[0]);
g.add(m);
if (inkMat) {
const lines = new THREE.LineSegments(edgesFor(geom.mesh, welded), inkMat);
lines.position.copy(m.position);
lines.quaternion.copy(m.quaternion);
g.add(lines);
}
}),
);
}
}
await Promise.all(pending);
const rig = { placer, root, bodies, joints };
setupJawPivot(rig);
return rig;
}
// ── Jaw hinge ───────────────────────────────────────────────────────────
// 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
// 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) => {
if (o.isMesh && JAW_MESH_NAMES.has(o.userData.meshName)) meshes.push(o);
});
if (!meshes.length) return;
const body = meshes[0].parent;
// 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 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();
const hingeL = body.worldToLocal(hingeW.clone());
const axisL = axisW.applyQuaternion(bodyQuatInv).normalize();
const pivot = new THREE.Group();
pivot.name = "jaw_pivot";
pivot.position.copy(hingeL);
// Plain array so Object3D.copy's JSON userData clone preserves it.
pivot.userData.jawAxis = axisL.toArray();
body.add(pivot);
for (const m of meshes) {
m.position.sub(hingeL);
pivot.add(m);
}
}
// Open the beak: 0 = closed, 1 = fully open (JAW_MAX_OPEN rad). The pivot
// is resolved lazily by name so clones from cloneRig work transparently.
const _jawAxis = new THREE.Vector3();
export function setJawOpen(rig, open) {
if (rig._jawPivot === undefined) {
rig._jawPivot = rig.placer.getObjectByName("jaw_pivot") ?? null;
}
const pivot = rig._jawPivot;
if (!pivot) return;
_jawAxis.fromArray(pivot.userData.jawAxis);
pivot.quaternion.setFromAxisAngle(_jawAxis, JAW_MAX_OPEN * open);
}
// Set one named joint, clamped to its MJCF range when known.
export function setJoint(rig, name, angle) {
const j = rig.joints.get(name);
if (!j) return;
let a = angle;
if (j.range) a = Math.min(j.range[1], Math.max(j.range[0], a));
const rot = _q.setFromAxisAngle(j.axis, a);
j.body.quaternion.copy(j.baseQuat).multiply(rot);
}
const _q = new THREE.Quaternion();
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 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).
export function cloneRig(rig) {
const placer = rig.placer.clone(true);
const root = placer.getObjectByName("duck_root");
const bodies = new Map();
for (const name of rig.bodies.keys()) {
bodies.set(name, placer.getObjectByName(name));
}
const joints = new Map();
for (const [name, j] of rig.joints) {
joints.set(name, {
body: placer.getObjectByName(j.body.name),
axis: j.axis, // read-only, safe to share
baseQuat: j.baseQuat.clone(),
range: j.range,
});
}
return { placer, root, bodies, joints };
}
// Ground using the whole rig's bounding box (sitting pose folds the legs
// under the trunk, so the feet are not the lowest point).
const _box = new THREE.Box3();
export function groundFullBody(rig, floorY = 0) {
rig.placer.updateWorldMatrix(true, true);
_box.setFromObject(rig.placer);
if (!Number.isFinite(_box.min.y)) return 0;
rig.placer.position.y += floorY - _box.min.y;
return floorY - _box.min.y;
}
// "SIT" keyframe. The mjlab model shares alpha's conventions (same
// onshape-to-robot pipeline): neck_pitch range max is 1.0472, so
// neck_pitch sits just under it (headroom for the breathing oscillation,
// +-0.025) and head_pitch compensates to keep the head level-ish with a
// slight upward tilt toward the camera. NOTE: head_pitch sign is
// inverted vs v1.5 (positive = head down), so the compensation is
// positive here (verified visually).
export const SITTING_POSE = {
left_hip_yaw: 0.0,
left_hip_roll: 0.0,
left_hip_pitch: -0.5236,
left_knee: 1.0472,
left_ankle: 0.0,
neck_pitch: 1.02,
head_pitch: 0.9,
head_yaw: 0.0,
head_roll: 0.0,
right_hip_yaw: 0.0,
right_hip_roll: 0.0,
right_hip_pitch: 0.5236,
right_knee: -1.0472,
right_ankle: 0.0,
};
+140
View File
@@ -0,0 +1,140 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>fx demo - glitch materialization</title>
<style>
html, body { margin: 0; height: 100%; background: #0b0d10; overflow: hidden; }
#app { position: fixed; inset: 0; }
#replay {
position: fixed; top: 16px; left: 16px; z-index: 10;
font: 700 13px/1 "SF Mono", ui-monospace, Menlo, monospace;
letter-spacing: 0.14em;
color: #ff7a2f; background: rgba(11, 13, 16, 0.85);
border: 1px solid #ff7a2f; border-radius: 4px;
padding: 10px 18px; cursor: pointer;
text-shadow: 0 0 8px rgba(255, 122, 47, 0.5);
}
#replay:hover { background: rgba(255, 122, 47, 0.15); box-shadow: 0 0 14px rgba(255, 122, 47, 0.35); }
#replay:active { transform: translateY(1px); }
#status {
position: fixed; bottom: 14px; left: 16px; z-index: 10;
font: 11px/1.4 ui-monospace, Menlo, monospace;
color: #3d4652; letter-spacing: 0.08em; user-select: none;
}
</style>
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.164.1/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.164.1/examples/jsm/"
}
}
</script>
</head>
<body>
<div id="app"></div>
<button id="replay" type="button" aria-label="Replay the glitch materialization">REPLAY</button>
<div id="status">loading rig...</div>
<script type="module">
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
import { loadKinematics, buildRig, groundFullBody } from "../duck.js";
import { VARIANTS, materialHookFor } from "../variants.js";
import * as fx from "./fx-glitch.js";
const mount = document.getElementById("app");
const statusEl = document.getElementById("status");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b0d10);
const camera = new THREE.PerspectiveCamera(40, 1, 0.02, 30);
camera.position.set(0.42, 0.22, 0.5);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(2, window.devicePixelRatio));
renderer.toneMapping = THREE.ACESFilmicToneMapping;
mount.appendChild(renderer.domElement);
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment()).texture;
scene.environmentIntensity = 0.45;
// Same light rig as the live playground.
scene.add(new THREE.AmbientLight(0xffffff, 0.6));
const keyLight = new THREE.DirectionalLight(0xffffff, 1.6);
keyLight.position.set(2, 4, 2);
scene.add(keyLight);
const fill = new THREE.DirectionalLight(0xffffff, 0.4);
fill.position.set(-2, 2, 1.5);
scene.add(fill);
const rim = new THREE.DirectionalLight(0xffb366, 0.7);
rim.position.set(0, 3, -2);
scene.add(rim);
// Ground: dark disc + faint grid.
const ground = new THREE.Mesh(
new THREE.CircleGeometry(1.4, 64).rotateX(-Math.PI / 2),
new THREE.MeshStandardMaterial({ color: 0x11141a, roughness: 0.95, metalness: 0 }),
);
scene.add(ground);
const grid = new THREE.GridHelper(2.4, 48, 0x232a33, 0x161b22);
grid.position.y = 0.001;
scene.add(grid);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.target.set(0, 0.1, 0);
controls.minDistance = 0.15;
controls.maxDistance = 3;
function resize() {
const w = mount.clientWidth, h = mount.clientHeight;
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.setSize(w, h);
}
window.addEventListener("resize", resize);
resize();
// ── Isolated duck rig (classic variant, standing pose) ────────────
// MODEL_DIR is page-relative ("./robot/mjlab") and resolves wrong from
// /fx/; mesh_dir inside the JSON is root-absolute so only this differs.
const k = await loadKinematics("../robot/mjlab/kinematics.json");
const rig = await buildRig(k, { materialForMesh: materialHookFor(VARIANTS.classic) });
groundFullBody(rig, 0);
scene.add(rig.placer);
// Aim the camera at the duck's actual center.
const box = new THREE.Box3().setFromObject(rig.placer);
const center = box.getCenter(new THREE.Vector3());
controls.target.copy(center);
fx.init({ THREE, scene, rig, camera, renderer });
statusEl.textContent = `fx: ${fx.name} | drag to orbit`;
document.getElementById("replay").addEventListener("click", () => fx.start());
// Debug hook for deterministic mid-effect screenshots.
window.fx = {
start: () => fx.start(),
setProgress: (p) => fx.setProgress(p),
isDone: () => fx.isDone(),
};
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const dt = Math.min(0.05, clock.getDelta());
fx.update(dt, clock.elapsedTime);
controls.update();
renderer.render(scene, camera);
});
// Auto-play once everything is loaded.
setTimeout(() => fx.start(), 500);
</script>
</body>
</html>
+113
View File
@@ -0,0 +1,113 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>FX demo - holographic wireframe scan-up</title>
<style>
html, body { margin: 0; height: 100%; background: #0b0d10; overflow: hidden; }
#app { position: fixed; inset: 0; }
#hud {
position: fixed; top: 14px; left: 14px; z-index: 10;
font: 12px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
color: #ff7a2f; user-select: none;
}
#replay {
margin-top: 8px; padding: 7px 18px; cursor: pointer;
font: 600 12px ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em; color: #ff7a2f;
background: rgba(255, 122, 47, 0.08);
border: 1px solid rgba(255, 122, 47, 0.55); border-radius: 4px;
}
#replay:hover { background: rgba(255, 122, 47, 0.2); }
</style>
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.164.1/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.164.1/examples/jsm/"
}
}
</script>
</head>
<body>
<div id="app"></div>
<div id="hud">
FX: HOLOGRAPHIC WIREFRAME SCAN-UP<br />
<button id="replay">REPLAY</button>
</div>
<script type="module">
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { loadKinematics, buildRig, groundFullBody } from "../duck.js";
import { VARIANTS, materialHookFor } from "../variants.js";
import * as fx from "./fx-wireframe.js";
const mount = document.getElementById("app");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b0d10);
const camera = new THREE.PerspectiveCamera(40, 1, 0.02, 30);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(2, window.devicePixelRatio));
renderer.toneMapping = THREE.ACESFilmicToneMapping;
mount.appendChild(renderer.domElement);
// Same light rig as the live app so materials read identically.
scene.add(new THREE.AmbientLight(0xffffff, 0.6));
const keyLight = new THREE.DirectionalLight(0xffffff, 1.6);
keyLight.position.set(2, 4, 2);
scene.add(keyLight);
const fill = new THREE.DirectionalLight(0xffffff, 0.4);
fill.position.set(-2, 2, 1.5);
scene.add(fill);
const rim = new THREE.DirectionalLight(0xffb366, 0.7);
rim.position.set(0, 3, -2);
scene.add(rim);
const grid = new THREE.GridHelper(2, 40, 0x232c3a, 0x151a22);
scene.add(grid);
const resize = () => {
const w = mount.clientWidth, h = mount.clientHeight;
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.setSize(w, h);
};
window.addEventListener("resize", resize);
resize();
// Isolated duck rig, classic colourway.
const k = await loadKinematics("/robot/mjlab/kinematics.json");
const rig = await buildRig(k, { materialForMesh: materialHookFor(VARIANTS.classic) });
groundFullBody(rig);
scene.add(rig.placer);
// Frame the duck.
rig.placer.updateWorldMatrix(true, true);
const box = new THREE.Box3().setFromObject(rig.placer);
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3()).length();
camera.position.set(center.x + size * 1.5, center.y + size * 0.85, center.z + size * 1.9);
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.copy(center);
controls.enableDamping = true;
controls.update();
fx.init({ THREE, scene, rig, camera, renderer });
fx.start();
window.fx = fx; // fx.setProgress(p) for deterministic captures
document.getElementById("replay").addEventListener("click", () => fx.start());
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const dt = Math.min(clock.getDelta(), 0.05);
fx.update(dt, clock.elapsedTime);
controls.update();
renderer.render(scene, camera);
});
</script>
</body>
</html>
+311
View File
@@ -0,0 +1,311 @@
// Cyberpunk 2077-style glitch materialization for the Microduck rig.
//
// The duck appears as stacked horizontal slices that flicker in and out
// with random screen-space horizontal offsets, converging to their true
// position. Chromatic aberration is faked with two additive silhouette
// ghosts (cyan / orange) offset left-right, digital noise blocks flash
// emissive or invert the surface colour, and a final warm flash "snaps"
// everything crisp.
//
// Implementation: onBeforeCompile injections on CACHED clones of the rig
// materials (same pattern and same program-cache trap as the entrance
// dissolve in rl.js: clones are cached per original material and reused
// on every replay, each with a unique customProgramCacheKey, otherwise
// three.js would reuse a compiled program without re-binding uniforms).
// All uniforms are shared singleton objects so one JS write per frame
// drives every material.
export const name = "glitch";
const DURATION = 1.15; // seconds
const TICK_HZ = 30; // discrete glitch update rate (digital feel)
const SLICES = 24;
// ── Shared uniforms (one instance drives all cloned materials) ──────────
const uP = { value: 0 }; // progress 0..1 (0 = invisible)
const uSeed = { value: 0 }; // discrete tick, drives all hashes
const uAmp = { value: 0 }; // slice offset amplitude (view-space meters)
const uFlash = { value: 0 }; // final snap flash intensity
const uGhostOff = { value: 0 }; // RGB-split ghost separation (meters)
const uB = { value: null }; // vec4(minY, height, sliceH, 0) world bounds
let T = null; // injected THREE namespace
let rigRef = null;
let playing = false;
let scrubbed = false;
let done = true;
let elapsed = 0;
// Deterministic JS-side hash, mirrors the GLSL one.
const jhash = (n) => {
const s = Math.sin(n * 127.1 + 311.7) * 43758.5453;
return s - Math.floor(s);
};
// ── GLSL injection ──────────────────────────────────────────────────────
const GLSL_HELPERS = /* glsl */ `
varying vec3 vGlW;
uniform float uGlP, uGlSeed;
uniform vec4 uGlB;
float glHash2(vec2 q) { return fract(sin(dot(q, vec2(127.1, 311.7))) * 43758.5453); }
vec3 glHash3(vec2 q) { return vec3(glHash2(q), glHash2(q + 17.17), glHash2(q + 31.3)); }
`;
function injectGlitch(shader, { signU = null, ghost = false } = {}) {
shader.uniforms.uGlP = uP;
shader.uniforms.uGlSeed = uSeed;
shader.uniforms.uGlAmp = uAmp;
shader.uniforms.uGlFlash = uFlash;
shader.uniforms.uGlGhostOff = uGhostOff;
shader.uniforms.uGlSign = signU ?? { value: 0 };
shader.uniforms.uGlB = uB;
shader.vertexShader = shader.vertexShader
.replace(
"#include <common>",
"#include <common>\n" + GLSL_HELPERS + "uniform float uGlAmp, uGlSign, uGlGhostOff;\n",
)
.replace(
"#include <project_vertex>",
/* glsl */ `#include <project_vertex>
vec4 glWp = modelMatrix * vec4(transformed, 1.0);
vGlW = glWp.xyz;
if (uGlP < 1.0) {
float glSid = floor((glWp.y - uGlB.x) / uGlB.z);
// Fraction of moving slices shrinks as p rises: convergence.
float glMove = step(0.25 + 0.62 * uGlP, glHash2(vec2(glSid * 1.71 + 4.2, uGlSeed + 13.0)));
float glOff = (glHash2(vec2(glSid, uGlSeed)) - 0.5) * 2.0 * uGlAmp * glMove;
// Occasional whole-body frame jump for one tick.
if (glHash2(vec2(uGlSeed, 3.17)) > 0.86) {
glOff += (glHash2(vec2(uGlSeed, 9.91)) - 0.5) * 3.0 * uGlAmp;
}
glOff += uGlSign * uGlGhostOff;
// View-space X = screen-horizontal, the classic spawn-glitch axis.
mvPosition.x += glOff;
gl_Position = projectionMatrix * mvPosition;
}`,
);
const sliceDiscard = /* glsl */ `
float glEdge = 0.0, glInvAmt = 0.0;
vec3 glAddC = vec3(0.0);
if (uGlP < 1.0) {
float glSid = floor((vGlW.y - uGlB.x) / uGlB.z);
float glH = glHash2(vec2(glSid, uGlSeed + 0.7));
float glVis = smoothstep(0.02, 0.82, uGlP) * 1.35;
// Two-three full-silhouette pre-flashes right at the start.
float glPre = (uGlP > 0.015 && uGlP < 0.14 && glHash2(vec2(uGlSeed, 7.7)) > 0.72) ? 1.0 : 0.0;
glVis = max(glVis, glPre);
if (glH > glVis) discard;
glEdge = max(glPre * 0.7, (1.0 - smoothstep(0.0, 0.3, glVis - glH)) * (1.0 - uGlP));
${ghost ? "" : /* glsl */ `
// Digital noise blocks: world-space rectangular patches, re-seeded per
// tick. Some invert the surface colour, most flash emissive.
vec2 glBq = floor((vGlW.xy + vec2(vGlW.z * 0.7, vGlW.z * 0.3)) * 52.0
+ vec2(uGlSeed * 0.373, uGlSeed * 0.719));
vec3 glBh = glHash3(glBq + uGlSeed);
float glBGate = (1.0 - uGlP) * 0.16;
if (glBh.x > 1.0 - glBGate) {
if (glBh.y < 0.3) glInvAmt = 1.0;
else glAddC += (glBh.z < 0.6 ? vec3(0.15, 1.3, 1.5)
: (glBh.z < 0.85 ? vec3(1.4) : vec3(1.6, 0.5, 0.06))) * (0.7 + glBh.y);
}
// Faint rolling scanline shimmer.
glAddC += vec3(0.05, 0.3, 0.35) * (1.0 - uGlP) * 0.18
* step(0.6, fract(vGlW.y * 150.0 - uGlSeed * 0.21));
`}
}`;
const emissiveOut = ghost
? "" // ghosts are pre-tinted additive silhouettes, no extra emissive
: /* glsl */ `
gl_FragColor.rgb = mix(gl_FragColor.rgb, vec3(1.1) - gl_FragColor.rgb, glInvAmt);
gl_FragColor.rgb += glAddC;
gl_FragColor.rgb += glEdge * vec3(0.25, 1.15, 1.35);
gl_FragColor.rgb += uGlFlash * vec3(1.25, 0.7, 0.35);`;
shader.fragmentShader = shader.fragmentShader
.replace(
"#include <common>",
"#include <common>\n" + GLSL_HELPERS + "uniform float uGlFlash;\n",
)
.replace("#include <clipping_planes_fragment>", "#include <clipping_planes_fragment>" + sliceDiscard)
.replace("#include <dithering_fragment>", "#include <dithering_fragment>" + emissiveOut);
}
// ── Material clones (cached, never disposed between replays) ────────────
const clones = new Map(); // original material uuid -> glitch clone
let cloneNonce = 0;
let saved = null; // Array<[mesh, originalMat, cloneMat]> while active
function cloneFor(orig) {
let m = clones.get(orig.uuid);
if (m) return m;
m = orig.clone();
m.onBeforeCompile = (shader) => injectGlitch(shader);
const key = `microduck-glitch-${cloneNonce++}`;
m.customProgramCacheKey = () => key;
m.needsUpdate = true;
clones.set(orig.uuid, m);
return m;
}
function applyGlitchMats() {
if (saved) return;
saved = [];
rigRef.placer.traverse((o) => {
if (!o.isMesh || o.userData.glGhost) return;
const orig = o.material;
const m = cloneFor(orig);
saved.push([o, orig, m]);
o.material = m;
});
}
function restoreMats() {
if (!saved) return;
for (const [mesh, orig, clone] of saved) {
if (mesh.material === clone) mesh.material = orig;
}
saved = null;
}
// ── RGB-split ghosts ────────────────────────────────────────────────────
// Two additive unlit silhouette copies of every rig mesh (cyan right,
// orange left), sharing the slice-discard shader so their outline always
// matches the sliced duck. Added as children of each mesh: they inherit
// the full kinematic transform for free.
let ghostMats = [];
let ghostMeshes = [];
function makeGhostMat(r, g, b, sign) {
const m = new T.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
blending: T.AdditiveBlending,
});
m.color.setRGB(r, g, b);
const signU = { value: sign };
m.onBeforeCompile = (shader) => injectGlitch(shader, { signU, ghost: true });
m.customProgramCacheKey = () => `microduck-glitch-ghost-${sign > 0 ? "r" : "l"}`;
return m;
}
function buildGhosts() {
ghostMats = [makeGhostMat(0.0, 1.1, 1.3, +1), makeGhostMat(1.3, 0.35, 0.02, -1)];
const hosts = [];
rigRef.placer.traverse((o) => {
if (o.isMesh && !o.userData.glGhost) hosts.push(o);
});
for (const mesh of hosts) {
for (const mat of ghostMats) {
const gm = new T.Mesh(mesh.geometry, mat);
gm.userData.glGhost = true;
gm.renderOrder = 2;
gm.frustumCulled = false;
gm.visible = false;
mesh.add(gm);
ghostMeshes.push(gm);
}
}
}
function setGhostsVisible(v) {
for (const gm of ghostMeshes) gm.visible = v;
}
// ── Deterministic per-progress uniform state ────────────────────────────
// Everything derives from p alone (tick included), so setProgress(p) gives
// reproducible frames for debugging/screenshots.
function setUniformsFor(p) {
uP.value = p;
const tick = Math.floor(p * DURATION * TICK_HZ);
uSeed.value = tick;
const h = uB.value.y; // duck height
const gate = 0.35 + 0.65 * jhash(tick + 3.7);
uAmp.value = p < 0.92 ? h * 0.3 * Math.pow(1 - p, 1.3) * gate : 0;
uGhostOff.value =
p > 0.04 && p < 0.9 ? (0.06 + 0.3 * jhash(tick + 11.1)) * (1 - p) * h : 0;
uFlash.value = p > 0.86 ? 1.5 * Math.exp(-16 * (p - 0.86) * DURATION) : 0;
const ghostOp =
p > 0.04 && p < 0.9 ? (0.05 + 0.32 * (1 - p)) * (0.4 + 0.6 * jhash(tick + 5.5)) : 0;
for (const m of ghostMats) m.opacity = ghostOp;
}
function finish() {
uP.value = 1;
uFlash.value = 0;
setGhostsVisible(false);
restoreMats();
playing = false;
done = true;
}
// ── Public interface ────────────────────────────────────────────────────
export function init({ THREE, scene, rig, camera, renderer }) {
T = THREE;
rigRef = rig;
rig.placer.updateWorldMatrix(true, true);
const box = new T.Box3().setFromObject(rig.placer);
const minY = box.min.y;
const height = Math.max(1e-3, box.max.y - minY);
uB.value = new T.Vector4(minY, height, height / SLICES, 0);
buildGhosts();
// Duck starts invisible: p=0 discards every fragment.
uP.value = 0;
applyGlitchMats();
done = true;
playing = false;
}
export function start() {
applyGlitchMats();
setGhostsVisible(true);
elapsed = 0;
playing = true;
scrubbed = false;
done = false;
setUniformsFor(0);
}
export function update(dt, t) {
if (!playing || scrubbed) return;
elapsed += dt;
const p = Math.min(1, elapsed / DURATION);
setUniformsFor(p);
if (p >= 1) finish();
}
export function isDone() {
return done;
}
export function dispose() {
restoreMats();
for (const gm of ghostMeshes) gm.parent?.remove(gm);
ghostMeshes = [];
for (const m of ghostMats) m.dispose();
ghostMats = [];
for (const m of clones.values()) m.dispose();
clones.clear();
playing = false;
done = true;
rigRef = null;
}
// Debug hook: freeze the effect at an exact progress value (deterministic,
// used by the demo page for mid-effect screenshots). start() resumes
// normal playback.
export function setProgress(p) {
scrubbed = true;
if (p >= 1) {
finish();
return;
}
playing = true;
done = false;
applyGlitchMats();
setGhostsVisible(true);
setUniformsFor(Math.max(0, p));
}
+339
View File
@@ -0,0 +1,339 @@
// Holographic wireframe scan-up materialization effect.
//
// Sequence (~0.9 s, reversible):
// 1. An invisible scan height rises from the floor through the target;
// the boundary reads on the surface itself (bright wireframe band
// right under the scan height - no standalone disc geometry).
// 2. Below the scan line the target shows as a flickering additive
// wireframe hologram (scanline stripes, brightness boost near the
// scan line).
// 3. A second, fainter "solidify" line trails behind: fragments below
// it render the real PBR materials (world-Y clip injected via
// onBeforeCompile), with a hot edge right at the line. Once it
// clears the top the original materials are restored directly.
//
// Played backwards, the same timeline de-materializes (solid peel ->
// hologram -> gone). Used for the ball despawn; the duck only ever
// materializes.
//
// createWireframeFx() returns an independent instance (duck and ball
// scan at the same time without sharing uniforms). The module-level
// named exports wrap a singleton so demo-wireframe.html is unchanged.
//
// Instance interface:
// init({ THREE, scene, rig | root, camera, renderer, hidden? })
// start() / startReverse() / update(dt) / isDone() / restore() / dispose()
// Extra: setProgress(p), playing, reversing, TOTAL_S.
export const name = "wireframe";
// ── Timeline (seconds) ──────────────────────────────────────────────────
const SCAN_S = 0.6; // wireframe scan line: floor -> top
const SOLID_DELAY_S = 0.3; // solidify line starts this long after the scan
const SOLID_S = 0.6; // solidify line: floor -> top
export const TOTAL_S = SOLID_DELAY_S + SOLID_S; // 0.9
const clamp01 = (x) => Math.min(Math.max(x, 0), 1);
// Ease-out only: the rise starts at full speed the instant the scan cues
// (a smoothstep ease-in reads as a stall near the feet) and lands softly.
const ease = (x) => 1 - (1 - x) * (1 - x);
// Deterministic pseudo-random flicker so setProgress(p) captures are
// reproducible (no Math.random).
const hash = (x) => {
const s = Math.sin(x * 127.1) * 43758.5453;
return s - Math.floor(s);
};
const flickerAt = (time) => {
let f = 0.82 + 0.18 * hash(Math.floor(time * 60) + 0.5);
if (hash(Math.floor(time * 24) + 7.7) < 0.12) f *= 0.5; // dropouts
return f;
};
// Unique customProgramCacheKey values across every instance: a fresh
// clone of the same source material would otherwise reuse the compiled
// program without re-running onBeforeCompile, leaving clip uniforms
// unbound (see the dissolve comment in rl.js).
let clipNonce = 0;
const BOTTOM_PAD = 0.025;
// The band widths and timeline above are tuned for duck-sized targets
// (~0.35 m tall). Bigger props (the arcade cabinets) scale the spatial
// constants linearly and the duration by sqrt(scale), so the scan still
// reads as the same effect instead of a fast flash with hairline bands.
// Clamped at 1 so duck- and ball-sized targets are untouched.
const REF_SPAN = 0.35;
export function createWireframeFx() {
// Per-instance uniforms: duck and ball must not share a scan height.
const uScanY = { value: -1e3 };
const uSolidY = { value: -1e3 };
const uFlicker = { value: 1 };
const uTime = { value: 0 };
const uSpanK = { value: 1 }; // size factor vs REF_SPAN (>= 1)
let ctx = null; // { THREE, scene, root, camera, renderer }
let t = 0;
let dir = 1; // +1 materialize, -1 dematerialize
let playing = false;
let finished = false;
let minY = 0;
let spanY = 0.3;
let durK = 1; // timeline stretch for big targets
const totalS = () => TOTAL_S * durK;
const clipClones = new Map();
let clipSaved = null; // Array<[mesh, originalMat, cloneMat]> while active
let wireMat = null;
let wireMeshes = [];
const isTargetMesh = (o) => o.isMesh && !o.userData.fxOverlay;
function clipCloneFor(orig) {
let m = clipClones.get(orig.uuid);
if (m) return m;
m = orig.clone();
m.onBeforeCompile = (shader) => {
shader.uniforms.uFxSolidY = uSolidY;
shader.uniforms.uFxSpanK = uSpanK;
shader.vertexShader = shader.vertexShader
.replace("#include <common>", "#include <common>\nvarying vec3 vFxW;")
.replace(
"#include <worldpos_vertex>",
"#include <worldpos_vertex>\nvFxW = (modelMatrix * vec4(transformed, 1.0)).xyz;",
);
shader.fragmentShader = shader.fragmentShader
.replace(
"#include <common>",
"#include <common>\nvarying vec3 vFxW;\nuniform float uFxSolidY;\nuniform float uFxSpanK;",
)
.replace(
"#include <clipping_planes_fragment>",
/* glsl */ `#include <clipping_planes_fragment>
float fxEdge = 0.0;
if (vFxW.y > uFxSolidY) discard;
fxEdge = 1.0 - smoothstep(0.002 * uFxSpanK, 0.018 * uFxSpanK, uFxSolidY - vFxW.y);`,
)
.replace(
"#include <dithering_fragment>",
/* glsl */ `#include <dithering_fragment>
gl_FragColor.rgb += fxEdge * vec3(0.95, 0.32, 0.05);`,
);
};
const key = `microduck-fx-wireframe-${clipNonce++}`;
m.customProgramCacheKey = () => key;
m.needsUpdate = true;
clipClones.set(orig.uuid, m);
return m;
}
function applyClipMaterials() {
if (clipSaved) return;
clipSaved = [];
ctx.root.traverse((o) => {
if (!isTargetMesh(o)) return;
const orig = o.material;
const clone = clipCloneFor(orig);
clipSaved.push([o, orig, clone]);
o.material = clone;
});
}
function restoreClipMaterials() {
if (!clipSaved) return;
for (const [mesh, orig, clone] of clipSaved) {
if (mesh.material === clone) mesh.material = orig;
}
clipSaved = null;
}
function makeWireMaterial(THREE) {
return new THREE.ShaderMaterial({
uniforms: { uScanY, uSolidY, uFlicker, uTime, uSpanK },
vertexShader: /* glsl */ `
varying vec3 vW;
void main() {
vec4 wp = modelMatrix * vec4(position, 1.0);
vW = wp.xyz;
gl_Position = projectionMatrix * viewMatrix * wp;
}`,
fragmentShader: /* glsl */ `
uniform float uScanY, uSolidY, uFlicker, uTime, uSpanK;
varying vec3 vW;
void main() {
if (vW.y > uScanY || vW.y < uSolidY) discard;
float lead = 1.0 - smoothstep(0.0, 0.06 * uSpanK, uScanY - vW.y);
float tail = smoothstep(0.0, 0.018 * uSpanK, vW.y - uSolidY);
float stripes = 0.7 + 0.3 * sin(vW.y * 900.0 / uSpanK - uTime * 45.0);
vec3 c = vec3(1.0, 0.34, 0.06) * (0.55 + 1.6 * lead);
float a = (0.10 + 0.40 * lead) * stripes * tail * uFlicker;
gl_FragColor = vec4(c, a);
}`,
wireframe: true,
transparent: true,
blending: THREE.AdditiveBlending,
depthWrite: false,
depthTest: true,
});
}
function buildWireOverlays(THREE, root) {
wireMat = makeWireMaterial(THREE);
root.traverse((o) => {
if (!isTargetMesh(o)) return;
// Child of the source mesh with identity transform so the overlay
// follows whatever pose the caller writes (duck joints or ball qpos).
// userData.fxWireGeometry substitutes a coarser geometry for the
// wireframe pass only (the ball's render sphere is too dense to read
// as a hologram); the solidify clip still runs on the real mesh.
const w = new THREE.Mesh(o.userData.fxWireGeometry ?? o.geometry, wireMat);
w.userData.fxOverlay = true;
w.renderOrder = 5;
w.visible = false;
o.add(w);
wireMeshes.push(w);
});
}
function applyAt(time) {
const scanP = ease(clamp01(time / (SCAN_S * durK)));
const solidP = ease(clamp01((time - SOLID_DELAY_S * durK) / (SOLID_S * durK)));
uFlicker.value = flickerAt(time);
uTime.value = time;
const jitter = scanP > 0 && scanP < 1 ? (hash(time * 41.3) - 0.5) * 0.02 * spanY : 0;
uScanY.value = minY + spanY * scanP + jitter;
uSolidY.value = minY + spanY * solidP;
const wiresOn = time > 0 && solidP < 1;
for (const w of wireMeshes) w.visible = wiresOn;
}
function finish() {
// Forward: restore the real materials (fully solid). Reverse: leave
// the clip parked at t=0 (fully hidden) so restoring wouldn't flash
// the solid mesh for a frame; the caller hides the object then
// restore()s.
if (dir > 0) restoreClipMaterials();
else applyAt(0);
for (const w of wireMeshes) w.visible = false;
finished = true;
playing = false;
}
function computeRange() {
const { THREE, root } = ctx;
root.updateWorldMatrix(true, true);
const box = new THREE.Box3().setFromObject(root);
minY = Math.min(box.min.y, 0) - BOTTOM_PAD;
spanY = Math.max(box.max.y - minY, 0.04) * 1.06;
// Size adaptation: spatial constants scale linearly with the target's
// height, the timeline by sqrt (a 1.7 m cabinet scans in ~2 s, not
// 0.9 s at 6x the line speed). >= 1: duck/ball keep the original look.
uSpanK.value = Math.max(1, spanY / REF_SPAN);
durK = Math.min(Math.sqrt(uSpanK.value), 2.5);
}
function arm(nextDir, resetT) {
dir = nextDir;
if (resetT) t = nextDir > 0 ? 0 : totalS();
finished = false;
computeRange();
applyClipMaterials();
applyAt(t);
playing = true;
}
function init({ THREE, scene, rig, root, camera, renderer, hidden = true }) {
const target = root ?? rig.placer;
ctx = { THREE, scene, root: target, camera, renderer };
computeRange();
buildWireOverlays(THREE, target);
t = 0;
dir = 1;
finished = false;
playing = false;
if (hidden) {
applyClipMaterials();
applyAt(0);
}
}
function start() {
// Mid-reverse: keep the current t and turn around. Fresh play: from 0.
arm(1, !playing);
}
function startReverse() {
arm(-1, !playing);
}
function update(dt) {
if (!playing || finished) return;
t += dir * dt;
if (dir > 0 && t >= totalS()) {
t = totalS();
applyAt(t);
finish();
return;
}
if (dir < 0 && t <= 0) {
t = 0;
applyAt(t);
finish();
return;
}
applyAt(t);
}
function isDone() {
return finished;
}
function setProgress(p) {
playing = false;
finished = false;
dir = 1;
computeRange();
applyClipMaterials();
t = clamp01(p) * totalS();
applyAt(t);
}
function restore() {
restoreClipMaterials();
}
function dispose() {
restoreClipMaterials();
for (const w of wireMeshes) w.parent?.remove(w);
wireMeshes = [];
wireMat?.dispose();
wireMat = null;
ctx = null;
playing = false;
finished = false;
}
return {
init, start, startReverse, update, isDone, setProgress, restore, dispose,
get playing() { return playing; },
get reversing() { return playing && dir < 0; },
get TOTAL_S() { return totalS(); },
};
}
// Singleton for the duck (and the isolated demo page). New callers that
// need a second scan (the ball) go through createWireframeFx().
const singleton = createWireframeFx();
export const init = (...a) => singleton.init(...a);
export const start = (...a) => singleton.start(...a);
export const startReverse = (...a) => singleton.startReverse(...a);
export const update = (...a) => singleton.update(...a);
export const isDone = (...a) => singleton.isDone(...a);
export const setProgress = (...a) => singleton.setProgress(...a);
export const restore = (...a) => singleton.restore(...a);
export const dispose = (...a) => singleton.dispose(...a);
+181
View File
@@ -0,0 +1,181 @@
// Click-to-walk target reticle, drawn in the same art direction as the
// wireframe materialization (fx-wireframe.js): additive orange hairlines
// (1 px GL lines), deterministic hologram flicker, ease-out timing.
//
// Anatomy (flat on the floor, group-local XZ plane):
// - main ring: hairline LineLoop
// - 4 radial ticks, slowly rotating (the "alive" tell while idle)
// - center cross marking the exact click point
// - ping ring: one-shot expanding echo played on (re)acquire
//
// Lifecycle, driven by update(dt, target) where target is the MJCF [x, y]
// from WaypointSource (or null):
// click / re-click -> "in": the ring resolves from wide to tight while
// fading up, and the ping echoes outward
// arrival / cancel -> "out": quick collapse + fade, then hidden
//
// The MJCF -> three mapping (x, y) -> (x, -y) lives here so the caller
// can hand the source's target over untouched.
import * as THREE from "three";
// Matches the scan color vec3(1.0, 0.34, 0.06) in fx-wireframe.js.
const COLOR = 0xff5710;
const R = 0.06; // main ring radius (m)
const TICK_R0 = 0.08, TICK_R1 = 0.102;
const CROSS_R = 0.013;
const FLOOR_Y = 0.012; // sits just above the floor plane
const IN_S = 0.35; // acquire: wide -> tight
const OUT_S = 0.22; // arrival/cancel: collapse + fade
const PING_S = 0.55; // echo ring lifetime
const PING_SCALE = 2.6; // echo end scale (relative to the main ring)
const BODY_OPACITY = 0.85;
const TICK_SPIN = 0.7; // rad/s
const clamp01 = (x) => Math.min(Math.max(x, 0), 1);
// Same ease-out as the scan: full speed on the cue, soft landing.
const ease = (x) => 1 - (1 - x) * (1 - x);
// Deterministic hologram flicker, same recipe as fx-wireframe.js (no
// Math.random so captures are reproducible).
const hash = (x) => {
const s = Math.sin(x * 127.1) * 43758.5453;
return s - Math.floor(s);
};
const flickerAt = (time) => {
let f = 0.86 + 0.14 * hash(Math.floor(time * 60) + 0.5);
if (hash(Math.floor(time * 24) + 7.7) < 0.08) f *= 0.55; // dropouts
return f;
};
function circleGeometry(r, n = 64) {
const pts = [];
for (let i = 0; i < n; i++) {
const a = (i / n) * Math.PI * 2;
pts.push(new THREE.Vector3(Math.cos(a) * r, 0, Math.sin(a) * r));
}
return new THREE.BufferGeometry().setFromPoints(pts);
}
function lineMaterial() {
return new THREE.LineBasicMaterial({
color: COLOR,
transparent: true,
opacity: 0,
blending: THREE.AdditiveBlending,
depthWrite: false,
});
}
export function createWaypointMarker() {
const group = new THREE.Group();
group.visible = false;
group.position.y = FLOOR_Y;
const bodyMat = lineMaterial();
const pingMat = lineMaterial();
const ringGeo = circleGeometry(R);
const ring = new THREE.LineLoop(ringGeo, bodyMat);
// 4 radial ticks at the diagonals, rotated as one object while idle.
const tickPts = [];
for (let i = 0; i < 4; i++) {
const a = Math.PI / 4 + (i * Math.PI) / 2;
const c = Math.cos(a), s = Math.sin(a);
tickPts.push(
new THREE.Vector3(c * TICK_R0, 0, s * TICK_R0),
new THREE.Vector3(c * TICK_R1, 0, s * TICK_R1),
);
}
const ticks = new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints(tickPts),
bodyMat,
);
const cross = new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-CROSS_R, 0, 0), new THREE.Vector3(CROSS_R, 0, 0),
new THREE.Vector3(0, 0, -CROSS_R), new THREE.Vector3(0, 0, CROSS_R),
]),
bodyMat,
);
// One-shot expanding echo; shares the ring geometry, scale-animated.
const ping = new THREE.LineLoop(ringGeo, pingMat);
ping.visible = false;
for (const o of [ring, ticks, cross, ping]) {
o.renderOrder = 5; // over the floor, same layer as the fx overlays
group.add(o);
}
let phase = "hidden"; // hidden | in | idle | out
let tPhase = 0;
let tPing = Infinity; // >= PING_S means the echo is spent
let time = 0; // flicker clock
let px = 0, pz = 0; // shown position (three coords)
function acquire(x, z) {
px = x;
pz = z;
group.position.set(px, FLOOR_Y, pz);
phase = "in";
tPhase = 0;
tPing = 0;
group.visible = true;
}
function update(dt, target) {
time += dt;
if (target) {
const tx = target[0], tz = -target[1]; // MJCF -> three
if (phase === "hidden" || phase === "out") acquire(tx, tz);
else if (Math.hypot(tx - px, tz - pz) > 1e-3) acquire(tx, tz); // re-click
} else if (phase === "in" || phase === "idle") {
phase = "out";
tPhase = 0;
}
if (phase === "hidden") return;
tPhase += dt;
tPing += dt;
ticks.rotation.y = time * TICK_SPIN;
let scale = 1;
let alpha = BODY_OPACITY;
if (phase === "in") {
const k = ease(clamp01(tPhase / IN_S));
scale = 1.6 - 0.6 * k; // resolves from wide to tight
alpha *= k;
if (tPhase >= IN_S) phase = "idle";
} else if (phase === "idle") {
scale = 1 + 0.03 * Math.sin(time * 2.4); // subtle breathing
alpha *= flickerAt(time);
} else if (phase === "out") {
const k = ease(clamp01(tPhase / OUT_S));
scale = 1 - 0.35 * k;
alpha *= 1 - k;
if (tPhase >= OUT_S) {
phase = "hidden";
group.visible = false;
}
}
for (const o of [ring, ticks, cross]) o.scale.setScalar(scale);
bodyMat.opacity = alpha;
if (tPing < PING_S) {
const p = ease(clamp01(tPing / PING_S));
ping.visible = true;
ping.scale.setScalar(1 + (PING_SCALE - 1) * p);
pingMat.opacity = 0.9 * (1 - p);
} else {
ping.visible = false;
}
}
return { group, update };
}
+2311
View File
File diff suppressed because it is too large Load Diff
+601
View File
@@ -0,0 +1,601 @@
// Live multiplayer ghosts: every open tab of the sandbox broadcasts its
// duck state over WebRTC and renders the other visitors as translucent
// ducks. There is no backend - this is a static Space - so peer discovery
// uses Trystero's serverless signaling over public Nostr relays. Payloads
// are tiny (22 floats + a variant name at SEND_HZ), and at most MAX_GHOSTS
// ghosts are instantiated regardless of how many peers are in the room.
//
// This module deliberately imports nothing from duck.js / variants.js:
// on the private Space those need the ?__sign JWT that only rl.js knows
// how to append, so all rig helpers arrive through init parameters.
const APP_ID = "microduck-sandbox";
const ROOM = "lobby";
// Explicit relay list instead of Trystero's default appId-seeded pick.
// The deterministic subset that "microduck-sandbox" draws from the default
// pool rotted away (2026-09 audit: 3 relays dead, 1 rejecting ephemeral
// events, 1 rate-limiting), which silently killed ghost discovery in prod.
// These were verified live to accept AND route Trystero's ephemeral
// events; the warnOnRelayFailure path logs any that decay later.
const RELAY_URLS = [
"wss://relay.damus.io",
"wss://nos.lol",
"wss://nostr.tegila.com.br",
"wss://staging.yabu.me",
"wss://social.amanah.eblessing.co",
"wss://relay-rpi.edufeed.org",
"wss://strfry.shock.network",
];
const MAX_GHOSTS = 3;
const SEND_HZ = 15;
const GHOST_OPACITY = 0.35;
// Snapshot interpolation: each ghost renders in the past, lerping between
// the two buffered snapshots that bracket the render time (timed by local
// ARRIVAL, so no clock sync and no payload change - old clients
// interoperate). This replaces the old exponential chase toward the
// latest packet, whose move-then-stall rhythm read as micro-stutter.
//
// The playback delay is ADAPTIVE per ghost: it tracks the measured
// snapshot arrival cadence (fast-attack / slow-release, like a jitter
// buffer), so a healthy 15 Hz peer keeps the ~150 ms floor while a
// background-throttled 1 Hz sender is replayed as continuous slow motion
// ~1.3 s in the past instead of the old sprint-then-freeze (a fixed
// 150 ms delay replayed each 1 s packet gap as a 150 ms dash). The delay
// is slew-rate limited so rate changes (tab hidden <-> shown) glide -
// render time never runs backward and never pops. Arrival stamps are
// also de-jittered: bursts delivered back-to-back by the reliable
// ordered channel (head-of-line blocking) are re-spaced to at least half
// the nominal send interval, so a burst replays as motion instead of a
// teleport. Nobody synchronizes on ghosts, so the latency is invisible.
const INTERP_DELAY_MS = 150; // floor, ~2.25 send intervals at 15 Hz
const INTERP_DELAY_MAX_MS = 2000; // cap for stalled senders
const RESPACE_MIN_MS = 1000 / SEND_HZ / 2; // de-jitter floor between stamps
const GAP_RELEASE = 0.15; // per-packet EWMA rate when arrivals speed up
const DELAY_SLEW = 0.5; // max delay change per ms of real time
const BUF_MAX = 40; // snapshots kept per ghost (~2.5 s at 15 Hz)
// Floor between legs<->rollers ghost rebuilds for one peer: a rebuild
// clones a full rig, so the rate is capped against flag-flapping peers.
const LOCO_SWAP_MIN_MS = 500;
// Hopeless-stream gate: a ghost whose snapshots arrive too sparsely to
// interpolate smoothly (peer tab throttled to ~1 Hz, bad network) is
// faded out entirely instead of shown as a stuttering slow-motion puppet.
// Health is judged on max(gapAvg, time since last packet) with hysteresis:
// sustained above HIDE_GAP_MS hides, sustained below SHOW_GAP_MS shows,
// and the band between the two keeps the current state so the boundary
// never flickers. The sustain windows also ride out one-off hiccups
// (gapAvg fast-attacks on a single late packet but releases within a few
// packets, well inside HIDE_SUSTAIN_MS). Fading drives the cloned ghost
// materials' opacity (same path as GHOST_OPACITY), the ghost ball, and
// the mapDots minimap feed; ghosts have no name tags or audio emitters,
// so there is nothing else to mute.
const HIDE_GAP_MS = 700; // sustained arrival interval that hides a ghost
const SHOW_GAP_MS = 350; // sustained interval that shows it again
const HIDE_SUSTAIN_MS = 1500; // how long the gap must stay bad to hide
const SHOW_SUSTAIN_MS = 700; // how long it must stay good to show
const FADE_MS = 400; // opacity ramp duration for hide/show
// Idle visitors stay invisible: a ghost is only shown once its peer has
// strayed from the pose of its first state message (everyone spawns at
// the arena center). Once revealed it stays visible for the whole peer
// session, so a reset teleporting the duck back to center doesn't blink
// the ghost out.
const REVEAL_DIST = 0.2; // m, horizontal distance from spawn
const REVEAL_YAW = 0.4; // rad (~23deg), turning in place also reveals
// state.p is raw MuJoCo qpos[0..6]: [x, y, z, qw, qx, qy, qz], Z-up.
const yawOf = (p) =>
Math.atan2(2 * (p[3] * p[6] + p[4] * p[5]), 1 - 2 * (p[5] * p[5] + p[6] * p[6]));
const hasMoved = (spawn, p) => {
const dx = p[0] - spawn.x, dy = p[1] - spawn.y;
if (dx * dx + dy * dy > REVEAL_DIST * REVEAL_DIST) return true;
const dyaw = yawOf(p) - spawn.yaw;
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: () => [], destroy() {}, injectState: () => false,
setSendHz: () => {},
};
let room;
try {
// Vendored npm dep (was esm.run); dynamic so it stays a lazy chunk
// loaded only when the ghost session actually starts.
const { joinRoom } = await import("trystero/nostr");
room = joinRoom({ appId: APP_ID, relayConfig: { urls: RELAY_URLS } }, ROOM);
} catch (e) {
console.warn("ghosts disabled (signaling unavailable):", e);
return noop;
}
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). The host may not have the wanted rig yet
// (the roller stack is lazy): servedLoco says which flavor a ghost
// actually gets right now, and prepareRigFor warms the missing one in
// the background so a later packet can rebuild onto the real thing.
const rigFor = (l) => (env.getRigFor ? env.getRigFor(l ?? 0) : env.rig);
const servedLoco = (l) => {
const want = l ?? 0;
return env.hasRigFor && !env.hasRigFor(want) ? 0 : want;
};
// trystero 0.25 (backed by @trystero-p2p): makeAction returns
// { send, onMessage, onReceiveProgress } where onMessage is a SETTER -
// the receive handler is registered by assignment, not by calling it.
const act = room.makeAction("s");
// send() rejects when a peer's channel drops mid-transfer; that peer will
// be swept anyway, so failures are non-events.
const sendState = (data) => act.send(data).catch(() => {});
// Ghosts share geometry with the local rig (cloneRig), but get their own
// transparent material clones so repainting them never touches the
// visitor's own duck (variants.js caches materials globally).
//
// Rendering: a ghost reads as ONE translucent shell, not ~70 individually
// transparent meshes (through which every internal motor/PCB used to show).
// Classic depth-prepass silhouette, kept inside the transparent pass so the
// grid floor/walls (transparent ShaderMaterials at renderOrder 0) still
// draw behind ghosts instead of being depth-rejected:
// PREPASS (renderOrder 1): every ghost mesh duplicated as a color-less
// twin (colorWrite off, depthWrite on) -> the depth buffer ends up
// holding the nearest ghost surface per pixel.
// BEAUTY (renderOrder 2): the real meshes, transparent + depthWrite off;
// the default LessEqual depth test then rejects everything except the
// fragment matching the prepass depth, so internals and back shell
// layers are skipped and each pixel is shaded exactly once.
// Orders are shared by all ghosts (not per-ghost pairs): every beauty pass
// tests against every ghost's prepass depth, so overlapping ghosts occlude
// each other like solids instead of double-blending.
const PREPASS_ORDER = 1;
const BEAUTY_ORDER = 2;
const ghostify = (rig) => {
// Collect first: twins are added below and must not be re-traversed.
const meshes = [];
rig.root.traverse((o) => { if (o.isMesh) meshes.push(o); });
const cache = new Map();
let depthMat = null;
for (const o of meshes) {
// Materialization-FX wire overlays cloned along with the local rig:
// drop them, they share the LIVE scan shader material and would
// flash on this ghost every time the local duck re-materializes.
if (o.userData.fxOverlay) { o.parent?.remove(o); continue; }
if (o.userData.ghostPrepass) continue; // twin from a previous ghostify
let m = cache.get(o.material.uuid);
if (!m) {
m = o.material.clone();
m.transparent = true;
m.opacity = GHOST_OPACITY;
m.depthWrite = false;
cache.set(o.material.uuid, m);
}
o.material = m;
o.renderOrder = BEAUTY_ORDER;
if (!o.userData.hasGhostTwin) {
if (!depthMat) {
// Depth-only material: cloned (no THREE import here) and muted.
// transparent stays true so the twin sorts into the transparent
// pass, after the grid but before the beauty meshes.
depthMat = m.clone();
depthMat.colorWrite = false;
depthMat.depthWrite = true;
}
// Twin as an identity-transform child: follows joints for free. No
// userData.meshName, so applyVariant never repaints it.
const twin = new o.constructor(o.geometry, depthMat);
twin.renderOrder = PREPASS_ORDER;
twin.userData.ghostPrepass = true;
o.userData.hasGhostTwin = true;
o.add(twin);
}
}
};
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, de-jittered: a snapshot never lands
// closer than RESPACE_MIN_MS after the previous one, so a burst of
// queued packets spreads into playable motion (the future-dated stamps
// stay behind the delayed render time).
const snapOf = (state, prevAt = -Infinity) => ({
p: state.p, j: state.j, w: state.w ?? 0,
b: state.b ?? null, // ball free-joint pose, or null while none in play
at: Math.max(performance.now(), prevAt + RESPACE_MIN_MS),
});
const makeGhost = (state) => {
// g.loco records the rig the ghost actually GOT (the served flavor),
// not the peer's flag: while the roller rig is still loading the ghost
// walks on legs, and the mismatch on later packets drives the rebuild.
const served = servedLoco(state.l);
if (served !== (state.l ?? 0)) env.prepareRigFor?.(state.l);
const rig = cloneRig(rigFor(served));
applyVariant(rig, state.v);
ghostify(rig);
scene.add(rig.placer);
const trunk = rig.bodies.get("trunk_base");
// Snap straight to the first received pose: no fly-in from the origin.
trunk.position.set(state.p[0], state.p[1], state.p[2]);
trunk.quaternion.set(state.p[4], state.p[5], state.p[6], state.p[3]);
return {
rig, trunk, buf: [snapOf(state)],
variant: state.v, loco: served,
ball: null, // { group, mesh } lazily built on the first ball pose
gapAvg: 1000 / SEND_HZ, // measured arrival cadence, ms
delay: INTERP_DELAY_MS, // current playback delay, ms
// Stream-health fade (see HIDE_GAP_MS block): fade is the current
// opacity factor, fadeTarget the hysteresis verdict (0 or 1), and
// appliedFade what the materials last received (fresh ghostify
// clones start at full GHOST_OPACITY, i.e. factor 1).
fade: 1, fadeTarget: 1, appliedFade: 1,
hideSince: null, showSince: null,
};
};
const removeGhost = (peerId) => {
const g = ghosts.get(peerId);
if (!g) return;
scene.remove(g.rig.placer);
const seen = new Set();
g.rig.root.traverse((o) => {
if (o.isMesh && !seen.has(o.material.uuid)) {
seen.add(o.material.uuid);
o.material.dispose();
}
});
if (g.ball) {
scene.remove(g.ball.group);
g.ball.mesh.material.dispose(); // cloned per ghost; geometry is shared
}
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)) &&
(state.b == null || finiteArray(state.b, 7)) && // ball pose, optional
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.
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
// Nostr relays replay recent events, so states from already-dead
// sessions can arrive right after joining: only ghost live peers.
if (!(peerId in room.getPeers())) return;
g = makeGhost(state);
// Idle-visitor gate: remember where this peer first appeared and keep
// its rig invisible until it strays from there (see hasMoved above).
g.spawn = { x: state.p[0], y: state.p[1], yaw: yawOf(state.p) };
g.revealed = false;
g.rig.placer.visible = false;
ghosts.set(peerId, g);
g.lastSeen = performance.now();
return;
}
g.lastSeen = performance.now();
const prevAt = g.buf[g.buf.length - 1]?.at;
const snap = snapOf(state, prevAt);
if (prevAt !== undefined) {
// Arrival cadence, fast attack / slow release: one late packet bumps
// the estimate (and thus the playback delay) immediately, a resumed
// fast sender eases it back down over ~a second of packets.
const gap = snap.at - prevAt;
g.gapAvg = gap > g.gapAvg ? gap : g.gapAvg + (gap - g.gapAvg) * GAP_RELEASE;
}
g.buf.push(snap);
if (g.buf.length > BUF_MAX) g.buf.shift();
if (!g.revealed && hasMoved(g.spawn, state.p)) {
g.revealed = true; // latched for the rest of this peer session
g.rig.placer.visible = true;
}
// Peer switched legs <-> rollers, or the rig its mode needs just
// finished lazy-loading: rebuild the ghost on the right rig (cheap -
// cloneRig shares geometry). The snapshot buffer carries over so the
// interpolated motion stays continuous across the swap. While the
// wanted rig is still loading, keep warming it and stay on legs.
// Rate-limited per peer: the lobby is public, so a hostile peer
// flapping the flag at packet rate must not turn into a 15 Hz
// teardown/rebuild loop on every viewer's tab (a real switch takes a
// ~1 s button hold, so legit swaps are never this close together).
if (state.l !== g.loco) {
const now = performance.now();
if (servedLoco(state.l) !== state.l) {
env.prepareRigFor?.(state.l);
} else if (now - (g.locoSwapAt ?? 0) >= LOCO_SWAP_MIN_MS) {
const { lastSeen, spawn, revealed, buf, gapAvg, delay,
fade, fadeTarget, hideSince, showSince } = g;
removeGhost(peerId);
g = makeGhost(state);
// appliedFade stays 1 (fresh rig materials): update() re-applies
// the carried fade on the next frame if it differs.
Object.assign(g, { lastSeen, spawn, revealed, buf, gapAvg, delay,
fade, fadeTarget, hideSince, showSince, locoSwapAt: now });
g.rig.placer.visible = revealed;
ghosts.set(peerId, g);
return;
}
}
if (state.v !== g.variant) {
g.variant = state.v;
applyVariant(g.rig, state.v);
ghostify(g.rig);
g.appliedFade = 1; // repaint recloned materials at full GHOST_OPACITY
}
};
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...
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
// still send at ~1 Hz).
const STALE_MS = 5000;
// Broadcast + stale sweep on a Web Worker clock: hidden tabs clamp
// main-thread timers (and rAF) to >= 1 s, which used to degrade a hidden
// tab's ghost to 1 Hz stepping in everyone else's view. Dedicated-worker
// timers are exempt, and the postMessage task still runs on the hidden
// main thread (only timers are throttled), so a backgrounded tab keeps
// broadcasting at the nominal SEND_HZ. Inline via blob URL - no extra
// file, no bundler config; falls back to a plain (throttled) interval
// if workers or blob URLs are unavailable (strict CSP).
const tick = () => {
const s = getLocalState();
if (s) sendState(s);
const now = performance.now();
for (const [peerId, g] of [...ghosts]) {
if (now - g.lastSeen > STALE_MS) removeGhost(peerId);
}
};
let tickWorker = null;
let tickId = null;
// Broadcast ticker, restartable so the QA hook below can emulate a
// throttled sender (there is no other way to reach the worker's
// interval from the console once it is running).
const startTicker = (hz) => {
tickWorker?.terminate();
tickWorker = null;
if (tickId !== null) { clearInterval(tickId); tickId = null; }
try {
const url = URL.createObjectURL(new Blob(
[`setInterval(() => postMessage(0), ${1000 / hz});`],
{ type: "text/javascript" },
));
tickWorker = new Worker(url);
URL.revokeObjectURL(url); // the worker resolved the URL synchronously
tickWorker.onmessage = tick;
} catch {
tickId = setInterval(tick, 1000 / hz);
}
};
startTicker(SEND_HZ);
// Scratch THREE.Quaternions without importing three: slerp needs real
// 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();
// Ghost ball: the peer's soccer ball as the same translucent shell as
// its duck. Built lazily on the first snapshot carrying a ball pose
// (env.makeGhostBall shares the local ball's geometry and clones its
// material), shown only while the ghost itself is revealed, hidden the
// moment the peer's ball despawns (b turns null in the stream). Poses
// interpolate like the trunk; on a spawn/despawn edge where only one
// bracketing snapshot has a ball, it snaps to that pose instead of
// lerping from nowhere. A single convex mesh needs no depth-prepass
// twin - plain transparent blending reads fine on a sphere.
const driveBall = (g, ab, bb, u) => {
if (!ab && !bb) {
if (g.ball) g.ball.group.visible = false;
return;
}
if (!g.ball) {
if (!env.makeGhostBall) return; // host without ball support
const ball = env.makeGhostBall();
const m = ball.mesh.material;
m.transparent = true;
m.opacity = GHOST_OPACITY;
m.depthWrite = false;
ball.mesh.renderOrder = BEAUTY_ORDER;
scene.add(ball.group);
g.ball = ball;
}
g.ball.group.visible = g.revealed && g.fade > 0;
const mesh = g.ball.mesh;
if (ab && bb) {
mesh.position.set(
ab[0] + (bb[0] - ab[0]) * u,
ab[1] + (bb[1] - ab[1]) * u,
ab[2] + (bb[2] - ab[2]) * u,
);
_qa.set(ab[4], ab[5], ab[6], ab[3]); // MJCF wxyz -> THREE xyzw
_qb.set(bb[4], bb[5], bb[6], bb[3]);
mesh.quaternion.copy(_qa.slerp(_qb, u));
} else {
const s = ab ?? bb;
mesh.position.set(s[0], s[1], s[2]);
mesh.quaternion.set(s[4], s[5], s[6], s[3]);
}
};
// Push the ghost's current fade factor into its cloned materials (beauty
// meshes + ghost ball; prepass twins are colorWrite-off so opacity is
// irrelevant, and the whole rig is hidden via placer.visible at fade 0).
// Called only on frames where the fade actually moved.
const applyFade = (g) => {
const seen = new Set();
g.rig.root.traverse((o) => {
if (!o.isMesh || o.userData.ghostPrepass || seen.has(o.material.uuid)) return;
seen.add(o.material.uuid);
o.material.opacity = GHOST_OPACITY * g.fade;
});
if (g.ball) g.ball.mesh.material.opacity = GHOST_OPACITY * g.fade;
g.appliedFade = g.fade;
};
let lastUpdateAt = performance.now(); // update() frame clock for the delay slew
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);
tickWorker?.terminate();
if (tickId !== null) 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 }),
// QA hook: rebuild the broadcast ticker at a different rate, to
// emulate a background-throttled / bad-network sender (drives the
// receiving side's sparse-stream fade, see HIDE_GAP_MS block).
setSendHz: (hz = SEND_HZ) => startTicker(hz),
peerCount: () => Object.keys(room.getPeers()).length,
ghostCount: () => ghosts.size,
// Minimap feed: revealed ghosts' arena positions in raw MJCF coords
// (trunk.position is set from qpos before the root's Z-up fix).
mapDots: () =>
[...ghosts.values()]
.filter((g) => g.revealed && g.fade > 0) // fade-hidden ghosts drop off the map too
.map((g) => ({ x: g.trunk.position.x, y: g.trunk.position.y })),
debug: () => [...ghosts.entries()].map(([peerId, g]) => {
let meshes = 0, visible = 0, op = null, twins = 0;
g.rig.root.traverse((o) => {
if (!o.isMesh) return;
if (o.userData.ghostPrepass) { twins++; return; }
meshes++; if (o.visible) visible++; op ??= o.material.opacity;
});
const w = g.trunk.getWorldPosition(g.trunk.position.clone());
const ball = g.ball
? { visible: g.ball.group.visible, p: g.ball.mesh.position.toArray() }
: null;
return { peerId, p: g.trunk.position.toArray(), world: w.toArray(), inScene: !!g.rig.placer.parent, revealed: g.revealed, meshes, visible, twins, op, v: g.variant, l: g.loco, ball, gapAvg: g.gapAvg, delay: g.delay, bufLen: g.buf.length, fade: g.fade, fadeTarget: g.fadeTarget, lastSeen: g.lastSeen };
}),
update() {
const now = performance.now();
// Frame delta for the delay slew; capped so a long-occluded tab's
// first frame back just snaps the delay while nobody was watching.
const dt = Math.min(250, now - lastUpdateAt);
lastUpdateAt = now;
for (const g of ghosts.values()) {
// Stream-health verdict with hysteresis (see HIDE_GAP_MS block):
// judge on the measured cadence AND the live silence since the
// last packet, so a sender that stopped entirely starts fading
// before the 5 s stale sweep removes it.
const sparse = Math.max(g.gapAvg, now - g.lastSeen);
if (sparse > HIDE_GAP_MS) {
g.showSince = null;
if (g.hideSince === null) g.hideSince = now;
else if (now - g.hideSince >= HIDE_SUSTAIN_MS) g.fadeTarget = 0;
} else if (sparse < SHOW_GAP_MS) {
g.hideSince = null;
if (g.showSince === null) g.showSince = now;
else if (now - g.showSince >= SHOW_SUSTAIN_MS) g.fadeTarget = 1;
} else {
g.hideSince = g.showSince = null; // dead band: hold current state
}
if (g.fade !== g.fadeTarget) {
const step = dt / FADE_MS;
g.fade += Math.min(step, Math.max(-step, g.fadeTarget - g.fade));
}
if (g.fade !== g.appliedFade) applyFade(g);
g.rig.placer.visible = g.revealed && g.fade > 0;
// Adaptive playback delay: track the measured arrival cadence with
// margin, floored at the healthy-peer delay. Slew-limited to half
// real time so render time never runs backward while the delay
// grows (slow-motion instead of reverse) and only gently
// fast-forwards (x1.5) while it shrinks back.
const target = Math.min(
INTERP_DELAY_MAX_MS,
Math.max(INTERP_DELAY_MS, g.gapAvg * 1.25 + 50),
);
const slew = dt * DELAY_SLEW;
g.delay += Math.min(slew, Math.max(-slew, target - g.delay));
const renderT = now - g.delay;
const buf = g.buf;
// Drop snapshots fully in the past; keep [0] and [1] bracketing
// renderT (or the two newest, if renderT has caught up).
while (buf.length > 2 && buf[1].at <= renderT) buf.shift();
const a = buf[0];
const b = buf.length > 1 ? buf[1] : a;
// Clamped: before the segment -> a, past the newest -> hold b.
const span = b.at - a.at;
const u = span > 0 ? Math.min(1, Math.max(0, (renderT - a.at) / span)) : 1;
// Trunk pose in raw MJCF coords: the cloned root applies Z-up -> Y-up.
g.trunk.position.set(
a.p[0] + (b.p[0] - a.p[0]) * u,
a.p[1] + (b.p[1] - a.p[1]) * u,
a.p[2] + (b.p[2] - a.p[2]) * u,
);
_qa.set(a.p[4], a.p[5], a.p[6], a.p[3]); // THREE order x,y,z,w
_qb.set(b.p[4], b.p[5], b.p[6], b.p[3]);
g.trunk.quaternion.copy(_qa.slerp(_qb, u));
for (let i = 0; i < jointNames.length; i++) {
setJoint(g.rig, jointNames[i], a.j[i] + (b.j[i] - a.j[i]) * u);
}
setJawOpen(g.rig, a.w + (b.w - a.w) * u);
driveBall(g, a.b, b.b, u);
}
},
};
liveInstances.add(api);
return api;
}
+139
View File
@@ -0,0 +1,139 @@
// Gamepad haptics engine: named one-shot pulses plus a continuous rumble
// bed, multiplexed onto the single dual-rumble channel the Gamepad API
// exposes per pad (playEffect always REPLACES the running effect - there
// is no hardware mixing, so the mixing policy lives here).
//
// Model (the usual game-feel split):
// strongMagnitude = heavy low-frequency motor -> mass, impacts, thuds
// weakMagnitude = light high-frequency motor -> texture, ticks
//
// Pulses are named presets with a priority: while one is playing, a
// lower-priority pulse is dropped (a wall bump can never eat the fall
// thud) and an equal/higher one takes the channel. `scale` multiplies
// both magnitudes so impact-style cues can ride the physics (ball |dv|,
// bump strength). Presets may be sequences (multi-tap patterns) - taps
// are scheduled with timeouts and cancelled wholesale if another pulse
// takes over mid-pattern.
//
// The bed is a 0..1 level written every control step (roller ground
// speed); it keeps the motors alive between pulses by re-issuing a short
// overlapping effect, yields the instant a pulse fires, and resumes when
// the pulse expires. Everything is fire-and-forget and safe without a
// pad or actuator (Safari, some Firefox/driver stacks): silent no-op.
import { pickPad } from "./controls/gamepad.js";
// Kill switch, mirroring SOUND_DISABLED in audio.js: flip to true and
// every entry point below early-returns.
const HAPTICS_DISABLED = false;
// One-shot presets. d/gap in ms, s/w = strong/weak magnitudes (0..1
// before scale), prio decides who wins the single channel.
const EFFECTS = {
// Confirmed fall (recovery entry or non-recoverable tip-over).
fall: { prio: 3, seq: [{ d: 450, s: 1.0, w: 0.7 }] },
// Solver explosion -> instant reset: the hardest hit in the game.
explode: { prio: 4, seq: [{ d: 550, s: 1.0, w: 1.0 }] },
// Barrel roll finished upright: landing thump.
land: { prio: 2, seq: [{ d: 170, s: 0.7, w: 0.35 }] },
// Kick swing launch (the ball contact rides ballHit on top).
kick: { prio: 1, seq: [{ d: 90, s: 0.5, w: 0.2 }] },
// Ball impact felt through the body - scaled by the hit's |dv|.
ballHit: { prio: 2, seq: [{ d: 120, s: 0.85, w: 0.4 }] },
// Trunk bump against a wall or prop - scaled by |dv|.
bump: { prio: 1, seq: [{ d: 130, s: 0.55, w: 0.25 }] },
// Recovery success (the duck got back up): light double tap.
recover: { prio: 2, seq: [{ d: 70, s: 0.3, w: 0.45 }, { gap: 90 }, { d: 100, s: 0.5, w: 0.65 }] },
};
// Bed tuning: texture-forward (weak motor), a whisper of mass underneath.
const BED_REFRESH_MS = 240; // re-issue cadence; duration overlaps 2x
const BED_STRONG = 0.12;
const BED_WEAK = 0.4;
const BED_FLOOR = 0.03; // below this the bed is considered off
let current = { until: 0, prio: 0 }; // the pulse owning the channel
let seqGen = 0; // generation token: bumping it cancels pending seq taps
let bedLevel = 0;
let bedIssuedAt = 0;
let bedActive = false;
const actuator = () => pickPad()?.vibrationActuator ?? null;
const play = (act, step, scale) => {
act
.playEffect("dual-rumble", {
duration: step.d,
strongMagnitude: Math.min(1, step.s * scale),
weakMagnitude: Math.min(1, step.w * scale),
})
.catch(() => {});
};
function pulse(name, scale = 1) {
if (HAPTICS_DISABLED) return;
const fx = EFFECTS[name];
if (!fx) return;
const act = actuator();
if (!act?.playEffect) return;
const now = performance.now();
if (now < current.until && fx.prio < current.prio) return;
seqGen++; // cancel any in-flight sequence from the previous pulse
const gen = seqGen;
let at = 0;
let total = 0;
for (const step of fx.seq) total += (step.gap ?? 0) + (step.d ?? 0);
current = { until: now + total, prio: fx.prio };
bedActive = false; // the pulse owns the channel; tick() resumes the bed
for (const step of fx.seq) {
at += step.gap ?? 0;
if (!step.d) continue;
if (at === 0) {
play(act, step, scale);
} else {
setTimeout(() => {
if (gen !== seqGen) return; // a newer pulse took the channel
const a = actuator(); // pad may have been yanked meanwhile
if (a?.playEffect) play(a, step, scale);
}, at);
}
at += step.d;
}
}
// Continuous rumble level (0..1), meant to be written every control step
// (it only becomes motion through tick()).
function setBed(level) {
bedLevel = HAPTICS_DISABLED ? 0 : Math.max(0, Math.min(1, level));
}
// Channel scheduler, called once per control step: re-issues the bed
// while it's on and no pulse owns the channel, and cuts the motors when
// the bed falls silent (playEffect would otherwise finish the last
// overlap on its own, a ~0.5 s tail).
function tick() {
if (HAPTICS_DISABLED) return;
const now = performance.now();
if (now < current.until) return;
const act = actuator();
if (!act) return;
if (bedLevel > BED_FLOOR) {
if (now - bedIssuedAt >= BED_REFRESH_MS) {
bedIssuedAt = now;
bedActive = true;
act
.playEffect?.("dual-rumble", {
duration: BED_REFRESH_MS * 2,
strongMagnitude: Math.min(1, BED_STRONG * bedLevel),
weakMagnitude: Math.min(1, BED_WEAK * bedLevel),
})
.catch(() => {});
}
} else if (bedActive) {
bedActive = false;
bedIssuedAt = 0;
try { act.reset?.()?.catch?.(() => {}); } catch { /* older impls throw sync */ }
}
}
export const haptics = { pulse, setBed, tick };
+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;
}
+13
View File
@@ -0,0 +1,13 @@
// Private HF Space auth: the hub iframe URL carries a ?__sign JWT, but
// subresource requests normally rely on a *.static.hf.space cookie that
// browsers often block inside the iframe (third-party cookie blocking),
// which 401s every same-origin fetch. Appending the JWT to each request
// authenticates them regardless of cookie policy. No-op locally.
//
// Only ASSET requests (meshes, policies, XML, audio, images) go through
// this now: application code ships in the Vite bundle, which the page load
// itself already authenticated.
const HF_SIGN = new URLSearchParams(location.search).get("__sign");
export const signed = (url) =>
HF_SIGN ? `${url}${url.includes("?") ? "&" : "?"}__sign=${encodeURIComponent(HF_SIGN)}` : url;
+222
View File
@@ -0,0 +1,222 @@
// Comic sticker popups: on notable game events (kick, quack, roll, ball
// spawn, ghost peer joining) a die-cut sticker or a comic onomatopoeia pops
// at a semi-random spot on screen, overshoots in, then fades out. Pure
// CSS animations, no dependencies.
//
// Fully self-contained and OPTIONAL: this module owns its DOM layer and its
// <style> tag, and imports nothing from the rest of the game. rl.js keeps a
// nullable `stickers` slot and calls `stickers?.pop("kick")` at each event
// site, so deleting the single import line in rl.js removes the feature
// without breaking anything.
//
// Image assets are the pre-cut Pollen showcase stickers (assets/stickers/,
// webp with transparency). Their URLs go through the injected `signed()`
// helper so they load on the private HF Space (?__sign JWT) as well as
// locally, where signed() is a no-op.
//
// const stickers = initStickers({ signed, isLocked });
// stickers.pop("quack"); // one of: kick, quack, roll, spawn, hi
// stickers.dispose(); // remove layer + styles (tests/teardown)
// Bump when the webp files change; python http.server sends no
// Cache-Control, same convention as the mesh/module ?v= busters.
const ASSET_V = "1";
const DIR = "./assets/stickers";
// Comic palette sampled from the sticker sheet itself.
const C = {
red: "#ff3b30",
teal: "#1fb6a8",
yellow: "#ffd23f",
blue: "#2f8bff",
pink: "#ff2d78",
};
// Per-event pools: each pop picks one variant at random. `img` is a die-cut
// webp sticker (w = on-screen width in px before jitter), `text` a pure
// CSS onomatopoeia; both together = text overlaid on the image (POP! burst).
// `cool` is the per-event rate limit in ms - repeated quacks/kicks reuse
// the sticker on screen instead of stacking a new one per press.
const EVENTS = {
kick: {
cool: 900,
pool: [
{ img: "bang-red", w: 170 },
{ img: "boom", w: 175 },
{ img: "star-yellow", w: 120 },
{ text: "BAM!", color: C.red },
],
},
quack: {
cool: 700,
pool: [
{ img: "quack", w: 180 },
{ img: "quack-quack", w: 170 },
{ text: "QUACK!", color: C.teal },
],
},
roll: {
cool: 1600,
pool: [
{ text: "WHEE!", color: C.pink },
{ img: "ziouuu", w: 200 },
{ img: "shooting-star", w: 150 },
],
},
spawn: {
cool: 900,
pool: [
{ img: "burst-yellow", w: 140, text: "POP!", color: C.pink },
{ text: "POP!", color: C.yellow },
],
},
hi: {
cool: 2500,
pool: [
{ text: "HI!", color: C.blue },
{ img: "wave", w: 150 },
],
},
};
const MAX_LIVE = 4; // concurrent stickers, all events combined
const LIFE_MS = 1250; // matches the CSS animation duration below
// Safe zone (viewport %): keeps stickers off the HUD corners - mode label
// top-left, REC/stats top-right (+ colour stack below it), hint keycaps
// along the bottom. The middle band is all playground.
const ZONE = { x0: 16, x1: 78, y0: 20, y1: 68 };
const CSS = `
#sticker-layer {
position: fixed;
inset: 0;
z-index: 9; /* above the CRT overlay (5), below the HUD (10) */
pointer-events: none;
overflow: hidden;
}
#sticker-layer .sticker {
position: absolute;
will-change: transform, opacity;
animation: sticker-pop ${LIFE_MS}ms cubic-bezier(0.22, 1, 0.36, 1) forwards;
}
#sticker-layer .sticker img {
display: block;
filter: drop-shadow(0 4px 10px rgba(0, 0, 0, 0.35));
}
#sticker-layer .sticker-text {
font-family: "Arial Black", "Avenir-Black", "Helvetica Neue", sans-serif;
font-weight: 900;
font-style: italic;
font-size: clamp(2.4rem, 5.5vw, 4.2rem);
letter-spacing: 0.02em;
white-space: nowrap;
-webkit-text-stroke: 0.24em #fff;
paint-order: stroke fill;
text-shadow: 0.07em 0.1em 0 rgba(20, 10, 40, 0.85);
filter: drop-shadow(0 4px 10px rgba(0, 0, 0, 0.35));
}
/* Text overlaid on a die-cut sticker (e.g. POP! on the blank burst). */
#sticker-layer .sticker-overlay {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
font-size: clamp(1.6rem, 3.2vw, 2.4rem);
transform: rotate(-8deg);
}
/* Pop-in with scale overshoot + a small rotation settle, short hold, then
shrink/fade. --rot / --s carry the per-pop random jitter. */
@keyframes sticker-pop {
0% { transform: translate(-50%, -50%) rotate(calc(var(--rot) - 12deg)) scale(0); opacity: 0; }
14% { transform: translate(-50%, -50%) rotate(calc(var(--rot) + 3deg)) scale(calc(var(--s) * 1.22)); opacity: 1; }
26% { transform: translate(-50%, -50%) rotate(var(--rot)) scale(calc(var(--s) * 0.96)); }
36% { transform: translate(-50%, -50%) rotate(var(--rot)) scale(var(--s)); }
78% { transform: translate(-50%, -50%) rotate(var(--rot)) scale(var(--s)); opacity: 1; }
100% { transform: translate(-50%, -50%) rotate(var(--rot)) scale(calc(var(--s) * 0.5)); opacity: 0; }
}
@media (prefers-reduced-motion: reduce) {
#sticker-layer .sticker { animation-duration: 1ms; }
}
`;
const rand = (a, b) => a + Math.random() * (b - a);
export function initStickers({ signed = (u) => u, isLocked = () => false } = {}) {
const url = (name) => signed(`${DIR}/${name}.webp?v=${ASSET_V}`);
const style = document.createElement("style");
style.textContent = CSS;
document.head.appendChild(style);
const layer = document.createElement("div");
layer.id = "sticker-layer";
layer.setAttribute("aria-hidden", "true");
document.body.appendChild(layer);
// Warm the image cache so the first pop of each sticker isn't a blank
// frame while the webp downloads.
for (const { pool } of Object.values(EVENTS))
for (const v of pool) if (v.img) new Image().src = url(v.img);
const lastAt = new Map(); // event -> last pop timestamp
// Avoid showing the same variant twice in a row per event.
const lastPick = new Map();
const pop = (event) => {
const cfg = EVENTS[event];
if (!cfg) return;
if (isLocked()) return; // no stickers during the entrance/reset ceremony
const now = performance.now();
if (now - (lastAt.get(event) ?? -Infinity) < cfg.cool) return;
if (layer.childElementCount >= MAX_LIVE) return;
lastAt.set(event, now);
let i = (Math.random() * cfg.pool.length) | 0;
if (cfg.pool.length > 1 && i === lastPick.get(event)) i = (i + 1) % cfg.pool.length;
lastPick.set(event, i);
const v = cfg.pool[i];
const el = document.createElement("div");
el.className = "sticker";
el.style.left = `${rand(ZONE.x0, ZONE.x1)}%`;
el.style.top = `${rand(ZONE.y0, ZONE.y1)}%`;
el.style.setProperty("--rot", `${rand(-14, 14)}deg`);
el.style.setProperty("--s", rand(0.88, 1.12).toFixed(2));
if (v.img) {
const img = document.createElement("img");
img.src = url(v.img);
img.width = v.w;
img.alt = "";
el.appendChild(img);
if (v.text) {
const t = document.createElement("span");
t.className = "sticker-text sticker-overlay";
t.style.color = v.color;
t.textContent = v.text;
el.appendChild(t);
}
} else {
const t = document.createElement("span");
t.className = "sticker-text";
t.style.color = v.color;
t.textContent = v.text;
el.appendChild(t);
}
el.addEventListener("animationend", () => el.remove(), { once: true });
// Fallback sweep in case the animation never fires (hidden tab).
setTimeout(() => el.remove(), LIFE_MS + 500);
layer.appendChild(el);
};
return {
pop,
dispose() {
layer.remove();
style.remove();
},
};
}
+358
View File
@@ -0,0 +1,358 @@
// Colour variants of the real Microduck robots (see the reference photo of
// the four printed units). Each variant fills the same semantic slots; the
// mesh-filename -> slot mapping lives in meshMaterialsFor(). All colours are
// linear-space RGB and slightly oversaturated: the renderer tone-maps with
// ACESFilmicToneMapping under warm key/rim lights, which desaturates and
// shifts hues toward gold, so the base colours lean past the target to land
// right on screen.
import * as THREE from "three";
// ── Shared slot specs (identical on all four robots) ───────────────────
// sRGB targets from the reference photo, converted to linear with a
// slight saturation boost (x1.12) so ACES lands on the clean tint.
const AMBER_YELLOW = { color: [1.0, 0.413, 0.007], roughness: 0.4, metalness: 0.0 }; // #ffb52e
const BRIGHT_ORANGE = { color: [1.0, 0.144, 0.008], roughness: 0.45, metalness: 0.0 }; // #ff7a2f
const AMBER = { color: [0.847, 0.339, 0.022], roughness: 0.45, metalness: 0.0 }; // #eda63e
const CLEAN_YELLOW = { color: [1.0, 0.608, 0.021], roughness: 0.4, metalness: 0.0 }; // #ffd23f
const CREAM = { color: [0.888, 0.86, 0.798], roughness: 0.35, metalness: 0.0 }; // #f2efe8
const DARK = { color: [0.012, 0.012, 0.014], roughness: 0.55, metalness: 0.3 }; // #1d1d1f
const GRAY = { color: [0.256, 0.256, 0.279], roughness: 0.5, metalness: 0.35 }; // #8b8b90
// Camera-lens eye: very dark blue-black, glossy like coated glass.
const LENS = { color: [0.01, 0.012, 0.02], roughness: 0.05, metalness: 0.0 };
// Per-variant colours.
const WARM_GRAY = { color: [0.328, 0.312, 0.283], roughness: 0.35, metalness: 0.0 }; // #9b9892
const AMBER_ORANGE = { color: [0.815, 0.321, 0.019], roughness: 0.5, metalness: 0.0 }; // #e9a23b
const CHARCOAL = { color: [0.028, 0.028, 0.033], roughness: 0.5, metalness: 0.0 }; // #2f2f33
const CHARCOAL_FACE = { color: [0.044, 0.044, 0.051], roughness: 0.5, metalness: 0.0 }; // #3c3c40
const CHARCOAL_BODY = { color: [0.017, 0.017, 0.019], roughness: 0.5, metalness: 0.0 }; // #232326
const LIGHT_WARM_GRAY = { color: [0.485, 0.459, 0.416], roughness: 0.35, metalness: 0.0 };// #b9b5ae
const PURPLE_RING = { color: [0.443, 0.308, 0.663], roughness: 0.4, metalness: 0.0 }; // #b098d0
// Sole pads read a notch deeper than the eye ring on the real robots.
const PURPLE_SOLE = { color: [0.221, 0.134, 0.465], roughness: 0.45, metalness: 0.0 }; // #8068b0
// Lavender trunk / leg shells: a notch lighter than the eye ring.
const LAVENDER_SHELL = { color: [0.462, 0.367, 0.688], roughness: 0.35, metalness: 0.0 }; // #b4a4d4
const SOFT_PURPLE = { color: [0.36, 0.23, 0.48], roughness: 0.45, metalness: 0.0 }; // #a489b5
const PURPLE_FEET = { color: [0.164, 0.085, 0.584], roughness: 0.45, metalness: 0.0 }; // #7a5fc9
const PALE_BLUE = { color: [0.441, 0.613, 0.723], roughness: 0.35, metalness: 0.0 }; // #b6cfdd
const MEDIUM_BLUE = { color: [0.13, 0.321, 0.552], roughness: 0.35, metalness: 0.0 }; // #6f9ec4
const BLUE_GRAY = { color: [0.183, 0.379, 0.565], roughness: 0.35, metalness: 0.0 }; // #7fa9c6
const FEET_YELLOW = { color: [0.784, 0.455, 0.023], roughness: 0.5, metalness: 0.0 }; // #e5b93e
// Slots (validated against the four-robot reference photo): headDome
// (top shell), facePlate (around the eye), trim (band under the shell +
// upper beak base), beakUpper (mouth-roof plate), beakLower (rigid jaw),
// tongue (soft pad inside the beak), eyeRing, lens, bodyShell (trunk
// base), sideShells (left + right trunk shells), legShells (upper-leg
// shells), feet (shoe upper: foot blocks + ankle brackets), soles (shoe
// lower: sole pads), hips (hip covers), mechDark, mechGray.
// The mouth interior (upper gum = beakUpper, tongue) is amber on the
// classic/blue pair and soft purple on the charcoal/purple pair (checked
// against the real robots). Only the rigid jaw (beakLower) carries the
// beak colour. Classic and blue wear orange shoes on clean yellow soles.
export const VARIANTS = {
// Front-center robot: warm gray head, cream body, amber eye, orange
// trim and beak, amber mouth interior, orange shoes on yellow soles.
classic: {
headDome: CREAM,
facePlate: WARM_GRAY,
trim: BRIGHT_ORANGE,
beakUpper: AMBER_YELLOW,
beakLower: BRIGHT_ORANGE,
tongue: AMBER_YELLOW,
eyeRing: AMBER_YELLOW,
lens: LENS,
bodyShell: CREAM,
sideShells: CREAM,
legShells: CREAM,
feet: BRIGHT_ORANGE,
soles: CLEAN_YELLOW,
hips: GRAY,
mechDark: DARK,
mechGray: GRAY,
},
// Front-left robot: shares the purple colourway everywhere except its
// shells - warm gray face plate, yellow trim / rigid jaw / shoes, soft
// purple mouth interior, purple eye ring on purple soles. The head dome
// and the trunk / leg shells stay charcoal, which is what tells this
// variant apart from purple (and what the picker chip shows).
charcoal: {
headDome: CHARCOAL,
facePlate: WARM_GRAY,
trim: CLEAN_YELLOW,
beakUpper: SOFT_PURPLE,
beakLower: CLEAN_YELLOW,
tongue: SOFT_PURPLE,
eyeRing: PURPLE_RING,
lens: LENS,
bodyShell: CHARCOAL_BODY,
sideShells: CHARCOAL_BODY,
legShells: CHARCOAL_BODY,
feet: CLEAN_YELLOW,
soles: PURPLE_SOLE,
hips: GRAY,
mechDark: DARK,
mechGray: GRAY,
},
// Back-center robot: lavender head dome over a warm gray face plate,
// pale blue eye (the same blue the sky variant wears), YELLOW trim and
// rigid jaw, soft purple mouth interior, lavender trunk / leg shells
// on purple soles.
purple: {
headDome: LAVENDER_SHELL,
facePlate: WARM_GRAY,
trim: CLEAN_YELLOW,
beakUpper: SOFT_PURPLE,
beakLower: CLEAN_YELLOW,
tongue: SOFT_PURPLE,
eyeRing: PALE_BLUE,
lens: LENS,
bodyShell: LAVENDER_SHELL,
sideShells: LAVENDER_SHELL,
legShells: LAVENDER_SHELL,
feet: CLEAN_YELLOW,
soles: PURPLE_SOLE,
hips: GRAY,
mechDark: DARK,
mechGray: GRAY,
// UI swatch override: kept from when the head and body were gray/cream
// and only the accents carried the purple identity. The shells are
// lavender now, so this no longer diverges much - and nothing reads it
// anyway (the HUD picker uses VARIANT_SWATCH_HEX below).
swatch: PURPLE_FEET,
},
// Right robot: shares the classic colourway everywhere except its
// shells - warm gray face plate, amber eye, orange beak, amber mouth
// interior, orange shoes on yellow soles, gray hips. The head dome and
// the trunk / leg shells stay pale blue, which is what tells this
// variant apart from classic (and what the picker chip shows).
blue: {
headDome: PALE_BLUE,
facePlate: WARM_GRAY,
trim: BRIGHT_ORANGE,
beakUpper: AMBER_YELLOW,
beakLower: BRIGHT_ORANGE,
tongue: AMBER_YELLOW,
eyeRing: AMBER_YELLOW,
lens: LENS,
bodyShell: PALE_BLUE,
sideShells: PALE_BLUE,
legShells: PALE_BLUE,
feet: BRIGHT_ORANGE,
soles: CLEAN_YELLOW,
hips: GRAY,
mechDark: DARK,
mechGray: GRAY,
},
};
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)];
// Mesh filename -> material spec for one variant (mjlab model meshes).
// Anything not listed is small mechanical hardware and falls back to
// mechGray. Verified visually against the four-robot reference photo.
export function meshMaterialsFor(v) {
return {
// Head: dome, band under it, face plate around the eye.
"top_head_shell.stl": v.headDome,
"bottom_head_shell.stl": v.trim,
"face_part.stl": v.facePlate,
// The eye: printed ring + camera lens behind it.
"noenoeil.stl": v.eyeRing,
"lens.stl": v.lens,
"m12_lens_holder.stl": v.mechDark,
// Beak: mouth-roof plate on top, rigid jaw below, soft pad (the
// tongue) riding on the jaw.
"soft_mouth_top.stl": v.beakUpper,
"jaw.stl": v.beakLower,
"jaw_soft.stl": v.tongue,
// Body: trunk base + the two side shells (shared slot).
"trunk_base.stl": v.bodyShell,
"left_shell.stl": v.sideShells,
"right_shell.stl": v.sideShells,
"upper_leg_left.stl": v.legShells,
"upper_leg_right.stl": v.legShells,
"hip_l.stl": v.hips,
// Feet: foot block + ankle bracket, soft sole pad below.
"foot_left.stl": v.feet,
"foot_right.stl": v.feet,
"ankle_left.stl": v.feet,
"ankle_right.stl": v.feet,
"sole_left.stl": v.soles,
"sole_right.stl": v.soles,
// Roller variant: the blade + ankle bracket take the shoe-upper slot,
// the rims take the sole accent, the tires are rubber-dark.
"ankle_l_v1.stl": v.feet,
"ankle_r_v1.stl": v.feet,
"roller_blade.stl": v.feet,
"rim.stl": v.soles,
"tire.stl": v.mechDark,
// Dark mechanics. leg.stl is the printed shin that wraps the ankle
// motor and its bearing ring: gray on the real robots, standing
// apart from the black motor it holds.
"xl330.stl": v.mechDark,
"leg.stl": v.mechGray,
"seeed_bearing__configuration_default.stl": v.mechDark,
// Hip yaw mechanism (ribbed ring + 4-screw plate): reads as the hip
// motor, so it goes dark too. The printed hip cover (hip_l.stl)
// keeps the dedicated `hips` slot. The neck bracket is gray on the
// real robots, standing apart from the motors it carries.
"yaw2roll.stl": v.mechDark,
"bearing_roll.stl": v.mechDark,
"neck.stl": v.mechGray,
"np_f970.stl": v.mechDark,
"pcb__raspberry_pi_zero_2_w.stl": v.mechDark,
"elec_rpi_robot_hat_pcb.stl": v.mechDark,
"banana_pcb_locker.stl": v.mechDark,
"speaker.stl": v.mechDark,
// Gray mechanics
"upper_leg_rigidity_plate.stl": v.mechGray,
"yaw_roll_motion.stl": v.mechGray,
"neck_pitch.stl": v.mechGray,
"motor_support.stl": v.mechGray,
"power_support.stl": v.mechGray,
"seeed_bearing__configuration__22x16x4.stl": v.mechGray,
};
}
// buildRig materialForMesh hook for one variant.
export const materialHookFor = (v) => {
const map = meshMaterialsFor(v);
return (mesh) => map[mesh] ?? v.mechGray;
};
// ── Live re-skin ────────────────────────────────────────────────────────
// Swap materials on an already-built rig without reloading any STL.
// Meshes are identified via userData.meshName (set by duck.js buildRig and
// preserved by cloneRig). Materials are cached per resolved spec so clones
// and repeated switches share GPU material instances.
const matCache = new Map();
function matFor(spec) {
const key = `${spec.color.join(",")}|${spec.roughness ?? 0.5}|${spec.metalness ?? 0}`;
let m = matCache.get(key);
if (!m) {
m = new THREE.MeshStandardMaterial({
color: new THREE.Color(...spec.color),
roughness: spec.roughness ?? 0.5,
metalness: spec.metalness ?? 0.0,
});
matCache.set(key, m);
}
return m;
}
// ── Smooth colourway fades ──────────────────────────────────────────────
// applyVariant on a rig that is live in a scene tweens every mesh's
// colour/roughness/metalness toward the new spec (same feel as the
// showcase site: ~0.35 s, ease in-out) instead of snapping. Off-scene
// rigs (first paint, the locomotion rig swap before scene.add, freshly
// cloned ghosts) keep the instant path, so hidden repaints stay exact.
//
// Each fading mesh gets a transient material (clone of the target cache
// entry, rewound to the current look) so the shared matCache instances
// are never mutated. The per-frame driver writes to that transient
// material AND to whatever the mesh currently carries: systems that swap
// materials mid-fade (ghostify's transparent clones, the wireframe FX's
// clip clones) keep receiving colour updates and still land on the exact
// target values. When nothing intervened, the mesh settles back on the
// shared cache material, so the at-rest state is byte-identical to a
// snap (the wireframe FX caches clip clones per material uuid, which
// must stay stable across colour changes). Driven by a self-contained
// rAF ticker that only runs while fades are active - no render-loop hook
// needed, and rapid re-clicks simply retarget from the current colours.
const FADE_S = 0.35;
const easeInOut = (x) => (x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2);
const fades = new Map(); // mesh -> fade record
let fadeRaf = 0;
function driveFades() {
const t = performance.now() / 1000;
for (const [mesh, f] of fades) {
const x = Math.min(1, (t - f.start) / FADE_S);
const e = easeInOut(x);
f.mat.color.lerpColors(f.fromColor, f.toColor, e);
f.mat.roughness = f.fromRough + (f.toRough - f.fromRough) * e;
f.mat.metalness = f.fromMetal + (f.toMetal - f.fromMetal) * e;
const cur = mesh.material;
if (cur !== f.mat && cur?.color) {
cur.color.copy(f.mat.color);
cur.roughness = f.mat.roughness;
cur.metalness = f.mat.metalness;
}
if (x >= 1) {
fades.delete(mesh);
if (cur === f.mat) {
mesh.material = matFor(f.spec);
f.mat.dispose();
}
}
}
fadeRaf = fades.size ? requestAnimationFrame(driveFades) : 0;
}
export function applyVariant(rig, variant) {
const v = typeof variant === "string" ? VARIANTS[variant] : variant;
const map = meshMaterialsFor(v);
const fade = !!rig.placer?.parent;
rig.root.traverse((o) => {
if (!o.isMesh || !o.userData.meshName) return;
const spec = map[o.userData.meshName] ?? v.mechGray;
const target = matFor(spec);
if (!fade) {
fades.delete(o);
o.material = target;
return;
}
// Already resting on the target material and not mid-fade: no-op.
if (o.material === target && !fades.has(o)) return;
const from = o.material;
const m = target.clone();
m.color.copy(from.color);
m.roughness = from.roughness;
m.metalness = from.metalness;
fades.set(o, {
mat: m,
spec,
fromColor: from.color.clone(),
toColor: target.color.clone(),
fromRough: from.roughness,
toRough: target.roughness,
fromMetal: from.metalness,
toMetal: target.metalness,
start: performance.now() / 1000,
});
o.material = m;
});
if (fades.size && !fadeRaf) fadeRaf = requestAnimationFrame(driveFades);
}
// Linear-space spec colour -> sRGB CSS hex, for swatch UI elements.
export function specToHex(spec) {
return `#${new THREE.Color(...spec.color).getHexString()}`;
}
+60
View File
@@ -0,0 +1,60 @@
/* eslint-disable */
// ZzFX - Zuper Zmall Zound Zynth - v1.3.2 by Frank Force
// https://github.com/KilledByAPixel/ZzFX
//
// MIT License - Copyright (c) 2019 Frank Force
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software. The above copyright notice and this
// permission notice shall be included in all copies or substantial portions
// of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
// KIND.
//
// Local adaptation (soundboard experiment): the upstream ZzFXMicro build
// creates its own AudioContext and plays straight to the hardware output.
// This build splits synthesis (zzfxG, byte-for-byte the upstream v1.3.2
// sample generator) from playback (zzfxP), and playback goes through a
// caller-provided AudioContext + destination node, so candidate sounds ride
// the game's shared master gain / sfx bus like the runtime sounds do.
export const zzfxR = 44100; // sample rate
export const zzfxV = 0.3; // default volume scale
// Generate samples for a ZzFX sound. Parameter order:
// volume, randomness, frequency, attack, sustain, release, shape, shapeCurve,
// slide, deltaSlide, pitchJump, pitchJumpTime, repeatTime, noise, modulation,
// bitCrush, delay, sustainVolume, decay, tremolo, filter
export const zzfxG = (p=1,k=.05,b=220,e=0,r=0,t=.1,q=0,D=1,u=0,y=0,v=0,z=0,l=0,E=0,A=0,F=0,c=0,w=1,m=0,B=0,N=0)=>{
let M=Math,d=2*M.PI,R=zzfxR,G=u*=500*d/R/R,C=b*=(1-k+2*k*M.random(k=[]))*d/R,
g=0,H=0,a=0,n=1,I=0,J=0,f=0,h=N<0?-1:1,x=d*h*N*2/R,L=M.cos(x),Z=M.sin,K=Z(x)/4,O=1+K,
X=-2*L/O,Y=(1-K)/O,P=(1+h*L)/2/O,Q=-(h+L)/O,S=P,T=0,U=0,V=0,W=0;
e=R*e+9;m*=R;r*=R;t*=R;c*=R;y*=500*d/R**3;A*=d/R;v*=d/R;z*=R;l=R*l|0;p*=zzfxV;
for(h=e+m+r+t+c|0;a<h;k[a++]=f*p)
++J%(100*F|0)||(
f=q?1<q?2<q?3<q?4<q?(g/d%1<D/2)*2-1:Z(g**3):M.max(M.min(M.tan(g),1),-1):1-(2*g/d%2+2)%2:1-4*M.abs(M.round(g/d)-g/d):Z(g),
f=(l?1-B+B*Z(d*a/l):1)*(4<q?f:(f<0?-1:1)*M.abs(f)**D)*(a<e?a/e:a<e+m?1-(a-e)/m*(1-w):a<e+m+r?w:a<h-c?(h-a-c)/t*w:0),
f=c?f/2+(c>a?0:(a<h-c?1:(h-a)/c)*k[a-c|0]/2/p):f,
N?f=W=S*T+Q*(T=U)+P*(U=f)-Y*V-X*(V=W):0
),
x=(b+=u+=y)*M.cos(A*H++),
g+=x+x*E*Z(a**5),
n&&++n>z&&(b+=v,C+=v,n=0),
!l||++I%l||(b=C,u=G,n=n||1);
return k;
};
// Play generated samples through the given context/destination.
export function zzfxP(ctx, destination, samples) {
const buf = ctx.createBuffer(1, samples.length, zzfxR);
buf.getChannelData(0).set(samples);
const src = ctx.createBufferSource();
src.buffer = buf;
src.connect(destination);
src.start();
return src;
}
// Convenience: synthesize + play in one call.
export const zzfx = (ctx, destination, ...params) => zzfxP(ctx, destination, zzfxG(...params));
+27
View File
@@ -0,0 +1,27 @@
import { lazy, Suspense } from "react";
import { createRoot } from "react-dom/client";
import { ThemeProvider } from "@mui/material/styles";
import CssBaseline from "@mui/material/CssBaseline";
import { theme } from "./theme.js";
// ?soundboard=1: standalone audio A/B experiment page instead of the game
// (lazy on both sides so the soundboard never pulls the game bundle in).
const App = new URLSearchParams(location.search).get("soundboard") === "1"
? lazy(() => import("./ui/Soundboard.jsx"))
: lazy(() => import("./App.jsx"));
// Build tag: bump to change the bundle's content hash, e.g. to bust a stale
// edge-cached asset URL on the HF Space.
const BUILD_TAG = "2026-08-25";
console.info(`Microduck build ${BUILD_TAG}`);
// No StrictMode: the game core is a heavyweight singleton (MuJoCo WASM,
// ONNX sessions, WebRTC room) and dev double-mounting would double-boot it.
createRoot(document.getElementById("root")).render(
<ThemeProvider theme={theme}>
<CssBaseline />
<Suspense fallback={null}>
<App />
</Suspense>
</ThemeProvider>,
);
+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;
}
+61
View File
@@ -0,0 +1,61 @@
// R3F shell around the imperative game core. The Canvas owns the renderer,
// default camera and the rAF loop; <Game> boots the core once and drives it
// from useFrame. Lights and environment are declarative; the grid, walls,
// duck rig, ball and props are added to the scene by the core (they carry
// ceremony-driven shader state).
import { useEffect } from "react";
import * as THREE from "three";
import { Canvas, useThree, useFrame } from "@react-three/fiber";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
import { bootGame } from "../game/game.js";
import { gameApi } from "../store.js";
import { SPAWN_X, SPAWN_Y } from "../game/constants.js";
import CrtDistortion, { CRT_DISTORTION_ENABLED } from "./CrtDistortion.jsx";
function Game() {
const { scene, camera, gl } = useThree();
useEffect(() => {
scene.background = new THREE.Color(0x08080c);
gl.setClearColor(0x08080c, 1);
const pmrem = new THREE.PMREMGenerator(gl);
scene.environment = pmrem.fromScene(new RoomEnvironment()).texture;
scene.environmentIntensity = 0.45;
bootGame({ scene, camera, renderer: gl });
}, [scene, camera, gl]);
// dt clamped so a background-tab stall can't slingshot the camera orbit.
useFrame((_, dt) => {
gameApi.frame?.(Math.min(dt, 0.05));
});
return (
<>
<ambientLight intensity={0.6} />
<directionalLight position={[2, 4, 2]} intensity={1.6} />
<directionalLight position={[-2, 2, 1.5]} intensity={0.4} />
<directionalLight color={0xffb366} position={[0, 3, -2]} intensity={0.7} />
</>
);
}
export default function GameCanvas() {
return (
<Canvas
style={{ position: "fixed", inset: 0, zIndex: 1 }}
dpr={[1, 2]}
gl={{ antialias: true, alpha: true }}
// Boot framing translated onto the spawn cell (the orbit target
// follows), so the follow-cam has nothing to drift toward during boot.
camera={{
fov: 40,
near: 0.02,
far: 30,
position: [SPAWN_X + 0.55, 0.35, -SPAWN_Y + 0.7],
}}
>
<Game />
{CRT_DISTORTION_ENABLED && <CrtDistortion />}
</Canvas>
);
}
+87
View File
@@ -0,0 +1,87 @@
// Central bridge between the imperative game core and the React UI.
//
// Data flows one way per concern:
// game -> store state the UI renders (mode label, loco, telemetry, boot
// milestones). Written via useGame.setState from game code;
// high-frequency values (telemetry) are throttled at the
// producer so React never re-renders at frame rate.
// UI -> gameApi intents (set colour, switch loco, reset, open/close
// menu side effects). gameApi is a plain object populated
// once the game boots; optional-chained calls make the UI
// safe to interact with before that.
import { create } from "zustand";
import { subscribeWithSelector } from "zustand/middleware";
export const useGame = create(
subscribeWithSelector(() => ({
// Boot lifecycle
prebootDone: false, // title assets ready, grey veil dropped
entered: false, // first "Waddle in" clicked (latches)
menuOpen: false, // title / pause overlay up (opened by App after preboot)
biosVisible: false, // BIOS readout playing over the scene
bootDone: false,
bootFailed: false,
// Game state mirrored for the UI
modeLabel: "Run",
loco: "legs", // "legs" | "rollers" - what the game is actually running
locoWant: "legs", // what the quickbar asked for (game reconciles)
locoSwitching: false,
rollersLoading: false, // OSD line while the roller stack streams in
variant: "classic",
// Community move: null = all-official slots. Written by the game
// (game.js loadCustomPolicyIntoGame / the watchdog) and by App.jsx for
// the boot-time ?move= request.
// { ref, name, status: "loading"|"active"|"error", error?, revertReason?,
// kind?: "perpetual"|"episodic"|"script", slot?: "walk"|"sitstand"|"trick"|"script",
// title?, author?, academy? (manifest.academy block) }
customPolicy: null,
padConnected: false,
touchMode: false,
ballActive: false,
// Throttled telemetry block (4 Hz), bottom-right OSD
telemetry: { fps: 0, ctrlHz: 0, speed: 0, odo: 0, peers: 0 },
})),
);
// Imperative game surface, assigned by game/game.js once booted. The UI
// only ever optional-chains into it.
export const gameApi = {};
// Debug handles for the console / automated QA (same spirit as window.rl).
if (typeof window !== "undefined") {
window.__store = useGame;
window.__gameApi = gameApi;
}
// BIOS/POST milestone log. Plain module state on purpose: the readout
// component polls it inside its own paced replay loop (same as the old
// playBios), so no reactivity is needed and log spam never re-renders React.
// Entries: { label, status, raw, halt, progress } - status null = pending.
export const bootLog = [];
export const bootLine = (label) => {
const entry = { label, status: null, raw: false, progress: null };
bootLog.push(entry);
const done = (status = "OK") => {
entry.status = status;
};
done.progress = (p) => {
entry.progress = p;
};
return done;
};
export const bootNote = (label) => {
bootLog.push({ label, status: "", raw: true });
};
// Fatal boot failure: freeze the BIOS on the halt screen (the readout is
// the diagnostic surface). Drops the title overlay if still up.
export function bootHalt(detail) {
const s = useGame.getState();
if (s.bootFailed || s.bootDone) return;
bootNote(`>> ${detail}`);
bootLog.push({ label: "SYSTEM HALTED", status: "", raw: true, halt: true });
useGame.setState({ bootFailed: true, menuOpen: false, biosVisible: true });
}
+25
View File
@@ -0,0 +1,25 @@
// MUI theme carrying the sim's DA: ink background, bright robot orange,
// system sans for copy, tight monospace for the OSD layers. Components keep
// most of their look in sx/styled - the theme only centralizes the tokens.
import { createTheme } from "@mui/material/styles";
export const INK = "#08080c";
export const ORANGE = "#ff7a2f";
export const MONO = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';
export const theme = createTheme({
palette: {
mode: "dark",
primary: { main: ORANGE, contrastText: INK },
background: { default: INK, paper: INK },
text: {
primary: "rgba(255, 255, 255, 0.85)",
secondary: "rgba(255, 255, 255, 0.45)",
},
},
typography: {
fontFamily:
'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
},
shape: { borderRadius: 8 },
});
+195
View File
@@ -0,0 +1,195 @@
// BIOS/POST boot readout. The real load runs silently behind the title
// overlay and only RECORDS milestones into bootLog (store.js); the readout
// itself plays after the first "Waddle in": a rapid-fire replay when
// everything already finished, or an honest live tracker (cursor blinking
// on the pending line) when the user enters mid-load. Never slows the
// actual boot. The line pacing is imperative DOM on purpose - it is a
// character-level animation, not UI state.
import { useEffect, useRef, useState } from "react";
import Box from "@mui/material/Box";
import { keyframes } from "@mui/material/styles";
import { useGame, gameApi, bootLog } from "../store.js";
import { playBiosBeep, playBiosTick } from "../game/audio.js";
import { INK, MONO } from "../theme.js";
const postBlink = keyframes`
0%, 55% { opacity: 1; }
56%, 100% { opacity: 0; }
`;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const lineText = (e) => {
if (e.raw) return e.label;
// Pending line: bare label, plus a live counter when the stage reports
// progress (e.g. "LOADING POLICIES [3/5]").
if (e.status === null) return e.progress ? `${e.label} [${e.progress}]` : e.label;
return `${e.label} `.padEnd(26, ".") + ` ${e.status}`;
};
export default function BiosOverlay() {
const entered = useGame((s) => s.entered);
const bootFailed = useGame((s) => s.bootFailed);
const postRef = useRef(null);
const startedRef = useRef(false);
const [visible, setVisible] = useState(false);
const [off, setOff] = useState(false);
useEffect(() => {
// Only the initial entry triggers the replay (startedRef latches);
// a fatal boot failure forces it up regardless (the halt screen IS
// the diagnostic surface).
if ((!entered && !bootFailed) || startedRef.current) return;
startedRef.current = true;
playBios();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [entered, bootFailed]);
async function playBios() {
const store = useGame.getState;
setVisible(true);
useGame.setState({ biosVisible: true });
// POST beep: the replay only starts after the enter click (the audio
// unlock gesture), and the synth no-ops if the context is still locked
// (gamepad-only entry).
playBiosBeep();
const postEl = postRef.current;
// Seeded LCG: the replay rhythm is random-feeling but identical on
// every load - real POST screens burst through most checks and stall
// on a few.
let seed = 11;
const rand = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
const els = new Map(); // entry -> element
let i = 0;
for (;;) {
const { bootDone, bootFailed: failed } = store();
if (i < bootLog.length) {
const entry = bootLog[i++];
const el = document.createElement("div");
if (entry.halt) el.className = "halt";
postEl.appendChild(el);
els.set(entry, el);
playBiosTick(); // whisper-level teletype tick per printed line
if (entry.status === null && !bootDone && !failed) {
// Honest mode: show the stage label and hold while it's really
// in flight, cursor blinking via CSS.
el.textContent = lineText(entry);
while (entry.status === null && !store().bootDone && !store().bootFailed) {
await sleep(60);
el.textContent = lineText(entry); // live [n/m] counter
}
await sleep(90);
el.textContent = lineText(entry);
} else if (entry.raw || entry.status === null) {
// Header / note lines: quick, no dotted leader to animate.
el.textContent = lineText(entry);
await sleep(20 + 60 * rand());
} else {
// Finished check: bursty POST pacing. Most lines snap in nearly
// instantly; the occasional one stalls on a "slow check" - and
// on a stall the dotted leader types out one dot at a time
// before the status lands.
const r = rand();
const stall = r < 0.75 ? 20 * rand() : 150 + 250 * rand();
if (stall < 45) {
el.textContent = lineText(entry);
await sleep(stall);
} else {
const prefix = `${entry.label} `;
const nDots = Math.max(26 - prefix.length, 3);
el.textContent = prefix;
const per = stall / nDots;
for (let d = 0; d < nDots; d++) {
await sleep(per);
el.textContent += ".";
}
await sleep(40);
el.textContent = lineText(entry);
}
}
} else if (bootDone) {
break;
} else {
// Waiting for the next real stage. On a failed boot this parks the
// console forever: everything queued (FAIL line, error detail,
// SYSTEM HALTED) has been printed and nothing more will come.
await sleep(failed ? 500 : 60);
}
}
const ready = document.createElement("div");
ready.textContent = "READY.";
postEl.appendChild(ready);
playBiosTick();
await sleep(500);
setOff(true);
// Wait out the 0.45 s opacity transition BEFORE cueing the draw-in:
// starting it under the fading overlay hides the first (and busiest)
// part of the animation and only the tail end shows.
await sleep(500);
setVisible(false);
useGame.setState({ biosVisible: false });
// Cue the world draw-in + duck scan-up on a fully black screen.
gameApi.startEntrance?.();
}
return (
<Box
sx={{
position: "fixed",
inset: 0,
display: visible ? "flex" : "none",
// POST readout sits bottom-left like a real BIOS, not centered
alignItems: "flex-end",
justifyContent: "flex-start",
p: "2.2rem 2.4rem",
background: INK,
zIndex: 20,
pointerEvents: "none",
opacity: off ? 0 : 1,
transition: "opacity 0.45s ease",
}}
>
<Box
ref={postRef}
sx={{
minWidth: "min(380px, 84vw)",
// Grow upward from the bottom-left anchor; when the log outgrows
// the viewport, clip the OLDEST lines at the top so the newest
// line + cursor stay visible.
maxHeight: "calc(100vh - 4.4rem)",
display: "flex",
flexDirection: "column",
justifyContent: "flex-end",
overflow: "hidden",
// Raw 90s POST look: small, tight, unsmoothed monospace.
fontFamily: MONO,
fontSize: "12px",
fontWeight: 400,
lineHeight: 1.55,
letterSpacing: 0,
textTransform: "uppercase",
textAlign: "left",
// Robot orange (classic duck's BRIGHT_ORANGE, #ff7a2f in sRGB)
color: "rgba(255, 122, 47, 0.92)",
whiteSpace: "pre-wrap",
overflowWrap: "break-word",
"& > div:first-of-type": {
color: "rgba(255, 255, 255, 0.85)",
marginBottom: "0.55em",
},
// Blinking block cursor at the end of the newest line
"& > div:last-of-type::after": {
content: '"\\2588"',
marginLeft: "0.15em",
animation: `${postBlink} 1s steps(1) infinite`,
},
// Fatal boot failure: SYSTEM HALTED blinks like an old POST fault
"& > div.halt": {
color: "rgba(255, 82, 47, 0.95)",
animation: `${postBlink} 1s steps(1) infinite`,
},
}}
/>
</Box>
);
}
+635
View File
@@ -0,0 +1,635 @@
// 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 { keyframes } from "@mui/material/styles";
import { useGame, gameApi } from "../store.js";
import { VARIANT_LABELS, VARIANT_SWATCH_HEX } from "../game/variants.js";
import { uiClick, isMuted, setMuted } from "../game/audio.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.
// Monospace keeps the width stable mid-scramble.
const SCRAMBLE_GLYPHS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&*<>/=+";
function useScramble(target) {
const [text, setText] = useState(target.toUpperCase());
const timer = useRef(null);
const shown = useRef(target.toUpperCase());
useEffect(() => {
const t = target.toUpperCase();
if (shown.current === t) return;
shown.current = t;
if (timer.current) clearInterval(timer.current);
const n = t.length;
const DUR = 450; // ms until the last letter locks
const rnd = () => SCRAMBLE_GLYPHS[(Math.random() * SCRAMBLE_GLYPHS.length) | 0];
const t0 = performance.now();
timer.current = setInterval(() => {
const k = Math.floor(((performance.now() - t0) / DUR) * n);
if (k >= n) {
clearInterval(timer.current);
timer.current = null;
setText(t);
return;
}
let out = t.slice(0, k);
for (let i = k; i < n; i++) out += rnd();
setText(out);
}, 40);
return () => timer.current && clearInterval(timer.current);
}, [target]);
return text;
}
const recBlink = keyframes`
0%, 58% { opacity: 1; }
59%, 100% { opacity: 0.12; }
`;
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 (
<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>
);
}
// Speaker icon in the same square-stroke language as the back arrow:
// body + cone always, waves when live, a hard ink cross when muted.
function SpeakerIcon({ muted }) {
return (
<Box
component="svg"
viewBox="0 0 24 24"
aria-hidden
fill="none"
stroke="currentColor"
strokeWidth={2.25}
strokeLinecap="square"
strokeLinejoin="miter"
sx={{ width: "1.05em", height: "1.05em", display: "block", flex: "none" }}
>
<path d="M4 9h4l5-4v14l-5-4H4z" />
{muted ? (
<path d="M16 9l6 6M22 9l-6 6" />
) : (
<>
<path d="M16 9.5a3.5 3.5 0 0 1 0 5" />
<path d="M18.5 7a7 7 0 0 1 0 10" />
</>
)}
</Box>
);
}
function BackArrowIcon() {
return (
<Box
component="svg"
viewBox="0 0 24 24"
aria-hidden
fill="none"
stroke="currentColor"
strokeWidth={2.25}
strokeLinecap="square"
strokeLinejoin="miter"
sx={{ width: "0.95em", height: "0.95em", display: "block", flex: "none" }}
>
<path d="M20 12H6" />
<path d="M12 5l-7 7 7 7" />
</Box>
);
}
const hudHitSx = {
appearance: "none",
display: "inline-flex",
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="button"
type="button"
onClick={() => { uiClick(); useGame.setState({ menuOpen: true }); }}
sx={{
...hudHitSx,
"&:hover": {
color: ORANGE,
background: "rgba(255, 122, 47, 0.12)",
},
"&:active": { filter: "brightness(0.92)" },
}}
>
<BackArrowIcon /> Back
</Box>
</HudPlate>
);
}
export const SHOP_URL = "https://store.pollen-robotics.com/collections/microduck";
// Exported: the title/pause overlay renders the same plate in the same
// spot, so the pause fade reads as the button staying put, not two
// different buttons swapping.
export function PreorderButton({ sx }) {
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, ...sx }}
>
<Box
component="a"
href={SHOP_URL}
target="_blank"
rel="noopener noreferrer"
onClick={() => uiClick()}
sx={{
...hudHitSx,
background: ORANGE,
color: COMIC_INK,
"&:hover": { filter: "brightness(1.07)" },
"&:active": { filter: "brightness(0.92)" },
}}
>
{text}
</Box>
</HudPlate>
);
}
function Quickbar() {
const variant = useGame((s) => s.variant);
const locoWant = useGame((s) => s.locoWant);
return (
<Box
sx={{
position: "fixed",
bottom: "1.25rem",
left: "1.5rem",
zIndex: 10,
display: "flex",
flexWrap: "wrap",
alignItems: "flex-end",
gap: "0.85rem",
maxWidth: "calc(100vw - 14.5rem)",
}}
>
<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={() => { uiClick(); 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={() => { uiClick(); gameApi.requestLoco?.(name); }}
sx={{
...hudHitSx,
px: "1.05rem",
background: selected ? ORANGE : "transparent",
color: selected ? COMIC_INK : "rgba(250, 248, 242, 0.72)",
"&:hover": {
color: selected ? COMIC_INK : CREAM,
background: selected ? ORANGE : "rgba(255, 122, 47, 0.12)",
},
"&:active": { filter: "brightness(0.92)" },
}}
>
{label}
</Box>
);
})}
</Box>
</HudPlate>
<PolicyChip />
{/* Sound is fully disabled for now (SOUND_DISABLED in audio.js) -
the mute toggle comes back with the finished sound design. */}
{/* <SoundToggle /> */}
</Box>
);
}
// Active community move chip: rides the quickbar row in the same panel
// language. "PLAYING: <prompt or name> by <owner>" (Academy moves carry
// their prompt and author in manifest.academy), a hint on the key that
// plays a trick / script, and an X that swaps the official slot back in
// (gameApi.clearCustomPolicy).
function PolicyChip() {
const cp = useGame((s) => s.customPolicy);
if (cp?.status !== "active") return null;
const title = cp.title || cp.name;
const by = cp.author ? ` by ${cp.author}` : "";
const hint = cp.slot === "trick" || cp.slot === "script" || cp.slot === "sitstand" ? " \u00b7 R" : "";
return (
<HudPlate caption="Playing" captionFill="orange">
<Box sx={{ display: "inline-flex", alignItems: "stretch", height: "100%" }}>
<Box
sx={{
...hudHitSx,
px: "0.85rem",
cursor: "default",
color: ORANGE,
maxWidth: "22rem",
overflow: "hidden",
textOverflow: "ellipsis",
display: "inline-block",
lineHeight: `${CELL_H}px`,
}}
title={`${cp.ref}${cp.kind ? ` (${cp.kind})` : ""}`}
>
{`${title}${by}${hint}`}
</Box>
<Box
component="button"
type="button"
aria-label={`Unload move ${cp.name}`}
onClick={() => { uiClick(); gameApi.clearCustomPolicy?.(); }}
sx={{
...hudHitSx,
px: "0.6rem",
color: "rgba(250, 248, 242, 0.72)",
"&:hover": {
color: ORANGE,
background: "rgba(255, 122, 47, 0.12)",
},
"&:active": { filter: "brightness(0.92)" },
}}
>
{"\u2715"}
</Box>
</Box>
</HudPlate>
);
}
// Mute / unmute panel: same cartouche language as the other groups. The
// toggle ramps audio.js's master gain (~50 ms) and persists; unmuting
// plays the HUD click as confirmation (muting stays silent, obviously).
function SoundToggle() {
const [muted, setMutedState] = useState(isMuted);
const toggle = () => {
const next = !muted;
setMuted(next);
setMutedState(next);
if (!next) uiClick();
};
return (
<HudPlate caption="Sound">
<Box
component="button"
type="button"
aria-label={muted ? "Unmute sound" : "Mute sound"}
aria-pressed={muted}
onClick={toggle}
sx={{
...hudHitSx,
px: "0.75rem",
color: muted ? "rgba(250, 248, 242, 0.5)" : CREAM,
"&:hover": {
color: muted ? CREAM : ORANGE,
background: "rgba(255, 122, 47, 0.12)",
},
"&:active": { filter: "brightness(0.92)" },
}}
>
<SpeakerIcon muted={muted} />
</Box>
</HudPlate>
);
}
function Telemetry() {
const t = useGame((s) => s.telemetry);
const odo = t.odo < 1000 ? `${t.odo.toFixed(1)}M` : `${(t.odo / 1000).toFixed(2)}KM`;
const lines = [];
if (t.peers) lines.push(`${t.peers + 1} ONLINE`);
lines.push(`${t.speed.toFixed(2)}M/S \u00b7 ODO ${odo}`);
lines.push(`FPS ${t.fps} \u00b7 CTRL ${t.ctrlHz}HZ`);
return (
<Box
sx={{
position: "fixed",
bottom: "1.25rem",
right: "1.5rem",
zIndex: 10,
pointerEvents: "none",
fontFamily: MONO,
fontSize: "0.62rem",
letterSpacing: "0.14em",
textTransform: "uppercase",
color: "rgba(255, 255, 255, 0.35)",
fontVariantNumeric: "tabular-nums",
textShadow: "0 0 6px rgba(255, 255, 255, 0.15)",
whiteSpace: "pre-line",
textAlign: "right",
lineHeight: 1.8,
}}
>
{lines.join("\n")}
</Box>
);
}
function OsdLoad() {
const rollersLoading = useGame((s) => s.rollersLoading);
const policyLoading = useGame((s) => s.customPolicy?.status === "loading");
const lines = [];
if (rollersLoading) lines.push("LOADING ROLLERS");
if (policyLoading) lines.push("LOADING MOVE");
if (!lines.length) return null;
return (
<Box
sx={{
position: "fixed",
top: "5.2rem",
right: "1.5rem",
zIndex: 10,
fontFamily: MONO,
fontSize: "0.68rem",
letterSpacing: "0.14em",
color: ORANGE,
textShadow: "0 0 8px rgba(255, 122, 47, 0.4)",
textAlign: "right",
lineHeight: 1.9,
}}
>
{lines.map((l) => (
<Box key={l}>
{l}
<Box
component="span"
sx={{ display: "inline-block", ml: "0.15em", animation: `${recBlink} 0.8s steps(1) infinite` }}
>
{"\u2588"}
</Box>
</Box>
))}
</Box>
);
}
// Toast-style OSD line for policy failures: a load error or a watchdog
// revert paints below the loading line for a few seconds, then clears the
// store slot (the official walker is already back by then).
function PolicyToast() {
const cp = useGame((s) => s.customPolicy);
const isError = cp?.status === "error";
useEffect(() => {
if (!isError) return;
const t = setTimeout(() => {
if (useGame.getState().customPolicy === cp) {
useGame.setState({ customPolicy: null });
}
}, 9000);
return () => clearTimeout(t);
}, [cp, isError]);
if (!isError) return null;
const msg = cp.revertReason
? `MOVE REVERTED \u00b7 ${cp.revertReason}`
: `MOVE LOAD FAILED \u00b7 ${cp.error ?? "unknown error"}`;
return (
<Box
role="alert"
sx={{
position: "fixed",
top: "7.4rem",
right: "1.5rem",
zIndex: 10,
maxWidth: "24rem",
fontFamily: MONO,
fontSize: "0.66rem",
letterSpacing: "0.1em",
textTransform: "uppercase",
textAlign: "right",
lineHeight: 1.7,
color: "#ff4b3a",
textShadow: "0 0 8px rgba(255, 75, 58, 0.45)",
}}
>
{msg}
</Box>
);
}
export default function Hud() {
const entered = useGame((s) => s.entered);
const menuOpen = useGame((s) => s.menuOpen);
const touchMode = useGame((s) => s.touchMode);
if (!entered || menuOpen) return null;
return (
<>
<BackButton />
<PreorderButton />
{!touchMode && (
<>
<Quickbar />
<Telemetry />
<OsdLoad />
<PolicyToast />
</>
)}
</>
);
}
+350
View File
@@ -0,0 +1,350 @@
// Title-menu duck stage: the simulated twin, sitting on the title screen
// like the vitrine landing's colour module - head aims at the pointer
// (idle glances at the camera when it's quiet), click/tap quacks. No
// physics, no policies: just the shared rig posed and micro-animated.
//
// Why a separate rig instead of showing the game scene: the boot
// dramaturgy keeps the in-game duck hidden until the BIOS readout cues
// the entrance scan-up, so the title screen needs its own duck. Geometry
// is free anyway - duck.js caches the GLB module-wide, so this rig and
// the game's share the same buffers.
//
// The stage is a lazy module singleton: built once on first open, then
// re-attached on every pause. The rAF loop only runs while attached.
import { useEffect, useRef } from "react";
import Box from "@mui/material/Box";
import * as THREE from "three";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
import {
loadKinematics, buildRig, setJoint, setJawOpen, applyPose,
SITTING_POSE, groundFullBody, MODEL_DIR,
} from "../game/duck.js";
import { VARIANTS, DEFAULT_VARIANT, materialHookFor, applyVariant } from "../game/variants.js";
import { createWireframeFx } from "../game/fx/fx-wireframe.js";
import { playUrl } from "../game/audio.js";
import { signed } from "../game/signed.js";
import { useGame } from "../store.js";
// Aim calibration, verbatim from the vitrine's duck3d/scene.js: positive
// head_pitch is head-down on the mjlab model, so screen-up subtracts.
const SIGN_YAW = 1;
const SIGN_PITCH = -1;
const SPREAD_YAW = 0.55; // rad of head yaw across half the stage width
const SPREAD_PITCH = 0.32; // rad of head pitch across half the stage height
// Quack envelope: openness eases toward a target instead of replaying a
// fixed curve, so clicking mid-quack never snaps the jaw backwards.
const QUACK_HOLD_S = 0.3;
const QUACK_ATTACK_TAU = 0.04;
const QUACK_RELEASE_TAU = 0.09;
// The vitrine's aim framing, loosened for the menu column: the duck fills
// ~2/3 of the frame height instead of edge to edge. The look height is
// tuned WITH the zoom to put the feet (y=0) ~18% above the frame's bottom
// edge - floating well clear of the shortcut strip.
const CAM_POS = [0.28, 0.2, 0.43];
const CAM_LOOK = [0, 0.122, 0];
const CAM_ZOOM = 0.78;
const FOV_DEG = 32;
// Same voice banks as the game's quack (game.js VOICE_BANK).
const VOICE_BANK = { classic: "duck1", charcoal: "duck2", purple: "duck3", blue: "duck4" };
const CHIRP_TAKES = "abcdefghijkl";
const clamp = (x, a, b) => Math.min(b, Math.max(a, x));
const rand = (a, b) => a + Math.random() * (b - a);
let stagePromise = null;
let liveStage = null;
let stageReady = false;
function getStage() {
if (!stagePromise) {
stagePromise = buildStage()
.then((s) => {
liveStage = s;
stageReady = true;
return s;
})
.catch((e) => {
// Still flip ready: the title screen must not spin forever when
// WebGL / assets fail - it just shows without the duck.
stageReady = true;
throw e;
});
}
return stagePromise;
}
// Title-screen loading gate: the menu holds a spinner until the stage's
// assets are in (kinematics + GLB + rig build), so the content reveal
// and the duck's entrance scan cue together instead of the duck popping
// into an already-settled screen.
export const preloadMenuDuck = () => getStage();
export const isMenuDuckReady = () => stageReady;
async function buildStage() {
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(FOV_DEG, 1, 0.05, 20);
camera.position.set(
...CAM_LOOK.map((l, i) => l + (CAM_POS[i] - l) / CAM_ZOOM),
);
camera.lookAt(...CAM_LOOK);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setClearColor(0x000000, 0);
renderer.setPixelRatio(Math.min(2, window.devicePixelRatio));
// Same output pipeline the variant palette was calibrated against.
renderer.toneMapping = THREE.ACESFilmicToneMapping;
const el = renderer.domElement;
el.style.position = "absolute";
el.style.inset = "0";
el.style.width = "100%";
el.style.height = "100%";
// Anti-flicker: invisible until the first frame has been presented.
el.style.opacity = "0";
el.style.transition = "opacity 0.45s ease";
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment()).texture;
scene.environmentIntensity = 0.25;
// Vitrine light rig: strong white key, soft fill, warm orange rim.
scene.add(new THREE.AmbientLight(0xffffff, 0.45));
const key = new THREE.DirectionalLight(0xffffff, 1.25);
key.position.set(2, 4, 2);
scene.add(key);
const fill = new THREE.DirectionalLight(0xffffff, 0.4);
fill.position.set(-2, 2, 1.5);
scene.add(fill);
const rim = new THREE.DirectionalLight(0xffb366, 0.7);
rim.position.set(0, 3, -2);
scene.add(rim);
const k = await loadKinematics(`${MODEL_DIR}/kinematics.json`);
let appliedVariant = useGame.getState().variant ?? DEFAULT_VARIANT;
if (!VARIANTS[appliedVariant]) appliedVariant = DEFAULT_VARIANT;
const rig = await buildRig(k, {
materialForMesh: materialHookFor(VARIANTS[appliedVariant]),
});
// Face the camera: MJCF forward is +X; the placer yaw turns it to +Z.
rig.placer.rotation.y = -Math.PI / 2;
scene.add(rig.placer);
applyPose(rig, SITTING_POSE);
groundFullBody(rig);
// Vitrine-style entrance: the duck materializes with the wireframe
// scan-up the first time the menu shows. Hidden (clip at floor level)
// until the stage is attached, then start() cues the scan; once done
// the fx restores the real materials and is dropped for good - pause
// reopens show the solid duck immediately.
//
// Shader pre-warm: the scan cycles through three material states, each
// compiling its GPU program on the frame it first renders - the plain
// PBR originals (restored when the scan finishes), the per-mesh clip
// clones (unique customProgramCacheKey each, so ~30 separate PBR
// compiles), and the wireframe ShaderMaterial (only drawn once the
// scan is running). Left alone, those compiles land mid-animation as
// driver-timed freezes. The canvas is still detached and invisible
// here, so render each state once now: solid first, then a mid-scan
// frame (wires on, clones clipping), then rewind to hidden.
renderer.render(scene, camera);
let entranceFx = createWireframeFx();
entranceFx.init({ THREE, scene, root: rig.placer, camera, renderer, hidden: true });
entranceFx.setProgress(0.5);
renderer.render(scene, camera);
entranceFx.setProgress(0);
let entranceStarted = false;
const headPivot = rig.joints.get("head_yaw").body;
const headWorld = new THREE.Vector3();
const camDir = new THREE.Vector3();
// ── Pointer → aim state ───────────────────────────────────────────────
const ndc = new THREE.Vector2(0, 0);
let mountEl = null;
let lastT = 0;
let lastMouseT = -Infinity;
let hasFocus = document.hasFocus();
let mouseInside = true;
let az = 0, el2 = 0;
let attention = 0;
const o1 = rand(0, 6.3), o2 = rand(0, 6.3);
let quackHoldUntil = -Infinity;
let quackOpen = 0;
const onPointerMove = (e) => {
if (!mountEl) return;
const r = mountEl.getBoundingClientRect();
if (!r.width || !r.height) return;
ndc.x = clamp(((e.clientX - r.left) / r.width) * 2 - 1, -2, 2);
ndc.y = clamp(-(((e.clientY - r.top) / r.height) * 2 - 1), -2, 2);
lastMouseT = lastT;
mouseInside = true;
};
const onBlur = () => { hasFocus = false; };
const onFocus = () => { hasFocus = true; };
const onMouseLeave = () => { mouseInside = false; };
const onMouseEnter = () => { mouseInside = true; };
// Any click on the title screen quacks, not just the stage box: the
// overlay owns the whole viewport while the menu is up, and the quack
// never swallows the event (buttons underneath still do their thing).
const onPointerDown = () => quack();
function quack() {
quackHoldUntil = lastT + QUACK_HOLD_S;
const bank = VOICE_BANK[appliedVariant] ?? "duck1";
const take = CHIRP_TAKES[(Math.random() * CHIRP_TAKES.length) | 0];
// The click that lands here is a user gesture, so this also unlocks
// the shared AudioContext on the very first interaction.
playUrl(signed(`./assets/voices/${bank}/chirp_${take}.wav`), { gain: 0.7 });
}
function step(dt, t) {
lastT = t;
headPivot.getWorldPosition(headWorld);
camDir.copy(camera.position).sub(headWorld);
const azCam = Math.atan2(camDir.x, camDir.z);
const elCam = Math.atan2(camDir.y, Math.hypot(camDir.x, camDir.z));
// Attention 0..1: eases toward 1 while the page is focused, the
// pointer is around and moved recently; lazy camera glances otherwise.
const engaged = hasFocus && mouseInside && t - lastMouseT < 3.0;
attention += ((engaged ? 1 : 0) - attention) * (1 - Math.exp(-dt / 0.3));
const azAim = azCam + ndc.x * SPREAD_YAW;
const elAim = elCam * 0.5 + ndc.y * SPREAD_PITCH;
const azIdle = azCam + 0.45 * Math.sin(0.21 * t + o1) * Math.sin(0.09 * t + o2) * 2;
const elIdle = elCam * 0.5 + 0.1 * Math.sin(0.4 * t + o2);
const azT = azIdle + (azAim - azIdle) * attention;
const elT = elIdle + (elAim - elIdle) * attention;
const kSmooth = 1 - Math.exp(-dt * (2.5 + 7.5 * attention));
az += (azT - az) * kSmooth;
el2 += (elT - el2) * kSmooth;
const breathe = Math.sin(t * 1.4) * 0.025;
setJoint(rig, "neck_pitch", SITTING_POSE.neck_pitch + breathe);
setJoint(rig, "head_yaw", SIGN_YAW * az);
setJoint(rig, "head_pitch", SITTING_POSE.head_pitch + SIGN_PITCH * el2);
setJoint(rig, "head_roll", 0.3 * SIGN_YAW * (az - azCam));
const quackTarget = t < quackHoldUntil ? 1 : 0;
const tau = quackTarget > quackOpen ? QUACK_ATTACK_TAU : QUACK_RELEASE_TAU;
quackOpen += (quackTarget - quackOpen) * (1 - Math.exp(-dt / tau));
setJawOpen(rig, quackOpen);
if (entranceFx) {
if (!entranceStarted) {
entranceFx.start();
entranceStarted = true;
}
entranceFx.update(dt);
if (entranceFx.isDone()) {
entranceFx.dispose();
entranceFx = null;
}
}
// Colourway follows the in-game duck (store.variant), fading live.
// Deferred while the entrance scan holds its clip-material clones:
// an applyVariant mid-scan would repaint clones that get thrown away
// on restore. The sync lands on the first frame after the scan.
const v = useGame.getState().variant;
if (!entranceFx && v !== appliedVariant && VARIANTS[v]) {
appliedVariant = v;
applyVariant(rig, v);
}
renderer.render(scene, camera);
if (el.style.opacity === "0") el.style.opacity = "1";
}
// ── Attach / detach (rAF only runs while a mount hosts the canvas) ────
let raf = 0;
let prevNow = 0;
const loop = (now) => {
raf = requestAnimationFrame(loop);
const dt = Math.min((now - prevNow) / 1000, 0.05);
prevNow = now;
step(dt, now / 1000);
};
function resize() {
if (!mountEl) return;
const w = mountEl.clientWidth;
const h = mountEl.clientHeight;
if (!w || !h) return;
camera.aspect = w / h;
camera.updateProjectionMatrix();
renderer.setSize(w, h);
}
const resizeObserver = new ResizeObserver(resize);
function attach(mount) {
if (!mount || mountEl === mount) return;
detach();
mountEl = mount;
mount.appendChild(el);
resizeObserver.observe(mount);
resize();
window.addEventListener("pointermove", onPointerMove);
window.addEventListener("pointerdown", onPointerDown);
window.addEventListener("blur", onBlur);
window.addEventListener("focus", onFocus);
document.addEventListener("mouseleave", onMouseLeave);
document.addEventListener("mouseenter", onMouseEnter);
prevNow = performance.now();
raf = requestAnimationFrame(loop);
}
function detach() {
if (!mountEl) return;
cancelAnimationFrame(raf);
resizeObserver.disconnect();
window.removeEventListener("pointermove", onPointerMove);
window.removeEventListener("pointerdown", onPointerDown);
window.removeEventListener("blur", onBlur);
window.removeEventListener("focus", onFocus);
document.removeEventListener("mouseleave", onMouseLeave);
document.removeEventListener("mouseenter", onMouseEnter);
el.remove();
mountEl = null;
}
const stage = { attach, detach, quack, step };
// Deterministic hook for automated verification, same spirit as the
// game's window.rl: rAF pauses in background tabs, so tests drive
// frames by hand.
window.__menuDuck = stage;
return stage;
}
export default function MenuDuck({ sx }) {
const hostRef = useRef(null);
useEffect(() => {
let disposed = false;
getStage()
.then((stage) => {
if (disposed) return;
if (hostRef.current) stage.attach(hostRef.current);
})
.catch((e) => console.warn("menu duck disabled:", e));
return () => {
disposed = true;
liveStage?.detach();
};
}, []);
return (
<Box
ref={hostRef}
aria-hidden
sx={{
position: "relative",
touchAction: "manipulation",
userSelect: "none",
...sx,
}}
/>
);
}
+111
View File
@@ -0,0 +1,111 @@
// Full-viewport decorative layers over the 3D scene: halftone dots and the
// CRT/old-TV treatment (scanlines + boiling static + vignette). Stacked at
// z 2-5: above the canvas, below the HUD (z 10), the BIOS screen (z 20)
// and the title overlay (z 30) - the interface stays crisp and only the
// scene gets the old-TV treatment.
//
// Performance: the only animation is a transform-only jitter on the noise
// layer, so everything stays on the compositor and never repaints the
// WebGL canvas underneath.
import Box from "@mui/material/Box";
import { keyframes } from "@mui/material/styles";
const crtNoise = keyframes`
0% { transform: translate(0, 0); }
25% { transform: translate(-45px, 30px); }
50% { transform: translate(25px, -55px); }
75% { transform: translate(-30px, -15px); }
100% { transform: translate(0, 0); }
`;
const NOISE_SVG =
"url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix type='matrix' values='0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0.7 0'/%3E%3C/filter%3E%3Crect width='160' height='160' filter='url(%23n)'/%3E%3C/svg%3E\")";
export function Halftone() {
return (
<Box
aria-hidden
sx={{
position: "fixed",
inset: 0,
zIndex: 2,
pointerEvents: "none",
backgroundImage:
"radial-gradient(rgba(255, 255, 255, 0.05) 1px, transparent 1.5px)",
backgroundSize: "21px 21px",
maskImage: "linear-gradient(to bottom, transparent 30%, black 100%)",
}}
/>
);
}
export function CrtOverlay() {
const scanlineOpacity = 0.13;
const scanlinePitch = "3px";
const noiseOpacity = 0.045;
const vignetteOpacity = 0.42;
return (
<Box
aria-hidden
sx={{
position: "fixed",
inset: 0,
zIndex: 5,
pointerEvents: "none",
overflow: "hidden",
}}
>
{/* SCANLINES: one thin dark line every pitch, plus a very faint
vertical RGB fringe (aperture-grille tint). Static. */}
<Box
sx={{
position: "absolute",
inset: 0,
opacity: scanlineOpacity,
background: `repeating-linear-gradient(
to bottom,
rgba(0, 0, 0, 0.55) 0,
rgba(0, 0, 0, 0.55) 1px,
transparent 1px,
transparent ${scanlinePitch}
),
repeating-linear-gradient(
to right,
rgba(255, 70, 60, 0.05) 0,
rgba(255, 70, 60, 0.05) 1px,
rgba(70, 255, 90, 0.035) 1px,
rgba(70, 255, 90, 0.035) 2px,
rgba(70, 110, 255, 0.05) 2px,
rgba(70, 110, 255, 0.05) 3px
)`,
}}
/>
{/* NOISE: tiled SVG turbulence, jittered between four offsets with
steps() so the grain "boils" like broadcast static. */}
<Box
sx={{
position: "absolute",
inset: "-80px",
backgroundImage: NOISE_SVG,
backgroundSize: "160px 160px",
opacity: noiseOpacity,
animation: `${crtNoise} 0.5s steps(1) infinite`,
willChange: "transform",
"@media (prefers-reduced-motion: reduce)": { animation: "none" },
}}
/>
{/* VIGNETTE: gently darkened corners, like curved CRT glass. */}
<Box
sx={{
position: "absolute",
inset: 0,
background: `radial-gradient(
115% 90% at 50% 50%,
transparent 62%,
rgba(0, 0, 0, ${vignetteOpacity}) 100%
)`,
}}
/>
</Box>
);
}
+368
View File
@@ -0,0 +1,368 @@
// Soundboard experiment page (?soundboard=1): trigger and A/B-compare every
// game sound - the CURRENT runtime implementation (straight from audio.js,
// exact same code paths, non-spatial) against a ZzFX-synthesized candidate.
// Throwaway experiment: plain CSS, no game boot, additive only.
import { useEffect, useRef, useState } from "react";
import {
audioCtx, busNode, preloadSfx, playSfx, playUrl, uiClick,
startAmbient, setRumble, playEntranceSweep, playPropSweep, playLineBlip,
playBiosBeep, playBiosTick, playConfirmBloop,
} from "../game/audio.js";
import { signed } from "../game/signed.js";
import { zzfx } from "../game/vendor/zzfx.js";
// Bus levels mirrored from audio.js BUS_LEVELS; the master volume slider
// rescales the (module-private) bus gains through busNode(), which is safe
// here because the game never mounts on this page.
const BUS_DEFAULTS = { ambient: 1, sfx: 0.9, voice: 1 };
// ZzFX candidate presets. Parameter order:
// [volume, randomness, frequency, attack, sustain, release, shape, shapeCurve,
// slide, deltaSlide, pitchJump, pitchJumpTime, repeatTime, noise, modulation,
// bitCrush, delay, sustainVolume, decay, tremolo, filter]
// Shapes: 0 sin, 1 triangle, 2 saw, 3 tan, 4 noise, 5 square (duty=shapeCurve/2).
export const ZZFX_PRESETS = {
// Soft noise-burst tap, quick pitch drop, mirrors the Kenney step takes.
footstepTap: [1.4, .3, 120, .001, .01, .05, 4, 1.9, -12, , , , , 1.3, , .1, , .5, .02],
// Duller, breathier alternative take (more noise, lower).
footstepSoft: [1.1, .4, 85, .001, .008, .04, 4, 2.2, -8, , , , , 2, , .2, , .45, .015],
// Round sine drop with a fast slide: hollow bouncing-ball body.
ballThump: [2, .15, 210, .002, .02, .16, 0, 2.4, -30, , , , , .3, , , , .8, .08],
// Same family an octave-ish down, more noise: duller body bump.
bodyBump: [1.7, .2, 90, .002, .03, .19, 0, 2.9, -15, , , , , 1, , .3, , .7, .11],
// Tiny triangle tick around 1.1 kHz.
uiClick: [.5, .2, 1100, .001, .005, .02, 1, 1.4, , , , , , , , , , .6, .01],
// Two rising square notes C5 -> G5 (pitchJump +261 Hz at 70 ms).
confirmBloop: [.7, 0, 523, .005, .12, .08, 5, 1, , , 261, .07, , , , , , .8, .02],
// Classic single POST beep, steady 940 Hz square.
biosBeep: [.4, 0, 940, .004, .1, .05, 5, 1, , , , , , , , , , .9, .01],
// Whisper teletype tick, high square with slight randomness.
biosTick: [.25, .2, 1850, .001, .004, .014, 5, 1, , , , , , , , , , .5, .005],
// Per-line scan chirp ~1.9 kHz triangle; randomness spreads the flurry.
scanBlip: [.35, .25, 1900, .001, .01, .04, 1, 1, , , , , , , , , , .6, .01],
// Rising saw sweep + noise shimmer + long release: sweep approximation.
entranceSweep: [1, 0, 150, .05, .5, .3, 2, 1, 11, .4, , , , .35, , .15, , .8, .2],
};
// Resume-then-run wrapper: every trigger lands in a user gesture, so a
// suspended context gets one resume attempt before the sound fires (the
// runtime helpers silently no-op on a suspended context).
async function armed(fn) {
const c = audioCtx();
if (c.state === "suspended") {
try { await c.resume(); } catch { return; }
}
fn();
}
// ZzFX candidates land on the sfx bus: same master gain as the runtime.
const playZ = (params) => zzfx(audioCtx(), busNode("sfx"), ...params);
const CHIRP_TAKES = "abcdefghijkl";
export default function Soundboard() {
const [vol, setVol] = useState(1);
const [ambientOn, setAmbientOn] = useState(false);
const [rumbleOn, setRumbleOn] = useState(false);
const [wheeeOn, setWheeeOn] = useState(false);
const wheeeRide = useRef(null);
const chirpIdx = useRef(0);
useEffect(() => {
audioCtx();
preloadSfx();
}, []);
// Master volume: rescale all three bus gains (ambient stays at 0 while
// its loop toggle is off - startAmbient() has no runtime stop hook, so
// the toggle gates the whole ambient bus instead).
useEffect(() => {
audioCtx();
for (const [name, base] of Object.entries(BUS_DEFAULTS)) {
const scale = name === "ambient" && !ambientOn ? 0 : vol;
busNode(name).gain.value = base * scale;
}
}, [vol, ambientOn]);
const toggleAmbient = () => armed(() => {
if (!ambientOn) startAmbient();
setAmbientOn((v) => !v);
});
const toggleRumble = () => armed(() => {
setRumble(rumbleOn ? 0 : 0.7);
setRumbleOn((v) => !v);
});
// Wheee reference loop: minimal version of the game's ride (loop take a,
// voice bus, short fades). Token in the ref guards the decode race.
const toggleWheee = () => armed(async () => {
const c = audioCtx();
const ride = wheeeRide.current;
if (ride) {
wheeeRide.current = null;
setWheeeOn(false);
if (ride.src) {
ride.gain.gain.setTargetAtTime(0, c.currentTime, 0.05);
try { ride.src.stop(c.currentTime + 0.3); } catch { /* ended */ }
}
return;
}
const next = {};
wheeeRide.current = next;
setWheeeOn(true);
let buf;
try {
const res = await fetch(signed("./assets/voices/duck1/wheee_loop_a.wav"));
buf = await c.decodeAudioData(await res.arrayBuffer());
} catch {
if (wheeeRide.current === next) { wheeeRide.current = null; setWheeeOn(false); }
return;
}
if (wheeeRide.current !== next) return; // toggled off during decode
const gain = c.createGain();
gain.connect(busNode("voice"));
const t0 = c.currentTime + 0.02;
gain.gain.setValueAtTime(0, t0);
gain.gain.linearRampToValueAtTime(0.7, t0 + 0.02);
const src = c.createBufferSource();
src.buffer = buf;
src.loop = true;
src.connect(gain);
src.start(t0);
Object.assign(next, { src, gain });
});
const playQuack = () => {
const take = CHIRP_TAKES[chirpIdx.current++ % CHIRP_TAKES.length];
playUrl(signed(`./assets/voices/duck1/chirp_${take}.wav`), { gain: 0.7 });
};
// One-shot rows: name, category, note, current trigger, zzfx candidates.
const rows = [
{
name: "Footstep", cat: "sampled", note: "step_a-e, random take, in-game gain/rate spread",
current: () => playSfx("step", { gain: 0.2, rate: 0.9 + Math.random() * 0.25 }),
zz: [["tap", ZZFX_PRESETS.footstepTap], ["soft", ZZFX_PRESETS.footstepSoft]],
},
{
name: "Ball thump", cat: "sampled", note: "thump_a-c, mid-strength kick",
current: () => playSfx("thump", { gain: 0.34, rate: 1.05 + Math.random() * 0.08 }),
zz: [["thump", ZZFX_PRESETS.ballThump]],
},
{
name: "Body bump", cat: "sampled", note: "thump takes pitched down to ~0.57",
current: () => playSfx("thump", { gain: 0.27, rate: 0.57 + Math.random() * 0.06 }),
zz: [["bump", ZZFX_PRESETS.bodyBump]],
},
{
name: "UI click", cat: "sampled", note: "click_a/b via uiClick()",
current: () => uiClick(),
zz: [["click", ZZFX_PRESETS.uiClick]],
},
{
name: "Confirm bloop", cat: "synth", note: "menu confirm, C5 -> G5 squares",
current: () => playConfirmBloop(),
zz: [["bloop", ZZFX_PRESETS.confirmBloop]],
},
{
name: "BIOS beep", cat: "synth", note: "POST beep, 940 Hz square",
current: () => playBiosBeep(),
zz: [["beep", ZZFX_PRESETS.biosBeep]],
},
{
name: "BIOS tick", cat: "synth", note: "teletype tick per POST line",
current: () => playBiosTick(),
zz: [["tick", ZZFX_PRESETS.biosTick]],
},
{
name: "Scan blip", cat: "synth", note: "per-line entrance blip, random pitch",
current: () => playLineBlip(Math.random()),
zz: [["blip", ZZFX_PRESETS.scanBlip]],
},
{
name: "Entrance sweep", cat: "synth", note: "3-layer materialize sweep + thunk + ping (0.9 s)",
current: () => playEntranceSweep(0.9),
zz: [["sweep", ZZFX_PRESETS.entranceSweep]],
},
{
name: "Prop sweep (small)", cat: "synth", note: "duck-sized prop materialize (0.9 s, quieter, no garnish)",
current: () => playPropSweep(0.9),
zz: null,
},
{
name: "Prop sweep (cabinet)", cat: "synth", note: "big prop: size-stretched 2.2 s, register dropped by the stretch",
current: () => playPropSweep(2.2),
zz: null,
},
{
name: "Quack", cat: "voice", note: "reference only, chirp takes a-l round-robin",
current: playQuack,
zz: null,
},
];
const loops = [
{
name: "Ambient bed", cat: "synth", note: "arcade-room hum loop; ZzFX n/a (already synth)",
on: ambientOn, toggle: toggleAmbient,
},
{
name: "Roller rumble", cat: "synth", note: "rolling-noise loop at 0.7 speed; ZzFX n/a (already synth)",
on: rumbleOn, toggle: toggleRumble,
},
{
name: "Wheee", cat: "voice", note: "reference only, loop take a on the voice bus",
on: wheeeOn, toggle: toggleWheee,
},
];
return (
<div className="sb-root">
<style>{CSS}</style>
<header className="sb-head">
<h1>Microduck Soundboard</h1>
<p className="sb-sub">
A/B: current runtime implementation vs ZzFX candidate. First click unlocks audio.
</p>
<label className="sb-vol">
Master volume
<input
type="range" min="0" max="1" step="0.01" value={vol}
aria-label="Master volume"
onChange={(e) => setVol(Number(e.target.value))}
/>
<span>{Math.round(vol * 100)}%</span>
</label>
</header>
<div className="sb-grid" role="table" aria-label="One-shot sounds">
<div className="sb-row sb-row-head" role="row">
<span>Sound</span><span>Category</span><span>Current</span><span>ZzFX candidate</span>
</div>
{rows.map((r) => (
<div className="sb-row" role="row" key={r.name}>
<span className="sb-name">
{r.name}
<small>{r.note}</small>
</span>
<span><em className={`sb-cat sb-cat-${r.cat}`}>{r.cat}</em></span>
<span>
<button type="button" className="sb-btn sb-btn-cur" onClick={() => armed(r.current)}>
Play
</button>
</span>
<span className="sb-zz">
{r.zz
? r.zz.map(([label, params]) => (
<button
type="button" key={label} className="sb-btn sb-btn-zz"
onClick={() => armed(() => playZ(params))}
>
{label}
</button>
))
: <em className="sb-na">n/a (voice reference)</em>}
</span>
</div>
))}
</div>
<h2 className="sb-h2">Loops</h2>
<div className="sb-grid" role="table" aria-label="Looping sounds">
{loops.map((l) => (
<div className="sb-row" role="row" key={l.name}>
<span className="sb-name">
{l.name}
<small>{l.note}</small>
</span>
<span><em className={`sb-cat sb-cat-${l.cat}`}>{l.cat}</em></span>
<span>
<button
type="button"
className={`sb-btn sb-btn-cur ${l.on ? "sb-on" : ""}`}
aria-pressed={l.on}
onClick={l.toggle}
>
{l.on ? "Stop" : "Start"}
</button>
</span>
<span className="sb-zz"><em className="sb-na">n/a</em></span>
</div>
))}
</div>
</div>
);
}
const CSS = `
/* The game's index.html pins body { overflow: hidden } for the canvas;
this page is a document, so re-enable normal scrolling. */
html, body { height: auto; overflow: auto; }
#root { height: auto; }
.sb-root {
min-height: 100vh;
background: #faf8f2;
color: #101018;
font: 15px/1.45 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
padding: 2.2rem clamp(1rem, 5vw, 4rem) 4rem;
}
.sb-head h1 {
font-family: 'Anton', 'Arial Narrow', Impact, sans-serif;
font-size: clamp(2rem, 5vw, 3.2rem);
text-transform: uppercase;
letter-spacing: 0.02em;
margin: 0;
color: #101018;
-webkit-text-stroke: 1px #101018;
}
.sb-sub { margin: 0.3rem 0 1.2rem; opacity: 0.75; }
.sb-vol {
display: inline-flex; align-items: center; gap: 0.7rem;
border: 2px solid #101018; background: #fff;
padding: 0.5rem 0.9rem; box-shadow: 4px 4px 0 #101018;
margin-bottom: 1.6rem; font-weight: 700;
}
.sb-vol input { accent-color: #ff7a2f; width: 200px; }
.sb-h2 {
font-family: 'Anton', 'Arial Narrow', Impact, sans-serif;
text-transform: uppercase; margin: 2rem 0 0.6rem;
}
.sb-grid { border: 2px solid #101018; background: #fff; box-shadow: 6px 6px 0 #101018; }
.sb-row {
display: grid;
grid-template-columns: minmax(220px, 1.6fr) 110px 130px minmax(160px, 1fr);
align-items: center; gap: 0.8rem;
padding: 0.55rem 0.9rem;
border-bottom: 1px solid rgba(16, 16, 24, 0.18);
}
.sb-row:last-child { border-bottom: none; }
.sb-row-head {
font-weight: 700; text-transform: uppercase; font-size: 12px;
background: #101018; color: #faf8f2;
}
.sb-name { display: flex; flex-direction: column; font-weight: 700; }
.sb-name small { font-weight: 400; opacity: 0.6; font-size: 11px; }
.sb-cat {
font-style: normal; font-size: 11px; font-weight: 700;
text-transform: uppercase; padding: 2px 7px; border: 1.5px solid #101018;
}
.sb-cat-sampled { background: #ffe9db; }
.sb-cat-synth { background: #e5eeff; }
.sb-cat-voice { background: #fff3b0; }
.sb-btn {
font: inherit; font-weight: 700; text-transform: uppercase; font-size: 12px;
border: 2px solid #101018; padding: 0.35rem 0.9rem; cursor: pointer;
box-shadow: 3px 3px 0 #101018; background: #faf8f2; color: #101018;
margin: 2px 6px 2px 0;
}
.sb-btn:active { transform: translate(2px, 2px); box-shadow: 1px 1px 0 #101018; }
.sb-btn:focus-visible { outline: 3px solid #ff7a2f; outline-offset: 2px; }
.sb-btn-zz { background: #ff7a2f; color: #101018; }
.sb-btn-cur.sb-on { background: #101018; color: #faf8f2; }
.sb-na { opacity: 0.5; font-size: 12px; }
@media (max-width: 700px) {
.sb-row { grid-template-columns: 1fr; gap: 0.3rem; }
.sb-row-head { display: none; }
}
`;
+751
View File
@@ -0,0 +1,751 @@
// Title / pause overlay: a full-page ink screen printed in the landing's
// comic DA - big Anton title with the ink-drop + cyan/magenta aberration
// treatment, a comic-block CTA on an acid plate, and an orange halftone
// ramp pooling in the top-left corner. Colour and locomotion live in the
// in-game HUD quickbar, so the intro's only action is Waddle in.
//
// The first "Waddle in" cues the BIOS; later Esc / the in-game Back button
// reopen the overlay as pause ("Resume"). The ?boot=1 bypass lives in
// App.jsx and never mounts this component.
import { useEffect, useRef, useState } from "react";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { keyframes, styled } from "@mui/material/styles";
import { useGame } from "../store.js";
import { signed } from "../game/signed.js";
import { playConfirmBloop } from "../game/audio.js";
import { INK, ORANGE, MONO } from "../theme.js";
import { ComicButton, ComicTitle, HalftoneRamp, ANTON, CREAM } from "./comic.jsx";
import MenuDuck, { preloadMenuDuck, isMenuDuckReady } from "./MenuDuck.jsx";
import { PreorderButton } from "./Hud.jsx";
import { readLayoutMap, resolveKeycaps } from "./keyboard-layout.js";
const rowIn = keyframes`
from { transform: translateY(12px); opacity: 0; }
to { transform: none; opacity: 1; }
`;
const brandIn = keyframes`
from { transform: translateY(10px) scale(0.94); opacity: 0; }
to { transform: none; opacity: 1; }
`;
// Title-screen blink for the "press Enter" prompt - a soft pulse, not a
// hard arcade strobe, so it invites rather than nags.
const promptPulse = keyframes`
from { opacity: 0.8; }
to { opacity: 0.18; }
`;
const spin = keyframes`
to { transform: rotate(360deg); }
`;
// One soft ease, small travel, ~80 ms between rows - staged, not showy.
const row = (delay, name = rowIn) => ({
animation: `${name} 0.55s cubic-bezier(0.22, 1, 0.36, 1) both`,
animationDelay: `${delay}s`,
"@media (prefers-reduced-motion: reduce)": { animation: "none" },
});
const Kbd = styled("kbd")(({ round }) => ({
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
minWidth: round ? "1.9rem" : "1.65rem",
height: "1.65rem",
padding: "0 0.45rem",
font: "inherit",
fontSize: "0.68rem",
fontWeight: 600,
color: "#fff",
background: "#14141c",
border: `2px solid ${INK}`,
borderRadius: round ? "50%" : 8,
boxShadow: "0 0 0 2px rgba(255, 255, 255, 0.82)",
}));
// Arcade-style cheat strip pinned at the bottom of the title screen: one
// keycap group + label per move, scannable in a second. The CTA is the
// screen's centre of gravity - players enter first and learn in game.
// Controls bind physical KeyboardEvent.code positions, so letter keycaps
// carry `codes` and get their printed label resolved for the active layout
// (QWERTY fallback where the Keyboard Map API is unavailable).
const SHORTCUTS = {
kb: [
{ caps: ["\u2191\u2190\u2193\u2192"], name: "Move" },
{ codes: ["KeyQ", "KeyE"], name: "Kick" },
{ codes: ["KeyR"], name: "Sit" },
{ codes: ["KeyG"], name: "Pick up" },
{ codes: ["KeyC"], name: "Camera" },
{ caps: ["Space"], name: "Reset" },
],
pad: [
{ caps: ["LS"], name: "Move" },
{ caps: ["LB", "RB"], name: "Kick" },
{ caps: ["Y"], name: "Head" },
{ caps: ["RS"], name: "Camera" },
{ caps: ["X", "\u2193"], name: "Sit" },
],
touch: [
{ caps: ["Stick"], name: "Move" },
{ caps: ["A"], round: true, name: "Kick" },
{ caps: ["B"], round: true, name: "Quack" },
],
};
// kb's hint is built at render time from the resolved layout (see kbHint).
const HINTS = {
pad: "A ground pick \u00b7 RT quack \u00b7 hold LT wheee \u00b7 R3 chase",
touch: "drag to orbit \u00b7 pinch to zoom",
};
// Per-colourway screen accent: the title fill and the halftone pool
// follow the duck on stage. Cream keeps the landing's brand orange (the
// classic duck's trim colour); lavender and sky use the press-kit swatch
// hexes (shared with the vitrine picker); graphite's swatch is too dark
// for type on ink, so it wears the palette's light warm gray instead.
const VARIANT_ACCENTS = {
classic: ORANGE,
charcoal: "#b9b5ae",
purple: "#bfa9cf",
blue: "#a9dbe8",
};
// #rrggbb -> rgba() at the halftone's alpha.
const tint = (hex, a) =>
`rgba(${parseInt(hex.slice(1, 3), 16)}, ${parseInt(hex.slice(3, 5), 16)}, ${parseInt(hex.slice(5, 7), 16)}, ${a})`;
const KB_CODES = SHORTCUTS.kb.flatMap((t) => t.codes ?? []);
function useKeycaps(enabled) {
const [keycaps, setKeycaps] = useState(() => resolveKeycaps(KB_CODES, null));
useEffect(() => {
if (!enabled) return;
let cancelled = false;
let latest = 0;
const read = async () => {
const ticket = ++latest;
const map = await readLayoutMap();
// Overlapping reads can settle out of order; only the newest paints.
if (!cancelled && ticket === latest) setKeycaps(resolveKeycaps(KB_CODES, map));
};
read();
const keyboard = navigator.keyboard;
keyboard?.addEventListener?.("layoutchange", read);
return () => {
cancelled = true;
keyboard?.removeEventListener?.("layoutchange", read);
};
}, [enabled]);
return keycaps;
}
function closeMenu() {
useGame.setState({ menuOpen: false });
if (!useGame.getState().entered) useGame.setState({ entered: true });
// Menu-confirm bloop. On the first entry the `entered` latch above has
// just created the shared AudioContext inside this very gesture, so the
// bloop rides the unlock (the synth resume-retries if still suspended).
playConfirmBloop();
}
export default function TitleMenu() {
const menuOpen = useGame((s) => s.menuOpen);
const entered = useGame((s) => s.entered);
const padConnected = useGame((s) => s.padConnected);
const touchMode = useGame((s) => s.touchMode);
const variant = useGame((s) => s.variant);
const bootDone = useGame((s) => s.bootDone);
const bootFailed = useGame((s) => s.bootFailed);
const [closing, setClosing] = useState(false);
const prevOpen = useRef(menuOpen);
// A plugged-in gamepad wins over the touch tutorial.
const tutorialVariant = padConnected ? "pad" : touchMode ? "touch" : "kb";
const { labels, moveHint } = useKeycaps(tutorialVariant === "kb");
// Touch devices and narrow (mobile-sized) screens skip the 3D stage
// entirely: no duck column, and the GLB is never even downloaded. The
// width check matches the layout's md breakpoint, so the stage never
// renders where the column would stack under the text anyway. Everyone
// else holds a spinner until the stage's assets are in, so the content
// reveal and the duck's entrance scan cue together. The stage is a
// module singleton, so pause reopens resolve instantly (no second
// spinner).
const [wide, setWide] = useState(
() => window.matchMedia("(min-width: 900px)").matches,
);
useEffect(() => {
const mq = window.matchMedia("(min-width: 900px)");
const onChange = () => setWide(mq.matches);
mq.addEventListener("change", onChange);
return () => mq.removeEventListener("change", onChange);
}, []);
const showDuck = !touchMode && wide;
const [duckReady, setDuckReady] = useState(isMenuDuckReady);
useEffect(() => {
if (!showDuck || duckReady) return;
let on = true;
preloadMenuDuck()
.catch(() => {})
.then(() => { if (on) setDuckReady(true); });
return () => { on = false; };
}, [showDuck, duckReady]);
// The display face too: Anton is the screen's voice (title, CTA,
// strip) and would otherwise FOUT in after the reveal. It loads
// lazily on first use, so nudge it explicitly - the content is gated
// and would never request it. Timeout so a stuck font never wedges
// the menu behind the spinner.
const [fontsReady, setFontsReady] = useState(
() => !!document.fonts?.check?.("1rem Anton"),
);
useEffect(() => {
if (fontsReady) return;
let on = true;
const done = () => { if (on) setFontsReady(true); };
const anton = document.fonts?.load
? document.fonts.load("1rem Anton")
: Promise.resolve();
const allFonts = document.fonts?.ready ?? Promise.resolve();
Promise.all([anton, allFonts]).then(done, done);
const t = setTimeout(done, 4000);
return () => { on = false; clearTimeout(t); };
}, [fontsReady]);
// The brand lockup images too (formerly the preboot veil's job): the
// corner chrome is part of the gated reveal, so the logo must not pop
// in after it. Capped so a broken asset never wedges the menu.
const [brandReady, setBrandReady] = useState(false);
useEffect(() => {
if (brandReady) return;
let on = true;
const done = () => { if (on) setBrandReady(true); };
const load = (src) =>
new Promise((res) => {
const img = new Image();
img.src = signed(src);
if (img.complete && img.naturalWidth) res();
else {
img.addEventListener("load", res, { once: true });
img.addEventListener("error", res, { once: true });
}
});
Promise.all([
load("./assets/duck-head-mark.webp"),
load("./assets/duck-head-mark-open.webp"),
]).then(done, done);
const t = setTimeout(done, 2500);
return () => { on = false; clearTimeout(t); };
}, [brandReady]);
// The game core too: it boots eagerly behind the title screen (MuJoCo
// WASM, scene geometry, policy sessions), saturating the main thread
// in ~10-40 ms chunks for a couple of seconds. Revealing the menu
// mid-boot made the duck's entrance scan stutter (profiled: the scan
// window sat inside the boot's busy region), so the spinner holds
// until the boot settles - the reveal then animates on a free thread
// and Waddle-in is instant. bootFailed releases the gate: the halt
// screen owns the viewport at that point.
const ready =
(duckReady || !showDuck) &&
fontsReady &&
brandReady &&
(bootDone || bootFailed);
// Keep the overlay mounted through the 0.35 s closing fade.
useEffect(() => {
const was = prevOpen.current;
prevOpen.current = menuOpen;
if (was && !menuOpen) {
setClosing(true);
const t = setTimeout(() => setClosing(false), 380);
return () => clearTimeout(t);
}
}, [menuOpen]);
// Enter enters / resumes; Esc toggles the pause menu (never over the
// BIOS readout).
useEffect(() => {
const onKey = (e) => {
const s = useGame.getState();
if (e.code === "Enter" && s.menuOpen) {
if (e.target instanceof HTMLButtonElement && e.target.dataset.cta !== "1") return;
e.preventDefault();
closeMenu();
return;
}
if (e.code !== "Escape") return;
if (s.biosVisible) return;
if (s.menuOpen) {
if (s.entered) closeMenu();
return;
}
if (s.entered) useGame.setState({ menuOpen: true });
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, []);
// Gamepad twin of the handler above: A (button 0) enters / resumes
// through the same closeMenu() as the CTA click; Start (9) or Select (8)
// reopens the overlay in-game, like Escape. Polled with a light rAF loop
// because the game's own gamepad source only exists once the core has
// booted (and its actions are game-facing). Edge state persists across
// the open/close transition, so one press fires exactly one action.
useEffect(() => {
const prev = { enter: false, menu: false };
// The A press that closes the menu is applied one frame LATE on
// purpose: closing unlocks the game inputs synchronously, and the
// in-game gamepad source polls in the same rAF round - if it sees the
// press only after the unlock, its own A edge fires (groundPick). The
// one-frame delay guarantees it polls the press at least once while
// the pause lock still gates it, so by the unlock frame its edge
// state already knows the button is down and the entering press is
// swallowed.
let enterPending = false;
let raf;
const poll = () => {
raf = requestAnimationFrame(poll);
if (enterPending) {
enterPending = false;
if (useGame.getState().menuOpen) closeMenu();
}
// Same pad preference as controls/gamepad.js: standard mapping first.
const pads = [...(navigator.getGamepads?.() ?? [])].filter((p) => p && p.connected);
const gp = pads.find((p) => p.mapping === "standard") ?? pads[0];
if (!gp) {
prev.enter = false;
prev.menu = false;
return;
}
const enter = !!gp.buttons[0]?.pressed;
const menu = !!(gp.buttons[9]?.pressed || gp.buttons[8]?.pressed);
const enterEdge = enter && !prev.enter;
const menuEdge = menu && !prev.menu;
prev.enter = enter;
prev.menu = menu;
const s = useGame.getState();
if (enterEdge && s.menuOpen) {
enterPending = true;
return;
}
if (menuEdge && !s.menuOpen && s.entered && !s.biosVisible)
useGame.setState({ menuOpen: true });
};
raf = requestAnimationFrame(poll);
return () => cancelAnimationFrame(raf);
}, []);
if (!menuOpen && !closing) return null;
// Letter keycaps resolved for the active layout (QWERTY fallback).
const shortcuts =
tutorialVariant === "kb"
? SHORTCUTS.kb.map((t) =>
t.codes ? { ...t, caps: t.codes.map((code) => labels[code]) } : t,
)
: SHORTCUTS[tutorialVariant];
// The strip's footnote names the letter movement cluster for the active
// layout too ("ZQSD works too" reads wrong on QWERTY and Dvorak).
const kbHint = `${moveHint.replace(/^arrows or /, "")} works too \u00b7 drag to orbit \u00b7 scroll to zoom`;
const ctaLabel = entered ? "Resume" : "Waddle in";
// Blinking key prompt under the CTA; touch has no key to press.
const enterHint = padConnected ? "press A" : touchMode ? null : "press Enter";
const accent = VARIANT_ACCENTS[variant] ?? ORANGE;
return (
<Box
role="dialog"
aria-modal="true"
aria-label="Microduck"
sx={{
position: "fixed",
inset: 0,
zIndex: 30,
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
p: "2.4rem 1.4rem 1.8rem",
background: INK,
opacity: menuOpen ? 1 : 0,
pointerEvents: menuOpen ? "auto" : "none",
overflowY: "auto",
transition: "opacity 0.35s ease, background 0.4s ease",
}}
>
{/* Theme-orange halftone pooling in the top-left corner, dots
growing toward it - the landing's screen-tone on ink ground. */}
<HalftoneRamp
color={tint(accent, 0.16)}
size={20}
corner="top-left"
reach={60}
/>
{/* Corner chrome, shared grammar with the vitrine header (drawn
duck head, top-left) and the in-game HUD (pre-order, top-right):
the title screen wears the same screen furniture as the game.
Gated with the rest of the reveal so the loading state is a
single centered spinner on bare ink. */}
{ready && (
<Box
aria-hidden
sx={{
position: "absolute",
top: "1.25rem",
left: "1.5rem",
zIndex: 1,
display: "flex",
alignItems: "center",
gap: "0.65rem",
userSelect: "none",
...row(0, brandIn),
"&:hover .duck-closed": { opacity: 0 },
"&:hover .duck-open": { opacity: 1 },
}}
>
<Box
component="span"
sx={{
position: "relative",
display: "block",
height: "2.1rem",
filter: "drop-shadow(2px 2px 0 rgba(0, 0, 0, 0.5))",
}}
>
<Box
component="img"
className="duck-closed"
alt=""
src={signed("./assets/duck-head-mark.webp")}
sx={{ display: "block", height: "100%", width: "auto" }}
/>
{/* The open frame's canvas (460x333) is a hair wider/taller
than the closed one (454x269); offsets pin the head while
the jaw hangs below. */}
<Box
component="img"
className="duck-open"
alt=""
src={signed("./assets/duck-head-mark-open.webp")}
sx={{
position: "absolute",
top: "-0.75%",
left: "-1.1%",
width: "101.3%",
maxWidth: "none",
height: "auto",
opacity: 0,
}}
/>
</Box>
<Box
component="span"
sx={{
fontFamily: ANTON,
fontSize: "1rem",
letterSpacing: "0.05em",
textTransform: "uppercase",
color: "#fff",
display: { xs: "none", sm: "block" },
}}
>
Microduck
</Box>
</Box>
)}
{/* The in-game HUD's shop plate, verbatim: same component, same
fixed spot, so pausing never swaps it for a lookalike. */}
{ready && <PreorderButton sx={{ ...row(0.1) }} />}
{/* Loading gate: one centered spinner on bare ink until logo,
fonts, the duck stage's assets and the game boot are all in -
then the whole composition (corner chrome included) reveals at
once (row stagger + entrance scan). */}
{!ready && (
<Box
role="status"
aria-label="Loading"
sx={{
m: "auto",
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: "1.1rem",
}}
>
<Box
aria-hidden
sx={{
width: "2.4rem",
height: "2.4rem",
borderRadius: "50%",
border: "3px solid rgba(255, 255, 255, 0.14)",
borderTopColor: accent,
animation: `${spin} 0.8s linear infinite`,
}}
/>
<Typography
sx={{
fontFamily: MONO,
fontSize: "0.64rem",
fontWeight: 600,
letterSpacing: "0.16em",
textTransform: "uppercase",
color: "rgba(255, 255, 255, 0.5)",
}}
>
Loading
</Typography>
</Box>
)}
{/* Split title screen: brand + CTA column on the left, the live
duck stage on the right (stacked on narrow screens). The row
stretches to fill the space between the corner chrome and the
bottom strip, so the duck stands ON the strip's rule - the
screen has a floor instead of elements floating mid-air. */}
{ready && (
<>
<Box
sx={{
position: "relative",
display: "flex",
flexDirection: { xs: "column", md: "row" },
alignItems: "stretch",
justifyContent: "center",
gap: { xs: "0.4rem", md: "1.5rem" },
width: "100%",
maxWidth: "min(66rem, 94vw)",
flex: "1 1 auto",
minHeight: 0,
pt: { xs: "2.6rem", md: 0 },
}}
>
<Box
sx={{
position: "relative",
flex: { md: "0 1 33rem" },
width: "100%",
maxWidth: { xs: "min(48rem, 92vw)", md: "none" },
mx: { xs: "auto", md: 0 },
// Game-menu grammar: the text block rides the column's vertical
// centre on desktop; left-anchored there, centered when stacked
// or when the duck column is absent (touch mode).
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: { xs: "center", md: showDuck ? "flex-start" : "center" },
textAlign: { xs: "center", md: showDuck ? "left" : "center" },
}}
>
{/* The landing hero's mistracked-VHS treatment: orange fill with
ink drop + chroma ghosts, hollow echo line below. */}
<ComicTitle
component="h1"
tone="dark"
accent={accent}
fontSize="clamp(3.4rem, 9vw, 6.2rem)"
lines={[
{ text: "Microduck" },
{ text: "Simulator", variant: "outline", scale: 0.78 },
]}
sx={{ ...row(0.08) }}
/>
<Typography
sx={{
mx: { xs: "auto", md: 0 },
mt: "1.1rem",
"@media (max-height: 700px)": { mt: "0.8rem" },
maxWidth: "34ch",
fontSize: { xs: "0.95rem", sm: "1.05rem" },
lineHeight: 1.5,
letterSpacing: "-0.012em",
color: "rgba(255, 255, 255, 0.72)",
textWrap: "balance",
...row(0.24),
}}
>
The exact same trained policies that drive the real robot,
live in your browser.
</Typography>
{/* CTA + key prompt travel as one block so the prompt stays
centred under the button whatever the column's alignment. */}
<Box
sx={{
display: "inline-flex",
flexDirection: "column",
alignItems: "center",
mt: "2rem",
"@media (max-height: 700px)": { mt: "1.3rem" },
...row(0.32),
}}
>
<ComicButton
scheme="orange"
size="medium"
onDark
data-cta="1"
onClick={closeMenu}
>
{/* Pad prompt: ink circle with the A face button, shown while a
gamepad is connected - it mirrors the A-to-enter binding of
the poll loop above. Decorative; the text label carries the
meaning. */}
{padConnected && (
<Box
component="span"
aria-hidden
sx={{
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
width: "1.5em",
height: "1.5em",
borderRadius: "50%",
background: INK,
color: CREAM,
fontSize: "0.72em",
lineHeight: 1,
}}
>
A
</Box>
)}
{ctaLabel}
</ComicButton>
{enterHint && (
<Typography
aria-hidden
sx={{
mt: "0.85rem",
fontFamily: MONO,
fontSize: "0.66rem",
fontWeight: 600,
letterSpacing: "0.14em",
textTransform: "uppercase",
color: "rgba(255, 255, 255, 0.6)",
...row(0.4),
}}
>
<Box
component="span"
sx={{
display: "inline-block",
animation: `${promptPulse} 0.95s ease-in-out infinite alternate`,
"@media (prefers-reduced-motion: reduce)": {
animation: "none",
opacity: 0.6,
},
}}
>
{enterHint}
</Box>
</Typography>
)}
</Box>
</Box>
{/* Right column: the duck's simulated twin, live - head follows the
pointer, click quacks. Its colourway tracks the in-game duck. No
backdrop, no fake shadow: the render alone, standing on the
bottom strip's rule like a character select. Touch devices skip
the stage entirely (no column, no GLB download). */}
{showDuck && (
<Box
sx={{
position: "relative",
flex: { xs: "1 1 auto", md: "1 1 22rem" },
width: "100%",
minHeight: { xs: "min(30vh, 16rem)", md: 0 },
...row(0.16, brandIn),
}}
>
<MenuDuck sx={{ position: "absolute", inset: 0 }} />
</Box>
)}
</Box>
{/* Bottom cheat strip: every move on one wrapping line, arcade
instruction-card style. Reference material, not the main event -
it sits at the screen's bottom edge, out of the CTA's way. */}
<Box
sx={{
position: "relative",
width: "100%",
textAlign: "center",
mt: "1.2rem",
pt: "1.15rem",
borderTop: "1px solid rgba(255, 255, 255, 0.08)",
...row(0.5),
}}
>
<Box
sx={{
display: "flex",
flexWrap: "wrap",
justifyContent: "center",
alignItems: "center",
gap: "0.55rem 1.25rem",
// Strip keycaps are a notch smaller than the CTA scale.
"& kbd": {
minWidth: "1.45rem",
height: "1.45rem",
p: "0 0.34rem",
fontSize: "0.6rem",
},
}}
>
{shortcuts.map((s) => (
<Box
key={s.name}
sx={{
display: "inline-flex",
alignItems: "center",
gap: "0.45rem",
}}
>
<Box sx={{ display: "inline-flex", gap: "0.22rem" }}>
{/* Index keys: exotic layouts can print the same glyph twice. */}
{s.caps.map((c, i) => (
<Kbd key={i} round={s.round ? 1 : 0}>{c}</Kbd>
))}
</Box>
<Box
component="span"
sx={{
fontFamily: ANTON,
fontSize: "0.74rem",
letterSpacing: "0.07em",
textTransform: "uppercase",
color: "rgba(255, 255, 255, 0.88)",
}}
>
{s.name}
</Box>
</Box>
))}
</Box>
<Typography
sx={{
mt: "0.7rem",
fontFamily: MONO,
fontSize: "0.62rem",
fontWeight: 600,
letterSpacing: "0.12em",
textTransform: "uppercase",
color: "rgba(255, 255, 255, 0.34)",
}}
>
{tutorialVariant === "kb" ? kbHint : HINTS[tutorialVariant]}
</Typography>
</Box>
</>
)}
</Box>
);
}
+128
View File
@@ -0,0 +1,128 @@
// Touch overlay: Game Boy thumbs. Left thumb = floating virtual stick
// (the whole lower-left quadrant grabs it, the base re-anchors under the
// finger), right thumb = A/B caps on the classic diagonal.
//
// The DOM here is deliberately plain and keyed by ids: controls/touch.js
// binds pointer events to #touch-zone / #touch-stick / #touch-a / #touch-b
// at controller init and toggles the .live/.down classes itself. React
// only owns the wrapper's visibility, so it never fights those mutations -
// which is also why this component must stay mounted at all times.
import Box from "@mui/material/Box";
import { useGame } from "../store.js";
import { INK, ORANGE } from "../theme.js";
export default function TouchOverlay() {
const touchMode = useGame((s) => s.touchMode);
const entered = useGame((s) => s.entered);
const menuOpen = useGame((s) => s.menuOpen);
const visible = touchMode && entered && !menuOpen;
return (
<Box
id="touch-ui"
sx={{
display: visible ? "block" : "none",
// Floating-stick zone: sits BELOW the back button in z so its tap
// still lands; the resting stick inside marks the zone when idle.
"& #touch-zone": {
position: "fixed",
left: 0,
right: "50%",
top: "30%",
bottom: 0,
zIndex: 9,
touchAction: "none",
},
"& #touch-stick": {
position: "absolute",
left: "1.3rem",
bottom: "2rem",
width: "8.2rem",
height: "8.2rem",
borderRadius: "50%",
border: "1px solid rgba(255, 255, 255, 0.18)",
background: "rgba(8, 8, 12, 0.4)",
pointerEvents: "none", // the zone owns the pointer
},
"& #touch-stick .nub": {
position: "absolute",
left: "50%",
top: "50%",
width: "3.6rem",
height: "3.6rem",
margin: "-1.8rem 0 0 -1.8rem",
borderRadius: "50%",
border: "1px solid rgba(255, 255, 255, 0.35)",
background: "rgba(255, 255, 255, 0.14)",
pointerEvents: "none",
},
"& #touch-stick.live": { borderColor: "rgba(255, 122, 47, 0.55)" },
"& #touch-stick.live .nub": {
background: "rgba(255, 122, 47, 0.45)",
borderColor: ORANGE,
},
"& #touch-btns": {
position: "fixed",
right: "1.3rem",
bottom: "2.2rem",
zIndex: 12,
width: "9.4rem",
height: "8.4rem",
},
"& .capwrap": {
position: "absolute",
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: "0.3rem",
},
"& .cap-a": { right: 0, top: 0 },
"& .cap-b": { left: 0, bottom: 0 },
"& #touch-btns button": {
appearance: "none",
width: "4.2rem",
height: "4.2rem",
borderRadius: "50%",
border: "1px solid rgba(255, 255, 255, 0.22)",
background: "rgba(8, 8, 12, 0.5)",
color: "rgba(255, 255, 255, 0.85)",
font: "inherit",
fontSize: "1.3rem",
fontWeight: 700,
cursor: "pointer",
touchAction: "none",
userSelect: "none",
WebkitUserSelect: "none",
},
"& #touch-btns button.down": {
background: ORANGE,
borderColor: ORANGE,
color: INK,
},
"& .capwrap span": {
fontSize: "0.55rem",
fontWeight: 600,
letterSpacing: "0.18em",
textTransform: "uppercase",
color: "rgba(255, 255, 255, 0.45)",
},
}}
>
<div id="touch-zone">
<div id="touch-stick">
<div className="nub" />
</div>
</div>
<div id="touch-btns">
<div className="capwrap cap-a">
<button type="button" id="touch-a" aria-label="Kick">A</button>
<span>Kick</span>
</div>
<div className="capwrap cap-b">
<button type="button" id="touch-b" aria-label="Quack">B</button>
<span>Quack</span>
</div>
</div>
</Box>
);
}
+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>
);
}
+44
View File
@@ -0,0 +1,44 @@
// Controls use physical KeyboardEvent.code positions; getLayoutMap() provides
// the characters printed on those keys for the active layout.
const MOVEMENT_CODES = ["KeyW", "KeyA", "KeyS", "KeyD"];
const MOVEMENT_FALLBACK_HINT = "arrows or WASD";
function keycap(value) {
if (typeof value !== "string") return null;
const glyph = value.trim();
if ([...glyph].length !== 1 || /[\p{M}\p{C}\p{Z}]/u.test(glyph)) return null;
const upper = glyph.toUpperCase();
return [...upper].length === 1 ? upper : glyph; // "ß" must not become "SS"
}
export function resolveKeycaps(codes, layoutMap) {
const required = [...new Set([...MOVEMENT_CODES, ...codes])];
const labels = {};
let complete = true;
for (const code of required) {
let label = null;
try {
label = keycap(layoutMap?.get?.(code));
} catch {
label = null;
}
if (!label) complete = false;
labels[code] = label;
}
if (!complete) {
for (const code of required) labels[code] = code.replace(/^Key/, "");
return { labels, moveHint: MOVEMENT_FALLBACK_HINT };
}
return {
labels,
moveHint: `arrows or ${MOVEMENT_CODES.map((code) => labels[code]).join("")}`,
};
}
export async function readLayoutMap(nav = globalThis.navigator) {
try {
return (await nav?.keyboard?.getLayoutMap?.()) ?? null;
} catch {
return null;
}
}