Files
Robot-Clash/game/netfight.js

103 lines
6.1 KiB
JavaScript
Raw Normal View History

/* 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").
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, 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;
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 => {
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;
function sendInput(inp, dt) {
sendT -= dt; keepT -= dt;
if (sendT > 0 || (!changed(inp) && keepT > 0)) return;
const i = RC.Proto.input(inp);
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()); }
}
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 (!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 !!(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);