@adatechnology/game-workers 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Anderson Fernandes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,128 @@
1
- # Temporary Holding Version
1
+ # @adatechnology/game-workers
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The coordinator of every worker of a game. It decides how many workers there are (by the machine's cores, or by hand), which lane each kind of job runs in, the order by priority and by the frame a result is due, and runs the same kernel on the main thread when a worker is late or missing. Physics stays deterministic: a `sim` job gives the same bytes with 0, 1 or 8 workers. Browser module workers, a one-file page (Blob URL), Node `worker_threads`, or none. The rule that every package follows is CLAUDE.md §14 (`specs/regras/14-workers.md`).
4
+
5
+ ```ts
6
+ import { createWorkerCoordinator, browserSpawn } from '@adatechnology/game-workers'
7
+
8
+ const workers = createWorkerCoordinator({ spawn: browserSpawn(new URL('./game-worker.js', import.meta.url)) })
9
+ await workers.warm(KINDS) // at load: workers up, each kernel run once (JIT), unknown kinds caught here
10
+
11
+ // fixed step N
12
+ workers.tick(frame)
13
+ const handle = workers.submit(groundTiles, input, { frame }) // due in N + latencyFrames
14
+ // fixed step handle.dueFrame
15
+ const tiles = handle.collect(frame) // the worker's answer, or the kernel run here now
16
+ ```
17
+
18
+ ## Kinds
19
+
20
+ A **task** kind is a pure function of plain data: `run(input)` reads nothing but its input (a seed travels inside it), and the same function runs in the worker and on the main thread. A **resident** kind is an instance built once per worker from an `init` and stepped (the crowd physics, later a region of the world).
21
+
22
+ ```ts
23
+ export const pathfinding = defineTaskKind<PathInput, PathOutput>({
24
+ id: 'mygame.pathfinding', // package.thing, unique in a coordinator
25
+ lane: 'sim', // sim | build | background
26
+ priority: 180, // higher first, as DEFERRED_PRIORITY
27
+ latencyFrames: 2, // sim: applied in N + 2
28
+ late: 'sync', // sim: always sync
29
+ run: (input) => ({ cells: aStar(input) }),
30
+ transferOutput: (out) => [out.cells.buffer],
31
+ warmup: SMALL_GRID, // run once in every worker at warm()
32
+ })
33
+ ```
34
+
35
+ The kit's kinds and their default schedule are in `WORKER_KIND_DEFAULTS` (`@adatechnology/game-contracts`); a game changes any of them by id: `createWorkerCoordinator({ kinds: { 'crowd.physics': { priority: 260 } } })`.
36
+
37
+ ## Lanes and the automatic split
38
+
39
+ | Lane | For | Late or no worker |
40
+ | --- | --- | --- |
41
+ | `sim` | physics and anything the next frames read; the result is applied in a fixed frame | the main thread runs it at `collect` (`late: 'sync'`, the only rule) |
42
+ | `build` | generation at load: shapes, colliders, normals | `sync`: one job per macrotask on the main thread; `drop`; `keep-waiting` |
43
+ | `background` | the living world far from the player | usually `drop`: the far world can wait, the frame cannot |
44
+
45
+ `workers: 'auto'` (default) makes `cores − 1 − reserveCores` workers, at most `maxWorkers` (8). `sim` gets a third rounded up (1 to 3), `background` its own worker from 6 on, `build` the rest; one worker serves every lane. A `build` worker takes `sim` jobs first (they have a deadline); a `background` worker never does. `reserveCores` leaves cores to others (Jolt's job threads, an audio worklet). `workers: 0`, no `spawn`, or a runtime with no workers: every job runs on the main thread through the same kernel.
46
+
47
+ | Cores | Workers | sim | build | background |
48
+ | --- | --- | --- | --- | --- |
49
+ | 1 | 0 | main thread | main thread | main thread |
50
+ | 2 | 1 | 1, every lane | shared | shared, when idle |
51
+ | 4 | 3 | 1 | 2 | shared with build |
52
+ | 8 | 7 | 3 | 3 | 1 |
53
+ | 16+ | 8 | 3 | 4 | 1 |
54
+
55
+ ## Due frame, determinism and the fallback
56
+
57
+ 1. Frame N: `submit(kind, input, { frame: N })`; `dueFrame = N + latencyFrames`. The input is the coordinator's from here on: do not change it.
58
+ 2. A free worker takes the job (each worker holds at most `inFlightPerWorker`, 16 by default; the rest wait in the coordinator's queue, where an urgent job passes them. Jobs leave that queue only when the main thread reads a worker's answer, so a small cap turns a burst into several frames of round trips: in the room a crater's tiles were 139 of 163 late with 2 and none with 16).
59
+ 3. Frame `dueFrame`: `collect(dueFrame)` gives the worker's answer if it is back; otherwise the kernel runs here, and the late answer is thrown away when it comes. Collecting before the due frame is an error, so an early answer changes nothing.
60
+
61
+ The main thread never waits for a worker (`Atomics.wait` is forbidden there in a browser). The input of a `sync` job is copied to the worker, never transferred: the main thread keeps it for the fallback. A kind whose caller keeps its own copy for its own fallback (the ground tiles) sets `transferAwaitedInput: true`: its awaited jobs (`run`) transfer the input (`transferInput`) instead of a structured clone, and such a job, once sent, is never run on the main thread (a worker that fails it or dies holding it rejects its promise); jobs read through `collect` still copy. Outputs are transferred back (`transferOutput`). A worker that crashes is replaced (at most 5 times per worker) and its jobs go back in line; a job that kills two workers runs on the main thread.
62
+
63
+ ## Workers: browser, one-file page, Node
64
+
65
+ ```ts
66
+ // game-worker.ts — the file each worker loads: the kit's kinds and the game's own
67
+ import { installWorkerHost } from '@adatechnology/game-workers'
68
+ import { crowdPhysicsKind } from '@adatechnology/game-crowd'
69
+ installWorkerHost(self, [crowdPhysicsKind, pathfinding])
70
+ ```
71
+
72
+ - `browserSpawn(url)`: module workers (`new URL('./game-worker.js', import.meta.url)`, resolved by the bundler).
73
+ - `sourceSpawn(code)`: a page that is one file embeds the worker bundle as text; a Blob URL is made once.
74
+ - `nodeSpawn(url)` and `nodeWorkerScope()` from `@adatechnology/game-workers/node`: `worker_threads` with the same protocol.
75
+ - `inThreadSpawn(kinds)`: the same protocol in this thread on a later macrotask (copy and transfer included), for tests.
76
+
77
+ ## Equivalence test
78
+
79
+ Every kind passes `checkTaskKind(kind, samples, [nodeSpawn(url)])` in CI: each sample on the main thread, through the in-thread worker and through a real `worker_threads` worker, compared byte for byte (`firstDifference`). A resident is checked through its package (the crowd: `tests/physics/coordinator.test.ts`, the whole crowd state hashed with no worker, a worker on time and a worker always late).
80
+
81
+ ## Stats
82
+
83
+ `stats()`: workers per lane, queued, running, respawned, and per kind `submitted`, `onTime`, `fallback`, `dropped`, `cancelled`, `failed`, `workerMs`, `mainMs`, `queueMs`. The test room and `perf-gate` read them: a kind with many fallbacks needs more latency, a higher priority, or more `sim` workers.
84
+
85
+ ## The simulation thread
86
+
87
+ The main thread of a page may not wait, so in the plain coordinator a late `sim` job is computed again on the main thread. The simulation thread removes that limit the way native engines do: the whole fixed step runs in one dedicated worker, which **may wait** for the jobs it hands to other workers and sleeps until its next step (`Atomics.wait` is allowed in a worker). The page only pushes input and draws.
88
+
89
+ ```ts
90
+ // sim-worker.ts: the simulation thread's file, with every module the game may start
91
+ import { installSimThread } from '@adatechnology/game-workers'
92
+ import { hordeSimModule } from '@adatechnology/game-crowd'
93
+ installSimThread(self, [hordeSimModule])
94
+
95
+ // the page
96
+ if (canRunSimThread()) {
97
+ const sim = startSimThread(browserSpawn(new URL('./sim-worker.js', import.meta.url)), { module: 'crowd.horde', init, snapshotBytes: hordeSnapshotBytes(capacity) })
98
+ // every frame: input in, the newest whole snapshot out; neither ever waits
99
+ sim.send([HORDE_COMMAND.TARGET, player.x, player.z, player.yaw, 1])
100
+ const snapshot = sim.latest()
101
+ if (snapshot) readHordeSnapshot(crowd.store, snapshot.bytes)
102
+ }
103
+ ```
104
+
105
+ - A module is a `SimModule` (`game-contracts`): `create(init)` gives `step(frame, dt, commands)` and `write(out, frame)`. `step` may return a promise: the loop awaits the jobs it handed to a coordinator of its own (`workers.run`), so the result never depends on how fast those workers were.
106
+ - The state reaches the page through a triple buffer of snapshots (`SnapshotWriter` / `SnapshotReader`): the writer never waits, the reader always gets the newest whole snapshot. Input goes the other way through a ring of fixed-width commands (`CommandRing`): a full ring refuses a command instead of waiting.
107
+ - `runSimInline(module, init, { steps, commands })` runs the same loop on this thread: the reference the thread must match byte for byte, and the fallback where memory cannot be shared.
108
+ - It needs shared memory: `canShareMemory()` is true in Node, in Electron (always cross-origin isolated) and in a page served with `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`. Without it, keep the plain coordinator.
109
+ - The paced loop counts its own steps (`stats()`: steps, mean and max step ms, stalls dropped); `stop()` wakes it from its sleep.
110
+
111
+ ## Choosing a setup by project
112
+
113
+ | Project | Coordinator | Simulation thread | Notes |
114
+ |---|---|---|---|
115
+ | Browser game, page not isolated | `'auto'` (on in the kit preset) | no | `sim` jobs collected at their due frame, fallback here |
116
+ | Browser game, served with COOP/COEP | `'auto'` | yes, when the fixed step is busy (horde, crater ground, AI) | the page keeps input and drawing |
117
+ | Electron app | `'auto'`, `reserveCores` for Jolt | yes | `nodeSpawn` in the main process for the far world and loading; native code as a Rust addon only from the main process or a worker |
118
+ | Node server or tool | `nodeSpawn`, `'auto'` | optional (`paced: false` for a server tick or a replay) | the main thread may wait in Node |
119
+ | Phone or webview | `maxWorkers: 2` to `3` | no | measure on the device before raising it |
120
+ | Tests | `inThreadSpawn` or `nodeSpawn` | `runSimInline` | `checkTaskKind` byte for byte |
121
+
122
+ The `kit_workers` tool of the repository's `game-kit` MCP answers this for a given platform, core count and set of heavy work: the plan per lane, the kit kinds that apply with their schedule, whether to run the simulation thread, what the host must serve, and the code to start it.
123
+
124
+ Native code, when a measurement shows a kernel is worth it, is Rust compiled to WebAssembly and run inside a kind, with the same equivalence test against the TypeScript kernel (spec 009, D5). Physics stays on Jolt, which runs its own job threads: leave them cores with `reserveCores`.
125
+
126
+ ## Inspirations
127
+
128
+ Naughty Dog's fiber job system (everything heavy is a job, frames in a pipeline), Unity's Job System (data-only jobs, handles, `Complete()` that forces the end: here the fallback), Unreal's TaskGraph (priority classes, named pools), Frostbite (jobs by frame phase) and Bevy's task pools (pools by the nature of the work, each a share of the cores with a floor and a ceiling). What does not carry over to the browser: fibers, waiting on the main thread, thread affinity. The design document is linked from `specs/regras/14-workers.md`.
@@ -0,0 +1,340 @@
1
+ import { TaskKind, AnyWorkerKind, WorkerLane, WorkerKindSchedule, WorkerCoordinator, ResidentKind, AnySimModule, SimModule } from '@adatechnology/game-contracts';
2
+ export { AnyResidentKind, AnySimModule, AnyTaskKind, AnyWorkerKind, ResidentHandle, ResidentInstance, ResidentKind, SimInstance, SimModule, TaskHandle, TaskKind, WORKER_KIND_DEFAULTS, WORKER_KIND_ID, WORKER_LANES, WorkerCoordinator, WorkerCoordinatorStats, WorkerKindSchedule, WorkerKindStats, WorkerLane, WorkerLateRule, WorkerResultSource } from '@adatechnology/game-contracts';
3
+
4
+ /** Messages between the coordinator and a worker host. One protocol for browser workers, `worker_threads` and the in-thread host. */
5
+ type ToWorker = {
6
+ readonly t: 'hello';
7
+ readonly id: number;
8
+ } | {
9
+ readonly t: 'task';
10
+ readonly id: number;
11
+ readonly kind: string;
12
+ readonly input: unknown;
13
+ } | {
14
+ readonly t: 'create';
15
+ readonly rid: number;
16
+ readonly kind: string;
17
+ readonly init: unknown;
18
+ } | {
19
+ readonly t: 'step';
20
+ readonly id: number;
21
+ readonly rid: number;
22
+ readonly input: unknown;
23
+ } | {
24
+ readonly t: 'dispose';
25
+ readonly rid: number;
26
+ };
27
+ type FromWorker = {
28
+ readonly t: 'hello';
29
+ readonly id: number;
30
+ readonly kinds: readonly string[];
31
+ } | {
32
+ readonly t: 'done';
33
+ readonly id: number;
34
+ readonly ok: true;
35
+ readonly output: unknown;
36
+ readonly ms: number;
37
+ } | {
38
+ readonly t: 'done';
39
+ readonly id: number;
40
+ readonly ok: false;
41
+ readonly error: string;
42
+ readonly ms: number;
43
+ };
44
+ /** Anything with `postMessage` / `onmessage` / `terminate`: a browser `Worker`, a `worker_threads` wrapper, the in-thread host. */
45
+ interface WorkerLike {
46
+ onmessage: ((event: {
47
+ data: unknown;
48
+ }) => void) | null;
49
+ onerror: ((event: unknown) => void) | null;
50
+ postMessage(message: unknown, transfer?: readonly ArrayBuffer[]): void;
51
+ terminate(): void;
52
+ }
53
+ /** The worker side: `self` in a browser worker, `parentPort` in Node (through `nodeWorkerScope`), or the in-thread host. */
54
+ interface WorkerScopeLike {
55
+ onmessage: ((event: {
56
+ data: unknown;
57
+ }) => void) | null;
58
+ postMessage(message: unknown, transfer?: readonly ArrayBuffer[]): void;
59
+ }
60
+ /** Makes one worker that runs `installWorkerHost` with the kinds the coordinator is asked for. */
61
+ type Spawn = () => WorkerLike;
62
+
63
+ interface KindReport {
64
+ readonly ok: boolean;
65
+ readonly problems: readonly string[];
66
+ }
67
+ /** Where two values differ, byte for byte in typed arrays (`-0`, `NaN` payloads included); `null` when they are the same. */
68
+ declare function firstDifference(a: unknown, b: unknown, path?: string): string | null;
69
+ /**
70
+ * The equivalence test every kind passes (CLAUDE.md §14): each sample run on the main thread, through the in-thread worker (the protocol,
71
+ * the copy and the transfer) and through each `spawn` given (a real `worker_threads` worker in CI), and the outputs compared byte for byte.
72
+ * `extraKinds`: the other kinds the given workers host.
73
+ */
74
+ declare function checkTaskKind<In, Out>(kind: TaskKind<In, Out>, samples: readonly In[], spawns?: readonly Spawn[], extraKinds?: readonly AnyWorkerKind[]): Promise<KindReport>;
75
+
76
+ interface LaneOptions {
77
+ /** Workers of this lane (default: the automatic split). */
78
+ readonly workers?: number;
79
+ /** `build` only: its idle workers take `sim` jobs (default true). */
80
+ readonly borrow?: boolean;
81
+ }
82
+ interface WorkerPlanOptions {
83
+ /** `'auto'` (default): `cores - 1 - reserveCores`, at most `maxWorkers`. A number: exactly that many. 0: everything on the main thread. */
84
+ readonly workers?: 'auto' | number;
85
+ /** Ceiling of the automatic count (default 8). */
86
+ readonly maxWorkers?: number;
87
+ /** Cores others use (Jolt's job threads, an audio worklet): the automatic count leaves them free. */
88
+ readonly reserveCores?: number;
89
+ readonly lanes?: Partial<Readonly<Record<WorkerLane, LaneOptions>>>;
90
+ }
91
+ interface WorkerPlan {
92
+ readonly total: number;
93
+ readonly lanes: Readonly<Record<WorkerLane, number>>;
94
+ /** For each worker, by index, the lane it belongs to. */
95
+ readonly homes: readonly WorkerLane[];
96
+ /** For each worker, by index, the lanes it takes jobs from, in order (a `build` worker takes `sim` jobs first: they have a deadline). */
97
+ readonly serves: readonly (readonly WorkerLane[])[];
98
+ }
99
+ declare const DEFAULT_MAX_WORKERS = 8;
100
+ /** The cores of this machine, or 1 where the runtime does not say. */
101
+ declare function hardwareCores(): number;
102
+ /**
103
+ * How many workers and which lanes each one serves. Automatic: `cores - 1 - reserveCores` workers (the main thread keeps a core), at most
104
+ * `maxWorkers`; the `sim` lane takes a third rounded up (1 to 3), `background` gets its own worker from 6 on, `build` the rest. One worker
105
+ * serves every lane. A `build` worker takes `sim` jobs first (they have a deadline), then its own, then `background` when that lane has
106
+ * none of its own; a `background` worker never takes `sim` jobs, so the far world never delays a frame.
107
+ */
108
+ declare function planWorkers(options?: WorkerPlanOptions, cores?: number): WorkerPlan;
109
+
110
+ /** Jobs a worker holds at once unless `CoordinatorOptions.inFlightPerWorker` says otherwise (room measurement, spec 009 T7). */
111
+ declare const IN_FLIGHT_PER_WORKER = 16;
112
+ interface CoordinatorOptions extends WorkerPlanOptions {
113
+ /** Makes one worker (`browserSpawn`, `sourceSpawn`, `nodeSpawn`, `inThreadSpawn`). Without it every job runs on the main thread. */
114
+ readonly spawn?: Spawn;
115
+ /** The game's overrides of a kind's schedule, by kind id. */
116
+ readonly kinds?: Readonly<Record<string, Partial<WorkerKindSchedule>>>;
117
+ /**
118
+ * Jobs a worker holds at once (default `IN_FLIGHT_PER_WORKER`, 16): the rest wait in the coordinator's queue, where a more urgent one can pass them. A job only leaves that
119
+ * queue when the main thread reads a worker's answer, which on a busy frame is once per frame: a burst (a blast asks for dozens of ground tiles at once) with a small cap
120
+ * needs several frames of round trips and misses its due frame. Measured in the room (crater, 4 threads): 2 left 139 of 163 tiles late, 16 none.
121
+ */
122
+ readonly inFlightPerWorker?: number;
123
+ /** The machine's cores for the automatic count (default `navigator.hardwareConcurrency`). */
124
+ readonly cores?: number;
125
+ /** Clock in milliseconds (default `performance.now`). */
126
+ readonly now?: () => number;
127
+ }
128
+ /** The promise of a job given up by `late: 'drop'` rejects with it. */
129
+ declare class WorkerTaskDropped extends Error {
130
+ constructor(kind: string);
131
+ }
132
+ /** The promise of a cancelled job rejects with it. */
133
+ declare class WorkerTaskCancelled extends Error {
134
+ constructor(kind: string);
135
+ }
136
+ /**
137
+ * The promise of an awaited job whose input was transferred (`transferAwaitedInput`) rejects with it when its worker died holding it: the input went with the worker, so the
138
+ * coordinator cannot run it here; the caller makes it from its own copy (`isWorkerInputLost`). A worker that answers with an error rejects with that error instead.
139
+ */
140
+ declare class WorkerTaskInputLost extends Error {
141
+ constructor(kind: string);
142
+ }
143
+ /**
144
+ * The coordinator of every worker of a game (see the `game-workers` README). `sim` jobs are applied in a fixed frame: `collect(dueFrame)`
145
+ * gives the worker's answer when it is back and runs the same kernel here when it is not, so the result never depends on timing. The main
146
+ * thread never waits for a worker.
147
+ */
148
+ declare function createWorkerCoordinator(options?: CoordinatorOptions): WorkerCoordinator & {
149
+ readonly plan: WorkerPlan;
150
+ };
151
+
152
+ /** Checks a schedule: a known lane and rule, `sync` on the `sim` lane (its result is read in a fixed frame), a whole latency >= 1. */
153
+ declare function checkSchedule(id: string, schedule: WorkerKindSchedule): void;
154
+ /** The schedule a kit kind declares by default, by id (`WORKER_KIND_DEFAULTS`); `undefined` for a game's own kind. */
155
+ declare const kitScheduleOf: (id: string) => WorkerKindSchedule | undefined;
156
+ /**
157
+ * A task kind, checked: the id, the lane and the late rule. The kit's kinds take their schedule from `WORKER_KIND_DEFAULTS`.
158
+ *
159
+ * ```ts
160
+ * export const pathfinding = defineTaskKind<PathInput, PathOutput>({ id: 'mygame.pathfinding', lane: 'sim', priority: 180, latencyFrames: 2, late: 'sync', run: aStar })
161
+ * ```
162
+ */
163
+ declare function defineTaskKind<In, Out>(kind: Omit<TaskKind<In, Out>, 'kind'>): TaskKind<In, Out>;
164
+ /** A resident kind, checked as `defineTaskKind`. */
165
+ declare function defineResidentKind<Init, Step, Result>(kind: Omit<ResidentKind<Init, Step, Result>, 'kind'>): ResidentKind<Init, Step, Result>;
166
+
167
+ /**
168
+ * The worker side of the coordinator: answers each job with the kind's own `run` (or the resident instance's `step`) and transfers the
169
+ * output's buffers back. Call it in the file the worker loads, with every kind the game registers, the kit's and its own:
170
+ *
171
+ * ```ts
172
+ * // game-worker.ts
173
+ * import { installWorkerHost } from '@adatechnology/game-workers'
174
+ * installWorkerHost(self, [...KIT_WORKER_KINDS, pathfinding])
175
+ * ```
176
+ */
177
+ declare function installWorkerHost(scope: WorkerScopeLike, kinds: readonly AnyWorkerKind[]): void;
178
+
179
+ interface InThreadOptions {
180
+ /** Milliseconds before each answer reaches the coordinator (default 0: the next macrotask), to play a slow worker in tests. */
181
+ readonly delayMs?: number;
182
+ }
183
+ /**
184
+ * A worker that runs `installWorkerHost` in this thread and answers on a later macrotask, as a real one does: the same protocol, the same
185
+ * copy of the input (`structuredClone`) and the same transfer of the output. For tests, and the reference of `checkTaskKind`.
186
+ */
187
+ declare function inThreadSpawn(kinds: readonly AnyWorkerKind[], options?: InThreadOptions): Spawn;
188
+
189
+ /** Whether this runtime has browser workers. */
190
+ declare const canSpawnBrowserWorkers: () => boolean;
191
+ /**
192
+ * Module workers that load `url`, the file that calls `installWorkerHost` (a bundler resolves `new URL('./game-worker.js', import.meta.url)`).
193
+ * Throws where there is no `Worker`; the coordinator then runs every job on the main thread.
194
+ */
195
+ declare function browserSpawn(url: string | URL, options?: {
196
+ readonly type?: 'module' | 'classic';
197
+ readonly name?: string;
198
+ }): Spawn;
199
+ /**
200
+ * Workers made from the worker's own source text, for a page that is one file (no worker file beside it to load): the build embeds the
201
+ * bundle of the worker as a string and this makes a Blob URL of it once.
202
+ */
203
+ declare function sourceSpawn(source: string, options?: {
204
+ readonly type?: 'module' | 'classic';
205
+ readonly name?: string;
206
+ }): Spawn;
207
+
208
+ /**
209
+ * Memory the main thread and the simulation thread share, with no lock and no wait on the main thread (it may not wait in a browser or in
210
+ * the Electron renderer): a triple buffer of snapshots (the simulation writes, the page reads the newest whole one) and a ring of commands
211
+ * (the page writes input, the simulation drains it at the start of a step). One writer and one reader each.
212
+ */
213
+ /** Whether this runtime shares memory between threads: `SharedArrayBuffer` and, in a page, cross-origin isolation (COOP/COEP; always in Electron). */
214
+ declare function canShareMemory(): boolean;
215
+ /** A buffer of three snapshots of `bytes` each. */
216
+ declare function createSnapshotBuffer(bytes: number): SharedArrayBuffer;
217
+ /** One snapshot as the reader sees it: valid until its next `latest()`, which may hand the slot back to the writer. */
218
+ interface Snapshot {
219
+ readonly frame: number;
220
+ readonly buffer: SharedArrayBuffer;
221
+ readonly byteOffset: number;
222
+ readonly byteLength: number;
223
+ readonly bytes: Uint8Array;
224
+ }
225
+ /** The writer's side (the simulation thread): `begin` a free slot, fill it, `commit` it with its frame. Never waits. */
226
+ declare class SnapshotWriter {
227
+ readonly buffer: SharedArrayBuffer;
228
+ private readonly header;
229
+ private readonly views;
230
+ private slot;
231
+ constructor(buffer: SharedArrayBuffer);
232
+ /** A slot neither published nor being read: there is always one of the three. */
233
+ begin(): Uint8Array;
234
+ commit(frame: number): void;
235
+ }
236
+ /** The reader's side (the page): the newest whole snapshot, or `null` before the first. Never waits; retries only when a commit lands mid-claim. */
237
+ declare class SnapshotReader {
238
+ readonly buffer: SharedArrayBuffer;
239
+ private readonly header;
240
+ private readonly size;
241
+ private readonly views;
242
+ constructor(buffer: SharedArrayBuffer);
243
+ latest(): Snapshot | null;
244
+ /** Lets the writer take the slot of the last snapshot (the reader is done with it). */
245
+ release(): void;
246
+ }
247
+ /** A ring of `capacity` commands of `width` numbers each. */
248
+ declare function createCommandBuffer(width: number, capacity: number): SharedArrayBuffer;
249
+ /** Both ends of the ring: the page `push`es, the simulation `drain`s; a full ring refuses the command (`false`) rather than waiting. */
250
+ declare class CommandRing {
251
+ readonly buffer: SharedArrayBuffer;
252
+ private readonly header;
253
+ private readonly data;
254
+ readonly width: number;
255
+ readonly capacity: number;
256
+ constructor(buffer: SharedArrayBuffer);
257
+ push(command: ArrayLike<number>): boolean;
258
+ /** Every command pushed so far, oldest first, each a copy. */
259
+ drain(): Float64Array[];
260
+ }
261
+
262
+ /**
263
+ * The simulation thread (spec 009, T22): the whole fixed step of a game runs in one dedicated worker, which **may wait** (for the jobs it
264
+ * hands to other workers, for its next step), as the main thread of a native engine's simulation does. The page only pushes input into a
265
+ * command ring and draws the newest whole snapshot, so it never waits, in a browser or in the Electron renderer.
266
+ *
267
+ * The same module also runs on the calling thread (`runSimInline`): the snapshot bytes are the same after the same steps and commands, which
268
+ * is what the equivalence test checks.
269
+ */
270
+ interface SimLoopOptions {
271
+ /** Seconds of one fixed step (default 1/60). */
272
+ readonly stepSeconds?: number;
273
+ /** Stop after this many steps (tests, a replay); default: run until `stop`. */
274
+ readonly steps?: number;
275
+ /** Steps on the clock (default) or as fast as they compute (`false`: tests, a server). */
276
+ readonly paced?: boolean;
277
+ /** Steps the loop catches up after a stall before it drops the time instead (default 4). */
278
+ readonly maxCatchUp?: number;
279
+ }
280
+ interface SimThreadOptions<Init> extends SimLoopOptions {
281
+ readonly module: string;
282
+ readonly init: Init;
283
+ /** Bytes of one snapshot. */
284
+ readonly snapshotBytes: number;
285
+ /** Numbers in one command (default 8) and commands the ring holds (default 256). */
286
+ readonly commandWidth?: number;
287
+ readonly commandCapacity?: number;
288
+ }
289
+ interface SimThreadStats {
290
+ /** Steps done. */
291
+ readonly steps: number;
292
+ readonly lastStepMs: number;
293
+ readonly meanStepMs: number;
294
+ readonly maxStepMs: number;
295
+ /** Stalls the loop gave up catching up on. */
296
+ readonly dropped: number;
297
+ }
298
+ /** The page's side of a running simulation thread. */
299
+ interface SimThread {
300
+ /** Resolves when the module is built and the first step is about to run; rejects when the thread could not build it. */
301
+ readonly ready: Promise<void>;
302
+ /** Resolves with the steps done when the loop ends (`steps` reached or `stop`). */
303
+ readonly done: Promise<number>;
304
+ /** The newest whole snapshot (never waits), `null` before the first. Valid until the next `latest`. */
305
+ latest(): Snapshot | null;
306
+ /** Queues a command for the start of the next step; `false` when the ring is full. */
307
+ send(command: ArrayLike<number>): boolean;
308
+ stats(): SimThreadStats;
309
+ /** Ends the loop after the step it is in. */
310
+ stop(): void;
311
+ /** Stops and terminates the worker. */
312
+ dispose(): void;
313
+ }
314
+ /**
315
+ * The simulation thread's side: call it in the file of the simulation worker with every module the game may start.
316
+ *
317
+ * ```ts
318
+ * // sim-worker.ts
319
+ * import { installSimThread } from '@adatechnology/game-workers'
320
+ * installSimThread(self, [hordeSim])
321
+ * ```
322
+ */
323
+ declare function installSimThread(scope: WorkerScopeLike, modules: readonly AnySimModule[]): void;
324
+ /** Whether a simulation thread can run here: shared memory (`canShareMemory`) and workers to spawn. */
325
+ declare const canRunSimThread: () => boolean;
326
+ /** Starts `options.module` in a new worker from `spawn` (a worker that calls `installSimThread`). Throws where memory cannot be shared. */
327
+ declare function startSimThread<Init>(spawn: Spawn, options: SimThreadOptions<Init>): SimThread;
328
+ /**
329
+ * The same module and loop on this thread, unpaced: the snapshot after `steps` steps, with `commands[frame]` pushed before that step. The
330
+ * reference the simulation thread must match byte for byte, and the fallback where memory cannot be shared.
331
+ */
332
+ declare function runSimInline<Init>(module: SimModule<Init>, init: Init, options: {
333
+ readonly steps: number;
334
+ readonly snapshotBytes: number;
335
+ readonly stepSeconds?: number;
336
+ readonly commands?: readonly (readonly ArrayLike<number>[])[];
337
+ readonly commandWidth?: number;
338
+ }): Promise<Uint8Array>;
339
+
340
+ export { CommandRing, type CoordinatorOptions, DEFAULT_MAX_WORKERS, type FromWorker, IN_FLIGHT_PER_WORKER, type InThreadOptions, type KindReport, type LaneOptions, type SimLoopOptions, type SimThread, type SimThreadOptions, type SimThreadStats, type Snapshot, SnapshotReader, SnapshotWriter, type Spawn, type ToWorker, type WorkerLike, type WorkerPlan, type WorkerPlanOptions, type WorkerScopeLike, WorkerTaskCancelled, WorkerTaskDropped, WorkerTaskInputLost, browserSpawn, canRunSimThread, canShareMemory, canSpawnBrowserWorkers, checkSchedule, checkTaskKind, createCommandBuffer, createSnapshotBuffer, createWorkerCoordinator, defineResidentKind, defineTaskKind, firstDifference, hardwareCores, inThreadSpawn, installSimThread, installWorkerHost, kitScheduleOf, planWorkers, runSimInline, sourceSpawn, startSimThread };