@margoengine/netcode 0.0.0-stage → 0.1.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.
Files changed (66) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1306 -3
  4. package/dist/client.d.ts +167 -0
  5. package/dist/clock.d.ts +29 -0
  6. package/dist/extrapolate.d.ts +42 -0
  7. package/dist/extrapolate.js +25 -0
  8. package/dist/game.d.ts +68 -0
  9. package/dist/generate-rust.d.ts +14 -0
  10. package/dist/generate-rust.js +184 -0
  11. package/dist/generate.d.ts +25 -0
  12. package/dist/generate.js +156 -0
  13. package/dist/hitboxes.d.ts +74 -0
  14. package/dist/hitboxes.js +124 -0
  15. package/dist/index.d.ts +9 -0
  16. package/dist/index.js +457 -0
  17. package/dist/interest.d.ts +101 -0
  18. package/dist/interest.js +166 -0
  19. package/dist/interpolation-delay.d.ts +114 -0
  20. package/dist/interpolation-delay.js +79 -0
  21. package/dist/interpolation-fields.d.ts +117 -0
  22. package/dist/interpolation-fields.js +147 -0
  23. package/dist/interpolation-timeline.d.ts +100 -0
  24. package/dist/interpolation-timeline.js +122 -0
  25. package/dist/interpolation.d.ts +39 -0
  26. package/dist/interpolation.js +61 -0
  27. package/dist/lag.d.ts +62 -0
  28. package/dist/lobby.d.ts +77 -0
  29. package/dist/lobby.js +96 -0
  30. package/dist/loopback.d.ts +92 -0
  31. package/dist/media.d.ts +197 -0
  32. package/dist/media.js +274 -0
  33. package/dist/migrate.d.ts +113 -0
  34. package/dist/migrate.js +289 -0
  35. package/dist/node.d.ts +101 -0
  36. package/dist/node.js +166 -0
  37. package/dist/physics.d.ts +133 -0
  38. package/dist/physics.js +169 -0
  39. package/dist/presence.d.ts +156 -0
  40. package/dist/presence.js +226 -0
  41. package/dist/protocol-asi_qndb.js +122 -0
  42. package/dist/protocol.d.ts +75 -0
  43. package/dist/relay.d.ts +152 -0
  44. package/dist/relay.js +235 -0
  45. package/dist/rollback.d.ts +131 -0
  46. package/dist/rollback.js +194 -0
  47. package/dist/rooms.d.ts +366 -0
  48. package/dist/rooms.js +479 -0
  49. package/dist/schema-CMfqK4Gu.js +616 -0
  50. package/dist/schema.d.ts +263 -0
  51. package/dist/server-DAVzHcWW.js +203 -0
  52. package/dist/server.d.ts +147 -0
  53. package/dist/shared/bytes.d.ts +36 -0
  54. package/dist/signal.d.ts +156 -0
  55. package/dist/signal.js +261 -0
  56. package/dist/smoothing.d.ts +76 -0
  57. package/dist/smoothing.js +155 -0
  58. package/dist/transport-DeQodwyv.js +49 -0
  59. package/dist/transport.d.ts +76 -0
  60. package/dist/webrtc.d.ts +32 -0
  61. package/dist/webrtc.js +64 -0
  62. package/dist/websocket.d.ts +27 -0
  63. package/dist/websocket.js +42 -0
  64. package/dist/webtransport.d.ts +83 -0
  65. package/dist/webtransport.js +120 -0
  66. package/package.json +140 -6
package/README.md CHANGED
@@ -1,3 +1,1306 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @margoengine/netcode
2
+
3
+ Import `margoengine/netcode` from the `margoengine` package, or `@margoengine/netcode` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ Game networking for any game, not only voxels: one schema describes your state and inputs, an authoritative server
6
+ runs the game at a fixed tick rate, and clients predict their own player, reconcile with the server and draw everyone
7
+ else interpolated. It runs in browsers, Node, Deno and workers (no platform APIs), it is optional and tree-shakable,
8
+ and core and the stage never import it. Clean-room code from public descriptions of the techniques (see "Sources").
9
+
10
+ ```ts
11
+ import { defineGame, defineSchema, GameClient, GameServer, LoopbackNetwork } from '@margoengine/netcode';
12
+
13
+ // One schema for both ends. Quantized floats are small on the wire; maps are entity collections sent as deltas.
14
+ const schema = defineSchema({
15
+ types: {
16
+ Input: { x: { type: 'quantized', min: -1, max: 1, bits: 8 }, y: { type: 'quantized', min: -1, max: 1, bits: 8 } },
17
+ Box: { x: 'f32', y: 'f32' },
18
+ State: { boxes: { type: 'map', of: 'Box', maxSize: 64 } },
19
+ },
20
+ } as const);
21
+
22
+ // One deterministic step for both ends: the server runs it authoritatively, clients run it to predict.
23
+ const game = defineGame({
24
+ schema,
25
+ state: 'State',
26
+ input: 'Input',
27
+ tickRate: 30,
28
+ initial: () => ({ boxes: new Map() }),
29
+ join: (state, id) => void state.boxes.set(id, { x: 0, y: 0 }),
30
+ leave: (state, id) => void state.boxes.delete(id),
31
+ step(state, inputs, _tick, dt) {
32
+ for (const [id, input] of inputs) {
33
+ const box = state.boxes.get(id);
34
+ if (box) (box.x += input.x * 5 * dt), (box.y += input.y * 5 * dt);
35
+ }
36
+ },
37
+ });
38
+
39
+ // A simulated network: 60 ms each way, 20 ms of jitter, 5% loss. Swap in a real transport for a real game.
40
+ const network = new LoopbackNetwork({ latency: 60, jitter: 20, loss: 0.05, seed: 1 });
41
+ const now = () => network.time;
42
+ const server = new GameServer(game, { now });
43
+ network.listen().onconnection = (connection) => server.accept(connection);
44
+
45
+ const joining = GameClient.join(game, network.connect(), { now, input: () => ({ x: 1, y: 0 }) });
46
+ let client: Awaited<typeof joining> | undefined;
47
+ joining.then((joined) => (client = joined));
48
+ for (let frame = 0; frame < 300; frame++) {
49
+ network.advance(1000 / 60); // one frame of virtual time
50
+ if (network.time >= (server.tick + 1) * game.tickMs) server.step();
51
+ client?.update();
52
+ await null; // let the join promise settle
53
+ }
54
+ console.log('me', client?.predicted.boxes.get(client.player), 'server', server.state.boxes.get(client?.player ?? 0));
55
+ ```
56
+
57
+ In a real game the server calls `server.run({ signal })` (real-time ticks) and the client calls `client.update()` every
58
+ frame; the loop above drives both by hand so the example runs anywhere, at once, the same way every time.
59
+
60
+ ## What it does
61
+
62
+ - **Schema-first binary codec** (`defineSchema`): structs of `u8` `u16` `u32` `i8` `i16` `i32`, 32-bit varints
63
+ (`uint`, zigzag `int`), `f32` `f64`, quantized floats, `bool`, UTF-8 `string`, `bytes`, `enum`, `array`, `optional`
64
+ and `map` (entity id to value). Full types from the definition (`Infer<typeof schema.definition, 'State'>`), every
65
+ value checked on encode (a `RangeError` or `TypeError` that names the field and the fix), every byte checked on
66
+ decode (truncated or malformed input throws a `RangeError`, never anything else, and never allocates more than the
67
+ bytes it holds). `encodeDelta` / `decodeDelta` send only the fields and map entries that changed against a baseline
68
+ both ends hold. `schema.json` is the normalized definition a generator in another language reads (see "Wire format").
69
+ - **Authoritative server** (`GameServer`): fixed-timestep ticks (`run` in real time, scheduled from a fixed start so
70
+ timer error does not drift the rate; `step` for one tick), per-player input buffers keyed by tick, the player's last
71
+ input when this tick's has not arrived, joins and leaves at the start of a tick (a player who leaves before that
72
+ tick never reaches the game), snapshots against the newest
73
+ snapshot each client confirmed (or in full), per-player views (`view`) for interest management or hidden
74
+ information, reliable game messages (`send`, `onmessage`), `kick`, `close` and `using`.
75
+ - **Client** (`GameClient.join` resolves once welcomed, clock-synced and holding a snapshot): runs ahead of the server by
76
+ the measured one-way delay plus a jitter margin, so its input for a tick arrives before the server runs that tick;
77
+ predicts with the game's own step; on each snapshot compares its prediction for that tick byte for byte and, when
78
+ they differ, goes back to the server's state and replays its unconfirmed inputs. Each input message repeats the
79
+ newest 8 unconfirmed inputs, so a lost packet costs nothing. `interpolated()` blends the two snapshots around a
80
+ render time a little in the past (default 2 snapshot intervals plus the jitter, or what an `AdaptiveDelay` measures;
81
+ see below) on a clock that never runs backwards.
82
+ - **Clock sync** (`ClockSync`): Cristian's method over the last 8 pings; the fastest round trip gives the offset and
83
+ the spread of round trips gives the jitter. The server also reports how many ticks it ran without the client's input,
84
+ and the client leads by one more tick for a while each time that grows.
85
+ - **Transports**: anything with the `Connection` shape (`send(bytes, 'reliable' | 'unreliable')`, `close`, `onmessage`,
86
+ `onclose`). `LoopbackNetwork` is the in-memory one, on a virtual clock: latency, jitter, loss, duplication and
87
+ reordering from a seed, reliable messages resent under loss and never reordered. `messages(connection, { signal })`
88
+ reads any connection as an async iterator.
89
+
90
+ ## Measured render delay
91
+
92
+ Pass an `AdaptiveDelay` from `@margoengine/netcode/interpolation-delay` as `interpolationDelay` and the view stays as close as what the link allows, one snapshot interval on a clean one, instead of a fixed number of ticks. Nothing loads it unless you do. Snapshots live on `Timeline` from `@margoengine/netcode/interpolation-timeline`, the same ring `SnapshotBuffer` uses.
93
+
94
+ ```ts
95
+ import { AdaptiveDelay } from 'margoengine/netcode/interpolation-delay';
96
+ import { defineGame, defineSchema, GameClient, GameServer, LoopbackNetwork } from 'margoengine/netcode';
97
+
98
+ const schema = defineSchema({
99
+ version: 1,
100
+ types: { Input: { x: 'f32' }, State: { x: 'f32' } },
101
+ } as const);
102
+ const game = defineGame({
103
+ schema,
104
+ state: 'State',
105
+ input: 'Input',
106
+ tickRate: 30,
107
+ initial: () => ({ x: 0 }),
108
+ step: (state, inputs, _tick, dt) => {
109
+ for (const input of inputs.values()) state.x += input.x * dt;
110
+ },
111
+ });
112
+ const network = new LoopbackNetwork({ latency: 40, jitter: 30, seed: 3 });
113
+ const now = () => network.time;
114
+ const server = new GameServer(game, { now });
115
+ network.listen().onconnection = (connection) => server.accept(connection);
116
+ const delay = new AdaptiveDelay();
117
+ const joining = GameClient.join(game, network.connect(), { now, input: () => ({ x: 1 }), interpolationDelay: delay });
118
+ let client: Awaited<typeof joining> | undefined;
119
+ joining.then((joined) => (client = joined));
120
+ for (let frame = 0; frame < 300; frame++) {
121
+ network.advance(1000 / 60);
122
+ if (network.time >= (server.tick + 1) * game.tickMs) server.step();
123
+ client?.update();
124
+ client?.interpolated();
125
+ await null;
126
+ }
127
+ console.log('delay', delay.target, 'view tick', client?.viewTick);
128
+ ```
129
+
130
+ ## Snapshot interpolation
131
+
132
+ `@margoengine/netcode/interpolation` and the three entries beside it hold what was the `@margoengine/net` package.
133
+
134
+ Bounded snapshot interpolation for position, quaternion and velocity, with capped dead reckoning.
135
+
136
+ ```ts
137
+ import {SnapshotBuffer, createSnapshot} from 'margoengine/netcode/interpolation';
138
+ const renderTimeSeconds = performance.now() / 1000;
139
+ const buffer = new SnapshotBuffer(32);
140
+ const output = createSnapshot();
141
+ // buffer.push(timeSeconds, position, quaternion, velocity)
142
+ buffer.sample(renderTimeSeconds, output);
143
+ ```
144
+
145
+ Position interpolation is cubic Hermite using endpoint velocities, and the sampled velocity is that curve's derivative; rotations use shortest-arc slerp. Ordered snapshots are copied into a preallocated ring, quaternions normalized, and duplicate/out-of-order timestamps return false. Extrapolation uses last velocity up to maxPrediction (default 0.25 seconds), then holds. Before the oldest sample, the oldest pose is held. Outputs are reused by default; supply your own to retain results. This is interpolation/prediction, not transport, authority, rollback or packet security.
146
+
147
+ ### Adaptive render delay
148
+
149
+ `AdaptiveDelay` in `margoengine/netcode/interpolation-delay` picks how far behind the newest snapshot to draw from what the link does, so a calm link draws close and a rough one stays smooth.
150
+
151
+ ```ts
152
+ import {SnapshotBuffer, createSnapshot} from 'margoengine/netcode/interpolation';
153
+ import {AdaptiveDelay} from 'margoengine/netcode/interpolation-delay';
154
+ const buffer = new SnapshotBuffer();
155
+ const delay = new AdaptiveDelay();
156
+ const pose = createSnapshot();
157
+ // A snapshot stamped with the server's time arrives:
158
+ const serverTime = 12.5;
159
+ buffer.push(serverTime, [1, 0, 2]);
160
+ delay.observe(serverTime, performance.now() / 1000);
161
+ // Each frame:
162
+ const time = delay.renderTime(performance.now() / 1000);
163
+ if (!Number.isNaN(time)) buffer.sample(time, pose);
164
+ console.log(delay.target, delay.spiking);
165
+ ```
166
+
167
+ The sender's clock and yours need no agreement: only differences of received minus sent are used, and the smallest stands for the link's fixed delay plus the clock offset. Each arrival gives the delay it would have needed, which holds the send interval, the jitter and any lost snapshots at once, so a clean link settles on exactly one send interval. The target is the `quantile` of the last `window` of those. A sudden rise past `spikeHead` times the delay is followed and not learned from, until an arrival needs no more than `spikeTail` times the delay before it. The view's clock never goes back: it runs up to `slowdown` slower or `speedup` faster than real time until it reaches the target.
168
+
169
+ | Option | Default | Meaning |
170
+ | --- | --- | --- |
171
+ | `quantile` | 0.99 | Share of recent arrivals to cover, 0.5 to 1 |
172
+ | `window` | 256 | Arrivals remembered, 16 to 65,536 |
173
+ | `initial` | 0.1 | Seconds of delay, and the floor, for the first 8 arrivals |
174
+ | `min`, `max` | 0, 1 | Bounds on the delay in seconds |
175
+ | `margin` | 0 | Seconds added to the measured delay |
176
+ | `slowdown`, `speedup` | 0.25, 0.05 | How far off real time the view may run |
177
+ | `spikeHead`, `spikeTail` | 4, 2 | Where a spike starts and ends |
178
+
179
+ Call `reset()` after a reconnect. Its proof runs on seeded simulated links, not a captured network trace; [docs/limits.md](../../docs/limits.md) has the limits.
180
+
181
+ ### Any field
182
+
183
+ `FieldBuffer` in `margoengine/netcode/interpolation-fields` does for any fields you name what `SnapshotBuffer` does for the pose, each field blending its own way.
184
+
185
+ ```ts
186
+ import {FieldBuffer} from 'margoengine/netcode/interpolation-fields';
187
+ const buffer = new FieldBuffer({
188
+ position: {type: 'hermite', velocity: 'velocity'},
189
+ velocity: {type: 'linear', size: 3},
190
+ rotation: {type: 'quaternion'},
191
+ scale: {type: 'linear', size: 3},
192
+ tint: {type: 'color'},
193
+ clip: {type: 'step'},
194
+ clipTime: {type: 'time', period: 1.2, clip: 'clip'},
195
+ });
196
+ buffer.push(10, {position: [0, 0, 0], velocity: [1, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1], tint: [1, 0, 0], clip: 2, clipTime: 1.15});
197
+ // A later snapshot need only hold what changed.
198
+ buffer.push(10.1, {position: [0.1, 0, 0], tint: [0, 0, 1], clipTime: 0.05});
199
+ const now = buffer.sample(10.05);
200
+ console.log(now?.position, now?.tint, now?.clipTime);
201
+ ```
202
+
203
+ | Type | Blend | Past the newest snapshot |
204
+ | --- | --- | --- |
205
+ | `linear` | Straight line. One plain number, or `size` numbers | Holds |
206
+ | `hermite` | Cubic through both ends, using its `velocity` field (a `linear` field of the same size) | Runs on, up to `maxPrediction` |
207
+ | `angle` | Radians, the short way round | Holds |
208
+ | `quaternion` | Shortest-arc slerp, normalized when pushed | Holds |
209
+ | `color` | RGB or RGBA in linear light; `space` is `'srgb'` (default) or `'linear'`, alpha straight | Holds |
210
+ | `time` | Animation time. `period` loops it through the seam; `clip` names a `step` field it never blends across | Runs on at its last rate, up to `maxPrediction` |
211
+ | `step` | None: changes on the next snapshot's time | Holds |
212
+
213
+ The options are `capacity` (default 32) and `maxPrediction` (default 0.25 seconds). Like `SnapshotBuffer`, it ignores older or repeated times, gives the oldest snapshot before the ring begins, and reuses its output unless you pass your own from `create()`. Change the `clip` number on every restart of a clip, as a restart without one reads as a scrub back.
214
+
215
+ ### One timeline
216
+
217
+ `margoengine/netcode/interpolation-timeline` is the one home of time-ordered snapshots in the engine. `SnapshotBuffer` and `FieldBuffer` here, and the client and the rewind of `@margoengine/netcode`, all sit on it. Use `Timeline` for snapshots that are objects, and `TimeRing` for rows of numbers in your own storage.
218
+
219
+ ```ts
220
+ import {Timeline, blendAngle} from 'margoengine/netcode/interpolation-timeline';
221
+ const states = new Timeline<{heading: number}>(32);
222
+ states.add(100, {heading: 3});
223
+ states.add(102, {heading: -3});
224
+ states.dropThrough(90); // what is older than you need
225
+ if (states.locate(101) && states.from && states.to) {
226
+ // `a` and `b` are equal on an entry and outside the ring; `past` says how far beyond the newest.
227
+ console.log(blendAngle(states.from.heading, states.to.heading, states.u));
228
+ }
229
+ ```
230
+
231
+ Times must rise: `add` refuses an older or repeated one, and `replace` changes the value at a time already held. `get` finds an exact time in O(log n), `locate` the two entries around a moment. The same file exports the blends the buffers share: `blendAngle`, `slerpInto` and `normalizeQuaternion`.
232
+
233
+ Apache-2.0. Optional, tree-shakable package; `/fields` depends on `@margoengine/math`, and nothing here needs core.
234
+
235
+ ## Extrapolation
236
+
237
+ `client.interpolated()` holds the newest snapshot when the next one is late, so a remote player freezes. `Extrapolator` (its own entry, `@margoengine/netcode/extrapolate`) draws the same view, but past the newest snapshot it keeps moving on at the speed of the last two, for up to `maxTicks`, then holds. When the truth arrives it blends from what was on screen instead of jumping.
238
+
239
+ ```ts
240
+ import { defineGame, defineSchema, GameClient, GameServer, LoopbackNetwork } from '@margoengine/netcode';
241
+ import { Extrapolator } from '@margoengine/netcode/extrapolate';
242
+
243
+ const schema = defineSchema({
244
+ types: {
245
+ Input: { x: 'f32' },
246
+ Box: { x: 'f32', heading: { type: 'f32', interpolate: 'angle' } },
247
+ State: { boxes: { type: 'map', of: 'Box', maxSize: 8 } },
248
+ },
249
+ } as const);
250
+ const game = defineGame({
251
+ schema,
252
+ state: 'State',
253
+ input: 'Input',
254
+ tickRate: 30,
255
+ initial: () => ({ boxes: new Map() }),
256
+ join: (state, id) => void state.boxes.set(id, { x: 0, heading: 0 }),
257
+ step(state, _inputs, _tick, dt) {
258
+ for (const box of state.boxes.values()) box.x += 3 * dt;
259
+ },
260
+ });
261
+
262
+ const network = new LoopbackNetwork({ latency: 40 });
263
+ const now = () => network.time;
264
+ const server = new GameServer(game, { now });
265
+ network.listen().onconnection = (connection) => server.accept(connection);
266
+ let stalled = false;
267
+ const tick = () => {
268
+ network.advance(1000 / 60);
269
+ if (!stalled) while (network.time >= (server.tick + 1) * game.tickMs) server.step();
270
+ };
271
+ const joining = GameClient.join(game, network.connect(), { now, input: () => ({ x: 0 }) });
272
+ let joined = false;
273
+ joining.then(() => (joined = true));
274
+ while (!joined) {
275
+ tick();
276
+ await null;
277
+ }
278
+ const client = await joining;
279
+ const view = new Extrapolator(client, { now, maxTicks: 6, blend: 100 });
280
+ for (let frame = 0; frame < 180; frame++) {
281
+ stalled = frame >= 90 && frame < 120; // half a second with no snapshots
282
+ tick();
283
+ client.update();
284
+ const box = view.state().boxes.get(client.player); // draw this in place of client.interpolated()
285
+ if (frame % 15 === 0) console.log(frame, box?.x, 'ticks late', view.late);
286
+ }
287
+ ```
288
+
289
+ - `'linear'` fields move on in a line and `'angle'` fields the short way; integers, booleans and strings keep their newest value, as in `interpolated()`.
290
+ - `maxTicks` (default 6) bounds how wrong a guess can get: 200 ms at 30 ticks a second. Past it the entity holds.
291
+ - `blend` (default 100 ms, 0 jumps) is the time from what was drawn to the truth once a snapshot arrives. A snapshot that lands while still late starts a blend too.
292
+ - It is a straight line from the last two snapshots, so it overshoots a turn or a stop, and a teleport in the newest snapshot flings the entity on for `maxTicks`. Keep `maxTicks` small, or set it to 0 for a game full of sudden moves.
293
+ - It draws; it does not predict. `client.predicted` and the server see nothing of it, and a shot still rewinds to `client.viewTick`, the interpolated view, not to what was guessed.
294
+ - `client.previousSnapshot` is the snapshot before the newest with its tick, for your own schemes. `SnapshotBuffer` in `@margoengine/netcode/interpolation` extrapolates transforms for a game not on `GameClient`.
295
+
296
+ ## Determinism: why prediction converges exactly
297
+
298
+ The server simulates from exactly the values clients decode: after every tick it encodes the state and continues from
299
+ the decoded copy (floats at wire precision, maps sorted by id). The client does the same after each predicted step,
300
+ and both simulate with the decoded input. So the same inputs give the same bytes on both ends, and a prediction is
301
+ either byte-identical to the server's snapshot or replaced by it. Your `step` must be deterministic: use `+ - * /`,
302
+ `Math.sqrt` (all correctly rounded in IEEE 754), comparisons, and iterate maps; avoid `Math.sin`, `Math.random`,
303
+ `Date.now` and anything whose result can differ between engines.
304
+
305
+ The tests prove it: `tests/netcode.test.js` checks that a client's prediction equals the server's state at the same
306
+ tick under 60 ms latency, 25 ms jitter, 10% loss, duplication and reordering; that a clean link has no misprediction at
307
+ all once joined; and an 8-client soak for 60 s of game time under loss and jitter in which every client stays joined
308
+ and converges.
309
+
310
+ ## Rollback netcode (peer to peer)
311
+
312
+ For deterministic games where every peer runs the whole simulation (fighting games, small co-op): `RollbackSession`
313
+ (its own entry, `@margoengine/netcode/rollback`) uses the same `defineGame` definition. Each peer's input is used `inputDelay` frames after it is sampled (default 2),
314
+ inputs of other players that have not arrived are predicted as their last known input, and when the real one arrives
315
+ and differs, the session loads the state saved before that frame and simulates again to the present (at most
316
+ `maxRollback` frames, default 8; past that it waits). Frames whose every input is known are final: `onconfirm(frame,
317
+ checksum)` reports each, and peers exchange a checksum every `checksumEvery` confirmed frames (default 30) so a desync
318
+ calls `ondesync`. A peer that runs ahead of the others waits a frame now and then (half the difference of the two
319
+ sides' frame advantages), so no one rolls back all the time.
320
+
321
+ ```ts
322
+ import { defineGame, defineSchema, LoopbackNetwork } from '@margoengine/netcode';
323
+ import { RollbackSession } from '@margoengine/netcode/rollback';
324
+
325
+ const schema = defineSchema({
326
+ types: {
327
+ Input: { x: { type: 'quantized', min: -1, max: 1, bits: 8 } },
328
+ Fighter: { x: 'f32' },
329
+ State: { fighters: { type: 'map', of: 'Fighter', maxSize: 4 } },
330
+ },
331
+ } as const);
332
+ const game = defineGame({
333
+ schema,
334
+ state: 'State',
335
+ input: 'Input',
336
+ tickRate: 60,
337
+ initial: () => ({ fighters: new Map() }),
338
+ join: (state, id) => void state.fighters.set(id, { x: id * 2 }),
339
+ step(state, inputs) {
340
+ for (const [id, input] of inputs) {
341
+ const fighter = state.fighters.get(id);
342
+ if (fighter) fighter.x += input.x * 0.1;
343
+ }
344
+ },
345
+ });
346
+
347
+ // Two peers over a simulated 40 ms link; in a game each peer is a different machine with a WebRTC data channel.
348
+ const network = new LoopbackNetwork({ latency: 40, jitter: 10, seed: 2 });
349
+ const [toTwo, toOne] = network.pair();
350
+ const now = () => network.time;
351
+ const one = new RollbackSession(game, { players: [1, 2], local: 1, peers: new Map([[2, toTwo]]), now, input: () => ({ x: 1 }) });
352
+ const two = new RollbackSession(game, { players: [1, 2], local: 2, peers: new Map([[1, toOne]]), now, input: () => ({ x: -1 }) });
353
+ for (let frame = 0; frame < 600; frame++) {
354
+ network.advance(1000 / 60);
355
+ one.update();
356
+ two.update();
357
+ }
358
+ console.log(one.confirmed, one.stats.rollbacks, one.state.fighters.get(1), two.state.fighters.get(1));
359
+ ```
360
+
361
+ The test `tests/rollback.test.js` runs four peers for 20 s under 50 ms latency, 20 ms jitter and 10% loss and checks
362
+ that every confirmed frame of every peer has the same checksum as the game run once offline with every real input.
363
+
364
+ ### Physics worlds: rollback, snapshot diffs and server bodies
365
+
366
+ `@margoengine/netcode/physics` puts a deterministic physics world (a `Physics` of `@margoengine/physics`, or anything with
367
+ `takeSnapshot`, `restoreSnapshot`, `step` and `fixedTimestep`) in a session; it imports no physics code itself.
368
+ `physicsGame({world, schema, input, apply})` is a rollback game whose state is the world's snapshot bytes: each tick
369
+ loads them, calls `apply(inputs, tick)` to drive the world (impulses, forces, motor targets), steps once and keeps the
370
+ snapshot it leaves, so rolling back is loading an older snapshot and every peer reaches the same bits. Every peer builds
371
+ the same world in the same order and keeps every body, collider and joint for the whole session. The tick rate is the
372
+ world's step rate.
373
+
374
+ `snapshotDiff(base, next)` and `applySnapshotDiff(base, diff)` send a snapshot against one both ends have: the changed
375
+ 32-bit words XORed, the unchanged ones counted. `bodyStates([[id, body], ...])` reads a server's bodies into the
376
+ `BODY_STATE_FIELDS` struct its state map sends, and a client's `BodyInterpolator` plays them back between the states it
377
+ has (`push(time, states)`, `sample(time)`, `apply(time, proxies)` onto kinematic bodies' next poses).
378
+
379
+ ```ts
380
+ import { Physics } from '@margoengine/physics';
381
+ import { defineSchema, LoopbackNetwork } from '@margoengine/netcode';
382
+ import { physicsGame } from '@margoengine/netcode/physics';
383
+ import { RollbackSession } from '@margoengine/netcode/rollback';
384
+
385
+ await Physics.load();
386
+ const schema = defineSchema({ types: { Input: { x: 'f32' } } } as const);
387
+ function peer(local: number, link: import('@margoengine/netcode').Connection, push: number) {
388
+ const world = new Physics(null);
389
+ world.addBody(null, { type: 'fixed', position: [0, -0.5, 0], colliders: { shape: 'box', halfExtents: [10, 0.5, 10] } });
390
+ const balls = [1, 2].map((p) => world.addBody(null, { position: [p * 2, 0.5, 0], colliders: { shape: 'sphere', radius: 0.5 } }));
391
+ const game = physicsGame<{ x: number }, ReturnType<Physics['takeSnapshot']>>({
392
+ world,
393
+ schema,
394
+ input: 'Input',
395
+ apply: (inputs) => {
396
+ for (const [p, input] of [...inputs].sort((a, b) => a[0] - b[0])) balls[p - 1]!.applyImpulse([input.x, 0, 0]);
397
+ },
398
+ });
399
+ return new RollbackSession(game, { players: [1, 2], local, peers: new Map([[3 - local, link]]), now: () => network.time, input: () => ({ x: push }) });
400
+ }
401
+ const network = new LoopbackNetwork({ latency: 40, seed: 1 });
402
+ const [toTwo, toOne] = network.pair();
403
+ const one = peer(1, toTwo, 0.1),
404
+ two = peer(2, toOne, -0.1);
405
+ for (let frame = 0; frame < 300; frame++) {
406
+ network.advance(1000 / 60);
407
+ one.update();
408
+ two.update();
409
+ }
410
+ console.log(one.confirmed > 200, one.stats.desyncs + two.stats.desyncs); // true 0
411
+ ```
412
+
413
+ `tests/physics.test.js` rolls a world of six boxes and two pushed balls back on two peers under 60 ms latency, 25 ms
414
+ jitter and 10% loss: 353 frames confirmed, 48 rollbacks and 137 frames stepped again, and every confirmed frame of each
415
+ peer has the checksum of the world stepped offline with every input on time; a diff of one step of a rolling ball is
416
+ 221 bytes of a 1,661,504 byte snapshot.
417
+
418
+ ### Past a full mesh: the relay and spectators
419
+
420
+ A full mesh needs a link from every peer to every other, which stops being practical at about 8. `@margoengine/netcode/relay` gives each peer one link, to a `RollbackRelay`, and shows it the other players through that link as ordinary connections, so `RollbackSession` does not change. The relay runs no game. It also learns each input on the way through, and streams every frame whose inputs are all known to `RollbackSpectator`s, who run the same game on them with no rollback.
421
+
422
+ ```ts
423
+ import { defineGame, defineSchema, LoopbackNetwork } from '@margoengine/netcode';
424
+ import { RollbackSession } from '@margoengine/netcode/rollback';
425
+ import { relayPeers, RollbackRelay, RollbackSpectator } from '@margoengine/netcode/relay';
426
+
427
+ const schema = defineSchema({
428
+ types: {
429
+ Input: { x: 'f32' },
430
+ Fighter: { x: 'f32' },
431
+ State: { fighters: { type: 'map', of: 'Fighter', maxSize: 16 } },
432
+ },
433
+ } as const);
434
+ const game = defineGame({
435
+ schema,
436
+ state: 'State',
437
+ input: 'Input',
438
+ tickRate: 60,
439
+ initial: () => ({ fighters: new Map() }),
440
+ join: (state, id) => void state.fighters.set(id, { x: 0 }),
441
+ step(state, inputs, _frame, dt) {
442
+ for (const [id, input] of inputs) state.fighters.get(id)!.x += input.x * dt;
443
+ },
444
+ });
445
+
446
+ const network = new LoopbackNetwork({ latency: 30 });
447
+ const now = () => network.time;
448
+ const players = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
449
+ const relay = new RollbackRelay({ players });
450
+ const connect = () => {
451
+ const [near, far] = network.pair();
452
+ relay.accept(far);
453
+ return near;
454
+ };
455
+ const sessions = players.map(
456
+ (local) =>
457
+ new RollbackSession(game, {
458
+ players,
459
+ local,
460
+ peers: relayPeers(connect(), { players, local }), // one link, however many players
461
+ now,
462
+ input: () => ({ x: local % 2 ? 1 : -1 }),
463
+ }),
464
+ );
465
+ const watcher = new RollbackSpectator(game, connect());
466
+ for (let frame = 0; frame < 300; frame++) {
467
+ network.advance(1000 / 60);
468
+ for (const session of sessions) session.update();
469
+ watcher.update();
470
+ }
471
+ console.log('players at', sessions[0].confirmed, 'spectator at', watcher.frame, watcher.state.fighters.get(1));
472
+ ```
473
+
474
+ - Every message crosses twice, so a player sees the sum of two links' latency instead of one, and the relay carries every player's traffic: with `n` players, a peer's messages reach `n - 1` others through it. It holds no state of the game and cannot change an input, but it is one place that can fail.
475
+ - A spectator starts from the first frame however late it joins, at `maxFrames` a call (default 8), and what it shows is final: the same `onconfirm` checksums as the players. `spectatorDelay` keeps it that many frames behind, so a spectator cannot help a player. Frames are kept for `history` frames (default 216,000: an hour at 60 Hz); a spectator who comes after that is refused.
476
+ - `authorize(player, token)` decides who gets in, with `player` undefined for a spectator. A seat already taken closes with `CloseCode.full`. The relay trusts the `player` a connection names, so with no `authorize` a stranger can take an empty seat.
477
+ - A peer can still send different inputs to different peers: the relay keeps the first it saw for spectators, and the desync check catches the rest.
478
+
479
+ ## Lag compensation (server-side rewind)
480
+
481
+ `LagCompensation` keeps where every hit shape (circle or sphere) was at each of the last `history` ticks (default 32).
482
+ Record the shapes after each server tick; when a shot arrives, check it against the shapes at the tick the shooter was
483
+ looking at (`client.viewTick`, sent with the shot), blended between the recorded ticks around it. A client cannot rewind
484
+ further than the history. Validate the rest of the shot on the server (that the origin is the shooter's position, the
485
+ rate of fire), as for any input.
486
+
487
+ ```ts
488
+ import { LagCompensation } from '@margoengine/netcode';
489
+
490
+ const lag = new LagCompensation({ history: 32 });
491
+ lag.record(100, [[7, { position: [0, 0], radius: 0.5 }]]);
492
+ lag.record(101, [[7, { position: [2, 0], radius: 0.5 }]]);
493
+ // A shooter that saw tick 100.5 aimed along +y from (1, -5): the target was at (1, 0) then.
494
+ const hit = lag.raycast(100.5, [1, -5], [0, 1]);
495
+ console.log(hit?.id, hit?.distance); // 7 4.5
496
+ ```
497
+
498
+ ### Boxes and capsules
499
+
500
+ `LagCompensation` tests circles and spheres. `HitboxRewind` (its own entry, `@margoengine/netcode/hitboxes`) has the same `record`, `at` and `raycast`, and also takes boxes and capsules that turn. It is 3D: a 2D game passes z as 0.
501
+
502
+ ```ts
503
+ import { HitboxRewind } from '@margoengine/netcode/hitboxes';
504
+
505
+ const rewind = new HitboxRewind({ history: 32 });
506
+ const turned = [0, Math.sin(Math.PI / 8), 0, Math.cos(Math.PI / 8)]; // a quarter turn about y, as [x, y, z, w]
507
+ rewind.record(100, [
508
+ [7, { position: [0, 1, 0], radius: 0.4, halfHeight: 0.5 }], // a player: a standing capsule
509
+ [8, { position: [4, 1, 0], halfExtents: [2, 1, 0.1] }], // a shield: a box
510
+ ]);
511
+ rewind.record(101, [
512
+ [7, { position: [2, 1, 0], radius: 0.4, halfHeight: 0.5 }],
513
+ [8, { position: [4, 1, 0], halfExtents: [2, 1, 0.1], rotation: turned }],
514
+ ]);
515
+ // A shooter that saw tick 100.5 aimed along +z from (1, 1, -5): the capsule was at x = 1 then.
516
+ const hit = rewind.raycast(100.5, [1, 1, -5], [0, 0, 1], { maxDistance: 100 });
517
+ console.log(hit?.id, hit?.distance, hit?.point);
518
+ ```
519
+
520
+ - Shapes: `{ position, radius }` is a sphere, `{ position, halfExtents, rotation? }` a box, and `{ position, radius, halfHeight, rotation? }` a capsule along its own y axis, `2 * (halfHeight + radius)` tall in all. `rotation` is a quaternion `[x, y, z, w]`, normalised for you, default none.
521
+ - Between two ticks positions and sizes blend in a line and rotations the short way round. A shape that changes between box and capsule takes the nearer tick. A tick older than `history` is clamped, so a client cannot rewind further.
522
+ - For several parts of one body, give each its own id and map ids back to the player yourself.
523
+ - The ray tests are those of `@margoengine/math`: a slab test for boxes and `Capsule.intersectRay`, in each shape's own frame. Spheres give what `LagCompensation` gives.
524
+
525
+ ## Interest management and bandwidth budgets
526
+
527
+ `InterestManager` (its own entry, `@margoengine/netcode/interest`) is a ready-made `view` for `GameServer`: each client gets only the entities within `radius` of its player, the most important first, and no snapshot message goes over `budget` bytes. What it leaves out never reaches that client, so a cheat cannot read it from the wire.
528
+
529
+ ```ts
530
+ import { defineGame, defineSchema, GameClient, GameServer, LoopbackNetwork } from 'margoengine/netcode';
531
+ import { InterestManager } from 'margoengine/netcode/interest';
532
+
533
+ const schema = defineSchema({
534
+ types: {
535
+ Input: { x: 'f32' },
536
+ Box: { x: 'f32', y: 'f32', spin: 'f32' },
537
+ State: { boxes: { type: 'map', of: 'Box', maxSize: 1024 } },
538
+ },
539
+ } as const);
540
+ const game = defineGame({
541
+ schema,
542
+ state: 'State',
543
+ input: 'Input',
544
+ tickRate: 30,
545
+ initial: () => {
546
+ const boxes = new Map<number, { x: number; y: number; spin: number }>();
547
+ for (let i = 0; i < 500; i++) boxes.set(1000 + i, { x: i % 25, y: Math.floor(i / 25), spin: 0 });
548
+ return { boxes };
549
+ },
550
+ join: (state, id) => void state.boxes.set(id, { x: 12, y: 10, spin: 0 }),
551
+ leave: (state, id) => void state.boxes.delete(id),
552
+ step(state) {
553
+ for (const box of state.boxes.values()) box.spin += 0.1;
554
+ },
555
+ });
556
+
557
+ const interest = new InterestManager(game, {
558
+ collections: { boxes: { position: (box) => [box.x, box.y] } },
559
+ radius: 8,
560
+ budget: 400, // bytes per snapshot: 12,000 B/s at 30 snapshots a second
561
+ });
562
+ const network = new LoopbackNetwork({ latency: 30 });
563
+ const now = () => network.time;
564
+ const server = new GameServer(game, { now, view: interest.view });
565
+ network.listen().onconnection = (connection) => server.accept(connection);
566
+ const joining = GameClient.join(game, network.connect(), { now, input: () => ({ x: 0 }) });
567
+ let client: Awaited<typeof joining> | undefined;
568
+ joining.then((joined) => (client = joined));
569
+ for (let frame = 0; frame < 120; frame++) {
570
+ network.advance(1000 / 60);
571
+ if (network.time >= (server.tick + 1) * game.tickMs) server.step();
572
+ client?.update();
573
+ await null;
574
+ }
575
+ console.log('client holds', client?.authoritative.boxes.size, 'of', server.state.boxes.size);
576
+ console.log(interest.stats(client?.player ?? 0)); // { inScope, sent, deferred, removed, bytes, over }
577
+ ```
578
+
579
+ - **Who is in scope:** the exact circle (or sphere, for 3-number positions) of `radius` around the player's own entity, or around `focus(state, player)` for a camera. A hashed grid only speeds the search, so `cell` never changes the result. An entity stays in scope until `leaveRadius` (default `radius` x 1.1), so one on the edge does not flicker. `always` adds entities at any distance (team mates, objectives) and `visible` hides ones inside the circle (behind a wall, stealthed). Other fields of the state, and maps you do not list, go to everyone whole.
580
+ - **Who goes first:** a priority accumulator per client. Each snapshot every entity with something new adds its `priority` (default `radius / distance`, 1 at the edge up to 16 close by); the highest go first, those sent go back to 0, those left out keep theirs, so nothing starves. An entity too big for the bytes left is skipped for a smaller one behind it.
581
+ - **The budget:** counts the whole message, the 21 bytes of envelope included, and `stats(player).bytes` never reads less than the real size. `budget` may be a function of the player and is read on every snapshot, so it can follow what the link does. For a rate, divide bytes per second by snapshots per second. The own entity and the fields not managed always go; if they alone pass the budget, `stats(player).over` says by how much.
582
+ - **What the client sees:** an entity held back keeps the value it last got and stays on screen; it never goes back to an older one in normal running. A value sent is repeated until the client confirms it, because a snapshot is a delta against what the client confirmed. That is what makes loss harmless, and it means that under a tight budget a moving entity updates about once per round trip plus one snapshot. With bytes to spare and nothing waiting, repeats are brought up to date at once.
583
+
584
+ `view` also gets the state the client confirmed as a third argument, so a `view` of your own can see what would cost nothing to send.
585
+
586
+ ## Correction smoothing
587
+
588
+ When a snapshot corrects the prediction, `client.predicted` jumps to the truth at once. `CorrectionSmoother` (its own entry, `@margoengine/netcode/smoothing`) gives you a state to draw in which that jump is blended away over a few frames, while the simulation stays exact: every number has an offset that shrinks over time, drawn as value plus offset, and a correction folds into the offset so nothing moves on screen at that moment.
589
+
590
+ ```ts
591
+ import { defineGame, defineSchema, GameClient, GameServer, LoopbackNetwork } from 'margoengine/netcode';
592
+ import { CorrectionSmoother } from 'margoengine/netcode/smoothing';
593
+
594
+ const schema = defineSchema({
595
+ types: {
596
+ Input: { x: 'f32' },
597
+ Box: { x: 'f32', heading: { type: 'f32', interpolate: 'angle' } },
598
+ State: { boxes: { type: 'map', of: 'Box', maxSize: 8 } },
599
+ },
600
+ } as const);
601
+ const game = defineGame({
602
+ schema,
603
+ state: 'State',
604
+ input: 'Input',
605
+ tickRate: 30,
606
+ initial: () => ({ boxes: new Map() }),
607
+ join: (state, id) => void state.boxes.set(id, { x: 0, heading: 0 }),
608
+ step(state, inputs, _tick, dt) {
609
+ for (const [id, input] of inputs) {
610
+ const box = state.boxes.get(id);
611
+ if (box) box.x += input.x * dt;
612
+ }
613
+ },
614
+ });
615
+
616
+ const network = new LoopbackNetwork({ latency: 40 });
617
+ const now = () => network.time;
618
+ const server = new GameServer(game, { now });
619
+ network.listen().onconnection = (connection) => server.accept(connection);
620
+ const tick = () => {
621
+ network.advance(1000 / 60);
622
+ if (network.time >= (server.tick + 1) * game.tickMs) server.step();
623
+ };
624
+ const joining = GameClient.join(game, network.connect(), { now, input: () => ({ x: 1 }) });
625
+ let joined = false;
626
+ joining.then(() => (joined = true));
627
+ while (!joined) {
628
+ tick();
629
+ await null;
630
+ }
631
+ const client = await joining;
632
+ const smooth = new CorrectionSmoother(client, { now, halfLife: 50, snap: 10 });
633
+ for (let frame = 0; frame < 120; frame++) {
634
+ tick();
635
+ if (frame === 60) server.state.boxes.get(client.player)!.x += 2; // something the client cannot predict
636
+ client.update();
637
+ const drawn = smooth.state(); // draw this; client.predicted stays exact
638
+ if (frame % 20 === 0) console.log(drawn.boxes.get(client.player)?.x, 'left to blend', smooth.error);
639
+ }
640
+ ```
641
+
642
+ - Every field the schema interpolates eases: `'linear'` numbers in a line, `'angle'` numbers the short way round. Integers, booleans and strings step at once, as they do in `interpolated()`. Maps, arrays, optionals and nested structs are followed; an entity that appears or goes gets no offset.
643
+ - `halfLife` (default 50 ms) is how long an error takes to halve, by the clock, so the blend is the same at any frame rate.
644
+ - `fast: { from, to, halfLife }` blends in a second, shorter half life for errors from `from` to `to` world units, so a small error eases gently and a big one does not drag on. The numbers of one struct shrink as one vector, keeping its direction.
645
+ - `snap` (default never) is the distance over which an error jumps instead of blending: a teleport or a respawn. `smooth.reset()` clears everything by hand.
646
+ - `smooth.state()` returns `client.predicted` itself once settled, so a settled frame allocates nothing. Do not write to what it returns. `smooth.error` is what is left. `close()` or `using` stops it.
647
+
648
+ A `GameClient` also has `oncorrection(before, after)`, called with the predicted state just before and just after each correction: the raw event, for your own smoothing or for logging how often prediction goes wrong.
649
+
650
+ ## Transports and the Node server
651
+
652
+ Each transport is its own entry, so an app loads only the one it uses.
653
+
654
+ - `@margoengine/netcode/websocket`: `openWebSocket(url, { signal, protocols })` resolves with a `Connection` over
655
+ the standard WebSocket class (browsers, Deno, Bun, Node 22+). A WebSocket is one ordered reliable stream, so
656
+ 'unreliable' messages go reliably too, except that they are dropped while more than 64 KiB is buffered
657
+ (`dropUnreliableAbove`): a stale snapshot queued behind others is worse than none.
658
+ - `@margoengine/netcode/webrtc`: `createDataChannels(peer)` makes two pre-negotiated data channels on an
659
+ `RTCPeerConnection` (ordered reliable, and unordered with `maxRetransmits: 0`) and `dataChannelConnection(channels)`
660
+ wraps them as a `Connection`, so snapshots and inputs really are unreliable and never wait behind a lost packet.
661
+ `@margoengine/netcode/signal` carries the offers, answers and ICE candidates (see "Signalling for WebRTC" below), or carry them yourself over any channel. Works for client-server and for
662
+ `RollbackSession` peers.
663
+ - `@margoengine/netcode/webtransport`: `openWebTransport(url, { signal, serverCertificateHashes, congestionControl })`
664
+ resolves with a `Connection` over the W3C WebTransport class on HTTP/3: 'unreliable' messages are real datagrams, so a
665
+ lost snapshot never holds up the next, with no ICE and no signalling, and 'reliable' messages go length-prefixed on
666
+ one bidirectional stream. A message bigger than `maxDatagramSize` goes on the stream rather than vanish, and a full
667
+ datagram queue drops the message, a stale snapshot being worse than none. Where there is no WebTransport it rejects
668
+ with code `unsupported`: fall back to `openWebSocket`. The server end is yours to host: Node has no HTTP/3 server, so
669
+ `acceptWebTransport(session)` takes a session of the W3C shape from the HTTP/3 server you run and gives the `Connection`
670
+ for `server.accept`, and `webTransportConnection(session, stream)` wraps a stream you opened yourself. See "WebTransport" below.
671
+ - `@margoengine/netcode/node` (Node only): `listenWebSocket({ port, host, path, origins, maxConnections, firstMessageTimeout, maxPayload })` is a WebSocket
672
+ server written here from RFC 6455 on `node:http` and `node:crypto` (no dependency): binary messages only (text
673
+ closes with 1003), client frames must be masked (1002), messages over `maxPayload` (default 64 KiB) close with 1009,
674
+ fragmentation and ping are handled, a close frame with a code no peer may send fails with 1002 and one whose reason
675
+ is not UTF-8 with 1007, another protocol version gets 426 naming 13, a client more than 8 MiB behind is closed as too
676
+ slow. Safe defaults, each with
677
+ an option: only web pages served from the server's own host may connect (`origins`, default the own host; `'*'` allows
678
+ any page, a list allows exactly those origins; a client that sends no Origin, such as Node, still connects unless a
679
+ list is given; others get 403), at most 1,024 connections (`maxConnections`; the next upgrade gets 503) and a
680
+ connection that sends no message within 10,000 ms is closed with `CloseCode.timeout` (`firstMessageTimeout`).
681
+ `serve(game, options)` runs a `GameServer` on it in real time: the self-hosted server in one call.
682
+
683
+ ```ts
684
+ // Server and client in one file for the example; in a game, put the schema and game in a module both import.
685
+ import { defineGame, defineSchema } from '@margoengine/netcode';
686
+ import { serve } from '@margoengine/netcode/node';
687
+ import { openWebSocket } from '@margoengine/netcode/websocket';
688
+ import { GameClient } from '@margoengine/netcode';
689
+
690
+ const schema = defineSchema({
691
+ types: {
692
+ Input: { x: { type: 'quantized', min: -1, max: 1, bits: 8 } },
693
+ Player: { x: 'f32' },
694
+ State: { players: { type: 'map', of: 'Player', maxSize: 16 } },
695
+ },
696
+ } as const);
697
+ const game = defineGame({
698
+ schema,
699
+ state: 'State',
700
+ input: 'Input',
701
+ initial: () => ({ players: new Map() }),
702
+ join: (state, id) => void state.players.set(id, { x: 0 }),
703
+ leave: (state, id) => void state.players.delete(id),
704
+ step(state, inputs, _tick, dt) {
705
+ for (const [id, input] of inputs) {
706
+ const player = state.players.get(id);
707
+ if (player) player.x += input.x * 4 * dt;
708
+ }
709
+ },
710
+ });
711
+
712
+ const stop = new AbortController();
713
+ const { port } = await serve(game, { port: 0, signal: stop.signal }); // pass host: '0.0.0.0' to accept other machines
714
+
715
+ // A client (in a browser it is the same code with your server's wss:// URL).
716
+ const client = await GameClient.join(game, await openWebSocket(`ws://127.0.0.1:${port}`), { input: () => ({ x: 1 }) });
717
+ const frames = setInterval(() => client.update(), 1000 / 60);
718
+ setTimeout(() => {
719
+ clearInterval(frames);
720
+ console.log('moved to', client.predicted.players.get(client.player)?.x);
721
+ client.close();
722
+ stop.abort();
723
+ }, 1000);
724
+ ```
725
+
726
+ Behind TLS: run it on a private port behind a reverse proxy (nginx, Caddy) that terminates `wss://` and forwards the
727
+ upgrade. The default `origins` compares the page's Origin with the request's `Host` header, so if the proxy rewrites
728
+ `Host` (or the page is served from another host than the game server), set `origins` to your site's origin, for
729
+ example `origins: ['https://game.example.com']`; `origins: '*'` accepts any page.
730
+
731
+ ## WebTransport
732
+
733
+ ```ts
734
+ import { defineGame, defineSchema, GameClient, type GameServer } from '@margoengine/netcode';
735
+ import { acceptWebTransport, openWebTransport, type WebTransportSession } from '@margoengine/netcode/webtransport';
736
+
737
+ const schema = defineSchema({
738
+ types: {
739
+ Input: { x: 'f32' },
740
+ State: { x: 'f32' },
741
+ },
742
+ } as const);
743
+ const game = defineGame({
744
+ schema,
745
+ state: 'State',
746
+ input: 'Input',
747
+ initial: () => ({ x: 0 }),
748
+ step(state, inputs, _tick, dt) {
749
+ for (const [, input] of inputs) state.x += input.x * dt;
750
+ },
751
+ });
752
+
753
+ // In a browser: one line. A session that is not up rejects with a coded error; `signal` aborts it.
754
+ async function join(url: string) {
755
+ const connection = await openWebTransport(url);
756
+ return GameClient.join(game, connection, { input: () => ({ x: 1 }) });
757
+ }
758
+
759
+ // In the HTTP/3 server you run: hand each session of the W3C shape to the game.
760
+ async function welcome(server: GameServer<unknown, unknown>, session: WebTransportSession) {
761
+ server.accept(await acceptWebTransport(session));
762
+ }
763
+
764
+ console.log('ready to wire up', join.name, welcome.name);
765
+ ```
766
+
767
+ - A server with no public certificate passes `serverCertificateHashes` from a self-signed certificate of at most 14 days, the browser's rule.
768
+ - `congestionControl` defaults to `'low-latency'` here, for snapshots; it is a hint the browser may ignore.
769
+ - Chromium reported a `maxDatagramSize` of 1,211 B on loopback. A snapshot over the limit goes on the stream, in order and behind anything lost, so keep snapshots small (see the budgets of `@margoengine/netcode/interest`).
770
+ - Options shared with the other transports: `dropUnreliableAbove` (default 65,536 B waiting on the stream) and `maxMessageBytes` (default 16 MiB; a bigger reliable message closes the connection with `CloseCode.rateLimit`).
771
+ - Close codes and reasons reach the other end; a reason is cut to 1,024 bytes on a character boundary, as the W3C API asks.
772
+ - Proved against a real browser and a real HTTP/3 server: `packages/netcode/tests/webtransport-proof/` runs Chromium against an echo server on the outside tool aioquic, which is test-only and is not shipped.
773
+
774
+ ## Rooms and matchmaking
775
+
776
+ `@margoengine/netcode/rooms` has the room API shape that web game servers commonly use, for games that want rooms,
777
+ messages and a synced state rather than tick-based prediction (turn-based games, lobbies, card games): a `Room`
778
+ subclass with `onCreate`, `onAuth`, `onJoin`, `onLeave`, `onDispose`, `onMessage(type, handler)`, `setState`,
779
+ `broadcast`, `setPatchRate`, `setSimulationInterval`, `lock` and `unlock`; a `RoomServer` that defines rooms by name and
780
+ matches clients into them (`joinOrCreate`, `create`, `join`, `joinById`); and a `RoomsClient` whose joined room has
781
+ `state`, `onStateChange`, `onMessage`, `send`, `leave` and `states()` (an async iterator). Written from public
782
+ descriptions of that API shape, not from any library's source. The state is a schema struct sent in full once, then as
783
+ deltas at the patch rate (default every 50 ms); messages are JSON with a size limit (default 4096 bytes), and anything
784
+ malformed closes the connection. A room is listed and joinable only once its `onCreate` resolved (joins that arrive
785
+ meanwhile wait for it). When `onCreate`, `onJoin`, `onLeave`, `onDispose` or a message handler throws (or its promise
786
+ rejects), the client concerned is closed with `CloseCode.error`, the error goes to `rooms.onerror(error, room)`
787
+ (default `console.error`) and the server keeps running; a room whose `onCreate` threw is disposed. When a timed patch
788
+ or a `setSimulationInterval` step throws, `onerror` gets it with the room, and that room is stopped: every client is
789
+ closed with `CloseCode.error` and the room is disposed.
790
+
791
+ `new RoomServer(options)` limits what clients can hold; every option has a safe default and `new RoomServer()` uses
792
+ them all:
793
+
794
+ | Option | Default | What happens past it |
795
+ | --- | --- | --- |
796
+ | `joinTimeout` | 10,000 ms | A connection that has not sent its join is closed with `CloseCode.timeout`. |
797
+ | `maxConnections` | 1,024 | Connections in rooms plus those still joining; the next is closed with `CloseCode.full`. `rooms.connections` counts them. |
798
+ | `maxRooms` | 256 | Rooms, those in `onCreate` included. `rooms.create()` rejects with MargoError `'failed'`; a client's `create` or `joinOrCreate` that would make one more is refused (its join rejects). |
799
+ | `limits.messagesPerSecond` | 120 | A token bucket per client in every room; a client over it, its burst spent, is closed with `CloseCode.rateLimit`. A room may set its own `maxMessagesPerSecond`, as it sets `maxMessageBytes`. |
800
+ | `limits.burst` | 60 | The bucket size; a room may set its own `messageBurst`. |
801
+
802
+ ```ts
803
+ import { defineSchema, LoopbackNetwork } from '@margoengine/netcode';
804
+ import { Room, type RoomClient, RoomServer, RoomsClient } from '@margoengine/netcode/rooms';
805
+
806
+ const schema = defineSchema({
807
+ types: {
808
+ Player: { name: { type: 'string', maxLength: 32 }, score: 'uint' },
809
+ State: { players: { type: 'map', of: 'Player', maxSize: 8 } },
810
+ },
811
+ } as const);
812
+ type State = { players: Map<number, { name: string; score: number }> };
813
+
814
+ class Quiz extends Room<State> {
815
+ schema = schema;
816
+ stateType = 'State';
817
+ maxClients = 8;
818
+ onCreate() {
819
+ this.setState({ players: new Map() });
820
+ this.onMessage('answer', (client, answer: string) => {
821
+ const player = this.state.players.get(this.idOf(client));
822
+ if (player && answer === '42') player.score++;
823
+ });
824
+ }
825
+ onJoin(client: RoomClient, options: { name?: string }) {
826
+ this.state.players.set(this.idOf(client), { name: String(options.name ?? 'guest'), score: 0 });
827
+ }
828
+ onLeave(client: RoomClient) {
829
+ this.state.players.delete(this.idOf(client));
830
+ }
831
+ }
832
+
833
+ // Server and client in one page over the loopback; with Node, use listenWebSocket and openWebSocket instead.
834
+ const network = new LoopbackNetwork({ latency: 20 });
835
+ const rooms = new RoomServer().define('quiz', Quiz);
836
+ network.listen().onconnection = (connection) => rooms.accept(connection);
837
+ const client = new RoomsClient(async () => network.connect());
838
+ const joining = client.joinOrCreate<State>('quiz', { name: 'Ada' }, { schema, stateType: 'State' });
839
+ const tick = setInterval(() => network.advance(10), 10);
840
+ const room = await joining;
841
+ room.onStateChange((state) => console.log([...state.players.values()]));
842
+ room.send('answer', '42');
843
+ setTimeout(() => {
844
+ clearInterval(tick);
845
+ room.leave();
846
+ rooms.close();
847
+ }, 300);
848
+ ```
849
+
850
+ ### Reconnection and held seats
851
+
852
+ Set `reconnectWindow` on a room and a client whose link drops keeps its seat for that many milliseconds. `onDrop` runs at once, and `onLeave` only if the time runs out. The seat counts against `maxClients`, an empty room with a held seat stays alive, and the same `RoomClient` comes back, so `idOf` and `userData` hold. The client keeps `room.reconnectionToken` and hands it to `RoomsClient.reconnect` on a new connection; the whole state follows.
853
+
854
+ ```ts
855
+ import { defineSchema, LoopbackNetwork } from '@margoengine/netcode';
856
+ import { Room, RoomsClient, RoomServer, type RoomClient } from '@margoengine/netcode/rooms';
857
+
858
+ const schema = defineSchema({
859
+ types: {
860
+ Player: { online: 'bool' },
861
+ State: { players: { type: 'map', of: 'Player', maxSize: 8 } },
862
+ },
863
+ } as const);
864
+ interface State {
865
+ players: Map<number, { online: boolean }>;
866
+ }
867
+
868
+ class Table extends Room<State> {
869
+ schema = schema;
870
+ stateType = 'State';
871
+ reconnectWindow = 30_000; // a dropped player has 30 seconds to come back
872
+ onCreate() {
873
+ this.setState({ players: new Map() });
874
+ }
875
+ onJoin(client: RoomClient) {
876
+ this.state.players.set(this.idOf(client), { online: true });
877
+ }
878
+ onDrop(client: RoomClient) {
879
+ this.state.players.get(this.idOf(client))!.online = false;
880
+ }
881
+ onReconnect(client: RoomClient) {
882
+ this.state.players.get(this.idOf(client))!.online = true;
883
+ }
884
+ onLeave(client: RoomClient) {
885
+ this.state.players.delete(this.idOf(client));
886
+ }
887
+ }
888
+
889
+ const network = new LoopbackNetwork({ latency: 10 });
890
+ const rooms = new RoomServer().define('table', Table);
891
+ network.listen().onconnection = (connection) => rooms.accept(connection);
892
+ const connections: ReturnType<LoopbackNetwork['connect']>[] = [];
893
+ const client = new RoomsClient(async () => {
894
+ connections.push(network.connect());
895
+ return connections.at(-1)!;
896
+ });
897
+ const options = { schema, stateType: 'State' };
898
+ const tick = setInterval(() => network.advance(10), 5);
899
+
900
+ const first = await client.joinOrCreate<State>('table', {}, options);
901
+ connections[0].close(1006, 'link lost');
902
+ await new Promise((resolve) => setTimeout(resolve, 100));
903
+ const back = await client.reconnect<State>(first.reconnectionToken, options); // keep the token in sessionStorage
904
+ console.log('same seat:', back.sessionId === first.sessionId);
905
+ clearInterval(tick);
906
+ rooms.close();
907
+ ```
908
+
909
+ - `reconnectWindow` defaults to 0: no seats are held, no token is sent and everything behaves as it did. `room.dropped` lists the clients being waited for.
910
+ - A token works once; each reconnect gives a new one. It holds 128 random bits from `crypto.getRandomValues`, and whoever has it can take the seat, so keep it private to the player.
911
+ - No seat is kept after a clean `leave()`, a kick, a protocol or rate-limit close, or a hook that threw: the seat is for a link that was lost.
912
+ - A client that comes back before the server noticed the loss takes over: its old connection closes with `CloseCode.removed`, and neither `onDrop` nor `onLeave` runs.
913
+ - A seat is held for the client that had it. To hold a seat ahead for a player who has not joined yet (for example from a matchmaker), use `LobbyRoom` below.
914
+
915
+ ### Lobby listings and reserved seats
916
+
917
+ `@margoengine/netcode/lobby` adds a room list and one-time seat reservations, the two things a matchmaker needs.
918
+ Subclass `LobbyRoom` in place of `Room`, give it searchable `setMetadata({...})`, and serve `RoomLobby.list()` from
919
+ your own authenticated HTTP API. `reserve(roomId, options)` holds a seat for a player who has not connected yet: the
920
+ seat counts against `maxClients` (so a public join cannot take it), keeps an empty room alive, and runs out after
921
+ `lifetime` milliseconds (default 15,000). The player joins with `joinById(roomId, { seatToken })`; `onAuth` and
922
+ `onJoin` get the options given at reservation, never options the player sends.
923
+
924
+ ```ts
925
+ import { defineSchema, LoopbackNetwork } from '@margoengine/netcode';
926
+ import { RoomsClient, RoomServer, type RoomClient, type RoomOptions } from '@margoengine/netcode/rooms';
927
+ import { LobbyRoom, RoomLobby } from '@margoengine/netcode/lobby';
928
+
929
+ const schema = defineSchema({
930
+ types: { Player: { team: 'uint' }, State: { players: { type: 'map', of: 'Player', maxSize: 8 } } },
931
+ } as const);
932
+ interface State {
933
+ players: Map<number, { team: number }>;
934
+ }
935
+
936
+ class Match extends LobbyRoom<State> {
937
+ schema = schema;
938
+ stateType = 'State';
939
+ maxClients = 2;
940
+ onCreate() {
941
+ this.setState({ players: new Map() });
942
+ this.setMetadata({ mode: 'duel', map: 'harbour' });
943
+ }
944
+ onJoin(client: RoomClient, options: RoomOptions) {
945
+ this.state.players.set(this.idOf(client), { team: Number(options.team) });
946
+ }
947
+ }
948
+
949
+ const network = new LoopbackNetwork({ latency: 10 });
950
+ const rooms = new RoomServer().define('match', Match);
951
+ network.listen().onconnection = (connection) => rooms.accept(connection);
952
+ const lobby = new RoomLobby(rooms);
953
+ const tick = setInterval(() => network.advance(10), 5);
954
+
955
+ // The matchmaker (server code): find a duel, hold a seat with the team it chose.
956
+ const room = await rooms.create('match');
957
+ console.log(lobby.list({ metadata: { mode: 'duel' } }).length, 'duel room open');
958
+ const seat = lobby.reserve(room.roomId, { team: 2 }, 10_000);
959
+
960
+ // The player, told roomId and seatToken over your authenticated API:
961
+ const client = new RoomsClient(async () => network.connect());
962
+ const joined = await client.joinById<State>(seat.roomId, { seatToken: seat.seatToken }, { schema, stateType: 'State' });
963
+ console.log('joined', joined.roomId === room.roomId);
964
+ clearInterval(tick);
965
+ rooms.close();
966
+ ```
967
+
968
+ - The token holds 256 random bits and is good once; whoever holds it takes the reserved join identity, so send it to
969
+ the player alone over TLS. `cancelReservation(seatToken)` frees a seat at once; expiry and room disposal free it too.
970
+ - The seat stays counted while the room's async `onAuth` runs, so slow authentication cannot overbook the room.
971
+ - Listings are exact-match filters on name and scalar metadata; locked, full and `privateRoom` rooms are left out,
972
+ and a private room is still joinable by id or reservation. Plain `Room` subclasses are listed with empty metadata
973
+ but cannot be reserved in.
974
+ - Reservations live in the memory of the one server process, as held seats do: a restart loses them.
975
+
976
+ ### Many server processes: presence
977
+
978
+ `@margoengine/netcode/presence` lists and reserves rooms across several `RoomServer` processes. Wrap each server in a
979
+ `RoomNode` with its public `endpoint` and a shared `RoomPresence`; `run()` keeps a leased directory entry fresh and
980
+ serves reservation requests for the rooms it owns. Any node's `list()` sees the open rooms of every live process, and
981
+ `reserve(roomId)` is carried to the owning process, which grants the seat and returns its endpoint with the token.
982
+ `MemoryPresence` shares one process (tests, a single host with several servers); `openSqlitePresence(file)` shares
983
+ processes on one host through a SQLite WAL file; for several hosts implement `PresenceStore` (`set`, `get`, `keys`,
984
+ an atomic `take`, `delete`) on your database and pass it to `StorePresence`.
985
+
986
+ ```ts
987
+ import { defineSchema } from '@margoengine/netcode';
988
+ import { RoomServer } from '@margoengine/netcode/rooms';
989
+ import { LobbyRoom } from '@margoengine/netcode/lobby';
990
+ import { MemoryPresence, RoomNode } from '@margoengine/netcode/presence';
991
+
992
+ const schema = defineSchema({ types: { State: { joined: 'uint' } } } as const);
993
+ class Match extends LobbyRoom<{ joined: number }> {
994
+ schema = schema;
995
+ stateType = 'State';
996
+ maxClients = 2;
997
+ onCreate() {
998
+ this.setState({ joined: 0 });
999
+ this.setMetadata({ mode: 'duel' });
1000
+ }
1001
+ }
1002
+
1003
+ using presence = new MemoryPresence();
1004
+ using east = new RoomServer().define('match', Match);
1005
+ using west = new RoomServer().define('match', Match);
1006
+ await using a = new RoomNode(east, { presence, endpoint: 'wss://east.example.com' });
1007
+ await using b = new RoomNode(west, { presence, endpoint: 'wss://west.example.com' });
1008
+ const room = await east.create('match');
1009
+ const serving = a.run();
1010
+ await a.sync(); // publish now instead of at the next heartbeat
1011
+
1012
+ const [open] = await b.list({ metadata: { mode: 'duel' } }); // west sees east's room
1013
+ const seat = await b.reserve(open.roomId, { team: 1 }); // granted by east, the owner
1014
+ console.log(seat.endpoint, seat.roomId === room.roomId); // connect there, then joinById with seat.seatToken
1015
+ await a.close();
1016
+ await serving;
1017
+ ```
1018
+
1019
+ - Leases default to 10,000 ms and heartbeats to 1,000 ms (the heartbeat must be shorter); a process that stops
1020
+ renewing drops out of every list when its lease ends. Lists are eventually consistent: call `sync()` after creating
1021
+ or changing a room to publish at once.
1022
+ - Only the owner grants a seat, so two nodes can never hand out the same seat. A request that failed or timed out is
1023
+ never sent again, since it may have reached the owner; its seat then frees itself when the reservation expires.
1024
+ - The directory is trusted server code. Authenticate the HTTP endpoints that call `list` and `reserve`.
1025
+
1026
+ ### Peer-to-peer host migration
1027
+
1028
+ `@margoengine/netcode/migrate` keeps a peer-to-peer game going when its host leaves. Every peer makes a
1029
+ `HostMigration` with the same schema, starting state and roster, over reliable links to every other peer. The host
1030
+ calls `confirm(state, frame)` at its checkpoints, which prepares and commits that state on every connected peer. When
1031
+ the host drops, the surviving peers pick the lowest id, restore the newest checkpoint they all hold, and resume from
1032
+ it; `handoff(id)` moves authority on purpose.
1033
+
1034
+ ```ts
1035
+ import { defineSchema, LoopbackNetwork, type Connection } from '@margoengine/netcode';
1036
+ import { HostMigration } from '@margoengine/netcode/migrate';
1037
+
1038
+ const schema = defineSchema({ types: { State: { score: 'uint' } } } as const);
1039
+ const network = new LoopbackNetwork({ latency: 10 });
1040
+ const [ab, ba] = network.pair(),
1041
+ [ac, ca] = network.pair(),
1042
+ [bc, cb] = network.pair();
1043
+ const peer = (local: number, peers: [number, Connection][]) =>
1044
+ new HostMigration({ schema, stateType: 'State', local, peers: new Map(peers), initial: { score: 0 } });
1045
+ const a = peer(1, [[2, ab], [3, ac]]),
1046
+ b = peer(2, [[1, ba], [3, bc]]),
1047
+ c = peer(3, [[1, ca], [2, cb]]);
1048
+
1049
+ const saved = a.confirm({ score: 9 }, 120); // the host checkpoints frame 120
1050
+ network.advance(5000);
1051
+ await saved;
1052
+ a.close(); // the host leaves
1053
+ network.advance(5000);
1054
+ const resumed = await b.waitForHost();
1055
+ console.log(resumed.host, resumed.frame, resumed.state.score, c.isHost); // 2 120 9 false
1056
+ b.close();
1057
+ c.close();
1058
+ ```
1059
+
1060
+ - Only the peer whose `isHost` is true may simulate and publish; others wait with `waitForHost()`. `confirmed` is the
1061
+ last locally committed checkpoint; await `confirm` before treating it as held by everyone.
1062
+ - Up to 64 peers; checkpoints up to `maxSnapshotBytes` (default 1 MiB, at most 16 MiB). Peers are trusted and the
1063
+ surviving mesh must stay connected: this is not consensus, so a split network or a lying peer needs your own
1064
+ membership and fencing. A peer cannot join a live session; start a new one.
1065
+
1066
+ ## Signalling for WebRTC
1067
+
1068
+ Two browsers cannot open a WebRTC link until they have swapped an offer, an answer and ICE candidates through something else. `@margoengine/netcode/signal` is that something: a small server that passes messages between the peers of a room, a client, and `PeerMesh`, which makes a link to every peer of the room. Once linked, the peers talk directly and the server carries nothing.
1069
+
1070
+ ```ts
1071
+ // Server and two peers' signalling in one file for the example; in a game the server runs on Node and each
1072
+ // peer in its own browser, where `new PeerMesh(room, ...)` then makes the links.
1073
+ import { LoopbackNetwork } from '@margoengine/netcode';
1074
+ import { SignalClient, SignalServer } from '@margoengine/netcode/signal';
1075
+
1076
+ const network = new LoopbackNetwork({ latency: 10 });
1077
+ const signals = new SignalServer({ maxPeers: 8 });
1078
+ network.listen().onconnection = (connection) => signals.accept(connection);
1079
+ const tick = setInterval(() => network.advance(10), 5);
1080
+
1081
+ const one = await SignalClient.join(network.connect(), 'lobby-7');
1082
+ const two = await SignalClient.join(network.connect(), 'lobby-7');
1083
+ console.log('two sees', [...two.peers], 'which is', one.id);
1084
+ one.onsignal = (from, data) => console.log('from', from, data);
1085
+ two.send(one.id, { hello: 'there' });
1086
+ await new Promise((resolve) => setTimeout(resolve, 100));
1087
+ clearInterval(tick);
1088
+ signals.close();
1089
+ ```
1090
+
1091
+ In the browser:
1092
+
1093
+ ```ts
1094
+ import { GameClient, type Game } from '@margoengine/netcode';
1095
+ import { PeerMesh, SignalClient } from '@margoengine/netcode/signal';
1096
+ import { openWebSocket } from '@margoengine/netcode/websocket';
1097
+
1098
+ export async function joinMesh(game: Game<unknown, unknown>, url: string) {
1099
+ const room = await SignalClient.join(await openWebSocket(url), 'lobby-7', { token: 'from your login' });
1100
+ return new PeerMesh(room, {
1101
+ configuration: { iceServers: [{ urls: 'stun:stun.example.com' }] }, // none means the same network only
1102
+ onconnection: (peer, connection) => void GameClient.join(game, connection, { input: () => ({}) }),
1103
+ onerror: (peer, error) => console.error(peer, error),
1104
+ });
1105
+ }
1106
+ ```
1107
+
1108
+ On Node, `listenWebSocket` gives the server its connections: `listener.onconnection = (connection) => signals.accept(connection)`.
1109
+
1110
+ - The joiner offers to the peers already there, so two peers never offer to each other, and each step with a peer waits for the one before it. A candidate found before the description went out waits for it.
1111
+ - `PeerMesh` takes over the client's `onsignal` and `onleft`; `onpeer` stays yours. `mesh.connections` holds each open `Connection`, ready for `GameClient`, `GameServer` or `RollbackSession`.
1112
+ - A link that is up lives on its own: it ends when its channels close or it fails, not when the peer leaves the room or the server goes. A link still being set up goes with the peer.
1113
+ - The server sets each message's sender itself, so a peer cannot pose as another, and a message never leaves its room. It keeps no history.
1114
+ - Server options, each with a default: `maxRooms` 1,024, `maxPeers` 16, `maxMessageBytes` 65,536, `messagesPerSecond` 100 with a `burst` of 200, `joinTimeout` 10,000 ms, and `authorize(room, token)`, default anyone with the room's name.
1115
+ - A room's name is not a secret unless `authorize` makes it one, and what a peer sends may be anything: `onsignal` is for you to check. `PeerMesh` sends what is not a description or candidate to `onerror`.
1116
+ - Run behind `wss://`: the server sees every description, which holds each peer's addresses.
1117
+
1118
+ ## One schema, generated code
1119
+
1120
+ `@margoengine/netcode/generate` turns a schema into a standalone TypeScript module: an interface per struct and
1121
+ `encode<Name>`, `decode<Name>`, `encode<Name>Delta`, `decode<Name>Delta` and `same<Name>` functions that write and check
1122
+ exactly the bytes `schema.encode` does, with no import at all (it runs in Node as is, since it uses only erasable
1123
+ syntax). Use it where loading the runtime schema compiler is not wanted, or as the reference for a generator in
1124
+ another language: `schema.json` is the normalized definition, and README "Wire format" says how each field is written.
1125
+ `@margoengine/netcode/generate-rust` reads the same JSON and writes a Rust module that produces the same bytes (below); the
1126
+ tests compare each generated module with the runtime codec on random values, deltas and corrupted input. Any struct name the schema takes works, Map and Uint8Array
1127
+ included; only a pair such as `Player` and `PlayerDelta` is refused with a TypeError, since both would define
1128
+ `encodePlayerDelta`.
1129
+
1130
+ ```ts
1131
+ import { defineSchema } from '@margoengine/netcode';
1132
+ import { generateTypeScript } from '@margoengine/netcode/generate';
1133
+
1134
+ const schema = defineSchema({ types: { Ping: { at: 'f64', from: { type: 'string', maxLength: 16 } } } });
1135
+ const source = generateTypeScript(schema, { source: 'ping schema' });
1136
+ console.log(source.length, 'characters; write it to ping.protocol.ts');
1137
+ console.log(JSON.stringify(schema.json)); // what the Rust generator reads
1138
+ ```
1139
+
1140
+ ### Rust
1141
+
1142
+ `generateRust(schema)` (or `generateRust(schema.json)`) writes one standalone Rust 2021 file for a Rust server or
1143
+ tool: no crate dependencies, Rust 1.82 or newer. Each struct becomes `Msg<Name>` with fields `f_<name>`; maps are
1144
+ `BTreeMap<u32, T>`, enums their `u32` wire index and optionals `Option<Box<T>>`. Each type has `encode`, `decode`,
1145
+ `encode_delta`, `decode_delta` and `same`, writing the bytes `schema.encode` writes, and the module carries the
1146
+ schema's `SCHEMA_HASH`, so a Rust room server and a TypeScript client agree or refuse to talk.
1147
+
1148
+ ```ts
1149
+ import { defineSchema } from '@margoengine/netcode';
1150
+ import { generateRust } from '@margoengine/netcode/generate-rust';
1151
+
1152
+ const schema = defineSchema({ types: { Ping: { at: 'f64', from: { type: 'string', maxLength: 16 } } } });
1153
+ const rust = generateRust(schema, { source: 'ping schema' });
1154
+ console.log(rust.includes('pub struct MsgPing'), 'write it to src/ping_protocol.rs');
1155
+ ```
1156
+
1157
+ - Decoding returns `margo_wire::Result`: limits are checked, and trailing bytes, invalid UTF-8, non-finite floats and
1158
+ malformed map masks are errors, never a partial value. Nesting past 256 codec calls is an error, so untrusted input
1159
+ cannot recurse without bound.
1160
+ - `f32` fields use Rust's `f32`; quantized fields decode to `f64`.
1161
+
1162
+ ## The arena demo
1163
+
1164
+ `examples/arena/` (in this package's folder, not in the published tarball) is a small multiplayer arena of boxes: the
1165
+ game definition the tests use (`game.js`), a Node server and a browser page that draws each player's own box predicted
1166
+ (solid) and the others interpolated (outlined). From the repository folder:
1167
+
1168
+ 1. Start the arena server: `node packages/netcode/examples/arena/server.mjs` (it prints the address it listens on).
1169
+ 2. In a second terminal, start the dev server: `npm run dev:examples`, and open
1170
+ `http://127.0.0.1:5173/packages/netcode/examples/arena/?server=ws://127.0.0.1:8787` (if Vite prints another port,
1171
+ use that one). Arrow keys or WASD move your box; a bot drives the second view.
1172
+
1173
+ Without `?server=` the page runs its own server in the page over a simulated network, with latency and loss sliders.
1174
+ Opened straight from disk (`file://`) the page cannot run modules and says so, with these commands.
1175
+ `tests/arena.test.js` runs both commands as written and checks the server accepts a client and the page is served.
1176
+
1177
+ ## Security
1178
+
1179
+ - **The server trusts nothing but inputs.** Clients never send state; the server applies only decoded inputs, through
1180
+ your `step`, so a client can move only as your rules allow. Validate game rules (cool-downs, ammunition, speed) in
1181
+ `step` or in `validateInput(input, player, state)`, which drops an input that returns false.
1182
+ - **Every byte is checked.** Envelopes and schema bytes are decoded with bounds on every count and length; anything
1183
+ that does not decode closes the connection with `CloseCode.protocol`. Fields outside their schema range cannot be
1184
+ represented at all.
1185
+ - **Rate limits.** A token bucket per client (`limits.messagesPerSecond`, default 120, `limits.burst`, default 60) and
1186
+ a size limit (`limits.maxMessageBytes`, default 4096); a client over either is closed with `CloseCode.rateLimit`.
1187
+ Inputs more than `maxInputAhead` ticks ahead (default 2 seconds) are dropped, so a client cannot queue a burst, and
1188
+ the server consumes at most one input per player per tick, so a client cannot speed up time.
1189
+ - **Join checks.** The hello names the envelope version and the schema hash; a mismatch closes with
1190
+ `CloseCode.mismatch`. `maxPlayers` (default 64) counts every accepted player once,
1191
+ including a hello received before the next simulation tick, and closes the next
1192
+ one with `CloseCode.full`. A disconnect frees its slot immediately. Silent clients close with
1193
+ `CloseCode.timeout` after `timeout` ms (default 10,000).
1194
+ - **Not covered here**: authentication (pass only connections you accepted, after your own login check), encryption
1195
+ (use `wss://` or WebRTC's DTLS), and denial of service at the network level (put the server behind a proxy).
1196
+
1197
+ ## Limits (honest)
1198
+
1199
+ - Prediction treats other players as idle (their inputs are not sent to other clients), so in a crowd most snapshots
1200
+ differ from the prediction and the client replays its unconfirmed ticks each time. That is correct but costs CPU in
1201
+ proportion to the lead (a few ticks) times the step's cost. Draw other players from `interpolated()`, not from
1202
+ `predicted`.
1203
+ - Corrections are applied at once to `client.predicted`. To draw them eased over a few frames use `CorrectionSmoother`.
1204
+ - Snapshots go to every client every `snapshotEvery` ticks, the whole state (or your `view` of it) as a delta; there
1205
+ is no priority or bandwidth budget per entity yet. Measured on the arena fixture (8 players, 4 crates): 99 bytes per
1206
+ snapshot on average.
1207
+ - `interpolated()` holds the newest snapshot when the next one is late; `Extrapolator` moves on instead.
1208
+ - A client more than 8 ticks off its target jumps instead of slewing; a client that falls more than 4 x `history`
1209
+ ticks behind skips ticks rather than replaying them.
1210
+ - Rollback keeps `maxRollback + 2` saved states (encoded bytes) and resimulates at most `maxRollback` frames per
1211
+ rollback; the cost of a rollback is that many calls of your `step`. Measured in the 4-peer test (50 ms latency,
1212
+ 20 ms jitter, 10% loss, 30 frames per second, input delay 2): 147 rollbacks in 581 frames, 185 frames resimulated,
1213
+ never more than 3 at once. All peers must use the same `inputDelay`; a mismatch shows up as a desync.
1214
+ - A physics world in rollback (`physicsGame`) saves its whole snapshot every frame and loads it every step: two copies of
1215
+ the world's memory a simulated frame (1.66 MB for the test's small world, whose memory holds room to grow), so its cost
1216
+ grows with the world's memory, not with what moves. The world must keep the same bodies, colliders and joints, and a
1217
+ world that grows its memory mid-session is refused. Send `snapshotDiff`s, not snapshots, when a world goes over the wire.
1218
+ - Rollback sessions over direct links are a full mesh (each peer sends to every other), sensible up to about 8 players. Past that use `@margoengine/netcode/relay`, at the cost of a second hop.
1219
+ - The WebSocket server has no compression extension (snapshots are small and already delta coded) and no TLS of its
1220
+ own (use a reverse proxy). The WebRTC transport is tested here with stand-in channels; signalling is not included.
1221
+ - Rooms send the state to each client at the patch rate as a delta against the last state that client got (reliable
1222
+ channel), so a room's cost grows with clients times state size. Held seats (`reconnectWindow`) and reserved seats
1223
+ (`LobbyRoom`) live in the memory of one server process; a restart loses them.
1224
+
1225
+ ## Wire format
1226
+
1227
+ Everything is little-endian. `varint` is unsigned LEB128 of at most 32 bits (5 bytes); a zigzag `int` maps 0, -1, 1,
1228
+ -2 ... to 0, 1, 2, 3 ... first.
1229
+
1230
+ | Field | Bytes |
1231
+ | --- | --- |
1232
+ | `u8` `u16` `u32` `i8` `i16` `i32` | 1, 2, 4 bytes (two's complement for the signed ones) |
1233
+ | `uint`, `int` | varint, zigzag varint |
1234
+ | `f32`, `f64` | IEEE 754, 4 or 8 bytes; NaN and infinities are refused |
1235
+ | `bool` | 1 byte, 0 or 1 |
1236
+ | `quantized` | `q = round((v - min) * ((2^bits - 2) / (max - min)))` in `ceil(bits / 8)` bytes; decoded `min + (max - min) * (q / (2^bits - 2))`; `q` above `2^bits - 2` is refused |
1237
+ | `string`, `bytes` | varint byte length (at most `maxLength`), then the bytes (UTF-8 for strings, checked) |
1238
+ | `enum` | varint index into `values` |
1239
+ | `array` | varint count (at most `maxLength`), then the items |
1240
+ | `optional` | 1 byte, 0 (absent) or 1, then the value |
1241
+ | `map` | varint count (at most `maxSize`), the ids ascending, each written as the gap after the previous minus one (the first as itself), then the values in that order |
1242
+ | struct | the fields in definition order |
1243
+
1244
+ A **delta** of a struct is one bit per field (`ceil(fields / 8)` bytes, bit `i & 7` of byte `i >> 3`, set when the field
1245
+ changed), then each changed field: as a delta when it is a struct or a map and the baseline has it, otherwise in full.
1246
+ A delta of a map is the removed ids (count, then gap-coded ids), then the added and changed ids (count, gap-coded), then
1247
+ each of their values: a delta against the baseline entry when the entry existed and is a struct, otherwise in full.
1248
+
1249
+ `schema.hash` is FNV-1a (32-bit) of the UTF-8 bytes of `JSON.stringify(schema.json)`, the normalized definition with
1250
+ every default written out; two ends speak the same format exactly when their hashes match.
1251
+
1252
+ **Envelope**: one byte of kind, then: 1 hello (varint version, u32 schema hash); 2 welcome (varint player, tick rate,
1253
+ tick, snapshot interval); 3 inputs (varint snapshot ack, first tick, count up to 32, then each input as varint length
1254
+ and schema bytes); 4 snapshot (varint tick, baseline tick or 0, newest input tick, missed ticks, then the state bytes);
1255
+ 5 ping (f64 client time); 6 pong (f64 client time, varint tick, f32 fraction of the next tick); 7 message (varint type
1256
+ index into `schema.names`, then its schema bytes). Snapshots, inputs, pings and pongs go unreliable; everything else
1257
+ reliable.
1258
+
1259
+ ## Voice chat and screen share
1260
+
1261
+ `@margoengine/netcode/media` adds microphone and screen tracks to the WebRTC links of a `PeerMesh`. Starting or stopping one renegotiates over the same signalling (the mesh runs the W3C "perfect negotiation" pattern: the peer with the higher room id is polite and gives way when both offer at once). A remote stream with video is a screen; one with only audio is a voice. Any number of peers may share a screen at once.
1262
+
1263
+ ```ts
1264
+ import type { PeerMesh } from '@margoengine/netcode/signal';
1265
+ import { MediaSession, type MediaSessionEvent } from '@margoengine/netcode/media';
1266
+
1267
+ export async function voice(mesh: PeerMesh, context: AudioContext) {
1268
+ const media = new MediaSession(mesh, {
1269
+ audioContext: context,
1270
+ pushToTalk: false, // true: closed until media.talk(true)
1271
+ // Optional: route each voice through your own graph, for example a PannerNode that follows the player.
1272
+ spatial: (peer, volume, ctx) => {
1273
+ const panner = ctx.createPanner();
1274
+ panner.connect(ctx.destination);
1275
+ return panner;
1276
+ },
1277
+ });
1278
+ media.addEventListener('speaking', (event) => {
1279
+ const { peer, speaking } = (event as MediaSessionEvent<'speaking'>).detail;
1280
+ console.log(peer, speaking ? 'talks' : 'is quiet');
1281
+ });
1282
+ await media.startVoice({ signal: AbortSignal.timeout(15_000) }); // echo cancellation, noise suppression, auto gain on
1283
+ media.setMuted(true);
1284
+ media.setVolume(3, 0.5); // peer 3, this end only
1285
+ media.mutePeer(4, true);
1286
+ await media.startScreenShare(); // getDisplayMedia; 'screenended' fires when the user uses the browser's stop button
1287
+ for await (const remote of media.events('remote')) console.log(remote.peer, remote.kind, remote.active);
1288
+ return media; // media.dispose() or `using` stops every track
1289
+ }
1290
+ ```
1291
+
1292
+ Options (defaults): `audio` microphone constraints (echo cancellation, noise suppression and automatic gain control on), `pushToTalk` (false), `speakingOn` (0.04 RMS), `speakingOff` (0.02), `speakingHangMs` (250), `pollMs` (50; 0 reads only on `poll()`), `audioContext`, `spatial`, `mediaDevices`, `now`. Speaking is an RMS level through an `AnalyserNode` with hysteresis (`SpeakingDetector` is exported for your own use). Remote streams are on `media.remotes.get(peer)` (`voice`, `screen`, `volume`, `muted`, `speaking`) for your own `<audio>` or `<video>` element.
1293
+
1294
+ ## Sources
1295
+
1296
+ Clean room, from public descriptions only: Glenn Fiedler's articles "Fix Your Timestep!", "Snapshot Compression",
1297
+ "Snapshot Interpolation", "Deterministic Lockstep" and "State Synchronization"; the GGPO documentation (Tony Cannon and
1298
+ others, ggpo.net) on rollback; Gabriel Gambetta's "Fast-Paced Multiplayer" series (prediction, reconciliation, entity
1299
+ interpolation); Yahn Bernier, "Latency Compensating Methods in Client/Server In-game Protocol Design and
1300
+ Optimization" (GDC 2001); Timothy Ford, "Overwatch Gameplay Architecture and Netcode" (GDC 2017); F. Cristian,
1301
+ "Probabilistic clock synchronization" (1989); the LEB128 and zigzag encodings as specified for DWARF and Protocol
1302
+ Buffers; FNV-1a as published by Fowler, Noll and Vo; the W3C WebTransport Candidate Recommendation, in part; for media, W3C WebRTC 1.0 (addTrack, removeTrack, negotiationneeded and the perfect negotiation example), W3C Media Capture and Streams (getUserMedia, audio constraints, track `enabled` and `ended`), W3C Screen Capture (getDisplayMedia) and the W3C Web Audio API (MediaStreamAudioSourceNode, AnalyserNode, GainNode). No library's source was read.
1303
+
1304
+ Apache-2.0. Optional, tree-shakable package; depends on `@margoengine/math` only (the physics entry is typed by shape and imports no physics code).
1305
+
1306
+ Build and unit tests: npm test --workspace @margoengine/netcode