@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.
package/src/browser.js CHANGED
@@ -32,6 +32,7 @@ var Usion = (function () {
32
32
  VALUE_TOO_LARGE: 'VALUE_TOO_LARGE', // Single value over the per-value quota
33
33
  LOBBY_FULL: 'LOBBY_FULL', // Lobby at max_players
34
34
  LOBBY_CLOSED: 'LOBBY_CLOSED', // Lobby exists but is not open
35
+ WORLD_FULL: 'WORLD_FULL', // World room at max_players
35
36
  CONFLICT: 'CONFLICT', // Concurrent-write conflict; retry
36
37
  RATE_LIMITED: 'RATE_LIMITED', // Too many calls; back off (see retryAfter)
37
38
  REQUEST_TIMEOUT: 'REQUEST_TIMEOUT', // Host/parent did not reply in time
@@ -81,6 +82,7 @@ var Usion = (function () {
81
82
  [/value too large/i, ERROR_CODES.VALUE_TOO_LARGE],
82
83
  [/lobby is full/i, ERROR_CODES.LOBBY_FULL],
83
84
  [/lobby is not open/i, ERROR_CODES.LOBBY_CLOSED],
85
+ [/world room is full/i, ERROR_CODES.WORLD_FULL],
84
86
  [/not found|unknown service/i, ERROR_CODES.NOT_FOUND],
85
87
  [/conflict/i, ERROR_CODES.CONFLICT],
86
88
  [/cancelled/i, ERROR_CODES.CANCELLED],
@@ -189,7 +191,7 @@ var Usion = (function () {
189
191
  * Core Usion object with init, _post, _request
190
192
  */
191
193
  const core = {
192
- version: '2.22.0', // injected from package.json at build
194
+ version: '2.24.0', // injected from package.json at build
193
195
  config: {},
194
196
  _initialized: false,
195
197
  _initCallback: null,
@@ -1464,6 +1466,7 @@ var Usion = (function () {
1464
1466
  return self._connectPromise;
1465
1467
  }
1466
1468
 
1469
+ if (self._resConfigure) self._resConfigure(config); // liveness/backpressure opts → game._res
1467
1470
  self._connecting = true;
1468
1471
  self.directMode = true;
1469
1472
  self._autoReconnect = config.autoReconnect !== undefined
@@ -1574,6 +1577,7 @@ var Usion = (function () {
1574
1577
  self._sendDirect('heartbeat', {});
1575
1578
  }
1576
1579
  }, 25000);
1580
+ if (self._resOnOpen) self._resOnOpen(); // start liveness watchdog + foreground resync
1577
1581
  resolve();
1578
1582
  };
1579
1583
 
@@ -1585,6 +1589,7 @@ var Usion = (function () {
1585
1589
  };
1586
1590
 
1587
1591
  ws.onclose = function(evt) {
1592
+ if (self._resOnClose) self._resOnClose(evt); // capture close code, stop timers
1588
1593
  self.connected = false;
1589
1594
  self._joined = false;
1590
1595
  self._joinPromise = null;
@@ -1600,6 +1605,7 @@ var Usion = (function () {
1600
1605
  };
1601
1606
 
1602
1607
  ws.onmessage = function(evt) {
1608
+ if (self._res) self._res.lastInboundAt = Date.now(); // any bytes = alive
1603
1609
  self._handleDirectMessage(evt && evt.data);
1604
1610
  };
1605
1611
  });
@@ -1620,7 +1626,9 @@ var Usion = (function () {
1620
1626
  if (!self.directMode) { self._reconnecting = false; return; } // disconnected meanwhile
1621
1627
  attempt += 1;
1622
1628
  self._reconnectAttempt = attempt;
1623
- self._fetchDirectAccess({})
1629
+ // Reuse the cached room token while valid (skips the access round trip).
1630
+ var reuse = self._resCanReuseToken && self._resCanReuseToken();
1631
+ (reuse ? Promise.resolve(self.directConfig) : self._fetchDirectAccess({}))
1624
1632
  .then(function(access) { self.directConfig = access; return self._initDirectSocket(access); })
1625
1633
  .then(function() {
1626
1634
  self.connected = true;
@@ -1635,11 +1643,13 @@ var Usion = (function () {
1635
1643
  setTimeout(go, delay);
1636
1644
  });
1637
1645
  };
1638
- setTimeout(go, 500);
1646
+ setTimeout(go, 100); // fast first attempt; exponential backoff after
1639
1647
  };
1640
1648
 
1641
1649
  game._sendDirect = function(type, payload) {
1642
1650
  if (!this.directSocket || this.directSocket.readyState !== WebSocket.OPEN) return;
1651
+ // Backpressure (input frames only): hold latest while the buffer is full.
1652
+ if (type === 'input' && this._resHoldInput && this._resHoldInput(payload)) return;
1643
1653
  this._directSeq = this._directSeq + 1;
1644
1654
  this.directSocket.send(JSON.stringify({
1645
1655
  type: type,
@@ -1681,11 +1691,10 @@ var Usion = (function () {
1681
1691
  return;
1682
1692
  }
1683
1693
  if (data.type === 'pong') {
1684
- // Resolve a pending game.ping() RTT probe, if any.
1685
- if (this._pongWaiters && this._pongWaiters.length) {
1686
- const waiter = this._pongWaiters.shift();
1687
- if (waiter) waiter();
1688
- }
1694
+ // Resolve a pending game.ping() RTT probe, if any; feed the stats EWMA.
1695
+ var waiter = (this._pongWaiters && this._pongWaiters.length) ? this._pongWaiters.shift() : null;
1696
+ if (this._resOnPong) this._resOnPong(waiter);
1697
+ if (waiter) waiter();
1689
1698
  this._dispatch('sync', payload);
1690
1699
  return;
1691
1700
  }
@@ -1699,6 +1708,252 @@ var Usion = (function () {
1699
1708
  };
1700
1709
  }
1701
1710
 
1711
+ /**
1712
+ * Usion SDK Game Resilience (SDK >= 2.24) - direct-mode liveness watchdog,
1713
+ * token-reuse fast reconnect, input backpressure, and network stats/quality.
1714
+ * State lives on game._res; game-direct.js calls the small _res* hooks here.
1715
+ * Relay mode gets getNetworkStats()/onNetworkQuality() too (quality from the
1716
+ * connection-state machine; no relay RTT measurement in this module).
1717
+ */
1718
+
1719
+ /** @typedef {{probeAfterMs: number, deadAfterMs: number}} LivenessCfg */
1720
+
1721
+ /** @param {any} game @param {any} Usion */
1722
+ function applyGameResilience(game, Usion) {
1723
+ var res = {
1724
+ liveness: /** @type {LivenessCfg|null} */ ({ probeAfterMs: 4000, deadAfterMs: 12000 }),
1725
+ backpressureBytes: 8192,
1726
+ lastInboundAt: 0,
1727
+ lastProbeAt: 0,
1728
+ lastCloseCode: /** @type {number|null} */ (null),
1729
+ declaredDead: false,
1730
+ watchdogTimer: /** @type {*} */ (null),
1731
+ drainTimer: /** @type {*} */ (null),
1732
+ pendingInput: /** @type {*} */ (null),
1733
+ visHandler: /** @type {*} */ (null),
1734
+ lastVisResyncAt: 0,
1735
+ wrappedDisconnect: false,
1736
+ rtt: /** @type {number|null} */ (null),
1737
+ jitter: 0,
1738
+ quality: 'dead',
1739
+ };
1740
+ game._res = res;
1741
+
1742
+ /** EWMA (a=0.3) over ping->pong RTT samples. @param {number} sample */
1743
+ function feedRtt(sample) {
1744
+ if (!(sample >= 0)) return;
1745
+ if (res.rtt == null) { res.rtt = sample; res.jitter = 0; return; }
1746
+ res.jitter += 0.3 * (Math.abs(sample - res.rtt) - res.jitter);
1747
+ res.rtt += 0.3 * (sample - res.rtt);
1748
+ }
1749
+
1750
+ function measuredRtt() { // game.ping() samples count too (any transport)
1751
+ if (res.rtt != null) return { rtt: res.rtt, jitter: res.jitter };
1752
+ var m = game._pingMeter;
1753
+ return m && m.rtt != null ? { rtt: m.rtt, jitter: m.jitter } : { rtt: null, jitter: null };
1754
+ }
1755
+
1756
+ function computeQuality() {
1757
+ var state = game.getConnectionState ? game.getConnectionState()
1758
+ : (game.connected ? 'connected' : 'disconnected');
1759
+ if (res.declaredDead || state === 'disconnected') return 'dead';
1760
+ if (game.directMode && (!game.directSocket || game.directSocket.readyState !== 1)) return 'dead';
1761
+ var rtt = measuredRtt().rtt || 0;
1762
+ var age = (game.directMode && res.lastInboundAt) ? Date.now() - res.lastInboundAt : 0;
1763
+ return (rtt < 150 && age < 2000) ? 'good' : (rtt < 400 && age < 5000) ? 'fair' : 'poor';
1764
+ }
1765
+
1766
+ /** Dispatches networkQuality on TRANSITIONS only. */
1767
+ function evaluate() {
1768
+ var q = computeQuality();
1769
+ if (q === res.quality) return;
1770
+ var prev = res.quality;
1771
+ res.quality = q;
1772
+ game._dispatch('networkQuality', { quality: q, prev: prev, stats: game.getNetworkStats() });
1773
+ }
1774
+
1775
+ /** Cheap snapshot of tracked connection-health numbers. */
1776
+ game.getNetworkStats = function () {
1777
+ var direct = !!game.directMode;
1778
+ var s = direct ? game.directSocket : null;
1779
+ var m = measuredRtt();
1780
+ return {
1781
+ transport: direct ? 'direct' : 'relay',
1782
+ connectionState: game.getConnectionState ? game.getConnectionState() : 'disconnected',
1783
+ quality: res.quality,
1784
+ rtt: m.rtt,
1785
+ jitter: m.jitter,
1786
+ lastInboundAgeMs: (direct && res.lastInboundAt) ? Math.max(0, Date.now() - res.lastInboundAt) : null,
1787
+ bufferedAmount: s ? (s.bufferedAmount || 0) : null,
1788
+ };
1789
+ };
1790
+
1791
+ /** Quality transitions ({quality, prev, stats}); returns unsubscribe. @param {Function} callback */
1792
+ game.onNetworkQuality = function (callback) { return game._setHandler('networkQuality', callback); };
1793
+
1794
+ function stopWatchdog() {
1795
+ if (res.watchdogTimer) { clearInterval(res.watchdogTimer); res.watchdogTimer = null; }
1796
+ }
1797
+
1798
+ /** One plain RTT ping ({t}) - never {last_sequence} (that is a resync). */
1799
+ function sendProbe() {
1800
+ var s = game.directSocket;
1801
+ if (!s || s.readyState !== 1) return;
1802
+ var now = Date.now();
1803
+ var w = /** @type {any} */ (function () {}); // stats-only pong waiter
1804
+ w.sentAt = now;
1805
+ w.statsOnly = true;
1806
+ game._pongWaiters.push(w);
1807
+ res.lastProbeAt = now;
1808
+ game._sendDirect('ping', { t: now });
1809
+ }
1810
+
1811
+ function watchdogTick() {
1812
+ var s = game.directSocket;
1813
+ if (!game.directMode || !s || s.readyState !== 1) { stopWatchdog(); return; }
1814
+ if (res.liveness) {
1815
+ var age = Date.now() - res.lastInboundAt;
1816
+ if (age >= res.liveness.deadAfterMs) {
1817
+ // Silent-dead: declare + close; the onclose path then reconnects.
1818
+ res.declaredDead = true;
1819
+ stopWatchdog();
1820
+ Usion.log('Direct socket liveness timeout - declaring dead');
1821
+ evaluate();
1822
+ game._dispatch('disconnect', 'liveness_timeout');
1823
+ try { s.close(); } catch (e) { /* noop */ }
1824
+ return;
1825
+ }
1826
+ if (age >= res.liveness.probeAfterMs
1827
+ && Date.now() - res.lastProbeAt >= res.liveness.probeAfterMs) sendProbe();
1828
+ }
1829
+ evaluate();
1830
+ }
1831
+
1832
+ /** connectDirect(config) options -> clamped _res settings. @param {any} config */
1833
+ game._resConfigure = function (config) {
1834
+ if (config.liveness === false) {
1835
+ res.liveness = null;
1836
+ } else {
1837
+ var lv = (config.liveness && typeof config.liveness === 'object') ? config.liveness : {};
1838
+ var probe = isFinite(lv.probeAfterMs) ? Math.max(1000, lv.probeAfterMs) : 4000;
1839
+ var dead = isFinite(lv.deadAfterMs) ? lv.deadAfterMs : 12000;
1840
+ res.liveness = { probeAfterMs: probe, deadAfterMs: Math.max(dead, probe + 2000) };
1841
+ }
1842
+ if (config.backpressureBytes === false || config.backpressureBytes === 0) res.backpressureBytes = 0;
1843
+ else if (typeof config.backpressureBytes === 'number' && config.backpressureBytes > 0) res.backpressureBytes = config.backpressureBytes;
1844
+ };
1845
+
1846
+ /** Direct socket opened: reset state, start watchdog + foreground resync. */
1847
+ game._resOnOpen = function () {
1848
+ res.declaredDead = false;
1849
+ res.lastCloseCode = null;
1850
+ res.lastInboundAt = Date.now();
1851
+ res.lastProbeAt = 0;
1852
+ stopWatchdog();
1853
+ res.watchdogTimer = setInterval(watchdogTick, 1000);
1854
+ addVisibility();
1855
+ if (!res.wrappedDisconnect) { // clear timers even if onclose never fires
1856
+ res.wrappedDisconnect = true;
1857
+ var orig = game.disconnect;
1858
+ game.disconnect = function () { teardown(); return orig.apply(game, arguments); };
1859
+ }
1860
+ evaluate();
1861
+ };
1862
+
1863
+ /** @param {any} evt CloseEvent - code kept for the token-reuse decision. */
1864
+ game._resOnClose = function (evt) {
1865
+ res.lastCloseCode = (evt && typeof evt.code === 'number') ? evt.code : null;
1866
+ teardown();
1867
+ evaluate();
1868
+ };
1869
+
1870
+ /** Pong: feed the stats EWMA from the matched waiter. @param {any} waiter */
1871
+ game._resOnPong = function (waiter) {
1872
+ if (waiter && typeof waiter.sentAt === 'number') feedRtt(Date.now() - waiter.sentAt);
1873
+ evaluate();
1874
+ };
1875
+
1876
+ /** Reuse the cached room token on reconnect while safely un-expired. */
1877
+ game._resCanReuseToken = function () {
1878
+ if (res.lastCloseCode === 4401) return false; // auth reject -> refetch
1879
+ var cfg = game.directConfig;
1880
+ if (!cfg || !cfg.ws_url || !cfg.access_token) return false;
1881
+ var exp = parseExpiry(cfg.expires_at);
1882
+ return exp != null && exp - Date.now() > 30000;
1883
+ };
1884
+
1885
+ /**
1886
+ * Backpressure for realtime 'input' frames: while the send buffer is above
1887
+ * the threshold hold the LATEST frame only; drain when it clears.
1888
+ * @param {any} payload @returns {boolean} true = held, don't send now
1889
+ */
1890
+ game._resHoldInput = function (payload) {
1891
+ if (!res.backpressureBytes) return false;
1892
+ var s = game.directSocket;
1893
+ if (!s || (res.pendingInput == null && !(s.bufferedAmount > res.backpressureBytes))) return false;
1894
+ res.pendingInput = payload; // latest-only: newer input replaces stale
1895
+ if (!res.drainTimer) res.drainTimer = setTimeout(drainInput, 50);
1896
+ return true;
1897
+ };
1898
+
1899
+ function drainInput() {
1900
+ res.drainTimer = null;
1901
+ var s = game.directSocket;
1902
+ if (!s || s.readyState !== 1) { res.pendingInput = null; return; }
1903
+ if (res.pendingInput == null) return;
1904
+ if (s.bufferedAmount > res.backpressureBytes) { res.drainTimer = setTimeout(drainInput, 50); return; }
1905
+ var p = res.pendingInput;
1906
+ res.pendingInput = null;
1907
+ game._sendDirect('input', p);
1908
+ }
1909
+
1910
+ /** Defensive expires_at parse (ISO or epoch); null = doubt -> refetch. @param {*} v */
1911
+ function parseExpiry(v) {
1912
+ if (typeof v === 'number' && isFinite(v)) return v > 1e12 ? v : v * 1000;
1913
+ if (typeof v === 'string' && v) {
1914
+ var t = Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(v) ? v : v + 'Z'); // bare ISO = UTC
1915
+ return isNaN(t) ? null : t;
1916
+ }
1917
+ return null;
1918
+ }
1919
+
1920
+ function teardown() {
1921
+ stopWatchdog();
1922
+ if (res.drainTimer) { clearTimeout(res.drainTimer); res.drainTimer = null; }
1923
+ res.pendingInput = null;
1924
+ removeVisibility();
1925
+ if (game._pongWaiters && game._pongWaiters.length) {
1926
+ game._pongWaiters = game._pongWaiters.filter(function (/** @type {any} */ w) { return !w.statsOnly; });
1927
+ }
1928
+ }
1929
+
1930
+ /** Foreground: probe immediately + throttled requestSync. */
1931
+ function addVisibility() {
1932
+ if (typeof document === 'undefined' || !document.addEventListener || res.visHandler) return;
1933
+ res.visHandler = function () {
1934
+ if (document.visibilityState !== 'visible' || !game.directMode || !game._joined) return;
1935
+ sendProbe();
1936
+ var now = Date.now();
1937
+ if (now - res.lastVisResyncAt >= 2000) {
1938
+ res.lastVisResyncAt = now;
1939
+ try { game.requestSync(game._lastSequence || 0); } catch (e) { /* non-fatal */ }
1940
+ }
1941
+ };
1942
+ document.addEventListener('visibilitychange', res.visHandler);
1943
+ }
1944
+
1945
+ function removeVisibility() {
1946
+ if (res.visHandler && typeof document !== 'undefined' && document.removeEventListener) {
1947
+ document.removeEventListener('visibilitychange', res.visHandler);
1948
+ }
1949
+ res.visHandler = null;
1950
+ }
1951
+
1952
+ // Re-evaluate quality on connection events (covers relay mode too).
1953
+ game.on('disconnect', evaluate);
1954
+ game.on('connectionState', evaluate);
1955
+ }
1956
+
1702
1957
  /**
1703
1958
  * Usion SDK Game Socket — Socket.IO connection management
1704
1959
  */
@@ -2182,6 +2437,30 @@ var Usion = (function () {
2182
2437
  return self._joinPromise;
2183
2438
  };
2184
2439
 
2440
+ /**
2441
+ * Place this player into a drop-in/drop-out WORLD room (SDK ≥ 2.23).
2442
+ *
2443
+ * World rooms (services tagged `world`) run continuously: players enter and
2444
+ * leave at any time instead of playing fixed matches. Placement rides the
2445
+ * matchmaking channel (works embedded AND standalone): the platform returns
2446
+ * the world you're already in, else backfills a world with space, else
2447
+ * creates a new one. On success `game.roomId` is set, so the usual
2448
+ * `connect()`+`join()` (platform relay) or `connectDirect()` (direct/hosted)
2449
+ * flow works unchanged afterwards. Rejects with MATCH_TIMEOUT after 15s.
2450
+ *
2451
+ * @param {object} [opts]
2452
+ * @param {string} [opts.serviceId] - Defaults to the current service.
2453
+ * @returns {Promise<{roomId: string, playerIds: string[]}>}
2454
+ */
2455
+ game.joinWorld = function(opts) {
2456
+ const self = this;
2457
+ opts = opts || {};
2458
+ return Usion.matchmaking._joinWorld(opts.serviceId).then(function(m) {
2459
+ self.roomId = m.roomId;
2460
+ return { roomId: m.roomId, playerIds: m.players || [] };
2461
+ });
2462
+ };
2463
+
2185
2464
  /**
2186
2465
  * Leave the current game room
2187
2466
  */
@@ -4471,6 +4750,234 @@ var Usion = (function () {
4471
4750
  return reader(bytes)();
4472
4751
  }
4473
4752
 
4753
+ /**
4754
+ * Usion SDK Netcode — Interest grid (area-of-interest spatial hash).
4755
+ *
4756
+ * Buckets entities into fixed-size cells so "who is near (x, y)?" costs a few
4757
+ * cell lookups instead of an O(N) scan — the building block for world rooms
4758
+ * where each client should only receive nearby state (AOI filtering). Pure
4759
+ * JS, no DOM/window references: the same helper runs in the browser and in a
4760
+ * Node game server producing per-player snapshots.
4761
+ *
4762
+ * const grid = Usion.netcode.createInterestGrid({ cellSize: 256 });
4763
+ * grid.upsert('p1', 120, 40); // insert or move
4764
+ * grid.query(0, 0, 300); // → ids within 300 units (circle)
4765
+ * const { entered, left, visible } = grid.observe('p1', 120, 40, 500);
4766
+ * // entered → spawn for this observer; left → despawn (diffed per observer)
4767
+ */
4768
+
4769
+ /** @typedef {string|number} InterestGridId */
4770
+
4771
+ /**
4772
+ * @param {*} id
4773
+ * @param {string} method
4774
+ * @returns {InterestGridId}
4775
+ */
4776
+ function checkId(id, method) {
4777
+ const ok = (typeof id === 'string' && id.length > 0)
4778
+ || (typeof id === 'number' && isFinite(id));
4779
+ if (!ok) {
4780
+ throw new Error('interestGrid.' + method + ': id must be a non-empty string or a finite number');
4781
+ }
4782
+ return id;
4783
+ }
4784
+
4785
+ /**
4786
+ * @param {*} value
4787
+ * @param {string} name
4788
+ * @param {string} method
4789
+ * @returns {number}
4790
+ */
4791
+ function checkFinite(value, name, method) {
4792
+ if (typeof value !== 'number' || !isFinite(value)) {
4793
+ throw new Error('interestGrid.' + method + ': ' + name + ' must be a finite number');
4794
+ }
4795
+ return value;
4796
+ }
4797
+
4798
+ /**
4799
+ * @param {*} value
4800
+ * @param {string} method
4801
+ * @returns {number}
4802
+ */
4803
+ function checkRadius(value, method) {
4804
+ checkFinite(value, 'radius', method);
4805
+ if (value < 0) throw new Error('interestGrid.' + method + ': radius must be >= 0');
4806
+ return value;
4807
+ }
4808
+
4809
+ /**
4810
+ * Create an interest grid.
4811
+ * @param {{cellSize?: number}} [opts] - cellSize (world units) defaults to 256;
4812
+ * pick roughly the typical query radius so lookups touch ~4–9 cells.
4813
+ */
4814
+ function createInterestGrid(opts) {
4815
+ opts = opts || {};
4816
+ const cellSize = opts.cellSize != null ? opts.cellSize : 256;
4817
+ if (typeof cellSize !== 'number' || !isFinite(cellSize) || cellSize <= 0) {
4818
+ throw new Error('createInterestGrid: cellSize must be a finite number > 0');
4819
+ }
4820
+
4821
+ /** @type {Map<InterestGridId, {x: number, y: number, key: string}>} */
4822
+ const entities = new Map();
4823
+ /** @type {Map<string, Set<InterestGridId>>} */
4824
+ const cells = new Map();
4825
+ // Per-observer visible sets. `prev`/`next` are swapped (never reallocated)
4826
+ // each observe() call — this runs per tick per observer.
4827
+ /** @type {Map<InterestGridId, {prev: Set<InterestGridId>, next: Set<InterestGridId>}>} */
4828
+ const observers = new Map();
4829
+
4830
+ /** @param {string} key @param {InterestGridId} id */
4831
+ function addToCell(key, id) {
4832
+ let set = cells.get(key);
4833
+ if (!set) { set = new Set(); cells.set(key, set); }
4834
+ set.add(id);
4835
+ }
4836
+
4837
+ /** @param {string} key @param {InterestGridId} id */
4838
+ function removeFromCell(key, id) {
4839
+ const set = cells.get(key);
4840
+ if (!set) return;
4841
+ set.delete(id);
4842
+ if (set.size === 0) cells.delete(key);
4843
+ }
4844
+
4845
+ /**
4846
+ * Visit every entity within `radius` of (x, y): scan the cells the circle's
4847
+ * bounding box overlaps, then apply a true circle test per entity.
4848
+ * @param {number} x @param {number} y @param {number} radius
4849
+ * @param {(id: InterestGridId) => void} visit
4850
+ */
4851
+ function forEachInRadius(x, y, radius, visit) {
4852
+ const r2 = radius * radius;
4853
+ const minCx = Math.floor((x - radius) / cellSize);
4854
+ const maxCx = Math.floor((x + radius) / cellSize);
4855
+ const minCy = Math.floor((y - radius) / cellSize);
4856
+ const maxCy = Math.floor((y + radius) / cellSize);
4857
+ for (let cx = minCx; cx <= maxCx; cx++) {
4858
+ for (let cy = minCy; cy <= maxCy; cy++) {
4859
+ const set = cells.get(cx + ',' + cy);
4860
+ if (!set) continue;
4861
+ for (const id of set) {
4862
+ const ent = entities.get(id);
4863
+ if (!ent) continue;
4864
+ const dx = ent.x - x;
4865
+ const dy = ent.y - y;
4866
+ if (dx * dx + dy * dy <= r2) visit(id);
4867
+ }
4868
+ }
4869
+ }
4870
+ }
4871
+
4872
+ return {
4873
+ /**
4874
+ * Insert an entity or move an existing one.
4875
+ * @param {InterestGridId} id @param {number} x @param {number} y
4876
+ */
4877
+ upsert: function (id, x, y) {
4878
+ checkId(id, 'upsert');
4879
+ checkFinite(x, 'x', 'upsert');
4880
+ checkFinite(y, 'y', 'upsert');
4881
+ const key = Math.floor(x / cellSize) + ',' + Math.floor(y / cellSize);
4882
+ const ent = entities.get(id);
4883
+ if (ent) {
4884
+ ent.x = x;
4885
+ ent.y = y;
4886
+ if (ent.key !== key) {
4887
+ removeFromCell(ent.key, id);
4888
+ addToCell(key, id);
4889
+ ent.key = key;
4890
+ }
4891
+ return;
4892
+ }
4893
+ entities.set(id, { x: x, y: y, key: key });
4894
+ addToCell(key, id);
4895
+ },
4896
+
4897
+ /**
4898
+ * Remove an entity. Unknown ids are a no-op.
4899
+ * @param {InterestGridId} id
4900
+ */
4901
+ remove: function (id) {
4902
+ checkId(id, 'remove');
4903
+ const ent = entities.get(id);
4904
+ if (!ent) return;
4905
+ entities.delete(id);
4906
+ removeFromCell(ent.key, id);
4907
+ },
4908
+
4909
+ /**
4910
+ * All entity ids within `radius` of (x, y) — a circle test, not just
4911
+ * cell membership.
4912
+ * @param {number} x @param {number} y @param {number} radius
4913
+ * @returns {InterestGridId[]}
4914
+ */
4915
+ query: function (x, y, radius) {
4916
+ checkFinite(x, 'x', 'query');
4917
+ checkFinite(y, 'y', 'query');
4918
+ checkRadius(radius, 'query');
4919
+ /** @type {InterestGridId[]} */
4920
+ const out = [];
4921
+ forEachInRadius(x, y, radius, function (id) { out.push(id); });
4922
+ return out;
4923
+ },
4924
+
4925
+ /**
4926
+ * Like query(), but diffed against this observer's previous observe():
4927
+ * `entered` are ids newly visible, `left` are ids no longer visible,
4928
+ * `visible` is the full current set. Drive spawn/despawn messages from
4929
+ * entered/left and per-tick snapshots from visible.
4930
+ * @param {InterestGridId} observerId @param {number} x @param {number} y @param {number} radius
4931
+ * @returns {{entered: InterestGridId[], left: InterestGridId[], visible: InterestGridId[]}}
4932
+ */
4933
+ observe: function (observerId, x, y, radius) {
4934
+ checkId(observerId, 'observe');
4935
+ checkFinite(x, 'x', 'observe');
4936
+ checkFinite(y, 'y', 'observe');
4937
+ checkRadius(radius, 'observe');
4938
+ let tracker = observers.get(observerId);
4939
+ if (!tracker) {
4940
+ tracker = { prev: new Set(), next: new Set() };
4941
+ observers.set(observerId, tracker);
4942
+ }
4943
+ const prev = tracker.prev;
4944
+ const next = tracker.next;
4945
+ next.clear();
4946
+ /** @type {InterestGridId[]} */
4947
+ const entered = [];
4948
+ /** @type {InterestGridId[]} */
4949
+ const left = [];
4950
+ /** @type {InterestGridId[]} */
4951
+ const visible = [];
4952
+ forEachInRadius(x, y, radius, function (id) {
4953
+ next.add(id);
4954
+ visible.push(id);
4955
+ if (!prev.has(id)) entered.push(id);
4956
+ });
4957
+ for (const id of prev) {
4958
+ if (!next.has(id)) left.push(id);
4959
+ }
4960
+ tracker.prev = next;
4961
+ tracker.next = prev; // reused as scratch on the next call
4962
+ return { entered: entered, left: left, visible: visible };
4963
+ },
4964
+
4965
+ /**
4966
+ * Free an observer's tracking state (call when a player leaves).
4967
+ * @param {InterestGridId} observerId
4968
+ */
4969
+ dropObserver: function (observerId) {
4970
+ checkId(observerId, 'dropObserver');
4971
+ observers.delete(observerId);
4972
+ },
4973
+
4974
+ /** @returns {number} Number of entities in the grid. */
4975
+ size: function () {
4976
+ return entities.size;
4977
+ },
4978
+ };
4979
+ }
4980
+
4474
4981
  /**
4475
4982
  * Usion SDK Game Netcode — convenience wiring of the netcode toolkit onto the
4476
4983
  * game module. These helpers ride on the existing realtime/action channels, so
@@ -4489,6 +4996,7 @@ var Usion = (function () {
4489
4996
  game.createPredictor = function (opts) { return new Predictor(opts || {}); };
4490
4997
  game.createLagCompensator = function (opts) { return new LagCompensator(opts || {}); };
4491
4998
  game.createLockstep = function (opts) { return new Lockstep(opts || {}); };
4999
+ game.createInterestGrid = function (opts) { return createInterestGrid(opts || {}); };
4492
5000
 
4493
5001
  // ── Realtime channel router ──────────────────────────────────────────────
4494
5002
  // Multiplexes realtime by action_type so replicate / mesh / mesh-network and
@@ -4774,6 +5282,7 @@ var Usion = (function () {
4774
5282
  const id = self._pingMeter.begin();
4775
5283
  let done = false;
4776
5284
  const finish = function () { if (done) return; done = true; resolve(self._pingMeter.end(id)); };
5285
+ finish.sentAt = Date.now(); // lets the pong pair feed getNetworkStats' EWMA too
4777
5286
  self._pongWaiters.push(finish);
4778
5287
  self._sendDirect('ping', { t: Date.now() });
4779
5288
  setTimeout(function () {
@@ -5112,6 +5621,7 @@ var Usion = (function () {
5112
5621
  room_assigned: 'roomAssigned',
5113
5622
  connection_state: 'connectionState',
5114
5623
  reconnected: 'reconnected',
5624
+ network_quality: 'networkQuality',
5115
5625
  };
5116
5626
 
5117
5627
  function _normalizeEventName(event) {
@@ -5326,6 +5836,8 @@ var Usion = (function () {
5326
5836
 
5327
5837
  // Apply sub-modules
5328
5838
  applyGameDirect(game, Usion);
5839
+ // Direct-mode liveness/backpressure + network stats (hooks into game-direct).
5840
+ applyGameResilience(game, Usion);
5329
5841
  applyGameSocket(game, Usion);
5330
5842
  applyGameProxy(game, Usion);
5331
5843
  applyGameMethods(game, Usion);
@@ -5588,8 +6100,12 @@ var Usion = (function () {
5588
6100
  * Usion.matchmaking.onMatch(({ roomId, players }) => { ... });
5589
6101
  */
5590
6102
 
6103
+ // World placement is a single backend round-trip (no queue wait), so the
6104
+ // bound is fixed rather than caller-supplied like find()'s opts.timeout.
6105
+ const WORLD_JOIN_TIMEOUT_MS = 15000;
6106
+
5591
6107
  function createMatchmakingModule(Usion) {
5592
- let pending = null; // active find() entry: { resolve, reject }
6108
+ let pending = null; // active placement entry: { resolve, reject }
5593
6109
  let onMatchCb = null;
5594
6110
  let bound = false;
5595
6111
 
@@ -5607,6 +6123,69 @@ var Usion = (function () {
5607
6123
  });
5608
6124
  }
5609
6125
 
6126
+ /**
6127
+ * Shared mm-channel placement used by find() (queue matches) and
6128
+ * game.joinWorld() (world backfill): register the resolver, bound the wait,
6129
+ * emit mm:join, and resolve from the immediate-placement ack
6130
+ * ({queued:false, matched:true, room_id, player_ids}) or the mm:matched
6131
+ * push — whichever arrives first.
6132
+ * @param {object} payload - mm:join payload
6133
+ * @param {number} [timeout] - ms until MATCH_TIMEOUT (falsy = wait forever)
6134
+ * @param {string} timeoutMessage
6135
+ */
6136
+ function place(payload, timeout, timeoutMessage) {
6137
+ bind();
6138
+
6139
+ if (pending) {
6140
+ const old = pending; pending = null;
6141
+ old.reject(new UsionError(ERROR_CODES.SUPERSEDED, 'Superseded by a newer find()'));
6142
+ }
6143
+
6144
+ let timer = null;
6145
+ const entry = {};
6146
+ const promise = new Promise(function (resolve, reject) {
6147
+ entry.resolve = function (r) {
6148
+ if (timer) clearTimeout(timer);
6149
+ resolve(r);
6150
+ };
6151
+ entry.reject = function (e) {
6152
+ if (timer) clearTimeout(timer);
6153
+ if (pending === entry) pending = null;
6154
+ reject(e);
6155
+ };
6156
+ });
6157
+
6158
+ // Register BEFORE emitting mm:join: when someone is already waiting in
6159
+ // the queue, mm:matched can arrive ahead of the join ack — registering
6160
+ // afterwards dropped that instant match and left find() hanging forever.
6161
+ pending = entry;
6162
+
6163
+ if (timeout > 0) {
6164
+ timer = setTimeout(function () {
6165
+ timer = null;
6166
+ Usion._backendEmit('mm:cancel', {}).catch(function () { /* best-effort dequeue */ });
6167
+ entry.reject(new UsionError(ERROR_CODES.MATCH_TIMEOUT,
6168
+ timeoutMessage + timeout + 'ms'));
6169
+ }, timeout);
6170
+ }
6171
+
6172
+ Usion._backendEmit('mm:join', payload)
6173
+ .then(function (ack) {
6174
+ // Immediate placement (world rooms): the ack itself carries the room.
6175
+ // The mm:matched push may still follow; pending is already cleared,
6176
+ // so it can't double-resolve.
6177
+ if (ack && ack.matched && ack.room_id && pending === entry) {
6178
+ pending = null;
6179
+ entry.resolve(normalize(ack));
6180
+ }
6181
+ })
6182
+ .catch(function (err) {
6183
+ if (pending === entry) entry.reject(toUsionError(err));
6184
+ });
6185
+
6186
+ return promise;
6187
+ }
6188
+
5610
6189
  return {
5611
6190
  /** Register a handler called whenever a match is found. */
5612
6191
  onMatch: function (cb) { onMatchCb = cb; bind(); },
@@ -5622,47 +6201,17 @@ var Usion = (function () {
5622
6201
  find: function (serviceId, opts) {
5623
6202
  opts = opts || {};
5624
6203
  const sid = serviceId || (Usion.config && Usion.config.serviceId);
5625
- bind();
5626
-
5627
- if (pending) {
5628
- const old = pending; pending = null;
5629
- old.reject(new UsionError(ERROR_CODES.SUPERSEDED, 'Superseded by a newer find()'));
5630
- }
5631
-
5632
- let timer = null;
5633
- const entry = {};
5634
- const promise = new Promise(function (resolve, reject) {
5635
- entry.resolve = function (r) {
5636
- if (timer) clearTimeout(timer);
5637
- resolve(r);
5638
- };
5639
- entry.reject = function (e) {
5640
- if (timer) clearTimeout(timer);
5641
- if (pending === entry) pending = null;
5642
- reject(e);
5643
- };
5644
- });
5645
-
5646
- // Register BEFORE emitting mm:join: when someone is already waiting in
5647
- // the queue, mm:matched can arrive ahead of the join ack — registering
5648
- // afterwards dropped that instant match and left find() hanging forever.
5649
- pending = entry;
5650
-
5651
- if (opts.timeout > 0) {
5652
- timer = setTimeout(function () {
5653
- timer = null;
5654
- Usion._backendEmit('mm:cancel', {}).catch(function () { /* best-effort dequeue */ });
5655
- entry.reject(new UsionError(ERROR_CODES.MATCH_TIMEOUT,
5656
- 'No match within ' + opts.timeout + 'ms'));
5657
- }, opts.timeout);
5658
- }
5659
-
5660
- Usion._backendEmit('mm:join', { service_id: sid, size: opts.size || 2 })
5661
- .catch(function (err) {
5662
- if (pending === entry) entry.reject(toUsionError(err));
5663
- });
6204
+ return place({ service_id: sid, size: opts.size || 2 }, opts.timeout, 'No match within ');
6205
+ },
5664
6206
 
5665
- return promise;
6207
+ /**
6208
+ * @private SDK-internal — use Usion.game.joinWorld(). Immediate placement
6209
+ * into a drop-in/drop-out world room over the same mm channel.
6210
+ * @param {string} [serviceId]
6211
+ */
6212
+ _joinWorld: function (serviceId) {
6213
+ const sid = serviceId || (Usion.config && Usion.config.serviceId);
6214
+ return place({ service_id: sid, mode: 'world' }, WORLD_JOIN_TIMEOUT_MS, 'No world placement within ');
5666
6215
  },
5667
6216
 
5668
6217
  /** Leave the queue / stop waiting. */
@@ -6029,12 +6578,13 @@ var Usion = (function () {
6029
6578
  * MeshNetwork — N-peer full mesh
6030
6579
  * diff / patch / quantize — JSON delta compression (id-keyed arrays)
6031
6580
  * encode / decode — compact binary codec
6581
+ * createInterestGrid — spatial hash for area-of-interest (AOI) filtering
6032
6582
  */
6033
6583
 
6034
6584
  const netcode = {
6035
6585
  SnapshotInterpolation, Vault, Predictor, Coalescer, PingMeter,
6036
6586
  MeshConnection, MeshNetwork, WebTransportConnection, NetworkSim, Lockstep, LagCompensator,
6037
- diff, patch, quantize, encode, decode,
6587
+ diff, patch, quantize, encode, decode, createInterestGrid,
6038
6588
  };
6039
6589
 
6040
6590
  /**