feat: Vite+React+MUI+R3F app shell in app/ (framework-agnostic game core, zustand bridge)
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
+15
@@ -0,0 +1,15 @@
|
||||
# Build the Vite app, then serve the static bundle with nginx.
|
||||
# HF Spaces docker SDK: the container must listen on app_port (8080);
|
||||
# nginx-unprivileged listens on 8080 by default and runs as non-root,
|
||||
# which is exactly what Spaces expects.
|
||||
|
||||
FROM node:22-alpine AS build
|
||||
WORKDIR /build
|
||||
COPY app/package.json app/package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY app/ ./
|
||||
RUN npm run build
|
||||
|
||||
FROM nginxinc/nginx-unprivileged:alpine
|
||||
COPY --from=build /build/dist /usr/share/nginx/html
|
||||
EXPOSE 8080
|
||||
@@ -0,0 +1,2 @@
|
||||
node_modules/
|
||||
dist/
|
||||
@@ -0,0 +1,21 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Microduck</title>
|
||||
<style>
|
||||
:root {
|
||||
--ink: #08080c;
|
||||
}
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
html, body { height: 100%; }
|
||||
body { background: var(--ink); overflow: hidden; }
|
||||
#root { height: 100%; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+2052
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "microduck-sandbox",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@emotion/react": "^11.14.0",
|
||||
"@emotion/styled": "^11.14.1",
|
||||
"@mui/material": "^9.3.1",
|
||||
"@react-three/fiber": "^9.7.0",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"three": "^0.164.1",
|
||||
"zustand": "^5.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-react": "^6.1.0",
|
||||
"vite": "^8.2.2"
|
||||
}
|
||||
}
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../assets
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../policies
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../robot
|
||||
@@ -0,0 +1,87 @@
|
||||
// App shell: layers in z order - scene canvas (1), halftone (2), CRT (5),
|
||||
// HUD + touch overlay (9-12), BIOS readout (20), title menu (30), preboot
|
||||
// veil (40). Also owns the pre-game device detection (gamepad, touch) and
|
||||
// the preboot -> title -> enter flow.
|
||||
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 Preboot from "./ui/Preboot.jsx";
|
||||
import { useGame } from "./store.js";
|
||||
import { signed } from "./game/signed.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();
|
||||
|
||||
// Preboot veil: hold the title page until its logo and the fonts are
|
||||
// in (grey spinner meanwhile), capped so a broken asset can never wall
|
||||
// the menu off. ?boot=1 skips the title entirely - testing hook.
|
||||
if (params.get("boot") === "1") {
|
||||
useGame.setState({ prebootDone: true, entered: true, menuOpen: false });
|
||||
} else {
|
||||
const img = new Image();
|
||||
img.src = signed("./assets/duck-head-mark.webp");
|
||||
const imgReady = new Promise((res) => {
|
||||
if (img.complete && img.naturalWidth) res();
|
||||
else {
|
||||
img.addEventListener("load", res, { once: true });
|
||||
img.addEventListener("error", res, { once: true });
|
||||
}
|
||||
});
|
||||
const fontsReady = document.fonts?.ready ?? Promise.resolve();
|
||||
const cap = new Promise((res) => setTimeout(res, 2500));
|
||||
Promise.race([Promise.all([imgReady, fontsReady]), cap]).then(() => {
|
||||
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 />
|
||||
<Preboot />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
// 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 } 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 },
|
||||
},
|
||||
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, 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);
|
||||
}
|
||||
`,
|
||||
});
|
||||
const mesh = new THREE.Mesh(new THREE.PlaneGeometry(30, 30), 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);
|
||||
}
|
||||
`,
|
||||
});
|
||||
}
|
||||
|
||||
// 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 };
|
||||
}
|
||||
@@ -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; },
|
||||
};
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
// 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.
|
||||
|
||||
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,
|
||||
}) {
|
||||
const ENTRANCE_TOTAL_S = Math.max(
|
||||
ENTRANCE_GRID_S,
|
||||
ENTRANCE_WALL_DELAY_S + ENTRANCE_WALL_S,
|
||||
ENTRANCE_FX_START_S + fx.TOTAL_S,
|
||||
);
|
||||
|
||||
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();
|
||||
}
|
||||
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();
|
||||
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;
|
||||
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;
|
||||
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; },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// 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`,
|
||||
// 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;
|
||||
|
||||
// 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
|
||||
// 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;
|
||||
@@ -0,0 +1,188 @@
|
||||
// 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 } - 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). Stable
|
||||
// object reference, updated in place. Channels a source does
|
||||
// not drive stay 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)
|
||||
// kickL, kickR one-shot kicks, explicit foot
|
||||
// alternateKick one-shot kick, feet alternated by the game
|
||||
// spawnBall pop / respawn the kickable ball
|
||||
// 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 };
|
||||
|
||||
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;
|
||||
for (const s of this.#sources) {
|
||||
const a = s.axes;
|
||||
if (!a) continue;
|
||||
jaw = Math.max(jaw, a.jaw ?? 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;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
// Gamepad input source (see controller.js for the source interface
|
||||
// contract). Same mapping as the robot runtime (microduck_runtime):
|
||||
//
|
||||
// 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.
|
||||
// X roll (crouch-glide in roller mode - game decides)
|
||||
// Y ball spawn/respawn
|
||||
// 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 / LT analog jaw (max of both); RT edge quacks through a
|
||||
// Schmitt trigger (fire at >= 0.35, re-arm below 0.2 - a
|
||||
// single threshold re-fires on jitter, which is how one
|
||||
// squeeze used to quack several times).
|
||||
|
||||
const PAD_DEADZONE = 0.15;
|
||||
const PAD_ALPHA = 0.12; // EMA smoothing toward the stick target
|
||||
const dz = (v) => (Math.abs(v) < PAD_DEADZONE ? 0 : v);
|
||||
|
||||
// Standard-mapping button indices.
|
||||
const BTN_X = 2, BTN_Y = 3, BTN_LB = 4, BTN_RB = 5, BTN_LT = 6, BTN_RT = 7;
|
||||
const BTN_R3 = 11, BTN_DPAD_UP = 12, BTN_DPAD_DOWN = 13;
|
||||
|
||||
const DPAD_UP_HOLD_MS = 1000; // hold-to-switch-loco duration
|
||||
|
||||
export class GamepadSource {
|
||||
id = "gamepad";
|
||||
connected = false;
|
||||
command = new Float32Array(3); // [vx, 0, wz], EMA-smoothed
|
||||
axes = { jaw: 0, orbitX: 0, orbitY: 0 };
|
||||
pressed = {
|
||||
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
|
||||
#rtArmed = true; // Schmitt trigger state for the RT quack
|
||||
|
||||
constructor({ getVelocityLimits }) {
|
||||
this.#getVelocityLimits = getVelocityLimits;
|
||||
}
|
||||
|
||||
init() {} // poll-based: nothing to attach
|
||||
dispose() {}
|
||||
|
||||
isActive() {
|
||||
return this.#active;
|
||||
}
|
||||
|
||||
poll() {
|
||||
const prev = this.pressed;
|
||||
const gp = [...(navigator.getGamepads?.() ?? [])].find((p) => p && p.connected);
|
||||
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;
|
||||
return;
|
||||
}
|
||||
const now = performance.now();
|
||||
|
||||
// Left stick only: vertical = forward/back, horizontal = turn.
|
||||
// (No strafe; the right stick doesn't drive movement.)
|
||||
const lx = dz(gp.axes[0] ?? 0), ly = dz(gp.axes[1] ?? 0);
|
||||
const up = -ly; // browser sticks report up as -1
|
||||
const [limF, limB, limA] = this.#getVelocityLimits();
|
||||
const target = [
|
||||
up >= 0 ? up * limF : up * -limB,
|
||||
0,
|
||||
-lx * limA,
|
||||
];
|
||||
for (let i = 0; i < 3; i++) this.command[i] += PAD_ALPHA * (target[i] - this.command[i]);
|
||||
// Sticks grab command authority on first input, release when back at
|
||||
// rest (then the keyboard takes over again through the Controller's
|
||||
// arbitration).
|
||||
const stickInput = lx !== 0 || ly !== 0;
|
||||
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);
|
||||
}
|
||||
|
||||
// Right stick: raw (deadzoned) orbit rate. Reported every frame - the
|
||||
// downstream camera step needs the zeros too so a released stick
|
||||
// coasts to a stop.
|
||||
this.axes.orbitX = dz(gp.axes[2] ?? 0);
|
||||
this.axes.orbitY = dz(gp.axes[3] ?? 0);
|
||||
|
||||
// R3 (right stick click): chase-cam toggle, gamepad twin of KeyC.
|
||||
const r3 = !!gp.buttons[BTN_R3]?.pressed;
|
||||
if (r3 && !prev.r3) this.onAction("chaseToggle");
|
||||
prev.r3 = r3;
|
||||
|
||||
const x = !!gp.buttons[BTN_X]?.pressed;
|
||||
if (x && !prev.x) this.onAction("roll");
|
||||
prev.x = x;
|
||||
|
||||
const y = !!gp.buttons[BTN_Y]?.pressed;
|
||||
if (y && !prev.y) this.onAction("spawnBall");
|
||||
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 drive the mouth (max of both); RT quacks on its
|
||||
// Schmitt-triggered rising edge.
|
||||
const rt = gp.buttons[BTN_RT]?.value ?? 0;
|
||||
const lt = gp.buttons[BTN_LT]?.value ?? 0;
|
||||
this.axes.jaw = Math.max(rt, lt);
|
||||
if (this.#rtArmed && rt >= 0.35) {
|
||||
this.onAction("quack");
|
||||
this.#rtArmed = false;
|
||||
} else if (!this.#rtArmed && rt < 0.2) {
|
||||
this.#rtArmed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// 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.
|
||||
const ACTION_KEYS = {
|
||||
KeyB: "spawnBall",
|
||||
KeyC: "chaseToggle",
|
||||
KeyM: "locoToggle",
|
||||
KeyR: "roll",
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
// 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 { STLLoader } from "three/addons/loaders/STLLoader.js";
|
||||
import { mergeVertices, toCreasedNormals } from "three/addons/utils/BufferGeometryUtils.js";
|
||||
|
||||
// Cache-busting version appended to every STL request. python http.server
|
||||
// sends no Cache-Control, so browsers apply heuristic caching keyed on
|
||||
// Last-Modified and can keep serving stale mesh bytes even after the files
|
||||
// change on disk. Bump this whenever the mesh files are regenerated.
|
||||
export const MESH_VERSION = "8";
|
||||
|
||||
// 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 STLs: 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();
|
||||
// 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;
|
||||
}
|
||||
|
||||
// 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 loader = new STLLoader();
|
||||
|
||||
// STL files carry per-facet normals, which shade as a faceted mess.
|
||||
// Weld vertices, then rebuild normals with a crease angle: curved
|
||||
// surfaces smooth out, machined edges stay hard - the cel look needs
|
||||
// both. Two scale/attribute pitfalls here:
|
||||
// - mergeVertices hashes ALL attributes, so the per-facet STL normals
|
||||
// must be dropped first or coincident vertices never merge.
|
||||
// - toCreasedNormals groups vertices on a fixed 0.01-unit hash grid.
|
||||
// Our meshes are in meters, so that grid is 1 cm: normals of vertices
|
||||
// up to a centimeter apart get averaged together, which shades like a
|
||||
// heavily decimated mesh. Scaling to mm makes the grid 10 um.
|
||||
const CREASE = Math.PI / 5; // 36 deg
|
||||
const meshCache = new Map();
|
||||
const loadMesh = (name) => {
|
||||
if (!meshCache.has(name)) {
|
||||
meshCache.set(
|
||||
name,
|
||||
loader.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 meshCache.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 rear top edge of their combined bounding box
|
||||
// (the physical hinge line), and setJawOpen rotates that pivot about the
|
||||
// robot's left-right axis so the beak tip swings down.
|
||||
const JAW_MESH_NAMES = new Set(["jaw.stl", "jaw_soft.stl"]);
|
||||
export const JAW_MAX_OPEN = 0.32; // rad at openness 1
|
||||
|
||||
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 box = new THREE.Box3();
|
||||
for (const m of meshes) box.expandByObject(m);
|
||||
const hingeW = new THREE.Vector3(box.min.x, box.max.y, (box.min.z + box.max.z) / 2);
|
||||
// +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 STL files: 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,
|
||||
};
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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));
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
// 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;
|
||||
|
||||
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 };
|
||||
|
||||
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;
|
||||
|
||||
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.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;",
|
||||
)
|
||||
.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, 0.018, 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 },
|
||||
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;
|
||||
varying vec3 vW;
|
||||
void main() {
|
||||
if (vW.y > uScanY || vW.y < uSolidY) discard;
|
||||
float lead = 1.0 - smoothstep(0.0, 0.06, uScanY - vW.y);
|
||||
float tail = smoothstep(0.0, 0.018, vW.y - uSolidY);
|
||||
float stripes = 0.7 + 0.3 * sin(vW.y * 900.0 - 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));
|
||||
const solidP = ease(clamp01((time - SOLID_DELAY_S) / SOLID_S));
|
||||
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;
|
||||
}
|
||||
|
||||
function arm(nextDir, resetT) {
|
||||
dir = nextDir;
|
||||
if (resetT) t = nextDir > 0 ? 0 : TOTAL_S;
|
||||
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 >= TOTAL_S) {
|
||||
t = TOTAL_S;
|
||||
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) * TOTAL_S;
|
||||
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; },
|
||||
TOTAL_S,
|
||||
};
|
||||
}
|
||||
|
||||
// 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);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,288 @@
|
||||
// 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 TRYSTERO_URL = "https://esm.run/trystero@0.25.3/nostr";
|
||||
const APP_ID = "microduck-sandbox";
|
||||
const ROOM = "lobby";
|
||||
const MAX_GHOSTS = 3;
|
||||
const SEND_HZ = 15;
|
||||
const GHOST_OPACITY = 0.35;
|
||||
// Snapshot interpolation: each ghost renders INTERP_DELAY_MS 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 delay absorbs network jitter; past the newest snapshot the ghost
|
||||
// holds pose, so a background-throttled 1 Hz sender degrades into slow
|
||||
// discrete steps instead of teleports. Nobody synchronizes on ghosts, so
|
||||
// the added latency is invisible.
|
||||
const INTERP_DELAY_MS = 150;
|
||||
const BUF_MAX = 40; // snapshots kept per ghost (~2.5 s at 15 Hz)
|
||||
// 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;
|
||||
};
|
||||
|
||||
export async function initGhosts(env) {
|
||||
const noop = { update() {}, peerCount: () => 0, ghostCount: () => 0, debug: () => [], mapDots: () => [] };
|
||||
let room;
|
||||
try {
|
||||
const { joinRoom } = await import(/* @vite-ignore */ TRYSTERO_URL);
|
||||
room = joinRoom({ appId: APP_ID }, ROOM);
|
||||
} catch (e) {
|
||||
console.warn("ghosts disabled (signaling unavailable):", e);
|
||||
return noop;
|
||||
}
|
||||
|
||||
const { scene, cloneRig, setJoint, setJawOpen, applyVariant, jointNames, getLocalState } = env;
|
||||
// Locomotion-variant rig source: state.l 1 = rollers, 0/absent = legs
|
||||
// (old clients never send it). Falls back to the leg rig when the local
|
||||
// tab hasn't built the roller rig yet - known v1 limitation.
|
||||
const rigFor = (l) => (env.getRigFor ? env.getRigFor(l ?? 0) : env.rig);
|
||||
// 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
|
||||
// Interpolation snapshot: the pose parts of a state message, stamped
|
||||
// with the local arrival time.
|
||||
const snapOf = (state) => ({ p: state.p, j: state.j, w: state.w ?? 0, at: performance.now() });
|
||||
const makeGhost = (state) => {
|
||||
const rig = cloneRig(rigFor(state.l));
|
||||
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: state.l ?? 0,
|
||||
};
|
||||
};
|
||||
|
||||
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();
|
||||
}
|
||||
});
|
||||
ghosts.delete(peerId);
|
||||
};
|
||||
|
||||
// Handler signature in this build: (payload, context) where context is
|
||||
// { peerId } - NOT the bare peerId string of classic trystero.
|
||||
act.onMessage = (state, { peerId }) => {
|
||||
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();
|
||||
g.buf.push(snapOf(state));
|
||||
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: rebuild its ghost on the other rig
|
||||
// (cheap - cloneRig shares geometry). The snapshot buffer carries over
|
||||
// so the interpolated motion stays continuous across the swap.
|
||||
if ((state.l ?? 0) !== g.loco) {
|
||||
const { lastSeen, spawn, revealed, buf } = g;
|
||||
removeGhost(peerId);
|
||||
g = makeGhost(state);
|
||||
Object.assign(g, { lastSeen, spawn, revealed, buf });
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
// Same setter-style registration as onMessage.
|
||||
room.onPeerLeave = (peerId) => removeGhost(peerId);
|
||||
|
||||
// Graceful exit so other tabs drop this ghost immediately...
|
||||
window.addEventListener("pagehide", () => {
|
||||
try { room.leave(); } catch {}
|
||||
});
|
||||
// ...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 setInterval (not rAF) so both keep running
|
||||
// in occluded tabs.
|
||||
setInterval(() => {
|
||||
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);
|
||||
}
|
||||
}, 1000 / 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();
|
||||
return {
|
||||
room,
|
||||
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)
|
||||
.map((g) => ({ x: g.trunk.position.x, y: g.trunk.position.y })),
|
||||
debug: () => [...ghosts.values()].map((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());
|
||||
return { p: g.trunk.position.toArray(), world: w.toArray(), inScene: !!g.rig.placer.parent, revealed: g.revealed, meshes, visible, twins, op, v: g.variant };
|
||||
}),
|
||||
update() {
|
||||
const renderT = performance.now() - INTERP_DELAY_MS;
|
||||
for (const g of ghosts.values()) {
|
||||
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);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
// 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.114, 0.058, 0.578], roughness: 0.4, metalness: 0.0 }; // #6a52c8
|
||||
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 shoe is deliberately identical on all variants: yellow upper
|
||||
// (feet), orange lower (soles).
|
||||
export const VARIANTS = {
|
||||
// Front-center robot: warm gray head, cream body, amber eye, orange
|
||||
// trim and beak.
|
||||
classic: {
|
||||
headDome: CREAM,
|
||||
facePlate: WARM_GRAY,
|
||||
trim: BRIGHT_ORANGE,
|
||||
beakUpper: BRIGHT_ORANGE,
|
||||
beakLower: BRIGHT_ORANGE,
|
||||
tongue: AMBER_YELLOW,
|
||||
eyeRing: AMBER_YELLOW,
|
||||
lens: LENS,
|
||||
bodyShell: CREAM,
|
||||
sideShells: CREAM,
|
||||
legShells: CREAM,
|
||||
feet: BRIGHT_ORANGE,
|
||||
soles: AMBER_ORANGE,
|
||||
hips: GRAY,
|
||||
mechDark: DARK,
|
||||
mechGray: GRAY,
|
||||
},
|
||||
// Front-left robot: charcoal shells, slightly lighter face plate,
|
||||
// amber eye, orange/amber beak.
|
||||
charcoal: {
|
||||
headDome: CHARCOAL,
|
||||
facePlate: CHARCOAL_FACE,
|
||||
trim: BRIGHT_ORANGE,
|
||||
beakUpper: BRIGHT_ORANGE,
|
||||
beakLower: BRIGHT_ORANGE,
|
||||
tongue: AMBER_YELLOW,
|
||||
eyeRing: AMBER_YELLOW,
|
||||
lens: LENS,
|
||||
bodyShell: CHARCOAL_BODY,
|
||||
sideShells: CHARCOAL_BODY,
|
||||
legShells: CHARCOAL_BODY,
|
||||
feet: BRIGHT_ORANGE,
|
||||
soles: AMBER_ORANGE,
|
||||
hips: GRAY,
|
||||
mechDark: DARK,
|
||||
mechGray: GRAY,
|
||||
},
|
||||
// Back-center robot: light warm gray head, purple eye, YELLOW trim and
|
||||
// beak (both plates), cream body.
|
||||
purple: {
|
||||
headDome: LIGHT_WARM_GRAY,
|
||||
facePlate: WARM_GRAY,
|
||||
trim: CLEAN_YELLOW,
|
||||
beakUpper: CLEAN_YELLOW,
|
||||
beakLower: CLEAN_YELLOW,
|
||||
tongue: AMBER_YELLOW,
|
||||
eyeRing: PURPLE_RING,
|
||||
lens: LENS,
|
||||
bodyShell: CREAM,
|
||||
sideShells: CREAM,
|
||||
legShells: CREAM,
|
||||
feet: CLEAN_YELLOW,
|
||||
soles: PURPLE_RING,
|
||||
hips: GRAY,
|
||||
mechDark: DARK,
|
||||
mechGray: GRAY,
|
||||
// UI swatch override: the head is warm gray, but this colourway's
|
||||
// identity is its purple accents - the picker dot shows that.
|
||||
swatch: PURPLE_FEET,
|
||||
},
|
||||
// Right robot: pale blue dome over a medium blue face plate (two
|
||||
// different blues), amber eye, orange/amber beak, blue-gray body.
|
||||
blue: {
|
||||
headDome: PALE_BLUE,
|
||||
facePlate: MEDIUM_BLUE,
|
||||
trim: BRIGHT_ORANGE,
|
||||
beakUpper: BRIGHT_ORANGE,
|
||||
beakLower: BRIGHT_ORANGE,
|
||||
tongue: AMBER_YELLOW,
|
||||
eyeRing: AMBER_YELLOW,
|
||||
lens: LENS,
|
||||
bodyShell: PALE_BLUE,
|
||||
sideShells: PALE_BLUE,
|
||||
legShells: PALE_BLUE,
|
||||
feet: BRIGHT_ORANGE,
|
||||
soles: AMBER_ORANGE,
|
||||
hips: MEDIUM_BLUE,
|
||||
mechDark: DARK,
|
||||
mechGray: GRAY,
|
||||
},
|
||||
};
|
||||
|
||||
export const VARIANT_NAMES = Object.keys(VARIANTS);
|
||||
export const DEFAULT_VARIANT = "classic";
|
||||
|
||||
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: in gray they read as two gray motors,
|
||||
// so both go dark with the motor they hold.
|
||||
"xl330.stl": v.mechDark,
|
||||
"leg.stl": v.mechDark,
|
||||
"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.
|
||||
"yaw2roll.stl": v.mechDark,
|
||||
"bearing_roll.stl": v.mechDark,
|
||||
"neck.stl": v.mechDark,
|
||||
"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()}`;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { ThemeProvider } from "@mui/material/styles";
|
||||
import CssBaseline from "@mui/material/CssBaseline";
|
||||
import { theme } from "./theme.js";
|
||||
import App from "./App.jsx";
|
||||
|
||||
// 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 />
|
||||
<App />
|
||||
</ThemeProvider>,
|
||||
);
|
||||
@@ -0,0 +1,59 @@
|
||||
// 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";
|
||||
|
||||
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 />
|
||||
</Canvas>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// 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",
|
||||
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 });
|
||||
}
|
||||
@@ -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 },
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
// 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 { 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 });
|
||||
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);
|
||||
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);
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
// In-game HUD: Back (top-left), mode readout (top-right, Matrix-style
|
||||
// letter scramble on change), quickbar (bottom-left: live colour dots +
|
||||
// legs/rollers segment), telemetry stack (bottom-right) and the
|
||||
// LOADING ROLLERS line while the roller stack streams in.
|
||||
//
|
||||
// Whole HUD is hidden while the title/pause overlay is up; touch mode
|
||||
// strips it down to the thumbs + Back.
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import Box from "@mui/material/Box";
|
||||
import ButtonBase from "@mui/material/ButtonBase";
|
||||
import { keyframes } from "@mui/material/styles";
|
||||
import { useGame, gameApi } from "../store.js";
|
||||
import { VARIANT_SWATCHES } from "../game/game.js";
|
||||
import { INK, ORANGE, MONO } from "../theme.js";
|
||||
|
||||
// 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(() => {
|
||||
// Letters 0..k-1 are locked; the rest keep boiling.
|
||||
const k = Math.floor(((performance.now() - t0) / DUR) * n);
|
||||
if (k >= n) {
|
||||
clearInterval(timer.current);
|
||||
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; }
|
||||
`;
|
||||
|
||||
function BackButton() {
|
||||
return (
|
||||
<ButtonBase
|
||||
onClick={() => useGame.setState({ menuOpen: true })}
|
||||
sx={{
|
||||
position: "fixed",
|
||||
top: "1.4rem",
|
||||
left: "1.6rem",
|
||||
zIndex: 10,
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
gap: "0.45em",
|
||||
border: "1px solid rgba(255, 255, 255, 0.16)",
|
||||
background: "rgba(8, 8, 12, 0.55)",
|
||||
color: "rgba(255, 255, 255, 0.75)",
|
||||
font: "inherit",
|
||||
fontSize: "0.8rem",
|
||||
fontWeight: 600,
|
||||
letterSpacing: "0.14em",
|
||||
textTransform: "uppercase",
|
||||
p: "0.6rem 1.15rem",
|
||||
borderRadius: "999px",
|
||||
transition: "color 0.15s ease, background 0.15s ease, border-color 0.15s ease",
|
||||
"&:hover": {
|
||||
color: "#fff",
|
||||
borderColor: "rgba(255, 255, 255, 0.4)",
|
||||
background: "rgba(255, 255, 255, 0.06)",
|
||||
},
|
||||
"&.Mui-focusVisible": {
|
||||
outline: `2px solid ${ORANGE}`,
|
||||
outlineOffset: 2,
|
||||
},
|
||||
}}
|
||||
>
|
||||
{"\u2190"} Back
|
||||
</ButtonBase>
|
||||
);
|
||||
}
|
||||
|
||||
// Active policy/mode readout, top-right: bright orange caption over a big
|
||||
// white monospace name.
|
||||
function ModeReadout() {
|
||||
const modeLabel = useGame((s) => s.modeLabel);
|
||||
const text = useScramble(modeLabel);
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
position: "fixed",
|
||||
top: "1.4rem",
|
||||
right: "1.6rem",
|
||||
zIndex: 10,
|
||||
fontFamily: MONO,
|
||||
pointerEvents: "none",
|
||||
textAlign: "right",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
component="span"
|
||||
sx={{
|
||||
display: "block",
|
||||
mb: "0.35rem",
|
||||
fontSize: "0.78rem",
|
||||
fontWeight: 600,
|
||||
letterSpacing: "0.24em",
|
||||
textTransform: "uppercase",
|
||||
color: ORANGE,
|
||||
textShadow: "0 0 10px rgba(255, 122, 47, 0.35)",
|
||||
}}
|
||||
>
|
||||
Mode
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
minWidth: "8ch",
|
||||
minHeight: "1.2em",
|
||||
fontSize: "1.7rem",
|
||||
fontWeight: 600,
|
||||
letterSpacing: "0.16em",
|
||||
textTransform: "uppercase",
|
||||
color: "rgba(255, 255, 255, 0.95)",
|
||||
textAlign: "right",
|
||||
textShadow: "0 0 12px rgba(255, 255, 255, 0.28)",
|
||||
lineHeight: 1.2,
|
||||
}}
|
||||
>
|
||||
{text}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// In-game quick picks, bottom-left: colour dots + legs/rollers, live.
|
||||
// Same pill language as the vitrine DuckPlayground.
|
||||
function Quickbar() {
|
||||
const variant = useGame((s) => s.variant);
|
||||
const locoWant = useGame((s) => s.locoWant);
|
||||
const pill = {
|
||||
display: "inline-flex",
|
||||
gap: "0.24rem",
|
||||
p: "0.26rem",
|
||||
border: "1px solid rgba(255, 255, 255, 0.14)",
|
||||
borderRadius: "999px",
|
||||
background: "rgba(8, 8, 12, 0.55)",
|
||||
};
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
position: "fixed",
|
||||
bottom: "1.4rem",
|
||||
left: "1.6rem",
|
||||
zIndex: 10,
|
||||
display: "flex",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
gap: "0.6rem",
|
||||
}}
|
||||
>
|
||||
<Box role="group" aria-label="Duck colours" sx={pill}>
|
||||
{Object.entries(VARIANT_SWATCHES).map(([name, hex]) => (
|
||||
<ButtonBase
|
||||
key={name}
|
||||
aria-label={`${name} colours`}
|
||||
aria-pressed={name === variant}
|
||||
onClick={() => gameApi.setVariant?.(name)}
|
||||
sx={{
|
||||
height: { xs: "2rem", sm: "2.3rem" },
|
||||
px: { xs: "0.42rem", sm: "0.5rem" },
|
||||
borderRadius: "999px",
|
||||
"&.Mui-focusVisible": { outline: `2px solid ${ORANGE}`, outlineOffset: 2 },
|
||||
"&:hover .dot": { opacity: 1 },
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
className="dot"
|
||||
sx={{
|
||||
width: { xs: "1.2rem", sm: "1.4rem" },
|
||||
height: { xs: "1.2rem", sm: "1.4rem" },
|
||||
borderRadius: "50%",
|
||||
background: hex,
|
||||
opacity: name === variant ? 1 : 0.45,
|
||||
transform: name === variant ? "scale(1.15)" : "none",
|
||||
transition: "transform 0.2s ease, opacity 0.2s ease",
|
||||
}}
|
||||
/>
|
||||
</ButtonBase>
|
||||
))}
|
||||
</Box>
|
||||
<Box role="group" aria-label="Locomotion mode" sx={pill}>
|
||||
{["legs", "rollers"].map((name) => (
|
||||
<ButtonBase
|
||||
key={name}
|
||||
aria-pressed={locoWant === name}
|
||||
onClick={() => gameApi.requestLoco?.(name)}
|
||||
sx={{
|
||||
height: { xs: "2rem", sm: "2.3rem" },
|
||||
px: { xs: "0.8rem", sm: "1.05rem" },
|
||||
borderRadius: "999px",
|
||||
font: "inherit",
|
||||
fontSize: { xs: "0.68rem", sm: "0.76rem" },
|
||||
fontWeight: 600,
|
||||
letterSpacing: "0.14em",
|
||||
textTransform: "uppercase",
|
||||
color: locoWant === name ? ORANGE : "rgba(255, 255, 255, 0.45)",
|
||||
background: locoWant === name ? "rgba(255, 122, 47, 0.14)" : "transparent",
|
||||
transition: "color 0.2s ease, background 0.2s ease",
|
||||
"&.Mui-focusVisible": { outline: `2px solid ${ORANGE}`, outlineOffset: 2 },
|
||||
}}
|
||||
>
|
||||
{name === "legs" ? "Legs" : "Rollers"}
|
||||
</ButtonBase>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// Telemetry stack, bottom-right: peers / speed + odometer / loop rates,
|
||||
// one line each, quietest at the bottom.
|
||||
function Telemetry() {
|
||||
const t = useGame((s) => s.telemetry);
|
||||
const odo = t.odo < 1000 ? `${t.odo.toFixed(1)}M` : `${(t.odo / 1000).toFixed(2)}KM`;
|
||||
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.4rem",
|
||||
right: "1.6rem",
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
// BIOS-style line while the roller variant streams in on first switch.
|
||||
function OsdLoad() {
|
||||
const rollersLoading = useGame((s) => s.rollersLoading);
|
||||
if (!rollersLoading) return null;
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
position: "fixed",
|
||||
top: "6.1rem", // below the mode readout
|
||||
right: "1.6rem",
|
||||
zIndex: 10,
|
||||
fontFamily: MONO,
|
||||
fontSize: "0.68rem",
|
||||
letterSpacing: "0.14em",
|
||||
color: ORANGE,
|
||||
textShadow: "0 0 8px rgba(255, 122, 47, 0.4)",
|
||||
}}
|
||||
>
|
||||
LOADING ROLLERS
|
||||
<Box
|
||||
component="span"
|
||||
sx={{ display: "inline-block", ml: "0.15em", animation: `${recBlink} 0.8s steps(1) infinite` }}
|
||||
>
|
||||
{"\u2588"}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Hud() {
|
||||
const entered = useGame((s) => s.entered);
|
||||
const menuOpen = useGame((s) => s.menuOpen);
|
||||
const touchMode = useGame((s) => s.touchMode);
|
||||
// HUD stays off until the first enter and while the title overlay is up
|
||||
// (the BIOS readout simply covers it during boot, same as before).
|
||||
if (!entered || menuOpen) return null;
|
||||
return (
|
||||
<>
|
||||
<BackButton />
|
||||
{/* Touch mode strips the HUD down to the thumbs: no quickbar, no
|
||||
mode readout, no telemetry. Back stays to reach the menu. */}
|
||||
{!touchMode && (
|
||||
<>
|
||||
<ModeReadout />
|
||||
<Quickbar />
|
||||
<Telemetry />
|
||||
<OsdLoad />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// Pre-boot veil: covers everything until the title page's logo and fonts
|
||||
// are in, so the menu never pops in half-assembled. Light grey spinner,
|
||||
// centered on the ink.
|
||||
import { useEffect, useState } from "react";
|
||||
import Box from "@mui/material/Box";
|
||||
import { keyframes } from "@mui/material/styles";
|
||||
import { useGame } from "../store.js";
|
||||
import { INK } from "../theme.js";
|
||||
|
||||
const spin = keyframes`to { transform: rotate(360deg); }`;
|
||||
|
||||
export default function Preboot() {
|
||||
const prebootDone = useGame((s) => s.prebootDone);
|
||||
const [gone, setGone] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!prebootDone) return;
|
||||
const t = setTimeout(() => setGone(true), 300);
|
||||
return () => clearTimeout(t);
|
||||
}, [prebootDone]);
|
||||
|
||||
if (gone) return null;
|
||||
return (
|
||||
<Box
|
||||
aria-hidden
|
||||
sx={{
|
||||
position: "fixed",
|
||||
inset: 0,
|
||||
zIndex: 40,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
background: INK,
|
||||
opacity: prebootDone ? 0 : 1,
|
||||
pointerEvents: prebootDone ? "none" : "auto",
|
||||
transition: "opacity 0.25s ease",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
width: 22,
|
||||
height: 22,
|
||||
borderRadius: "50%",
|
||||
border: "2px solid rgba(255, 255, 255, 0.14)",
|
||||
borderTopColor: "rgba(255, 255, 255, 0.55)",
|
||||
animation: `${spin} 0.8s linear infinite`,
|
||||
"@media (prefers-reduced-motion: reduce)": {
|
||||
animationDuration: "1.6s",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
// Single-page title / pause menu: vitrine brand lockup, pitch, controls
|
||||
// tutorial (keyboard / gamepad / touch variant) and the CTA. The first
|
||||
// "Waddle in" cues the BIOS; later Esc / the in-game Back button reopen it
|
||||
// as pause. Rows fade up once, in reading order - the stagger replays on
|
||||
// every open because the component remounts.
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import Box from "@mui/material/Box";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import ButtonBase from "@mui/material/ButtonBase";
|
||||
import { keyframes, styled } from "@mui/material/styles";
|
||||
import { useGame } from "../store.js";
|
||||
import { signed } from "../game/signed.js";
|
||||
import { INK, ORANGE } from "../theme.js";
|
||||
|
||||
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; }
|
||||
`;
|
||||
|
||||
// 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)",
|
||||
}));
|
||||
|
||||
const TILES = {
|
||||
kb: [
|
||||
{ caps: "cluster-arrows", name: "Move", hint: "arrows or ZQSD" },
|
||||
{ caps: ["A", "E"], name: "Kick", hint: "left / right" },
|
||||
{ caps: ["R"], name: "Roll", hint: "barrel roll" },
|
||||
{ caps: ["B"], name: "Ball", hint: "pop a fresh one" },
|
||||
{ caps: ["C"], name: "Camera", hint: "toggle chase" },
|
||||
{ caps: ["Space"], name: "Reset", hint: "fresh start" },
|
||||
],
|
||||
pad: [
|
||||
{ caps: ["LS"], name: "Move", hint: "left stick" },
|
||||
{ caps: ["LB", "RB"], name: "Kick", hint: "left / right" },
|
||||
{ caps: ["X"], name: "Roll", hint: "barrel roll" },
|
||||
{ caps: ["Y"], name: "Ball", hint: "pop a fresh one" },
|
||||
{ caps: ["RS"], name: "Camera", hint: "orbit" },
|
||||
{ caps: ["\u2193"], name: "Sit", hint: "stand up" },
|
||||
],
|
||||
touch: [
|
||||
{ caps: ["Stick"], name: "Move", hint: "left thumb" },
|
||||
{ caps: ["A"], round: true, name: "Kick", hint: "tap it" },
|
||||
{ caps: ["B"], round: true, name: "Quack", hint: "hold for beak" },
|
||||
],
|
||||
};
|
||||
const HINTS = {
|
||||
kb: "drag to orbit \u00b7 scroll to zoom",
|
||||
pad: "R3 chase \u00b7 RT quack",
|
||||
touch: "drag to orbit \u00b7 pinch to zoom",
|
||||
};
|
||||
|
||||
function closeMenu() {
|
||||
useGame.setState({ menuOpen: false });
|
||||
if (!useGame.getState().entered) useGame.setState({ entered: true });
|
||||
}
|
||||
|
||||
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 [closing, setClosing] = useState(false);
|
||||
const prevOpen = useRef(menuOpen);
|
||||
|
||||
// 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);
|
||||
}, []);
|
||||
|
||||
if (!menuOpen && !closing) return null;
|
||||
|
||||
// A plugged-in gamepad wins over the touch tutorial.
|
||||
const variant = padConnected ? "pad" : touchMode ? "touch" : "kb";
|
||||
const tiles = TILES[variant];
|
||||
|
||||
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",
|
||||
}}
|
||||
>
|
||||
<Box sx={{ width: "100%", maxWidth: "min(48rem, 92vw)", textAlign: "center" }}>
|
||||
{/* Vitrine brand lockup, centered above the title: drawn duck head
|
||||
+ name. Hovering swaps to the open-beak frame, same hard sprite
|
||||
swap as the vitrine header. */}
|
||||
<Box
|
||||
aria-hidden
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: "0.55rem",
|
||||
mb: "1.3rem",
|
||||
userSelect: "none",
|
||||
...row(0, brandIn),
|
||||
"&:hover .duck-closed": { opacity: 0 },
|
||||
"&:hover .duck-open": { opacity: 1 },
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
component="span"
|
||||
sx={{
|
||||
position: "relative",
|
||||
display: "block",
|
||||
height: { xs: "2.4rem", sm: "3rem" },
|
||||
}}
|
||||
>
|
||||
<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): the dropped jaw sticks out
|
||||
past the head. Offsets pin the head in place 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={{
|
||||
fontWeight: 700,
|
||||
letterSpacing: "-0.03em",
|
||||
fontSize: { xs: "1.3rem", sm: "1.6rem" },
|
||||
color: "#fff",
|
||||
}}
|
||||
>
|
||||
MicroDuck
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: "0.6rem",
|
||||
mb: "1.15rem",
|
||||
fontSize: "0.72rem",
|
||||
fontWeight: 600,
|
||||
letterSpacing: "0.14em",
|
||||
textTransform: "uppercase",
|
||||
color: "rgba(255, 255, 255, 0.78)",
|
||||
...row(0.08),
|
||||
"& span:not(:last-child)::after": {
|
||||
content: '"\u00b7"',
|
||||
color: ORANGE,
|
||||
pl: "0.6em",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<span>MuJoCo physics</span>
|
||||
<span>ONNX policies at 50 Hz</span>
|
||||
</Box>
|
||||
|
||||
{/* Landing-grade h1: same type conventions as the vitrine hero. */}
|
||||
<Typography
|
||||
component="h1"
|
||||
sx={{
|
||||
m: "0 auto",
|
||||
maxWidth: "24ch",
|
||||
fontSize: { xs: "2rem", sm: "clamp(2.4rem, 5vw, 3.75rem)" },
|
||||
fontWeight: 600,
|
||||
letterSpacing: "-0.03em",
|
||||
color: "#fff",
|
||||
lineHeight: 1.02,
|
||||
textWrap: "balance",
|
||||
...row(0.16),
|
||||
}}
|
||||
>
|
||||
The Microduck simulator, live in your browser
|
||||
</Typography>
|
||||
<Typography
|
||||
sx={{
|
||||
mx: "auto",
|
||||
mt: "1.25rem",
|
||||
mb: 0,
|
||||
"@media (max-height: 700px)": { mt: "0.85rem" },
|
||||
maxWidth: "36ch",
|
||||
fontSize: { xs: "0.95rem", sm: "clamp(1.05rem, 1.5vw, 1.3rem)" },
|
||||
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.
|
||||
</Typography>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: {
|
||||
xs: variant === "touch" ? "repeat(3, 1fr)" : "repeat(2, 1fr)",
|
||||
sm: "repeat(3, 1fr)",
|
||||
},
|
||||
gap: "0.55rem",
|
||||
m: "1.4rem auto 0",
|
||||
maxWidth: "36rem",
|
||||
...row(0.32),
|
||||
}}
|
||||
>
|
||||
{tiles.map((t) => (
|
||||
<Box
|
||||
key={t.name}
|
||||
sx={{
|
||||
p: { xs: "0.65rem 0.35rem 0.6rem", sm: "0.85rem 0.45rem 0.75rem" },
|
||||
border: "1px solid rgba(255, 255, 255, 0.08)",
|
||||
borderRadius: "18px",
|
||||
background: "rgba(255, 255, 255, 0.035)",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: "0.2rem",
|
||||
height: { xs: "2.8rem", sm: "3.3rem" },
|
||||
// Arrow cluster keycaps are a notch smaller so two rows fit
|
||||
"& .cluster kbd": {
|
||||
minWidth: "1.4rem",
|
||||
height: "1.4rem",
|
||||
p: "0 0.3rem",
|
||||
fontSize: "0.62rem",
|
||||
},
|
||||
}}
|
||||
>
|
||||
{t.caps === "cluster-arrows" ? (
|
||||
<Box
|
||||
className="cluster"
|
||||
sx={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "0.2rem" }}
|
||||
>
|
||||
<Box sx={{ display: "flex", gap: "0.22rem", justifyContent: "center" }}>
|
||||
<Kbd>{"\u2191"}</Kbd>
|
||||
</Box>
|
||||
<Box sx={{ display: "flex", gap: "0.22rem", justifyContent: "center" }}>
|
||||
<Kbd>{"\u2190"}</Kbd>
|
||||
<Kbd>{"\u2193"}</Kbd>
|
||||
<Kbd>{"\u2192"}</Kbd>
|
||||
</Box>
|
||||
</Box>
|
||||
) : (
|
||||
<Box sx={{ display: "flex", gap: "0.22rem", justifyContent: "center" }}>
|
||||
{t.caps.map((c) => (
|
||||
<Kbd key={c} round={t.round ? 1 : 0}>{c}</Kbd>
|
||||
))}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
mt: "0.55rem",
|
||||
fontSize: "0.72rem",
|
||||
fontWeight: 600,
|
||||
letterSpacing: "-0.01em",
|
||||
color: "#fff",
|
||||
}}
|
||||
>
|
||||
{t.name}
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
mt: "0.18rem",
|
||||
fontSize: "0.62rem",
|
||||
fontWeight: 600,
|
||||
letterSpacing: "0.12em",
|
||||
textTransform: "uppercase",
|
||||
color: ORANGE,
|
||||
}}
|
||||
>
|
||||
{t.hint}
|
||||
</Box>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
|
||||
<Typography
|
||||
sx={{
|
||||
mt: "1rem",
|
||||
fontSize: "0.68rem",
|
||||
fontWeight: 600,
|
||||
letterSpacing: "0.08em",
|
||||
color: "rgba(255, 255, 255, 0.4)",
|
||||
...row(0.48),
|
||||
}}
|
||||
>
|
||||
{HINTS[variant]}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
gap: "1rem",
|
||||
mt: "1.6rem",
|
||||
"@media (max-height: 700px)": { mt: "1.1rem" },
|
||||
width: "100%",
|
||||
...row(0.56),
|
||||
}}
|
||||
>
|
||||
<ButtonBase
|
||||
data-cta="1"
|
||||
onClick={closeMenu}
|
||||
focusRipple
|
||||
sx={{
|
||||
border: `3px solid ${INK}`,
|
||||
background: ORANGE,
|
||||
color: INK,
|
||||
font: "inherit",
|
||||
fontSize: { xs: "0.95rem", sm: "1.02rem" },
|
||||
fontWeight: 600,
|
||||
letterSpacing: "-0.01em",
|
||||
p: { xs: "0.75rem 1.5rem", sm: "0.85rem 1.9rem" },
|
||||
borderRadius: "999px",
|
||||
boxShadow: "0 0 0 3px #fff",
|
||||
cursor: "pointer",
|
||||
transition: "transform 0.2s ease, box-shadow 0.2s ease",
|
||||
"&:hover": {
|
||||
transform: "translateY(-2px)",
|
||||
boxShadow: "0 0 0 3px #fff, 0 10px 26px rgba(255, 122, 47, 0.3)",
|
||||
},
|
||||
"&:active": {
|
||||
transform: "translateY(1px)",
|
||||
boxShadow: "0 0 0 3px #fff",
|
||||
},
|
||||
"&.Mui-focusVisible": {
|
||||
outline: "2px solid #fff",
|
||||
outlineOffset: "4px",
|
||||
},
|
||||
}}
|
||||
>
|
||||
{entered ? "Resume" : "Waddle in"}
|
||||
</ButtonBase>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
// MuJoCo WASM and onnxruntime-web stay on the CDN (dynamic import with
|
||||
// @vite-ignore in game/boot.js), exactly like the pre-Vite app: their
|
||||
// .wasm sidecars resolve relative to the CDN URL and never touch the
|
||||
// bundle.
|
||||
server: {
|
||||
port: 5173,
|
||||
},
|
||||
build: {
|
||||
// Keep the JS/CSS bundle out of dist/assets/: the game's static assets
|
||||
// (public/assets/) land there and must keep their historical URLs.
|
||||
assetsDir: "bundle",
|
||||
chunkSizeWarningLimit: 1500,
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user