fix(net): interpolate between snapshots to absorb jitter (P1-6)

netfight eased to the newest snapshot with no buffer, so a jittery
client's robot stalled then jumped. Render ~120 ms in the past between
the two bracketing snapshots instead. Dev params ?netlag/?interp/
?netprobe reproduce it; unit test for the interp math + a Playwright
lag test (tests/e2e/netlag.spec.js).
This commit is contained in:
2026-11-19 19:46:54 +01:00
parent 2bf5a40ebc
commit a494290548
6 changed files with 183 additions and 36 deletions

View File

@@ -211,6 +211,15 @@ eine zweite systemd-Unit + ein Caddy-Block ist – kein Umbau.
- [x] **P1-6 Client `netfight.js` neu:** Eingaben senden, Snapshots interpolieren, `match.end` anzeigen;
`game.js` nimmt das Ergebnis vom Server statt `s.result` selbst zu werten. *AK:* Zwei Browser-Fenster
(oder Playwright, P4-2) spielen einen Kampf; beide sehen dasselbe Ergebnis aus ihrer Sicht.
- **BEFUND 2026-11-19 (Michi laggt, Benni nicht):** `netfight.js` hat **keinen Jitter-Puffer** umgesetzt – es
zog den lokalen Zustand nur zum *neuesten* Snapshot (`k = dt*14`), nicht wie hier geplant „zwischen den zwei
letzten Snapshots (~100 ms Puffer)" (Zeile 151). Bei ungleichmäßiger Snapshot-Ankunft (Jitter/Bufferbloat,
auch über Kabel) bremst der Roboter und springt dann → F3 meldet `jitter`/`late`. Benni (gleichmäßige Leitung)
merkt nichts. **Fix (P4-x):** echte Entity-Interpolation mit ~100 ms Puffer; Render bei `now - INTERP_DELAY`
zwischen den zwei umgebenden Snapshots. **Reproduzierbar:** Dev-Param `?netlag=<basis>,<jitter>` verzögert
eingehende Snapshots geseedet; Node-Test `tests/netfight.test.js` (reine Interp-Mathe) + Playwright-Test misst
die Positions-Sprünge mit/ohne `netlag`. Erkenntnis für Benni: das Springen war ein Client-Interp-Problem,
kein Server-/Leitungsproblem.
- [x] **P1-7 Disconnect/Reconnect:** Gnadenfrist, KI-Übernahme, Wiederverbinden. *AK:* Test trennt einen Client
mitten im Kampf; Kampf endet trotzdem mit Ergebnis; Reconnect innerhalb 10 s übernimmt wieder.
- [x] **P1-8 Alt-Code entfernen:** `server/rtdb.js`, `server/rules.js`, `/db`-Routen, `game/lobby.js` (alt),

View File

@@ -99,6 +99,7 @@
if (Kit.store(ID).get('music', null) === null) audio.setVolume(0.1, 0.35);
const DEV = new URLSearchParams(location.search);
if (DEV.has('touch')) document.body.classList.add('forcetouch'); // dev: &touch shows the touch pad on desktop
const netProbe = DEV.has('netprobe') ? (window.__probe = []) : null; // dev: records opponent robot pos for the lag test
const net = RC.Net(NET_CFG);
const rank = RC.Ranking(net); // online ranking, computed by the server
const cloud = RC.CloudSave(net); // campaign copy for registered accounts (online saves live on the server)
@@ -768,7 +769,12 @@
const count = online ? Math.max(0, +online.countdown || 0) : 3.5;
F = { s, opp, training, exhibition: !!exhibition, online, tour: !!tour, brain: online ? null : RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count, beat: Math.ceil(count) + 1,
acc: [0, 0], accT: 0, banner: null, ended: false, oppAway: false };
if (online) { netStats.reset(); F.nf = RC.NetFight({ net, seat: online.seat, stats: netStats }); } // the server runs the fight, we show it
if (online) { // the server runs the fight, we show it (interpolated); dev: ?netlag=base,jit[,seed], ?interp=ms
netStats.reset();
let lag = null; const nl = DEV.get('netlag');
if (nl) { const [b, j, sd] = nl.split(',').map(Number); lag = { base: b || 0, jit: j || 0, seed: sd || 1 }; }
F.nf = RC.NetFight({ net, seat: online.seat, stats: netStats, interp: +DEV.get('interp') || 0, lag });
}
// dev: ?auto = AI drives the player too, ?ff=30 = fast-forward 30 s (screenshots, balancing)
if (DEV.has('auto')) F.auto = RC.AI.create({ style: 'brawler', skill: 0.7, seed: seed + 11 });
if (DEV.has('ff')) {
@@ -916,6 +922,7 @@
let events;
if (F.online) {
events = F.nf.frame(s, playerInput(), dt);
if (netProbe) { netProbe.push({ t: performance.now(), x: s.robots[1].x, z: s.robots[1].z }); if (netProbe.length > 2000) netProbe.shift(); }
if (F.nf.oppAway !== F.oppAway) { F.oppAway = F.nf.oppAway; banner(t(F.oppAway ? 'peer_lost' : 'peer_back'), F.oppAway ? '#ff4a3a' : '#6dff9e', 2.2); }
// no word from the server for 20 s (and no result yet - a hidden tab may simply have slept through the end)
if (!F.serverEnd && F.nf.silentFor > 20 && !F.ended) { F.ended = true; onlineFightLost(); return; }

View File

@@ -1,26 +1,62 @@
/* Robot Clash - client side of a server-run live fight. No simulation here: the server steps RC.Combat;
this sends the local input and shows the server's snapshots (already mapped to "robot 0 = me").
const nf = RC.NetFight({ net, seat, stats }) stats = RC.NetStats() (optional, F3 overlay)
nf.frame(s, input, dt) send input (on change, max 30/s, at least every 0.25 s), ease the local state toward
the newest snapshot, return the events of snapshots not seen yet
nf.oppAway true while the opponent is disconnected (server tells us)
nf.silentFor seconds since the last snapshot (connection trouble)
nf.stop() */
Entity interpolation: snapshots (20 Hz) are buffered and rendered ~INTERP_DELAY ms in the past, between the two
snapshots bracketing the render time. This absorbs jitter (uneven arrival) so the robot does not jump - the old
"ease to the newest snapshot" had no buffer and jumped whenever a snapshot arrived late.
const nf = RC.NetFight({ net, seat, stats, interp, lag })
interp interpolation delay in ms (default 100); lag = { base, jit, seed } delays incoming snapshots (dev only)
nf.frame(s, input, dt) send input, show the interpolated world, return not-yet-seen events
nf.oppAway / nf.silentFor / nf.stop()
Pure, Node-testable: RC.NetFight.pickFrames(buf, renderTime), RC.NetFight.lerpRobot(da, db, k) */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const SEND_MIN = 1 / 30, SEND_KEEP = 0.25;
const SEND_MIN = 1 / 30, SEND_KEEP = 0.25, INTERP_DEFAULT = 120, BUF_MAX = 30;
const EASE = ['x', 'z', 'y'], ANG = ['a', 'turretA'];
const wrap = a => { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; };
const mul = s => { let a = (s >>> 0) || 1; return () => { a |= 0; a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; };
// buf = [{ at, tick, snap }] sorted by at/tick ascending. Pick the snapshot reached by renderTime (a) and the
// next one (b), with the fraction between them. Past the newest -> hold the newest (a === b, frac 1).
function pickFrames(buf, renderTime) {
if (!buf.length) return null;
let a = buf[0], b = null;
for (let i = 0; i < buf.length; i++) { if (buf[i].at <= renderTime) a = buf[i]; else { b = buf[i]; break; } }
const span = b ? (b.at - a.at) : 0;
const frac = b && span > 0 ? Math.min(1, Math.max(0, (renderTime - a.at) / span)) : (b ? 0 : 1);
return { a, b: b || a, frac };
}
// blend two robot snapshots: positions/angles interpolate, discrete fields come from the reached snapshot (da)
function lerpRobot(da, db, k) {
const r = {};
for (const f of (RC.Proto ? RC.Proto.RF : Object.keys(da))) if (da[f] !== undefined && !EASE.includes(f) && !ANG.includes(f)) r[f] = da[f];
for (const f of EASE) { if (typeof da[f] === 'number' && typeof db[f] === 'number') r[f] = da[f] + (db[f] - da[f]) * k; else if (typeof da[f] === 'number') r[f] = da[f]; }
for (const f of ANG) { if (typeof da[f] === 'number' && typeof db[f] === 'number') r[f] = da[f] + wrap(db[f] - da[f]) * k; else if (typeof da[f] === 'number') r[f] = da[f]; }
r.lost = Object.assign({}, da.lost); r.lostW = (da.lostW || []).slice(); r.W = (da.W || []).map(w => Object.assign({}, w));
return r;
}
RC.NetFight = (opt) => {
const sock = opt.net.socket, seat = opt.seat;
let latest = null, seenTick = -1, seq = 0, sendT = 0, keepT = 0, prev = null, lastSnap = Date.now();
const stats = opt.stats || null; // RC.NetStats for the F3 overlay (optional)
const DELAY = opt.interp > 0 ? opt.interp : INTERP_DEFAULT;
const lag = opt.lag && opt.lag.base >= 0 ? opt.lag : null, rng = lag ? mul(lag.seed || 1) : null;
const stats = opt.stats || null;
const buf = []; // in-order snapshot buffer
let newest = null, lastTick = -1, seenTick = -1, seq = 0, sendT = 0, keepT = 0, prev = null, lastSnap = Date.now();
function accept(m) { // a snapshot arrived (possibly delayed by the dev lag injector)
const snap = RC.Proto.toLocal(seat, m);
lastSnap = Date.now(); newest = snap;
if (stats) stats.snap(snap, m._bytes, performance.now());
if (m.tick <= lastTick) return; // out of order (rare) -> drop, keep the buffer monotonic
lastTick = m.tick;
buf.push({ at: Date.now(), tick: m.tick, snap });
while (buf.length > BUF_MAX) buf.shift();
}
const off = sock.on('snap', m => {
latest = RC.Proto.toLocal(seat, m); lastSnap = Date.now();
if (stats) stats.snap(latest, m._bytes, performance.now());
if (!lag) return accept(m);
setTimeout(() => accept(m), Math.max(0, lag.base + (rng() * 2 - 1) * lag.jit));
});
const changed = i => !prev || i.throttle !== prev.throttle || i.turn !== prev.turn || i.fire !== prev.fire || i.fire2 !== prev.fire2 || i.fire3 !== prev.fire3;
@@ -31,38 +67,36 @@
if (sock.send(Object.assign({ t: 'input', seq: ++seq }, i))) { prev = i; sendT = SEND_MIN; keepT = SEND_KEEP; if (stats) stats.inputSent(seq, performance.now()); }
}
function applyRobot(r, d, k) {
for (const f of EASE) if (typeof d[f] === 'number') r[f] += (d[f] - r[f]) * k;
for (const f of ANG) if (typeof d[f] === 'number') r[f] += wrap(d[f] - r[f]) * k;
for (const f of RC.Proto.RF) if (!EASE.includes(f) && !ANG.includes(f) && d[f] !== undefined) r[f] = d[f];
if (d.lost) r.lost = Object.assign(r.lost || {}, d.lost);
if (d.lostW) r.lostW = d.lostW.slice();
if (d.W && r.W) d.W.forEach((w, i) => { if (r.W[i]) Object.assign(r.W[i], w); });
}
const applyRobot = (r, d) => { Object.assign(r, d); };
const syncList = (dst, src, def) => { dst.length = src.length; for (let i = 0; i < src.length; i++) dst[i] = Object.assign(dst[i] || Object.assign({}, def), src[i]); };
function frame(s, inp, dt) {
sendInput(inp, dt);
if (!latest) return [];
const n = latest, k = Math.min(1, dt * 14);
s.t = n.time; s.left = n.left; s.pitOpen = n.pitOpen; s.pitAlarm = n.pitAlarm; s.endIn = n.endIn;
s.press.st = n.press.st; s.press.y = n.press.y;
Object.assign(s.crane, n.crane);
syncList(s.rockets, n.rockets, { sp: 6, t: 3 });
syncList(s.mines, n.mines, { r: 0.85 });
applyRobot(s.robots[0], n.robots[0], k);
applyRobot(s.robots[1], n.robots[1], k);
if (n.result) s.result = n.result;
if (n.tick === seenTick) return [];
seenTick = n.tick;
return n.ev || [];
if (!buf.length) return [];
const renderTime = Date.now() - DELAY;
const fr = pickFrames(buf, renderTime), na = fr.a.snap, nb = fr.b.snap, k = fr.frac;
s.t = na.time; s.left = na.left; s.pitOpen = na.pitOpen; s.pitAlarm = na.pitAlarm; s.endIn = na.endIn;
s.press.st = na.press.st; s.press.y = na.press.y;
Object.assign(s.crane, na.crane);
syncList(s.rockets, na.rockets, { sp: 6, t: 3 });
syncList(s.mines, na.mines, { r: 0.85 });
applyRobot(s.robots[0], lerpRobot(na.robots[0], nb.robots[0], k));
applyRobot(s.robots[1], lerpRobot(na.robots[1], nb.robots[1], k));
if (na.result) s.result = na.result;
while (buf.length > 2 && buf[1].at <= renderTime) buf.shift(); // keep one snapshot older than renderTime
if (fr.a.tick === seenTick) return [];
seenTick = fr.a.tick;
return na.ev || [];
}
return {
frame,
get oppAway() { return !!(latest && latest.away && latest.away[1]); },
get oppAway() { return !!(newest && newest.away && newest.away[1]); },
get silentFor() { return (Date.now() - lastSnap) / 1000; },
stop() { off(); },
};
};
RC.NetFight.pickFrames = pickFrames;
RC.NetFight.lerpRobot = lerpRobot;
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -5,8 +5,8 @@ const { expect } = require('@playwright/test');
const mode = page => page.locator('body').getAttribute('data-mode');
// open the game in online mode and log in with name + password through the login card
async function login(page, name, pass) {
await page.goto('/?online');
async function login(page, name, pass, query = '') {
await page.goto('/?online' + query);
await page.locator('#oLogin').fill(name);
await page.locator('#oPass').fill(pass);
await page.locator('#oGo').click();

48
tests/e2e/netlag.spec.js Normal file
View File

@@ -0,0 +1,48 @@
// Repeatable lag test: one client gets a seeded snapshot delay+jitter (?netlag). The opponent robot must still
// move SMOOTHLY on that client (entity interpolation), i.e. no large per-step jumps - the bug Michi reported.
'use strict';
const { test, expect } = require('@playwright/test');
const { login, toLobby } = require('./helpers');
test('a jittery client still sees the opponent move smoothly (interpolation buffer)', async ({ browser }) => {
const ctxA = await browser.newContext(), ctxB = await browser.newContext();
const a = await ctxA.newPage(), b = await ctxB.newPage();
const errors = [];
for (const p of [a, b]) p.on('pageerror', e => errors.push(e.message));
// michi gets a repeatable snapshot delay + jitter (80 ms +/- 40 ms, seeded) + the position probe
await login(a, 'michi', 'Michi2000!', '&netlag=80,40,7&netprobe');
await login(b, 'benni', 'Benni2000!');
await toLobby(a); await toLobby(b);
await a.locator('.prow', { hasText: 'benni' }).locator('.chal').click();
await expect(b.locator('#cYes')).toBeVisible();
await b.locator('#cYes').click();
await expect(a.locator('body')).toHaveAttribute('data-mode', 'fight');
await expect(b.locator('body')).toHaveAttribute('data-mode', 'fight');
await a.waitForTimeout(4200); // countdown
await a.evaluate(() => { globalThis.__probe.length = 0; });
await b.keyboard.down('w'); // benni drives so his robot moves across michi's screen
await a.keyboard.down('a'); // michi turns a bit (keeps both sides active)
await a.waitForTimeout(2600);
await b.keyboard.up('w'); await a.keyboard.up('a');
const probe = await a.evaluate(() => globalThis.__probe.slice());
// consider only samples while the opponent was actually moving
const deltas = [];
let moved = 0;
for (let i = 1; i < probe.length; i++) {
const dx = probe[i].x - probe[i - 1].x, dz = probe[i].z - probe[i - 1].z;
const d = Math.hypot(dx, dz);
deltas.push(d); moved += d;
}
expect(probe.length, 'probe collected samples').toBeGreaterThan(30);
expect(moved, 'the opponent actually moved (test is meaningful)').toBeGreaterThan(0.8);
const maxJump = Math.max(...deltas);
// at ~5 m/s over a 60 Hz step a smooth move is ~0.08/step; a snapshot-jump would be several times that.
expect(maxJump, 'no large per-step jump despite jitter (smooth interpolation)').toBeLessThan(0.35);
expect(errors, 'no JavaScript errors').toEqual([]);
await ctxA.close(); await ctxB.close();
});

49
tests/netfight.test.js Normal file
View File

@@ -0,0 +1,49 @@
'use strict';
// Entity-interpolation math for the live fight (the jitter buffer that stops the robot from jumping).
const { test } = require('node:test');
const assert = require('node:assert');
const path = require('path');
require(path.join(__dirname, '..', 'game', 'protocol.js'));
require(path.join(__dirname, '..', 'game', 'netfight.js'));
const RC = globalThis.RC;
const { pickFrames, lerpRobot } = RC.NetFight;
test('pickFrames: brackets the render time and gives the fraction between the two snapshots', () => {
const buf = [{ at: 0, tick: 1 }, { at: 100, tick: 2 }];
const fr = pickFrames(buf, 50);
assert.strictEqual(fr.a.tick, 1);
assert.strictEqual(fr.b.tick, 2);
assert.ok(Math.abs(fr.frac - 0.5) < 1e-9);
});
test('pickFrames: past the newest snapshot holds it (no extrapolation jump)', () => {
const buf = [{ at: 0, tick: 1 }, { at: 100, tick: 2 }];
const fr = pickFrames(buf, 500);
assert.strictEqual(fr.a.tick, 2);
assert.strictEqual(fr.b.tick, 2);
assert.strictEqual(fr.frac, 1);
});
test('pickFrames: empty buffer -> null', () => {
assert.strictEqual(pickFrames([], 0), null);
});
test('lerpRobot: positions interpolate linearly', () => {
const r = lerpRobot({ x: 0, z: 0, y: 0, hp: 100 }, { x: 10, z: -4, y: 2, hp: 50 }, 0.5);
assert.ok(Math.abs(r.x - 5) < 1e-9);
assert.ok(Math.abs(r.z + 2) < 1e-9);
assert.ok(Math.abs(r.y - 1) < 1e-9);
});
test('lerpRobot: angles take the shortest path across the +/-PI seam', () => {
const r = lerpRobot({ a: 3.0 }, { a: -3.0 }, 0.5);
// short way is +0.28 rad across PI, not -6 rad the long way
assert.ok(r.a > 3.0 || r.a < -3.0, 'wrapped past PI, not back toward 0');
assert.ok(Math.abs(Math.abs(r.a) - Math.PI) < 0.2, 'lands near the seam');
});
test('lerpRobot: discrete fields come from the reached (older) snapshot, not the newer one', () => {
const r = lerpRobot({ x: 0, hp: 100, dead: false }, { x: 10, hp: 0, dead: true }, 0.5);
assert.strictEqual(r.hp, 100);
assert.strictEqual(r.dead, false);
});