@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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +1306 -3
- package/dist/client.d.ts +167 -0
- package/dist/clock.d.ts +29 -0
- package/dist/extrapolate.d.ts +42 -0
- package/dist/extrapolate.js +25 -0
- package/dist/game.d.ts +68 -0
- package/dist/generate-rust.d.ts +14 -0
- package/dist/generate-rust.js +184 -0
- package/dist/generate.d.ts +25 -0
- package/dist/generate.js +156 -0
- package/dist/hitboxes.d.ts +74 -0
- package/dist/hitboxes.js +124 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +457 -0
- package/dist/interest.d.ts +101 -0
- package/dist/interest.js +166 -0
- package/dist/interpolation-delay.d.ts +114 -0
- package/dist/interpolation-delay.js +79 -0
- package/dist/interpolation-fields.d.ts +117 -0
- package/dist/interpolation-fields.js +147 -0
- package/dist/interpolation-timeline.d.ts +100 -0
- package/dist/interpolation-timeline.js +122 -0
- package/dist/interpolation.d.ts +39 -0
- package/dist/interpolation.js +61 -0
- package/dist/lag.d.ts +62 -0
- package/dist/lobby.d.ts +77 -0
- package/dist/lobby.js +96 -0
- package/dist/loopback.d.ts +92 -0
- package/dist/media.d.ts +197 -0
- package/dist/media.js +274 -0
- package/dist/migrate.d.ts +113 -0
- package/dist/migrate.js +289 -0
- package/dist/node.d.ts +101 -0
- package/dist/node.js +166 -0
- package/dist/physics.d.ts +133 -0
- package/dist/physics.js +169 -0
- package/dist/presence.d.ts +156 -0
- package/dist/presence.js +226 -0
- package/dist/protocol-asi_qndb.js +122 -0
- package/dist/protocol.d.ts +75 -0
- package/dist/relay.d.ts +152 -0
- package/dist/relay.js +235 -0
- package/dist/rollback.d.ts +131 -0
- package/dist/rollback.js +194 -0
- package/dist/rooms.d.ts +366 -0
- package/dist/rooms.js +479 -0
- package/dist/schema-CMfqK4Gu.js +616 -0
- package/dist/schema.d.ts +263 -0
- package/dist/server-DAVzHcWW.js +203 -0
- package/dist/server.d.ts +147 -0
- package/dist/shared/bytes.d.ts +36 -0
- package/dist/signal.d.ts +156 -0
- package/dist/signal.js +261 -0
- package/dist/smoothing.d.ts +76 -0
- package/dist/smoothing.js +155 -0
- package/dist/transport-DeQodwyv.js +49 -0
- package/dist/transport.d.ts +76 -0
- package/dist/webrtc.d.ts +32 -0
- package/dist/webrtc.js +64 -0
- package/dist/websocket.d.ts +27 -0
- package/dist/websocket.js +42 -0
- package/dist/webtransport.d.ts +83 -0
- package/dist/webtransport.js +120 -0
- package/package.json +140 -6
package/dist/index.js
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
import { Timeline as e } from "./interpolation-timeline.js";
|
|
2
|
+
import { a as t, i as n, o as r, r as i } from "./schema-CMfqK4Gu.js";
|
|
3
|
+
import { i as a, r as o, t as s } from "./transport-DeQodwyv.js";
|
|
4
|
+
import { a as c, n as l, o as u, r as d, t as f } from "./protocol-asi_qndb.js";
|
|
5
|
+
import { t as p } from "./server-DAVzHcWW.js";
|
|
6
|
+
import { createRandom as m } from "@margoengine/math/mathutils";
|
|
7
|
+
//#region src/game.ts
|
|
8
|
+
function h(e) {
|
|
9
|
+
let { schema: t, state: n, input: r } = e;
|
|
10
|
+
for (let [e, i] of [["state", n], ["input", r]]) if (!t?.names?.includes(i)) throw TypeError(`Game ${e} type '${i}' is not in the schema; name one of its structs`);
|
|
11
|
+
if (typeof e.initial != "function" || typeof e.step != "function") throw TypeError("Game needs initial() and step(state, inputs, tick, dt) functions; add them");
|
|
12
|
+
let i = e.tickRate ?? 30;
|
|
13
|
+
if (!Number.isInteger(i) || i < 1 || i > 240) throw RangeError(`Game tickRate is ${i}; pass an integer from 1 to 240 ticks per second`);
|
|
14
|
+
let a = () => {};
|
|
15
|
+
return {
|
|
16
|
+
schema: t,
|
|
17
|
+
stateType: n,
|
|
18
|
+
inputType: r,
|
|
19
|
+
tickRate: i,
|
|
20
|
+
tickMs: 1e3 / i,
|
|
21
|
+
initial: e.initial,
|
|
22
|
+
step: e.step,
|
|
23
|
+
join: e.join ?? a,
|
|
24
|
+
leave: e.leave ?? a
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region src/loopback.ts
|
|
29
|
+
var g = (e, t, n, r) => {
|
|
30
|
+
let i = t ?? n;
|
|
31
|
+
if (typeof i != "number" || !Number.isFinite(i) || i < 0 || i > r) throw RangeError(`Loopback ${e} is ${i}; pass a number from 0 to ${r}`);
|
|
32
|
+
return i;
|
|
33
|
+
}, _ = (e, t) => {
|
|
34
|
+
let n = g("latency", e.latency, t?.latency ?? 0, 6e4);
|
|
35
|
+
return {
|
|
36
|
+
latency: n,
|
|
37
|
+
jitter: g("jitter", e.jitter, t?.jitter ?? 0, 6e4),
|
|
38
|
+
loss: g("loss", e.loss, t?.loss ?? 0, .99),
|
|
39
|
+
duplicate: g("duplicate", e.duplicate, t?.duplicate ?? 0, 1),
|
|
40
|
+
reorder: g("reorder", e.reorder, t?.reorder ?? 0, 1),
|
|
41
|
+
retransmit: g("retransmit", e.retransmit, t?.retransmit ?? 2 * n + 10, 6e4)
|
|
42
|
+
};
|
|
43
|
+
}, v = class {
|
|
44
|
+
constructor(e = {}) {
|
|
45
|
+
this.time = 0, this.stats = {
|
|
46
|
+
sent: 0,
|
|
47
|
+
delivered: 0,
|
|
48
|
+
lost: 0,
|
|
49
|
+
duplicated: 0,
|
|
50
|
+
resent: 0,
|
|
51
|
+
bytes: 0
|
|
52
|
+
}, this.queue = [], this.order = 0, this.listener = null, this.conditions = _(e), this.random = m(e.seed ?? 1);
|
|
53
|
+
}
|
|
54
|
+
listen() {
|
|
55
|
+
let e = {
|
|
56
|
+
closed: !1,
|
|
57
|
+
onconnection: null,
|
|
58
|
+
close() {
|
|
59
|
+
e.closed = !0;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
return this.listener = e, e;
|
|
63
|
+
}
|
|
64
|
+
connect(e = {}) {
|
|
65
|
+
let t = _(e, this.conditions), n = new y(this, t), r = new y(this, t);
|
|
66
|
+
n.peer = r, r.peer = n;
|
|
67
|
+
let i = this.listener;
|
|
68
|
+
return !i || i.closed ? this.schedule(this.time, () => n.close(1006, "no loopback listener")) : i.onconnection?.(r), n;
|
|
69
|
+
}
|
|
70
|
+
pair(e = {}) {
|
|
71
|
+
let t = _(e, this.conditions), n = new y(this, t), r = new y(this, t);
|
|
72
|
+
return n.peer = r, r.peer = n, [n, r];
|
|
73
|
+
}
|
|
74
|
+
advance(e) {
|
|
75
|
+
if (!Number.isFinite(e) || e < 0) throw RangeError(`Loopback advance(${e}); pass a finite ms of 0 or more`);
|
|
76
|
+
let t = this.time + e;
|
|
77
|
+
for (;;) {
|
|
78
|
+
let e = this.next(t);
|
|
79
|
+
if (!e) break;
|
|
80
|
+
this.time = Math.max(this.time, e.at), e.run();
|
|
81
|
+
}
|
|
82
|
+
this.time = t;
|
|
83
|
+
}
|
|
84
|
+
flush() {
|
|
85
|
+
for (; this.queue.length;) this.advance(Math.max(0, Math.max(...this.queue.map((e) => e.at)) - this.time));
|
|
86
|
+
}
|
|
87
|
+
next(e) {
|
|
88
|
+
let t = -1;
|
|
89
|
+
for (let n = 0; n < this.queue.length; n++) {
|
|
90
|
+
let r = this.queue[n];
|
|
91
|
+
r.at > e || (t < 0 || r.at < this.queue[t].at || r.at === this.queue[t].at && r.order < this.queue[t].order) && (t = n);
|
|
92
|
+
}
|
|
93
|
+
return t < 0 ? void 0 : this.queue.splice(t, 1)[0];
|
|
94
|
+
}
|
|
95
|
+
schedule(e, t) {
|
|
96
|
+
this.queue.push({
|
|
97
|
+
at: e,
|
|
98
|
+
order: this.order++,
|
|
99
|
+
run: t
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
roll() {
|
|
103
|
+
return this.random();
|
|
104
|
+
}
|
|
105
|
+
}, y = class {
|
|
106
|
+
constructor(e, t) {
|
|
107
|
+
this.network = e, this.link = t, this.open = !0, this.onmessage = null, this.onclose = null, this.reliableAt = 0;
|
|
108
|
+
}
|
|
109
|
+
send(e, t = "reliable") {
|
|
110
|
+
if (!this.open) return;
|
|
111
|
+
if (!(e instanceof Uint8Array)) throw TypeError("Loopback send needs a Uint8Array; pass the message bytes");
|
|
112
|
+
let n = this.network, r = this.link, i = n.stats, a = e.slice(), o = () => r.latency + r.jitter * n.roll();
|
|
113
|
+
i.sent++, i.bytes += e.length;
|
|
114
|
+
let s = (e) => n.schedule(e, () => {
|
|
115
|
+
this.peer.open && (i.delivered++, this.peer.onmessage?.(a, t));
|
|
116
|
+
});
|
|
117
|
+
if (t === "reliable") {
|
|
118
|
+
let e = n.time + o();
|
|
119
|
+
for (; n.roll() < r.loss;) i.resent++, e += r.retransmit;
|
|
120
|
+
this.reliableAt = Math.max(this.reliableAt, e), s(this.reliableAt);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
if (n.roll() < r.loss) {
|
|
124
|
+
i.lost++;
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
let c = n.time + o();
|
|
128
|
+
n.roll() < r.reorder && (c += 2 * (r.latency + 1) * n.roll()), s(c), n.roll() < r.duplicate && (i.duplicated++, s(n.time + o()));
|
|
129
|
+
}
|
|
130
|
+
close(e = 1e3, t = "") {
|
|
131
|
+
if (!this.open) return;
|
|
132
|
+
this.open = !1;
|
|
133
|
+
let n = this.peer;
|
|
134
|
+
this.onclose?.(e, t), this.network.schedule(Math.max(this.network.time + this.link.latency, this.reliableAt), () => {
|
|
135
|
+
n.open && (n.open = !1, n.onclose?.(e, t));
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
}, b = class {
|
|
139
|
+
constructor(e, t = 8) {
|
|
140
|
+
if (this.tickMs = e, this.window = t, this.samples = [], !(e > 0) || !Number.isFinite(e)) throw RangeError(`ClockSync tickMs is ${e}; pass ms > 0`);
|
|
141
|
+
if (!Number.isInteger(t) || t < 1) throw RangeError(`ClockSync window is ${t}; pass an integer of 1 or more`);
|
|
142
|
+
}
|
|
143
|
+
get synced() {
|
|
144
|
+
return this.samples.length > 0;
|
|
145
|
+
}
|
|
146
|
+
add(e, t, n, r) {
|
|
147
|
+
let i = t - e;
|
|
148
|
+
i >= 0 && Number.isFinite(i) && Number.isFinite(n) && Number.isFinite(r) && (this.samples.push({
|
|
149
|
+
rtt: i,
|
|
150
|
+
receivedAt: t,
|
|
151
|
+
tick: n + Math.min(Math.max(r, 0), 1)
|
|
152
|
+
}), this.samples.length > this.window && this.samples.shift());
|
|
153
|
+
}
|
|
154
|
+
best() {
|
|
155
|
+
let e;
|
|
156
|
+
for (let t of this.samples) (!e || t.rtt < e.rtt) && (e = t);
|
|
157
|
+
return e;
|
|
158
|
+
}
|
|
159
|
+
get rtt() {
|
|
160
|
+
return this.best()?.rtt ?? 0;
|
|
161
|
+
}
|
|
162
|
+
get jitter() {
|
|
163
|
+
if (!this.samples.length) return 0;
|
|
164
|
+
let e = Infinity, t = -Infinity;
|
|
165
|
+
for (let n of this.samples) e = Math.min(e, n.rtt), t = Math.max(t, n.rtt);
|
|
166
|
+
return (t - e) / 2;
|
|
167
|
+
}
|
|
168
|
+
serverTick(e) {
|
|
169
|
+
let t = this.best();
|
|
170
|
+
return t ? t.tick + (t.rtt / 2 + (e - t.receivedAt)) / this.tickMs : NaN;
|
|
171
|
+
}
|
|
172
|
+
}, x = class t {
|
|
173
|
+
constructor(t, n, r) {
|
|
174
|
+
if (this.game = t, this.connection = n, this.options = r, this.stats = {
|
|
175
|
+
snapshots: 0,
|
|
176
|
+
confirmed: 0,
|
|
177
|
+
mispredictions: 0,
|
|
178
|
+
replayed: 0,
|
|
179
|
+
ignored: 0,
|
|
180
|
+
rtt: 0,
|
|
181
|
+
missed: 0
|
|
182
|
+
}, this.player = 0, this.oncorrection = null, this.delay = 0, this.snapshotEvery = 1, this.predictedTick = 0, this.clockTick = NaN, this.lastUpdate = NaN, this.lastPing = -Infinity, this.renderTick = NaN, this.lastRender = NaN, this.extra = 0, this.extraSince = 0, this.serverMissed = 0, this.inputAck = 0, this.newest = 0, this.closed = !1, this.inputs = /* @__PURE__ */ new Map(), this.predictions = /* @__PURE__ */ new Map(), this.pings = /* @__PURE__ */ new Map(), this.ready = null, typeof r?.input != "function") throw TypeError("GameClient needs an input(tick) function; pass { input: (tick) => yourInput }");
|
|
183
|
+
if (this.now = r.now ?? (() => performance.now()), this.keep = r.history ?? 128, this.redundancy = r.redundancy ?? 8, this.buffer = r.inputBuffer ?? 1, this.pingEvery = r.pingInterval ?? 500, !Number.isInteger(this.keep) || this.keep < 8 || this.keep > 4096) throw RangeError(`GameClient history is ${this.keep}; pass an integer from 8 to 4096 ticks`);
|
|
184
|
+
if (!Number.isInteger(this.redundancy) || this.redundancy < 1 || this.redundancy > 32) throw RangeError(`GameClient redundancy is ${this.redundancy}; pass an integer from 1 to 32`);
|
|
185
|
+
if (!(this.buffer >= 0) || !(this.pingEvery > 0)) throw RangeError("GameClient needs inputBuffer >= 0 and pingInterval > 0; fix the options");
|
|
186
|
+
this.clock = new b(t.tickMs), this.snapshots = new e(this.keep);
|
|
187
|
+
let i = r.interpolationDelay;
|
|
188
|
+
if (typeof i == "object") {
|
|
189
|
+
if (typeof i?.observe != "function" || typeof i.renderTime != "function") throw TypeError("GameClient interpolationDelay needs a number of ticks or an AdaptiveDelay; fix the option");
|
|
190
|
+
i.reset(), this.viewClock = i;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
static join(e, n, r) {
|
|
194
|
+
let i = new t(e, n, r), a = r.signal;
|
|
195
|
+
return new Promise((t, c) => {
|
|
196
|
+
if (a?.aborted) return n.close(s.normal, "aborted"), c(a.reason);
|
|
197
|
+
let l = () => {
|
|
198
|
+
i.ready = null, i.close(), c(a?.reason);
|
|
199
|
+
};
|
|
200
|
+
a?.addEventListener("abort", l, { once: !0 }), i.ready = () => {
|
|
201
|
+
a?.removeEventListener("abort", l), t(i);
|
|
202
|
+
}, n.onmessage = (e) => i.receive(e), n.onclose = (e, t) => {
|
|
203
|
+
i.closed = !0, a?.removeEventListener("abort", l), i.ready && c(o("failed", `Game connection closed before joining (${e} ${t}); check the server`)), i.ready = null, r.onclose?.(e, t);
|
|
204
|
+
}, n.send(u({
|
|
205
|
+
kind: "hello",
|
|
206
|
+
version: 1,
|
|
207
|
+
schema: e.schema.hash
|
|
208
|
+
}));
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
get tick() {
|
|
212
|
+
return this.predictedTick;
|
|
213
|
+
}
|
|
214
|
+
get predicted() {
|
|
215
|
+
return this.predictedState;
|
|
216
|
+
}
|
|
217
|
+
get serverTick() {
|
|
218
|
+
return this.newest;
|
|
219
|
+
}
|
|
220
|
+
get authoritative() {
|
|
221
|
+
return this.snapshots.latest;
|
|
222
|
+
}
|
|
223
|
+
get previousSnapshot() {
|
|
224
|
+
let e = this.snapshots.previous;
|
|
225
|
+
if (e < 0) return;
|
|
226
|
+
let t = this.snapshots.times[e];
|
|
227
|
+
return {
|
|
228
|
+
tick: t,
|
|
229
|
+
state: this.snapshots.get(t)
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
get open() {
|
|
233
|
+
return !this.closed;
|
|
234
|
+
}
|
|
235
|
+
get viewTick() {
|
|
236
|
+
return this.renderTick;
|
|
237
|
+
}
|
|
238
|
+
ping(e) {
|
|
239
|
+
this.lastPing = e, this.pings.set(e, e), this.pings.size > 16 && this.pings.delete(this.pings.keys().next().value), this.connection.send(u({
|
|
240
|
+
kind: "ping",
|
|
241
|
+
time: e
|
|
242
|
+
}), "unreliable");
|
|
243
|
+
}
|
|
244
|
+
receive(e) {
|
|
245
|
+
if (this.closed) return;
|
|
246
|
+
let t;
|
|
247
|
+
try {
|
|
248
|
+
t = c(e);
|
|
249
|
+
} catch (e) {
|
|
250
|
+
this.connection.close(s.protocol, e.message.slice(0, 120));
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
let n = this.now(), r = this.game;
|
|
254
|
+
switch (t.kind) {
|
|
255
|
+
case "welcome":
|
|
256
|
+
if (this.player) break;
|
|
257
|
+
if (t.tickRate !== r.tickRate) {
|
|
258
|
+
this.connection.close(s.mismatch, "tick rate differs");
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
this.player = t.player, this.snapshotEvery = Math.max(1, t.snapshotEvery), this.delay = this.viewClock ? 0 : this.options.interpolationDelay ?? 2 * this.snapshotEvery, this.ping(n);
|
|
262
|
+
break;
|
|
263
|
+
case "pong": {
|
|
264
|
+
let e = this.pings.get(t.time);
|
|
265
|
+
if (e === void 0) break;
|
|
266
|
+
this.pings.delete(t.time), this.clock.add(e, n, t.tick, t.fraction), this.stats.rtt = this.clock.rtt;
|
|
267
|
+
break;
|
|
268
|
+
}
|
|
269
|
+
case "snapshot":
|
|
270
|
+
this.snapshot(t.tick, t.baseline, t.input, t.missed, t.data, n);
|
|
271
|
+
break;
|
|
272
|
+
case "message": {
|
|
273
|
+
let e = r.schema.names[t.type];
|
|
274
|
+
if (e === void 0) {
|
|
275
|
+
this.connection.close(s.protocol, "unknown message type");
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
this.options.onmessage?.(e, r.schema.decode(e, t.data));
|
|
279
|
+
break;
|
|
280
|
+
}
|
|
281
|
+
default:
|
|
282
|
+
this.connection.close(s.protocol, `unexpected ${t.kind}`);
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
if (this.ready && this.player && !this.clock.synced && n - this.lastPing >= this.pingEvery && this.ping(n), this.ready && this.player && this.clock.synced && this.predictedState !== void 0) {
|
|
286
|
+
let e = this.ready;
|
|
287
|
+
this.ready = null, this.lastUpdate = n, this.clockTick = Math.max(this.target(n), this.predictedTick);
|
|
288
|
+
for (let e = Math.floor(this.clockTick); this.predictedTick < e;) this.simulate(++this.predictedTick, void 0);
|
|
289
|
+
e();
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
snapshot(e, t, n, r, i, a) {
|
|
293
|
+
let o = this.game;
|
|
294
|
+
if (e <= this.newest) {
|
|
295
|
+
this.stats.ignored++;
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
let s = t ? this.snapshots.get(t) : void 0;
|
|
299
|
+
if (t && s === void 0) {
|
|
300
|
+
this.stats.ignored++;
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
let c = s === void 0 ? o.schema.decode(o.stateType, i) : o.schema.decodeDelta(o.stateType, i, s);
|
|
304
|
+
this.newest = e, this.snapshots.add(e, c), this.snapshots.dropThrough(e - this.keep), this.viewClock?.observe(e * o.tickMs / 1e3, a / 1e3), this.inputAck = Math.max(this.inputAck, n), this.stats.snapshots++, r > this.serverMissed ? ((this.serverMissed || this.extra) && (this.extra = Math.min(this.extra + 1, 10)), this.extraSince = a) : this.extra && a - this.extraSince > 1e4 && (this.extra--, this.extraSince = a), this.serverMissed = r, this.stats.missed = r, this.reconcile(e, c);
|
|
305
|
+
}
|
|
306
|
+
reconcile(e, t) {
|
|
307
|
+
let n = this.game, r = n.schema.encode(n.stateType, t), i = this.predictedState;
|
|
308
|
+
if (i === void 0 || e > this.predictedTick) {
|
|
309
|
+
this.predictedState = n.schema.decode(n.stateType, r), this.predictedTick = e, this.predictions.set(e, r), i !== void 0 && this.oncorrection?.(i, this.predictedState);
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
let a = this.predictions.get(e);
|
|
313
|
+
if (a && S(a, r)) this.stats.confirmed++;
|
|
314
|
+
else {
|
|
315
|
+
this.stats.mispredictions++, this.predictions.set(e, r), this.predictedState = n.schema.decode(n.stateType, r);
|
|
316
|
+
for (let t = e + 1; t <= this.predictedTick; t++) this.simulate(t, this.inputs.get(t)), this.stats.replayed++;
|
|
317
|
+
this.oncorrection?.(i, this.predictedState);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
simulate(e, t) {
|
|
321
|
+
let n = this.game, r = /* @__PURE__ */ new Map();
|
|
322
|
+
t !== void 0 && r.set(this.player, t), n.step(this.predictedState, r, e, 1 / n.tickRate);
|
|
323
|
+
let i = n.schema.encode(n.stateType, this.predictedState);
|
|
324
|
+
this.predictedState = n.schema.decode(n.stateType, i), this.predictions.set(e, i), this.predictions.delete(e - this.keep);
|
|
325
|
+
}
|
|
326
|
+
target(e) {
|
|
327
|
+
let t = this.game.tickMs;
|
|
328
|
+
return this.clock.serverTick(e) + (this.clock.rtt / 2 + 2 * this.clock.jitter) / t + this.buffer + this.extra;
|
|
329
|
+
}
|
|
330
|
+
update() {
|
|
331
|
+
if (this.closed) return;
|
|
332
|
+
if (Number.isNaN(this.clockTick)) throw o("state", "GameClient is not joined; await GameClient.join first");
|
|
333
|
+
let e = this.now(), t = Math.max(0, e - this.lastUpdate) / this.game.tickMs, n = this.target(e) - this.clockTick;
|
|
334
|
+
this.lastUpdate = e, Math.abs(n) > 8 ? this.clockTick += n : this.clockTick += t * Math.min(1.25, Math.max(.75, 1 + .05 * n));
|
|
335
|
+
let r = Math.floor(this.clockTick);
|
|
336
|
+
r - this.predictedTick > 4 * this.keep && (this.predictedTick = r - this.keep);
|
|
337
|
+
let i = !1;
|
|
338
|
+
for (; this.predictedTick < r;) {
|
|
339
|
+
let e = this.predictedTick + 1, t = this.options.input(e), n = this.game.schema.decode(this.game.inputType, this.game.schema.encode(this.game.inputType, t));
|
|
340
|
+
this.inputs.set(e, n), this.inputs.delete(e - 2 * this.keep), this.simulate(e, n), this.predictedTick = e, i = !0;
|
|
341
|
+
}
|
|
342
|
+
i && this.sendInputs(), e - this.lastPing >= this.pingEvery && this.ping(e);
|
|
343
|
+
}
|
|
344
|
+
sendInputs() {
|
|
345
|
+
let e = this.game, t = this.predictedTick, n = [], r = Math.max(this.inputAck + 1, t - this.redundancy + 1, 1);
|
|
346
|
+
for (; r <= t && !this.inputs.has(r);) r++;
|
|
347
|
+
for (let i = r; i <= t; i++) {
|
|
348
|
+
let t = this.inputs.get(i);
|
|
349
|
+
if (t === void 0) break;
|
|
350
|
+
n.push(e.schema.encode(e.inputType, t));
|
|
351
|
+
}
|
|
352
|
+
n.length && this.connection.send(u({
|
|
353
|
+
kind: "inputs",
|
|
354
|
+
ack: this.newest,
|
|
355
|
+
first: r,
|
|
356
|
+
inputs: n
|
|
357
|
+
}), "unreliable");
|
|
358
|
+
}
|
|
359
|
+
interpolated() {
|
|
360
|
+
let e = this.game.tickMs, t = this.now(), n = this.snapshots;
|
|
361
|
+
if (this.viewClock) this.renderTick = this.viewClock.renderTime(t / 1e3) * 1e3 / e;
|
|
362
|
+
else {
|
|
363
|
+
let n = this.clock.serverTick(t) - (this.clock.rtt / 2 + 2 * this.clock.jitter) / e - this.delay, r = n - this.renderTick;
|
|
364
|
+
Number.isNaN(r) || Math.abs(r) > 4 ? this.renderTick = n : this.renderTick += Math.max(0, t - this.lastRender) / e * Math.min(1.1, Math.max(.9, 1 + .1 * r)), this.lastRender = t;
|
|
365
|
+
}
|
|
366
|
+
return n.locate(this.renderTick) ? n.a === n.b ? n.from : this.game.schema.interpolate(this.game.stateType, n.from, n.to, n.u) : this.predictedState;
|
|
367
|
+
}
|
|
368
|
+
send(e, t) {
|
|
369
|
+
let n = this.game.schema.names.indexOf(e);
|
|
370
|
+
if (n < 0) throw TypeError(`Schema has no type '${e}'; send one of ${this.game.schema.names.join(", ")}`);
|
|
371
|
+
this.connection.send(u({
|
|
372
|
+
kind: "message",
|
|
373
|
+
type: n,
|
|
374
|
+
data: this.game.schema.encode(e, t)
|
|
375
|
+
}), "reliable");
|
|
376
|
+
}
|
|
377
|
+
close() {
|
|
378
|
+
this.closed || (this.closed = !0, this.connection.close(s.normal, "left"));
|
|
379
|
+
}
|
|
380
|
+
[Symbol.dispose]() {
|
|
381
|
+
this.close();
|
|
382
|
+
}
|
|
383
|
+
}, S = (e, t) => {
|
|
384
|
+
if (e.length !== t.length) return !1;
|
|
385
|
+
for (let n = 0; n < e.length; n++) if (e[n] !== t[n]) return !1;
|
|
386
|
+
return !0;
|
|
387
|
+
}, C = class {
|
|
388
|
+
constructor({ history: t = 32 } = {}) {
|
|
389
|
+
if (!Number.isInteger(t) || t < 2 || t > 4096) throw RangeError(`LagCompensation history is ${t}; pass an integer from 2 to 4096 ticks`);
|
|
390
|
+
this.history = t, this.frames = new e(t);
|
|
391
|
+
}
|
|
392
|
+
get range() {
|
|
393
|
+
let e = this.frames;
|
|
394
|
+
return e.count ? [e.oldest, e.newest] : void 0;
|
|
395
|
+
}
|
|
396
|
+
record(e, t) {
|
|
397
|
+
if (!Number.isFinite(e)) throw RangeError(`LagCompensation tick is ${e}; pass a finite tick`);
|
|
398
|
+
let n = this.frames;
|
|
399
|
+
if (e < n.newest) throw RangeError(`LagCompensation tick ${e} is older than ${n.newest}; record ticks in order`);
|
|
400
|
+
let r = /* @__PURE__ */ new Map();
|
|
401
|
+
for (let [e, n] of t) {
|
|
402
|
+
if (!n || !Array.isArray(n.position) || typeof n.radius != "number") throw TypeError("LagCompensation shapes need { position: [x, y] or [x, y, z], radius }; pass that shape");
|
|
403
|
+
if (n.position.length < 2 || n.position.length > 3 || !n.position.every(Number.isFinite)) throw RangeError(`LagCompensation shape ${e} needs 2 or 3 finite coordinates; fix its position`);
|
|
404
|
+
if (!(n.radius >= 0)) throw RangeError(`LagCompensation shape ${e} radius is ${n.radius}; use 0 or more`);
|
|
405
|
+
r.set(e, {
|
|
406
|
+
position: [...n.position],
|
|
407
|
+
radius: n.radius
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
n.add(e, r) || n.replace(e, r);
|
|
411
|
+
}
|
|
412
|
+
at(e) {
|
|
413
|
+
let t = /* @__PURE__ */ new Map(), n = this.frames;
|
|
414
|
+
if (!Number.isFinite(e) || !n.locate(e)) return t;
|
|
415
|
+
if (n.a === n.b) return new Map(n.from);
|
|
416
|
+
let r = n.from, i = n.to, a = n.u;
|
|
417
|
+
for (let [e, n] of i) {
|
|
418
|
+
let i = r.get(e);
|
|
419
|
+
!i || i.position.length !== n.position.length ? t.set(e, a < .5 && i ? i : n) : t.set(e, {
|
|
420
|
+
position: n.position.map((e, t) => i.position[t] + (e - i.position[t]) * a),
|
|
421
|
+
radius: i.radius + (n.radius - i.radius) * a
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
for (let [e, n] of r) !t.has(e) && a < .5 && t.set(e, n);
|
|
425
|
+
return t;
|
|
426
|
+
}
|
|
427
|
+
raycast(e, t, n, { maxDistance: r = Infinity, ignore: i } = {}) {
|
|
428
|
+
let a = t.length;
|
|
429
|
+
if (a !== 2 && a !== 3 || n.length !== a) throw RangeError("LagCompensation raycast needs origin and direction of 2 or 3 numbers each; fix them");
|
|
430
|
+
let o = 0;
|
|
431
|
+
for (let e = 0; e < a; e++) o += n[e] * n[e];
|
|
432
|
+
if (!(o > 0)) throw RangeError("LagCompensation raycast direction is zero; pass a direction");
|
|
433
|
+
let s = (e) => typeof i == "number" ? e === i : i?.has(e) === !0, c;
|
|
434
|
+
for (let [i, l] of this.at(e)) {
|
|
435
|
+
if (s(i) || l.position.length !== a) continue;
|
|
436
|
+
let e = 0, u = 0;
|
|
437
|
+
for (let r = 0; r < a; r++) {
|
|
438
|
+
let i = t[r] - l.position[r];
|
|
439
|
+
e += i * n[r], u += i * i;
|
|
440
|
+
}
|
|
441
|
+
let d = u - l.radius * l.radius, f = e * e - o * d;
|
|
442
|
+
if (f < 0) continue;
|
|
443
|
+
let p = (-e - Math.sqrt(f)) / o;
|
|
444
|
+
p < 0 && (p = d <= 0 ? 0 : (-e + Math.sqrt(f)) / o), !(p < 0 || p > r || c && p >= c.distance) && (c = {
|
|
445
|
+
id: i,
|
|
446
|
+
distance: p,
|
|
447
|
+
point: t.map((e, t) => e + n[t] * p)
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
return c;
|
|
451
|
+
}
|
|
452
|
+
clear() {
|
|
453
|
+
this.frames.clear();
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
//#endregion
|
|
457
|
+
export { b as ClockSync, s as CloseCode, f as ENVELOPE_VERSION, x as GameClient, p as GameServer, C as LagCompensation, v as LoopbackNetwork, l as MAX_INPUTS_PER_MESSAGE, d as MAX_INPUT_BYTES, c as decodeEnvelope, h as defineGame, i as defineSchema, n as dequantize, u as encodeEnvelope, t as fnv1a, a as messages, r as quantize };
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { Game } from './game.js';
|
|
2
|
+
/** How one map of the state is shared out. `Value` is the type of the map's entries. */
|
|
3
|
+
export interface InterestCollection<Value = any> {
|
|
4
|
+
/** Where an entity is: [x, y] or [x, y, z], the same length for every entity. */
|
|
5
|
+
position(value: Value, id: number): ArrayLike<number>;
|
|
6
|
+
/**
|
|
7
|
+
* What is added to the entity's accumulator on each snapshot it waits, 0 or more: bigger goes more often. Default
|
|
8
|
+
* `radius / distance`, from 1 at the edge up to 16 close by.
|
|
9
|
+
*/
|
|
10
|
+
priority?(value: Value, id: number, player: number, distance: number): number;
|
|
11
|
+
/** Return true to send the entity at any distance: team mates, objectives, a boss. */
|
|
12
|
+
always?(value: Value, id: number, player: number): boolean;
|
|
13
|
+
/** Return false to hide an entity inside the circle: behind a wall, stealthed. Runs for each one in the circle. */
|
|
14
|
+
visible?(value: Value, id: number, player: number, distance: number): boolean;
|
|
15
|
+
}
|
|
16
|
+
/** Options of {@link InterestManager}. */
|
|
17
|
+
export interface InterestOptions<State> {
|
|
18
|
+
/** The maps of the state to manage, by field name; any other field goes to every client whole. */
|
|
19
|
+
collections: {
|
|
20
|
+
readonly [field: string]: InterestCollection;
|
|
21
|
+
};
|
|
22
|
+
/** Radius of the area of interest around the player, in world units. */
|
|
23
|
+
radius: number;
|
|
24
|
+
/** An entity in the area stays until it is this far away, so one on the edge does not flicker (default radius x 1.1). */
|
|
25
|
+
leaveRadius?: number;
|
|
26
|
+
/** Size of a grid cell of the index (default `radius`). It changes the speed, never the result. */
|
|
27
|
+
cell?: number;
|
|
28
|
+
/**
|
|
29
|
+
* Most bytes of one snapshot message, or a function of the player (default no limit). For a rate, pass bytes per
|
|
30
|
+
* second divided by snapshots per second. Read on every snapshot, so a function can follow the link as it changes.
|
|
31
|
+
*/
|
|
32
|
+
budget?: number | ((player: number) => number);
|
|
33
|
+
/** The id of the player's own entity, always sent and never held back (default the player id). */
|
|
34
|
+
self?(player: number): number;
|
|
35
|
+
/** The centre of the player's area: a camera, say (default the position of its own entity). */
|
|
36
|
+
focus?(state: State, player: number): ArrayLike<number> | undefined;
|
|
37
|
+
}
|
|
38
|
+
/** What {@link InterestManager.stats} reports of a player's newest snapshot. */
|
|
39
|
+
export interface InterestStats {
|
|
40
|
+
/** Entities in the area of interest. */
|
|
41
|
+
inScope: number;
|
|
42
|
+
/** Entities written with their newest value. */
|
|
43
|
+
sent: number;
|
|
44
|
+
/** Entities with something new that the budget held back; their accumulators grew. */
|
|
45
|
+
deferred: number;
|
|
46
|
+
/** Entities the client is told to drop. */
|
|
47
|
+
removed: number;
|
|
48
|
+
/** The most bytes the snapshot message can take: never less than the real size. */
|
|
49
|
+
bytes: number;
|
|
50
|
+
/** Bytes over the budget: the part of the state that always goes (own entity, other fields) did not fit. */
|
|
51
|
+
over: number;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Picks what each client of a `GameServer` sees. Pass {@link InterestManager.view} as the server's `view`.
|
|
55
|
+
*
|
|
56
|
+
* An entity the budget holds back keeps the value the client last got, so it stays on screen and catches up in its
|
|
57
|
+
* turn. A value sent but not yet acknowledged is repeated until it is, because a snapshot is a delta against what the
|
|
58
|
+
* client confirmed; that is also what makes loss harmless.
|
|
59
|
+
*
|
|
60
|
+
* @example
|
|
61
|
+
* ```ts
|
|
62
|
+
* const interest = new InterestManager(game, {
|
|
63
|
+
* collections: { boxes: { position: (box) => [box.x, box.y] } },
|
|
64
|
+
* radius: 50,
|
|
65
|
+
* budget: 1200,
|
|
66
|
+
* });
|
|
67
|
+
* const server = new GameServer(game, { view: interest.view });
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
export declare class InterestManager<State, Input = unknown> {
|
|
71
|
+
readonly game: Game<State, Input>;
|
|
72
|
+
private readonly options;
|
|
73
|
+
private readonly managed;
|
|
74
|
+
private readonly viewers;
|
|
75
|
+
private readonly radius;
|
|
76
|
+
private readonly leave;
|
|
77
|
+
private readonly cell;
|
|
78
|
+
private indexed;
|
|
79
|
+
private round;
|
|
80
|
+
/**
|
|
81
|
+
* @throws RangeError for a radius, leaveRadius, cell or budget out of range.
|
|
82
|
+
* @throws TypeError for a collection that is not a map of structs at the top of the state.
|
|
83
|
+
*/
|
|
84
|
+
constructor(game: Game<State, Input>, options: InterestOptions<State>);
|
|
85
|
+
/** What the newest snapshot of `player` held, undefined before its first or after it left. */
|
|
86
|
+
stats(player: number): Readonly<InterestStats> | undefined;
|
|
87
|
+
private cellOf;
|
|
88
|
+
private index;
|
|
89
|
+
/** Entity id to distance for everything of `m` the player has in scope. */
|
|
90
|
+
private scope;
|
|
91
|
+
private bytes;
|
|
92
|
+
private origin;
|
|
93
|
+
/**
|
|
94
|
+
* The state `player` may see, for the server's `view`. `baseline` is what the client confirmed, which the server
|
|
95
|
+
* passes; a snapshot in full (no baseline) is held to the same budget.
|
|
96
|
+
* @throws RangeError for a budget or priority function that returns something out of range.
|
|
97
|
+
*/
|
|
98
|
+
readonly view: (state: State, player: number, baseline?: State) => State;
|
|
99
|
+
/** Forgets every player and the index. */
|
|
100
|
+
clear(): void;
|
|
101
|
+
}
|