@usions/sdk 2.22.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.
@@ -29,6 +29,7 @@ export const ERROR_CODES = {
29
29
  VALUE_TOO_LARGE: 'VALUE_TOO_LARGE', // Single value over the per-value quota
30
30
  LOBBY_FULL: 'LOBBY_FULL', // Lobby at max_players
31
31
  LOBBY_CLOSED: 'LOBBY_CLOSED', // Lobby exists but is not open
32
+ WORLD_FULL: 'WORLD_FULL', // World room at max_players
32
33
  CONFLICT: 'CONFLICT', // Concurrent-write conflict; retry
33
34
  RATE_LIMITED: 'RATE_LIMITED', // Too many calls; back off (see retryAfter)
34
35
  REQUEST_TIMEOUT: 'REQUEST_TIMEOUT', // Host/parent did not reply in time
@@ -78,6 +79,7 @@ const BACKEND_PATTERNS = [
78
79
  [/value too large/i, ERROR_CODES.VALUE_TOO_LARGE],
79
80
  [/lobby is full/i, ERROR_CODES.LOBBY_FULL],
80
81
  [/lobby is not open/i, ERROR_CODES.LOBBY_CLOSED],
82
+ [/world room is full/i, ERROR_CODES.WORLD_FULL],
81
83
  [/not found|unknown service/i, ERROR_CODES.NOT_FOUND],
82
84
  [/conflict/i, ERROR_CODES.CONFLICT],
83
85
  [/cancelled/i, ERROR_CODES.CANCELLED],
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  import { applyGameDirect } from './game-direct.js';
6
+ import { applyGameResilience } from './game-resilience.js';
6
7
  import { applyGameSocket } from './game-socket.js';
7
8
  import { applyGameProxy } from './game-proxy.js';
8
9
  import { applyGameMethods } from './game-methods.js';
@@ -31,6 +32,7 @@ const _EVENT_ALIASES = {
31
32
  room_assigned: 'roomAssigned',
32
33
  connection_state: 'connectionState',
33
34
  reconnected: 'reconnected',
35
+ network_quality: 'networkQuality',
34
36
  };
35
37
 
36
38
  function _normalizeEventName(event) {
@@ -245,6 +247,8 @@ export function createGameModule(Usion) {
245
247
 
246
248
  // Apply sub-modules
247
249
  applyGameDirect(game, Usion);
250
+ // Direct-mode liveness/backpressure + network stats (hooks into game-direct).
251
+ applyGameResilience(game, Usion);
248
252
  applyGameSocket(game, Usion);
249
253
  applyGameProxy(game, Usion);
250
254
  applyGameMethods(game, Usion);
@@ -24,6 +24,7 @@ export function applyGameDirect(game, Usion) {
24
24
  return self._connectPromise;
25
25
  }
26
26
 
27
+ if (self._resConfigure) self._resConfigure(config); // liveness/backpressure opts → game._res
27
28
  self._connecting = true;
28
29
  self.directMode = true;
29
30
  self._autoReconnect = config.autoReconnect !== undefined
@@ -134,6 +135,7 @@ export function applyGameDirect(game, Usion) {
134
135
  self._sendDirect('heartbeat', {});
135
136
  }
136
137
  }, 25000);
138
+ if (self._resOnOpen) self._resOnOpen(); // start liveness watchdog + foreground resync
137
139
  resolve();
138
140
  };
139
141
 
@@ -145,6 +147,7 @@ export function applyGameDirect(game, Usion) {
145
147
  };
146
148
 
147
149
  ws.onclose = function(evt) {
150
+ if (self._resOnClose) self._resOnClose(evt); // capture close code, stop timers
148
151
  self.connected = false;
149
152
  self._joined = false;
150
153
  self._joinPromise = null;
@@ -160,6 +163,7 @@ export function applyGameDirect(game, Usion) {
160
163
  };
161
164
 
162
165
  ws.onmessage = function(evt) {
166
+ if (self._res) self._res.lastInboundAt = Date.now(); // any bytes = alive
163
167
  self._handleDirectMessage(evt && evt.data);
164
168
  };
165
169
  });
@@ -180,7 +184,9 @@ export function applyGameDirect(game, Usion) {
180
184
  if (!self.directMode) { self._reconnecting = false; return; } // disconnected meanwhile
181
185
  attempt += 1;
182
186
  self._reconnectAttempt = attempt;
183
- self._fetchDirectAccess({})
187
+ // Reuse the cached room token while valid (skips the access round trip).
188
+ var reuse = self._resCanReuseToken && self._resCanReuseToken();
189
+ (reuse ? Promise.resolve(self.directConfig) : self._fetchDirectAccess({}))
184
190
  .then(function(access) { self.directConfig = access; return self._initDirectSocket(access); })
185
191
  .then(function() {
186
192
  self.connected = true;
@@ -195,11 +201,13 @@ export function applyGameDirect(game, Usion) {
195
201
  setTimeout(go, delay);
196
202
  });
197
203
  };
198
- setTimeout(go, 500);
204
+ setTimeout(go, 100); // fast first attempt; exponential backoff after
199
205
  };
200
206
 
201
207
  game._sendDirect = function(type, payload) {
202
208
  if (!this.directSocket || this.directSocket.readyState !== WebSocket.OPEN) return;
209
+ // Backpressure (input frames only): hold latest while the buffer is full.
210
+ if (type === 'input' && this._resHoldInput && this._resHoldInput(payload)) return;
203
211
  this._directSeq = this._directSeq + 1;
204
212
  this.directSocket.send(JSON.stringify({
205
213
  type: type,
@@ -241,11 +249,10 @@ export function applyGameDirect(game, Usion) {
241
249
  return;
242
250
  }
243
251
  if (data.type === 'pong') {
244
- // Resolve a pending game.ping() RTT probe, if any.
245
- if (this._pongWaiters && this._pongWaiters.length) {
246
- const waiter = this._pongWaiters.shift();
247
- if (waiter) waiter();
248
- }
252
+ // Resolve a pending game.ping() RTT probe, if any; feed the stats EWMA.
253
+ var waiter = (this._pongWaiters && this._pongWaiters.length) ? this._pongWaiters.shift() : null;
254
+ if (this._resOnPong) this._resOnPong(waiter);
255
+ if (waiter) waiter();
249
256
  this._dispatch('sync', payload);
250
257
  return;
251
258
  }
@@ -88,6 +88,30 @@ export function applyGameMethods(game, Usion) {
88
88
  return self._joinPromise;
89
89
  };
90
90
 
91
+ /**
92
+ * Place this player into a drop-in/drop-out WORLD room (SDK ≥ 2.23).
93
+ *
94
+ * World rooms (services tagged `world`) run continuously: players enter and
95
+ * leave at any time instead of playing fixed matches. Placement rides the
96
+ * matchmaking channel (works embedded AND standalone): the platform returns
97
+ * the world you're already in, else backfills a world with space, else
98
+ * creates a new one. On success `game.roomId` is set, so the usual
99
+ * `connect()`+`join()` (platform relay) or `connectDirect()` (direct/hosted)
100
+ * flow works unchanged afterwards. Rejects with MATCH_TIMEOUT after 15s.
101
+ *
102
+ * @param {object} [opts]
103
+ * @param {string} [opts.serviceId] - Defaults to the current service.
104
+ * @returns {Promise<{roomId: string, playerIds: string[]}>}
105
+ */
106
+ game.joinWorld = function(opts) {
107
+ const self = this;
108
+ opts = opts || {};
109
+ return Usion.matchmaking._joinWorld(opts.serviceId).then(function(m) {
110
+ self.roomId = m.roomId;
111
+ return { roomId: m.roomId, playerIds: m.players || [] };
112
+ });
113
+ };
114
+
91
115
  /**
92
116
  * Leave the current game room
93
117
  */
@@ -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
+ }
@@ -14,8 +14,12 @@
14
14
  */
15
15
  import { UsionError, toUsionError, ERROR_CODES } from './errors.js';
16
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
+
17
21
  export function createMatchmakingModule(Usion) {
18
- let pending = null; // active find() entry: { resolve, reject }
22
+ let pending = null; // active placement entry: { resolve, reject }
19
23
  let onMatchCb = null;
20
24
  let bound = false;
21
25
 
@@ -33,6 +37,69 @@ export function createMatchmakingModule(Usion) {
33
37
  });
34
38
  }
35
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
+
36
103
  return {
37
104
  /** Register a handler called whenever a match is found. */
38
105
  onMatch: function (cb) { onMatchCb = cb; bind(); },
@@ -48,47 +115,17 @@ export function createMatchmakingModule(Usion) {
48
115
  find: function (serviceId, opts) {
49
116
  opts = opts || {};
50
117
  const sid = serviceId || (Usion.config && Usion.config.serviceId);
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 (opts.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
- 'No match within ' + opts.timeout + 'ms'));
83
- }, opts.timeout);
84
- }
85
-
86
- Usion._backendEmit('mm:join', { service_id: sid, size: opts.size || 2 })
87
- .catch(function (err) {
88
- if (pending === entry) entry.reject(toUsionError(err));
89
- });
118
+ return place({ service_id: sid, size: opts.size || 2 }, opts.timeout, 'No match within ');
119
+ },
90
120
 
91
- return promise;
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 ');
92
129
  },
93
130
 
94
131
  /** Leave the queue / stop waiting. */
@@ -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
  };