@adatechnology/game-workers 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1086 @@
1
+ "use strict";
2
+ var GameWorkers = (() => {
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
+
23
+ // src/index.ts
24
+ var index_exports = {};
25
+ __export(index_exports, {
26
+ CommandRing: () => CommandRing,
27
+ DEFAULT_MAX_WORKERS: () => DEFAULT_MAX_WORKERS,
28
+ IN_FLIGHT_PER_WORKER: () => IN_FLIGHT_PER_WORKER,
29
+ SnapshotReader: () => SnapshotReader,
30
+ SnapshotWriter: () => SnapshotWriter,
31
+ WORKER_KIND_DEFAULTS: () => WORKER_KIND_DEFAULTS,
32
+ WORKER_KIND_ID: () => WORKER_KIND_ID,
33
+ WORKER_LANES: () => WORKER_LANES,
34
+ WorkerTaskCancelled: () => WorkerTaskCancelled,
35
+ WorkerTaskDropped: () => WorkerTaskDropped,
36
+ WorkerTaskInputLost: () => WorkerTaskInputLost,
37
+ browserSpawn: () => browserSpawn,
38
+ canRunSimThread: () => canRunSimThread,
39
+ canShareMemory: () => canShareMemory,
40
+ canSpawnBrowserWorkers: () => canSpawnBrowserWorkers,
41
+ checkSchedule: () => checkSchedule,
42
+ checkTaskKind: () => checkTaskKind,
43
+ createCommandBuffer: () => createCommandBuffer,
44
+ createSnapshotBuffer: () => createSnapshotBuffer,
45
+ createWorkerCoordinator: () => createWorkerCoordinator,
46
+ defineResidentKind: () => defineResidentKind,
47
+ defineTaskKind: () => defineTaskKind,
48
+ firstDifference: () => firstDifference,
49
+ hardwareCores: () => hardwareCores,
50
+ inThreadSpawn: () => inThreadSpawn,
51
+ installSimThread: () => installSimThread,
52
+ installWorkerHost: () => installWorkerHost,
53
+ kitScheduleOf: () => kitScheduleOf,
54
+ planWorkers: () => planWorkers,
55
+ runSimInline: () => runSimInline,
56
+ sourceSpawn: () => sourceSpawn,
57
+ startSimThread: () => startSimThread
58
+ });
59
+
60
+ // ../game-contracts/dist/index.js
61
+ var DEFAULT_BLAST_IMPULSE = { bodyArea: 0.7, lift: 0.15, minSpeed: 0.3, tntPerJoule: 0.24 / 2e5 };
62
+ var DEFAULT_COST_ALLOCATION_BYTES = 1024 * 1024;
63
+ var DEFERRED_QUEUE_ID = {
64
+ DESTRUCTION_EVENTS: "destruction.events",
65
+ BREACH_PAINT: "floorplan.breach-paint",
66
+ BREACH_CUT: "floorplan.breach-cut",
67
+ AUDIO_VOICES: "audio.voices",
68
+ VEHICLE_CREASE: "vehicles.crease",
69
+ AUDIO_OCCLUSION: "audio.occlusion",
70
+ FLUID_FILM: "fluids.film",
71
+ VEHICLE_LOD_BATCH: "vehicles.lod-batch",
72
+ SETTLED_BATCH: "destruction.settled-batch",
73
+ STATIC_BATCH: "render.static-batch",
74
+ ANIMALS_STATIC_BATCH: "animals.static-batch",
75
+ CHARACTERS_STATIC_BATCH: "characters.static-batch",
76
+ HOUSE_SHADOW_BATCH: "floorplan.shadow-batch",
77
+ DESTRUCTION_PREFIT: "destruction.prefit"
78
+ };
79
+ var DEFERRED_PRIORITY = {
80
+ [DEFERRED_QUEUE_ID.DESTRUCTION_EVENTS]: { priority: 300, phase: "present" },
81
+ // every frame: the walls cut since the last frame are painted once each, and a hole must show in the frame of the blast
82
+ [DEFERRED_QUEUE_ID.BREACH_CUT]: { priority: 260, phase: "present", minEveryFrames: 1 },
83
+ [DEFERRED_QUEUE_ID.BREACH_PAINT]: { priority: 250, phase: "present", minEveryFrames: 1 },
84
+ [DEFERRED_QUEUE_ID.AUDIO_VOICES]: { priority: 200, phase: "idle", reserveMs: 1 },
85
+ [DEFERRED_QUEUE_ID.AUDIO_OCCLUSION]: { priority: 190, phase: "idle", minEveryFrames: 8 },
86
+ [DEFERRED_QUEUE_ID.FLUID_FILM]: { priority: 120, phase: "idle", minEveryFrames: 2 },
87
+ [DEFERRED_QUEUE_ID.VEHICLE_CREASE]: { priority: 100, phase: "idle" },
88
+ [DEFERRED_QUEUE_ID.VEHICLE_LOD_BATCH]: { priority: 90, phase: "idle", minEveryFrames: 4 },
89
+ [DEFERRED_QUEUE_ID.SETTLED_BATCH]: { priority: 70, phase: "idle", minEveryFrames: 8 },
90
+ [DEFERRED_QUEUE_ID.STATIC_BATCH]: { priority: 60, phase: "idle", minEveryFrames: 8 },
91
+ [DEFERRED_QUEUE_ID.ANIMALS_STATIC_BATCH]: { priority: 60, phase: "idle", minEveryFrames: 8 },
92
+ [DEFERRED_QUEUE_ID.CHARACTERS_STATIC_BATCH]: { priority: 60, phase: "idle", minEveryFrames: 8 },
93
+ [DEFERRED_QUEUE_ID.HOUSE_SHADOW_BATCH]: { priority: 50, phase: "idle", minEveryFrames: 8 },
94
+ [DEFERRED_QUEUE_ID.DESTRUCTION_PREFIT]: { priority: 40, phase: "idle", minEveryFrames: 30 }
95
+ };
96
+ var MUST_DRAIN_QUEUE_IDS = /* @__PURE__ */ new Set([DEFERRED_QUEUE_ID.DESTRUCTION_EVENTS, DEFERRED_QUEUE_ID.BREACH_CUT]);
97
+ var SURFACE_IDS = ["concrete", "asphalt", "wood", "tile", "dirt", "grass", "gravel", "sand", "metal", "water", "glass", "carpet"];
98
+ var GAIT_IDS = ["walk", "run"];
99
+ var LANDING_IDS = ["light", "heavy"];
100
+ var BODY_SOUND_IDS = [
101
+ "jump",
102
+ "cloth_rustle",
103
+ "body_fall",
104
+ "fall_damage",
105
+ "player_hurt",
106
+ "player_breath_run",
107
+ "player_death",
108
+ "bite",
109
+ "grab",
110
+ "punch_swing",
111
+ "punch_hit_body",
112
+ "punch_hit_face",
113
+ "punch_hit_object",
114
+ "kick_swing",
115
+ "kick_hit",
116
+ "kick_hit_object",
117
+ "shove_two_hands",
118
+ "knife_swing",
119
+ "knife_stab",
120
+ "knife_slash",
121
+ "knife_hit_object",
122
+ "blunt_swing",
123
+ "blunt_hit",
124
+ "blunt_hit_object",
125
+ "axe_swing",
126
+ "axe_chop",
127
+ "axe_hit_object"
128
+ ];
129
+ var footstepSoundId = (surface, gait) => `footstep_${surface}_${gait}`;
130
+ var FOOTSTEP_SOUND_IDS = SURFACE_IDS.flatMap((surface) => GAIT_IDS.map((gait) => footstepSoundId(surface, gait)));
131
+ var LAND_SOUND_IDS = SURFACE_IDS.flatMap((surface) => LANDING_IDS.map((landing) => `land_${surface}_${landing}`));
132
+ var BODY_FOLEY_IDS = [...FOOTSTEP_SOUND_IDS, ...LAND_SOUND_IDS, ...BODY_SOUND_IDS];
133
+ var WORKER_LANES = ["sim", "build", "background"];
134
+ var WORKER_LATE_RULES = ["sync", "drop", "keep-waiting"];
135
+ var WORKER_KIND_ID = {
136
+ GROUND_TILES: "destruction.ground-tiles",
137
+ CROWD_PHYSICS: "crowd.physics",
138
+ PIECE_BOXES: "destruction.piece-boxes",
139
+ STATIC_COLLIDERS: "destruction.static-colliders",
140
+ SHAPES_GENERATE: "shapes.generate",
141
+ WORLD_REGION: "world.region"
142
+ };
143
+ var WORKER_KIND_DEFAULTS = {
144
+ [WORKER_KIND_ID.GROUND_TILES]: { lane: "sim", priority: 300, latencyFrames: 2, late: "sync" },
145
+ [WORKER_KIND_ID.CROWD_PHYSICS]: { lane: "sim", priority: 250, latencyFrames: 1, late: "sync" },
146
+ [WORKER_KIND_ID.PIECE_BOXES]: { lane: "sim", priority: 200, latencyFrames: 2, late: "sync" },
147
+ [WORKER_KIND_ID.STATIC_COLLIDERS]: { lane: "build", priority: 150, late: "sync" },
148
+ [WORKER_KIND_ID.SHAPES_GENERATE]: { lane: "build", priority: 100, late: "sync" },
149
+ [WORKER_KIND_ID.WORLD_REGION]: { lane: "background", priority: 10, latencyFrames: 10, late: "drop" }
150
+ };
151
+ var WORKER_INPUT_LOST = "WorkerTaskInputLost";
152
+
153
+ // src/define.ts
154
+ var ID = /^[a-z0-9-]+(\.[a-z0-9-]+)+$/;
155
+ function checkSchedule(id, schedule) {
156
+ if (!WORKER_LANES.includes(schedule.lane)) throw new Error(`worker kind ${id}: unknown lane "${schedule.lane}"`);
157
+ if (!WORKER_LATE_RULES.includes(schedule.late)) throw new Error(`worker kind ${id}: unknown late rule "${schedule.late}"`);
158
+ if (schedule.lane === "sim" && schedule.late !== "sync") throw new Error(`worker kind ${id}: the sim lane needs late "sync" (its result is applied in a fixed frame)`);
159
+ if (!Number.isFinite(schedule.priority)) throw new Error(`worker kind ${id}: priority must be a number`);
160
+ const latency = schedule.latencyFrames ?? 1;
161
+ if (!Number.isInteger(latency) || latency < 1) throw new Error(`worker kind ${id}: latencyFrames must be a whole number >= 1`);
162
+ }
163
+ var checkId = (id) => {
164
+ if (!ID.test(id)) throw new Error(`worker kind "${id}": the id is "package.thing" in lowercase (destruction.ground-tiles)`);
165
+ };
166
+ var kitScheduleOf = (id) => WORKER_KIND_DEFAULTS[id];
167
+ function defineTaskKind(kind) {
168
+ checkId(kind.id);
169
+ checkSchedule(kind.id, kind);
170
+ if (kind.transferAwaitedInput && !kind.transferInput) throw new Error(`worker kind ${kind.id}: transferAwaitedInput needs transferInput (the buffers to transfer)`);
171
+ return Object.freeze({ ...kind, kind: "task" });
172
+ }
173
+ function defineResidentKind(kind) {
174
+ checkId(kind.id);
175
+ checkSchedule(kind.id, kind);
176
+ return Object.freeze({ ...kind, kind: "resident" });
177
+ }
178
+
179
+ // src/plan.ts
180
+ var DEFAULT_MAX_WORKERS = 8;
181
+ function hardwareCores() {
182
+ const n = globalThis.navigator?.hardwareConcurrency;
183
+ return typeof n === "number" && n > 0 ? n : 1;
184
+ }
185
+ var whole = (n) => Math.max(0, Math.floor(n));
186
+ function planWorkers(options = {}, cores = hardwareCores()) {
187
+ const max = whole(options.maxWorkers ?? DEFAULT_MAX_WORKERS);
188
+ const asked = options.workers ?? "auto";
189
+ const total = asked === "auto" ? Math.min(max, whole(cores - 1 - (options.reserveCores ?? 0))) : whole(asked);
190
+ const fixed = options.lanes ?? {};
191
+ let sim;
192
+ let background;
193
+ if (total <= 1) {
194
+ sim = total;
195
+ background = 0;
196
+ } else {
197
+ sim = Math.min(3, Math.max(1, Math.ceil(total / 3)));
198
+ background = total >= 6 ? 1 : 0;
199
+ }
200
+ if (fixed.sim?.workers !== void 0) sim = whole(fixed.sim.workers);
201
+ if (fixed.background?.workers !== void 0) background = whole(fixed.background.workers);
202
+ let build = fixed.build?.workers !== void 0 ? whole(fixed.build.workers) : Math.max(0, total - sim - background);
203
+ if (fixed.sim?.workers === void 0 && fixed.build?.workers === void 0 && fixed.background?.workers === void 0) build = total - sim - background;
204
+ const count = sim + build + background;
205
+ const borrow = fixed.build?.borrow !== false;
206
+ const serves = [];
207
+ for (let i = 0; i < sim; i++) serves.push(["sim", ...build === 0 ? ["build"] : [], ...build === 0 && background === 0 ? ["background"] : []]);
208
+ for (let i = 0; i < build; i++) serves.push([...borrow ? ["sim"] : [], "build", ...background === 0 ? ["background"] : []]);
209
+ for (let i = 0; i < background; i++) serves.push(["background"]);
210
+ const homes = [...Array(sim).fill("sim"), ...Array(build).fill("build"), ...Array(background).fill("background")];
211
+ return { total: count, lanes: { sim, build, background }, homes, serves };
212
+ }
213
+
214
+ // src/protocol.ts
215
+ var isFromWorker = (data) => typeof data === "object" && data !== null && typeof data.t === "string";
216
+ var isToWorker = (data) => typeof data === "object" && data !== null && typeof data.t === "string";
217
+
218
+ // src/coordinator.ts
219
+ var IN_FLIGHT_PER_WORKER = 16;
220
+ var WorkerTaskDropped = class extends Error {
221
+ constructor(kind) {
222
+ super(`worker job of ${kind} dropped: no worker took it`);
223
+ this.name = "WorkerTaskDropped";
224
+ }
225
+ };
226
+ var WorkerTaskCancelled = class extends Error {
227
+ constructor(kind) {
228
+ super(`worker job of ${kind} cancelled`);
229
+ this.name = "WorkerTaskCancelled";
230
+ }
231
+ };
232
+ var WorkerTaskInputLost = class extends Error {
233
+ constructor(kind) {
234
+ super(`worker job of ${kind}: its worker died holding its transferred input`);
235
+ this.name = WORKER_INPUT_LOST;
236
+ }
237
+ };
238
+ var MAX_CRASHES = 2;
239
+ var MAX_RESPAWNS = 5;
240
+ var defaultNow = () => typeof performance !== "undefined" ? performance.now() : Date.now();
241
+ var before = (a, b) => a.priority > b.priority || a.priority === b.priority && (a.dueFrame < b.dueFrame || a.dueFrame === b.dueFrame && a.seq < b.seq);
242
+ var insertSorted = (queue, job) => {
243
+ let i = queue.length;
244
+ while (i > 0 && before(job, queue[i - 1])) i--;
245
+ queue.splice(i, 0, job);
246
+ };
247
+ function createWorkerCoordinator(options = {}) {
248
+ const now3 = options.now ?? defaultNow;
249
+ const perWorker = Math.max(1, Math.floor(options.inFlightPerWorker ?? IN_FLIGHT_PER_WORKER));
250
+ const overrides = options.kinds ?? {};
251
+ const plan = options.spawn ? planWorkers(options, options.cores) : { total: 0, lanes: { sim: 0, build: 0, background: 0 }, homes: [], serves: [] };
252
+ const queues = { sim: [], build: [], background: [] };
253
+ const mainQueue = [];
254
+ const counters = /* @__PURE__ */ new Map();
255
+ const residents = /* @__PURE__ */ new Set();
256
+ const slots = [];
257
+ let frame = 0;
258
+ let nextId = 1;
259
+ let nextRid = 1;
260
+ let respawned = 0;
261
+ const deathsAt = /* @__PURE__ */ new Map();
262
+ let disposed = false;
263
+ let mainTimer = null;
264
+ const countersOf = (kind, lane) => {
265
+ let c = counters.get(kind.id);
266
+ if (!c) counters.set(kind.id, c = { id: kind.id, lane, submitted: 0, answered: 0, onTime: 0, fallback: 0, dropped: 0, cancelled: 0, failed: 0, workerMs: 0, mainMs: 0, queueMs: 0 });
267
+ return c;
268
+ };
269
+ const scheduleOf = (kind) => {
270
+ const own = overrides[kind.id];
271
+ if (!own) return kind;
272
+ const merged = { lane: own.lane ?? kind.lane, priority: own.priority ?? kind.priority, latencyFrames: own.latencyFrames ?? kind.latencyFrames, late: own.late ?? kind.late };
273
+ checkSchedule(kind.id, merged);
274
+ return merged;
275
+ };
276
+ const makeSlot = (index, home, serves) => {
277
+ let worker;
278
+ try {
279
+ worker = options.spawn();
280
+ } catch {
281
+ return null;
282
+ }
283
+ const slot = { index, home, serves, worker, running: /* @__PURE__ */ new Map(), own: [], residents: /* @__PURE__ */ new Set(), hello: /* @__PURE__ */ new Map(), alive: true };
284
+ worker.onmessage = (event) => onReply(slot, event.data);
285
+ worker.onerror = () => onCrash(slot);
286
+ return slot;
287
+ };
288
+ for (let i = 0; i < plan.serves.length; i++) {
289
+ const slot = makeSlot(i, plan.homes[i], plan.serves[i]);
290
+ if (slot) slots.push(slot);
291
+ }
292
+ const served = (lane) => slots.some((slot) => slot.serves.includes(lane));
293
+ const homeOf = (lane) => {
294
+ let best = null;
295
+ for (const slot of slots) {
296
+ if (!slot.alive || !slot.serves.includes(lane)) continue;
297
+ const own = slot.home === lane ? 0 : 1;
298
+ const bestOwn = best && best.home === lane ? 0 : 1;
299
+ if (!best || own < bestOwn || own === bestOwn && slot.residents.size < best.residents.size) best = slot;
300
+ }
301
+ return best;
302
+ };
303
+ const send = (slot, job) => {
304
+ job.state = "running";
305
+ job.slot = slot;
306
+ job.counters.queueMs += now3() - job.queuedAt;
307
+ slot.running.set(job.id, job);
308
+ try {
309
+ slot.worker.postMessage(job.message, job.transfer);
310
+ } catch (error) {
311
+ slot.running.delete(job.id);
312
+ job.slot = null;
313
+ job.counters.failed++;
314
+ if (job.late === "sync") runOnMain(job);
315
+ else fail(job, error instanceof Error ? error : new Error(String(error)));
316
+ }
317
+ };
318
+ const dispatch = () => {
319
+ if (disposed) return;
320
+ for (const slot of slots) {
321
+ while (slot.alive && slot.running.size < perWorker) {
322
+ let job = slot.own.shift();
323
+ if (!job) {
324
+ for (const lane of slot.serves) if (job = queues[lane].shift()) break;
325
+ }
326
+ if (!job) break;
327
+ send(slot, job);
328
+ }
329
+ }
330
+ };
331
+ const onReply = (slot, data) => {
332
+ if (!isFromWorker(data)) return;
333
+ if (data.t === "hello") {
334
+ slot.hello.get(data.id)?.(data.kinds);
335
+ slot.hello.delete(data.id);
336
+ return;
337
+ }
338
+ const job = slot.running.get(data.id);
339
+ if (!job) return;
340
+ slot.running.delete(data.id);
341
+ job.counters.workerMs += data.ms;
342
+ job.counters.answered++;
343
+ if (job.state === "running") {
344
+ if (data.ok) {
345
+ job.state = "done";
346
+ job.output = data.output;
347
+ job.source = "worker";
348
+ if (job.lane !== "sim" && !job.resident) finish(job);
349
+ else job.settle.resolve(job.output);
350
+ } else {
351
+ job.counters.failed++;
352
+ if (job.late === "sync" && !job.moved) runOnMain(job);
353
+ else fail(job, new Error(data.error));
354
+ }
355
+ }
356
+ dispatch();
357
+ };
358
+ const onCrash = (slot) => {
359
+ if (!slot.alive) return;
360
+ slot.alive = false;
361
+ slot.worker.terminate();
362
+ const deaths = (deathsAt.get(slot.index) ?? 0) + 1;
363
+ deathsAt.set(slot.index, deaths);
364
+ const replacement = disposed || deaths > MAX_RESPAWNS ? null : makeSlot(slot.index, slot.home, slot.serves);
365
+ if (replacement) {
366
+ respawned++;
367
+ slots[slots.indexOf(slot)] = replacement;
368
+ } else slots.splice(slots.indexOf(slot), 1);
369
+ for (const resident of slot.residents) {
370
+ resident.slot = replacement;
371
+ if (replacement) {
372
+ replacement.residents.add(resident);
373
+ replacement.worker.postMessage({ t: "create", rid: resident.rid, kind: resident.kind.id, init: resident.init });
374
+ }
375
+ }
376
+ const waiting = [...slot.own];
377
+ const back = [...slot.running.values()].filter((job) => job.state === "running").sort((a, b) => a.seq - b.seq);
378
+ slot.own.length = 0;
379
+ for (const job of back) job.crashes++;
380
+ for (const job of [...back, ...waiting]) {
381
+ job.state = "queued";
382
+ job.slot = null;
383
+ if (job.crashes >= MAX_CRASHES || job.moved) {
384
+ job.counters.failed++;
385
+ if (job.moved) fail(job, new WorkerTaskInputLost(job.kindId));
386
+ else if (job.late === "sync") runOnMain(job);
387
+ else fail(job, new Error(`${job.kindId}: its worker died ${job.crashes} times running it`));
388
+ } else if (job.resident) {
389
+ if (replacement) replacement.own.push(job);
390
+ } else if (served(job.lane)) insertSorted(queues[job.lane], job);
391
+ else toMain(job);
392
+ }
393
+ dispatch();
394
+ };
395
+ const finish = (job) => {
396
+ if (job.source === "worker") job.counters.onTime++;
397
+ job.state = "settled";
398
+ job.settle.resolve(job.output);
399
+ };
400
+ const fail = (job, error) => {
401
+ job.state = "settled";
402
+ job.error = error;
403
+ job.settle.reject(error);
404
+ };
405
+ const unqueue = (job) => {
406
+ for (const queue of [queues[job.lane], mainQueue, job.resident?.slot?.own ?? []]) {
407
+ const at = queue.indexOf(job);
408
+ if (at >= 0) queue.splice(at, 1);
409
+ }
410
+ };
411
+ const runOnMain = (job) => {
412
+ unqueue(job);
413
+ const started = now3();
414
+ try {
415
+ job.output = job.runHere();
416
+ job.source = "main";
417
+ job.counters.fallback++;
418
+ job.counters.mainMs += now3() - started;
419
+ finish(job);
420
+ } catch (error) {
421
+ job.counters.mainMs += now3() - started;
422
+ fail(job, error instanceof Error ? error : new Error(String(error)));
423
+ }
424
+ };
425
+ const drainMain = () => {
426
+ mainTimer = null;
427
+ const job = mainQueue.shift();
428
+ if (job && job.state === "queued") runOnMain(job);
429
+ if (mainQueue.length && !disposed) mainTimer = setTimeout(drainMain, 0);
430
+ };
431
+ const toMain = (job) => {
432
+ if (job.late === "drop") {
433
+ job.counters.dropped++;
434
+ fail(job, new WorkerTaskDropped(job.kindId));
435
+ return;
436
+ }
437
+ insertSorted(mainQueue, job);
438
+ if (!mainTimer) mainTimer = setTimeout(drainMain, 0);
439
+ };
440
+ const makeJob = (spec) => {
441
+ let settle = { resolve: () => void 0, reject: () => void 0 };
442
+ const promise = new Promise((resolve, reject) => settle = { resolve, reject });
443
+ promise.catch(() => void 0);
444
+ const id = nextId++;
445
+ const job = {
446
+ id,
447
+ seq: id,
448
+ kindId: spec.kind.id,
449
+ counters: countersOf(spec.kind, spec.schedule.lane),
450
+ lane: spec.schedule.lane,
451
+ priority: spec.schedule.priority,
452
+ late: spec.schedule.late,
453
+ dueFrame: spec.dueFrame,
454
+ message: spec.message(id),
455
+ transfer: spec.transfer,
456
+ moved: spec.moved ?? false,
457
+ runHere: spec.runHere,
458
+ resident: spec.resident,
459
+ queuedAt: now3(),
460
+ state: "queued",
461
+ crashes: 0,
462
+ output: void 0,
463
+ error: null,
464
+ source: null,
465
+ slot: null,
466
+ settle,
467
+ promise
468
+ };
469
+ job.counters.submitted++;
470
+ return job;
471
+ };
472
+ const handleOf = (job) => ({
473
+ dueFrame: job.dueFrame,
474
+ promise: job.promise,
475
+ get source() {
476
+ return job.source;
477
+ },
478
+ collect(at) {
479
+ if (at < job.dueFrame) throw new Error(`${job.kindId}: collected in frame ${at}, before its due frame ${job.dueFrame}`);
480
+ if (job.state === "cancelled") throw new WorkerTaskCancelled(job.kindId);
481
+ if (job.state === "done") finish(job);
482
+ else if (job.state === "queued" || job.state === "running") runOnMain(job);
483
+ if (job.error) throw job.error;
484
+ return job.output;
485
+ },
486
+ cancel() {
487
+ if (job.state !== "queued" && job.state !== "running") return;
488
+ unqueue(job);
489
+ job.state = "cancelled";
490
+ job.counters.cancelled++;
491
+ job.settle.reject(new WorkerTaskCancelled(job.kindId));
492
+ }
493
+ });
494
+ const enqueue = (job) => {
495
+ if (disposed) throw new Error("worker coordinator: disposed");
496
+ if (job.resident) {
497
+ if (job.resident.slot) job.resident.slot.own.push(job);
498
+ } else if (served(job.lane)) insertSorted(queues[job.lane], job);
499
+ else if (job.lane !== "sim") toMain(job);
500
+ dispatch();
501
+ };
502
+ const latencyOf = (schedule, at) => Math.max(1, Math.floor(at?.latencyFrames ?? schedule.latencyFrames ?? 1));
503
+ const taskJob = (kind, input, at, awaited = false) => {
504
+ const schedule = scheduleOf(kind);
505
+ const submitted = at?.frame ?? frame;
506
+ const moved = schedule.late === "sync" && awaited && kind.transferAwaitedInput === true && kind.transferInput !== void 0;
507
+ const job = makeJob({
508
+ kind,
509
+ schedule,
510
+ dueFrame: schedule.lane === "sim" ? submitted + latencyOf(schedule, at) : Number.POSITIVE_INFINITY,
511
+ message: (id) => ({ t: "task", id, kind: kind.id, input }),
512
+ transfer: schedule.late === "sync" && !moved ? [] : [...kind.transferInput?.(input) ?? []],
513
+ moved,
514
+ runHere: () => kind.run(input),
515
+ resident: null
516
+ });
517
+ return job;
518
+ };
519
+ const coordinator = {
520
+ plan,
521
+ submit(kind, input, at) {
522
+ const job = taskJob(kind, input, at);
523
+ enqueue(job);
524
+ return handleOf(job);
525
+ },
526
+ run(kind, input, signal) {
527
+ const job = taskJob(kind, input, void 0, true);
528
+ enqueue(job);
529
+ if (job.lane === "sim" && job.state === "queued" && !served("sim")) toMain(job);
530
+ const handle = handleOf(job);
531
+ if (signal) {
532
+ if (signal.aborted) handle.cancel();
533
+ else signal.addEventListener("abort", () => handle.cancel(), { once: true });
534
+ }
535
+ return handle.promise;
536
+ },
537
+ resident(kind, init) {
538
+ const any = kind;
539
+ const schedule = scheduleOf(any);
540
+ const resident = { rid: nextRid++, kind: any, schedule, init, slot: homeOf(schedule.lane), local: null, disposed: false };
541
+ residents.add(resident);
542
+ resident.slot?.residents.add(resident);
543
+ resident.slot?.worker.postMessage({ t: "create", rid: resident.rid, kind: kind.id, init });
544
+ const local = () => resident.local ?? (resident.local = any.create(init));
545
+ return {
546
+ id: kind.id,
547
+ step(input, at) {
548
+ if (resident.disposed) throw new Error(`${kind.id}: resident disposed`);
549
+ const submitted = at?.frame ?? frame;
550
+ const job = makeJob({
551
+ kind: any,
552
+ schedule,
553
+ dueFrame: submitted + latencyOf(schedule, at),
554
+ message: (id) => ({ t: "step", id, rid: resident.rid, input }),
555
+ transfer: schedule.late === "sync" ? [] : [...kind.transferInput?.(input) ?? []],
556
+ runHere: () => local().step(input),
557
+ resident
558
+ });
559
+ enqueue(job);
560
+ return handleOf(job);
561
+ },
562
+ dispose() {
563
+ if (resident.disposed) return;
564
+ resident.disposed = true;
565
+ residents.delete(resident);
566
+ resident.slot?.residents.delete(resident);
567
+ if (resident.slot?.alive) resident.slot.worker.postMessage({ t: "dispose", rid: resident.rid });
568
+ resident.local?.dispose?.();
569
+ }
570
+ };
571
+ },
572
+ tick(at) {
573
+ frame = at;
574
+ dispatch();
575
+ },
576
+ async warm(kinds) {
577
+ for (const kind of kinds) scheduleOf(kind);
578
+ await Promise.all(
579
+ slots.map(async (slot) => {
580
+ const id = nextId++;
581
+ const known = await new Promise((resolve) => {
582
+ slot.hello.set(id, resolve);
583
+ slot.worker.postMessage({ t: "hello", id });
584
+ });
585
+ const missing = kinds.filter((kind) => !known.includes(kind.id)).map((kind) => kind.id);
586
+ if (missing.length) throw new Error(`worker ${slot.index} does not know ${missing.join(", ")}: add them to its installWorkerHost`);
587
+ })
588
+ );
589
+ const warmups = [];
590
+ for (const kind of kinds) {
591
+ if (kind.kind !== "task" || kind.warmup === void 0) continue;
592
+ for (const slot of slots) {
593
+ const job = makeJob({ kind, schedule: scheduleOf(kind), dueFrame: Number.NEGATIVE_INFINITY, message: (id) => ({ t: "task", id, kind: kind.id, input: kind.warmup }), transfer: [], runHere: () => kind.run(kind.warmup), resident: null });
594
+ job.counters.submitted--;
595
+ send(slot, job);
596
+ warmups.push(job.promise.catch(() => void 0));
597
+ }
598
+ }
599
+ await Promise.all(warmups);
600
+ },
601
+ scheduleOf,
602
+ stats() {
603
+ let running = 0;
604
+ for (const slot of slots) running += slot.running.size;
605
+ const lanes = { sim: 0, build: 0, background: 0 };
606
+ for (const slot of slots) lanes[slot.home]++;
607
+ return {
608
+ workers: slots.length,
609
+ lanes,
610
+ queued: WORKER_LANES.reduce((n, lane) => n + queues[lane].length, 0) + mainQueue.length + slots.reduce((n, slot) => n + slot.own.length, 0),
611
+ running,
612
+ respawned,
613
+ kinds: [...counters.values()].map((c) => ({ ...c }))
614
+ };
615
+ },
616
+ dispose() {
617
+ if (disposed) return;
618
+ disposed = true;
619
+ if (mainTimer) clearTimeout(mainTimer);
620
+ const pending = [...WORKER_LANES.flatMap((lane) => queues[lane]), ...mainQueue, ...slots.flatMap((slot) => [...slot.own, ...slot.running.values()])];
621
+ for (const job of pending) if (job.state === "queued" || job.state === "running") fail(job, new Error("worker coordinator: disposed"));
622
+ for (const slot of slots) {
623
+ slot.alive = false;
624
+ slot.worker.terminate();
625
+ }
626
+ for (const resident of residents) resident.local?.dispose?.();
627
+ residents.clear();
628
+ slots.length = 0;
629
+ }
630
+ };
631
+ return coordinator;
632
+ }
633
+
634
+ // src/host.ts
635
+ var now = () => typeof performance !== "undefined" ? performance.now() : Date.now();
636
+ function installWorkerHost(scope, kinds) {
637
+ const byId = /* @__PURE__ */ new Map();
638
+ for (const kind of kinds) {
639
+ if (byId.has(kind.id) && byId.get(kind.id) !== kind) throw new Error(`installWorkerHost: two kinds with the id ${kind.id}`);
640
+ byId.set(kind.id, kind);
641
+ }
642
+ const residents = /* @__PURE__ */ new Map();
643
+ const reply = (message2, transfer = []) => scope.postMessage(message2, transfer);
644
+ const fail = (id, error, started) => reply({ t: "done", id, ok: false, error: error instanceof Error ? error.message : String(error), ms: now() - started });
645
+ scope.onmessage = (event) => {
646
+ const message2 = event.data;
647
+ if (!isToWorker(message2)) return;
648
+ switch (message2.t) {
649
+ case "hello":
650
+ reply({ t: "hello", id: message2.id, kinds: [...byId.keys()] });
651
+ return;
652
+ case "task": {
653
+ const started = now();
654
+ const kind = byId.get(message2.kind);
655
+ if (!kind || kind.kind !== "task") return fail(message2.id, new Error(`this worker has no task kind ${message2.kind}`), started);
656
+ try {
657
+ const output = kind.run(message2.input);
658
+ reply({ t: "done", id: message2.id, ok: true, output, ms: now() - started }, kind.transferOutput?.(output) ?? []);
659
+ } catch (error) {
660
+ fail(message2.id, error, started);
661
+ }
662
+ return;
663
+ }
664
+ case "create": {
665
+ const kind = byId.get(message2.kind);
666
+ if (kind?.kind === "resident") residents.set(message2.rid, { kind, instance: kind.create(message2.init) });
667
+ return;
668
+ }
669
+ case "step": {
670
+ const started = now();
671
+ const resident = residents.get(message2.rid);
672
+ if (!resident) return fail(message2.id, new Error(`this worker has no resident ${message2.rid}`), started);
673
+ try {
674
+ const output = resident.instance.step(message2.input);
675
+ reply({ t: "done", id: message2.id, ok: true, output, ms: now() - started }, resident.kind.transferOutput?.(output) ?? []);
676
+ } catch (error) {
677
+ fail(message2.id, error, started);
678
+ }
679
+ return;
680
+ }
681
+ case "dispose":
682
+ residents.get(message2.rid)?.instance.dispose?.();
683
+ residents.delete(message2.rid);
684
+ return;
685
+ }
686
+ };
687
+ }
688
+
689
+ // src/in-thread.ts
690
+ function inThreadSpawn(kinds, options = {}) {
691
+ return () => {
692
+ let alive = true;
693
+ const worker = {
694
+ onmessage: null,
695
+ onerror: null,
696
+ postMessage(message2, transfer = []) {
697
+ const copy = structuredClone(message2, { transfer: [...transfer] });
698
+ setTimeout(() => alive && scope.onmessage?.({ data: copy }), 0);
699
+ },
700
+ terminate() {
701
+ alive = false;
702
+ }
703
+ };
704
+ const scope = {
705
+ onmessage: null,
706
+ postMessage(message2, transfer = []) {
707
+ const copy = structuredClone(message2, { transfer: [...transfer] });
708
+ setTimeout(() => alive && worker.onmessage?.({ data: copy }), options.delayMs ?? 0);
709
+ }
710
+ };
711
+ installWorkerHost(scope, kinds);
712
+ return worker;
713
+ };
714
+ }
715
+
716
+ // src/check.ts
717
+ var bytesOf = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
718
+ function firstDifference(a, b, path = "output") {
719
+ if (ArrayBuffer.isView(a) || ArrayBuffer.isView(b)) {
720
+ if (!ArrayBuffer.isView(a) || !ArrayBuffer.isView(b) || a.constructor !== b.constructor) return `${path}: not the same kind of array`;
721
+ const x = bytesOf(a);
722
+ const y = bytesOf(b);
723
+ if (x.length !== y.length) return `${path}: ${x.length} bytes against ${y.length}`;
724
+ for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return `${path}: byte ${i} differs`;
725
+ return null;
726
+ }
727
+ if (a instanceof ArrayBuffer || b instanceof ArrayBuffer) {
728
+ if (!(a instanceof ArrayBuffer) || !(b instanceof ArrayBuffer)) return `${path}: not both ArrayBuffers`;
729
+ return firstDifference(new Uint8Array(a), new Uint8Array(b), path);
730
+ }
731
+ if (typeof a !== "object" || a === null || typeof b !== "object" || b === null) return Object.is(a, b) ? null : `${path}: ${String(a)} against ${String(b)}`;
732
+ if (Array.isArray(a) !== Array.isArray(b)) return `${path}: an array against an object`;
733
+ const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
734
+ for (const key of keys) {
735
+ const difference = firstDifference(a[key], b[key], `${path}.${key}`);
736
+ if (difference) return difference;
737
+ }
738
+ return null;
739
+ }
740
+ async function checkTaskKind(kind, samples, spawns = [], extraKinds = []) {
741
+ const problems = [];
742
+ const any = kind;
743
+ const paths = [{ name: "in-thread worker", spawn: inThreadSpawn([any, ...extraKinds]) }, ...spawns.map((spawn, i) => ({ name: `worker ${i + 1}`, spawn }))];
744
+ for (const path of paths) {
745
+ const coordinator = createWorkerCoordinator({ spawn: path.spawn, workers: 1 });
746
+ try {
747
+ await coordinator.warm([any]);
748
+ for (let i = 0; i < samples.length; i++) {
749
+ const reference = kind.run(structuredClone(samples[i]));
750
+ const handle = coordinator.submit(kind, structuredClone(samples[i]), { frame: 0 });
751
+ const out = await handle.promise;
752
+ if (handle.source !== "worker") problems.push(`${kind.id} sample ${i}: ${path.name} did not answer (${handle.source ?? "no result"})`);
753
+ const difference = firstDifference(reference, out);
754
+ if (difference) problems.push(`${kind.id} sample ${i}, ${path.name}: ${difference}`);
755
+ if (kind.transferAwaitedInput) {
756
+ const awaited = firstDifference(reference, await coordinator.run(kind, structuredClone(samples[i])));
757
+ if (awaited) problems.push(`${kind.id} sample ${i}, ${path.name}, awaited: ${awaited}`);
758
+ }
759
+ }
760
+ } catch (error) {
761
+ problems.push(`${kind.id}, ${path.name}: ${error instanceof Error ? error.message : String(error)}`);
762
+ } finally {
763
+ coordinator.dispose();
764
+ }
765
+ }
766
+ return { ok: problems.length === 0, problems };
767
+ }
768
+
769
+ // src/spawn.ts
770
+ var workerConstructor = () => globalThis.Worker ?? null;
771
+ var canSpawnBrowserWorkers = () => workerConstructor() !== null;
772
+ var wrap = (worker) => {
773
+ const like = {
774
+ onmessage: null,
775
+ onerror: null,
776
+ postMessage: (message2, transfer = []) => worker.postMessage(message2, [...transfer]),
777
+ terminate: () => worker.terminate()
778
+ };
779
+ worker.onmessage = (event) => like.onmessage?.(event);
780
+ worker.onerror = (event) => like.onerror?.(event);
781
+ return like;
782
+ };
783
+ function browserSpawn(url, options = {}) {
784
+ return () => {
785
+ const Ctor = workerConstructor();
786
+ if (!Ctor) throw new Error("browserSpawn: no Worker in this runtime");
787
+ return wrap(new Ctor(url, { type: options.type ?? "module", ...options.name ? { name: options.name } : {} }));
788
+ };
789
+ }
790
+ function sourceSpawn(source, options = {}) {
791
+ let url = null;
792
+ return () => {
793
+ if (!url) {
794
+ if (typeof Blob === "undefined" || typeof URL.createObjectURL !== "function") throw new Error("sourceSpawn: no Blob URLs in this runtime");
795
+ url = URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
796
+ }
797
+ return browserSpawn(url, options)();
798
+ };
799
+ }
800
+
801
+ // src/shared.ts
802
+ var HEADER_BYTES = 32;
803
+ var SLOTS = 3;
804
+ var PUBLISHED = 0;
805
+ var CLAIMED = 1;
806
+ var FRAME = 2;
807
+ var align8 = (n) => Math.ceil(n / 8) * 8;
808
+ function canShareMemory() {
809
+ if (typeof SharedArrayBuffer === "undefined" || typeof Atomics === "undefined") return false;
810
+ const isolated = globalThis.crossOriginIsolated;
811
+ return isolated !== false;
812
+ }
813
+ function createSnapshotBuffer(bytes) {
814
+ return new SharedArrayBuffer(HEADER_BYTES + SLOTS * align8(bytes));
815
+ }
816
+ var slotBytes = (buffer) => (buffer.byteLength - HEADER_BYTES) / SLOTS;
817
+ var SnapshotWriter = class {
818
+ constructor(buffer) {
819
+ __publicField(this, "buffer", buffer);
820
+ __publicField(this, "header");
821
+ __publicField(this, "views");
822
+ __publicField(this, "slot", -1);
823
+ this.header = new Int32Array(buffer, 0, HEADER_BYTES / 4);
824
+ const size = slotBytes(buffer);
825
+ this.views = Array.from({ length: SLOTS }, (_, k) => new Uint8Array(buffer, HEADER_BYTES + k * size, size));
826
+ }
827
+ /** A slot neither published nor being read: there is always one of the three. */
828
+ begin() {
829
+ const published = Atomics.load(this.header, PUBLISHED) - 1;
830
+ const claimed = Atomics.load(this.header, CLAIMED) - 1;
831
+ let slot = 0;
832
+ while (slot === published || slot === claimed) slot++;
833
+ this.slot = slot;
834
+ return this.views[slot];
835
+ }
836
+ commit(frame) {
837
+ if (this.slot < 0) throw new Error("SnapshotWriter.commit: no begin");
838
+ Atomics.store(this.header, FRAME + this.slot, frame);
839
+ Atomics.store(this.header, PUBLISHED, this.slot + 1);
840
+ this.slot = -1;
841
+ }
842
+ };
843
+ var SnapshotReader = class {
844
+ constructor(buffer) {
845
+ __publicField(this, "buffer", buffer);
846
+ __publicField(this, "header");
847
+ __publicField(this, "size");
848
+ __publicField(this, "views");
849
+ this.header = new Int32Array(buffer, 0, HEADER_BYTES / 4);
850
+ this.size = slotBytes(buffer);
851
+ this.views = Array.from({ length: SLOTS }, (_, k) => new Uint8Array(buffer, HEADER_BYTES + k * this.size, this.size));
852
+ }
853
+ latest() {
854
+ for (; ; ) {
855
+ const published = Atomics.load(this.header, PUBLISHED);
856
+ if (published === 0) return null;
857
+ Atomics.store(this.header, CLAIMED, published);
858
+ if (Atomics.load(this.header, PUBLISHED) !== published) continue;
859
+ const slot = published - 1;
860
+ return {
861
+ frame: Atomics.load(this.header, FRAME + slot),
862
+ buffer: this.buffer,
863
+ byteOffset: HEADER_BYTES + slot * this.size,
864
+ byteLength: this.size,
865
+ bytes: this.views[slot]
866
+ };
867
+ }
868
+ }
869
+ /** Lets the writer take the slot of the last snapshot (the reader is done with it). */
870
+ release() {
871
+ Atomics.store(this.header, CLAIMED, 0);
872
+ }
873
+ };
874
+ var RING_HEADER_BYTES = 8;
875
+ function createCommandBuffer(width, capacity) {
876
+ if (!Number.isInteger(width) || width < 1 || !Number.isInteger(capacity) || capacity < 1) throw new Error("createCommandBuffer: width and capacity are integers >= 1");
877
+ const buffer = new SharedArrayBuffer(RING_HEADER_BYTES + 8 + width * capacity * 8);
878
+ new Float64Array(buffer, RING_HEADER_BYTES, 1)[0] = width;
879
+ return buffer;
880
+ }
881
+ var CommandRing = class {
882
+ constructor(buffer) {
883
+ __publicField(this, "buffer", buffer);
884
+ __publicField(this, "header");
885
+ __publicField(this, "data");
886
+ __publicField(this, "width");
887
+ __publicField(this, "capacity");
888
+ this.header = new Int32Array(buffer, 0, 2);
889
+ this.width = new Float64Array(buffer, RING_HEADER_BYTES, 1)[0];
890
+ this.data = new Float64Array(buffer, RING_HEADER_BYTES + 8);
891
+ this.capacity = this.data.length / this.width;
892
+ }
893
+ push(command) {
894
+ if (command.length > this.width) throw new Error(`CommandRing.push: ${command.length} numbers, the ring holds ${this.width}`);
895
+ const written = Atomics.load(this.header, 0);
896
+ if (written - Atomics.load(this.header, 1) >= this.capacity) return false;
897
+ const at = written % this.capacity * this.width;
898
+ this.data.fill(0, at, at + this.width);
899
+ for (let k = 0; k < command.length; k++) this.data[at + k] = command[k];
900
+ Atomics.store(this.header, 0, written + 1);
901
+ return true;
902
+ }
903
+ /** Every command pushed so far, oldest first, each a copy. */
904
+ drain() {
905
+ const written = Atomics.load(this.header, 0);
906
+ const read = Atomics.load(this.header, 1);
907
+ const out = [];
908
+ for (let k = read; k < written; k++) {
909
+ const at = k % this.capacity * this.width;
910
+ out.push(this.data.slice(at, at + this.width));
911
+ }
912
+ Atomics.store(this.header, 1, written);
913
+ return out;
914
+ }
915
+ };
916
+
917
+ // src/sim-thread.ts
918
+ var STOP = 0;
919
+ var STEPS = 1;
920
+ var WAKE = 2;
921
+ var DROPPED = 3;
922
+ var LAST_MS = 0;
923
+ var SUM_MS = 1;
924
+ var MAX_MS = 2;
925
+ var CONTROL_BYTES = 64;
926
+ var now2 = () => typeof performance !== "undefined" ? performance.now() : Date.now();
927
+ var message = (error) => error instanceof Error ? error.message : String(error);
928
+ var isThenable = (value) => typeof value === "object" && value !== null && typeof value.then === "function";
929
+ async function simLoop(instance, options, io) {
930
+ const stepSeconds = options.stepSeconds ?? 1 / 60;
931
+ const stepMs = stepSeconds * 1e3;
932
+ const paced = options.paced ?? true;
933
+ const maxCatchUp = options.maxCatchUp ?? 4;
934
+ const words = new Int32Array(io.control, 0, 8);
935
+ const numbers = new Float64Array(io.control, 32, 4);
936
+ let frame = 0;
937
+ let next = now2();
938
+ while (Atomics.load(words, STOP) === 0 && (options.steps === void 0 || frame < options.steps)) {
939
+ if (paced) {
940
+ const wait = next - now2();
941
+ if (wait > 0.25) {
942
+ io.sleep(wait);
943
+ continue;
944
+ }
945
+ if (-wait > maxCatchUp * stepMs) {
946
+ next = now2();
947
+ Atomics.add(words, DROPPED, 1);
948
+ }
949
+ }
950
+ io.beforeStep?.(frame);
951
+ const commands = io.ring.drain();
952
+ const started = now2();
953
+ const stepped = instance.step(frame, stepSeconds, commands);
954
+ if (isThenable(stepped)) await stepped;
955
+ instance.write(io.writer.begin(), frame);
956
+ io.writer.commit(frame);
957
+ const ms = now2() - started;
958
+ numbers[LAST_MS] = ms;
959
+ numbers[SUM_MS] = numbers[SUM_MS] + ms;
960
+ if (ms > numbers[MAX_MS]) numbers[MAX_MS] = ms;
961
+ frame++;
962
+ Atomics.store(words, STEPS, frame);
963
+ next += stepMs;
964
+ }
965
+ return frame;
966
+ }
967
+ var statsOf = (control) => {
968
+ const words = new Int32Array(control, 0, 8);
969
+ const numbers = new Float64Array(control, 32, 4);
970
+ const steps = Atomics.load(words, STEPS);
971
+ return { steps, lastStepMs: numbers[LAST_MS], meanStepMs: steps ? numbers[SUM_MS] / steps : 0, maxStepMs: numbers[MAX_MS], dropped: Atomics.load(words, DROPPED) };
972
+ };
973
+ var isToSim = (data) => typeof data === "object" && data !== null && data.t === "sim-start";
974
+ var isFromSim = (data) => typeof data === "object" && data !== null && typeof data.t === "string";
975
+ function installSimThread(scope, modules) {
976
+ const byId = new Map(modules.map((m) => [m.id, m]));
977
+ scope.onmessage = (event) => {
978
+ const start = event.data;
979
+ if (!isToSim(start)) return;
980
+ const reply = (m) => scope.postMessage(m);
981
+ const module = byId.get(start.module);
982
+ if (!module) {
983
+ reply({ t: "sim-error", error: `installSimThread: no module ${start.module} (this thread has ${[...byId.keys()].join(", ") || "none"})` });
984
+ return;
985
+ }
986
+ const words = new Int32Array(start.control, 0, 8);
987
+ const io = {
988
+ ring: new CommandRing(start.commands),
989
+ writer: new SnapshotWriter(start.snapshot),
990
+ control: start.control,
991
+ // a worker may wait: this is the native engine's sleep, woken early by `stop`
992
+ sleep: (ms) => void Atomics.wait(words, WAKE, 0, ms)
993
+ };
994
+ void (async () => {
995
+ let instance = null;
996
+ try {
997
+ instance = await module.create(start.init);
998
+ reply({ t: "sim-ready" });
999
+ reply({ t: "sim-done", steps: await simLoop(instance, start.loop, io) });
1000
+ } catch (error) {
1001
+ reply({ t: "sim-error", error: message(error) });
1002
+ } finally {
1003
+ instance?.dispose?.();
1004
+ }
1005
+ })();
1006
+ };
1007
+ }
1008
+ var canRunSimThread = () => canShareMemory();
1009
+ function startSimThread(spawn, options) {
1010
+ if (!canShareMemory()) throw new Error("startSimThread: no shared memory here (SharedArrayBuffer and cross-origin isolation: COOP/COEP, always on in Electron)");
1011
+ const snapshot = createSnapshotBuffer(options.snapshotBytes);
1012
+ const commands = createCommandBuffer(options.commandWidth ?? 8, options.commandCapacity ?? 256);
1013
+ const control = new SharedArrayBuffer(CONTROL_BYTES);
1014
+ const words = new Int32Array(control, 0, 8);
1015
+ const reader = new SnapshotReader(snapshot);
1016
+ const ring = new CommandRing(commands);
1017
+ const worker = spawn();
1018
+ let readyResolve;
1019
+ let readyReject;
1020
+ let doneResolve;
1021
+ let doneReject;
1022
+ const ready = new Promise((resolve, reject) => (readyResolve = resolve, readyReject = reject));
1023
+ const done = new Promise((resolve, reject) => (doneResolve = resolve, doneReject = reject));
1024
+ done.catch(() => {
1025
+ });
1026
+ const fail = (error) => {
1027
+ readyReject(error);
1028
+ doneReject(error);
1029
+ };
1030
+ worker.onmessage = (event) => {
1031
+ const data = event.data;
1032
+ if (!isFromSim(data)) return;
1033
+ if (data.t === "sim-ready") readyResolve();
1034
+ else if (data.t === "sim-done") doneResolve(data.steps);
1035
+ else fail(new Error(data.error));
1036
+ };
1037
+ worker.onerror = (event) => fail(event instanceof Error ? event : new Error(`simulation thread failed: ${message(event.message ?? event)}`));
1038
+ const loop = {
1039
+ ...options.stepSeconds !== void 0 ? { stepSeconds: options.stepSeconds } : {},
1040
+ ...options.steps !== void 0 ? { steps: options.steps } : {},
1041
+ ...options.paced !== void 0 ? { paced: options.paced } : {},
1042
+ ...options.maxCatchUp !== void 0 ? { maxCatchUp: options.maxCatchUp } : {}
1043
+ };
1044
+ const start = { t: "sim-start", module: options.module, init: options.init, snapshot, commands, control, loop };
1045
+ worker.postMessage(start);
1046
+ const stop = () => {
1047
+ Atomics.store(words, STOP, 1);
1048
+ Atomics.notify(words, WAKE);
1049
+ };
1050
+ return {
1051
+ ready,
1052
+ done,
1053
+ latest: () => reader.latest(),
1054
+ send: (command) => ring.push(command),
1055
+ stats: () => statsOf(control),
1056
+ stop,
1057
+ dispose: () => {
1058
+ stop();
1059
+ worker.terminate();
1060
+ }
1061
+ };
1062
+ }
1063
+ async function runSimInline(module, init, options) {
1064
+ const snapshot = createSnapshotBuffer(options.snapshotBytes);
1065
+ const control = new SharedArrayBuffer(CONTROL_BYTES);
1066
+ const ring = new CommandRing(createCommandBuffer(options.commandWidth ?? 8, 4096));
1067
+ const instance = await module.create(init);
1068
+ try {
1069
+ await simLoop(instance, { steps: options.steps, paced: false, ...options.stepSeconds !== void 0 ? { stepSeconds: options.stepSeconds } : {} }, {
1070
+ ring,
1071
+ writer: new SnapshotWriter(snapshot),
1072
+ control,
1073
+ sleep: () => {
1074
+ },
1075
+ beforeStep: (frame) => {
1076
+ for (const command of options.commands?.[frame] ?? []) if (!ring.push(command)) throw new Error("runSimInline: more commands in one frame than the ring holds");
1077
+ }
1078
+ });
1079
+ } finally {
1080
+ instance.dispose?.();
1081
+ }
1082
+ return new SnapshotReader(snapshot).latest().bytes.slice();
1083
+ }
1084
+ return __toCommonJS(index_exports);
1085
+ })();
1086
+ //# sourceMappingURL=index.global.js.map