tickflare 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/CHANGELOG.md +240 -0
  2. package/LICENSE +21 -0
  3. package/README.md +112 -2
  4. package/dist/binary.d.ts +91 -0
  5. package/dist/binary.js +466 -0
  6. package/dist/binary.js.map +1 -0
  7. package/dist/client/accounts.d.ts +193 -0
  8. package/dist/client/accounts.js +306 -0
  9. package/dist/client/accounts.js.map +1 -0
  10. package/dist/client/buffered.d.ts +88 -0
  11. package/dist/client/buffered.js +229 -0
  12. package/dist/client/buffered.js.map +1 -0
  13. package/dist/client/clock.d.ts +36 -0
  14. package/dist/client/clock.js +83 -0
  15. package/dist/client/clock.js.map +1 -0
  16. package/dist/client/draft.d.ts +17 -0
  17. package/dist/client/draft.js +133 -0
  18. package/dist/client/draft.js.map +1 -0
  19. package/dist/client/index.d.ts +182 -0
  20. package/dist/client/index.js +496 -0
  21. package/dist/client/index.js.map +1 -0
  22. package/dist/client/interpolate.d.ts +31 -0
  23. package/dist/client/interpolate.js +59 -0
  24. package/dist/client/interpolate.js.map +1 -0
  25. package/dist/client/lockstep.d.ts +86 -0
  26. package/dist/client/lockstep.js +339 -0
  27. package/dist/client/lockstep.js.map +1 -0
  28. package/dist/client/matchmaking.d.ts +21 -0
  29. package/dist/client/matchmaking.js +55 -0
  30. package/dist/client/matchmaking.js.map +1 -0
  31. package/dist/client/pacer.d.ts +22 -0
  32. package/dist/client/pacer.js +65 -0
  33. package/dist/client/pacer.js.map +1 -0
  34. package/dist/client/predict.d.ts +75 -0
  35. package/dist/client/predict.js +203 -0
  36. package/dist/client/predict.js.map +1 -0
  37. package/dist/client/token.d.ts +10 -0
  38. package/dist/client/token.js +15 -0
  39. package/dist/client/token.js.map +1 -0
  40. package/dist/lockstep.d.ts +154 -0
  41. package/dist/lockstep.js +140 -0
  42. package/dist/lockstep.js.map +1 -0
  43. package/dist/patch.d.ts +54 -0
  44. package/dist/patch.js +186 -0
  45. package/dist/patch.js.map +1 -0
  46. package/dist/protocol.d.ts +268 -0
  47. package/dist/protocol.js +54 -0
  48. package/dist/protocol.js.map +1 -0
  49. package/dist/server/accounts.d.ts +320 -0
  50. package/dist/server/accounts.js +1223 -0
  51. package/dist/server/accounts.js.map +1 -0
  52. package/dist/server/delta.d.ts +50 -0
  53. package/dist/server/delta.js +426 -0
  54. package/dist/server/delta.js.map +1 -0
  55. package/dist/server/frames.d.ts +15 -0
  56. package/dist/server/frames.js +23 -0
  57. package/dist/server/frames.js.map +1 -0
  58. package/dist/server/gateway.d.ts +80 -0
  59. package/dist/server/gateway.js +144 -0
  60. package/dist/server/gateway.js.map +1 -0
  61. package/dist/server/index.d.ts +21 -0
  62. package/dist/server/index.js +22 -0
  63. package/dist/server/index.js.map +1 -0
  64. package/dist/server/limiter.d.ts +12 -0
  65. package/dist/server/limiter.js +43 -0
  66. package/dist/server/limiter.js.map +1 -0
  67. package/dist/server/lockstep.d.ts +127 -0
  68. package/dist/server/lockstep.js +549 -0
  69. package/dist/server/lockstep.js.map +1 -0
  70. package/dist/server/matches.d.ts +31 -0
  71. package/dist/server/matches.js +69 -0
  72. package/dist/server/matches.js.map +1 -0
  73. package/dist/server/matchmaker.d.ts +121 -0
  74. package/dist/server/matchmaker.js +479 -0
  75. package/dist/server/matchmaker.js.map +1 -0
  76. package/dist/server/room.d.ts +402 -0
  77. package/dist/server/room.js +1896 -0
  78. package/dist/server/room.js.map +1 -0
  79. package/dist/server/signals.d.ts +18 -0
  80. package/dist/server/signals.js +37 -0
  81. package/dist/server/signals.js.map +1 -0
  82. package/dist/server/storage.d.ts +117 -0
  83. package/dist/server/storage.js +330 -0
  84. package/dist/server/storage.js.map +1 -0
  85. package/dist/server/tokens.d.ts +74 -0
  86. package/dist/server/tokens.js +117 -0
  87. package/dist/server/tokens.js.map +1 -0
  88. package/dist/server/tracked.d.ts +47 -0
  89. package/dist/server/tracked.js +270 -0
  90. package/dist/server/tracked.js.map +1 -0
  91. package/dist/world.d.ts +20 -0
  92. package/dist/world.js +21 -0
  93. package/dist/world.js.map +1 -0
  94. package/package.json +74 -4
  95. package/src/binary.ts +496 -0
  96. package/src/client/accounts.ts +423 -0
  97. package/src/client/buffered.ts +264 -0
  98. package/src/client/clock.ts +86 -0
  99. package/src/client/draft.ts +138 -0
  100. package/src/client/index.ts +631 -0
  101. package/src/client/interpolate.ts +60 -0
  102. package/src/client/lockstep.ts +398 -0
  103. package/src/client/matchmaking.ts +61 -0
  104. package/src/client/pacer.ts +67 -0
  105. package/src/client/predict.ts +239 -0
  106. package/src/client/token.ts +22 -0
  107. package/src/lockstep.ts +285 -0
  108. package/src/patch.ts +188 -0
  109. package/src/protocol.ts +300 -0
  110. package/src/server/accounts.ts +1474 -0
  111. package/src/server/delta.ts +467 -0
  112. package/src/server/frames.ts +23 -0
  113. package/src/server/gateway.ts +213 -0
  114. package/src/server/index.ts +86 -0
  115. package/src/server/limiter.ts +41 -0
  116. package/src/server/lockstep.ts +617 -0
  117. package/src/server/matches.ts +99 -0
  118. package/src/server/matchmaker.ts +537 -0
  119. package/src/server/room.ts +1999 -0
  120. package/src/server/signals.ts +46 -0
  121. package/src/server/storage.ts +392 -0
  122. package/src/server/tokens.ts +184 -0
  123. package/src/server/tracked.ts +260 -0
  124. package/src/world.ts +29 -0
  125. package/tools/rooms-report.mjs +168 -0
@@ -0,0 +1,423 @@
1
+ import type { TokenSource } from "./token.js";
2
+
3
+ /*
4
+ * The client side of `Accounts`: sign up, sign in, a guest identity before
5
+ * that, the player's own data, profiles and leaderboards.
6
+ */
7
+
8
+ /** Where the accounts API is and how the session travels. Every option has a default. */
9
+ export interface AccountClientOptions {
10
+ /** Where the Worker is, e.g. "https://game.example.com". Defaults to the page's own origin. */
11
+ baseUrl?: string;
12
+ /** Where the accounts API is served. Default "/api/accounts". */
13
+ prefix?: string;
14
+ /**
15
+ * How the session travels. "cookie" (the default in browsers): an HttpOnly
16
+ * cookie the page's scripts never see. "bearer" (the default elsewhere):
17
+ * the client keeps the session token and sends it with every request; pass
18
+ * `session` to restore one and `onSession` to keep it.
19
+ */
20
+ mode?: "cookie" | "bearer";
21
+ /** A session token to start with, in bearer mode. */
22
+ session?: string | null;
23
+ /** Called when the session token changes, in bearer mode: store it to stay signed in. */
24
+ onSession?(token: string | null): void;
25
+ /** Where to keep the guest identity between visits. Defaults to `localStorage` when there is one. */
26
+ storage?: KeyValueStore | null;
27
+ /** The fetch to use. Defaults to the global one. */
28
+ fetch?: typeof fetch;
29
+ }
30
+
31
+ /** The signed-in player's own account, as `GET /me` returns it. */
32
+ export interface Account {
33
+ /** The player id. A guest who registered keeps theirs. */
34
+ id: string;
35
+ /** The account name. */
36
+ name: string;
37
+ /** The email address, if one was given. */
38
+ email: string | null;
39
+ /** When the account was made, in epoch milliseconds. */
40
+ createdAt: number;
41
+ /** Whether the account has a recovery code. */
42
+ recoveryCode: boolean;
43
+ /** Every data key the player has, private ones included. */
44
+ data: Record<string, unknown>;
45
+ /** Every stat the player has. */
46
+ stats: Record<string, number>;
47
+ }
48
+
49
+ /** What anyone may see of a player. */
50
+ export interface Profile {
51
+ /** The player id. */
52
+ id: string;
53
+ /** The account name. */
54
+ name: string;
55
+ /** When the account was made, in epoch milliseconds. */
56
+ createdAt: number;
57
+ /** The data keys the game made public. */
58
+ data: Record<string, unknown>;
59
+ /** Every stat the player has. */
60
+ stats: Record<string, number>;
61
+ }
62
+
63
+ /** One line of a leaderboard. */
64
+ export interface LeaderboardLine {
65
+ /** 1 for the highest value. Players with the same value share a rank. */
66
+ rank: number;
67
+ /** The player id. */
68
+ id: string;
69
+ /** The account name. */
70
+ name: string;
71
+ /** The player's value of the stat. */
72
+ value: number;
73
+ }
74
+
75
+ /** A page of a leaderboard, highest value first. */
76
+ export interface Leaderboard {
77
+ /** The stat it ranks. */
78
+ stat: string;
79
+ /** This page's lines. */
80
+ entries: LeaderboardLine[];
81
+ /** Players with a value for this stat, in total. */
82
+ total: number;
83
+ }
84
+
85
+ /** A guest identity: a player id with a join token, before or instead of an account. */
86
+ export interface Guest {
87
+ /** The guest's player id. */
88
+ id: string;
89
+ /** A join token for `id`. */
90
+ token: string;
91
+ /** When the token stops working, in epoch milliseconds. */
92
+ expiresAt: number;
93
+ /** When the client renews it for the same id, in epoch milliseconds. */
94
+ renewAt: number;
95
+ }
96
+
97
+ /** A request the accounts API refused. `code` is machine-readable, e.g. "name_taken" or "invalid_credentials". */
98
+ export class AccountRequestError extends Error {
99
+ /** The HTTP status, e.g. 409. */
100
+ readonly status: number;
101
+ /** Machine-readable, e.g. `name_taken`. */
102
+ readonly code: string;
103
+
104
+ constructor(status: number, code: string, message: string) {
105
+ super(message);
106
+ this.name = "AccountRequestError";
107
+ this.status = status;
108
+ this.code = code;
109
+ }
110
+ }
111
+
112
+ /** The part of `localStorage` the client uses. */
113
+ export interface KeyValueStore {
114
+ /** The value under `key`, or null. */
115
+ getItem(key: string): string | null;
116
+ /** Stores `value` under `key`. */
117
+ setItem(key: string, value: string): void;
118
+ /** Removes `key`. */
119
+ removeItem(key: string): void;
120
+ }
121
+
122
+ const GUEST_KEY = "tickflare.guest";
123
+ /** What a browser has, seen from code that is not typed for one. */
124
+ const browser = globalThis as { document?: unknown; location?: { origin: string }; localStorage?: KeyValueStore };
125
+
126
+ /**
127
+ * The client side of `Accounts`: a guest identity until the player signs up,
128
+ * sign-up and sign-in, the player's own data, profiles and leaderboards.
129
+ *
130
+ * const accounts = new AccountClient();
131
+ * await accounts.restore();
132
+ * const room = new RoomClient(url, { token: accounts.tokenSource });
133
+ */
134
+ export class AccountClient {
135
+ #account: Account | null = null;
136
+
137
+ readonly #base: string;
138
+ readonly #mode: "cookie" | "bearer";
139
+ readonly #fetch: typeof fetch;
140
+ readonly #storage: AccountClientOptions["storage"];
141
+ readonly #onSession: AccountClientOptions["onSession"];
142
+ #session: string | null;
143
+ #guest: Guest | null = null;
144
+ #listeners = new Set<(account: Account | null) => void>();
145
+
146
+ constructor(options: AccountClientOptions = {}) {
147
+ const inBrowser = browser.document !== undefined;
148
+ const origin = options.baseUrl ?? browser.location?.origin ?? "";
149
+ this.#base = `${origin.replace(/\/+$/, "")}${(options.prefix ?? "/api/accounts").replace(/\/+$/, "")}`;
150
+ this.#mode = options.mode ?? (inBrowser ? "cookie" : "bearer");
151
+ this.#session = options.session ?? null;
152
+ this.#onSession = options.onSession;
153
+ this.#fetch = options.fetch ?? ((input, init) => fetch(input, init));
154
+ this.#storage = options.storage !== undefined ? options.storage : (browser.localStorage ?? null);
155
+ }
156
+
157
+ /** The signed-in account, once `restore`, `login` or `register` has found one. */
158
+ get account(): Account | null {
159
+ return this.#account;
160
+ }
161
+
162
+ /** Whether someone is signed in. */
163
+ get signedIn(): boolean {
164
+ return this.#account !== null;
165
+ }
166
+
167
+ /** The player id to use: the account's, else the guest's, else undefined. */
168
+ get playerId(): string | undefined {
169
+ return this.#account?.id ?? this.#guest?.id ?? this.#storedGuest()?.id;
170
+ }
171
+
172
+ /** Calls `listener` whenever the signed-in account changes. Returns a function that stops it. */
173
+ onChange(listener: (account: Account | null) => void): () => void {
174
+ this.#listeners.add(listener);
175
+ return () => this.#listeners.delete(listener);
176
+ }
177
+
178
+ /** Finds out whether a session is still good. Call once at startup. */
179
+ async restore(): Promise<Account | null> {
180
+ if (this.#mode === "bearer" && !this.#session) return this.#setAccount(null);
181
+ try {
182
+ return this.#setAccount(await this.#request<Account>("GET", "/me"));
183
+ } catch (error) {
184
+ if (error instanceof AccountRequestError && error.status === 401) {
185
+ this.#setSession(null);
186
+ return this.#setAccount(null);
187
+ }
188
+ throw error;
189
+ }
190
+ }
191
+
192
+ /** Creates an account and signs in. A guest who registers keeps their player id. */
193
+ async register(input: { name: string; password: string; email?: string }): Promise<Account> {
194
+ const guest = this.#guest ?? this.#storedGuest();
195
+ const body = guest && guest.expiresAt > Date.now() ? { ...input, guestToken: guest.token } : input;
196
+ const result = await this.#request<{ account: Account; token: string }>("POST", "/register", body);
197
+ this.#forgetGuest();
198
+ this.#setSession(result.token);
199
+ this.#setAccount(result.account);
200
+ return result.account;
201
+ }
202
+
203
+ /** Signs in. Rejects with `AccountRequestError` (`invalid_credentials`, `too_many_attempts`) if it cannot. */
204
+ async login(name: string, password: string): Promise<Account> {
205
+ const result = await this.#request<{ account: Account; token: string }>("POST", "/login", { name, password });
206
+ this.#setSession(result.token);
207
+ this.#setAccount(result.account);
208
+ return result.account;
209
+ }
210
+
211
+ /** Ends the session, on the server and here. */
212
+ async logout(): Promise<void> {
213
+ try {
214
+ await this.#request("POST", "/logout");
215
+ } finally {
216
+ this.#setSession(null);
217
+ this.#setAccount(null);
218
+ }
219
+ }
220
+
221
+ /** Changes the password. Every other session of the account is signed out. */
222
+ async changePassword(current: string, next: string): Promise<void> {
223
+ const result = await this.#request<{ account: Account; token: string }>("POST", "/password", { current, next });
224
+ this.#setSession(result.token);
225
+ this.#setAccount(result.account);
226
+ }
227
+
228
+ /**
229
+ * Makes a recovery code and returns it: show it to the player once, to
230
+ * keep somewhere safe. It sets a new password with `recover`, with no
231
+ * email involved, and replaces the code the account had. Needs the password.
232
+ */
233
+ async createRecoveryCode(password: string): Promise<string> {
234
+ const result = await this.#request<{ code: string }>("POST", "/recovery-code", { password });
235
+ if (this.#account) this.#setAccount({ ...this.#account, recoveryCode: true });
236
+ return result.code;
237
+ }
238
+
239
+ /**
240
+ * Sets a new password with a recovery code, and signs in. The code is used
241
+ * up. Rejects with `AccountRequestError` (`invalid_code`, `too_many_attempts`).
242
+ */
243
+ async recover(name: string, code: string, password: string): Promise<Account> {
244
+ const result = await this.#request<{ account: Account; token: string }>("POST", "/recover", { name, code, password });
245
+ this.#setSession(result.token);
246
+ this.#setAccount(result.account);
247
+ return result.account;
248
+ }
249
+
250
+ /**
251
+ * Asks for a password reset link to be sent to the account with this name,
252
+ * or to every account with this email address. It resolves whether or not
253
+ * there is such an account, so as not to tell. Rejects with `not_enabled`
254
+ * if the game does not send email.
255
+ */
256
+ async forgotPassword(who: { name: string } | { email: string }): Promise<void> {
257
+ await this.#request("POST", "/forgot", who);
258
+ }
259
+
260
+ /** Sets a new password with the token from a reset link, and signs in. Rejects with `invalid_token`. */
261
+ async resetPassword(token: string, password: string): Promise<Account> {
262
+ const result = await this.#request<{ account: Account; token: string }>("POST", "/reset", { token, password });
263
+ this.#setSession(result.token);
264
+ this.#setAccount(result.account);
265
+ return result.account;
266
+ }
267
+
268
+ /** Takes another name. */
269
+ async rename(name: string): Promise<Account> {
270
+ const account = await this.#request<Account>("POST", "/name", { name });
271
+ this.#account = account;
272
+ return account;
273
+ }
274
+
275
+ /** Sets the email address, or removes it with null. Needs the password. */
276
+ async setEmail(password: string, email: string | null): Promise<Account> {
277
+ const account = await this.#request<Account>("POST", "/email", { password, email });
278
+ this.#account = account;
279
+ return account;
280
+ }
281
+
282
+ /** Deletes the account and everything stored with it. */
283
+ async deleteAccount(password: string): Promise<void> {
284
+ await this.#request("DELETE", "/me", { password });
285
+ this.#setSession(null);
286
+ this.#setAccount(null);
287
+ }
288
+
289
+ /** Everything the server keeps about the signed-in player. */
290
+ async exportData(): Promise<Record<string, unknown>> {
291
+ return this.#request("GET", "/export");
292
+ }
293
+
294
+ /**
295
+ * A guest identity, made on first use and kept in `storage`. Its token is
296
+ * renewed, for the same player id, once it is half way to expiring; a
297
+ * guest who stays away until it has expired starts over as a new player.
298
+ */
299
+ async guest(): Promise<Guest> {
300
+ const known = this.#guest ?? this.#storedGuest();
301
+ if (known && known.renewAt > Date.now()) return (this.#guest = known);
302
+ const guest = await this.#request<Guest>("POST", "/guest", known ? { token: known.token } : undefined);
303
+ this.#guest = guest;
304
+ try {
305
+ this.#storage?.setItem(GUEST_KEY, JSON.stringify(guest));
306
+ } catch {
307
+ // Storage full or blocked: the guest lasts for this visit.
308
+ }
309
+ return guest;
310
+ }
311
+
312
+ /** A short-lived join token for a room or queue, for the signed-in player. */
313
+ async joinToken(scope?: string): Promise<string> {
314
+ const result = await this.#request<{ token: string }>("POST", "/token", scope === undefined ? {} : { scope });
315
+ return result.token;
316
+ }
317
+
318
+ /**
319
+ * For `RoomClient`'s `token` option: a join token for the signed-in player,
320
+ * or the guest's token for anyone else.
321
+ */
322
+ readonly tokenSource: TokenSource = async (room) => {
323
+ if (this.#account) return this.joinToken(room);
324
+ return (await this.guest()).token;
325
+ };
326
+
327
+ /** The signed-in player's value under `key`, or undefined. */
328
+ async getData<T = unknown>(key: string): Promise<T | undefined> {
329
+ try {
330
+ return (await this.#request<{ value: T }>("GET", `/data/${encodeURIComponent(key)}`)).value;
331
+ } catch (error) {
332
+ if (error instanceof AccountRequestError && error.status === 404) return undefined;
333
+ throw error;
334
+ }
335
+ }
336
+
337
+ /** Stores a value under a key the game lets players write. */
338
+ async setData(key: string, value: unknown): Promise<void> {
339
+ await this.#request("PUT", `/data/${encodeURIComponent(key)}`, { value });
340
+ if (this.#account) this.#account = { ...this.#account, data: { ...this.#account.data, [key]: value } };
341
+ }
342
+
343
+ /** Removes a value under a key the game lets players write. */
344
+ async deleteData(key: string): Promise<void> {
345
+ await this.#request("DELETE", `/data/${encodeURIComponent(key)}`);
346
+ if (this.#account) {
347
+ const { [key]: _removed, ...data } = this.#account.data;
348
+ this.#account = { ...this.#account, data };
349
+ }
350
+ }
351
+
352
+ /** A player's public profile, or null if there is no such account. */
353
+ async profile(playerId: string): Promise<Profile | null> {
354
+ try {
355
+ return await this.#request<Profile>("GET", `/players/${encodeURIComponent(playerId)}`);
356
+ } catch (error) {
357
+ if (error instanceof AccountRequestError && error.status === 404) return null;
358
+ throw error;
359
+ }
360
+ }
361
+
362
+ /** A page of the leaderboard for `stat`, highest first. */
363
+ async leaderboard(stat: string, page: { limit?: number; offset?: number } = {}): Promise<Leaderboard> {
364
+ const query = new URLSearchParams();
365
+ if (page.limit !== undefined) query.set("limit", String(page.limit));
366
+ if (page.offset !== undefined) query.set("offset", String(page.offset));
367
+ const suffix = query.size > 0 ? `?${query}` : "";
368
+ return this.#request("GET", `/leaderboards/${encodeURIComponent(stat)}${suffix}`);
369
+ }
370
+
371
+ async #request<T = unknown>(method: string, path: string, body?: unknown): Promise<T> {
372
+ const headers: Record<string, string> = {};
373
+ if (body !== undefined) headers["Content-Type"] = "application/json";
374
+ if (this.#mode === "bearer" && this.#session) headers.Authorization = `Bearer ${this.#session}`;
375
+ const init: RequestInit & { credentials?: "include" } = {
376
+ method,
377
+ headers,
378
+ body: body === undefined ? undefined : JSON.stringify(body),
379
+ };
380
+ // So the cookie also travels when the API is on another origin. Not set otherwise:
381
+ // runtimes other than browsers may not know the option.
382
+ if (this.#mode === "cookie") init.credentials = "include";
383
+ const response = await this.#fetch(`${this.#base}${path}`, init);
384
+ if (response.status === 204) return undefined as T;
385
+ const payload = (await response.json().catch(() => null)) as { error?: string; message?: string } | null;
386
+ if (!response.ok) {
387
+ throw new AccountRequestError(response.status, payload?.error ?? "request_failed", payload?.message ?? response.statusText);
388
+ }
389
+ return payload as T;
390
+ }
391
+
392
+ #setSession(token: string | null): void {
393
+ if (this.#mode !== "bearer" || this.#session === token) return;
394
+ this.#session = token;
395
+ this.#onSession?.(token);
396
+ }
397
+
398
+ #setAccount(account: Account | null): Account | null {
399
+ const changed = this.#account?.id !== account?.id;
400
+ this.#account = account;
401
+ if (changed) for (const listener of this.#listeners) listener(account);
402
+ return account;
403
+ }
404
+
405
+ #storedGuest(): Guest | null {
406
+ try {
407
+ const raw = this.#storage?.getItem(GUEST_KEY);
408
+ const guest = raw ? (JSON.parse(raw) as Guest) : null;
409
+ return guest && typeof guest.token === "string" && guest.expiresAt > Date.now() ? guest : null;
410
+ } catch {
411
+ return null;
412
+ }
413
+ }
414
+
415
+ #forgetGuest(): void {
416
+ this.#guest = null;
417
+ try {
418
+ this.#storage?.removeItem(GUEST_KEY);
419
+ } catch {
420
+ // Nothing to forget.
421
+ }
422
+ }
423
+ }
@@ -0,0 +1,264 @@
1
+ import { ServerClock, localNow } from "./clock.js";
2
+
3
+ /** What `BufferedInterpolator` reads the ticks from: a `RoomClient` will do. */
4
+ export interface TickSource {
5
+ /** The tick of the latest state: read when `update` is called. */
6
+ readonly tick: number;
7
+ /** Ticks a second; 0 in event mode. */
8
+ readonly tickRate: number;
9
+ /** The tick the room is on at `now`, by estimate, as `RoomClient.serverTick` gives it. */
10
+ serverTick?(now?: number): number | undefined;
11
+ }
12
+
13
+ /** Settings for `BufferedInterpolator`. */
14
+ export interface BufferedInterpolatorOptions<Field extends string> {
15
+ /**
16
+ * How far behind the newest state it expects to have, in ticks, before the
17
+ * margin for jitter is added. 2 by default: a patch can be a tick late, or
18
+ * cover two ticks, without anything having to be guessed.
19
+ */
20
+ delayTicks?: number;
21
+ /**
22
+ * For how many ticks a thing keeps moving at its last speed when no newer
23
+ * state has arrived for it, before it stops where it got to. 3 by default;
24
+ * 0 stops it at its last known place.
25
+ */
26
+ maxExtrapolationTicks?: number;
27
+ /**
28
+ * A change between two states in a row farther than this, measured over
29
+ * the fields that are not angles, is a jump: drawn as one, when the time
30
+ * comes, instead of a slide. Off by default. Set it above the farthest
31
+ * anything moves between two patches.
32
+ */
33
+ snapDistance?: number;
34
+ /** Fields that are angles in radians, which go the short way round through ±π. */
35
+ angles?: readonly Field[];
36
+ }
37
+
38
+ interface Snapshot<Field extends string> {
39
+ tick: number;
40
+ values: Record<Field, number>;
41
+ /** It was a jump from the one before. */
42
+ snap: boolean;
43
+ }
44
+
45
+ /** Snapshots kept per id at the most, whatever the delay. */
46
+ const MAX_SNAPSHOTS = 64;
47
+
48
+ /**
49
+ * Smooths values that arrive once per tick by drawing them a little in the
50
+ * past, at an even pace, from the ticks they belong to.
51
+ *
52
+ * `Interpolator` glides to each new value as it arrives: it adds almost no
53
+ * delay, but things speed up when two patches arrive together and stop when
54
+ * one is late. This one keeps the last few states of each id, keyed by the
55
+ * room's tick, and draws the moment `delay` ticks behind the tick the room
56
+ * is on (`RoomClient.serverTick()`), blending the states on either side.
57
+ * Motion then keeps the pace of the room, whatever the network does to the
58
+ * patches, at the cost of the delay: two ticks and a margin for the jitter
59
+ * it measures, which it keeps adjusting.
60
+ *
61
+ * When the newest state is older than the moment it draws, it carries each
62
+ * thing on at its last speed for up to `maxExtrapolationTicks`, then holds
63
+ * it. A jump, such as a respawn, is drawn as one: say so with `snap(id)`, or
64
+ * set `snapDistance`.
65
+ *
66
+ * const glide = new BufferedInterpolator(room, ["x", "y"], { snapDistance: 200 });
67
+ * room.on("state", (state) => glide.update(state.units));
68
+ * // in the render loop:
69
+ * const { x, y } = glide.at(id) ?? state.units[id];
70
+ *
71
+ * Against a room older than 0.2, which does not say where its clock is, it
72
+ * times the patches as they arrive instead.
73
+ */
74
+ export class BufferedInterpolator<Field extends string> {
75
+ readonly #source: TickSource;
76
+ readonly #fields: readonly Field[];
77
+ readonly #angles: ReadonlySet<Field>;
78
+ readonly #delayTicks: number;
79
+ readonly #maxExtrapolation: number;
80
+ readonly #snapDistance: number;
81
+ #tracks = new Map<string, Snapshot<Field>[]>();
82
+ /** Times the patches as they arrive, for a room that does not say where its clock is. */
83
+ #arrivals = new ServerClock();
84
+ /** How many ticks behind the room's clock a state arrives, smoothed, and how much that varies. */
85
+ #lateness: number | undefined;
86
+ #jitter = 0;
87
+ #newestTick = -Infinity;
88
+ /** The latest moment drawn, and when it was asked for: what is drawn never goes back. */
89
+ #shown: { tick: number; now: number } | undefined;
90
+
91
+ /**
92
+ * @param source where the ticks come from: the `RoomClient`
93
+ * @param fields the numeric fields to smooth, e.g. `["x", "y"]`
94
+ * @param options see `BufferedInterpolatorOptions`
95
+ */
96
+ constructor(source: TickSource, fields: readonly Field[], options: BufferedInterpolatorOptions<Field> = {}) {
97
+ this.#source = source;
98
+ this.#fields = fields;
99
+ this.#angles = new Set(options.angles ?? []);
100
+ this.#delayTicks = Math.max(0, options.delayTicks ?? 2);
101
+ this.#maxExtrapolation = Math.max(0, options.maxExtrapolationTicks ?? 3);
102
+ this.#snapDistance = options.snapDistance ?? Infinity;
103
+ }
104
+
105
+ /** The delay it draws at right now, in ticks behind the room's clock: see the class. */
106
+ get delay(): number {
107
+ return (this.#lateness ?? 0) + this.#delayTicks + 2 * this.#jitter;
108
+ }
109
+
110
+ /**
111
+ * Feed the latest values, keyed by id, as of tick `tick`: the source's
112
+ * latest unless given. Ids missing from `targets` are forgotten.
113
+ *
114
+ * @param now when they arrived, from `performance.now()`
115
+ */
116
+ update(targets: Record<string, Record<Field, number>>, tick = this.#source.tick, now = localNow()): void {
117
+ if (tick < this.#newestTick) {
118
+ // The room went back to a save: what was kept is of a timeline that no longer is.
119
+ this.#tracks.clear();
120
+ this.#arrivals.reset();
121
+ this.#lateness = undefined;
122
+ this.#jitter = 0;
123
+ this.#shown = undefined;
124
+ }
125
+ if (tick > this.#newestTick) {
126
+ this.#newestTick = tick;
127
+ this.#measure(tick, now);
128
+ }
129
+ const drawn = this.#shown?.tick ?? -Infinity;
130
+ const tracks = new Map<string, Snapshot<Field>[]>();
131
+ for (const id of Object.keys(targets)) {
132
+ const target = targets[id]!;
133
+ const values = {} as Record<Field, number>;
134
+ for (const field of this.#fields) values[field] = target[field];
135
+ const track = this.#tracks.get(id) ?? [];
136
+ const last = track[track.length - 1];
137
+ if (last?.tick === tick) {
138
+ last.values = values;
139
+ } else {
140
+ track.push({ tick, values, snap: last !== undefined && this.#distance(last.values, values) > this.#snapDistance });
141
+ }
142
+ // What lies behind the moment drawn is no longer needed, apart from the one it starts from.
143
+ let drop = 0;
144
+ while (drop < track.length - 2 && track[drop + 1]!.tick <= drawn) drop += 1;
145
+ drop = Math.max(drop, track.length - MAX_SNAPSHOTS);
146
+ if (drop > 0) track.splice(0, drop);
147
+ tracks.set(id, track);
148
+ }
149
+ this.#tracks = tracks;
150
+ }
151
+
152
+ /**
153
+ * The latest values given for `id` were a jump, such as a respawn: draw
154
+ * them in one step when their tick comes, not as a slide. Call it after
155
+ * the `update` that brought them, for instance when a message says so:
156
+ * messages arrive after the patch of the same tick.
157
+ */
158
+ snap(id: string): void {
159
+ const track = this.#tracks.get(id);
160
+ const last = track?.[track.length - 1];
161
+ if (last && track!.length > 1) last.snap = true;
162
+ }
163
+
164
+ /** The values to draw for `id` right now, or undefined if it is not known. */
165
+ at(id: string, now = localNow()): Record<Field, number> | undefined {
166
+ const track = this.#tracks.get(id);
167
+ if (!track || track.length === 0) return undefined;
168
+ const newest = track[track.length - 1]!;
169
+ const tick = this.#drawnTick(now);
170
+ if (tick === undefined) return { ...newest.values };
171
+
172
+ if (tick >= newest.tick) {
173
+ const before = track[track.length - 2];
174
+ const ahead = Math.min(tick - newest.tick, this.#maxExtrapolation);
175
+ if (!before || newest.snap || ahead <= 0) return { ...newest.values };
176
+ // Carried on at the speed it last had, for as long as that is allowed.
177
+ return this.#blend(before.values, newest.values, 1 + ahead / (newest.tick - before.tick));
178
+ }
179
+ let i = track.length - 1;
180
+ while (i > 0 && track[i - 1]!.tick > tick) i -= 1;
181
+ const to = track[i]!;
182
+ const from = track[i - 1];
183
+ // Before the first it knows, it shows the first.
184
+ if (!from) return { ...to.values };
185
+ if (to.snap) return { ...from.values };
186
+ return this.#blend(from.values, to.values, (tick - from.tick) / (to.tick - from.tick));
187
+ }
188
+
189
+ /** Forget everything, e.g. after moving to another room. */
190
+ clear(): void {
191
+ this.#tracks.clear();
192
+ this.#arrivals.reset();
193
+ this.#lateness = undefined;
194
+ this.#jitter = 0;
195
+ this.#newestTick = -Infinity;
196
+ this.#shown = undefined;
197
+ }
198
+
199
+ /** The room's tick at `now`, from its clock if it says where that is, else from when patches arrive. */
200
+ #clockTick(now: number): number | undefined {
201
+ const told = this.#source.serverTick?.(now);
202
+ if (told !== undefined) {
203
+ // A clock that stands still: the simulation has stopped, and the latest state is final.
204
+ if (this.#source.serverTick!(now + 1000) === told) return Infinity;
205
+ return told;
206
+ }
207
+ return this.#arrivals.tick(now);
208
+ }
209
+
210
+ /** A state of `tick` arrived at `now`: how late was it, by the room's clock? */
211
+ #measure(tick: number, now: number): void {
212
+ const rate = this.#source.tickRate;
213
+ if (!(rate > 0)) return;
214
+ if (this.#source.serverTick?.(now) === undefined) this.#arrivals.reading(tick, rate, 0, 0, now);
215
+ const clock = this.#clockTick(now);
216
+ if (clock === undefined || clock === Infinity) return;
217
+ const late = clock - tick;
218
+ if (this.#lateness === undefined) {
219
+ this.#lateness = late;
220
+ return;
221
+ }
222
+ // As TCP smooths its round trip: the mean takes an eighth of each sample, the spread a quarter.
223
+ this.#jitter += (Math.abs(late - this.#lateness) - this.#jitter) / 4;
224
+ this.#lateness += (late - this.#lateness) / 8;
225
+ }
226
+
227
+ /** The tick drawn at `now`, with its fraction. Undefined when there is no clock to go by. */
228
+ #drawnTick(now: number): number | undefined {
229
+ if (!(this.#source.tickRate > 0)) return undefined;
230
+ const clock = this.#clockTick(now);
231
+ if (clock === undefined || clock === Infinity) return undefined;
232
+ let tick = clock - this.delay;
233
+ const shown = this.#shown;
234
+ // A delay that grows would take what is drawn back in time. It waits for the clock instead.
235
+ if (shown && now >= shown.now) tick = Math.max(tick, shown.tick);
236
+ if (!shown || now >= shown.now) this.#shown = { tick, now };
237
+ return tick;
238
+ }
239
+
240
+ #blend(from: Record<Field, number>, to: Record<Field, number>, t: number): Record<Field, number> {
241
+ const shown = {} as Record<Field, number>;
242
+ for (const field of this.#fields) {
243
+ const a = from[field];
244
+ const b = to[field];
245
+ shown[field] = this.#angles.has(field) ? wrap(a + wrap(b - a) * t) : a + (b - a) * t;
246
+ }
247
+ return shown;
248
+ }
249
+
250
+ #distance(a: Record<Field, number>, b: Record<Field, number>): number {
251
+ if (this.#snapDistance === Infinity) return 0;
252
+ let sum = 0;
253
+ for (const field of this.#fields) {
254
+ if (!this.#angles.has(field)) sum += (b[field] - a[field]) ** 2;
255
+ }
256
+ return Math.sqrt(sum);
257
+ }
258
+ }
259
+
260
+ /** An angle in radians, brought into (-π, π]. */
261
+ function wrap(angle: number): number {
262
+ const turned = angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));
263
+ return turned === -Math.PI ? Math.PI : turned;
264
+ }