1
0
Fork 0

feat(minigames): make Ordnance Disposal movement feel instant

The client rendered the local technician only from server round trips, so
every keypress showed up RTT + tick + easing late (roughly 250-500ms in
production, per HAR analysis of a live playtest). Two changes, shipped
together:

Direction edges now fire immediately with a monotonic seq instead of queueing
behind an in-flight POST. The registry applies only strictly newer seqs, so
out-of-order action POSTs can never resurrect a stale intent, and echoes the
last applied seq back in every snapshot for client reconciliation.

The client predicts its own seat locally with a line-level port of the
engine's movement rule (align-first turns, blocked settle, slip-to-rest,
kick-push with an optimistic overlay) and reconciles per snapshot by
replaying unacknowledged inputs forward from the server position, timed by
send time plus measured latency, instead of snapping toward a stale sample.
A soft 20%/frame correction absorbs sub-cell error; teleports and round
resets still snap.
This commit is contained in:
Jason Fraley 2026-10-16 01:41:19 -04:00
parent 535a5208da
commit 7935e857af
4 changed files with 345 additions and 44 deletions

View file

@ -5,7 +5,7 @@ import { Eye, Flag, Play, Radio, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import type { BomperatorView, Dir, PlayerView } from "@/lib/minigames/bomperator/types";
import { GRID_H, GRID_W, MAX_SEATS, MIN_TO_START, TICKS_PER_SECOND } from "@/lib/minigames/bomperator/constants";
import { GRID_H, GRID_W, MAX_SEATS, MIN_TO_START, TICK_MS, TICKS_PER_SECOND } from "@/lib/minigames/bomperator/constants";
import { sendBomperatorInput } from "@/app/(frontend)/minigames/bomperator/actions";
import { BomperatorHud, seatColor } from "./BomperatorHud";
import { useBomperatorSounds } from "./sounds";
@ -40,6 +40,147 @@ interface RenderPos {
y: number;
}
/* ----- client-side prediction: replicate the engine's grid-locked movement ----- */
const PRED_DIR_VEC: Record<Dir, readonly [number, number]> = {
up: [0, -1],
down: [0, 1],
left: [-1, 0],
right: [1, 0],
};
const PRED_EPS = 1e-6;
interface PredictBomb {
id: string;
x: number;
y: number;
}
function predCellCentered(x: number, y: number): boolean {
return Math.abs(x - Math.round(x)) < PRED_EPS && Math.abs(y - Math.round(y)) < PRED_EPS;
}
function predApproach(current: number, target: number, step: number): number {
const delta = target - current;
if (Math.abs(delta) <= step) return target;
return current + Math.sign(delta) * step;
}
function predBombAt(bombs: readonly PredictBomb[], x: number, y: number): PredictBomb | undefined {
return bombs.find((b) => b.x === x && b.y === y);
}
function predOpen(grid: readonly number[], x: number, y: number): boolean {
return x >= 0 && y >= 0 && x < GRID_W && y < GRID_H && grid[y * GRID_W + x] === 0;
}
function predCanStand(grid: readonly number[], bombs: readonly PredictBomb[], x: number, y: number): boolean {
return predOpen(grid, x, y) && !predBombAt(bombs, x, y);
}
/**
* One small advance step mirroring the engine's advancePlayer exactly: finish
* aligning the perpendicular axis first, then move toward the adjacent cell
* center; a charge blocks unless kick-capable (then it slides one cell forward,
* recorded into the mutable bombs list).
*/
function predStep(
grid: readonly number[],
bombs: PredictBomb[],
x0: number,
y0: number,
dir: Dir,
kick: boolean,
step: number,
): RenderPos {
const [dx, dy] = PRED_DIR_VEC[dir];
let x = x0;
let y = y0;
if (dx !== 0) {
if (Math.abs(y - Math.round(y)) > PRED_EPS) {
const ty = Math.round(y);
y += Math.sign(ty - y) * Math.min(Math.abs(ty - y), step);
if (Math.abs(ty - y) < PRED_EPS) y = ty;
return { x, y };
}
const cy = Math.round(y);
const entering = dx > 0 ? Math.floor(x) + 1 : Math.ceil(x) - 1;
const home = dx > 0 ? Math.floor(x + PRED_EPS) : Math.ceil(x - PRED_EPS);
const bomb = predBombAt(bombs, entering, cy);
if (bomb) {
if (kick) {
const bx = entering + dx;
if (predOpen(grid, bx, cy) && !predBombAt(bombs, bx, cy)) {
bomb.x = bx;
bomb.y = cy;
return { x: predApproach(x, entering, step), y };
}
}
return { x: home, y };
}
if (!predCanStand(grid, bombs, entering, cy)) return { x: home, y };
return { x: predApproach(x, entering, step), y };
}
if (Math.abs(x - Math.round(x)) > PRED_EPS) {
const tx = Math.round(x);
x += Math.sign(tx - x) * Math.min(Math.abs(tx - x), step);
if (Math.abs(tx - x) < PRED_EPS) x = tx;
return { x, y };
}
const cx = Math.round(x);
const entering = dy > 0 ? Math.floor(y) + 1 : Math.ceil(y) - 1;
const home = dy > 0 ? Math.floor(y + PRED_EPS) : Math.ceil(y - PRED_EPS);
const bomb = predBombAt(bombs, cx, entering);
if (bomb) {
if (kick) {
const by = entering + dy;
if (predOpen(grid, cx, by) && !predBombAt(bombs, cx, by)) {
bomb.x = cx;
bomb.y = by;
return { x, y: predApproach(y, entering, step) };
}
}
return { x, y: home };
}
if (!predCanStand(grid, bombs, cx, entering)) return { x, y: home };
return { x, y: predApproach(y, entering, step) };
}
/**
* Advance over `durationMs` in small slices, honoring the engine's slip-to-rest:
* with no active direction the technician keeps traveling in `facing` until it
* lands exactly on a cell center; a blocked cell settles it back to the one it
* was leaving, where it then stays.
*/
function predAdvance(
grid: readonly number[],
bombs: PredictBomb[],
start: RenderPos,
dir: Dir | null,
facing: Dir,
speed: number,
kick: boolean,
durationMs: number,
): RenderPos {
let { x, y } = start;
let remaining = Math.min(durationMs, 1500);
let guard = 0;
while (remaining > 0.5 && guard < 120) {
guard += 1;
const slice = Math.min(remaining, 16);
const step = (speed * slice) / 1000;
const effDir = dir ?? (predCellCentered(x, y) ? null : facing);
if (!effDir) break;
const res = predStep(grid, bombs, x, y, effDir, kick, step);
const moved = Math.abs(res.x - x) > 1e-9 || Math.abs(res.y - y) > 1e-9;
x = res.x;
y = res.y;
if (!moved) break; // settled against a blocked cell
remaining -= slice;
}
return { x, y };
}
/* ------------------------------------------------------------- draw helpers */
function drawFloor(ctx: CanvasRenderingContext2D) {
@ -218,6 +359,16 @@ export function BomperatorGame({
const renderPosRef = useRef<Map<number, RenderPos>>(new Map());
const heldKeysRef = useRef<Dir[]>([]);
const [starting, setStarting] = useState(false);
/* ---- client-side prediction state (own seat only) ---- */
const predRef = useRef<RenderPos | null>(null);
const facingRef = useRef<Dir>("down");
const inputSeqRef = useRef(0);
const pendingRef = useRef<Array<{ seq: number; dir: Dir | null; sentAt: number }>>([]);
const pushOverlayRef = useRef<Map<string, { x: number; y: number; at: number }>>(new Map());
const lastAckRef = useRef(0);
const lastAckedDirRef = useRef<Dir | null>(null);
const lastVersionSeenRef = useRef(-1);
const rttAvgRef = useRef(100);
useEffect(() => {
matchRef.current = match;
@ -242,40 +393,36 @@ export function BomperatorGame({
}
}, [match.matchId, playPlace]);
/**
* Fire a direction change immediately with a monotonic seq. The server drops
* anything at or below the last applied seq, so there is no reason to queue
* behind an in-flight POST: the newest intent always wins on the wire, and a
* direction change costs one round trip instead of up to two. Human key edges
* are inherently rate-limited, so this cannot flood the way the old unbounded
* intervals did. Each send also feeds a rolling RTT estimate for prediction.
*/
const sendDir = useCallback(
(dir: Dir | null) => {
const seq = (inputSeqRef.current += 1);
const pending = pendingRef.current;
pending.push({ seq, dir, sentAt: performance.now() });
if (pending.length > 64) pending.splice(0, pending.length - 64);
const t0 = performance.now();
void sendBomperatorInput(match.matchId, { dir, seq })
.catch(() => undefined)
.finally(() => {
rttAvgRef.current = rttAvgRef.current * 0.8 + (performance.now() - t0) * 0.2;
});
},
[match.matchId],
);
useEffect(() => {
if (!canControl) return;
// Level-triggered movement: the server keeps applying the last direction we
// sent until we send a different one, so we only transmit on change (edge),
// plus a slow re-assert while a key is held to recover a lost packet. A single
// in-flight request with coalescing means inputs never stack behind each other
// or behind polls, which is what kept them seconds behind under load.
let desired: Dir | null = null;
let sending = false;
let pending = false;
const flush = () => {
if (sending) {
pending = true;
return;
}
sending = true;
const dir = desired;
void sendBomperatorInput(match.matchId, { dir })
.catch(() => undefined)
.finally(() => {
sending = false;
if (pending) {
pending = false;
flush();
}
});
};
const setDir = (dir: Dir | null) => {
desired = dir;
flush();
};
// sent until we send a different one, so we transmit on change (edge), plus
// a slow re-assert while a key is held to recover a lost packet.
const onKeyDown = (e: KeyboardEvent) => {
if (e.repeat) return;
if (e.code === "Space") {
@ -287,13 +434,13 @@ export function BomperatorGame({
if (!dir) return;
e.preventDefault();
heldKeysRef.current = [dir, ...heldKeysRef.current.filter((d) => d !== dir)];
setDir(dir);
sendDir(heldKeysRef.current[0] ?? null);
};
const onKeyUp = (e: KeyboardEvent) => {
const dir = KEY_DIR[e.code];
if (!dir) return;
heldKeysRef.current = heldKeysRef.current.filter((d) => d !== dir);
setDir(heldKeysRef.current[0] ?? null);
sendDir(heldKeysRef.current[0] ?? null);
};
window.addEventListener("keydown", onKeyDown, { capture: true });
window.addEventListener("keyup", onKeyUp, { capture: true });
@ -301,7 +448,8 @@ export function BomperatorGame({
// Slow re-assert, only while actually holding a direction. An idle tab sends
// nothing, so it adds zero load.
const keepalive = window.setInterval(() => {
if (desired !== null) flush();
const held = heldKeysRef.current[0] ?? null;
if (held !== null) sendDir(held);
}, 400);
return () => {
@ -310,9 +458,9 @@ export function BomperatorGame({
window.clearInterval(keepalive);
heldKeysRef.current = [];
};
}, [canControl, match.matchId, sendDrop]);
}, [canControl, match.matchId, sendDrop, sendDir]);
/* ---- render loop: ease toward the latest snapshot each frame ---- */
/* ---- render loop: predict our own seat, ease the rest toward snapshots ---- */
useEffect(() => {
if (!hasBoard) return;
@ -331,17 +479,132 @@ export function BomperatorGame({
let last = performance.now();
const step = (now: number) => {
raf = requestAnimationFrame(step);
const dt = Math.min((now - last) / 16.6667, 3);
const rawDt = now - last;
last = now;
const dt = Math.min(rawDt / 16.6667, 3);
const dtMs = Math.min(rawDt, 100);
const view = matchRef.current;
const pos = renderPosRef.current;
const ease = Math.min(1, 0.4 * dt);
// Ease every technician toward its authoritative server position. Monotonic
// (never overshoots a collision-valid target), so it cannot jitter or show a
// technician inside a wall. A large gap snaps instead of sliding across the
// map (round resets / teleports).
const mySeat = view.yourSeat;
const me = mySeat !== null ? (view.players[mySeat] ?? null) : null;
const overlay = pushOverlayRef.current;
// Working bomb set for prediction + drawing: server truth plus optimistic
// kick-pushes we have made that the server has not confirmed yet.
const bombsWorking: PredictBomb[] = view.bombs.map((b) => {
const to = overlay.get(b.id);
return { id: b.id, x: to?.x ?? b.x, y: to?.y ?? b.y };
});
/* -- local prediction: our own technician answers the keyboard immediately -- */
if (view.phase === "battle" && me && me.alive) {
if (predRef.current === null) predRef.current = { x: me.x, y: me.y };
const held = heldKeysRef.current[0] ?? null;
if (held) facingRef.current = held;
predRef.current = predAdvance(
view.grid,
bombsWorking,
predRef.current,
held,
facingRef.current,
me.speed,
me.kick,
dtMs,
);
// Record any optimistic push so collision and drawing agree next frame.
for (const b of bombsWorking) {
const orig = view.bombs.find((vb) => vb.id === b.id);
if (orig && (orig.x !== b.x || orig.y !== b.y)) overlay.set(b.id, { x: b.x, y: b.y, at: now });
}
} else {
// Not controlling (between rounds, dead, or spectating): no prediction,
// and no stale inputs may replay into the next round's spawn position.
predRef.current = null;
pendingRef.current = [];
overlay.clear();
}
/* -- reconcile against the server once per fresh snapshot -- */
if (view.version !== lastVersionSeenRef.current) {
lastVersionSeenRef.current = view.version;
if (me) {
const ack = me.lastInputSeq ?? 0;
if (ack < lastAckRef.current) {
// Ack moved backwards: the server rebuilt state (round reset). Snap.
pendingRef.current = [];
overlay.clear();
predRef.current = me.alive ? { x: me.x, y: me.y } : null;
facingRef.current = me.dir;
lastAckedDirRef.current = null;
} else {
// Drop acknowledged inputs; the newest one is the dir the server is
// now applying. Note a release (null) counts as a real direction.
let ackedDir = lastAckedDirRef.current;
const pending = pendingRef.current;
while (pending.length > 0) {
const head = pending[0];
if (!head || head.seq > ack) break;
ackedDir = head.dir;
pending.shift();
}
lastAckedDirRef.current = ackedDir;
// Prune optimistic pushes the server has caught up to, plus any a
// rejected push left stranded (server never agreed within 1.5s).
for (const [id, to] of overlay) {
const b = view.bombs.find((vb) => vb.id === id);
if (!b || (b.x === to.x && b.y === to.y) || now - to.at > 1500) overlay.delete(id);
}
if (me.alive && predRef.current) {
const pred = predRef.current;
// Estimate where the server really is NOW: start from its snapshot
// position and replay every input it has not yet acknowledged,
// timed by our send times plus the measured one-way latency.
const rtt = rttAvgRef.current;
const replayBombs: PredictBomb[] = view.bombs.map((b) => {
const to = overlay.get(b.id);
return { id: b.id, x: to?.x ?? b.x, y: to?.y ?? b.y };
});
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 gap = Math.hypot(est.x - pred.x, est.y - pred.y);
if (gap > 2.5) {
// Teleport/respawn: snap instead of sliding across the map.
predRef.current = est;
facingRef.current = facing;
} else if (gap > 1e-4) {
// Soft correction: prediction error decays smoothly, no snap-back.
pred.x += (est.x - pred.x) * 0.2;
pred.y += (est.y - pred.y) * 0.2;
}
}
}
lastAckRef.current = ack;
}
}
// Ease every OTHER technician toward its authoritative server position.
// Monotonic (never overshoots a collision-valid target); a large gap snaps
// instead of sliding across the map (round resets / teleports).
for (const player of view.players) {
if (predRef.current && mySeat !== null && player.seat === mySeat) continue;
const target = { x: player.x, y: player.y };
const current = pos.get(player.seat);
if (!current) {
@ -367,10 +630,17 @@ export function BomperatorGame({
}
}
for (const drop of view.drops) drawDrop(ctx, drop.x, drop.y, drop.kind, now);
for (const bomb of view.bombs) drawBomb(ctx, bomb.x, bomb.y, bomb.fuseTicks, now);
for (const bomb of view.bombs) {
const w = bombsWorking.find((wb) => wb.id === bomb.id);
drawBomb(ctx, w?.x ?? bomb.x, w?.y ?? bomb.y, bomb.fuseTicks, now);
}
for (const flame of view.flames) drawFlame(ctx, flame.x, flame.y, flame.ticksLeft, now);
for (const player of view.players) {
const rp = pos.get(player.seat) ?? { x: player.x, y: player.y };
const isMe = mySeat !== null && player.seat === mySeat;
const rp =
isMe && predRef.current
? predRef.current
: (pos.get(player.seat) ?? { x: player.x, y: player.y });
drawPlayer(ctx, rp, player, String(player.userId) === String(currentUserId));
}
};

View file

@ -270,6 +270,12 @@ export function startRound(state: BomperatorState, seedOverride?: number): Bompe
export interface BomperatorInput {
readonly dir?: Dir | null;
readonly drop?: boolean;
/**
* Client-issued sequence number. The registry applies only strictly newer
* values so direction POSTs that arrive out of order (the client now fires
* them immediately rather than queueing) can never resurrect a stale intent.
*/
readonly seq?: number;
}
/**

View file

@ -65,6 +65,8 @@ interface BomperatorMatchRecord {
lastActivityAt: number;
/** Per-seat input rate limiting: rolling one-second window. */
inputWindow: Map<number, { count: number; windowStart: number }>;
/** Per-seat highest client input seq applied (rejects out-of-order POSTs). */
lastInputSeq: Map<number, number>;
/** userId -> last time they polled/watched, so we can push snapshots to
* seated players AND active spectators over the SSE bus. */
viewers: Map<number, number>;
@ -104,12 +106,19 @@ async function getPayloadOrNull(): Promise<Payload | null> {
function buildViewFor(record: BomperatorMatchRecord, userId: number | null): BomperatorView {
const yourSeat = userId === null ? null : seatOf(record, userId);
return buildBomperatorView(record.state, {
const view = buildBomperatorView(record.state, {
matchId: record.id,
name: record.name,
version: record.version,
yourSeat,
});
// Echo each seat's last applied input seq so the owning client can reconcile
// its local prediction against what the server has actually consumed.
const players = view.players.map((p) => ({
...p,
lastInputSeq: record.lastInputSeq.get(p.seat) ?? 0,
}));
return { ...view, players };
}
/**
@ -292,6 +301,7 @@ export function createMatch(
createdAt: new Date().toISOString(),
lastActivityAt: Date.now(),
inputWindow: new Map(),
lastInputSeq: new Map(),
viewers: new Map(),
};
matches.set(record.id, record);
@ -393,6 +403,15 @@ export function submitInput(
}
record.inputWindow.set(seat, window);
// Sequence guard: the client fires direction changes immediately, so action
// POSTs can arrive out of order. Only the newest intent may win; anything at
// or below the last applied seq is a stale echo and is dropped silently.
if (typeof input.seq === "number") {
const last = record.lastInputSeq.get(seat) ?? -1;
if (input.seq <= last) return;
record.lastInputSeq.set(seat, input.seq);
}
record.state = applyInput(record.state, seat, input);
record.lastActivityAt = now;
}

View file

@ -159,6 +159,12 @@ export interface PlayerView {
readonly kills: number;
readonly roundsWon: number;
readonly connected: boolean;
/**
* Highest client input seq the registry has applied for this seat. Lets the
* owning client reconcile local prediction (drop acknowledged inputs, replay
* the rest). Stamped by the registry; 0 when nothing has been applied.
*/
readonly lastInputSeq?: number;
}
/** The complete per-poll snapshot the registry serves. */