Files
Robot-Clash/game/netfight.js
2026-11-15 20:05:02 +01:00

163 lines
8.9 KiB
JavaScript

/* Robot Clash - live PvP sync over an existing deterministic fight. Needs net.js, combat.js, ai.js.
Robot 0 is always the local player, robot 1 the opponent (both clients see it that way, so the host
mirrors indices when it publishes). The lower-uid player is the host (authority): it runs the real
RC.Combat.step and publishes snapshots; the guest renders them and only sends its input.
const nf = RC.NetFight({ net, id, host, mySeat, oppStyle, oppSkill, onPeerLost(wasHost) });
nf.start()
HOST each tick, instead of the normal step:
nf.hostStep(s, localInput, dt) runs step with [local, remote|AI], publishes ~15 Hz, returns events
GUEST each frame, instead of step:
nf.guestFrame(s, localInput, dt) eases robots toward the last snapshot, returns events to play
nf.peerAlive false once the peer went silent > GRACE (AI takes over)
nf.stop()
mySeat: 0 if I am meta[myUid] rendered as robot 0 (always true locally). The host publishes with robots
ordered [host, guest]; each side maps so that *its* robot is index 0. */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const PUB = 1 / 15, GRACE = 4000; // ms without news before the AI covers for the peer
// robot fields the view / HUD / sound read - kept small for the wire
const RF = ['x', 'z', 'a', 'y', 'hp', 'maxHp', 'flipped', 'stun', 'lifted', 'grabbedBy', 'grab', 'turretA', 'spin', 'sawOn', 'flameOn', 'gunOn', 'swing', 'cd', 'cd2', 'boost', 'gcd', 'gUses', 'shield', 'lost', 'dead', 'out'];
const rnd = v => (typeof v === 'number' ? Math.round(v * 1000) / 1000 : v);
const packRobot = r => { const o = {}; for (const k of RF) o[k] = rnd(r[k]); return o; };
const wrap = a => { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; };
RC.NetFight = (opt) => {
const net = opt.net, db = net.db, id = opt.id, host = opt.host;
const base = `matches/${id}`;
let pubT = 0, seq = 0, sendT = 0, beatT = 0, lastInSeq = -1, evBuf = [];
let sending = false, slow = 0; // one write at a time; back off while the line is slow
let remoteInput = { throttle: 0, turn: 0, fire: false, fire2: false, fire3: false };
let started = false, lastPeer = Date.now(), peerAlive = true, ai = null, subIn = null, subState = null, subPing = null, lastState = null, stateApplied = -1;
function start() {
if (host) {
// host reads the guest's input stream
subIn = db.stream(`${base}/in`, v => { if (v && typeof v.seq === 'number') { remoteInput = v; lastPeer = Date.now(); } });
} else {
// guest reads the host's state stream
subState = db.stream(`${base}/state`, v => { if (v && typeof v.seq === 'number') { lastState = v; lastPeer = Date.now(); } });
subPing = db.stream(`${base}/ping`, v => { if (v) lastPeer = Date.now(); }); // host alive during the countdown
}
}
function checkPeer() {
if (!started) { started = true; lastPeer = Math.max(lastPeer, Date.now()); } // countdown is over: start the clock
if (!peerAlive && Date.now() - lastPeer < GRACE) { peerAlive = true; if (opt.onPeerBack) opt.onPeerBack(host); }
if (peerAlive && Date.now() - lastPeer > GRACE) {
peerAlive = false;
if (host && !ai) ai = RC.AI.create({ style: opt.oppStyle || 'brawler', skill: opt.oppSkill != null ? opt.oppSkill : 0.5, seed: 7 });
if (opt.onPeerLost) opt.onPeerLost(host);
}
}
// HOST: step with [local, guest-or-AI], publish robots as [host, guest] but return a state where
// index 0 is the LOCAL player (so game.js renders identically on both sides).
function hostStep(s, localInput, dt) {
checkPeer();
const guestInput = peerAlive ? remoteInput : ai.think(s, s.robots[1], s.robots[0], dt);
RC.Combat.step(s, dt, [localInput, guestInput]);
if (s.events.length) evBuf.push.apply(evBuf, s.events); // batch events between publishes for the guest
pubT -= dt;
// publish only when the previous write came back - otherwise slow uploads queue up and the host stutters
if (pubT <= 0 && !sending) {
pubT = PUB + slow;
sending = true;
const t0 = Date.now();
const payload = {
seq: ++seq, t: rnd(s.t), left: rnd(s.left), pitOpen: rnd(s.pitOpen), pitAlarm: s.pitAlarm,
press: { st: s.press.st, y: rnd(s.press.y) }, crane: { st: s.crane.st, x: rnd(s.crane.x), z: rnd(s.crane.z), who: s.crane.who },
rockets: s.rockets.map(k => ({ x: rnd(k.x), z: rnd(k.z), y: rnd(k.y), a: rnd(k.a) })),
mines: s.mines.map(k => ({ x: rnd(k.x), z: rnd(k.z), arm: rnd(k.arm) })),
r: [packRobot(s.robots[0]), packRobot(s.robots[1])],
ev: evBuf.slice(-24), result: s.result, endIn: rnd(s.endIn),
};
evBuf.length = 0;
const done = () => {
sending = false;
const ms = Date.now() - t0; // slow line: send less often instead of piling up
slow = ms > 400 ? 0.2 : ms > 180 ? 0.08 : 0;
};
try { Promise.resolve(db.put(`${base}/state`, payload)).then(done, done); } catch (e) { done(); }
}
return s.events;
}
// GUEST: no simulation. Ease local robots toward the latest snapshot; snap flags/hp; play its events once.
function guestFrame(s, localInput, dt) {
checkPeer();
// send my input (I am robot 0 locally = guest = snapshot index 1)
sendT -= dt;
beatT -= dt;
// send on change, and at least every 0.5 s as a heartbeat (otherwise the host thinks I am gone)
if (sendT <= 0 && !sending && (changed(localInput) || beatT <= 0)) {
sendT = PUB; beatT = 0.5; lastInSeq++;
sending = true;
const fin = () => { sending = false; };
try {
Promise.resolve(db.put(`${base}/in`, { seq: lastInSeq, throttle: rnd(localInput.throttle || 0), turn: rnd(localInput.turn || 0),
fire: !!localInput.fire, fire2: !!localInput.fire2, fire3: !!localInput.fire3 })).then(fin, fin);
} catch (e) { fin(); }
prevInput = localInput;
}
const ev = [];
if (lastState) {
const snap = lastState;
s.t = snap.t; s.left = snap.left; s.pitOpen = snap.pitOpen; s.pitAlarm = snap.pitAlarm;
s.press.st = snap.press.st; s.press.y = snap.press.y;
s.crane.st = snap.crane.st; s.crane.x = snap.crane.x; s.crane.z = snap.crane.z; s.crane.who = snap.crane.who;
syncRockets(s, snap.rockets);
syncMines(s, snap.mines);
s.result = snap.result; s.endIn = snap.endIn;
// snapshot order [host, guest]; locally guest must be index 0 -> swap
applyRobot(s.robots[0], snap.r[1], dt); // me (guest)
applyRobot(s.robots[1], snap.r[0], dt); // host
if (snap.seq !== stateApplied) {
stateApplied = snap.seq;
for (const e of snap.ev || []) { const c = Object.assign({}, e); if (c.who === 0) c.who = 1; else if (c.who === 1) c.who = 0; ev.push(c); }
}
}
return ev;
}
function applyRobot(r, d, dt) {
if (!d) return;
const k = Math.min(1, dt * 14); // ease position/angle, snap the rest
r.x += (d.x - r.x) * k; r.z += (d.z - r.z) * k; r.y += (d.y - r.y) * k;
r.a += wrap(d.a - r.a) * k;
r.turretA += wrap(d.turretA - r.turretA) * k;
for (const f of ['hp', 'maxHp', 'flipped', 'stun', 'lifted', 'grabbedBy', 'grab', 'spin', 'sawOn', 'flameOn', 'gunOn', 'swing', 'cd', 'cd2', 'boost', 'gcd', 'gUses', 'shield', 'lost', 'dead', 'out']) if (d[f] !== undefined) r[f] = d[f];
}
function syncRockets(s, list) {
list = list || [];
s.rockets.length = list.length;
for (let i = 0; i < list.length; i++) s.rockets[i] = Object.assign(s.rockets[i] || { owner: 1, sp: 6, t: 3 }, list[i]);
}
function syncMines(s, list) {
list = list || [];
s.mines.length = list.length;
for (let i = 0; i < list.length; i++) s.mines[i] = Object.assign(s.mines[i] || { owner: 0, r: 0.85 }, list[i]);
}
let prevInput = null;
function changed(inp) { return !prevInput || inp.throttle !== prevInput.throttle || inp.turn !== prevInput.turn || inp.fire !== prevInput.fire || inp.fire2 !== prevInput.fire2 || inp.fire3 !== prevInput.fire3; }
return {
start, hostStep, guestFrame,
// during the countdown: keep the line alive (guest sends a neutral input, host an empty state ping)
idle(dt) {
sendT -= dt;
if (sendT > 0) return;
sendT = 0.5;
if (host) db.patch(`${base}/ping`, { h: Date.now() });
else { lastInSeq++; db.put(`${base}/in`, { seq: lastInSeq, throttle: 0, turn: 0, fire: false, fire2: false, fire3: false }); }
},
get peerAlive() { return peerAlive; },
stop() { if (subIn) subIn.close(); if (subState) subState.close(); if (subPing) subPing.close(); },
};
};
})(typeof window !== 'undefined' ? window : globalThis);