diff --git a/src/components/frontend/minigames/bomperator/BomperatorGame.tsx b/src/components/frontend/minigames/bomperator/BomperatorGame.tsx index 12d7e0c7..1b9d771d 100644 --- a/src/components/frontend/minigames/bomperator/BomperatorGame.tsx +++ b/src/components/frontend/minigames/bomperator/BomperatorGame.tsx @@ -9,6 +9,7 @@ import { BOMB_FUSE_TICKS, FLAME_LIFETIME_TICKS, GRID_H, GRID_W, MAX_SEATS, MIN_T import { PRED_DEADZONE, PRED_ENVELOPE_BUDGET_MS, + projectServerPosition, } from "@/lib/minigames/bomperator/prediction"; import type { BomperatorTransport } from "./transport"; import { BomperatorHud, seatColor } from "./BomperatorHud"; @@ -858,24 +859,23 @@ export function BomperatorGame({ for (const g of ghostBombsRef.current) { replayBombs.push({ id: `ghost:${g.placedAt}`, x: g.x, y: g.y, ghost: true }); } - let t = now - rtt / 2 - TICK_MS / 2; - let est = { x: me.x, y: me.y }; - let dir = ackedDir; - let facing = me.dir; - for (const p of pending) { - const recv = p.sentAt + rtt / 2; - est = predAdvance( - view.grid, replayBombs, est, dir, facing, me.speed, me.kick, - Math.max(0, Math.min(recv - t, 1000)), - ); - t = recv; - dir = p.dir; - if (p.dir) facing = p.dir; - } - est = predAdvance( - view.grid, replayBombs, est, dir, facing, me.speed, me.kick, - Math.max(0, Math.min(now - t, 1000)), + const projected = projectServerPosition( + view.grid, + replayBombs, + { x: me.x, y: me.y }, + me.dir, + ackedDir, + pending, + me.speed, + me.kick, + rtt, + // Calibrated snapshot age: lands the estimate on the server's + // quantized "now" (half a tick of projection bias). + now - rtt / 2 - TICK_MS / 2, + now, ); + const est = projected.pos; + const facing = projected.facing; const gap = Math.hypot(est.x - pred.x, est.y - pred.y); // Lead-aware correction envelope. The old policy corrected only // once EVERY input was acked, so when the server's tick loop diff --git a/src/lib/minigames/AGENTS.md b/src/lib/minigames/AGENTS.md index 8dddaac9..10ab5bef 100644 --- a/src/lib/minigames/AGENTS.md +++ b/src/lib/minigames/AGENTS.md @@ -11,7 +11,7 @@ Five XP-earning minigames under one parent: routes live at `/minigames/*` (moved - **Call for Fire (artillery observer)**: `/minigames/call-for-fire`, game rules in `src/lib/minigames/call-for-fire.ts` (patrol/checkpoint/compound difficulties, compass bearing observer reports, ADD/DROP + RIGHT/LEFT corrections, scoring/accuracy/XP, injected rng, pure). Components: `src/components/frontend/minigames/call-for-fire/` (`CallForFireArena`, `FireMissionBoard`, `CallForFireLeaderboard`). Action `submitCallForFireResult` validates result bounds, updates profile stats, awards XP + chips, emits `minigame:call-for-fire`, and records the ledger entry (accuracy is distance-to-target on a win, null on a loss). - **Call for Fire: Versus (multiplayer)**: `/minigames/call-for-fire-versus`, category `multiplayer` (out of periods). Pure engine in `src/lib/minigames/call-for-fire-versus/` (`engine.ts`, `views.ts`, `types.ts`, `constants.ts`; client-safe) plus a server-only in-memory match registry in `registry.ts` (mirrors `blackjack/tables.ts`: `globalThis`-anchored Map, lobby, per-turn timeout, expiry sweep, SINGLE-INSTANCE ONLY). Each player hides a FOB fleet, then alternates fire corrections (first shot is a grid designation, later shots adjust from the last impact). `views.ts` builds per-viewer snapshots that never serialize the opponent's fleet. Client polls `fetchVersusMatch` (the in-memory SSE bus is unreliable across dev module copies, same as blackjack). Rewards on completion via `stats.ts` (`minigame:call-for-fire-versus`, profile group `callForFireVersus`). - **Ordnance Disposal (multiplayer, real-time)**: `/minigames/bomperator` (internal key `bomperator`, label "Ordnance Disposal"), category `multiplayer` (out of periods), a 2-8 player free-for-all Bomberman-style charge-clearing drill. Same pure-engine + in-memory-registry split as CFF versus, but upgraded from turn-based to a **fixed ~20 Hz tick loop** (was ~10 Hz until v0.12.3; every tick-denominated constant doubles with the rate so real-world durations stay identical): `src/lib/minigames/bomperator/{constants,types,engine,views}.ts` are pure/client-safe (seeded RNG via `state.rngState`/`gridSeed`; `generateGrid`, `createMatchState`, `startRound`, `applyInput`, `tick`), and `registry.ts` runs one `setInterval(TICK_MS)` per live match (started on `startMatch`, cleared on complete/dissolve; `globalThis.__bomperatorMatches`; SINGLE-INSTANCE ONLY: a restart/redeploy kills live matches). Grid is 15x13 (border + even/even pillars + seeded crates with one hidden power-up each; four classic pickups bomb/range/speed/kick). Movement is grid-locked with sub-cell interpolation; charges fuse ~2.5s, cross-flames stop at walls, destroy crates, chain-detonate, and kick-push; round ends at <=1 alive; sudden death spawns random-cell explosions after the 150s timer, with a draw guard. FFA has no hidden info so `buildBomperatorView` serves every viewer the same board (`yourSeat: null` = spectator). Clients POST inputs (`sendBomperatorInput`, rate-limited 40/s) and poll `fetchBomperatorMatch` (~500ms fallback behind the SSE stream); a rolling event buffer (monotonic ids) drives client SFX without diffing. Disconnects hold the seat for `RECONNECT_WINDOW_MS` then eliminate; below two active seats the match dissolves. Rewards on completion via `stats.ts` (`minigame:bomperator`, profile group `bomperator`: matchesPlayed/matchWins/roundsWon/kills/xpEarned; XP win/loss base + per-kill bounty, chips auto-derived). Registry row ships `status: "upcoming"` (page renders `MinigameComingSoon` until an admin flips it active). - - **Client prediction & correction**: `BomperatorGame.tsx` predicts its own seat between snapshots and reconciles with a lead-aware envelope policy (helpers in `bomperator/prediction.ts`): gaps inside `max(PRED_DEADZONE, speed*(rttEnv/2 + TICK_MS/2 + PRED_ENVELOPE_BUDGET_MS)/1000)` ride untouched, anything beyond is trimmed by at most 0.35 cells per snapshot (a run-speed glide, never a one-frame pull), and gaps past 2.5 cells ease toward the estimate at up to 2.5x run speed instead of teleporting (round resets still snap via the ack-backwards branch). `rttEnv` is `min(300, max(rtt, ackLat - rtt))`: transport RTT plus the server-side share of the measured input-to-ack EMA, because ping/pong alone omits the tick queue and snapshot turnaround (sizing from ping alone put the envelope under the real gap noise floor). Prediction advances by real elapsed time with a 1s sanity cap, so a main-thread hitch does not leave a permanent gap (the engine runs on wall clock); correction easing keeps its own 100ms slice so one catch-up frame cannot discharge a whole gap. A hidden tab releases held keys (input is level-triggered, so the server would otherwise keep running the player). Optimistic ghost charges are replayed in BOTH the local prediction and the server estimate. Root cause of the old teleport-back: Node event-loop stalls make the server's 20Hz tick loop DROP setInterval callbacks (no catch-up), so the sim permanently lags wall clock; the old all-inputs-acked pull let that gap stack and discharge at once. `tests/int/bomperator-prediction.int.spec.ts` is an offline deterministic harness (real engine + modeled network + frame-by-frame reconcile mirror) including production-latency replay (`tests/fixtures/bomperator-prod-rtt.json`, from HAR) and a server-stall A/B proof; change client prediction in BOTH component and mirror, and run the trace scenarios before shipping. v0.12.4 lesson (reverted in v0.12.5): do not add mechanisms that trust precise latency estimates (decision nudges, projected ghost placement); real TTFB swings 31-463ms and they glitch under it. + - **Client prediction & correction**: `BomperatorGame.tsx` predicts its own seat between snapshots and reconciles with a lead-aware envelope policy (helpers in `bomperator/prediction.ts`): gaps inside `max(PRED_DEADZONE, speed*(rttEnv/2 + TICK_MS/2 + PRED_ENVELOPE_BUDGET_MS)/1000)` ride untouched, anything beyond is trimmed by at most 0.35 cells per snapshot (a run-speed glide, never a one-frame pull), and gaps past 2.5 cells ease toward the estimate at up to 2.5x run speed instead of teleporting (round resets still snap via the ack-backwards branch). `rttEnv` is `min(300, max(rtt, ackLat - rtt))`: transport RTT plus the server-side share of the measured input-to-ack EMA, because ping/pong alone omits the tick queue and snapshot turnaround (sizing from ping alone put the envelope under the real gap noise floor). Prediction advances by real elapsed time with a 1s sanity cap, so a main-thread hitch does not leave a permanent gap (the engine runs on wall clock); correction easing keeps its own 100ms slice so one catch-up frame cannot discharge a whole gap. A hidden tab releases held keys (input is level-triggered, so the server would otherwise keep running the player). Optimistic ghost charges are replayed in BOTH the local prediction and the server estimate. The estimator's replay clock only moves FORWARD: an unacknowledged input older than the snapshot contributes its direction, never its age (rewinding the clock let a stale 400ms keepalive inflate the estimate by up to 4 cells, which the reconcile then chased). Root cause of the old teleport-back: Node event-loop stalls make the server's 20Hz tick loop DROP setInterval callbacks (no catch-up), so the sim permanently lags wall clock; the old all-inputs-acked pull let that gap stack and discharge at once. `tests/int/bomperator-prediction.int.spec.ts` is an offline deterministic harness (real engine + modeled network + frame-by-frame reconcile mirror) including production-latency replay (`tests/fixtures/bomperator-prod-rtt.json`, from HAR) and a server-stall A/B proof; change client prediction in BOTH component and mirror, and run the trace scenarios before shipping. v0.12.4 lesson (reverted in v0.12.5): do not add mechanisms that trust precise latency estimates (decision nudges, projected ghost placement); real TTFB swings 31-463ms and they glitch under it. - **Arena transport (WebSocket match replication)**: when `NEXT_PUBLIC_ARENA_URL` is baked into the bundle, the client tries a dedicated arena process first (`src/arena/`, Node 22 + `ws`, Coolify service #2, Docker target `runner-arena`): its own event loop runs the 20 Hz tick via a drift-corrected `setTimeout` chain (capped catch-up, `tick-drift` log every 30s), inputs/snapshots ride one socket (`src/arena/protocol.ts`), and RTT comes from 2s ping/pong instead of POST timing. Transport selection lives in `components/frontend/minigames/bomperator/transport.ts`: WS first, automatic fallback to the unchanged HTTP path (registry actions + SSE + slow poll) after 2 connection failures or a 5s setup timeout; absent `NEXT_PUBLIC_ARENA_URL` = pure HTTP (kill switch/rollback). Server side, `ARENA_SECRET` + `ARENA_INTERNAL_URL` make the bomperator actions proxy the lifecycle to the arena (match ownership moves); the arena holds NO Payload dependency: auth is 30s jose tickets `{uid, matchId, iat}` minted by `createArenaTicket` (query string on the WS handshake; no replay store by design), awards go back through `POST /api/minigames/bomperator/results` (secret header, idempotent by matchId). **Restarting the arena kills live matches** (process memory, like the SSE bus before it; acceptable for ~90s matches). The seq/lastInputSeq pending ledger and envelope reconcile work over both transports; the prediction harness pins the low-latency end too ("ws-grade latency" scenario). - **Mobile / touch input**: `BomperatorTouchControls.tsx` renders a D-pad (+ stop) and plant button on coarse pointers only (`(pointer: coarse)`); the board itself accepts swipes (dominant-axis cardinal, sets direction) and taps (stop). ALL input sources feed the same `pressDir`/`releaseDir`/`stopAll` edge callbacks in `BomperatorGame.tsx` that keyboard uses, so prediction/keepalive/pending logic stays source-agnostic; held-stack priority makes D-pad + swipe coexist. Canvas is CSS-scaled (`w-full h-auto`, max 520px wrapper) with fixed internal resolution. Backgrounded-tab safety is harness-proven ("backgrounded tab" scenario: 4s rAF freeze under prod trace replay, teleports=0). E2E smoke: `tests/e2e/bomperator-mobile.e2e.spec.ts` (phone viewport, no horizontal overflow); run with `E2E_BROWSER_PATH=` when Vivaldi crashes. - Leaderboards match active players by user id (not display name) — see commit 72715c4 if leaderboard queries look wrong. diff --git a/src/lib/minigames/bomperator/prediction.ts b/src/lib/minigames/bomperator/prediction.ts index 67f58420..524b7e5d 100644 --- a/src/lib/minigames/bomperator/prediction.ts +++ b/src/lib/minigames/bomperator/prediction.ts @@ -238,17 +238,27 @@ export function projectServerPosition( for (const p of pending) { const recv = p.sentAt + rttAvg / 2; if (recv >= targetMs) break; - pos = predAdvance( - grid, - bombs, - pos, - dir, - facing, - speed, - kick, - Math.max(0, Math.min(recv - t, 1000)), - ); - t = recv; + // Advance time FORWARD only. An unacknowledged input older than the + // snapshot's own clock was already received before that snapshot was built + // (its seq just has not come back in the ack yet), so its direction is + // current but replaying it must not rewind `t`. Rewinding made the trailing + // segment below span the input's whole age, so every stale keepalive + // inflated the estimate by up to the 400ms re-assert cadence: a phantom + // lead of 1-4 cells that the reconcile then chased (prod telemetry showed + // gap p50 1.0, p95 4.1, 22% of snapshots easing, with zero frame hitches). + if (recv > t) { + pos = predAdvance( + grid, + bombs, + pos, + dir, + facing, + speed, + kick, + Math.min(recv - t, 1000), + ); + t = recv; + } dir = p.dir; if (p.dir) facing = p.dir; } diff --git a/tests/int/bomperator-prediction.int.spec.ts b/tests/int/bomperator-prediction.int.spec.ts index 1fb480a3..7f387308 100644 --- a/tests/int/bomperator-prediction.int.spec.ts +++ b/tests/int/bomperator-prediction.int.spec.ts @@ -862,3 +862,46 @@ describe("bomperator prediction harness", () => { expect(after.deaths).toBe(0); }); }); + +describe("projectServerPosition time base", () => { + const openGrid = () => new Array(GRID_W * GRID_H).fill(0) as number[]; + + it("does not replay the age of an unacknowledged input older than the snapshot", () => { + const T = 10_000; + const projected = projectServerPosition( + openGrid(), + [], + { x: 5, y: 6 }, + "right", + "right", + [{ seq: 9, dir: "right", sentAt: T - 300 }], + 7, + false, + 4, + T, + T + 5, + ); + // 5ms of travel, not 305: rewinding `t` to T-300 made the trailing segment + // span the keepalive's whole age (2.1 cells of phantom lead at 7 cells/s). + expect(projected.pos.x).toBeCloseTo(5.035, 3); + expect(projected.pos.x).toBeLessThan(5.1); + }); + + it("still advances through inputs received after the snapshot clock", () => { + const T = 10_000; + const projected = projectServerPosition( + openGrid(), + [], + { x: 5, y: 6 }, + "right", + "right", + [{ seq: 9, dir: "right", sentAt: T - 10 }], + 7, + false, + 4, + T, + T + 40, + ); + expect(projected.pos.x).toBeCloseTo(5.28, 2); + }); +});