@usions/sdk 2.21.0 → 2.24.0

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.
@@ -16,6 +16,7 @@ import { Lockstep } from './netcode/lockstep.js';
16
16
  import { LagCompensator } from './netcode/lagcomp.js';
17
17
  import { diff, patch, quantize } from './netcode/delta.js';
18
18
  import { encode, decode } from './netcode/binary.js';
19
+ import { createInterestGrid } from './netcode/interest-grid.js';
19
20
 
20
21
  export function applyGameNetcode(game, Usion) {
21
22
  game.diff = diff;
@@ -28,6 +29,7 @@ export function applyGameNetcode(game, Usion) {
28
29
  game.createPredictor = function (opts) { return new Predictor(opts || {}); };
29
30
  game.createLagCompensator = function (opts) { return new LagCompensator(opts || {}); };
30
31
  game.createLockstep = function (opts) { return new Lockstep(opts || {}); };
32
+ game.createInterestGrid = function (opts) { return createInterestGrid(opts || {}); };
31
33
 
32
34
  // ── Realtime channel router ──────────────────────────────────────────────
33
35
  // Multiplexes realtime by action_type so replicate / mesh / mesh-network and
@@ -313,6 +315,7 @@ export function applyGameNetcode(game, Usion) {
313
315
  const id = self._pingMeter.begin();
314
316
  let done = false;
315
317
  const finish = function () { if (done) return; done = true; resolve(self._pingMeter.end(id)); };
318
+ finish.sentAt = Date.now(); // lets the pong pair feed getNetworkStats' EWMA too
316
319
  self._pongWaiters.push(finish);
317
320
  self._sendDirect('ping', { t: Date.now() });
318
321
  setTimeout(function () {
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Usion SDK Game Resilience (SDK >= 2.24) - direct-mode liveness watchdog,
3
+ * token-reuse fast reconnect, input backpressure, and network stats/quality.
4
+ * State lives on game._res; game-direct.js calls the small _res* hooks here.
5
+ * Relay mode gets getNetworkStats()/onNetworkQuality() too (quality from the
6
+ * connection-state machine; no relay RTT measurement in this module).
7
+ */
8
+
9
+ /** @typedef {{probeAfterMs: number, deadAfterMs: number}} LivenessCfg */
10
+
11
+ /** @param {any} game @param {any} Usion */
12
+ export function applyGameResilience(game, Usion) {
13
+ var res = {
14
+ liveness: /** @type {LivenessCfg|null} */ ({ probeAfterMs: 4000, deadAfterMs: 12000 }),
15
+ backpressureBytes: 8192,
16
+ lastInboundAt: 0,
17
+ lastProbeAt: 0,
18
+ lastCloseCode: /** @type {number|null} */ (null),
19
+ declaredDead: false,
20
+ watchdogTimer: /** @type {*} */ (null),
21
+ drainTimer: /** @type {*} */ (null),
22
+ pendingInput: /** @type {*} */ (null),
23
+ visHandler: /** @type {*} */ (null),
24
+ lastVisResyncAt: 0,
25
+ wrappedDisconnect: false,
26
+ rtt: /** @type {number|null} */ (null),
27
+ jitter: 0,
28
+ quality: 'dead',
29
+ };
30
+ game._res = res;
31
+
32
+ /** EWMA (a=0.3) over ping->pong RTT samples. @param {number} sample */
33
+ function feedRtt(sample) {
34
+ if (!(sample >= 0)) return;
35
+ if (res.rtt == null) { res.rtt = sample; res.jitter = 0; return; }
36
+ res.jitter += 0.3 * (Math.abs(sample - res.rtt) - res.jitter);
37
+ res.rtt += 0.3 * (sample - res.rtt);
38
+ }
39
+
40
+ function measuredRtt() { // game.ping() samples count too (any transport)
41
+ if (res.rtt != null) return { rtt: res.rtt, jitter: res.jitter };
42
+ var m = game._pingMeter;
43
+ return m && m.rtt != null ? { rtt: m.rtt, jitter: m.jitter } : { rtt: null, jitter: null };
44
+ }
45
+
46
+ function computeQuality() {
47
+ var state = game.getConnectionState ? game.getConnectionState()
48
+ : (game.connected ? 'connected' : 'disconnected');
49
+ if (res.declaredDead || state === 'disconnected') return 'dead';
50
+ if (game.directMode && (!game.directSocket || game.directSocket.readyState !== 1)) return 'dead';
51
+ var rtt = measuredRtt().rtt || 0;
52
+ var age = (game.directMode && res.lastInboundAt) ? Date.now() - res.lastInboundAt : 0;
53
+ return (rtt < 150 && age < 2000) ? 'good' : (rtt < 400 && age < 5000) ? 'fair' : 'poor';
54
+ }
55
+
56
+ /** Dispatches networkQuality on TRANSITIONS only. */
57
+ function evaluate() {
58
+ var q = computeQuality();
59
+ if (q === res.quality) return;
60
+ var prev = res.quality;
61
+ res.quality = q;
62
+ game._dispatch('networkQuality', { quality: q, prev: prev, stats: game.getNetworkStats() });
63
+ }
64
+
65
+ /** Cheap snapshot of tracked connection-health numbers. */
66
+ game.getNetworkStats = function () {
67
+ var direct = !!game.directMode;
68
+ var s = direct ? game.directSocket : null;
69
+ var m = measuredRtt();
70
+ return {
71
+ transport: direct ? 'direct' : 'relay',
72
+ connectionState: game.getConnectionState ? game.getConnectionState() : 'disconnected',
73
+ quality: res.quality,
74
+ rtt: m.rtt,
75
+ jitter: m.jitter,
76
+ lastInboundAgeMs: (direct && res.lastInboundAt) ? Math.max(0, Date.now() - res.lastInboundAt) : null,
77
+ bufferedAmount: s ? (s.bufferedAmount || 0) : null,
78
+ };
79
+ };
80
+
81
+ /** Quality transitions ({quality, prev, stats}); returns unsubscribe. @param {Function} callback */
82
+ game.onNetworkQuality = function (callback) { return game._setHandler('networkQuality', callback); };
83
+
84
+ function stopWatchdog() {
85
+ if (res.watchdogTimer) { clearInterval(res.watchdogTimer); res.watchdogTimer = null; }
86
+ }
87
+
88
+ /** One plain RTT ping ({t}) - never {last_sequence} (that is a resync). */
89
+ function sendProbe() {
90
+ var s = game.directSocket;
91
+ if (!s || s.readyState !== 1) return;
92
+ var now = Date.now();
93
+ var w = /** @type {any} */ (function () {}); // stats-only pong waiter
94
+ w.sentAt = now;
95
+ w.statsOnly = true;
96
+ game._pongWaiters.push(w);
97
+ res.lastProbeAt = now;
98
+ game._sendDirect('ping', { t: now });
99
+ }
100
+
101
+ function watchdogTick() {
102
+ var s = game.directSocket;
103
+ if (!game.directMode || !s || s.readyState !== 1) { stopWatchdog(); return; }
104
+ if (res.liveness) {
105
+ var age = Date.now() - res.lastInboundAt;
106
+ if (age >= res.liveness.deadAfterMs) {
107
+ // Silent-dead: declare + close; the onclose path then reconnects.
108
+ res.declaredDead = true;
109
+ stopWatchdog();
110
+ Usion.log('Direct socket liveness timeout - declaring dead');
111
+ evaluate();
112
+ game._dispatch('disconnect', 'liveness_timeout');
113
+ try { s.close(); } catch (e) { /* noop */ }
114
+ return;
115
+ }
116
+ if (age >= res.liveness.probeAfterMs
117
+ && Date.now() - res.lastProbeAt >= res.liveness.probeAfterMs) sendProbe();
118
+ }
119
+ evaluate();
120
+ }
121
+
122
+ /** connectDirect(config) options -> clamped _res settings. @param {any} config */
123
+ game._resConfigure = function (config) {
124
+ if (config.liveness === false) {
125
+ res.liveness = null;
126
+ } else {
127
+ var lv = (config.liveness && typeof config.liveness === 'object') ? config.liveness : {};
128
+ var probe = isFinite(lv.probeAfterMs) ? Math.max(1000, lv.probeAfterMs) : 4000;
129
+ var dead = isFinite(lv.deadAfterMs) ? lv.deadAfterMs : 12000;
130
+ res.liveness = { probeAfterMs: probe, deadAfterMs: Math.max(dead, probe + 2000) };
131
+ }
132
+ if (config.backpressureBytes === false || config.backpressureBytes === 0) res.backpressureBytes = 0;
133
+ else if (typeof config.backpressureBytes === 'number' && config.backpressureBytes > 0) res.backpressureBytes = config.backpressureBytes;
134
+ };
135
+
136
+ /** Direct socket opened: reset state, start watchdog + foreground resync. */
137
+ game._resOnOpen = function () {
138
+ res.declaredDead = false;
139
+ res.lastCloseCode = null;
140
+ res.lastInboundAt = Date.now();
141
+ res.lastProbeAt = 0;
142
+ stopWatchdog();
143
+ res.watchdogTimer = setInterval(watchdogTick, 1000);
144
+ addVisibility();
145
+ if (!res.wrappedDisconnect) { // clear timers even if onclose never fires
146
+ res.wrappedDisconnect = true;
147
+ var orig = game.disconnect;
148
+ game.disconnect = function () { teardown(); return orig.apply(game, arguments); };
149
+ }
150
+ evaluate();
151
+ };
152
+
153
+ /** @param {any} evt CloseEvent - code kept for the token-reuse decision. */
154
+ game._resOnClose = function (evt) {
155
+ res.lastCloseCode = (evt && typeof evt.code === 'number') ? evt.code : null;
156
+ teardown();
157
+ evaluate();
158
+ };
159
+
160
+ /** Pong: feed the stats EWMA from the matched waiter. @param {any} waiter */
161
+ game._resOnPong = function (waiter) {
162
+ if (waiter && typeof waiter.sentAt === 'number') feedRtt(Date.now() - waiter.sentAt);
163
+ evaluate();
164
+ };
165
+
166
+ /** Reuse the cached room token on reconnect while safely un-expired. */
167
+ game._resCanReuseToken = function () {
168
+ if (res.lastCloseCode === 4401) return false; // auth reject -> refetch
169
+ var cfg = game.directConfig;
170
+ if (!cfg || !cfg.ws_url || !cfg.access_token) return false;
171
+ var exp = parseExpiry(cfg.expires_at);
172
+ return exp != null && exp - Date.now() > 30000;
173
+ };
174
+
175
+ /**
176
+ * Backpressure for realtime 'input' frames: while the send buffer is above
177
+ * the threshold hold the LATEST frame only; drain when it clears.
178
+ * @param {any} payload @returns {boolean} true = held, don't send now
179
+ */
180
+ game._resHoldInput = function (payload) {
181
+ if (!res.backpressureBytes) return false;
182
+ var s = game.directSocket;
183
+ if (!s || (res.pendingInput == null && !(s.bufferedAmount > res.backpressureBytes))) return false;
184
+ res.pendingInput = payload; // latest-only: newer input replaces stale
185
+ if (!res.drainTimer) res.drainTimer = setTimeout(drainInput, 50);
186
+ return true;
187
+ };
188
+
189
+ function drainInput() {
190
+ res.drainTimer = null;
191
+ var s = game.directSocket;
192
+ if (!s || s.readyState !== 1) { res.pendingInput = null; return; }
193
+ if (res.pendingInput == null) return;
194
+ if (s.bufferedAmount > res.backpressureBytes) { res.drainTimer = setTimeout(drainInput, 50); return; }
195
+ var p = res.pendingInput;
196
+ res.pendingInput = null;
197
+ game._sendDirect('input', p);
198
+ }
199
+
200
+ /** Defensive expires_at parse (ISO or epoch); null = doubt -> refetch. @param {*} v */
201
+ function parseExpiry(v) {
202
+ if (typeof v === 'number' && isFinite(v)) return v > 1e12 ? v : v * 1000;
203
+ if (typeof v === 'string' && v) {
204
+ var t = Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(v) ? v : v + 'Z'); // bare ISO = UTC
205
+ return isNaN(t) ? null : t;
206
+ }
207
+ return null;
208
+ }
209
+
210
+ function teardown() {
211
+ stopWatchdog();
212
+ if (res.drainTimer) { clearTimeout(res.drainTimer); res.drainTimer = null; }
213
+ res.pendingInput = null;
214
+ removeVisibility();
215
+ if (game._pongWaiters && game._pongWaiters.length) {
216
+ game._pongWaiters = game._pongWaiters.filter(function (/** @type {any} */ w) { return !w.statsOnly; });
217
+ }
218
+ }
219
+
220
+ /** Foreground: probe immediately + throttled requestSync. */
221
+ function addVisibility() {
222
+ if (typeof document === 'undefined' || !document.addEventListener || res.visHandler) return;
223
+ res.visHandler = function () {
224
+ if (document.visibilityState !== 'visible' || !game.directMode || !game._joined) return;
225
+ sendProbe();
226
+ var now = Date.now();
227
+ if (now - res.lastVisResyncAt >= 2000) {
228
+ res.lastVisResyncAt = now;
229
+ try { game.requestSync(game._lastSequence || 0); } catch (e) { /* non-fatal */ }
230
+ }
231
+ };
232
+ document.addEventListener('visibilitychange', res.visHandler);
233
+ }
234
+
235
+ function removeVisibility() {
236
+ if (res.visHandler && typeof document !== 'undefined' && document.removeEventListener) {
237
+ document.removeEventListener('visibilitychange', res.visHandler);
238
+ }
239
+ res.visHandler = null;
240
+ }
241
+
242
+ // Re-evaluate quality on connection events (covers relay mode too).
243
+ game.on('disconnect', evaluate);
244
+ game.on('connectionState', evaluate);
245
+ }
@@ -7,12 +7,19 @@
7
7
  *
8
8
  * const m = await Usion.matchmaking.find(); // resolves when matched
9
9
  * await Usion.game.connect(); await Usion.game.join(m.roomId);
10
- * // ...or cancel while waiting:
10
+ * // ...or bound the wait / cancel while waiting:
11
+ * const m2 = await Usion.matchmaking.find(null, { timeout: 30000 });
11
12
  * Usion.matchmaking.cancel();
12
13
  * Usion.matchmaking.onMatch(({ roomId, players }) => { ... });
13
14
  */
15
+ import { UsionError, toUsionError, ERROR_CODES } from './errors.js';
16
+
17
+ // World placement is a single backend round-trip (no queue wait), so the
18
+ // bound is fixed rather than caller-supplied like find()'s opts.timeout.
19
+ const WORLD_JOIN_TIMEOUT_MS = 15000;
20
+
14
21
  export function createMatchmakingModule(Usion) {
15
- let pending = null; // { resolve, reject } for an in-flight find()
22
+ let pending = null; // active placement entry: { resolve, reject }
16
23
  let onMatchCb = null;
17
24
  let bound = false;
18
25
 
@@ -30,31 +37,103 @@ export function createMatchmakingModule(Usion) {
30
37
  });
31
38
  }
32
39
 
40
+ /**
41
+ * Shared mm-channel placement used by find() (queue matches) and
42
+ * game.joinWorld() (world backfill): register the resolver, bound the wait,
43
+ * emit mm:join, and resolve from the immediate-placement ack
44
+ * ({queued:false, matched:true, room_id, player_ids}) or the mm:matched
45
+ * push — whichever arrives first.
46
+ * @param {object} payload - mm:join payload
47
+ * @param {number} [timeout] - ms until MATCH_TIMEOUT (falsy = wait forever)
48
+ * @param {string} timeoutMessage
49
+ */
50
+ function place(payload, timeout, timeoutMessage) {
51
+ bind();
52
+
53
+ if (pending) {
54
+ const old = pending; pending = null;
55
+ old.reject(new UsionError(ERROR_CODES.SUPERSEDED, 'Superseded by a newer find()'));
56
+ }
57
+
58
+ let timer = null;
59
+ const entry = {};
60
+ const promise = new Promise(function (resolve, reject) {
61
+ entry.resolve = function (r) {
62
+ if (timer) clearTimeout(timer);
63
+ resolve(r);
64
+ };
65
+ entry.reject = function (e) {
66
+ if (timer) clearTimeout(timer);
67
+ if (pending === entry) pending = null;
68
+ reject(e);
69
+ };
70
+ });
71
+
72
+ // Register BEFORE emitting mm:join: when someone is already waiting in
73
+ // the queue, mm:matched can arrive ahead of the join ack — registering
74
+ // afterwards dropped that instant match and left find() hanging forever.
75
+ pending = entry;
76
+
77
+ if (timeout > 0) {
78
+ timer = setTimeout(function () {
79
+ timer = null;
80
+ Usion._backendEmit('mm:cancel', {}).catch(function () { /* best-effort dequeue */ });
81
+ entry.reject(new UsionError(ERROR_CODES.MATCH_TIMEOUT,
82
+ timeoutMessage + timeout + 'ms'));
83
+ }, timeout);
84
+ }
85
+
86
+ Usion._backendEmit('mm:join', payload)
87
+ .then(function (ack) {
88
+ // Immediate placement (world rooms): the ack itself carries the room.
89
+ // The mm:matched push may still follow; pending is already cleared,
90
+ // so it can't double-resolve.
91
+ if (ack && ack.matched && ack.room_id && pending === entry) {
92
+ pending = null;
93
+ entry.resolve(normalize(ack));
94
+ }
95
+ })
96
+ .catch(function (err) {
97
+ if (pending === entry) entry.reject(toUsionError(err));
98
+ });
99
+
100
+ return promise;
101
+ }
102
+
33
103
  return {
34
104
  /** Register a handler called whenever a match is found. */
35
105
  onMatch: function (cb) { onMatchCb = cb; bind(); },
36
106
 
37
107
  /**
38
108
  * Join the queue for `serviceId` (defaults to the current game) and resolve
39
- * when matched with { roomId, players, serviceId }. Stays pending until a
40
- * match (use cancel() to stop waiting).
109
+ * when matched with { roomId, players, serviceId }. Without `opts.timeout`
110
+ * it stays pending until a match (use cancel() to stop waiting); with it,
111
+ * rejects MATCH_TIMEOUT (and leaves the queue) once the wait elapses.
112
+ * @param {string} [serviceId]
113
+ * @param {{size?: number, timeout?: number}} [opts]
41
114
  */
42
115
  find: function (serviceId, opts) {
43
116
  opts = opts || {};
44
117
  const sid = serviceId || (Usion.config && Usion.config.serviceId);
45
- bind();
46
- const self = this;
47
- return Usion._backendEmit('mm:join', { service_id: sid, size: opts.size || 2 }).then(function () {
48
- return new Promise(function (resolve, reject) {
49
- if (pending) pending.reject(new Error('superseded'));
50
- pending = { resolve: resolve, reject: reject };
51
- });
52
- });
118
+ return place({ service_id: sid, size: opts.size || 2 }, opts.timeout, 'No match within ');
119
+ },
120
+
121
+ /**
122
+ * @private SDK-internal — use Usion.game.joinWorld(). Immediate placement
123
+ * into a drop-in/drop-out world room over the same mm channel.
124
+ * @param {string} [serviceId]
125
+ */
126
+ _joinWorld: function (serviceId) {
127
+ const sid = serviceId || (Usion.config && Usion.config.serviceId);
128
+ return place({ service_id: sid, mode: 'world' }, WORLD_JOIN_TIMEOUT_MS, 'No world placement within ');
53
129
  },
54
130
 
55
131
  /** Leave the queue / stop waiting. */
56
132
  cancel: function () {
57
- if (pending) { pending.reject(new Error('cancelled')); pending = null; }
133
+ if (pending) {
134
+ const old = pending; pending = null;
135
+ old.reject(new UsionError(ERROR_CODES.CANCELLED, 'cancelled'));
136
+ }
58
137
  return Usion._backendEmit('mm:cancel', {});
59
138
  },
60
139
  };
@@ -127,9 +127,10 @@ export const miscMethods = {
127
127
  * Listen for messages from parent app
128
128
  * @param {string} type - Message type to listen for
129
129
  * @param {function} callback - Handler function
130
+ * @returns {function} Unsubscribe function
130
131
  */
131
132
  on: function(type, callback) {
132
- window.addEventListener('message', function(event) {
133
+ function listener(event) {
133
134
  if (!isTrustedMessageSource(event)) return;
134
135
 
135
136
  let data;
@@ -142,6 +143,10 @@ export const miscMethods = {
142
143
  if (data.type === type) {
143
144
  callback(data);
144
145
  }
145
- });
146
+ }
147
+ window.addEventListener('message', listener);
148
+ return function() {
149
+ window.removeEventListener('message', listener);
150
+ };
146
151
  }
147
152
  };
@@ -14,6 +14,7 @@
14
14
  * MeshNetwork — N-peer full mesh
15
15
  * diff / patch / quantize — JSON delta compression (id-keyed arrays)
16
16
  * encode / decode — compact binary codec
17
+ * createInterestGrid — spatial hash for area-of-interest (AOI) filtering
17
18
  */
18
19
  import { SnapshotInterpolation, Vault } from './interpolation.js';
19
20
  import { Predictor } from './prediction.js';
@@ -27,15 +28,16 @@ import { Lockstep } from './lockstep.js';
27
28
  import { LagCompensator } from './lagcomp.js';
28
29
  import { diff, patch, quantize } from './delta.js';
29
30
  import { encode, decode } from './binary.js';
31
+ import { createInterestGrid } from './interest-grid.js';
30
32
 
31
33
  export const netcode = {
32
34
  SnapshotInterpolation, Vault, Predictor, Coalescer, PingMeter,
33
35
  MeshConnection, MeshNetwork, WebTransportConnection, NetworkSim, Lockstep, LagCompensator,
34
- diff, patch, quantize, encode, decode,
36
+ diff, patch, quantize, encode, decode, createInterestGrid,
35
37
  };
36
38
 
37
39
  export {
38
40
  SnapshotInterpolation, Vault, Predictor, Coalescer, PingMeter,
39
41
  MeshConnection, MeshNetwork, WebTransportConnection, NetworkSim, Lockstep, LagCompensator,
40
- diff, patch, quantize, encode, decode,
42
+ diff, patch, quantize, encode, decode, createInterestGrid,
41
43
  };
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Usion SDK Netcode — Interest grid (area-of-interest spatial hash).
3
+ *
4
+ * Buckets entities into fixed-size cells so "who is near (x, y)?" costs a few
5
+ * cell lookups instead of an O(N) scan — the building block for world rooms
6
+ * where each client should only receive nearby state (AOI filtering). Pure
7
+ * JS, no DOM/window references: the same helper runs in the browser and in a
8
+ * Node game server producing per-player snapshots.
9
+ *
10
+ * const grid = Usion.netcode.createInterestGrid({ cellSize: 256 });
11
+ * grid.upsert('p1', 120, 40); // insert or move
12
+ * grid.query(0, 0, 300); // → ids within 300 units (circle)
13
+ * const { entered, left, visible } = grid.observe('p1', 120, 40, 500);
14
+ * // entered → spawn for this observer; left → despawn (diffed per observer)
15
+ */
16
+
17
+ /** @typedef {string|number} InterestGridId */
18
+
19
+ /**
20
+ * @param {*} id
21
+ * @param {string} method
22
+ * @returns {InterestGridId}
23
+ */
24
+ function checkId(id, method) {
25
+ const ok = (typeof id === 'string' && id.length > 0)
26
+ || (typeof id === 'number' && isFinite(id));
27
+ if (!ok) {
28
+ throw new Error('interestGrid.' + method + ': id must be a non-empty string or a finite number');
29
+ }
30
+ return id;
31
+ }
32
+
33
+ /**
34
+ * @param {*} value
35
+ * @param {string} name
36
+ * @param {string} method
37
+ * @returns {number}
38
+ */
39
+ function checkFinite(value, name, method) {
40
+ if (typeof value !== 'number' || !isFinite(value)) {
41
+ throw new Error('interestGrid.' + method + ': ' + name + ' must be a finite number');
42
+ }
43
+ return value;
44
+ }
45
+
46
+ /**
47
+ * @param {*} value
48
+ * @param {string} method
49
+ * @returns {number}
50
+ */
51
+ function checkRadius(value, method) {
52
+ checkFinite(value, 'radius', method);
53
+ if (value < 0) throw new Error('interestGrid.' + method + ': radius must be >= 0');
54
+ return value;
55
+ }
56
+
57
+ /**
58
+ * Create an interest grid.
59
+ * @param {{cellSize?: number}} [opts] - cellSize (world units) defaults to 256;
60
+ * pick roughly the typical query radius so lookups touch ~4–9 cells.
61
+ */
62
+ export function createInterestGrid(opts) {
63
+ opts = opts || {};
64
+ const cellSize = opts.cellSize != null ? opts.cellSize : 256;
65
+ if (typeof cellSize !== 'number' || !isFinite(cellSize) || cellSize <= 0) {
66
+ throw new Error('createInterestGrid: cellSize must be a finite number > 0');
67
+ }
68
+
69
+ /** @type {Map<InterestGridId, {x: number, y: number, key: string}>} */
70
+ const entities = new Map();
71
+ /** @type {Map<string, Set<InterestGridId>>} */
72
+ const cells = new Map();
73
+ // Per-observer visible sets. `prev`/`next` are swapped (never reallocated)
74
+ // each observe() call — this runs per tick per observer.
75
+ /** @type {Map<InterestGridId, {prev: Set<InterestGridId>, next: Set<InterestGridId>}>} */
76
+ const observers = new Map();
77
+
78
+ /** @param {string} key @param {InterestGridId} id */
79
+ function addToCell(key, id) {
80
+ let set = cells.get(key);
81
+ if (!set) { set = new Set(); cells.set(key, set); }
82
+ set.add(id);
83
+ }
84
+
85
+ /** @param {string} key @param {InterestGridId} id */
86
+ function removeFromCell(key, id) {
87
+ const set = cells.get(key);
88
+ if (!set) return;
89
+ set.delete(id);
90
+ if (set.size === 0) cells.delete(key);
91
+ }
92
+
93
+ /**
94
+ * Visit every entity within `radius` of (x, y): scan the cells the circle's
95
+ * bounding box overlaps, then apply a true circle test per entity.
96
+ * @param {number} x @param {number} y @param {number} radius
97
+ * @param {(id: InterestGridId) => void} visit
98
+ */
99
+ function forEachInRadius(x, y, radius, visit) {
100
+ const r2 = radius * radius;
101
+ const minCx = Math.floor((x - radius) / cellSize);
102
+ const maxCx = Math.floor((x + radius) / cellSize);
103
+ const minCy = Math.floor((y - radius) / cellSize);
104
+ const maxCy = Math.floor((y + radius) / cellSize);
105
+ for (let cx = minCx; cx <= maxCx; cx++) {
106
+ for (let cy = minCy; cy <= maxCy; cy++) {
107
+ const set = cells.get(cx + ',' + cy);
108
+ if (!set) continue;
109
+ for (const id of set) {
110
+ const ent = entities.get(id);
111
+ if (!ent) continue;
112
+ const dx = ent.x - x;
113
+ const dy = ent.y - y;
114
+ if (dx * dx + dy * dy <= r2) visit(id);
115
+ }
116
+ }
117
+ }
118
+ }
119
+
120
+ return {
121
+ /**
122
+ * Insert an entity or move an existing one.
123
+ * @param {InterestGridId} id @param {number} x @param {number} y
124
+ */
125
+ upsert: function (id, x, y) {
126
+ checkId(id, 'upsert');
127
+ checkFinite(x, 'x', 'upsert');
128
+ checkFinite(y, 'y', 'upsert');
129
+ const key = Math.floor(x / cellSize) + ',' + Math.floor(y / cellSize);
130
+ const ent = entities.get(id);
131
+ if (ent) {
132
+ ent.x = x;
133
+ ent.y = y;
134
+ if (ent.key !== key) {
135
+ removeFromCell(ent.key, id);
136
+ addToCell(key, id);
137
+ ent.key = key;
138
+ }
139
+ return;
140
+ }
141
+ entities.set(id, { x: x, y: y, key: key });
142
+ addToCell(key, id);
143
+ },
144
+
145
+ /**
146
+ * Remove an entity. Unknown ids are a no-op.
147
+ * @param {InterestGridId} id
148
+ */
149
+ remove: function (id) {
150
+ checkId(id, 'remove');
151
+ const ent = entities.get(id);
152
+ if (!ent) return;
153
+ entities.delete(id);
154
+ removeFromCell(ent.key, id);
155
+ },
156
+
157
+ /**
158
+ * All entity ids within `radius` of (x, y) — a circle test, not just
159
+ * cell membership.
160
+ * @param {number} x @param {number} y @param {number} radius
161
+ * @returns {InterestGridId[]}
162
+ */
163
+ query: function (x, y, radius) {
164
+ checkFinite(x, 'x', 'query');
165
+ checkFinite(y, 'y', 'query');
166
+ checkRadius(radius, 'query');
167
+ /** @type {InterestGridId[]} */
168
+ const out = [];
169
+ forEachInRadius(x, y, radius, function (id) { out.push(id); });
170
+ return out;
171
+ },
172
+
173
+ /**
174
+ * Like query(), but diffed against this observer's previous observe():
175
+ * `entered` are ids newly visible, `left` are ids no longer visible,
176
+ * `visible` is the full current set. Drive spawn/despawn messages from
177
+ * entered/left and per-tick snapshots from visible.
178
+ * @param {InterestGridId} observerId @param {number} x @param {number} y @param {number} radius
179
+ * @returns {{entered: InterestGridId[], left: InterestGridId[], visible: InterestGridId[]}}
180
+ */
181
+ observe: function (observerId, x, y, radius) {
182
+ checkId(observerId, 'observe');
183
+ checkFinite(x, 'x', 'observe');
184
+ checkFinite(y, 'y', 'observe');
185
+ checkRadius(radius, 'observe');
186
+ let tracker = observers.get(observerId);
187
+ if (!tracker) {
188
+ tracker = { prev: new Set(), next: new Set() };
189
+ observers.set(observerId, tracker);
190
+ }
191
+ const prev = tracker.prev;
192
+ const next = tracker.next;
193
+ next.clear();
194
+ /** @type {InterestGridId[]} */
195
+ const entered = [];
196
+ /** @type {InterestGridId[]} */
197
+ const left = [];
198
+ /** @type {InterestGridId[]} */
199
+ const visible = [];
200
+ forEachInRadius(x, y, radius, function (id) {
201
+ next.add(id);
202
+ visible.push(id);
203
+ if (!prev.has(id)) entered.push(id);
204
+ });
205
+ for (const id of prev) {
206
+ if (!next.has(id)) left.push(id);
207
+ }
208
+ tracker.prev = next;
209
+ tracker.next = prev; // reused as scratch on the next call
210
+ return { entered: entered, left: left, visible: visible };
211
+ },
212
+
213
+ /**
214
+ * Free an observer's tracking state (call when a player leaves).
215
+ * @param {InterestGridId} observerId
216
+ */
217
+ dropObserver: function (observerId) {
218
+ checkId(observerId, 'dropObserver');
219
+ observers.delete(observerId);
220
+ },
221
+
222
+ /** @returns {number} Number of entities in the grid. */
223
+ size: function () {
224
+ return entities.size;
225
+ },
226
+ };
227
+ }