feat: playable wheee - pentatonic pressure notes, clean release, jaw sync

LT pressure now picks the wheee note on a major pentatonic octave anchored
below the sample's natural pitch (playbackRate glide, constant gain); the
ride plays the loop segment directly so pitch responds from the first
frame. Release cuts the ride like the robot runtime (no end-segment
retrigger). Both triggers open the beak analogically (visual only). Also
fixes LT/RT trigger cross-talk on pads that mirror a combined trigger
channel, and prefers standard-mapping gamepads.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
tfrere
2026-08-25 20:08:41 +02:00
parent 61550fb935
commit d5db286b9d
3 changed files with 125 additions and 69 deletions
+12 -8
View File
@@ -29,12 +29,14 @@
// 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.
// axes { jaw, orbitX, orbitY, ride } - auxiliary continuous
// channels. jaw in [0, 1] (mouth opening), orbit axes in
// [-1, 1] (camera orbit rate; the inertia/smoothing lives
// downstream in the camera code, sources report raw
// deflection), ride in [0, 1] (LT squeeze pressure, bends
// the wheee note's pitch). Stable object reference, updated
// in place. Channels a source does not drive may be omitted
// (merged as 0).
// pressed Plain object of booleans (stable reference) mirroring which
// physical controls are currently down. HUD highlighting
// only - never game logic.
@@ -93,7 +95,7 @@ export class Controller {
#sources = [];
#listeners = new Map(); // action -> Set(cb)
#locked = false;
#axes = { jaw: 0, orbitX: 0, orbitY: 0 };
#axes = { jaw: 0, orbitX: 0, orbitY: 0, ride: 0 };
constructor({ sources = [] } = {}) {
for (const s of sources) this.addSource(s);
@@ -125,17 +127,19 @@ export class Controller {
// 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;
let jaw = 0, ox = 0, oy = 0, ride = 0;
for (const s of this.#sources) {
const a = s.axes;
if (!a) continue;
jaw = Math.max(jaw, a.jaw ?? 0);
ride = Math.max(ride, a.ride ?? 0);
if (Math.abs(a.orbitX ?? 0) > Math.abs(ox)) ox = a.orbitX;
if (Math.abs(a.orbitY ?? 0) > Math.abs(oy)) oy = a.orbitY;
}
this.#axes.jaw = jaw;
this.#axes.orbitX = ox;
this.#axes.orbitY = oy;
this.#axes.ride = ride;
}
setLocked(v) {
+47 -24
View File
@@ -19,15 +19,21 @@
// 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
// RT analog jaw + quack on the rising edge, through a
// Schmitt trigger (fire at >= 0.35, re-arm below 0.2 - a
// single threshold re-fires on jitter, which is how one
// squeeze used to quack several times). LT additionally
// rides the looping "wheee" (runtime behavior): start on
// the rising edge, stop the instant it releases - same
// Schmitt hysteresis so jitter can't restart the ride.
// The two are mutually exclusive: RT edges are ignored
// while the ride is open, LT edges while RT is engaged.
// squeeze used to quack several times).
// LT rides the looping "wheee": start on the rising edge, cut
// the instant it releases - same Schmitt hysteresis so
// jitter can't restart the ride. The analog pressure is
// reported continuously in `axes.ride` so the game can
// pick the note with the squeeze (pentatonic steps over
// one octave - the trigger is a tiny instrument).
// The two are mutually exclusive: an edge on one trigger
// is CONSUMED while the other is physically down, so one
// squeeze can never fire both sounds - even on pads that
// mirror a combined trigger channel onto both button
// slots (see the trigger block for the tie-break).
const PAD_DEADZONE = 0.15;
const PAD_ALPHA = 0.12; // EMA smoothing toward the stick target
@@ -43,7 +49,7 @@ export class GamepadSource {
id = "gamepad";
connected = false;
command = new Float32Array(3); // [vx, 0, wz], EMA-smoothed
axes = { jaw: 0, orbitX: 0, orbitY: 0 };
axes = { jaw: 0, orbitX: 0, orbitY: 0, ride: 0 };
// Head-mode routing flag, owned by the game (mode state machine lives
// there); while true the sticks fill `head` instead of command/orbit.
headMode = false;
@@ -58,8 +64,8 @@ export class GamepadSource {
#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
#ltDown = false; // LT physical Schmitt state (edge detection)
#rtDown = false; // RT physical Schmitt state (edge detection + gating)
#ltDown = false; // LT physical Schmitt state (edge detection + gating)
#ltRide = false; // wheee ride currently open (LT edge that wasn't blocked)
constructor({ getVelocityLimits }) {
@@ -75,7 +81,12 @@ export class GamepadSource {
poll() {
const prev = this.pressed;
const gp = [...(navigator.getGamepads?.() ?? [])].find((p) => p && p.connected);
// Prefer a standard-mapping pad: the button indices above are only
// guaranteed by the "standard" layout. A non-standard pad (mapping "")
// is a last-resort fallback - its indices are firmware-defined and
// some mirror one combined trigger channel onto both trigger slots.
const pads = [...(navigator.getGamepads?.() ?? [])].filter((p) => p && p.connected);
const gp = pads.find((p) => p.mapping === "standard") ?? pads[0];
this.connected = !!gp;
if (!gp) {
if (this.#active) {
@@ -85,6 +96,7 @@ export class GamepadSource {
}
this.axes.orbitX = 0;
this.axes.orbitY = 0;
this.axes.ride = 0;
this.#zeroHead();
// A pad yanked mid-ride must not leave the wheee looping forever.
if (this.#ltRide) {
@@ -183,31 +195,42 @@ export class GamepadSource {
}
prev.dpadUp = dpadUp;
// Triggers drive the mouth (max of both, like the runtime). Physical
// Schmitt edges are detected first, then the actions are gated so the
// two triggers stay mutually exclusive: an RT edge squeezed while the
// wheee ride is open, or an LT edge while RT is engaged, is CONSUMED -
// releasing the blocker never retro-fires the suppressed action.
// Triggers. Both open the beak analogically - the duck sings the
// wheee with its mouth, wider with the squeeze (jaw is purely visual:
// no sound and no policy input ever reads it, so this can't re-open
// the cross-talk fixed below). Physical Schmitt edges are detected
// first - state must advance even for blocked edges, so releasing a
// blocker never retro-fires the suppressed action - then the actions
// are gated so the two triggers stay mutually exclusive.
const rt = gp.buttons[BTN_RT]?.value ?? 0;
const lt = gp.buttons[BTN_LT]?.value ?? 0;
this.axes.jaw = Math.max(rt, lt);
const rtEdge = this.#rtArmed && rt >= 0.35;
if (rtEdge) this.#rtArmed = false;
else if (!this.#rtArmed && rt < 0.2) this.#rtArmed = true;
this.axes.ride = lt; // raw squeeze, consumed per-frame for the wheee pitch
const rtEdge = !this.#rtDown && rt >= 0.35;
if (rtEdge) this.#rtDown = true;
else if (this.#rtDown && rt < 0.2) this.#rtDown = false;
const ltEdge = !this.#ltDown && lt >= 0.3;
if (ltEdge) this.#ltDown = true;
else if (this.#ltDown && lt < 0.2) this.#ltDown = false;
// RT quack, blocked while the wheee ride is open.
if (rtEdge && !this.#ltRide) this.onAction("quack");
// LT wheee ride: open on the rising edge (runtime threshold ~0.3)
// unless RT is engaged; cut the instant LT drops below the low rail.
if (ltEdge && this.#rtArmed) {
// LT wheee ride first: blocked only if RT was already down BEFORE
// this frame. On pads that mirror one combined trigger channel onto
// both button slots a squeeze raises rt and lt together; treating the
// same-frame rt rise as "engaged" would hand the race to the quack
// (the old bug: LT presses fired RT's sound). The LT edge wins the
// tie deterministically; cut the ride the instant LT drops below the
// low rail.
const rtWasDown = this.#rtDown && !rtEdge;
if (ltEdge && !rtWasDown) {
this.#ltRide = true;
this.onAction("wheeeStart");
} else if (this.#ltRide && !this.#ltDown) {
this.#ltRide = false;
this.onAction("wheeeStop");
}
// RT quack: consumed while LT is down or the ride is open. In the
// mirrored case above the lt rise opened the ride and set #ltDown in
// the same frame, so the phantom rt edge always lands here.
if (rtEdge && !this.#ltDown && !this.#ltRide) this.onAction("quack");
}
#zeroHead() {
+66 -37
View File
@@ -1192,13 +1192,33 @@ async function boot({ scene, camera, renderer }) {
setJawOpen(rig, jawOpenNow());
}
// ── Wheee: LT-held looping ride (runtime behavior) ────────────────────
// start → loop (repeated while the trigger is held) → end, from the same
// per-colourway voice bank as the chirps. Web Audio instead of <audio>:
// the loop segment is crossfade-authored to wrap sample-exactly and the
// start→loop handoff needs sample-accurate scheduling - HTMLAudio's loop
// is neither gap-free nor schedulable.
// ── Wheee: LT-held playable note (sim behavior) ───────────────────────
// The ride plays the voice bank's LOOP segment only (crossfade-authored
// to wrap sample-exactly), faded in over ~20 ms, and the LT analog
// pressure PICKS ITS NOTE: major-pentatonic steps over one octave via
// playbackRate, glided with setTargetAtTime so per-frame updates and
// step changes never zipper or click. The runtime has no pitch feature
// (raw PCM through aplay) - this is the sim's own instrument.
//
// The authored start segment is deliberately NOT played: it is 0.8-0.9 s
// long and cannot be pitch-modulated without breaking the sample-accurate
// start→loop handoff, so with it the first second of every squeeze was
// stuck at base pitch - pressure read as a volume change (the attack's
// own crescendo), not as notes.
//
// Release CUTS the ride and plays nothing else - the runtime kills the
// streaming aplay on the LT falling edge (its end segment never plays on
// the gamepad path), and the sim's old end-segment playback re-attacked
// a note on release, which read as a retriggered sound. A short gain
// ramp stands in for the process kill so Web Audio doesn't click. The
// gain is otherwise CONSTANT - pressure must never track loudness.
const WHEEE_TAKES = "ab";
// Major pentatonic anchored one octave BELOW the sample's natural pitch:
// full squeeze reaches the natural note, casual play sits clearly lower
// (the natural pitch alone read as too shrill). -12 st = playbackRate 0.5.
const WHEEE_SCALE = [-12, -10, -8, -5, -3, 0]; // semitones vs natural pitch
const WHEEE_DEADZONE = 0.05; // squeeze below this is stick noise, maps to the root
const WHEEE_GAIN = 0.7;
let wheeeCtx = null;
const wheeeBufCache = new Map();
let wheeeRide = null; // current ride, null while the trigger is up
@@ -1218,55 +1238,63 @@ async function boot({ scene, camera, renderer }) {
if (wheeeCtx.state === "suspended") wheeeCtx.resume().catch(() => {});
const bank = VOICE_BANK[currentVariant] ?? "duck1";
const take = WHEEE_TAKES[(Math.random() * WHEEE_TAKES.length) | 0];
const ride = { bank, take, startSrc: null, loopSrc: null, gain: null };
const ride = { loopSrc: null, gain: null };
wheeeRide = ride;
const seg = (name) =>
wheeeBuffer(signed(`./assets/voices/${bank}/wheee_${name}_${take}.wav`));
let startBuf, loopBuf;
let loopBuf;
try {
// The end segment is fetched too so it's decoded by release time.
[startBuf, loopBuf] = await Promise.all([seg("start"), seg("loop"), seg("end")]);
loopBuf = await wheeeBuffer(signed(`./assets/voices/${bank}/wheee_loop_${take}.wav`));
} catch {
return; // asset missing / fetch failed: ride silently never starts
}
if (wheeeRide !== ride) return; // released (or replaced) during decode
const gain = wheeeCtx.createGain();
gain.gain.value = 0.7;
gain.connect(wheeeCtx.destination);
const t0 = wheeeCtx.currentTime + 0.02;
const startSrc = wheeeCtx.createBufferSource();
startSrc.buffer = startBuf;
startSrc.connect(gain);
startSrc.start(t0);
// The loop is steady-state audio (no authored attack): a ~20 ms fade-in
// makes a clean note onset instead of a click. Constant gain after that.
gain.gain.setValueAtTime(0, t0);
gain.gain.linearRampToValueAtTime(WHEEE_GAIN, t0 + 0.02);
const loopSrc = wheeeCtx.createBufferSource();
loopSrc.buffer = loopBuf;
loopSrc.loop = true;
loopSrc.connect(gain);
loopSrc.start(t0 + startBuf.duration);
Object.assign(ride, { startSrc, loopSrc, gain });
loopSrc.start(t0);
Object.assign(ride, { loopSrc, gain });
}
function stopWheee({ silent = false } = {}) {
const ride = wheeeRide;
if (!ride) return;
wheeeRide = null;
try { ride.startSrc?.stop(); } catch { /* already ended */ }
try { ride.loopSrc?.stop(); } catch { /* already ended */ }
ride.gain?.disconnect();
// No tail if nothing was heard (released mid-decode) or on replace.
if (silent || !ride.gain) return;
// The end segment has its own onset, playable from any loop point.
wheeeBuffer(signed(`./assets/voices/${ride.bank}/wheee_end_${ride.take}.wav`))
.then((buf) => {
const gain = wheeeCtx.createGain();
gain.gain.value = 0.7;
gain.connect(wheeeCtx.destination);
const src = wheeeCtx.createBufferSource();
src.buffer = buf;
src.connect(gain);
src.onended = () => gain.disconnect();
src.start();
})
.catch(() => {});
// Nothing audible yet (released mid-decode) or replaced by a re-press:
// hard stop is inaudible and frees the nodes immediately.
if (silent || !ride.gain) {
try { ride.loopSrc?.stop(); } catch { /* already ended */ }
ride.gain?.disconnect();
return;
}
// Release: cut the ride, retrigger nothing (runtime kills its player
// here). ~50 ms fade instead of a hard stop so the cut doesn't click.
const t = wheeeCtx.currentTime;
ride.gain.gain.setTargetAtTime(0, t, 0.05);
const stopAt = t + 0.3; // > 5 time constants: fully silent by then
try { ride.loopSrc?.stop(stopAt); } catch { /* already ended */ }
const gain = ride.gain;
setTimeout(() => gain.disconnect(), 400);
}
// Per-frame note picking: the full LT travel (above a small deadzone)
// spans the pentatonic scale, one octave below natural pitch at rest up
// to the natural pitch at full squeeze. Quantized to scale steps so
// squeezing plays NOTES, not a siren; the ~40 ms setTargetAtTime glide
// smooths both the per-frame updates and the step jumps (portamento
// instead of clicks). Digital 0/1 triggers simply play the top note
// (the natural pitch). Gain never tracks pressure.
function driveWheeePitch(pressure) {
const ride = wheeeRide;
if (!ride?.loopSrc) return;
const u = Math.min(1, Math.max(0, (pressure - WHEEE_DEADZONE) / (1 - WHEEE_DEADZONE)));
const semis = WHEEE_SCALE[Math.round(u * (WHEEE_SCALE.length - 1))];
ride.loopSrc.playbackRate.setTargetAtTime(2 ** (semis / 12), wheeeCtx.currentTime, 0.04);
}
// ── Telemetry (throttled into the store) ─────────────────────────────
@@ -1336,6 +1364,7 @@ async function boot({ scene, camera, renderer }) {
function frame(dt) {
controller.update(dt);
padJaw = controller.getAxes().jaw;
driveWheeePitch(controller.getAxes().ride); // no-op while no ride is open
if (padSource.connected !== padWasConnected) {
padWasConnected = padSource.connected;
setStore({ padConnected: padSource.connected });