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
JavaScript163 lines7.3 KB
export const FULL_EVERY = 60;export const RING = 64;const r1 = (v) => (Math.round(v * 10) / 10) || 0;const r3 = (v) => (Math.round(v * 1000) / 1000) || 0;const q0 = (v) => Math.round(v) || 0; export function encodeJoin(name, token, lastTick, watch) {  const m = ['j', name, token ?? null, lastTick ?? null];  if (watch) m.push(1);  return m;}/** Input: ['i', seq, turn, boost, lastSnapshotTick] (ack piggybacked). */export function encodeInput(seq, turn, boost, lastSnapTick) { return ['i', seq, turn, boost, lastSnapTick]; }export function encodeAck(tick) { return ['a', tick]; }export function encodePing(t) { return ['p', t]; }export function encodePong(t, tick) { return ['o', t, tick]; }export function encodeError(code, msg) { return ['e', code, msg]; }export function encodeEvents(tick, events) { return ['v', tick, ...events]; } export function parseMessage(text) {  let m;  try { m = JSON.parse(text); } catch { return null; }  return Array.isArray(m) && typeof m[0] === 'string' ? m : null;} /** * World snapshot (extras are optional): * { tick, phase, radius, cycles:{id:[id,x,y,heading,speed,boost,alive,score,meter,hue]}, *   trails:{id:[trailBase, x0,y0,...]} (integer coords), orbs:{id:[x,y]}, names:{id:name}, *   arena:[radius,nextRadius,warnTicksLeft], secondsLeft } * Trail point arrays are cached per player and extended from counters * (trailBase + length), so only appended points are quantised each tick. */const trailCache = new WeakMap();function quantTrail(p) {  let c = trailCache.get(p);  const len = p.trail.length;  if (!c || c.base > p.trailBase || c.len > len || (c.base === p.trailBase && c.len === 0 && len > 0 && false)) {    c = { base: p.trailBase, len: 0, arr: [p.trailBase] };    trailCache.set(p, c);  }  if (c.base < p.trailBase) {    const drop = Math.min((p.trailBase - c.base) * 2, c.arr.length - 1);    c.arr.splice(1, drop);    c.len = Math.max(0, c.len - drop);    c.base = p.trailBase;    c.arr[0] = p.trailBase;  }  // The newest point can still move (head point), so re-quantise the last point.  let from = c.len >= 2 ? c.len - 2 : c.len;  if (from & 1) from--;  // copy-on-write: earlier snapshots keep their (immutable) array  const arr = c.arr.slice(0, 1 + from);  for (let i = from; i < len; i++) arr.push(q0(p.trail[i]));  c.arr = arr;  c.len = len;  return arr;} export function makeSnapshot(state) {  const cycles = {}, trails = {}, orbs = {}, names = {};  for (const p of state.players.values()) {    cycles[p.id] = [p.id, r1(p.x), r1(p.y), r3(p.heading), r1(p.speed), p.boost, p.alive ? 1 : 0, p.score, Math.round(p.meter), p.hue || 0];    trails[p.id] = quantTrail(p);    names[p.id] = p.name;  }  for (const o of state.orbs) orbs[o[0]] = [o[1], o[2]];  const warn = state.warnUntilTick >= 0 ? Math.max(0, state.warnUntilTick - state.tick) : 0;  let secondsLeft = 0;  if (state.matchEndTick > state.tick) secondsLeft = Math.ceil((state.matchEndTick - state.tick) / 30);  else if (state.phaseTicks > 0) secondsLeft = Math.max(0, Math.ceil((state.phaseTick + state.phaseTicks - state.tick) / 30));  return {    tick: state.tick, phase: state.phase, radius: r1(state.radius), cycles, trails, orbs, names,    arena: [r1(state.radius), r1(state.nextRadius), warn], secondsLeft,  };} const same = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]); /** * delta: [phase, radius, cyclesChanged[], cyclesRemoved[], trailAppends[], trailsReset[], *         orbsAdded[], orbsRemoved[], names, arena, secondsLeft]; prev null => full. * Cycles are tiny and compared per tick; trails use length/base counters only. * append: [id, trailBase, startIndex, x, y, ...] where startIndex is a flat index into the * trail as of trailBase; reset: [id, trailBase, ...allPoints] (full / base mismatch). */export function encodeSnapshot(prev, next) {  const full = !prev;  const cyc = [], cycRem = [], app = [], reset = [], orbAdd = [], orbRem = [];  const names = {};  for (const id in next.cycles) {    if (full || !prev.cycles[id] || !same(prev.cycles[id], next.cycles[id])) cyc.push(next.cycles[id]);    if (full || prev.names[id] !== next.names[id]) names[id] = next.names[id];    const nt = next.trails[id], pt = full ? null : prev.trails[id];    if (!pt || pt[0] > nt[0] || nt.length < pt.length || (nt[0] !== pt[0] && false)) {      reset.push(packTrail(+id, nt));    } else if (nt[0] !== pt[0]) {      // front points dropped: client trims by base; append from the old end (in new indices)      const ptEnd = pt.length - 1 + pt[0] * 2;      const from = ptEnd - nt[0] * 2;      if (from < 0) reset.push(packTrail(+id, nt));      else if (nt.length - 1 > from) app.push([+id, nt[0], from, ...nt.slice(1 + from)]);      else app.push([+id, nt[0], from]);    } else if (nt.length > pt.length || !tailSame(pt, nt)) {      // the old last point may have moved: resend from the last old point      const from = Math.max(0, pt.length - 3);      app.push([+id, nt[0], from & ~1, ...nt.slice(1 + (from & ~1))]);    }  }  if (!full) {    for (const id in prev.cycles) if (!next.cycles[id]) cycRem.push(+id);    for (const id in prev.orbs) if (!next.orbs[id]) orbRem.push(+id);  }  for (const id in next.orbs) if (full || !prev.orbs[id]) orbAdd.push([+id, ...next.orbs[id]]);  return [next.phase, next.radius, cyc, cycRem, app, reset, orbAdd, orbRem, names, next.arena, next.secondsLeft];} function tailSame(a, b) {  const n = a.length;  return n < 3 || (a[n - 1] === b[n - 1] && a[n - 2] === b[n - 2]);} export function applySnapshot(prev, delta, tick) {  const [phase, radius, cyc, cycRem, app, reset, orbAdd, orbRem, nm, arena, secondsLeft] = delta;  const out = { tick, phase, radius, cycles: {}, trails: {}, orbs: {}, names: {} };  if (arena) { out.arena = arena; out.secondsLeft = secondsLeft; }  if (prev) {    for (const id in prev.cycles) { out.cycles[id] = prev.cycles[id]; out.names[id] = prev.names[id]; out.trails[id] = prev.trails[id]; }    for (const id in prev.orbs) out.orbs[id] = prev.orbs[id];  }  for (const id of cycRem) { delete out.cycles[id]; delete out.names[id]; delete out.trails[id]; }  for (const c of cyc) out.cycles[c[0]] = c;  for (const id in nm) out.names[id] = nm[id];  for (const r of reset) out.trails[r[0]] = unpackTrail(r);  for (const a of app) {    const cur = out.trails[a[0]] || [a[1]];    const trimmed = (a[1] - cur[0]) * 2; // points dropped from the front since cur    const body = trimmed > 0 ? cur.slice(1 + trimmed) : cur.slice(1);    out.trails[a[0]] = [a[1]].concat(body.slice(0, a[2]), a.slice(3));  }  for (const o of orbAdd) out.orbs[o[0]] = [o[1], o[2]];  for (const id of orbRem) delete out.orbs[id];  return out;} export function encodeServerSnapshot(tick, baseTick, lastSeq, delta) { return ['s', tick, baseTick, lastSeq, delta]; } /** Full trails are delta-coded: [id, base, x0, y0, dx1, dy1, ...] (differences to the previous point). */function packTrail(id, nt) {  const n = nt.length - 1; // number of coordinates  const out = new Array(n + 2);  out[0] = id; out[1] = nt[0];  for (let k = 0; k < n; k++) out[k + 2] = k < 2 ? nt[k + 1] : nt[k + 1] - nt[k - 1];  return out;}function unpackTrail(r) {  const n = r.length - 2;  const out = new Array(n + 1);  out[0] = r[1];  for (let k = 0; k < n; k++) out[k + 1] = k < 2 ? r[k + 2] : out[k - 1] + r[k + 2];  return out;}