Skip to content

gitflarePublicPartly agent-ready40

neon-drift

Real-time multiplayer arcade racer on Cloudflare Workers and Durable Objects.

Add the Apache-2.0 licence3efe3da
JavaScript235 lines9.8 KB
import { applySnapshot, encodeJoin, encodeInput, encodeAck, encodePing, parseMessage } from '/shared/protocol.js';import { stepCycle, DT } from '/shared/sim.js'; const EXTRAP_MS = 250, TICK_MS = 1000 / 30, MAX_PENDING = 120; function blank() { return { x: 0, y: 0, heading: 0, speed: 160, boost: 0, meter: 100, alive: 0, score: 0, hue: 0 }; } export function createNet(code, name, handlers, opts) {  const h = handlers || {};  const net = {    id: 0, role: '', queued: false, rtt: 0, connected: false, phase: 'waiting', secondsLeft: 0, tick: 0,    arena: { radius: 1000, nextRadius: 1000, warn: false },    names: Object.create(null), cycleIds: [], orbs: new Map(), trails: new Map(),    me: null, sendInput: null, update: null, sampleCycle: null, close: null,  };  const key = 'nd-token-' + code;  let watch = !!(opts && opts.watch) || (typeof location !== 'undefined' && /[?&]watch=1/.test(location.search));  let ws = null, retry = 250, closed = false;  const snaps = new Map();  let ackTick = -1, lastAcked = -1, lastAckSent = 0;  let seq = 0, lastSig = '', lastSentAt = 0, curTurn = 0, curBoost = 0;  const pending = [];  let msBase = 0, tickBase = 0, synced = false;  const hist = new Map();  const base = blank(), pred = blank(), meOut = blank();  meOut.alive = false;  let hasBase = false, errX = 0, errY = 0, lastUpdate = 0, accum = 0;  const input = { turn: 0, boost: 0 };   function open() {    ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/ws/' + code);    ws.onopen = () => ws.send(JSON.stringify(encodeJoin(name, sessionStorage.getItem(key), net.tick || null, watch)));    ws.onmessage = (ev) => {      const m = parseMessage(ev.data);      if (!m) return;      if (m[0] === 's') accept(m[1], m[2], m[3], m[4]);      else if (m[0] === 'v') { if (h.events) for (let i = 2; i < m.length; i++) h.events(m[i]); }      else if (m[0] === 'o') {        const r = Date.now() - m[1];        net.rtt = net.rtt ? net.rtt * 0.8 + r * 0.2 : r;      } else if (m[0] === 'w') {        net.id = m[1]; net.role = m[4]; net.queued = m[7] === 1;        if (m[2]) sessionStorage.setItem(key, m[2]);        net.connected = true; retry = 250;        snaps.clear(); hist.clear(); net.trails.clear(); net.orbs.clear(); pending.length = 0;        hasBase = false; net.me = null; ackTick = -1; lastAcked = -1; synced = false;        accept(m[5], -1, 0, m[6]);        if (h.welcome) h.welcome({ id: m[1], token: m[2], code: m[3], role: m[4], tick: m[5] });        if (h.status) h.status(true);      }    };    ws.onclose = () => {      net.connected = false;      if (h.status) h.status(false);      if (closed) return;      setTimeout(open, retry);      retry = Math.min(15000, retry * 2);    };  }   function ring(id) {    let r = hist.get(id);    if (!r) {      r = { n: 0, i: 0, t: new Float64Array(16), x: new Float32Array(16), y: new Float32Array(16), hd: new Float32Array(16), sp: new Float32Array(16), bo: new Uint8Array(16), me: new Float32Array(16), al: new Uint8Array(16), sc: new Int32Array(16), hue: 0 };      hist.set(id, r);    }    return r;  }   function copy(a, b) {    a.x = b.x; a.y = b.y; a.heading = b.heading; a.speed = b.speed; a.boost = b.boost;    a.meter = b.meter; a.alive = b.alive; a.score = b.score; a.hue = b.hue;  }   function replay() {    copy(pred, base);    accum = 0;    if (!pred.alive) return;    for (let i = 0; i < pending.length; i++) stepCycle(pred, pending[i], DT);  }   function accept(tick, baseTick, lastSeq, delta) {    let prev = null;    if (baseTick !== -1) {      prev = snaps.get(baseTick);      if (!prev) return;    }    const w = applySnapshot(prev, delta, tick);    snaps.set(tick, w);    snaps.delete(tick - 64);    const nowMs = performance.now();    const est = tickBase + (nowMs - msBase) / TICK_MS;    if (!synced || Math.abs(est - tick) > 4) { synced = true; tickBase = tick; }    else tickBase = est + (tick - est) * 0.1;    msBase = nowMs;    net.tick = tick; ackTick = tick; net.phase = w.phase;    if (w.arena) {      net.arena.radius = w.arena[0]; net.arena.nextRadius = w.arena[1]; net.arena.warn = w.arena[2] > 0;      net.secondsLeft = w.secondsLeft || 0;    } else net.arena.radius = w.radius;    for (const id in w.names) net.names[id] = w.names[id];    net.cycleIds.length = 0;    for (const id in w.cycles) {      const c = w.cycles[id];      net.cycleIds.push(c[0]);      const r = ring(c[0]);      const k = r.i; r.i = (k + 1) & 15; if (r.n < 16) r.n++;      r.t[k] = tick; r.x[k] = c[1]; r.y[k] = c[2]; r.hd[k] = c[3]; r.sp[k] = c[4]; r.bo[k] = c[5];      r.al[k] = c[6]; r.sc[k] = c[7]; r.me[k] = c[8]; r.hue = c[9] || 0;    }    for (const id of hist.keys()) if (!w.cycles[id]) hist.delete(id);    for (const id in w.trails) {      const t = w.trails[id], nid = +id;      let e = net.trails.get(nid);      if (!e) { e = { pts: [], alive: true, deadAt: 0, hue: 0 }; net.trails.set(nid, e); }      const pts = e.pts;      pts.length = t.length - 1;      for (let i = 1; i < t.length; i++) pts[i - 1] = t[i];      const c = w.cycles[id];      const alive = c ? c[6] === 1 : false;      if (e.alive && !alive) e.deadAt = nowMs;      e.alive = alive; e.hue = c ? c[9] || 0 : e.hue;    }    for (const id of net.trails.keys()) if (!w.trails[id]) net.trails.delete(id);    net.orbs.clear();    for (const id in w.orbs) net.orbs.set(+id, { x: w.orbs[id][0], y: w.orbs[id][1] });    const mc = w.cycles[net.id];    if (mc && net.role === 'player') {      let k = 0;      while (k < pending.length && pending[k].seq <= lastSeq) k++;      if (k) pending.splice(0, k);      const px = pred.x, py = pred.y, had = hasBase;      base.x = mc[1]; base.y = mc[2]; base.heading = mc[3]; base.speed = mc[4]; base.boost = mc[5];      base.alive = mc[6]; base.score = mc[7]; base.meter = mc[8]; base.hue = mc[9] || 0;      hasBase = true;      replay();      if (had && base.alive) {        const dx = px + errX - pred.x, dy = py + errY - pred.y;        if (dx * dx + dy * dy > 900) { errX = 0; errY = 0; } else { errX = dx; errY = dy; }      } else { errX = 0; errY = 0; }    }  }   net.sendInput = (turn, boost) => {    curTurn = turn; curBoost = boost;    if (!net.connected || net.role !== 'player' || !ws || ws.readyState !== 1) return;    const now = performance.now();    const same = turn + ',' + boost === lastSig;    if (same ? now - lastSentAt < 100 : now - lastSentAt < 33) return;    lastSig = turn + ',' + boost; lastSentAt = now;    seq++;    pending.push({ seq, turn, boost });    if (pending.length > MAX_PENDING) pending.shift();    lastAckSent = now; lastAcked = ackTick; // ack is piggybacked on the input    ws.send(JSON.stringify(encodeInput(seq, turn, boost, ackTick)));  };   net.update = (nowMs) => {    const dt = lastUpdate ? Math.min(100, nowMs - lastUpdate) : 16;    lastUpdate = nowMs;    if (ws && ws.readyState === 1 && ackTick !== lastAcked && nowMs - lastAckSent >= 100) {      lastAckSent = nowMs; lastAcked = ackTick;      ws.send(JSON.stringify(encodeAck(ackTick)));    }    if (!hasBase || net.role !== 'player') { net.me = null; return; }    accum += dt / 1000;    input.turn = curTurn; input.boost = curBoost;    let guard = 0;    while (accum >= DT && guard++ < 6) { if (pred.alive) stepCycle(pred, input, DT); accum -= DT; }    const decay = Math.exp(-dt / 100 * 2.3);    errX *= decay; errY *= decay;    meOut.x = pred.x + errX; meOut.y = pred.y + errY;    meOut.heading = pred.heading; meOut.speed = pred.speed; meOut.boost = pred.boost;    meOut.meter = pred.meter; meOut.alive = !!pred.alive; meOut.score = pred.score; meOut.hue = pred.hue;    if (accum > 0 && pred.alive) {      meOut.x += Math.cos(pred.heading) * pred.speed * accum;      meOut.y += Math.sin(pred.heading) * pred.speed * accum;    }    net.me = meOut;    const e = net.trails.get(net.id);    if (e && e.pts.length >= 2 && pred.alive) {      e.pts[e.pts.length - 2] = meOut.x; e.pts[e.pts.length - 1] = meOut.y;    }  };   // renderMs is already (now - 100) from the renderer; it is mapped to a fractional server tick.  net.sampleCycle = (id, renderMs, out) => {    const r = hist.get(id);    if (!r || r.n === 0) return false;    const rt = tickBase + (renderMs - msBase) / TICK_MS;    let hi = -1, lo = -1;    for (let j = 0; j < r.n; j++) {      const k = (r.i - 1 - j) & 15;      if (r.t[k] <= rt) { lo = k; break; }      hi = k;    }    out.hue = r.hue;    if (lo < 0) {      const k = (r.i - r.n) & 15;      out.x = r.x[k]; out.y = r.y[k]; out.heading = r.hd[k]; out.speed = r.sp[k]; out.boost = r.bo[k];      out.meter = r.me[k]; out.alive = r.al[k] === 1; out.score = r.sc[k];      return true;    }    out.speed = r.sp[lo]; out.boost = r.bo[lo]; out.meter = r.me[lo]; out.score = r.sc[lo];    if (hi >= 0) {      const f = Math.min(1, Math.max(0, (rt - r.t[lo]) / (r.t[hi] - r.t[lo] || 1)));      out.x = r.x[lo] + (r.x[hi] - r.x[lo]) * f;      out.y = r.y[lo] + (r.y[hi] - r.y[lo]) * f;      let dh = r.hd[hi] - r.hd[lo];      dh = Math.atan2(Math.sin(dh), Math.cos(dh));      out.heading = r.hd[lo] + dh * f;      out.alive = r.al[lo] === 1;      return true;    }    const secs = Math.min(EXTRAP_MS / 1000, Math.max(0, (rt - r.t[lo]) * TICK_MS / 1000));    out.heading = r.hd[lo]; out.alive = r.al[lo] === 1;    out.x = r.x[lo]; out.y = r.y[lo];    if (out.alive) {      out.x += Math.cos(out.heading) * out.speed * secs;      out.y += Math.sin(out.heading) * out.speed * secs;    }    return true;  };   net.close = () => { closed = true; clearInterval(pingTimer); if (ws) ws.close(); };  open();  const pingTimer = setInterval(() => { if (net.connected && ws.readyState === 1) ws.send(JSON.stringify(encodePing(Date.now()))); }, 2000);  net.join = (n) => {    if (n != null) name = n;    watch = false;    if (ws && ws.readyState === 1) ws.send(JSON.stringify(encodeJoin(name, sessionStorage.getItem(key), null, false)));  };  return net;}