@margoengine/netcode 0.0.0-stage → 1.0.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 +1387 -2
- 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 +215 -0
- package/dist/media.js +305 -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 +38 -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 +138 -4
package/dist/schema.d.ts
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import { ByteReader, ByteWriter } from './shared/bytes.js';
|
|
2
|
+
/** Number kinds: fixed-width integers, 32-bit LEB128 varints (`uint`, zigzag `int`) and little-endian floats. */
|
|
3
|
+
export type NumberKind = 'u8' | 'u16' | 'u32' | 'i8' | 'i16' | 'i32' | 'uint' | 'int' | 'f32' | 'f64';
|
|
4
|
+
/** The kinds a field can name directly as a string. */
|
|
5
|
+
export type ScalarKind = NumberKind | 'bool' | 'string' | 'bytes';
|
|
6
|
+
/** How {@link SchemaCodec.interpolate} blends a number: straight line, shortest turn in radians, or no blend (step). */
|
|
7
|
+
export type FieldInterpolation = 'linear' | 'angle' | 'none';
|
|
8
|
+
/**
|
|
9
|
+
* One field's type: a {@link ScalarKind}, the name of another struct in the schema, or an object form:
|
|
10
|
+
* - `{ type: 'f32' | ... , interpolate? }` a number with its interpolation (floats default to `'linear'`, integers
|
|
11
|
+
* are always `'none'`);
|
|
12
|
+
* - `{ type: 'quantized', min, max, bits, interpolate? }` a float in [min, max] sent as an unsigned integer of `bits`
|
|
13
|
+
* (2 to 32) bits in `ceil(bits / 8)` bytes, in `2^bits - 2` equal steps so that min, max and their midpoint
|
|
14
|
+
* (0 in a range like -1..1) are exact;
|
|
15
|
+
* - `{ type: 'string' | 'bytes', maxLength? }` UTF-8 text or raw bytes, at most `maxLength` bytes (default 256 for
|
|
16
|
+
* strings, 4096 for bytes);
|
|
17
|
+
* - `{ type: 'enum', values }` one of up to 2^32 strings, sent as its index;
|
|
18
|
+
* - `{ type: 'array', of, maxLength? }` a list of up to `maxLength` items (default 256);
|
|
19
|
+
* - `{ type: 'optional', of }` the value or `undefined`;
|
|
20
|
+
* - `{ type: 'map', of, maxSize? }` a `Map` from entity id (0 to 2^32 - 1) to values, at most `maxSize` entries
|
|
21
|
+
* (default 1024). Maps are the entity collections: a delta sends only added, changed and removed entries.
|
|
22
|
+
*/
|
|
23
|
+
export type FieldType = ScalarKind | (string & {}) | {
|
|
24
|
+
readonly type: NumberKind;
|
|
25
|
+
readonly interpolate?: FieldInterpolation;
|
|
26
|
+
} | {
|
|
27
|
+
readonly type: 'quantized';
|
|
28
|
+
readonly min: number;
|
|
29
|
+
readonly max: number;
|
|
30
|
+
readonly bits: number;
|
|
31
|
+
readonly interpolate?: FieldInterpolation;
|
|
32
|
+
} | {
|
|
33
|
+
readonly type: 'string' | 'bytes';
|
|
34
|
+
readonly maxLength?: number;
|
|
35
|
+
} | {
|
|
36
|
+
readonly type: 'enum';
|
|
37
|
+
readonly values: readonly string[];
|
|
38
|
+
} | {
|
|
39
|
+
readonly type: 'array';
|
|
40
|
+
readonly of: FieldType;
|
|
41
|
+
readonly maxLength?: number;
|
|
42
|
+
} | {
|
|
43
|
+
readonly type: 'optional';
|
|
44
|
+
readonly of: FieldType;
|
|
45
|
+
} | {
|
|
46
|
+
readonly type: 'map';
|
|
47
|
+
readonly of: FieldType;
|
|
48
|
+
readonly maxSize?: number;
|
|
49
|
+
};
|
|
50
|
+
/** A struct: field names in wire order, each with its {@link FieldType}. */
|
|
51
|
+
export type StructDefinition = {
|
|
52
|
+
readonly [field: string]: FieldType;
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* A whole schema: named structs (names start with a capital letter) and an optional version number of your own. The
|
|
56
|
+
* same object, as JSON, is the input of every generator.
|
|
57
|
+
*/
|
|
58
|
+
export interface SchemaDefinition {
|
|
59
|
+
/** Your protocol's version, part of the hash (default 1). */
|
|
60
|
+
readonly version?: number;
|
|
61
|
+
/** Struct name to its fields. */
|
|
62
|
+
readonly types: {
|
|
63
|
+
readonly [name: string]: StructDefinition;
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Any schema definition's shape, without checking its fields: the constraint of the type helpers below. (Checking
|
|
68
|
+
* fields against {@link FieldType} there makes TypeScript's inference too deep; `defineSchema` checks them.)
|
|
69
|
+
*/
|
|
70
|
+
export interface SchemaShape {
|
|
71
|
+
/** Struct name to its fields. */
|
|
72
|
+
readonly types: {
|
|
73
|
+
readonly [name: string]: {
|
|
74
|
+
readonly [field: string]: unknown;
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
type FieldValue<T, F> = F extends 'bool' ? boolean : F extends NumberKind ? number : F extends 'string' ? string : F extends 'bytes' ? Uint8Array : F extends {
|
|
79
|
+
type: 'quantized' | NumberKind;
|
|
80
|
+
} ? number : F extends {
|
|
81
|
+
type: 'string';
|
|
82
|
+
} ? string : F extends {
|
|
83
|
+
type: 'bytes';
|
|
84
|
+
} ? Uint8Array : F extends {
|
|
85
|
+
type: 'enum';
|
|
86
|
+
values: readonly (infer E)[];
|
|
87
|
+
} ? E : F extends {
|
|
88
|
+
type: 'array';
|
|
89
|
+
of: infer O;
|
|
90
|
+
} ? FieldValue<T, O>[] : F extends {
|
|
91
|
+
type: 'optional';
|
|
92
|
+
of: infer O;
|
|
93
|
+
} ? FieldValue<T, O> | undefined : F extends {
|
|
94
|
+
type: 'map';
|
|
95
|
+
of: infer O;
|
|
96
|
+
} ? Map<number, FieldValue<T, O>> : F extends keyof T ? StructValue<T, T[F]> : unknown;
|
|
97
|
+
type OptionalKeys<S> = {
|
|
98
|
+
[K in keyof S]: S[K] extends {
|
|
99
|
+
type: 'optional';
|
|
100
|
+
} ? K : never;
|
|
101
|
+
}[keyof S];
|
|
102
|
+
type StructValue<T, S> = {
|
|
103
|
+
-readonly [K in Exclude<keyof S, OptionalKeys<S>>]: FieldValue<T, S[K]>;
|
|
104
|
+
} & {
|
|
105
|
+
-readonly [K in OptionalKeys<S>]?: FieldValue<T, S[K]>;
|
|
106
|
+
};
|
|
107
|
+
/** Names of the structs of schema definition `S`. */
|
|
108
|
+
export type TypeName<S extends SchemaShape> = keyof S['types'] & string;
|
|
109
|
+
/** The JavaScript value of struct `N` of schema definition `S`, as `encode` takes it and `decode` returns it. */
|
|
110
|
+
export type Infer<S extends SchemaShape, N extends TypeName<S>> = StructValue<S['types'], S['types'][N]>;
|
|
111
|
+
/** A normalized field: every shorthand expanded and every default filled in (see {@link SchemaCodec.json}). */
|
|
112
|
+
export type NormalizedField = {
|
|
113
|
+
type: NumberKind;
|
|
114
|
+
interpolate: FieldInterpolation;
|
|
115
|
+
} | {
|
|
116
|
+
type: 'bool';
|
|
117
|
+
} | {
|
|
118
|
+
type: 'quantized';
|
|
119
|
+
min: number;
|
|
120
|
+
max: number;
|
|
121
|
+
bits: number;
|
|
122
|
+
interpolate: FieldInterpolation;
|
|
123
|
+
} | {
|
|
124
|
+
type: 'string' | 'bytes';
|
|
125
|
+
maxLength: number;
|
|
126
|
+
} | {
|
|
127
|
+
type: 'enum';
|
|
128
|
+
values: string[];
|
|
129
|
+
} | {
|
|
130
|
+
type: 'array';
|
|
131
|
+
of: NormalizedField;
|
|
132
|
+
maxLength: number;
|
|
133
|
+
} | {
|
|
134
|
+
type: 'optional';
|
|
135
|
+
of: NormalizedField;
|
|
136
|
+
} | {
|
|
137
|
+
type: 'map';
|
|
138
|
+
of: NormalizedField;
|
|
139
|
+
maxSize: number;
|
|
140
|
+
} | {
|
|
141
|
+
type: 'struct';
|
|
142
|
+
name: string;
|
|
143
|
+
};
|
|
144
|
+
/** The normalized schema, the exact input of generators and of {@link SchemaCodec.hash}. */
|
|
145
|
+
export interface NormalizedSchema {
|
|
146
|
+
/** The definition's version (default 1). */
|
|
147
|
+
version: number;
|
|
148
|
+
/** Struct name to its normalized fields, in wire order. */
|
|
149
|
+
types: {
|
|
150
|
+
[name: string]: {
|
|
151
|
+
[field: string]: NormalizedField;
|
|
152
|
+
};
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
/** A compiled schema: the codec of every struct it names. */
|
|
156
|
+
export interface SchemaCodec<S extends SchemaShape = SchemaDefinition> {
|
|
157
|
+
/** The definition as given. */
|
|
158
|
+
readonly definition: S;
|
|
159
|
+
/** The normalized definition: what a generator in another language reads (`JSON.stringify(schema.json)`). */
|
|
160
|
+
readonly json: NormalizedSchema;
|
|
161
|
+
/** FNV-1a 32-bit hash of `JSON.stringify(schema.json)` as UTF-8: two ends with the same hash speak the same format. */
|
|
162
|
+
readonly hash: number;
|
|
163
|
+
/** Struct names, in definition order. */
|
|
164
|
+
readonly names: readonly TypeName<S>[];
|
|
165
|
+
/**
|
|
166
|
+
* Bytes of `value` as struct `name`.
|
|
167
|
+
* @throws TypeError for a value of the wrong shape; RangeError for one outside its field's range (a non-integer or
|
|
168
|
+
* out-of-range integer, a non-finite float, a quantized value outside [min, max], text, a list or a map over its
|
|
169
|
+
* limit).
|
|
170
|
+
*/
|
|
171
|
+
encode<N extends TypeName<S>>(name: N, value: Infer<S, N>): Uint8Array;
|
|
172
|
+
/**
|
|
173
|
+
* The value `encode(name, ...)` wrote. Maps come back sorted by id.
|
|
174
|
+
* @throws RangeError for truncated or malformed bytes, or bytes past the end (never anything else).
|
|
175
|
+
*/
|
|
176
|
+
decode<N extends TypeName<S>>(name: N, bytes: Uint8Array): Infer<S, N>;
|
|
177
|
+
/**
|
|
178
|
+
* Bytes of `value` as a change from `baseline` (a value `decode` or `decodeDelta` returned): one bit per field, then
|
|
179
|
+
* only the fields that changed; maps send only removed, added and changed entries.
|
|
180
|
+
* @throws as {@link SchemaCodec.encode}.
|
|
181
|
+
*/
|
|
182
|
+
encodeDelta<N extends TypeName<S>>(name: N, value: Infer<S, N>, baseline: Infer<S, N>): Uint8Array;
|
|
183
|
+
/**
|
|
184
|
+
* The value `encodeDelta(name, value, baseline)` described, equal to `decode(name, encode(name, value))`. Unchanged
|
|
185
|
+
* parts are shared with `baseline`, so treat decoded values as read-only (`clone` gives a private copy).
|
|
186
|
+
* @throws RangeError for truncated or malformed bytes, or bytes that do not fit `baseline`.
|
|
187
|
+
*/
|
|
188
|
+
decodeDelta<N extends TypeName<S>>(name: N, bytes: Uint8Array, baseline: Infer<S, N>): Infer<S, N>;
|
|
189
|
+
/** Whether `a` and `b` encode to the same bytes (floats compared after rounding to the wire precision). */
|
|
190
|
+
equals<N extends TypeName<S>>(name: N, a: Infer<S, N>, b: Infer<S, N>): boolean;
|
|
191
|
+
/** A private deep copy of `value` exactly as the other end decodes it (floats at wire precision, maps sorted by id). */
|
|
192
|
+
clone<N extends TypeName<S>>(name: N, value: Infer<S, N>): Infer<S, N>;
|
|
193
|
+
/**
|
|
194
|
+
* The blend of `a` and `b` at `t` (0 gives `a`, 1 gives `b`): floats per their {@link FieldInterpolation}, everything
|
|
195
|
+
* else steps to `b` at `t >= 1`; a map entry only in `b` is taken from `b`, one only in `a` is dropped.
|
|
196
|
+
*/
|
|
197
|
+
interpolate<N extends TypeName<S>>(name: N, a: Infer<S, N>, b: Infer<S, N>, t: number): Infer<S, N>;
|
|
198
|
+
}
|
|
199
|
+
/** A compiled schema seen without its definition's types: names are strings and values `unknown`. */
|
|
200
|
+
export interface UntypedSchema {
|
|
201
|
+
/** See {@link SchemaCodec.json}. */
|
|
202
|
+
readonly json: NormalizedSchema;
|
|
203
|
+
/** See {@link SchemaCodec.hash}. */
|
|
204
|
+
readonly hash: number;
|
|
205
|
+
/** See {@link SchemaCodec.names}. */
|
|
206
|
+
readonly names: readonly string[];
|
|
207
|
+
/** See {@link SchemaCodec.encode}. */
|
|
208
|
+
encode(name: string, value: unknown): Uint8Array;
|
|
209
|
+
/** See {@link SchemaCodec.decode}. */
|
|
210
|
+
decode(name: string, bytes: Uint8Array): unknown;
|
|
211
|
+
/** See {@link SchemaCodec.encodeDelta}. */
|
|
212
|
+
encodeDelta(name: string, value: unknown, baseline: unknown): Uint8Array;
|
|
213
|
+
/** See {@link SchemaCodec.decodeDelta}. */
|
|
214
|
+
decodeDelta(name: string, bytes: Uint8Array, baseline: unknown): unknown;
|
|
215
|
+
/** See {@link SchemaCodec.equals}. */
|
|
216
|
+
equals(name: string, a: unknown, b: unknown): boolean;
|
|
217
|
+
/** See {@link SchemaCodec.clone}. */
|
|
218
|
+
clone(name: string, value: unknown): unknown;
|
|
219
|
+
/** See {@link SchemaCodec.interpolate}. */
|
|
220
|
+
interpolate(name: string, a: unknown, b: unknown, t: number): unknown;
|
|
221
|
+
}
|
|
222
|
+
/** FNV-1a, 32 bits, over UTF-8 bytes. */
|
|
223
|
+
export declare function fnv1a(text: string): number;
|
|
224
|
+
/** The shared writer plus 64-bit floats. */
|
|
225
|
+
export declare class Writer extends ByteWriter {
|
|
226
|
+
/** Writes a little-endian 64-bit float. */
|
|
227
|
+
f64(v: number): void;
|
|
228
|
+
}
|
|
229
|
+
/** The shared checked reader plus 64-bit floats and finite-float checks. */
|
|
230
|
+
export declare class Reader extends ByteReader {
|
|
231
|
+
/** Reads a little-endian 32-bit float and rejects NaN and infinities. */
|
|
232
|
+
f32(): number;
|
|
233
|
+
/** Reads a little-endian 64-bit float and rejects NaN and infinities. */
|
|
234
|
+
f64(): number;
|
|
235
|
+
/** Throws unless `v` is finite. */
|
|
236
|
+
finite(v: number): number;
|
|
237
|
+
/** A count of items that each take at least one byte: at most `max` and at most the bytes left. */
|
|
238
|
+
count(max: number): number;
|
|
239
|
+
}
|
|
240
|
+
/** The quantized integer of `v` for a field with `min`, `max` and `bits` (the formula of README "Wire format"). */
|
|
241
|
+
export declare const quantize: (v: number, min: number, max: number, bits: number) => number;
|
|
242
|
+
/** The value of quantized integer `q` (the formula of README "Wire format"). */
|
|
243
|
+
export declare const dequantize: (q: number, min: number, max: number, bits: number) => number;
|
|
244
|
+
/**
|
|
245
|
+
* Checks and compiles a schema definition. Write it once, `as const` for full types, and share it between server and
|
|
246
|
+
* client; `schema.json` is the normalized form a generator in another language reads.
|
|
247
|
+
*
|
|
248
|
+
* @example
|
|
249
|
+
* ```ts
|
|
250
|
+
* const schema = defineSchema({
|
|
251
|
+
* types: {
|
|
252
|
+
* Input: { x: { type: 'quantized', min: -1, max: 1, bits: 8 }, jump: 'bool' },
|
|
253
|
+
* Box: { x: 'f32', y: 'f32', owner: 'uint' },
|
|
254
|
+
* State: { boxes: { type: 'map', of: 'Box', maxSize: 64 } },
|
|
255
|
+
* },
|
|
256
|
+
* } as const);
|
|
257
|
+
* const bytes = schema.encode('Input', { x: 0.5, jump: true });
|
|
258
|
+
* ```
|
|
259
|
+
* @throws TypeError for an unknown type, a bad name or a struct that contains itself directly; RangeError for a limit
|
|
260
|
+
* or quantized range out of bounds.
|
|
261
|
+
*/
|
|
262
|
+
export declare function defineSchema<const S extends SchemaDefinition>(definition: S): SchemaCodec<S>;
|
|
263
|
+
export {};
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { r as e, t } from "./transport-DeQodwyv.js";
|
|
2
|
+
import { a as n, o as r } from "./protocol-asi_qndb.js";
|
|
3
|
+
//#region src/server.ts
|
|
4
|
+
var i = (e, t, n, r) => {
|
|
5
|
+
if (!Number.isInteger(t) || t < n || t > r) throw RangeError(`GameServer ${e} is ${t}; pass an integer from ${n} to ${r}`);
|
|
6
|
+
return t;
|
|
7
|
+
}, a = class {
|
|
8
|
+
constructor(e, t = {}) {
|
|
9
|
+
if (this.game = e, this.options = t, this.stats = {
|
|
10
|
+
ticks: 0,
|
|
11
|
+
inputs: 0,
|
|
12
|
+
lateInputs: 0,
|
|
13
|
+
rejectedInputs: 0,
|
|
14
|
+
missedInputs: 0,
|
|
15
|
+
snapshots: 0,
|
|
16
|
+
deltaSnapshots: 0,
|
|
17
|
+
snapshotBytes: 0,
|
|
18
|
+
dropped: 0
|
|
19
|
+
}, this.ticks = 0, this.nextPlayer = 1, this.closed = !1, this.peers = /* @__PURE__ */ new Set(), this.joins = [], this.leaves = [], this.maxPlayers = i("maxPlayers", t.maxPlayers ?? 64, 1, 65536), this.snapshotEvery = i("snapshotEvery", t.snapshotEvery ?? 1, 1, 60), this.keep = i("history", t.history ?? 64, 2, 1024), this.ahead = i("maxInputAhead", t.maxInputAhead ?? 2 * e.tickRate, 1, 65536), this.timeout = t.timeout ?? 1e4, !(this.timeout > 0)) throw RangeError(`GameServer timeout is ${this.timeout}; pass milliseconds > 0`);
|
|
20
|
+
let n = t.limits ?? {};
|
|
21
|
+
if (this.rate = n.messagesPerSecond ?? 120, this.burst = n.burst ?? 60, this.maxBytes = i("maxMessageBytes", n.maxMessageBytes ?? 4096, 64, 1 << 24), !(this.rate > 0) || !(this.burst >= 1)) throw RangeError("GameServer limits need messagesPerSecond > 0 and burst >= 1; fix the limits");
|
|
22
|
+
this.now = t.now ?? (() => performance.now()), this.current = this.canonical(e.initial()), this.lastTickAt = this.now();
|
|
23
|
+
}
|
|
24
|
+
get tick() {
|
|
25
|
+
return this.ticks;
|
|
26
|
+
}
|
|
27
|
+
get state() {
|
|
28
|
+
return this.current;
|
|
29
|
+
}
|
|
30
|
+
get players() {
|
|
31
|
+
return [...this.peers].filter((e) => e.playing).map((e) => e.player);
|
|
32
|
+
}
|
|
33
|
+
canonical(e) {
|
|
34
|
+
return this.game.schema.clone(this.game.stateType, e);
|
|
35
|
+
}
|
|
36
|
+
accept(t) {
|
|
37
|
+
if (this.closed) throw e("disposed", "GameServer is closed; create a new GameServer");
|
|
38
|
+
let n = {
|
|
39
|
+
connection: t,
|
|
40
|
+
player: 0,
|
|
41
|
+
playing: !1,
|
|
42
|
+
inputs: /* @__PURE__ */ new Map(),
|
|
43
|
+
newest: 0,
|
|
44
|
+
missed: 0,
|
|
45
|
+
ack: 0,
|
|
46
|
+
sent: /* @__PURE__ */ new Map(),
|
|
47
|
+
tokens: this.burst,
|
|
48
|
+
refilled: this.now(),
|
|
49
|
+
heard: this.now()
|
|
50
|
+
};
|
|
51
|
+
this.peers.add(n), t.onmessage = (e, t) => this.receive(n, e, t), t.onclose = () => this.remove(n);
|
|
52
|
+
}
|
|
53
|
+
drop(e, t, n) {
|
|
54
|
+
this.stats.dropped++, e.connection.close(t, n), this.remove(e);
|
|
55
|
+
}
|
|
56
|
+
remove(e) {
|
|
57
|
+
if (!this.peers.delete(e) || !e.playing) return;
|
|
58
|
+
let t = this.joins.indexOf(e.player);
|
|
59
|
+
t >= 0 ? this.joins.splice(t, 1) : this.leaves.push(e.player);
|
|
60
|
+
}
|
|
61
|
+
receive(e, r, i) {
|
|
62
|
+
if (!this.peers.has(e)) return;
|
|
63
|
+
let a = this.now();
|
|
64
|
+
if (e.tokens = Math.min(this.burst, e.tokens + (a - e.refilled) * this.rate / 1e3), e.refilled = a, e.tokens < 1) return this.drop(e, t.rateLimit, "too many messages");
|
|
65
|
+
if (e.tokens--, r.length > this.maxBytes) return this.drop(e, t.rateLimit, "message too large");
|
|
66
|
+
e.heard = a;
|
|
67
|
+
let o;
|
|
68
|
+
try {
|
|
69
|
+
o = n(r);
|
|
70
|
+
} catch (n) {
|
|
71
|
+
return this.drop(e, t.protocol, n.message.slice(0, 120));
|
|
72
|
+
}
|
|
73
|
+
if (!e.player && o.kind !== "hello") return this.drop(e, t.protocol, "hello first");
|
|
74
|
+
try {
|
|
75
|
+
this.handle(e, o, a);
|
|
76
|
+
} catch (n) {
|
|
77
|
+
if (n instanceof RangeError || n instanceof TypeError) return this.drop(e, t.protocol, n.message.slice(0, 120));
|
|
78
|
+
throw n;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
handle(e, n, i) {
|
|
82
|
+
let a = this.game;
|
|
83
|
+
switch (n.kind) {
|
|
84
|
+
case "hello":
|
|
85
|
+
if (e.player) return this.drop(e, t.protocol, "hello twice");
|
|
86
|
+
if (n.version !== 1 || n.schema !== a.schema.hash) return this.drop(e, t.mismatch, "protocol or schema differs; update the client");
|
|
87
|
+
if (this.players.length >= this.maxPlayers) return this.drop(e, t.full, "server full");
|
|
88
|
+
e.player = this.nextPlayer++, e.playing = !0, this.joins.push(e.player), e.connection.send(r({
|
|
89
|
+
kind: "welcome",
|
|
90
|
+
player: e.player,
|
|
91
|
+
tickRate: a.tickRate,
|
|
92
|
+
tick: this.ticks,
|
|
93
|
+
snapshotEvery: this.snapshotEvery
|
|
94
|
+
}), "reliable");
|
|
95
|
+
return;
|
|
96
|
+
case "ping": {
|
|
97
|
+
let t = Math.min(Math.max((i - this.lastTickAt) / a.tickMs, 0), .999);
|
|
98
|
+
e.connection.send(r({
|
|
99
|
+
kind: "pong",
|
|
100
|
+
time: n.time,
|
|
101
|
+
tick: this.ticks,
|
|
102
|
+
fraction: t
|
|
103
|
+
}), "unreliable");
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
case "inputs":
|
|
107
|
+
n.ack <= this.ticks && n.ack > e.ack && (e.ack = n.ack), n.inputs.forEach((t, r) => {
|
|
108
|
+
let i = n.first + r;
|
|
109
|
+
if (i <= this.ticks) {
|
|
110
|
+
i > e.newest && this.stats.lateInputs++;
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (i > this.ticks + this.ahead || e.inputs.has(i)) {
|
|
114
|
+
e.inputs.has(i) || this.stats.rejectedInputs++;
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
let o = a.schema.decode(a.inputType, t);
|
|
118
|
+
this.options.validateInput && !this.options.validateInput(o, e.player, this.current) ? this.stats.rejectedInputs++ : (e.inputs.set(i, o), i > e.newest && (e.newest = i), this.stats.inputs++);
|
|
119
|
+
});
|
|
120
|
+
return;
|
|
121
|
+
case "message": {
|
|
122
|
+
let r = a.schema.names[n.type];
|
|
123
|
+
if (r === void 0) return this.drop(e, t.protocol, "unknown message type");
|
|
124
|
+
let i = a.schema.decode(r, n.data);
|
|
125
|
+
this.options.onmessage?.(e.player, r, i);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
default: return this.drop(e, t.protocol, `unexpected ${n.kind}`);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
step() {
|
|
132
|
+
if (this.closed) throw e("disposed", "GameServer is closed; create a new GameServer");
|
|
133
|
+
let n = this.game, r = this.ticks + 1, i = this.now(), a = this.current;
|
|
134
|
+
for (let e of [...this.peers]) i - e.heard > this.timeout && this.drop(e, t.timeout, "no messages");
|
|
135
|
+
for (let e of this.leaves.splice(0)) n.leave(a, e);
|
|
136
|
+
for (let e of this.joins.splice(0)) n.join(a, e);
|
|
137
|
+
let o = /* @__PURE__ */ new Map();
|
|
138
|
+
for (let e of this.peers) {
|
|
139
|
+
if (!e.playing) continue;
|
|
140
|
+
let t = e.inputs.get(r);
|
|
141
|
+
t === void 0 ? e.last !== void 0 && (e.missed++, this.stats.missedInputs++) : (e.inputs.delete(r), e.last = t), e.last !== void 0 && o.set(e.player, e.last);
|
|
142
|
+
for (let t of e.inputs.keys()) t <= r && e.inputs.delete(t);
|
|
143
|
+
}
|
|
144
|
+
n.step(a, o, r, 1 / n.tickRate);
|
|
145
|
+
let s = n.schema.encode(n.stateType, a), c = n.schema.decode(n.stateType, s);
|
|
146
|
+
this.current = n.schema.decode(n.stateType, s), this.ticks = r, this.lastTickAt = i, this.stats.ticks++, r % this.snapshotEvery === 0 && this.snapshot(r, c, s);
|
|
147
|
+
}
|
|
148
|
+
snapshot(e, t, n) {
|
|
149
|
+
let i = this.game, a = this.options.view;
|
|
150
|
+
for (let o of this.peers) {
|
|
151
|
+
if (!o.playing) continue;
|
|
152
|
+
let s = o.ack > 0 && o.ack > e - this.keep ? o.sent.get(o.ack) : void 0, c = a ? i.schema.clone(i.stateType, a(t, o.player, s)) : t, l = s === void 0 ? a ? i.schema.encode(i.stateType, c) : n : i.schema.encodeDelta(i.stateType, c, s);
|
|
153
|
+
o.sent.set(e, c), o.sent.delete(e - this.keep);
|
|
154
|
+
let u = r({
|
|
155
|
+
kind: "snapshot",
|
|
156
|
+
tick: e,
|
|
157
|
+
baseline: s === void 0 ? 0 : o.ack,
|
|
158
|
+
input: o.newest,
|
|
159
|
+
missed: o.missed,
|
|
160
|
+
data: l
|
|
161
|
+
});
|
|
162
|
+
this.stats.snapshots++, s !== void 0 && this.stats.deltaSnapshots++, this.stats.snapshotBytes += u.length, o.connection.send(u, "unreliable");
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
send(e, t, n) {
|
|
166
|
+
let i = this.game.schema.names.indexOf(e);
|
|
167
|
+
if (i < 0) throw TypeError(`Schema has no type '${e}'; send one of ${this.game.schema.names.join(", ")}`);
|
|
168
|
+
let a = r({
|
|
169
|
+
kind: "message",
|
|
170
|
+
type: i,
|
|
171
|
+
data: this.game.schema.encode(e, t)
|
|
172
|
+
});
|
|
173
|
+
for (let e of this.peers) e.playing && (n === void 0 || e.player === n) && e.connection.send(a, "reliable");
|
|
174
|
+
}
|
|
175
|
+
kick(e, n = "removed") {
|
|
176
|
+
for (let r of this.peers) r.player === e && this.drop(r, t.removed, n);
|
|
177
|
+
}
|
|
178
|
+
async run({ signal: e } = {}) {
|
|
179
|
+
let t = this.game.tickMs, n = this.now() + t;
|
|
180
|
+
for (; !this.closed && !e?.aborted;) {
|
|
181
|
+
if (await new Promise((t) => {
|
|
182
|
+
let r = setTimeout(i, Math.max(0, n - this.now()));
|
|
183
|
+
function i() {
|
|
184
|
+
e?.removeEventListener("abort", i), clearTimeout(r), t();
|
|
185
|
+
}
|
|
186
|
+
e?.addEventListener("abort", i, { once: !0 });
|
|
187
|
+
}), this.closed || e?.aborted) return;
|
|
188
|
+
let r = this.now();
|
|
189
|
+
for (r - n > 5 * t && (n = r); n <= r && !this.closed;) this.step(), n += t;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
close() {
|
|
193
|
+
if (!this.closed) {
|
|
194
|
+
this.closed = !0;
|
|
195
|
+
for (let e of [...this.peers]) this.peers.delete(e), e.connection.close(t.removed, "server closed");
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
[Symbol.dispose]() {
|
|
199
|
+
this.close();
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
//#endregion
|
|
203
|
+
export { a as t };
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import type { Game } from './game.js';
|
|
2
|
+
import { type Connection } from './transport.js';
|
|
3
|
+
/** Limits on what one client may send. */
|
|
4
|
+
export interface RateLimits {
|
|
5
|
+
/** Messages per second refilled into the client's bucket (default 120). */
|
|
6
|
+
messagesPerSecond?: number;
|
|
7
|
+
/** Bucket size: the most messages in a burst (default 60). */
|
|
8
|
+
burst?: number;
|
|
9
|
+
/** Largest message in bytes (default 4096). */
|
|
10
|
+
maxMessageBytes?: number;
|
|
11
|
+
}
|
|
12
|
+
/** Options of {@link GameServer}. */
|
|
13
|
+
export interface GameServerOptions<State, Input> {
|
|
14
|
+
/** Most players at once, 1 to 65,536 (default 64); one more is closed with `CloseCode.full`. */
|
|
15
|
+
maxPlayers?: number;
|
|
16
|
+
/** Send a snapshot every this many ticks, 1 to 60 (default 1). */
|
|
17
|
+
snapshotEvery?: number;
|
|
18
|
+
/** Ticks of snapshots kept as delta baselines, 2 to 1024 (default 64). */
|
|
19
|
+
history?: number;
|
|
20
|
+
/** Inputs more than this many ticks ahead of the server are dropped (default 2 seconds of ticks). */
|
|
21
|
+
maxInputAhead?: number;
|
|
22
|
+
/**
|
|
23
|
+
* Called for every decoded input before it is buffered; return false to drop it (it counts in
|
|
24
|
+
* `stats.rejectedInputs`). The schema already checked its types and ranges.
|
|
25
|
+
*/
|
|
26
|
+
validateInput?(input: Input, player: number, state: State): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* The part of the state player `player` may see (interest management, hidden information); default all of it.
|
|
29
|
+
* `baseline` is the state that client confirmed, undefined when the snapshot goes in full: what equals it costs no
|
|
30
|
+
* bytes. `InterestManager.view` from `@margoengine/netcode/interest` is one, with a byte budget.
|
|
31
|
+
*/
|
|
32
|
+
view?(state: State, player: number, baseline?: State): State;
|
|
33
|
+
/** Per-client limits; a client over them is closed with `CloseCode.rateLimit`. */
|
|
34
|
+
limits?: RateLimits;
|
|
35
|
+
/** Milliseconds of silence after which a client is closed with `CloseCode.timeout` (default 10,000). */
|
|
36
|
+
timeout?: number;
|
|
37
|
+
/** The clock in milliseconds (default `performance.now`); a test passes the loopback network's time. */
|
|
38
|
+
now?: () => number;
|
|
39
|
+
/** Called with each game message (`client.send`) once its schema bytes decoded. */
|
|
40
|
+
onmessage?(player: number, type: string, value: unknown): void;
|
|
41
|
+
}
|
|
42
|
+
/** Counts since the server started. */
|
|
43
|
+
export interface GameServerStats {
|
|
44
|
+
/** Ticks run. */
|
|
45
|
+
ticks: number;
|
|
46
|
+
/** Inputs buffered. */
|
|
47
|
+
inputs: number;
|
|
48
|
+
/** Inputs that arrived after their tick ran. */
|
|
49
|
+
lateInputs: number;
|
|
50
|
+
/**
|
|
51
|
+
* Inputs dropped by `validateInput` or as too far ahead. The repeated copies of an input that later input messages
|
|
52
|
+
* carry are not counted.
|
|
53
|
+
*/
|
|
54
|
+
rejectedInputs: number;
|
|
55
|
+
/** Ticks a playing client had no input for (its last input was used). */
|
|
56
|
+
missedInputs: number;
|
|
57
|
+
/** Snapshots sent; `deltaSnapshots` of them against a baseline. */
|
|
58
|
+
snapshots: number;
|
|
59
|
+
/** Snapshots sent against a baseline. */
|
|
60
|
+
deltaSnapshots: number;
|
|
61
|
+
/** Snapshot bytes sent. */
|
|
62
|
+
snapshotBytes: number;
|
|
63
|
+
/** Clients closed for breaking the protocol, the limits or the timeout. */
|
|
64
|
+
dropped: number;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The authoritative server of a {@link Game}. Hand it connections with {@link GameServer.accept}; run ticks with
|
|
68
|
+
* {@link GameServer.run} (real time) or {@link GameServer.step} (one tick, for tests and your own loop).
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```ts
|
|
72
|
+
* const server = new GameServer(game);
|
|
73
|
+
* listener.onconnection = (connection) => server.accept(connection);
|
|
74
|
+
* const stop = new AbortController();
|
|
75
|
+
* await server.run({ signal: stop.signal });
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
export declare class GameServer<State, Input> {
|
|
79
|
+
readonly game: Game<State, Input>;
|
|
80
|
+
private readonly options;
|
|
81
|
+
/** Counts since the server started. */
|
|
82
|
+
readonly stats: GameServerStats;
|
|
83
|
+
private current;
|
|
84
|
+
private ticks;
|
|
85
|
+
private lastTickAt;
|
|
86
|
+
private nextPlayer;
|
|
87
|
+
private closed;
|
|
88
|
+
private readonly peers;
|
|
89
|
+
private readonly joins;
|
|
90
|
+
private readonly leaves;
|
|
91
|
+
private readonly now;
|
|
92
|
+
private readonly maxPlayers;
|
|
93
|
+
private readonly snapshotEvery;
|
|
94
|
+
private readonly keep;
|
|
95
|
+
private readonly ahead;
|
|
96
|
+
private readonly timeout;
|
|
97
|
+
private readonly rate;
|
|
98
|
+
private readonly burst;
|
|
99
|
+
private readonly maxBytes;
|
|
100
|
+
/**
|
|
101
|
+
* @throws RangeError for an option out of range.
|
|
102
|
+
*/
|
|
103
|
+
constructor(game: Game<State, Input>, options?: GameServerOptions<State, Input>);
|
|
104
|
+
/** The newest tick run (0 before the first). */
|
|
105
|
+
get tick(): number;
|
|
106
|
+
/** The authoritative state after {@link GameServer.tick}. Replaced every tick: read it again after each. */
|
|
107
|
+
get state(): State;
|
|
108
|
+
/** Ids of the players in the game. */
|
|
109
|
+
get players(): number[];
|
|
110
|
+
private canonical;
|
|
111
|
+
/**
|
|
112
|
+
* Takes a new client connection: it joins the game once its hello matches this server's protocol and schema.
|
|
113
|
+
* @throws MargoError `disposed` once the server is closed.
|
|
114
|
+
*/
|
|
115
|
+
accept(connection: Connection): void;
|
|
116
|
+
private drop;
|
|
117
|
+
private remove;
|
|
118
|
+
private receive;
|
|
119
|
+
private handle;
|
|
120
|
+
/**
|
|
121
|
+
* Runs one tick: joins and leaves, then the game's step with each player's input for this tick (its last input
|
|
122
|
+
* when this one has not arrived), then snapshots.
|
|
123
|
+
* @throws MargoError `disposed` once the server is closed.
|
|
124
|
+
*/
|
|
125
|
+
step(): void;
|
|
126
|
+
private snapshot;
|
|
127
|
+
/**
|
|
128
|
+
* Sends game message `value` of schema struct `type` to player `player` (or to every player when `player` is
|
|
129
|
+
* omitted), reliably.
|
|
130
|
+
* @throws TypeError or RangeError when `value` does not fit `type`.
|
|
131
|
+
*/
|
|
132
|
+
send(type: string, value: unknown, player?: number): void;
|
|
133
|
+
/** Closes player `player`'s connection with `CloseCode.removed`; it leaves at the next tick. */
|
|
134
|
+
kick(player: number, reason?: string): void;
|
|
135
|
+
/**
|
|
136
|
+
* Runs ticks in real time until `signal` aborts or the server closes. Each tick is scheduled from a fixed start
|
|
137
|
+
* time, so the rate does not drift with timer error; after a stall of more than 5 ticks it skips ahead rather
|
|
138
|
+
* than running a burst.
|
|
139
|
+
*/
|
|
140
|
+
run({ signal }?: {
|
|
141
|
+
signal?: AbortSignal;
|
|
142
|
+
}): Promise<void>;
|
|
143
|
+
/** Closes every connection with `CloseCode.removed` and stops {@link GameServer.run}. */
|
|
144
|
+
close(): void;
|
|
145
|
+
/** Same as {@link GameServer.close}, for `using`. */
|
|
146
|
+
[Symbol.dispose](): void;
|
|
147
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** Signed integer to an unsigned one, small magnitudes small. */
|
|
2
|
+
export function zigzag(n: number): number;
|
|
3
|
+
/** The inverse of {@link zigzag}. */
|
|
4
|
+
export function unzigzag(z: number): number;
|
|
5
|
+
/** The parts laid end to end in one new array. */
|
|
6
|
+
export function concatBytes(parts: readonly Uint8Array[]): Uint8Array<ArrayBuffer>;
|
|
7
|
+
/** A growing little-endian byte buffer. */
|
|
8
|
+
export class ByteWriter {
|
|
9
|
+
bytes: Uint8Array;
|
|
10
|
+
view: DataView;
|
|
11
|
+
at: number;
|
|
12
|
+
constructor(size?: number);
|
|
13
|
+
room(n: number): void;
|
|
14
|
+
u8(v: number): void;
|
|
15
|
+
u16(v: number): void;
|
|
16
|
+
u32(v: number): void;
|
|
17
|
+
f32(v: number): void;
|
|
18
|
+
varint(v: number): void;
|
|
19
|
+
raw(b: Uint8Array): void;
|
|
20
|
+
done(): Uint8Array<ArrayBuffer>;
|
|
21
|
+
}
|
|
22
|
+
/** Checked little-endian reads; failures throw RangeError `"<what> <problem>; <fix>"`. */
|
|
23
|
+
export class ByteReader {
|
|
24
|
+
readonly bytes: Uint8Array;
|
|
25
|
+
readonly view: DataView;
|
|
26
|
+
readonly what: string;
|
|
27
|
+
readonly fix: string;
|
|
28
|
+
at: number;
|
|
29
|
+
constructor(bytes: Uint8Array, what: string, fix: string, start?: number);
|
|
30
|
+
fail(problem: string, fix?: string): RangeError;
|
|
31
|
+
need(n: number): void;
|
|
32
|
+
u8(): number;
|
|
33
|
+
u16(): number;
|
|
34
|
+
u32(): number;
|
|
35
|
+
f32(): number;
|
|
36
|
+
varint(): number;
|
|
37
|
+
end(): void;
|
|
38
|
+
}
|