@homie-rocks/studio 0.46.0 → 0.46.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@homie-rocks/studio",
3
- "version": "0.46.0",
3
+ "version": "0.46.2",
4
4
  "description": "A studio for games, music and video on its own Cloudflare: scaffold, multiplayer starters on the netplay contract, a port toolkit that makes existing single-player web games multiplayer, the site Worker with public rooms (Table/Lobby Durable Objects and D1, all on the free Workers plan, no payment method), a site with the hub's sections (Home, Games, Music, Videos, Rooms, Posts with feeds) in the studio's own look, an epic landing page for every game, big songs and videos in the studio's own R2 once it has storage (uploaded, checked by SHA-256, served at the same addresses), deploy, and the homie.rocks directory.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -95,6 +95,7 @@
95
95
  }
96
96
  },
97
97
  "files": [
98
+ "docs/",
98
99
  "bin/",
99
100
  "lib/",
100
101
  "netplay/",
@@ -158,10 +159,11 @@
158
159
  "three": "0.185.1",
159
160
  "typescript": "5.9.3",
160
161
  "viem": "2.57.4",
162
+ "ws": "8.22.0",
161
163
  "zod": "4.3.6"
162
164
  },
163
165
  "scripts": {
164
166
  "test": "node --test --test-concurrency=2 --test-timeout=1800000 test/*.test.mjs",
165
- "prepack": "node ../../scripts/authoring-guides.mjs --check"
167
+ "prepack": "node lib/build-identity.mjs --check && node ../../scripts/authoring-guides.mjs --check"
166
168
  }
167
169
  }
package/rules/host.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { stageTimings } from './timing.mjs';
1
2
  /*
2
3
  * host.ts — the host runtime: a rules module playing the host's part on the wire.
3
4
  * =============================================================================
@@ -112,6 +113,8 @@ export interface Host {
112
113
  readonly privateDelivery: boolean;
113
114
  projectSnapshot(snap: any, seat: number | null): any;
114
115
  readonly viewSettings: Compiled['settings']['view'];
116
+ /** The studio's own pace on player messages (`room.rates`), or null: Homie sets none. */
117
+ readonly rates: Record<string, number> | null;
115
118
  frame(m: Record<string, unknown>): void;
116
119
  /** Start the tick loop (the first person has joined). */
117
120
  start(): void;
@@ -158,7 +161,7 @@ const SPEECH = /^(?:say|chat|emote)/i;
158
161
  /**
159
162
  * The overrun check's memory: the last few ticks that started in this isolate, whichever rooms' they were, each with
160
163
  * when it started. Time inside a Worker stands still while code runs, so a tick cannot time itself; but the start of
161
- * the next tick, in any room, shows how long it took. A tick that starts more than a period late blames the newest
164
+ * the next tick, in any room, gives a scheduling interval (including other work). A late callback suspects the newest
162
165
  * tick here that took more than a period: the one just before it, or, when that one was quick and was itself held up,
163
166
  * the one before that.
164
167
  */
@@ -395,6 +398,7 @@ export function createHost(o: HostOptions): Host {
395
398
  /** Where in a tick the runtime is, for the log line of a fault. */
396
399
  let phase = '';
397
400
  let faultLoggedAt = -Infinity;
401
+ const timing = stageTimings();
398
402
  const stats = { ticks: 0, late: 0, slips: 0, since: 0, ins: 0, dropped: 0, lateEntries: 0, loggedAt: 0, faults: 0, lastFault: '' };
399
403
  /** Something was thrown in the runtime itself: it is counted, and said in the log at most once a second. */
400
404
  function fault(where: string, error: unknown): void {
@@ -648,17 +652,26 @@ export function createHost(o: HostOptions): Host {
648
652
  }
649
653
  if (roundRebasePending) publishRebase(now);
650
654
  phase = 'step';
655
+ const rulesAt = timing.now();
651
656
  core.step(inputs, guideBeat);
657
+ timing.record('rules', rulesAt);
652
658
  phase = 'frames';
659
+ const framesAt = timing.now();
653
660
  const out = core.drain();
654
661
  handle(out, now);
662
+ timing.record('frames', framesAt);
655
663
  if (ended) return;
656
664
  phase = 'snapshot';
665
+ const snapshotAt = timing.now();
657
666
  const data = core.snapshot();
667
+ timing.record('snapshot', snapshotAt);
658
668
  const nextPhase = (data[0] as number[])[1];
659
669
  if (roundPhase === 1 && nextPhase === 0) forceSave = true;
660
670
  roundPhase = nextPhase;
671
+ const checkpointAt = timing.now();
661
672
  checkpoint(forceSave);
673
+ timing.record('checkpoint', checkpointAt);
674
+ const encodeAt = timing.now();
662
675
  // The control table: one row a seat, [seat, r, ack, lead].
663
676
  const rows: number[][] = [];
664
677
  for (const b of core.bodies()) {
@@ -671,13 +684,17 @@ export function createHost(o: HostOptions): Host {
671
684
  // apart to whoever interpolates between them. The stamp always rises: a replica drops one that does not.
672
685
  lastSt = Math.max(lastSt + 1, Math.round(Math.min(now, dueOf(core.tick))));
673
686
  const snap = { t: 'snap', from: null, e: epoch, k: core.tick, st: lastSt, d: data, c: rows };
674
- o.send(snap, JSON.stringify(snap));
687
+ const encoded = JSON.stringify(snap);
688
+ timing.record('encode', encodeAt);
689
+ const sendAt = timing.now();
690
+ o.send(snap, encoded);
691
+ timing.record('send', sendAt);
675
692
  stats.ticks += 1;
676
693
  stats.since += 1;
677
694
  if (now - stats.loggedAt >= 10_000) {
678
695
  // Tick figures, one line every ten seconds, never a line a tick.
679
696
  const s = core.stats;
680
- log({ ev: 'ticks', game: o.game, ...(o.build ? { build: o.build } : {}), tick: core.tick, ticks: stats.since, late: stats.late, slips: stats.slips, ins: stats.ins, lateEntries: stats.lateEntries, dropped: stats.dropped, errors: s.errors, budgetStops: s.budgetStops, cut: s.ticksCut, maxUnits: s.maxUnits, worst: s.worst, maxTickUnits: s.maxTickUnits, ...(s.lost ? { lost: s.lost } : {}), ...(stats.faults ? { faults: stats.faults, lastFault: stats.lastFault } : {}), ...(s.lastError ? { lastError: s.lastError } : {}) });
697
+ log({ ev: 'ticks', timing: timing.facts(), game: o.game, ...(o.build ? { build: o.build } : {}), tick: core.tick, ticks: stats.since, late: stats.late, slips: stats.slips, ins: stats.ins, lateEntries: stats.lateEntries, dropped: stats.dropped, errors: s.errors, budgetStops: s.budgetStops, cut: s.ticksCut, maxUnits: s.maxUnits, worst: s.worst, maxTickUnits: s.maxTickUnits, ...(s.lost ? { lost: s.lost } : {}), ...(stats.faults ? { faults: stats.faults, lastFault: stats.lastFault } : {}), ...(s.lastError ? { lastError: s.lastError } : {}) });
681
698
  stats.loggedAt = now; stats.since = 0; stats.late = 0; stats.ins = 0; stats.lateEntries = 0;
682
699
  }
683
700
  }
@@ -687,6 +704,7 @@ export function createHost(o: HostOptions): Host {
687
704
  * of the clock the room ends, and the log names the handler (or the fault).
688
705
  */
689
706
  function tick(now: number): void {
707
+ const tickAt = timing.now();
690
708
  const cut = core.stats.ticksCut;
691
709
  let faulted = false;
692
710
  if (persistent) pendingOutput = [];
@@ -698,8 +716,9 @@ export function createHost(o: HostOptions): Host {
698
716
  pendingOutput = null;
699
717
  faulted = true; fault(`tick ${core.tick} (${phase})`, error);
700
718
  // Never continue from uncommitted memory or retire the last good save.
701
- if (persistent) { stop(); o.onEnd?.('storage-or-tick-failed', { tick: core.tick }); return; }
719
+ if (persistent) { timing.record('tick', tickAt); stop(); o.onEnd?.('storage-or-tick-failed', { tick: core.tick }); return; }
702
720
  }
721
+ timing.record('tick', tickAt);
703
722
  if (ended) return;
704
723
  if (!faulted && core.stats.ticksCut === cut) { failingSince = null; return; }
705
724
  if (failingSince === null) failingSince = now;
@@ -753,8 +772,13 @@ export function createHost(o: HostOptions): Host {
753
772
  if (overSince !== null) {
754
773
  overTicks += 1;
755
774
  if (2 * overBlamed < overTicks) overSince = null;
756
- // A room whose ticks have run slow for five seconds of the clock ends, and the log names the handler that used the most units.
757
- else if (now - overSince >= OVERRUN_MS) { end('overrun', { worst: core.stats.worst, maxUnits: core.stats.maxUnits, seconds: Math.round((now - overSince) / 100) / 10 }); return; }
775
+ // Late callbacks can catch up at the requested rate. End only a
776
+ // blamed room that also loses sustained throughput, not a healthy
777
+ // 20 Hz room whose callbacks arrive in pairs during admission/I/O.
778
+ else if (now - overSince >= OVERRUN_MS) {
779
+ if (overTicks * period < (now - overSince) * 0.9) { end('overrun', { worst: core.stats.worst, maxUnits: core.stats.maxUnits, seconds: Math.round((now - overSince) / 100) / 10 }); return; }
780
+ overSince = null;
781
+ }
758
782
  }
759
783
  if (o.enforceOverrun) recent.push({ who: self, at: now });
760
784
  if (recent.length > 8) recent.shift();
@@ -837,7 +861,8 @@ export function createHost(o: HostOptions): Host {
837
861
  }
838
862
 
839
863
  function save(): Uint8Array {
840
- return toBytes({ v: 1, ...(characters.size ? { characters: [...characters.values()] } : {}), core: core.save(), guideViews: [...guideViews], ...(agents ? { agents: agents.save() } : savedAgents ? { agents: savedAgents } : {}), names: [...names].filter(([seat]) => !core.bodies().some(b => b.seat === seat && b.owner === 'reserved')), queues: [...queues].map(([seat, q]) => [seat, q.held, q.claim, q.newest, q.ack]), inputs: [...queues] });
864
+ const reserved = new Set(core.bodies().filter(b => b.owner === 'reserved').map(b => b.seat));
865
+ return toBytes({ v: 1, ...(characters.size ? { characters: [...characters.values()] } : {}), core: core.save(), guideViews: [...guideViews], ...(agents ? { agents: agents.save() } : savedAgents ? { agents: savedAgents } : {}), names: [...names].filter(([seat]) => !reserved.has(seat)), queues: [...queues].map(([seat, q]) => [seat, q.held, q.claim, q.newest, q.ack]), inputs: [...queues] });
841
866
  }
842
867
  function checkpoint(force = false): void {
843
868
  if (persistent) {
@@ -888,6 +913,7 @@ export function createHost(o: HostOptions): Host {
888
913
  },
889
914
  characterReturned(account, lease) { if (characters.get(account)?.returning && characters.get(account)?.lease === lease) characters.delete(account); },
890
915
  get viewSettings() { return c.settings.view; },
916
+ get rates() { return c.settings.rates ?? null; },
891
917
  get viewRadiusM() { return c.settings.view?.radiusM ?? null; },
892
918
  get tick() { return core.tick; },
893
919
  get epoch() { return epoch; },
@@ -903,7 +929,7 @@ export function createHost(o: HostOptions): Host {
903
929
  try { now = o.clock.now(); tick(now); } catch (error) { fault('tickNow', error); } finally { keepTime(); }
904
930
  },
905
931
  save,
906
- facts: () => ({ tick: core.tick, epoch, running, paused, ended, armed, people: people(), tickHz, ...stats, core: { ...core.stats } }),
932
+ facts: () => ({ timing: timing.facts(), tick: core.tick, epoch, running, paused, ended, armed, people: people(), tickHz, ...stats, core: { ...core.stats } }),
907
933
  core,
908
934
  };
909
935
  }
@@ -1,6 +1,7 @@
1
1
  /** Per-connection state delivery. Pure data, shared by the relay and the view.
2
2
  * Deltas may name a periodic keyframe or the previous ordered frame. A missing
3
- * chained predecessor is ignored until the next keyframe (at most one second).
3
+ * chained predecessor is ignored until the next keyframe. Periodic encoders
4
+ * repair the chain; ordered transports reset it on connection or epoch change.
4
5
  * No history grows with time: one keyframe per connection, no per-frame queue.
5
6
  */
6
7
  const spatial = new WeakMap(), controls = new WeakMap();
@@ -16,7 +17,7 @@ function indexFor(snap, radius) {
16
17
  const p = e[3], key = `${Math.floor(p[0]/size)},${Math.floor(p[1]/size)},${Math.floor((p[2]??0)/size)}`;
17
18
  const list = cells.get(key) ?? []; list.push(e); cells.set(key, list);
18
19
  }
19
- const index = { own, cells, size, order }; byRadius.set(radius,index); return index;
20
+ const index = { own, cells, size, order, candidates: new Map() }; byRadius.set(radius,index); return index;
20
21
  }
21
22
  export function interestSnapshot(snap, seat, radiusM) {
22
23
  const [round, entities] = snap.d;
@@ -27,50 +28,121 @@ export function interestSnapshot(snap, seat, radiusM) {
27
28
  if (own && radiusM === null) visible = entities;
28
29
  else if (own) {
29
30
  const q=own[3], x=Math.floor(q[0]/index.size), y=Math.floor(q[1]/index.size), z=Math.floor((q[2]??0)/index.size);
30
- for(let dx=-1;dx<=1;dx++)for(let dy=-1;dy<=1;dy++)for(let dz=-1;dz<=1;dz++)
31
- for(const e of index.cells.get(`${x+dx},${y+dy},${z+dz}`)??[]) {
32
- const p=e[3];
33
- if(e===own||(p[0]-q[0])**2+(p[1]-q[1])**2+((p[2]??0)-(q[2]??0))**2<=radiusM**2)visible.push(e);
34
- }
35
- // Snapshot order is part of the view contract, even though cells are not.
36
- visible.sort((a,b)=>index.order.get(a)-index.order.get(b));
31
+ const cell = `${x},${y},${z}`;
32
+ let candidates = index.candidates.get(cell);
33
+ if (!candidates) {
34
+ candidates = [];
35
+ for(let dx=-1;dx<=1;dx++)for(let dy=-1;dy<=1;dy++)for(let dz=-1;dz<=1;dz++)
36
+ candidates.push(...(index.cells.get(`${x+dx},${y+dy},${z+dz}`)??[]));
37
+ // Every player in this cell shares the ordered candidates. The final
38
+ // radius check remains exact for that player's position.
39
+ candidates.sort((a,b)=>index.order.get(a)-index.order.get(b));
40
+ index.candidates.set(cell, candidates);
41
+ }
42
+ for (const e of candidates) {
43
+ const p=e[3];
44
+ if(e===own||(p[0]-q[0])**2+(p[1]-q[1])**2+((p[2]??0)-(q[2]??0))**2<=radiusM**2)visible.push(e);
45
+ }
37
46
  }
38
47
  }
39
48
  let control = snap.c && controls.get(snap.c);
40
49
  if (!control) { control = new Map((snap.c ?? []).map(row => [row[0], row])); if (snap.c) controls.set(snap.c, control); }
41
50
  return { ...snap, d: [round, visible, ...snap.d.slice(2)], c: control.has(seat) ? [control.get(seat)] : [] };
42
51
  }
43
- const encodedRows = new WeakMap();
44
- const rowText = row => {
45
- let text=encodedRows.get(row);
46
- if(!text){text=row.map(v=>JSON.stringify(v));encodedRows.set(row,text);}
52
+ // Snapshot tuples contain primitives and small numeric arrays. Compare these
53
+ // values without allocating a JSON string for every field on every tick.
54
+ // Keep JSON equality for uncommon object-valued fields, including key order.
55
+ function sameValue(a, b) {
56
+ if (a === b) return true;
57
+ if (Array.isArray(a) && Array.isArray(b)) {
58
+ if (a.length !== b.length) return false;
59
+ for (let i = 0; i < a.length; i++) if (!sameValue(a[i], b[i])) return false;
60
+ return true;
61
+ }
62
+ if (a === null || b === null || typeof a !== 'object' && typeof b !== 'object') return false;
63
+ return JSON.stringify(a) === JSON.stringify(b);
64
+ }
65
+
66
+ // Entity rows are immutable snapshot values. Gates share their comparisons and
67
+ // wire fragments across players whose visual baselines contain the same row.
68
+ const changesByBase = new WeakMap(), wireRows = new WeakMap();
69
+ function changedRow(entity, before) {
70
+ let cached = changesByBase.get(before);
71
+ if (cached?.entity === entity) return cached.row;
72
+ let mask = 0; const values = [];
73
+ for (let i = 1; i < entity.length; i++) if (!sameValue(entity[i], before[i])) { mask |= 1 << i; values.push(entity[i]); }
74
+ const row = mask ? [entity[0], mask, values] : null;
75
+ // A delivery frame visits all players before the next immutable frame.
76
+ // Keep the most recent pair without allocating a WeakMap for every row.
77
+ if (cached) { cached.entity = entity; cached.row = row; }
78
+ else changesByBase.set(before, { entity, row });
79
+ return row;
80
+ }
81
+ function wireRow(row) {
82
+ let text = wireRows.get(row);
83
+ if (text === undefined) { text = JSON.stringify(row); wireRows.set(row, text); }
47
84
  return text;
48
- };
85
+ }
86
+ /** JSON wire equivalent of a snapshot, sharing immutable entity fragments. */
87
+ export function snapshotText(snap) {
88
+ const { d, ...header } = snap;
89
+ let data;
90
+ if (Array.isArray(d)) data = '[' + JSON.stringify(d[0]) + ',[' + d[1].map(wireRow).join(',') + ']' + d.slice(2).map(v => ',' + JSON.stringify(v)).join('') + ']';
91
+ else {
92
+ const { changed, own, ...meta } = d;
93
+ data = JSON.stringify(meta).slice(0, -1) + ',"changed":[' + changed.map(wireRow).join(',') + ']' + (own ? ',"own":[' + own.map(wireRow).join(',') + ']' : '') + '}';
94
+ }
95
+ return JSON.stringify(header).slice(0, -1) + ',"d":' + data + '}';
96
+ }
97
+
98
+ /** Whether a body that left `sent` at tick `sentTick` and kept its velocity is within `tolerance` of `entity` now. */
99
+ const POSITION = 1 << 3, VELOCITY = 1 << 4, HEADING = 1 << 5;
100
+ function coasts(entity, sent, ticks, hz, tolerance) {
101
+ const p = entity[3], q = sent[3], v = sent[4], t = ticks / hz;
102
+ for (let i = 0; i < p.length; i++) if (Math.abs(p[i] - (q[i] + v[i] * t)) > tolerance) return false;
103
+ // A heading is a unit vector: the same tolerance, as a turn of that many metres at one metre's reach.
104
+ const h = entity[5], g = sent[5];
105
+ if (Array.isArray(h) && Array.isArray(g)) for (let i = 0; i < h.length; i++) if (Math.abs(h[i] - g[i]) > COAST_HEADING) return false;
106
+ return true;
107
+ }
108
+ /** A heading a coasting body may be off by before it is sent again: a twentieth of a radian, under three degrees. */
109
+ const COAST_HEADING = 0.05;
49
110
 
50
- export function snapshotEncoder(keyframeTicks, chained = false) {
111
+ /**
112
+ * `coast` ({ hz, toleranceM }, chained encoders only): a body that is where its last SENT position and velocity
113
+ * put it, within the tolerance, is not sent again; the decoder moves it there itself (`d.coast`). A body in a
114
+ * crowd changes its position every tick and its course rarely, so most of a frame goes unsent. The tolerance is the
115
+ * game's own `view.precisionM`; without one nothing coasts. A player's own body is always sent, exactly.
116
+ */
117
+ export function snapshotEncoder(keyframeTicks, chained = false, coast = null) {
51
118
  let base = null;
52
- let rows = new Map(), keyTick = -Infinity;
119
+ let rows = new Map(), keyTick = -Infinity, generation = 0;
120
+ const coasting = chained && coast && coast.toleranceM > 0 && coast.hz > 0 ? coast : null;
53
121
  return {
54
- reset() { base = null; rows.clear(); keyTick = -Infinity; },
122
+ reset() { base = null; rows.clear(); keyTick = -Infinity; generation = 0; },
55
123
  encode(snap, seat = null) {
56
124
  if (!base || snap.e !== base.e || snap.k <= base.k || snap.k - keyTick >= keyframeTicks) {
57
125
  base = snap; keyTick = snap.k;
58
- rows = new Map(snap.d[1].map(e => [e[0], rowText(e)]));
59
- return snap;
126
+ rows = new Map(snap.d[1].map(e => [e[0], { entity: e, generation, k: snap.k }]));
127
+ return coasting ? { ...snap, coast: coasting.hz } : snap;
60
128
  }
61
- const present = new Set(), changed = [];
129
+ const changed = [], removed = []; generation++;
62
130
  const own = chained && seat !== null ? snap.d[1].filter(e => e[9] === seat && e[10] !== 1) : null;
63
131
  for (const entity of snap.d[1]) {
64
- const id = entity[0]; present.add(id);
65
- if (own?.includes(entity)) continue;
66
- const before = rows.get(id);
132
+ const id = entity[0], held = rows.get(id), before = held?.entity;
133
+ if (held) held.generation = generation;
134
+ else if (chained) rows.set(id, { entity, generation, k: snap.k });
135
+ if (own?.includes(entity)) { if (held && chained) { held.entity = entity; held.k = snap.k; } continue; }
67
136
  if (!before) { changed.push(entity); continue; }
68
- let mask = 0; const values = [];
69
- for (let i = 1; i < entity.length; i++) if (rowText(entity)[i] !== before[i]) { mask |= 1 << i; values.push(entity[i]); }
70
- if (mask) changed.push([id, mask, values]);
137
+ const change = changedRow(entity, before);
138
+ // Only where it is, how fast and which way it faces: anything else a body changed is always sent.
139
+ if (change && coasting && !(change[1] & ~(POSITION | VELOCITY | HEADING)) && coasts(entity, before, snap.k - held.k, coasting.hz, coasting.toleranceM)) continue;
140
+ if (held && chained) { held.entity = entity; held.k = snap.k; }
141
+ if (change) changed.push(change);
71
142
  }
72
- const out = { ...snap, d: { base: base.k, round: snap.d[0], ...(snap.d.length > 2 && JSON.stringify(snap.d[2]) !== JSON.stringify(base.d[2]) ? { collision: snap.d[2] } : {}), changed, removed: [...rows.keys()].filter(id => !present.has(id)), ...(chained ? { chain: true } : {}), ...(own ? { own } : {}) } };
73
- if (chained) { base = snap; rows = new Map(snap.d[1].map(e => [e[0], rowText(e)])); }
143
+ rows.forEach((held, id) => { if (held.generation !== generation) { removed.push(id); if (chained) rows.delete(id); } });
144
+ const out = { ...snap, ...(coasting ? { coast: coasting.hz } : {}), d: { base: base.k, round: snap.d[0], ...(snap.d.length > 2 && JSON.stringify(snap.d[2]) !== JSON.stringify(base.d[2]) ? { collision: snap.d[2] } : {}), changed, removed, ...(chained ? { chain: true } : {}), ...(own ? { own } : {}) } };
145
+ if (chained) base = snap;
74
146
  return out;
75
147
  },
76
148
  };
@@ -79,8 +151,21 @@ export function snapshotEncoder(keyframeTicks, chained = false) {
79
151
  export function snapshotDecoder() {
80
152
  let base = null;
81
153
  let rows = new Map();
154
+ // The tick each row was last SENT at: a frame that says `coast` leaves a body out while it keeps its course,
155
+ // and this end moves it along its last velocity. `rows` keeps what was sent; what is returned is where it is now.
156
+ let sentAt = new Map();
157
+ const coasted = (list, snap) => {
158
+ const hz = snap.coast;
159
+ if (!(hz > 0)) return list;
160
+ return list.map(row => {
161
+ const ticks = snap.k - (sentAt.get(row[0]) ?? snap.k), v = row[4];
162
+ if (ticks <= 0 || !Array.isArray(v) || !v.some(n => n !== 0)) return row;
163
+ const moved = row.slice(); moved[3] = row[3].map((n, i) => n + v[i] * ticks / hz);
164
+ return moved;
165
+ });
166
+ };
82
167
  return {
83
- reset() { base = null; rows.clear(); },
168
+ reset() { base = null; rows.clear(); sentAt.clear(); },
84
169
  decode(snap) {
85
170
  if (!snap || typeof snap !== 'object') return null;
86
171
  if (Array.isArray(snap.d)) {
@@ -89,6 +174,7 @@ export function snapshotDecoder() {
89
174
  // A late duplicate keyframe must not replace the newer baseline.
90
175
  if (!base || snap.e !== base.e || snap.k >= base.k) {
91
176
  base = snap; rows = new Map(snap.d[1].map(e => [e[0], e]));
177
+ sentAt = new Map(snap.d[1].map(e => [e[0], snap.k]));
92
178
  }
93
179
  return snap;
94
180
  }
@@ -105,13 +191,14 @@ export function snapshotDecoder() {
105
191
  for (const e of d.own) visible.set(e[0], e);
106
192
  return { ...snap, d: [d.round, [...visible.values()], ...(d.collision === undefined ? base.d.slice(2) : [d.collision])] };
107
193
  }
108
- const next = new Map(rows);
109
- for (const id of d.removed) next.delete(id);
194
+ // Validate first, then mutate only the private chained baseline. Returned
195
+ // snapshots keep their own entity array and immutable row values.
196
+ const updates = [];
110
197
  for (const change of d.changed) {
111
198
  if (!Array.isArray(change) || typeof change[0] !== 'string') return null;
112
199
  if (change.length !== 3) {
113
200
  if (change.length < 9) return null;
114
- next.set(change[0], change); continue;
201
+ updates.push(change); continue;
115
202
  }
116
203
  if (!Number.isInteger(change[1]) || change[1] < 0 || !Array.isArray(change[2])) return null;
117
204
  const old = rows.get(change[0]);
@@ -119,10 +206,13 @@ export function snapshotDecoder() {
119
206
  const entity = old.slice(); let j = 0;
120
207
  for (let i = 1; i < entity.length; i++) if (change[1] & (1 << i)) entity[i] = change[2][j++];
121
208
  if (j !== change[2].length) return null;
122
- next.set(entity[0], entity);
209
+ updates.push(entity);
123
210
  }
124
- for (const e of d.own ?? []) next.set(e[0], e);
125
- const decoded = { ...snap, d: [d.round, [...next.values()], ...(d.collision === undefined ? base.d.slice(2) : [d.collision])] };
211
+ const next = d.chain ? rows : new Map(rows);
212
+ for (const id of d.removed) { next.delete(id); if (d.chain) sentAt.delete(id); }
213
+ for (const entity of updates) { next.set(entity[0], entity); if (d.chain) sentAt.set(entity[0], snap.k); }
214
+ for (const e of d.own ?? []) { next.set(e[0], e); if (d.chain) sentAt.set(e[0], snap.k); }
215
+ const decoded = { ...snap, d: [d.round, coasted([...next.values()], snap), ...(d.collision === undefined ? base.d.slice(2) : [d.collision])] };
126
216
  if (d.chain) { base = decoded; rows = next; }
127
217
  return decoded;
128
218
  },
@@ -134,33 +224,212 @@ export function snapshotDecoder() {
134
224
  */
135
225
  const quantizedRows = new WeakMap();
136
226
  export function scheduledView({ radiusM = null, precisionM = 0, nearM = null, farHz = null } = {}, tickHz = 20) {
137
- let previous = new Map(), epoch = null;
227
+ const previous = new Map(); let epoch = null, generation = 0;
138
228
  return (snap, seat) => {
139
229
  if (snap.e !== epoch) { previous.clear(); epoch = snap.e; }
140
230
  const selected = interestSnapshot(snap, seat, radiusM);
141
231
  const own = selected.d[1].find(e => e[9] === seat && e[10] !== 1);
142
- const next = new Map();
143
- const entities = selected.d[1].map(entity => {
144
- let row = entity;
232
+ generation++;
233
+ // Radius selection already owns its array. Overview selection shares the
234
+ // source, so copy only that case before replacing rows with visual values.
235
+ const entities = selected.d[1] === snap.d[1] ? selected.d[1].slice() : selected.d[1];
236
+ for (let index = 0; index < entities.length; index++) {
237
+ const entity = entities[index], held = previous.get(entity[0]);
238
+ let row = entity, sampledTick = snap.k;
145
239
  if (entity !== own) {
146
- const distance = own ? Math.hypot(...entity[3].map((n, i) => n - (own[3][i] ?? 0))) : 0;
147
- const old = previous.get(entity[0]);
148
- const interval = farHz && nearM !== null && distance > nearM ? Math.max(1, Math.round(tickHz / farHz)) : 1;
149
- if (old && snap.k % interval !== 0) row = old;
150
- else if (precisionM > 0) {
240
+ const p = entity[3], q = own?.[3];
241
+ const distanceSquared = q ? (p[0]-q[0])**2 + (p[1]-q[1])**2 + ((p[2]??0)-(q[2]??0))**2 : 0;
242
+ const old = held?.row;
243
+ const interval = farHz && nearM !== null && distanceSquared > nearM**2 ? Math.max(1, Math.round(tickHz / farHz)) : 1;
244
+ // Spread far-view refreshes across players instead of sending the
245
+ // whole room's largest deltas on the same tick. Each player retains
246
+ // the declared rate; newly visible bodies still arrive immediately.
247
+ const phase = (seat ?? 0) % interval;
248
+ sampledTick = snap.k - ((snap.k - phase) % interval + interval) % interval;
249
+ // Coalescing may skip the exact phase. Refresh at the first delivered
250
+ // tick after it, instead of waiting indefinitely for that residue.
251
+ if (old && interval > 1 && snap.k - held.sampledTick < interval) {
252
+ row = old; sampledTick = held.sampledTick;
253
+ } else if (precisionM > 0) {
151
254
  let versions = quantizedRows.get(entity);
152
- if (!versions) { versions = new Map(); quantizedRows.set(entity, versions); }
153
- row = versions.get(precisionM);
255
+ row = versions?.precision === precisionM ? versions.row : versions?.others?.get(precisionM);
154
256
  if (!row) {
155
257
  row = entity.slice();
156
258
  for (const i of [3, 4]) row[i] = entity[i].map(n => Number((Math.round(n / precisionM) * precisionM).toPrecision(12)));
157
- versions.set(precisionM, row);
259
+ if (!versions) quantizedRows.set(entity, { precision: precisionM, row });
260
+ else { versions.others ??= new Map(); versions.others.set(precisionM, row); }
158
261
  }
159
262
  }
160
263
  }
161
- next.set(entity[0], row); return row;
162
- });
163
- previous = next;
164
- return { ...selected, d: [selected.d[0], entities, ...selected.d.slice(2)] };
264
+ if (held) { held.row = row; held.generation = generation; held.sampledTick = sampledTick; }
265
+ else previous.set(entity[0], { row, generation, sampledTick });
266
+ entities[index] = row;
267
+ }
268
+ previous.forEach((held, id) => { if (held.generation !== generation) previous.delete(id); });
269
+ selected.d[1] = entities;
270
+ return selected;
271
+ };
272
+ }
273
+
274
+ /* ------------------------------------------------------------------ a Gate's crowd path (0.46.2)
275
+ *
276
+ * One Gate holds a few dozen players of a room of hundreds, and each of them sees a few hundred bodies. Selecting,
277
+ * comparing and serialising every one of those for every player, twenty times a second, is what a Gate ran out of
278
+ * time doing on Cloudflare at a thousand players. This path does per WORLD what does not depend on the player (the
279
+ * visual value of each body, whether anything but its motion changed, the text of its row), and per player only
280
+ * what must be: is this body in range, and is it still where this player was last told it would be.
281
+ *
282
+ * It is the same wire as `scheduledView` + `snapshotEncoder(Infinity, true, coast)` and the same decoder reads it.
283
+ * It differs in one thing a player can see: a far body is not held still between its `farHz` refreshes and then
284
+ * moved; it coasts, and is sent again when it has strayed half the distance it covers between those refreshes.
285
+ */
286
+ const sameTail = (a, b) => {
287
+ if (a.length !== b.length || a[1] !== b[1] || a[2] !== b[2] || a[6] !== b[6]) return false;
288
+ for (let i = 7; i < a.length; i++) if (!sameValue(a[i], b[i])) return false;
289
+ return true;
290
+ };
291
+ /** What a Gate works out once for each world, whoever is looking. One per Gate. */
292
+ export function crowdWorlds({ radiusM = null, precisionM = 0 } = {}) {
293
+ const known = new Map(); let generation = 0, last = null, lastOut = null;
294
+ // A precision that is one over a whole number (0.01, 0.05, 0.25) rounds with one multiply and one divide, to the
295
+ // same number the longer way gives; any other takes the longer way.
296
+ const steps = precisionM > 0 ? 1 / precisionM : 0, whole = precisionM > 0 && Math.abs(steps - Math.round(steps)) < 1e-9 ? Math.round(steps) : 0;
297
+ const quantize = (v) => {
298
+ const out = new Array(v.length);
299
+ if (whole) for (let a = 0; a < v.length; a++) out[a] = Math.round(v[a] * whole) / whole;
300
+ else for (let a = 0; a < v.length; a++) out[a] = Number((Math.round(v[a] / precisionM) * precisionM).toPrecision(12));
301
+ return out;
302
+ };
303
+ return {
304
+ radiusM, precisionM,
305
+ of(snap) {
306
+ if (snap === last) return lastOut;
307
+ const entities = snap.d[1], n = entities.length; generation++;
308
+ const stamps = new Int32Array(n), visual = new Array(n), texts = new Array(n);
309
+ const own = new Map(), cells = new Map(), size = radiusM > 0 ? radiusM : 1;
310
+ for (let i = 0; i < n; i++) {
311
+ const e = entities[i]; let held = known.get(e[0]);
312
+ // The stamp moves when anything but position, velocity and heading changed: a field, a revision, a seat.
313
+ if (!held) { held = { row: e, stamp: 1, generation }; known.set(e[0], held); }
314
+ else { if (held.row !== e && !sameTail(held.row, e)) held.stamp++; held.row = e; held.generation = generation; }
315
+ stamps[i] = held.stamp;
316
+ if (e[9] !== undefined && e[10] !== 1) own.set(e[9], i);
317
+ if (radiusM !== null) {
318
+ const p = e[3], key = `${Math.floor(p[0] / size)},${Math.floor(p[1] / size)},${Math.floor((p[2] ?? 0) / size)}`;
319
+ const list = cells.get(key); if (list) list.push(i); else cells.set(key, [i]);
320
+ }
321
+ }
322
+ if (known.size > n) for (const [id, held] of known) if (held.generation !== generation) known.delete(id);
323
+ let all = radiusM === null ? Array.from({ length: n }, (_, i) => i) : null; const around = new Map();
324
+ const control = new Map((snap.c ?? []).map(row => [row[0], row]));
325
+ last = snap;
326
+ lastOut = {
327
+ entities, stamps, own, control, size,
328
+ rest: snap.d.slice(2), restText: snap.d.length > 2 ? JSON.stringify(snap.d[2]) : null,
329
+ /** The body as others see it: the game's precision on where and how fast, a thousandth on which way. */
330
+ visual(i) {
331
+ let row = visual[i];
332
+ if (row === undefined) {
333
+ const e = entities[i];
334
+ if (precisionM > 0) {
335
+ row = e.slice();
336
+ row[3] = quantize(e[3]); row[4] = quantize(e[4]);
337
+ if (Array.isArray(e[5])) { const h = e[5], out = new Array(h.length); for (let a = 0; a < h.length; a++) out[a] = Math.round(h[a] * 1000) / 1000; row[5] = out; }
338
+ } else row = e;
339
+ visual[i] = row;
340
+ }
341
+ return row;
342
+ },
343
+ /** `[id, mask, values]` as text, for a change of only where, how fast and which way (mask of bits 3, 4, 5). */
344
+ motion(i, mask) {
345
+ const slot = texts[i] ??= {}; let text = slot[mask];
346
+ if (text === undefined) {
347
+ const row = this.visual(i), values = [];
348
+ for (let f = 3; f <= 5; f++) if (mask & (1 << f)) values.push(row[f]);
349
+ text = slot[mask] = JSON.stringify([row[0], mask, values]);
350
+ }
351
+ return text;
352
+ },
353
+ everything() { return all ??= Array.from({ length: n }, (_, i) => i); },
354
+ /** Indices of every body in the nine (or 27) cells about a point, in the world's order. */
355
+ near(p) {
356
+ if (radiusM === null) return this.everything();
357
+ const x = Math.floor(p[0] / size), y = Math.floor(p[1] / size), z = Math.floor((p[2] ?? 0) / size), key = `${x},${y},${z}`;
358
+ let list = around.get(key);
359
+ if (!list) {
360
+ list = [];
361
+ for (let dx = -1; dx <= 1; dx++) for (let dy = -1; dy <= 1; dy++) for (let dz = -1; dz <= 1; dz++) { const cell = cells.get(`${x + dx},${y + dy},${z + dz}`); if (cell) for (const i of cell) list.push(i); }
362
+ list.sort((a, b) => a - b); around.set(key, list);
363
+ }
364
+ return list;
365
+ },
366
+ };
367
+ return lastOut;
368
+ },
369
+ };
370
+ }
371
+ const sameVec = (a, b) => { if (a === b) return true; if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false; for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false; return true; };
372
+ /** One player's view of a Gate's worlds: `(snap, seat)` to the text of the frame to send them. */
373
+ export function crowdView(worlds, { nearM = null, farHz = null } = {}, tickHz = 20) {
374
+ const rows = new Map(); let epoch, tick = -Infinity, generation = 0, collision = null;
375
+ const { radiusM, precisionM } = worlds, reach = radiusM === null ? Infinity : radiusM * radiusM;
376
+ const nearSq = nearM !== null && farHz ? nearM * nearM : Infinity, farShare = farHz ? 0.5 / farHz : 0;
377
+ return (snap, seat) => {
378
+ const w = worlds.of(snap), { entities, stamps } = w;
379
+ const me = seat === null ? undefined : w.own.get(seat), mine = me === undefined ? null : entities[me], q = mine?.[3];
380
+ const key = tick === -Infinity || snap.e !== epoch || snap.k <= tick, baseTick = tick;
381
+ if (key) rows.clear();
382
+ epoch = snap.e; tick = snap.k; generation++;
383
+ const control = w.control.get(seat);
384
+ const head = JSON.stringify({ t: 'snap', from: null, k: snap.k, st: snap.st, ...(snap.e !== undefined ? { e: snap.e } : {}), c: control ? [control] : [], coast: tickHz }).slice(0, -1);
385
+ // A player with no body of their own (a screen) is shown the whole room; one whose body is gone, nothing.
386
+ const candidates = seat === null ? w.everything() : mine ? w.near(q) : [];
387
+ const parts = [];
388
+ for (let n = 0; n < candidates.length; n++) {
389
+ const i = candidates[n], e = entities[i];
390
+ let far = false;
391
+ if (e !== mine && q) {
392
+ const p = e[3]; let d = 0;
393
+ for (let a = 0; a < p.length; a++) d += (p[a] - q[a]) ** 2;
394
+ if (d > reach) continue;
395
+ far = d > nearSq;
396
+ }
397
+ const row = e === mine ? e : w.visual(i);
398
+ let held = rows.get(e[0]);
399
+ if (!held) { rows.set(e[0], { row, k: snap.k, stamp: stamps[i], generation }); if (e !== mine || key) parts.push(wireRow(row)); continue; }
400
+ held.generation = generation;
401
+ if (e === mine) { held.row = row; held.k = snap.k; held.stamp = stamps[i]; continue; }
402
+ const before = held.row;
403
+ if (held.stamp === stamps[i]) {
404
+ // Only its motion can differ. Where its last sent position and velocity put it now, within the game's
405
+ // precision (near) or half the way it goes between far refreshes: this player is told nothing.
406
+ const p = row[3], b = before[3], v = before[4], t = (snap.k - held.k) / tickHz;
407
+ let tolerance = precisionM;
408
+ if (far) { let speed = 0; for (let a = 0; a < v.length; a++) speed += v[a] * v[a]; tolerance = Math.max(precisionM, Math.sqrt(speed) * farShare); }
409
+ let there = true;
410
+ for (let a = 0; a < p.length; a++) if (Math.abs(p[a] - (b[a] + v[a] * t)) > tolerance) { there = false; break; }
411
+ if (there) {
412
+ const h = row[5], g = before[5];
413
+ if (Array.isArray(h) && Array.isArray(g)) for (let a = 0; a < h.length; a++) if (Math.abs(h[a] - g[a]) > COAST_HEADING) { there = false; break; }
414
+ }
415
+ if (there && tolerance > 0) continue;
416
+ const mask = (sameVec(p, b) ? 0 : POSITION) | (sameVec(row[4], v) ? 0 : VELOCITY) | (sameVec(row[5], before[5]) ? 0 : HEADING);
417
+ if (!mask) continue;
418
+ held.row = row; held.k = snap.k;
419
+ parts.push(w.motion(i, mask));
420
+ continue;
421
+ }
422
+ const change = changedRow(row, before);
423
+ held.row = row; held.k = snap.k; held.stamp = stamps[i];
424
+ if (change) parts.push(wireRow(change));
425
+ }
426
+ if (key) {
427
+ collision = w.restText;
428
+ return head + ',"d":[' + JSON.stringify(snap.d[0]) + ',[' + parts.join(',') + ']' + w.rest.map(v => ',' + JSON.stringify(v)).join('') + ']}';
429
+ }
430
+ let removed = '';
431
+ if (rows.size > 0) for (const [id, held] of rows) if (held.generation !== generation) { removed += (removed ? ',' : '') + JSON.stringify(id); rows.delete(id); }
432
+ const changedCollision = w.restText !== collision; collision = w.restText;
433
+ return head + ',"d":{"base":' + baseTick + ',"round":' + JSON.stringify(snap.d[0]) + (changedCollision && w.restText !== null ? ',"collision":' + w.restText : '') + ',"removed":[' + removed + '],"chain":true,"changed":[' + parts.join(',') + ']' + (mine ? ',"own":[' + wireRow(mine) + ']' : '') + '}}';
165
434
  };
166
435
  }