@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/generate.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
//#region src/generate.ts
|
|
2
|
+
var e = {
|
|
3
|
+
u8: [
|
|
4
|
+
0,
|
|
5
|
+
255,
|
|
6
|
+
"w.u8(v)",
|
|
7
|
+
"r.u8()"
|
|
8
|
+
],
|
|
9
|
+
u16: [
|
|
10
|
+
0,
|
|
11
|
+
65535,
|
|
12
|
+
"w.u16(v)",
|
|
13
|
+
"r.u16()"
|
|
14
|
+
],
|
|
15
|
+
u32: [
|
|
16
|
+
0,
|
|
17
|
+
2 ** 32 - 1,
|
|
18
|
+
"w.u32(v)",
|
|
19
|
+
"r.u32()"
|
|
20
|
+
],
|
|
21
|
+
i8: [
|
|
22
|
+
-128,
|
|
23
|
+
127,
|
|
24
|
+
"w.u8(v & 255)",
|
|
25
|
+
"(r.u8() << 24) >> 24"
|
|
26
|
+
],
|
|
27
|
+
i16: [
|
|
28
|
+
-32768,
|
|
29
|
+
32767,
|
|
30
|
+
"w.u16(v & 65535)",
|
|
31
|
+
"(r.u16() << 16) >> 16"
|
|
32
|
+
],
|
|
33
|
+
i32: [
|
|
34
|
+
-(2 ** 31),
|
|
35
|
+
2 ** 31 - 1,
|
|
36
|
+
"w.u32(v >>> 0)",
|
|
37
|
+
"r.u32() | 0"
|
|
38
|
+
],
|
|
39
|
+
uint: [
|
|
40
|
+
0,
|
|
41
|
+
2 ** 32 - 1,
|
|
42
|
+
"w.varint(v)",
|
|
43
|
+
"r.varint()"
|
|
44
|
+
],
|
|
45
|
+
int: [
|
|
46
|
+
-(2 ** 31),
|
|
47
|
+
2 ** 31 - 1,
|
|
48
|
+
"w.varint(v < 0 ? -2 * v - 1 : 2 * v)",
|
|
49
|
+
"unzigzag(r.varint())"
|
|
50
|
+
]
|
|
51
|
+
}, t = "const utf8 = new TextEncoder(),\n text = new TextDecoder('utf-8', { fatal: true });\nconst unzigzag = (z: number): number => (z % 2 ? -(z + 1) / 2 : z / 2);\nclass Wire_Writer {\n bytes = new Uint8Array(64);\n view = new DataView(this.bytes.buffer);\n at = 0;\n room(n: number): void {\n if (this.at + n <= this.bytes.length) return;\n const bytes = new Uint8Array(Math.max(2 * this.bytes.length, this.at + n));\n bytes.set(this.bytes);\n this.bytes = bytes;\n this.view = new DataView(bytes.buffer);\n }\n u8(v: number): void {\n this.room(1);\n this.bytes[this.at++] = v;\n }\n u16(v: number): void {\n this.room(2);\n this.view.setUint16(this.at, v, true);\n this.at += 2;\n }\n u32(v: number): void {\n this.room(4);\n this.view.setUint32(this.at, v, true);\n this.at += 4;\n }\n f32(v: number): void {\n this.room(4);\n this.view.setFloat32(this.at, v, true);\n this.at += 4;\n }\n f64(v: number): void {\n this.room(8);\n this.view.setFloat64(this.at, v, true);\n this.at += 8;\n }\n varint(v: number): void {\n this.room(5);\n for (; v > 127; v >>>= 7) this.bytes[this.at++] = (v & 127) | 128;\n this.bytes[this.at++] = v;\n }\n raw(b: globalThis.Uint8Array): void {\n this.room(b.length);\n this.bytes.set(b, this.at);\n this.at += b.length;\n }\n done(): globalThis.Uint8Array {\n return this.bytes.slice(0, this.at);\n }\n}\nclass Wire_Reader {\n at = 0;\n bytes: globalThis.Uint8Array;\n view: globalThis.DataView;\n constructor(bytes: globalThis.Uint8Array) {\n this.bytes = bytes;\n this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n }\n fail(problem: string): globalThis.RangeError {\n return new RangeError(`Schema bytes ${problem}; pass bytes the matching encoder returned`);\n }\n need(n: number): void {\n if (this.at + n > this.bytes.length) throw this.fail(`are truncated at byte ${this.at} of ${this.bytes.length}`);\n }\n u8(): number {\n this.need(1);\n return this.bytes[this.at++];\n }\n u16(): number {\n this.need(2);\n this.at += 2;\n return this.view.getUint16(this.at - 2, true);\n }\n u32(): number {\n this.need(4);\n this.at += 4;\n return this.view.getUint32(this.at - 4, true);\n }\n finite(v: number): number {\n if (!Number.isFinite(v)) throw this.fail(`hold a non-finite number at byte ${this.at}`);\n return v;\n }\n f32(): number {\n this.need(4);\n this.at += 4;\n return this.finite(this.view.getFloat32(this.at - 4, true));\n }\n f64(): number {\n this.need(8);\n this.at += 8;\n return this.finite(this.view.getFloat64(this.at - 8, true));\n }\n varint(): number {\n let value = 0,\n scale = 1;\n for (let n = 0; ; n++, scale *= 128) {\n this.need(1);\n const b = this.bytes[this.at++];\n if (n === 4 && b > 15) throw this.fail(`hold a varint wider than 32 bits at byte ${this.at - 1}`);\n value += (b & 127) * scale;\n if (b < 128) return value;\n }\n }\n count(max: number): number {\n const n = this.varint();\n if (n > max) throw this.fail(`hold a count of ${n}, over its limit of ${max}`);\n if (n > this.bytes.length - this.at) this.need(n);\n return n;\n }\n ids(n: number, out: number[]): void {\n for (let i = 0, last = -1; i < n; i++) {\n const id = last + 1 + this.varint();\n if (id > 4294967295) throw this.fail(`hold an entity id over 2^32 - 1 at byte ${this.at}`);\n out.push((last = id));\n }\n }\n end(): void {\n if (this.at !== this.bytes.length) throw this.fail(`have ${this.bytes.length - this.at} bytes past the end`);\n }\n}\nconst writeIds = (w: Wire_Writer, list: number[]): void => {\n for (let i = 0, last = -1; i < list.length; last = list[i++]) w.varint(list[i] - last - 1);\n};\nconst integer = (p: string, v: unknown, min: number, max: number): number => {\n if (typeof v !== 'number') throw new TypeError(`${p} must be a number`);\n if (!Number.isInteger(v) || v < min || v > max)\n throw new RangeError(`${p} is ${v}, not an integer from ${min} to ${max}; pass a whole number in that range`);\n return v;\n};\nconst number = (p: string, v: unknown): number => {\n if (typeof v !== 'number') throw new TypeError(`${p} must be a number`);\n return v;\n};\nconst sameBytes = (a: globalThis.Uint8Array, b: globalThis.Uint8Array): boolean => a.length === b.length && a.every((v, i) => v === b[i]);\n", n = (e) => e.replace(/[^A-Za-z0-9]/g, "_"), r = (e) => Object.is(e, -0) ? "-0" : String(e);
|
|
52
|
+
function i(i, a = {}) {
|
|
53
|
+
let o = i?.json, s = i?.hash;
|
|
54
|
+
if (!o?.types || typeof s != "number") throw TypeError("generateTypeScript needs a schema from defineSchema; pass defineSchema({ types })");
|
|
55
|
+
for (let e of Object.keys(o.types)) if (e.endsWith("Delta") && o.types[e.slice(0, -5)]) throw TypeError(`generateTypeScript: structs ${e.slice(0, -5)} and ${e} would both define encode${e}; rename one`);
|
|
56
|
+
let c = [], l = [], u = (e) => {
|
|
57
|
+
switch (e.type) {
|
|
58
|
+
case "bool": return "boolean";
|
|
59
|
+
case "string": return "string";
|
|
60
|
+
case "bytes": return "globalThis.Uint8Array";
|
|
61
|
+
case "enum": return e.values.map((e) => JSON.stringify(e)).join(" | ");
|
|
62
|
+
case "array": return `${u(e.of).includes("|") ? `(${u(e.of)})` : u(e.of)}[]`;
|
|
63
|
+
case "optional": return u(e.of);
|
|
64
|
+
case "map": return `globalThis.Map<number, ${u(e.of)}>`;
|
|
65
|
+
case "struct": return e.name;
|
|
66
|
+
default: return "number";
|
|
67
|
+
}
|
|
68
|
+
}, d = /* @__PURE__ */ new Set(), f = (t, n) => {
|
|
69
|
+
if (n.type === "struct") return {
|
|
70
|
+
w: `w_${n.name}`,
|
|
71
|
+
r: `r_${n.name}`,
|
|
72
|
+
s: `same${n.name}`,
|
|
73
|
+
dw: `dw_${n.name}`,
|
|
74
|
+
dr: `dr_${n.name}`
|
|
75
|
+
};
|
|
76
|
+
let i = {
|
|
77
|
+
w: `w_${t}`,
|
|
78
|
+
r: `r_${t}`,
|
|
79
|
+
s: `s_${t}`
|
|
80
|
+
};
|
|
81
|
+
if (n.type === "map" && Object.assign(i, {
|
|
82
|
+
dw: `dw_${t}`,
|
|
83
|
+
dr: `dr_${t}`
|
|
84
|
+
}), d.has(t)) return i;
|
|
85
|
+
d.add(t);
|
|
86
|
+
let a = u(n), o = (e, t, n, r) => l.push(`function ${e}(${t}): ${n} {\n${r}\n}`);
|
|
87
|
+
switch (n.type) {
|
|
88
|
+
case "bool":
|
|
89
|
+
o(i.w, "w: Wire_Writer, v: boolean, p: string", "void", " if (typeof v !== 'boolean') throw new TypeError(`${p} must be a boolean`);\n w.u8(v ? 1 : 0);"), o(i.r, "r: Wire_Reader", "boolean", " const b = r.u8();\n if (b > 1) throw r.fail(`hold a boolean byte of ${b} at byte ${r.at - 1}`);\n return b === 1;"), o(i.s, "a: boolean, b: boolean", "boolean", " return a === b;");
|
|
90
|
+
break;
|
|
91
|
+
case "f32":
|
|
92
|
+
o(i.w, "w: Wire_Writer, v: number, p: string", "void", " if (!Number.isFinite(Math.fround(number(p, v)))) throw new RangeError(`${p} is ${v}, not a finite 32-bit float; pass a finite number`);\n w.f32(v);"), o(i.r, "r: Wire_Reader", "number", " return r.f32();"), o(i.s, "a: number, b: number", "boolean", " return Math.fround(a) === Math.fround(b);");
|
|
93
|
+
break;
|
|
94
|
+
case "f64":
|
|
95
|
+
o(i.w, "w: Wire_Writer, v: number, p: string", "void", " if (!Number.isFinite(number(p, v))) throw new RangeError(`${p} is ${v}, not a finite number; pass a finite number`);\n w.f64(v);"), o(i.r, "r: Wire_Reader", "number", " return r.f64();"), o(i.s, "a: number, b: number", "boolean", " return a === b;");
|
|
96
|
+
break;
|
|
97
|
+
case "quantized": {
|
|
98
|
+
let e = 2 ** n.bits - 2, a = Math.ceil(n.bits / 8), s = e / (n.max - n.min), c = n.max - n.min, l = `Math.round((v - ${r(n.min)}) * ${r(s)})`;
|
|
99
|
+
o(`q_${t}`, "v: number", "number", ` return ${l};`), o(i.w, "w: Wire_Writer, v: number, p: string", "void", ` const x = number(p, v);\n if (!(x >= ${r(n.min)} && x <= ${r(n.max)})) throw new RangeError(\`\${p} is \${v}, outside its quantized range ${n.min}..${n.max}; widen the range\`);\n const n = q_${t}(x);\n for (let i = 0; i < ${a}; i++) w.u8(Math.floor(n / 2 ** (8 * i)) & 255);`), o(i.r, "r: Wire_Reader", "number", ` let n = 0;\n for (let i = 0; i < ${a}; i++) n += r.u8() * 2 ** (8 * i);\n if (n > ${e}) throw r.fail(\`hold quantized step \${n} over its top step ${e} at byte \${r.at - ${a}}\`);\n return ${r(n.min)} + ${r(c)} * (n / ${e});`), o(i.s, "a: number, b: number", "boolean", ` return q_${t}(a) === q_${t}(b);`);
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
case "string":
|
|
103
|
+
o(i.w, "w: Wire_Writer, v: string, p: string", "void", ` if (typeof v !== 'string') throw new TypeError(\`\${p} must be a string\`);\n const bytes = utf8.encode(v);\n if (bytes.length > ${n.maxLength}) throw new RangeError(\`\${p} is \${bytes.length} UTF-8 bytes, over its limit of ${n.maxLength}; shorten it\`);\n w.varint(bytes.length);\n w.raw(bytes);`), o(i.r, "r: Wire_Reader", "string", ` const n = r.count(${n.maxLength}),\n at = r.at;\n r.need(n);\n r.at += n;\n try {\n return text.decode(r.bytes.subarray(at, at + n));\n } catch {\n throw r.fail(\`hold text that is not UTF-8 at byte \${at}\`);\n }`), o(i.s, "a: string, b: string", "boolean", " return a === b;");
|
|
104
|
+
break;
|
|
105
|
+
case "bytes":
|
|
106
|
+
o(i.w, "w: Wire_Writer, v: globalThis.Uint8Array, p: string", "void", ` if (!(v instanceof Uint8Array)) throw new TypeError(\`\${p} must be a Uint8Array\`);\n if (v.length > ${n.maxLength}) throw new RangeError(\`\${p} is \${v.length} bytes, over its limit of ${n.maxLength}; shorten it\`);\n w.varint(v.length);\n w.raw(v);`), o(i.r, "r: Wire_Reader", "globalThis.Uint8Array", ` const n = r.count(${n.maxLength});\n r.need(n);\n r.at += n;\n return r.bytes.slice(r.at - n, r.at);`), o(i.s, "a: globalThis.Uint8Array, b: globalThis.Uint8Array", "boolean", " return sameBytes(a, b);");
|
|
107
|
+
break;
|
|
108
|
+
case "enum": {
|
|
109
|
+
let e = JSON.stringify(n.values);
|
|
110
|
+
l.push(`const values_${t}: readonly (${a})[] = ${e};`), o(i.w, `w: Wire_Writer, v: ${a}, p: string`, "void", ` const i = values_${t}.indexOf(v);\n if (i < 0) throw new RangeError(\`\${p} is \${String(v)}; use one of ${n.values.join(", ")}\`);\n w.varint(i);`), o(i.r, "r: Wire_Reader", a, ` const i = r.varint();\n if (i >= ${n.values.length}) throw r.fail(\`hold enum index \${i} of only ${n.values.length} values\`);\n return values_${t}[i];`), o(i.s, `a: ${a}, b: ${a}`, "boolean", " return a === b;");
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
case "array": {
|
|
114
|
+
let e = f(`${t}_i`, n.of);
|
|
115
|
+
o(i.w, `w: Wire_Writer, v: ${a}, p: string`, "void", ` if (!Array.isArray(v)) throw new TypeError(\`\${p} must be an array\`);\n if (v.length > ${n.maxLength}) throw new RangeError(\`\${p} has \${v.length} items, over its limit of ${n.maxLength}; send fewer or raise maxLength in the schema\`);\n w.varint(v.length);\n for (let i = 0; i < v.length; i++) ${e.w}(w, v[i], \`\${p}[\${i}]\`);`), o(i.r, "r: Wire_Reader", a, ` const n = r.count(${n.maxLength}),\n out: ${a} = new Array(n);\n for (let i = 0; i < n; i++) out[i] = ${e.r}(r);\n return out;`), o(i.s, `a: ${a}, b: ${a}`, "boolean", ` return a.length === b.length && a.every((v, i) => ${e.s}(v, b[i]));`);
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
case "optional": {
|
|
119
|
+
let e = f(`${t}_v`, n.of);
|
|
120
|
+
o(i.w, `w: Wire_Writer, v: ${a} | undefined, p: string`, "void", ` if (v === undefined) return w.u8(0);\n w.u8(1);\n ${e.w}(w, v, p);`), o(i.r, "r: Wire_Reader", `${a} | undefined`, ` const flag = r.u8();\n if (flag > 1) throw r.fail(\`hold an optional flag of \${flag} at byte \${r.at - 1}\`);\n return flag ? ${e.r}(r) : undefined;`), o(i.s, `a: ${a} | undefined, b: ${a} | undefined`, "boolean", ` return a === undefined || b === undefined ? a === b : ${e.s}(a, b);`);
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
case "map": {
|
|
124
|
+
let e = f(`${t}_i`, n.of), r = u(n.of), s = n.maxSize;
|
|
125
|
+
o(`ids_${t}`, `v: ${a}, p: string`, "number[]", ` if (!(v instanceof Map)) throw new TypeError(\`\${p} must be a Map from entity id to value\`);\n if (v.size > ${s}) throw new RangeError(\`\${p} has \${v.size} entries, over its limit of ${s}; send fewer or raise maxSize in the schema\`);\n const keys = [...v.keys()];\n for (const id of keys) integer(\`\${p} id\`, id, 0, 4294967295);\n return keys.sort((x, y) => x - y);`), o(i.w, `w: Wire_Writer, v: ${a}, p: string`, "void", ` const keys = ids_${t}(v, p);\n w.varint(keys.length);\n writeIds(w, keys);\n for (const id of keys) ${e.w}(w, v.get(id) as ${r}, \`\${p}(\${id})\`);`), o(i.r, "r: Wire_Reader", a, ` const n = r.count(${s}),\n keys: number[] = [];\n r.ids(n, keys);\n return new Map(keys.map((id) => [id, ${e.r}(r)]));`), o(i.s, `a: ${a}, b: ${a}`, "boolean", ` if (a.size !== b.size) return false;\n for (const [id, v] of a) if (!b.has(id) || !${e.s}(v, b.get(id) as ${r})) return false;\n return true;`), o(i.dw, `w: Wire_Writer, v: ${a}, base: ${a}, p: string`, "void", ` const keys = ids_${t}(v, p);\n const removed = [...base.keys()].filter((id) => !v.has(id)).sort((x, y) => x - y);\n const changed = keys.filter((id) => !base.has(id) || !${e.s}(v.get(id) as ${r}, base.get(id) as ${r}));\n w.varint(removed.length);\n writeIds(w, removed);\n w.varint(changed.length);\n writeIds(w, changed);\n for (const id of changed) {\n const value = v.get(id) as ${r};\n ${e.dw ? `if (base.has(id)) ${e.dw}(w, value, base.get(id) as ${r}, \`\${p}(\${id})\`);\n else ` : ""}${e.w}(w, value, \`\${p}(\${id})\`);\n }`), o(i.dr, `r: Wire_Reader, base: ${a}`, a, ` const removed: number[] = [],\n changed: number[] = [];\n r.ids(r.count(base.size), removed);\n for (const id of removed) if (!base.has(id)) throw r.fail(\`remove entity \${id}, which the baseline lacks\`);\n r.ids(r.count(${s}), changed);\n const gone = new Set(removed),\n out = new Map(base);\n for (const id of removed) out.delete(id);\n for (const id of changed) {\n if (gone.has(id)) throw r.fail(\`both remove and change entity \${id}\`);\n out.set(id, ${e.dr ? `out.has(id) ? ${e.dr}(r, out.get(id) as ${r}) : ` : ""}${e.r}(r));\n }\n if (out.size > ${s}) throw r.fail(\`leave \${out.size} entries, over the map limit of ${s}\`);\n return new Map([...out].sort((x, y) => x[0] - y[0]));`);
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
default: {
|
|
129
|
+
let [t, a, s, c] = e[n.type];
|
|
130
|
+
o(i.w, "w: Wire_Writer, v: number, p: string", "void", ` integer(p, v, ${r(t)}, ${r(a)});\n ${s};`), o(i.r, "r: Wire_Reader", "number", ` return ${c};`), o(i.s, "a: number, b: number", "boolean", " return a === b;");
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return i;
|
|
134
|
+
};
|
|
135
|
+
c.push(`// Generated by @margoengine/netcode/generate${a.source ? ` from ${a.source}` : ""}; do not edit.`, "// Standalone: no imports. The bytes match @margoengine/netcode schema.encode for the same schema.", "", "/** FNV-1a hash of the normalized schema: both ends must agree. */", `export const SCHEMA_HASH = ${s};`, "");
|
|
136
|
+
let p = [];
|
|
137
|
+
for (let [e, t] of Object.entries(o.types)) {
|
|
138
|
+
let r = Object.entries(t), i = r.map(([e, t]) => ` ${e}${t.type === "optional" ? "?" : ""}: ${u(t)};`);
|
|
139
|
+
c.push(`export interface ${e} {\n${i.join("\n")}\n}`, "");
|
|
140
|
+
let a = r.map(([t, r]) => [
|
|
141
|
+
t,
|
|
142
|
+
r,
|
|
143
|
+
f(`${n(e)}_${t}`, r)
|
|
144
|
+
]), o = Math.ceil(r.length / 8);
|
|
145
|
+
p.push(`function w_${e}(w: Wire_Writer, v: ${e}, p: string): void {\n if (!v || typeof v !== 'object' || Array.isArray(v) || v instanceof Map) throw new TypeError(\`\${p} must be a ${e} object\`);\n${a.map(([e, , t]) => ` ${t.w}(w, v.${e}, \`\${p}.${e}\`);`).join("\n")}\n}`, `function r_${e}(r: Wire_Reader): ${e} {\n const out = {} as ${e};\n${a.map(([e, t, n]) => t.type === "optional" ? ` {\n const value = ${n.r}(r);\n if (value !== undefined) out.${e} = value;\n }` : ` out.${e} = ${n.r}(r);`).join("\n")}\n return out;\n}`, `/** Whether two ${e} values encode to the same bytes. */\nexport function same${e}(a: ${e}, b: ${e}): boolean {\n if (!a || typeof a !== 'object' || !b || typeof b !== 'object') return false;\n return ${a.map(([e, , t]) => `${t.s}(a.${e}, b.${e})`).join(" && ")};\n}`, `function dw_${e}(w: Wire_Writer, v: ${e}, base: ${e}, p: string): void {\n if (!v || typeof v !== 'object' || Array.isArray(v) || v instanceof Map) throw new TypeError(\`\${p} must be a ${e} object\`);\n const mask = new Uint8Array(${o});\n${a.map(([e, , t], n) => ` if (!${t.s}(v.${e}, base.${e})) mask[${n >> 3}] |= ${1 << (n & 7)};`).join("\n")}\n w.raw(mask);\n${a.map(([e, t, n], r) => {
|
|
146
|
+
let i = n.dw && t.type !== "optional" ? `${n.dw}(w, v.${e}, base.${e}, \`\${p}.${e}\`)` : `${n.w}(w, v.${e}, \`\${p}.${e}\`)`;
|
|
147
|
+
return ` if (mask[${r >> 3}] & ${1 << (r & 7)}) ${i};`;
|
|
148
|
+
}).join("\n")}\n}`, `function dr_${e}(r: Wire_Reader, base: ${e}): ${e} {\n r.need(${o});\n const mask = r.bytes.slice(r.at, r.at + ${o});\n r.at += ${o};\n${r.length & 7 ? ` if (mask[${o - 1}] >> ${r.length & 7}) throw r.fail('set a change bit past the ${r.length} fields of ${e}');\n` : ""} const out = {} as ${e};\n${a.map(([e, t, n], r) => {
|
|
149
|
+
let i = n.dr && t.type !== "optional" ? `${n.dr}(r, base.${e})` : `${n.r}(r)`;
|
|
150
|
+
return t.type === "optional" ? ` {\n const value = mask[${r >> 3}] & ${1 << (r & 7)} ? ${i} : base.${e};\n if (value !== undefined) out.${e} = value;\n }` : ` out.${e} = mask[${r >> 3}] & ${1 << (r & 7)} ? ${i} : base.${e};`;
|
|
151
|
+
}).join("\n")}\n return out;\n}`, `/** Bytes of a ${e}. */\nexport function encode${e}(value: ${e}): globalThis.Uint8Array {\n const w = new Wire_Writer();\n w_${e}(w, value, '${e}');\n return w.done();\n}`, `/** The ${e} in \`bytes\`; RangeError for truncated or malformed bytes. */\nexport function decode${e}(bytes: globalThis.Uint8Array): ${e} {\n const r = new Wire_Reader(bytes),\n value = r_${e}(r);\n r.end();\n return value;\n}`, `/** Bytes of a ${e} as a change from \`baseline\`. */\nexport function encode${e}Delta(value: ${e}, baseline: ${e}): globalThis.Uint8Array {\n const w = new Wire_Writer();\n dw_${e}(w, value, baseline, '${e}');\n return w.done();\n}`, `/** The ${e} that \`encode${e}Delta(value, baseline)\` described. */\nexport function decode${e}Delta(bytes: globalThis.Uint8Array, baseline: ${e}): ${e} {\n const r = new Wire_Reader(bytes),\n value = dr_${e}(r, baseline);\n r.end();\n return value;\n}`);
|
|
152
|
+
}
|
|
153
|
+
return `${c.join("\n")}\n${t}\n${l.join("\n\n")}\n\n${p.join("\n\n")}\n`;
|
|
154
|
+
}
|
|
155
|
+
//#endregion
|
|
156
|
+
export { i as generateTypeScript };
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { RewindHit } from './lag.js';
|
|
2
|
+
/** A sphere: `position` [x, y, z] and `radius`. */
|
|
3
|
+
export interface RewindSphere {
|
|
4
|
+
readonly position: readonly number[];
|
|
5
|
+
readonly radius: number;
|
|
6
|
+
}
|
|
7
|
+
/** A box of half sizes `halfExtents` [x, y, z] around `position`, turned by the unit quaternion `rotation` [x, y, z, w]. */
|
|
8
|
+
export interface RewindBox {
|
|
9
|
+
readonly position: readonly number[];
|
|
10
|
+
readonly halfExtents: readonly number[];
|
|
11
|
+
readonly rotation?: readonly number[];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A capsule around `position`, `halfHeight` from the centre to the centre of each cap along its own y axis, as tall as
|
|
15
|
+
* `2 * (halfHeight + radius)` in all, turned by `rotation` [x, y, z, w].
|
|
16
|
+
*/
|
|
17
|
+
export interface RewindCapsule {
|
|
18
|
+
readonly position: readonly number[];
|
|
19
|
+
readonly radius: number;
|
|
20
|
+
readonly halfHeight: number;
|
|
21
|
+
readonly rotation?: readonly number[];
|
|
22
|
+
}
|
|
23
|
+
/** One shape of {@link HitboxRewind}. */
|
|
24
|
+
export type RewindShape = RewindSphere | RewindBox | RewindCapsule;
|
|
25
|
+
/**
|
|
26
|
+
* Where every sphere, box and capsule was at each of the last `history` ticks: `LagCompensation` for shapes that are
|
|
27
|
+
* not round. Shapes are 3D; a 2D game passes z as 0.
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```ts
|
|
31
|
+
* const rewind = new HitboxRewind({ history: 32 });
|
|
32
|
+
* // each server tick, after the step:
|
|
33
|
+
* rewind.record(server.tick, [...state.players].map(([id, p]) => [id, { position: [p.x, p.y, p.z], radius: 0.4, halfHeight: 0.5 }]));
|
|
34
|
+
* // a shot from a player who saw the world at (fractional) tick input.viewTick:
|
|
35
|
+
* const hit = rewind.raycast(input.viewTick, eye, aim, { ignore: shooter });
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export declare class HitboxRewind {
|
|
39
|
+
/** Ticks kept. */
|
|
40
|
+
readonly history: number;
|
|
41
|
+
private readonly frames;
|
|
42
|
+
/** @throws RangeError for a history that is not an integer from 2 to 4096. */
|
|
43
|
+
constructor({ history }?: {
|
|
44
|
+
history?: number;
|
|
45
|
+
});
|
|
46
|
+
/** The oldest and newest ticks held, or undefined while empty. */
|
|
47
|
+
get range(): [number, number] | undefined;
|
|
48
|
+
/**
|
|
49
|
+
* Records the shapes at `tick` (copies them). Ticks must increase; recording the same tick again replaces it.
|
|
50
|
+
* @throws RangeError for a tick older than the newest or a size or rotation out of range; TypeError for a shape
|
|
51
|
+
* with no position of 3 numbers.
|
|
52
|
+
*/
|
|
53
|
+
record(tick: number, shapes: Iterable<readonly [number, RewindShape]>): void;
|
|
54
|
+
private shapes;
|
|
55
|
+
/**
|
|
56
|
+
* The shapes at fractional tick `tick`, blended between the two recorded ticks around it: positions and sizes in a
|
|
57
|
+
* line, rotations the short way round. A new shape counts at once and one that went counts up to halfway, as in
|
|
58
|
+
* `LagCompensation`. A tick older than the history is clamped to the oldest frame, so a client cannot rewind further
|
|
59
|
+
* than `history` ticks.
|
|
60
|
+
*/
|
|
61
|
+
at(tick: number): Map<number, RewindShape>;
|
|
62
|
+
/**
|
|
63
|
+
* The nearest shape a ray from `origin` along `direction` hits at fractional tick `tick`, within `maxDistance`
|
|
64
|
+
* (default Infinity, in direction lengths) and not in `ignore` (an id or a set of ids, the shooter). A ray that starts
|
|
65
|
+
* inside a shape hits it at distance 0. Undefined when it hits nothing.
|
|
66
|
+
* @throws RangeError for an origin or direction that is not 3 finite numbers, or a zero direction.
|
|
67
|
+
*/
|
|
68
|
+
raycast(tick: number, origin: readonly number[], direction: readonly number[], { maxDistance, ignore, }?: {
|
|
69
|
+
maxDistance?: number;
|
|
70
|
+
ignore?: number | ReadonlySet<number>;
|
|
71
|
+
}): RewindHit | undefined;
|
|
72
|
+
/** Drops every recorded tick. */
|
|
73
|
+
clear(): void;
|
|
74
|
+
}
|
package/dist/hitboxes.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { Timeline as e } from "./interpolation-timeline.js";
|
|
2
|
+
import { Capsule as t } from "@margoengine/math/capsule";
|
|
3
|
+
import { OBB as n } from "@margoengine/math/obb";
|
|
4
|
+
import { Quaternion as r } from "@margoengine/math/quaternion";
|
|
5
|
+
import { Vector3 as i } from "@margoengine/math/vector3";
|
|
6
|
+
//#region src/hitboxes.ts
|
|
7
|
+
var a = (e, t) => Array.isArray(e) && e.length === t && e.every(Number.isFinite);
|
|
8
|
+
function o(e, t) {
|
|
9
|
+
let n = t, r = n.rotation ?? [
|
|
10
|
+
0,
|
|
11
|
+
0,
|
|
12
|
+
0,
|
|
13
|
+
1
|
|
14
|
+
];
|
|
15
|
+
if (!t || !a(n.position, 3)) throw TypeError(`HitboxRewind shape ${e} needs a position of 3 finite numbers; pass [x, y, z]`);
|
|
16
|
+
if (!a(r, 4) || !(Math.hypot(...r) > 0)) throw RangeError(`HitboxRewind shape ${e} rotation is not a quaternion; pass [x, y, z, w]`);
|
|
17
|
+
let i = Math.hypot(...r), o = n.halfExtents;
|
|
18
|
+
if (o !== void 0 && (!a(o, 3) || o.some((e) => e < 0))) throw RangeError(`HitboxRewind shape ${e} halfExtents needs 3 numbers of 0 or more; fix them`);
|
|
19
|
+
let s = n.radius ?? 0, c = n.halfHeight ?? 0;
|
|
20
|
+
if (!o && (typeof n.radius != "number" || !(s >= 0) || s === Infinity)) throw RangeError(`HitboxRewind shape ${e} radius is ${n.radius}; use a finite 0 or more, or pass halfExtents`);
|
|
21
|
+
if (!(c >= 0) || c === Infinity) throw RangeError(`HitboxRewind shape ${e} halfHeight is ${c}; use a finite 0 or more`);
|
|
22
|
+
return {
|
|
23
|
+
position: [...n.position],
|
|
24
|
+
rotation: r.map((e) => e / i),
|
|
25
|
+
radius: s,
|
|
26
|
+
halfHeight: c,
|
|
27
|
+
halfExtents: o ? [...o] : void 0
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
var s = (e, t, n) => e.map((e, r) => e + (t[r] - e) * n), c = new r(), l = new r();
|
|
31
|
+
function u(e, t, n) {
|
|
32
|
+
return c.set(e.rotation[0], e.rotation[1], e.rotation[2], e.rotation[3]), l.set(t.rotation[0], t.rotation[1], t.rotation[2], t.rotation[3]), c.slerp(l, n), {
|
|
33
|
+
position: s(e.position, t.position, n),
|
|
34
|
+
rotation: [
|
|
35
|
+
c.x,
|
|
36
|
+
c.y,
|
|
37
|
+
c.z,
|
|
38
|
+
c.w
|
|
39
|
+
],
|
|
40
|
+
radius: e.radius + (t.radius - e.radius) * n,
|
|
41
|
+
halfHeight: e.halfHeight + (t.halfHeight - e.halfHeight) * n,
|
|
42
|
+
halfExtents: e.halfExtents && s(e.halfExtents, t.halfExtents, n)
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
var d = new n(), f = new t(), p = {
|
|
46
|
+
origin: new i(),
|
|
47
|
+
direction: new i()
|
|
48
|
+
}, m = new i(), h = new r();
|
|
49
|
+
function g(e, t, n) {
|
|
50
|
+
let [r, i, a] = e.position, [o, s, c, l] = e.rotation;
|
|
51
|
+
h.set(-o, -s, -c, l), p.origin.set(t[0] - r, t[1] - i, t[2] - a).applyQuaternion(h), p.direction.set(n[0], n[1], n[2]).applyQuaternion(h);
|
|
52
|
+
let u = e.halfExtents;
|
|
53
|
+
if (u) {
|
|
54
|
+
if (d.halfSize.set(u[0], u[1], u[2]), !d.intersectRay(p, m)) return;
|
|
55
|
+
} else if (f.start.set(0, -e.halfHeight, 0), f.end.set(0, e.halfHeight, 0), f.radius = e.radius, !f.intersectRay(p, m)) return;
|
|
56
|
+
return m.sub(p.origin).dot(p.direction) / p.direction.dot(p.direction);
|
|
57
|
+
}
|
|
58
|
+
var _ = class {
|
|
59
|
+
constructor({ history: t = 32 } = {}) {
|
|
60
|
+
if (!Number.isInteger(t) || t < 2 || t > 4096) throw RangeError(`HitboxRewind history is ${t}; pass an integer from 2 to 4096 ticks`);
|
|
61
|
+
this.history = t, this.frames = new e(t);
|
|
62
|
+
}
|
|
63
|
+
get range() {
|
|
64
|
+
let e = this.frames;
|
|
65
|
+
return e.count ? [e.oldest, e.newest] : void 0;
|
|
66
|
+
}
|
|
67
|
+
record(e, t) {
|
|
68
|
+
if (!Number.isFinite(e)) throw RangeError(`HitboxRewind tick is ${e}; pass a finite tick`);
|
|
69
|
+
let n = this.frames;
|
|
70
|
+
if (e < n.newest) throw RangeError(`HitboxRewind tick ${e} is older than ${n.newest}; record ticks in order`);
|
|
71
|
+
let r = /* @__PURE__ */ new Map();
|
|
72
|
+
for (let [e, n] of t) r.set(e, o(e, n));
|
|
73
|
+
n.add(e, r) || n.replace(e, r);
|
|
74
|
+
}
|
|
75
|
+
shapes(e) {
|
|
76
|
+
let t = /* @__PURE__ */ new Map(), n = this.frames;
|
|
77
|
+
if (!Number.isFinite(e) || !n.locate(e)) return t;
|
|
78
|
+
if (n.a === n.b) return n.from;
|
|
79
|
+
let r = n.from, i = n.to, a = n.u;
|
|
80
|
+
for (let [e, n] of i) {
|
|
81
|
+
let i = r.get(e);
|
|
82
|
+
!i || !i.halfExtents != !n.halfExtents ? t.set(e, a < .5 && i ? i : n) : t.set(e, u(i, n, a));
|
|
83
|
+
}
|
|
84
|
+
for (let [e, n] of r) !t.has(e) && a < .5 && t.set(e, n);
|
|
85
|
+
return t;
|
|
86
|
+
}
|
|
87
|
+
at(e) {
|
|
88
|
+
let t = /* @__PURE__ */ new Map();
|
|
89
|
+
for (let [n, r] of this.shapes(e)) {
|
|
90
|
+
let { position: e, rotation: i } = r;
|
|
91
|
+
t.set(n, r.halfExtents ? {
|
|
92
|
+
position: e,
|
|
93
|
+
rotation: i,
|
|
94
|
+
halfExtents: r.halfExtents
|
|
95
|
+
} : {
|
|
96
|
+
position: e,
|
|
97
|
+
rotation: i,
|
|
98
|
+
radius: r.radius,
|
|
99
|
+
halfHeight: r.halfHeight
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
return t;
|
|
103
|
+
}
|
|
104
|
+
raycast(e, t, n, { maxDistance: r = Infinity, ignore: i } = {}) {
|
|
105
|
+
if (!a(t, 3) || !a(n, 3)) throw RangeError("HitboxRewind raycast needs origin and direction of 3 finite numbers; fix them");
|
|
106
|
+
if (!(Math.hypot(...n) > 0)) throw RangeError("HitboxRewind raycast direction is zero; pass a direction");
|
|
107
|
+
let o = (e) => typeof i == "number" ? e === i : i?.has(e) === !0, s;
|
|
108
|
+
for (let [i, a] of this.shapes(e)) {
|
|
109
|
+
if (o(i)) continue;
|
|
110
|
+
let e = g(a, t, n);
|
|
111
|
+
e === void 0 || e > r || s && e >= s.distance || (s = {
|
|
112
|
+
id: i,
|
|
113
|
+
distance: e,
|
|
114
|
+
point: t.map((t, r) => t + n[r] * e)
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
return s;
|
|
118
|
+
}
|
|
119
|
+
clear() {
|
|
120
|
+
this.frames.clear();
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
//#endregion
|
|
124
|
+
export { _ as HitboxRewind };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { defineSchema, dequantize, fnv1a, quantize, type FieldType, type Infer, type FieldInterpolation, type NormalizedField, type NormalizedSchema, type NumberKind, type ScalarKind, type SchemaCodec, type SchemaDefinition, type SchemaShape, type StructDefinition, type TypeName, type UntypedSchema, } from './schema.js';
|
|
2
|
+
export { defineGame, type Game, type GameDefinition } from './game.js';
|
|
3
|
+
export { CloseCode, messages, type Delivery, type Connection, type ConnectionMessage, type Listener, } from './transport.js';
|
|
4
|
+
export { LoopbackNetwork, type LinkConditions, type LoopbackOptions, type LoopbackStats } from './loopback.js';
|
|
5
|
+
export { ClockSync } from './clock.js';
|
|
6
|
+
export { decodeEnvelope, encodeEnvelope, MAX_INPUT_BYTES, MAX_INPUTS_PER_MESSAGE, ENVELOPE_VERSION, type Envelope, } from './protocol.js';
|
|
7
|
+
export { GameServer, type GameServerOptions, type GameServerStats, type RateLimits } from './server.js';
|
|
8
|
+
export { GameClient, type GameClientOptions, type GameClientStats, type ViewClock } from './client.js';
|
|
9
|
+
export { LagCompensation, type Hitbox, type RewindHit } from './lag.js';
|