@wasm-gaming/rsdkv4-wasm 0.1.5 → 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.
@@ -1,55 +1,85 @@
1
- // @wasm-gaming/rsdkv4-wasm — SDK entry point.
2
- //
3
- // Conforms to the wasm-gaming engine contract (github.com/wasm-gaming/engine-specs):
4
- // exports `manifest` (declarative) and `load(config)` (imperative).
5
- //
6
- // One game-agnostic rsdkv4.wasm runs both Sonic 1 and Sonic 2 — the difference is
7
- // only which Data.rsdk the host hands us in `config.assets.data`, written into the
8
- // filesystem at runtime (not baked with --preload-file).
9
- //
10
- // Filesystem: built with -sWASMFS (the modern Emscripten filesystem, not MEMFS).
11
- // The game working dir `/data` is mounted on **OPFS** for persistence when the
12
- // page is cross-origin isolated *and* the wasm build can create the OPFS backend
13
- // from the main thread (an Asyncify/JSPI build — today's is not, see WebFS.cpp);
14
- // otherwise it falls back to the WASMFS in-memory backend (transient, but the
15
- // engine still boots). The backend is selectable via
16
- // `config.persist` (see mountWorkingDir), and when the dir is OPFS-backed the SDK
17
- // reuses an already-persisted Data.rsdk/settings.ini instead of re-fetching.
18
- import { manifest } from './rsdkv4.manifest.js';
19
- import { DEFAULT_RSDKV4_OPTIONS } from './rsdkv4.options.js';
20
- export { manifest };
1
+ /**
2
+ * The engine package's entry point: an `EngineSDK` for RSDKv4.
3
+ *
4
+ * ```ts
5
+ * import Rsdkv4SDK from '@wasm-gaming/rsdkv4-wasm';
6
+ *
7
+ * const play = await new Rsdkv4SDK()
8
+ * .mount(document.querySelector('#stage'))
9
+ * .assets({ data: () => library.readBytes('Sonic2') })
10
+ * .storage({ namespace: 'rsdkv4/Sonic2' })
11
+ * .config({ startMenu: 'host' })
12
+ * .on('saves', ({ detail }) => paintSlots(detail))
13
+ * .start({ slot: 0 });
14
+ * ```
15
+ *
16
+ * Everything a host drives is the contract's, and documented there: the four payloads
17
+ * with their descriptors, `mount`, `on`/`off`, `start`, `restart`, `destroy`. What is
18
+ * this engine's own lives in two places — {@link Rsdkv4Config} and friends, which say
19
+ * what the payloads accept *here*, and the extra members of {@link Rsdkv4Play} below:
20
+ * {@link Rsdkv4Play.game} and {@link Rsdkv4Play.devMenu}, for a host that draws
21
+ * RSDKv4's start screens itself, owner-aware {@link Rsdkv4Play.pause}, and
22
+ * {@link Rsdkv4Play.input}, for a host that would rather drive the buttons than let
23
+ * the engine read the keyboard.
24
+ *
25
+ * One game-agnostic `rsdkv4.wasm` runs both Sonic 1 and Sonic 2 — the difference is
26
+ * only which `Data.rsdk` the host hands over in `assets.data`, written into the
27
+ * filesystem at runtime (not baked with `--preload-file`).
28
+ *
29
+ * Filesystem: built with `-sWASMFS`. The working dir is mounted on **OPFS** when the
30
+ * page is cross-origin isolated *and* the build can create the OPFS backend from the
31
+ * main thread (an Asyncify/JSPI build — today's is not, see `WebFS.cpp`); otherwise it
32
+ * falls back to the WASMFS in-memory backend, which boots fine but forgets everything.
33
+ * That fallback is why the SDK mirrors `SData.bin` into OPFS itself: see
34
+ * {@link Rsdkv4Storage.persist}.
35
+ *
36
+ * @module
37
+ * @see [The engine contract](https://wasm-gaming.github.io/engine-specs/api-docs/)
38
+ */
39
+ import { EnginePlayBase, EngineSDKBase, EventEmitter } from '@wasm-gaming/engine-specs';
40
+ import { RSDKV4_BUTTONS, RSDKV4_SPEC, } from './rsdkv4.options.js';
41
+ export { RSDKV4_BUTTONS, RSDKV4_INPUT, RSDKV4_SPEC } from './rsdkv4.options.js';
21
42
  const WORK_ROOT = '/data';
22
43
  const DEFAULT_STORAGE_NAMESPACE = 'default';
44
+ /** RSDKv4's save file, written next to the game data in the working dir. */
45
+ const SAVE_FILE = 'SData.bin';
23
46
  /**
24
47
  * Emscripten's SDL2 port locates the canvas via `document.querySelector('#canvas')`,
25
48
  * so the element the game draws into has to carry this id.
26
49
  */
27
50
  const CANVAS_ID = 'canvas';
28
51
  /**
29
- * Serialize engine options into RSDKv4's settings.ini format.
52
+ * The picture's native size, which is what the SDK scales to fit its mount.
30
53
  *
31
- * Note the Starting* trio defaults to 255 ("unset") — writing 0 is not neutral,
32
- * it tells the engine to skip its start-menu flow and force that stage. See
33
- * DEFAULT_RSDKV4_OPTIONS.
54
+ * A module constant rather than a manifest field: `EngineManifest` left the contract
55
+ * in 0.3.0, and this was one of only two things the SDK ever read back out of it.
34
56
  */
35
- function buildSettingsIni(options = {}) {
36
- const o = { ...DEFAULT_RSDKV4_OPTIONS, ...options };
37
- return [
38
- '[Dev]',
39
- `EngineDebugMode=${o.engineDebugMode ? 'true' : 'false'}`,
40
- `DevMenu=${o.devMenu ? 'true' : 'false'}`,
41
- `StartingCategory=${o.startingCategory | 0}`,
42
- `StartingScene=${o.startingScene | 0}`,
43
- `StartingPlayer=${o.startingPlayer | 0}`,
44
- '',
45
- '[Game]',
46
- `SkipStartMenu=${o.skipStartMenu ? 'true' : 'false'}`,
47
- '',
48
- '[Window]',
49
- `VSync=${o.vsync ? 'true' : 'false'}`,
50
- '',
51
- ].join('\n');
52
- }
57
+ export const RSDKV4_VIDEO = { baseWidth: 424, baseHeight: 240, aspect: '16:9' };
58
+ /**
59
+ * The embind bridges this SDK drives the engine through. All of them ship in the same
60
+ * rsdkv4.wasm, so a module missing any one of them is an artifact older than this SDK
61
+ * rather than a build variant.
62
+ */
63
+ const ENGINE_BRIDGES = [
64
+ 'web_engine_ready',
65
+ 'web_game_type',
66
+ 'web_get_players',
67
+ 'web_get_save_slots',
68
+ 'web_get_game_options',
69
+ 'web_start_game',
70
+ 'web_audio_stop',
71
+ 'web_devmenu_get_stage_list',
72
+ 'web_input_set_source',
73
+ ];
74
+ /**
75
+ * The name the engine's `web_input_pull()` looks the reader up under, on the module
76
+ * object itself rather than on a global: two engines on one page have two modules,
77
+ * and a global would have them fighting over one claim.
78
+ */
79
+ const INPUT_PULL_HOOK = '__rsdkv4_input_pull';
80
+ /** How often a pull that keeps throwing is allowed to say so. See {@link Rsdkv4Play}. */
81
+ const INPUT_ERROR_INTERVAL_MS = 1000;
82
+ // ---------------------------------------------------------------- small helpers
53
83
  function toUint8(x) {
54
84
  if (x == null)
55
85
  return null;
@@ -61,9 +91,15 @@ function toUint8(x) {
61
91
  return new Uint8Array(x);
62
92
  if (ArrayBuffer.isView(x))
63
93
  return new Uint8Array(x.buffer, x.byteOffset, x.byteLength);
64
- throw new TypeError('asset must be Uint8Array | ArrayBuffer | string');
94
+ throw new TypeError('rsdkv4: an asset must be Uint8Array | ArrayBuffer | string');
95
+ }
96
+ /** Bytes for an asset, calling the thunk form only when we get this far. */
97
+ async function resolveAsset(asset) {
98
+ if (asset == null)
99
+ return null;
100
+ return toUint8(typeof asset === 'function' ? await asset() : asset);
65
101
  }
66
- /** Normalize a user-provided storage namespace into a safe relative path. */
102
+ /** Normalize a host-provided storage namespace into a safe relative path. */
67
103
  function normalizeStorageNamespace(namespace) {
68
104
  if (typeof namespace !== 'string' || !namespace.trim())
69
105
  return DEFAULT_STORAGE_NAMESPACE;
@@ -76,6 +112,51 @@ function normalizeStorageNamespace(namespace) {
76
112
  .join('/');
77
113
  return cleaned || DEFAULT_STORAGE_NAMESPACE;
78
114
  }
115
+ /** The plain values behind a descriptor table — what the engine actually needs. */
116
+ function valuesOf(described) {
117
+ const out = {};
118
+ for (const [key, property] of Object.entries(described)) {
119
+ out[key] = property.value;
120
+ }
121
+ return out;
122
+ }
123
+ /**
124
+ * Serialize {@link Rsdkv4Config} into RSDKv4's settings.ini format.
125
+ *
126
+ * The `Starting*` trio is written as 255 — the engine's "unset" — and never anything
127
+ * else. That is not a leftover: anything else there, **including 0**, makes
128
+ * `Engine::Init` skip its normal boot flow and force a stage (see Userdata.cpp). The
129
+ * session's own `stage` is applied after boot instead, through the engine's stage
130
+ * loader, which is why it survives a `restart()`.
131
+ */
132
+ function buildSettingsIni(config) {
133
+ return [
134
+ '[Dev]',
135
+ `EngineDebugMode=${config.engineDebugMode ? 'true' : 'false'}`,
136
+ `DevMenu=${config.devMenu ? 'true' : 'false'}`,
137
+ 'StartingCategory=255',
138
+ 'StartingScene=255',
139
+ 'StartingPlayer=255',
140
+ '',
141
+ '[Game]',
142
+ `SkipStartMenu=${config.startMenu === 'host' ? 'true' : 'false'}`,
143
+ '',
144
+ '[Window]',
145
+ `VSync=${config.vsync ? 'true' : 'false'}`,
146
+ '',
147
+ ].join('\n');
148
+ }
149
+ function sameBytes(a, b) {
150
+ if (a === null || b === null)
151
+ return a === b;
152
+ if (a.length !== b.length)
153
+ return false;
154
+ for (let i = 0; i < a.length; i += 1)
155
+ if (a[i] !== b[i])
156
+ return false;
157
+ return true;
158
+ }
159
+ // ---------------------------------------------------------------- the wasm filesystem
79
160
  /** Best-effort mkdir -p for the Emscripten FS layer. */
80
161
  function ensureDir(Module, path) {
81
162
  const parts = path.split('/').filter(Boolean);
@@ -90,15 +171,25 @@ function ensureDir(Module, path) {
90
171
  }
91
172
  }
92
173
  }
174
+ /** True if `path` exists in the (mounted) filesystem. */
175
+ function fileExists(Module, path) {
176
+ try {
177
+ Module.FS.stat(path);
178
+ return true;
179
+ }
180
+ catch {
181
+ return false;
182
+ }
183
+ }
93
184
  /**
94
185
  * Whether this build can mount OPFS at all, asked of the wasm itself.
95
186
  *
96
- * WASMFS's `wasmfs_create_opfs_backend()` spawns a proxy worker synchronously,
97
- * which it refuses to do on the main browser thread without Asyncify/JSPI — it
98
- * *asserts*, and a failed assert calls `abort()`, which tears the module down for
99
- * good. That is past the point where a try/catch around the call can save us, so
100
- * we have to know before calling. `web_opfs_supported` (WebFS.cpp) mirrors the
101
- * same condition; builds predating that helper simply answer "no".
187
+ * WASMFS's `wasmfs_create_opfs_backend()` spawns a proxy worker synchronously, which it
188
+ * refuses to do on the main browser thread without Asyncify/JSPI — it *asserts*, and a
189
+ * failed assert calls `abort()`, which tears the module down for good. That is past the
190
+ * point where a try/catch around the call can save us, so we have to know before
191
+ * calling. `web_opfs_supported` (WebFS.cpp) mirrors the same condition; builds predating
192
+ * that helper simply answer "no".
102
193
  */
103
194
  function opfsMountSupported(Module) {
104
195
  const probe = Module._web_opfs_supported;
@@ -112,16 +203,12 @@ function opfsMountSupported(Module) {
112
203
  }
113
204
  }
114
205
  /**
115
- * Mount the game working dir, honoring `persist`:
116
- * 'opfs' → force an OPFS (persistent) mount; warn + fall back if unavailable.
117
- * null → force the in-memory WASMFS backend (the MEMFS-equivalent fallback).
118
- * undefined → auto: OPFS when the page is cross-origin isolated, else in-memory.
119
- * ('idbfs' isn't supported under WASMFS and is treated as in-memory.)
206
+ * Mount the game working dir, honouring {@link Rsdkv4Storage.persist}. Returns whether
207
+ * the resulting mount is persistent.
120
208
  *
121
- * Cross-origin isolation is necessary but not sufficient: the mount also needs a
122
- * build whose OPFS backend can run from where we call it (see opfsMountSupported),
123
- * so both gates apply before we touch `web_mount_opfs`.
124
- * Returns whether the resulting mount is persistent.
209
+ * Cross-origin isolation is necessary but not sufficient: the mount also needs a build
210
+ * whose OPFS backend can run from where we call it (see {@link opfsMountSupported}), so
211
+ * both gates apply before we touch `web_mount_opfs`.
125
212
  */
126
213
  function mountWorkingDir(Module, persist) {
127
214
  const isolated = typeof crossOriginIsolated !== 'undefined' && crossOriginIsolated;
@@ -142,20 +229,29 @@ function mountWorkingDir(Module, persist) {
142
229
  ensureDir(Module, WORK_ROOT);
143
230
  return { persistent: false };
144
231
  }
145
- /** True if `path` exists in the (mounted) filesystem. */
146
- function fileExists(Module, path) {
232
+ /**
233
+ * OPFS handle for `<namespace>/`, reached with the plain (async) OPFS API from JS —
234
+ * which, unlike the WASM side's sync access handles, works on the main thread of any
235
+ * page. Returns null when OPFS isn't available at all.
236
+ */
237
+ async function opfsNamespaceDir(namespace, create) {
238
+ if (typeof navigator === 'undefined' || !navigator.storage?.getDirectory)
239
+ return null;
147
240
  try {
148
- Module.FS.stat(path);
149
- return true;
241
+ let dir = await navigator.storage.getDirectory();
242
+ for (const segment of namespace.split('/').filter(Boolean)) {
243
+ dir = await dir.getDirectoryHandle(segment, { create });
244
+ }
245
+ return dir;
150
246
  }
151
247
  catch {
152
- return false;
248
+ return null; // missing (create: false), or blocked
153
249
  }
154
250
  }
155
251
  /**
156
- * Wait for Engine::Init, which runs on the engine's first frame (main.cpp's
157
- * main_loop), not inside callMain. Gives up after ~4s rather than hanging the
158
- * host: everything still works, the first read just comes back empty.
252
+ * Wait for `Engine::Init`, which runs on the engine's first frame (main.cpp's
253
+ * main_loop), not inside `callMain`. Gives up after ~4s rather than hanging the host:
254
+ * everything still works, the first read just comes back empty.
159
255
  */
160
256
  async function waitForEngine(Module, timeoutMs = 4000) {
161
257
  if (typeof Module.web_engine_ready !== 'function')
@@ -169,416 +265,836 @@ async function waitForEngine(Module, timeoutMs = 4000) {
169
265
  console.warn('[rsdkv4] engine did not report ready within %dms', timeoutMs);
170
266
  return false;
171
267
  }
172
- /**
173
- * The embind bridges this SDK drives the engine through. All of them ship in the
174
- * same rsdkv4.wasm, so a module missing any one of them is an artifact older
175
- * than this SDK rather than a build variant.
176
- */
177
- const ENGINE_BRIDGES = [
178
- 'web_engine_ready',
179
- 'web_game_type',
180
- 'web_get_players',
181
- 'web_get_save_slots',
182
- 'web_get_game_options',
183
- 'web_start_game',
184
- 'web_audio_stop',
185
- 'web_devmenu_get_stage_list',
186
- ];
187
268
  function engineBridgeComplete(Module) {
188
269
  return ENGINE_BRIDGES.every((name) => typeof Module?.[name] === 'function');
189
270
  }
190
- /** RSDKv4's save file, written next to the game data in the working dir. */
191
- const SAVE_FILE = 'SData.bin';
271
+ // ---------------------------------------------------------------- the live engine
192
272
  /**
193
- * OPFS handle for `<namespace>/`, reached with the plain (async) OPFS API from
194
- * JS — which, unlike the WASM side's sync access handles, works on the main
195
- * thread of any page. Returns null when OPFS isn't available at all.
273
+ * The running engine.
274
+ *
275
+ * Most of it is the contract's, inherited: the four getter/setter pairs, the cumulative
276
+ * merge, the chainable promise, the event channel, and `destroy()`. What this class
277
+ * adds is the four hooks the base leaves to an engine — {@link open}, {@link close},
278
+ * {@link mounted}, {@link patched} — plus the members below, which have no contract
279
+ * equivalent and exist because RSDKv4 has a start menu worth drawing from HTML.
196
280
  */
197
- async function opfsNamespaceDir(namespace, create) {
198
- if (typeof navigator === 'undefined' || !navigator.storage?.getDirectory)
199
- return null;
200
- try {
201
- let dir = await navigator.storage.getDirectory();
202
- for (const segment of namespace.split('/').filter(Boolean)) {
203
- dir = await dir.getDirectoryHandle(segment, { create });
281
+ export class Rsdkv4Play extends EnginePlayBase {
282
+ #module = null;
283
+ /** In flight, so two concurrent `restart()`s do not boot two engines. */
284
+ #booting = null;
285
+ #destroyed = false;
286
+ #canvas = null;
287
+ /** False when the host handed us its own canvas: then we neither size nor remove it. */
288
+ #ownsCanvas = false;
289
+ /** The element the picture has to fit inside, in CSS pixels. */
290
+ #box = null;
291
+ #boxObserver = null;
292
+ #persistent = false;
293
+ #namespace = DEFAULT_STORAGE_NAMESPACE;
294
+ #workDir = `${WORK_ROOT}/${DEFAULT_STORAGE_NAMESPACE}`;
295
+ #mirrorSaves = true;
296
+ #saveTimer = null;
297
+ /** Last bytes mirrored out, so the `saves` event means "changed" and not "checked". */
298
+ #lastSave = null;
299
+ /**
300
+ * Pause state, with an owner.
301
+ *
302
+ * `masterPaused` only freezes the logic loop — the audio callback keeps mixing, so a
303
+ * paused engine went on playing its music behind whatever the host put on top.
304
+ * Pausing therefore has to stop the sound too.
305
+ *
306
+ * The owner matters because pause/resume has several callers: a pause overlay, a
307
+ * start screen, the host itself. Closing an overlay must not resume a game something
308
+ * else had already frozen, so the *first* pause claims ownership and only that
309
+ * owner's `resume()` lifts it.
310
+ */
311
+ #pauseOwner = null;
312
+ /**
313
+ * The host's button object while it holds a claim, by reference — read on the
314
+ * engine's callback, never copied.
315
+ */
316
+ #buttons = null;
317
+ /** The reader handed to the engine, kept so the same function can be uninstalled. */
318
+ #pull = null;
319
+ /** Throttle state for a pull that throws. See {@link Rsdkv4Play.#readButtons}. */
320
+ #pullErrorKey = null;
321
+ #pullErrorAt = 0;
322
+ #pullErrors = 0;
323
+ constructor(init, events) {
324
+ // The spec goes up rather than being declared as a field: a subclass field
325
+ // initialiser runs after `super()`, which would be too late for the base to seed
326
+ // state from it.
327
+ super(RSDKV4_SPEC, init, events);
328
+ }
329
+ // ---- The hooks the contract's base class leaves to an engine ----
330
+ /**
331
+ * Open or reopen a session. The first call brings the wasm up; every call after that
332
+ * reuses it, because RSDKv4 cannot power-cycle in process and does not need to — a
333
+ * session is a save slot, a character and a stage, and all three are reachable on a
334
+ * running engine.
335
+ */
336
+ async open(options) {
337
+ await this.#ensureBooted();
338
+ // Re-applied from the merged state rather than from a patch, which is what makes a
339
+ // claim survive `restart()`: the engine's own input source was just reset by the
340
+ // boot (or never set, on a reopen), and the host's object is still the one it was.
341
+ if (options.buttons !== undefined)
342
+ this.#applyButtons(options.buttons);
343
+ // Absence is "boot the way the engine normally would", so an empty options bag
344
+ // leaves the engine wherever it came up — its own start menu, usually.
345
+ if (options.player !== undefined || options.slot !== undefined) {
346
+ this.game.start(options.slot ?? null, this.#playerIndex(options.player));
347
+ }
348
+ if (options.stage) {
349
+ this.devMenu.loadStage(options.stage.category | 0, options.stage.scene | 0);
204
350
  }
205
- return dir;
206
351
  }
207
- catch {
208
- return null; // missing (create: false), or blocked
352
+ /**
353
+ * Stop and release. The base emits `exit` once this resolves.
354
+ *
355
+ * There is no coming back: RSDKv4 cannot be restarted in process, so a later
356
+ * `start()` on the same factory reports that rather than quietly doing nothing.
357
+ */
358
+ async close() {
359
+ this.#destroyed = true;
360
+ if (this.#saveTimer !== null) {
361
+ clearInterval(this.#saveTimer);
362
+ this.#saveTimer = null;
363
+ }
364
+ const Module = this.#module;
365
+ if (Module) {
366
+ // Before anything else: the engine is about to be pumped a few more times on its
367
+ // way down, and there is no reason for those ticks to reach into a host object
368
+ // whose owner has already been told the session is over.
369
+ this.#applyButtons(null);
370
+ // Last chance to keep whatever the player earned this session.
371
+ if (this.#mirrorSaves)
372
+ await this.#mirrorSaveData();
373
+ try {
374
+ Module.pauseMainLoop?.();
375
+ }
376
+ catch {
377
+ /* engine already down */
378
+ }
379
+ this.#applyPaused(true);
380
+ // Freezing the loop does not silence the audio callback — without this the music
381
+ // kept playing after the host went back to its launcher.
382
+ try {
383
+ Module.web_audio_stop?.();
384
+ }
385
+ catch {
386
+ /* engine already down */
387
+ }
388
+ }
389
+ this.#teardownCanvas();
390
+ this.#module = null;
391
+ this.#booting = null;
209
392
  }
210
- }
211
- /**
212
- * Mirror for the engine's save file.
213
- *
214
- * The working dir is in-memory whenever the OPFS *mount* is unavailable (which
215
- * is every build without Asyncify/JSPI — see mountWorkingDir), so SData.bin
216
- * would die with the page and every save slot would read "NEW GAME" forever.
217
- * The host's own OPFS access has no such limitation, so the SDK copies the file
218
- * in before the engine boots and back out as it changes. Saves therefore
219
- * survive reloads even while the mounted working dir does not.
220
- */
221
- async function restoreSaveData(Module, namespace, workDir) {
222
- const dir = await opfsNamespaceDir(namespace, false);
223
- if (!dir)
224
- return;
225
- try {
226
- const file = await (await dir.getFileHandle(SAVE_FILE)).getFile();
227
- if (file.size > 0) {
228
- Module.FS.writeFile(`${workDir}/${SAVE_FILE}`, new Uint8Array(await file.arrayBuffer()));
393
+ /**
394
+ * Where the picture goes. Called by the base before the first `open()`, which is what
395
+ * guarantees the canvas exists before Emscripten's SDL2 port goes looking for it.
396
+ *
397
+ * Hand over a `<canvas>` and it is used as-is, untouched apart from the id SDL needs;
398
+ * hand over any other element and the SDK creates a canvas inside it and keeps it
399
+ * scaled to fit. Reparenting a live engine is legal — the same canvas moves.
400
+ */
401
+ async mounted(target) {
402
+ if (this.#canvas) {
403
+ this.#reparent(target);
404
+ return;
405
+ }
406
+ const provided = target instanceof HTMLCanvasElement ? target : null;
407
+ const canvas = provided ?? document.createElement('canvas');
408
+ this.#ownsCanvas = provided === null;
409
+ this.#canvas = canvas;
410
+ this.#box = this.#ownsCanvas ? target : canvas;
411
+ // Emscripten's SDL2 port locates the canvas via document.querySelector('#canvas').
412
+ if (canvas.id !== CANVAS_ID) {
413
+ if (canvas.id) {
414
+ console.warn(`[rsdkv4] renaming the render target's id from "${canvas.id}" to "${CANVAS_ID}" — SDL looks the canvas up by that id.`);
415
+ }
416
+ canvas.id = CANVAS_ID;
417
+ }
418
+ if (this.#ownsCanvas) {
419
+ canvas.style.display = 'block';
420
+ canvas.style.maxWidth = '100%';
421
+ canvas.style.maxHeight = '100%';
422
+ canvas.style.height = 'auto';
423
+ canvas.classList.add('emscripten');
424
+ target.appendChild(canvas);
425
+ }
426
+ // A canvas is not in the tab order and `focus()` on one is a silent no-op until it
427
+ // has a tabindex. -1 makes it focusable without adding a tab stop.
428
+ if (!canvas.hasAttribute('tabindex'))
429
+ canvas.setAttribute('tabindex', '-1');
430
+ // …and the focus ring would draw a browser-blue box around the picture.
431
+ canvas.style.outline = 'none';
432
+ canvas.addEventListener('contextmenu', this.#swallowContextMenu);
433
+ canvas.addEventListener('pointerdown', this.#onPointerDown);
434
+ window.addEventListener('resize', this.#onResize);
435
+ // Fullscreen transitions need a refit too.
436
+ document.addEventListener('fullscreenchange', this.#onFullscreenChange);
437
+ if (typeof ResizeObserver !== 'undefined' && this.#box) {
438
+ this.#boxObserver = new ResizeObserver(this.#onResize);
439
+ this.#boxObserver.observe(this.#box);
229
440
  }
441
+ this.#fitPicture();
230
442
  }
231
- catch {
232
- /* no save yet */
443
+ /**
444
+ * A payload changed on a running engine. Only the GAME OPTIONS rows are `live` here —
445
+ * `config` is `settings.ini`, read once at boot, and `player`/`slot`/`stage` are what
446
+ * a `restart()` is for.
447
+ */
448
+ async patched(kind, patch) {
449
+ if (kind !== 'options')
450
+ return;
451
+ // Ahead of the engine check, unlike everything below it: a claim written onto an
452
+ // engine that has not booted yet is still a claim, and a malformed one should be
453
+ // rejected by the call that made it rather than by the boot three lines later.
454
+ //
455
+ // `undefined` and `null` are not the same key here, and must not be collapsed:
456
+ // absence means "leave the claim as it is" — which is what keeps a later
457
+ // `options({ stage })` from dropping a claim on its way past — and only `null`
458
+ // releases.
459
+ const buttons = patch.buttons;
460
+ if (buttons !== undefined)
461
+ this.#applyButtons(buttons);
462
+ if (!this.#module)
463
+ return;
464
+ const rows = this.game.options();
465
+ for (const [key, value] of Object.entries(patch)) {
466
+ if (key === 'player' || key === 'slot' || key === 'stage' || key === 'buttons')
467
+ continue;
468
+ const row = rows.find((candidate) => candidate.key === key);
469
+ if (!row) {
470
+ console.warn(`[rsdkv4] "${key}" is not a game option this pack declares — ignoring. Read options() for the ones it does.`);
471
+ continue;
472
+ }
473
+ this.game.setOption(row.key, toEngineOption(row, value));
474
+ }
233
475
  }
234
- }
235
- async function persistSaveData(Module, namespace, workDir) {
236
- let bytes;
237
- try {
238
- bytes = Module.FS.readFile(`${workDir}/${SAVE_FILE}`);
476
+ options(patch) {
477
+ // `arguments.length`, not `patch === undefined`: `options(undefined)` is a write of
478
+ // nothing, not a read.
479
+ if (arguments.length === 0)
480
+ return this.#describeOptions();
481
+ return super.options(patch);
239
482
  }
240
- catch {
241
- return; // the engine hasn't written one
483
+ async #describeOptions() {
484
+ const described = (await super.options());
485
+ // The claim never reads back, engine or no engine. The base would have written the
486
+ // host's live object into `value` here, and this getter is what a host serialises
487
+ // to save its settings and what it reads to paint a settings screen — neither of
488
+ // which fourteen booleans that change sixty times a second belong in.
489
+ // `play.input.claimed` is the honest question, and it is a different one.
490
+ described.buttons = { ...described.buttons, value: null };
491
+ if (!this.#module)
492
+ return described;
493
+ const out = { ...described };
494
+ const players = this.game.players();
495
+ if (players.length)
496
+ out.player = { ...out.player, enum: players };
497
+ const stages = flattenStages(this.devMenu.getStageList());
498
+ if (stages.length)
499
+ out.stage = { ...out.stage, enum: stages };
500
+ for (const row of this.game.options()) {
501
+ if (row.key === 'player' ||
502
+ row.key === 'slot' ||
503
+ row.key === 'stage' ||
504
+ row.key === 'buttons') {
505
+ console.warn(`[rsdkv4] the pack declares a game option named "${row.key}" — shadowed`);
506
+ continue;
507
+ }
508
+ out[row.key] = {
509
+ value: fromEngineOption(row),
510
+ description: row.label,
511
+ live: true,
512
+ enum: row.type === 'boolean' ? [false, true] : (row.values ?? []),
513
+ };
514
+ }
515
+ return out;
242
516
  }
243
- const dir = await opfsNamespaceDir(namespace, true);
244
- if (!dir)
245
- return;
246
- try {
247
- const writable = await (await dir.getFileHandle(SAVE_FILE, { create: true })).createWritable();
248
- await writable.write(bytes);
249
- await writable.close();
517
+ restart(options) {
518
+ return super.restart(options);
250
519
  }
251
- catch (e) {
252
- console.warn('[rsdkv4] could not persist save data', e);
520
+ // ---- Members with no contract equivalent ----
521
+ /**
522
+ * Pause, on behalf of `owner`. The first caller to pause owns it and only that
523
+ * owner's `resume()` lifts it, so a pause overlay cannot resume a game a start
524
+ * screen — or the host — had already frozen. Audio stops with the engine.
525
+ *
526
+ * Emits the contract's `pause` event, whose detail carries the owner.
527
+ */
528
+ pause(owner = 'host') {
529
+ if (this.#pauseOwner !== null)
530
+ return; // whoever got there first keeps the claim
531
+ this.#pauseOwner = owner;
532
+ this.#applyPaused(true);
533
+ // A pause is a natural checkpoint for the save mirror.
534
+ if (this.#mirrorSaves)
535
+ void this.#mirrorSaveData();
536
+ this.emit('pause', { owner });
253
537
  }
254
- }
255
- /** Delete a file if present; returns true when something was removed. */
256
- function deleteFileIfExists(Module, path) {
257
- if (!fileExists(Module, path))
258
- return false;
259
- try {
260
- Module.FS.unlink(path);
261
- return true;
538
+ resume(owner = 'host') {
539
+ if (this.#pauseOwner !== owner)
540
+ return; // someone else's pause — leave it alone
541
+ this.#pauseOwner = null;
542
+ this.#applyPaused(false);
543
+ this.emit('resume', { owner });
262
544
  }
263
- catch {
264
- return false;
545
+ /** Who is holding the engine paused, or null. */
546
+ get pausedBy() {
547
+ return this.#pauseOwner;
265
548
  }
266
- }
267
- /** Boot the RSDKv4 engine. */
268
- export async function load(config) {
269
- const { assets, onEvent, attachTo } = config;
270
- const options = config.options;
271
- const emit = (event) => {
549
+ /** True when the working dir is OPFS-backed rather than in-memory. */
550
+ get persistent() {
551
+ return this.#persistent;
552
+ }
553
+ /** The normalised {@link Rsdkv4Storage.namespace} this session actually used. */
554
+ get namespace() {
555
+ return this.#namespace;
556
+ }
557
+ /**
558
+ * Input ownership, named. `play.input.claim(buttons)` and `play.input.release()`
559
+ * are exactly `options({ buttons })` and `options({ buttons: null })` — same state,
560
+ * same survival across `restart()`, same everything.
561
+ */
562
+ get input() {
563
+ // Captured, because `this` inside an object literal's getter is the literal. A
564
+ // host that holds on to `play.input` and asks later still gets today's answer.
565
+ const play = this;
566
+ return {
567
+ claim: (buttons) => this.options({ buttons }),
568
+ release: () => this.options({ buttons: null }),
569
+ get claimed() {
570
+ return play.#buttons !== null;
571
+ },
572
+ };
573
+ }
574
+ // ---- Host-driven input ----
575
+ /**
576
+ * Claim or release, on the engine and here. The only writer of {@link #buttons}.
577
+ *
578
+ * Order matters in both directions: the reader is installed before the engine is
579
+ * told to use it, and the engine is told to stop before it is taken away — so there
580
+ * is never a tick where the engine is pulling at something that is not there.
581
+ */
582
+ #applyButtons(buttons) {
583
+ if (buttons !== null)
584
+ validateButtons(buttons);
585
+ const Module = this.#module;
586
+ this.#buttons = buttons;
587
+ // Before a boot there is nothing to tell; `open()` re-applies from the merged
588
+ // state once the engine is up, which is the same path a `restart()` takes.
589
+ if (!Module)
590
+ return;
591
+ if (typeof Module.web_input_set_source !== 'function') {
592
+ console.error('[rsdkv4] web_input_set_source is missing from this build of rsdkv4.wasm — host-driven input needs an engine built from this SDK\'s build.sh. Rebuild it (`make build-wasm`); the engine keeps polling the keyboard until then.');
593
+ return;
594
+ }
595
+ if (buttons === null) {
596
+ Module.web_input_set_source(0);
597
+ delete Module[INPUT_PULL_HOOK];
598
+ this.#pull = null;
599
+ this.#resetPullErrors();
600
+ return;
601
+ }
602
+ this.#pull ??= () => this.#readButtons();
603
+ Module[INPUT_PULL_HOOK] = this.#pull;
604
+ Module.web_input_set_source(1);
605
+ }
606
+ /**
607
+ * The per-tick read. Called from the engine, at the top of its input pass, through
608
+ * `web_input_pull()` — never from a timer and never from anywhere else.
609
+ *
610
+ * **Keep it on the engine's callback.** A read inside a reactive effect would make
611
+ * all fourteen buttons dependencies of that effect (jq79 attributes every read
612
+ * through a store's `get` trap to whichever effect is running), and every keypress
613
+ * would wake it. The call stack here is always rAF → wasm → EM_JS → this, where no
614
+ * effect can be running, and that is an invariant to preserve rather than a
615
+ * coincidence to rely on.
616
+ */
617
+ #readButtons() {
618
+ const buttons = this.#buttons;
619
+ if (!buttons)
620
+ return 0;
272
621
  try {
273
- onEvent?.(event);
622
+ let mask = 0;
623
+ // Indexed, not `Object.entries`: the array's order is the engine's bit order,
624
+ // and a host object's key order is its own business.
625
+ for (let bit = 0; bit < RSDKV4_BUTTONS.length; bit++) {
626
+ if (buttons[RSDKV4_BUTTONS[bit]])
627
+ mask |= 1 << bit;
628
+ }
629
+ this.#resetPullErrors();
630
+ return mask;
274
631
  }
275
- catch {
276
- // A host callback must not break the engine runtime.
632
+ catch (error) {
633
+ this.#reportPullError(error);
634
+ // Everything released, never the last good mask: a repeated mask with a
635
+ // direction held leaves the character running into a pit on its own.
636
+ return 0;
277
637
  }
278
- };
279
- // ----------------------------------------------------------------- render target
280
- const providedCanvas = config.canvasEl ?? config.canvas ?? null;
281
- if (!providedCanvas && !attachTo) {
282
- throw new Error('rsdkv4: config.canvasEl or config.attachTo is required');
283
- }
284
- const ownsCanvas = providedCanvas === null;
285
- const canvas = providedCanvas ?? document.createElement('canvas');
286
- // Emscripten's SDL2 port locates the canvas via document.querySelector('#canvas').
287
- if (canvas.id !== CANVAS_ID) {
288
- if (canvas.id) {
289
- console.warn(`rsdkv4: renaming the render target's id from "${canvas.id}" to "${CANVAS_ID}" — SDL looks the canvas up by that id.`);
290
- }
291
- canvas.id = CANVAS_ID;
292
- }
293
- if (ownsCanvas) {
294
- canvas.style.display = 'block';
295
- canvas.style.maxWidth = '100%';
296
- canvas.style.maxHeight = '100%';
297
- canvas.style.height = 'auto';
298
- canvas.classList.add('emscripten');
299
- attachTo?.appendChild(canvas);
300
- }
301
- // A canvas is not in the tab order and `focus()` on one is a silent no-op
302
- // until it has a tabindex. -1 makes it focusable without adding a tab stop.
303
- if (!canvas.hasAttribute('tabindex'))
304
- canvas.setAttribute('tabindex', '-1');
305
- // …and the focus ring would draw a browser-blue box around the picture.
306
- canvas.style.outline = 'none';
307
- const swallowContextMenu = (event) => event.preventDefault();
308
- canvas.addEventListener('contextmenu', swallowContextMenu);
309
- const focusCanvas = () => {
310
- if (!document.hasFocus())
311
- window.focus();
312
- canvas.focus({ preventScroll: true });
313
- };
314
- const onPointerDown = () => focusCanvas();
315
- canvas.addEventListener('pointerdown', onPointerDown);
316
- // ----------------------------------------------------------------- sizing
317
- /** The box the picture has to fit inside, in CSS pixels. */
318
- const boxElement = ownsCanvas && attachTo ? attachTo : canvas;
319
- const fitPicture = () => {
320
- if (!ownsCanvas)
321
- return;
322
- const box = boxElement.getBoundingClientRect();
323
- if (box.width < 1 || box.height < 1)
638
+ }
639
+ /**
640
+ * Announce a failing pull at most once a second, with a count.
641
+ *
642
+ * This runs sixty times a second, so an unthrottled `emit` would bury the page. It
643
+ * does **not** release the claim: a transient fault recovers on its own, whereas
644
+ * releasing would change input ownership behind the host's back.
645
+ *
646
+ * With a plain object nothing here can fire. It exists because the API accepts any
647
+ * object and a Proxy runs host code on every read — a store nulled by a component
648
+ * that unmounted without releasing, a revoked `Proxy.revocable`, a `get` trap whose
649
+ * effect scope has been torn down. Claim-time validation covers none of those: it
650
+ * validated once, over a reference that was live at the time.
651
+ */
652
+ #reportPullError(error) {
653
+ const key = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
654
+ // performance.now() rather than a timer: nothing to schedule, nothing to clear,
655
+ // and the comparison is already in the hand.
656
+ const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
657
+ this.#pullErrors++;
658
+ if (key !== this.#pullErrorKey || now - this.#pullErrorAt >= INPUT_ERROR_INTERVAL_MS) {
659
+ const windowMs = this.#pullErrorKey === null ? 0 : now - this.#pullErrorAt;
660
+ this.emit('error', Object.assign(new Error(`rsdkv4: reading the host's buttons failed (${this.#pullErrors}× in ${Math.round(windowMs)}ms) — input is dead until it recovers, and the claim is still held. Release it with options({ buttons: null }) if the host is gone. Cause: ${key}`), { cause: error }));
661
+ this.#pullErrorKey = key;
662
+ this.#pullErrorAt = now;
663
+ this.#pullErrors = 0;
664
+ }
665
+ }
666
+ /** Forget the streak, so a relapse announces itself immediately rather than in a second. */
667
+ #resetPullErrors() {
668
+ if (this.#pullErrorKey === null)
324
669
  return;
325
- const bw = manifest.video.baseWidth;
326
- const bh = manifest.video.baseHeight;
327
- const scale = Math.min(box.width / bw, box.height / bh);
328
- canvas.style.width = `${Math.round(bw * scale)}px`;
329
- canvas.style.height = `${Math.round(bh * scale)}px`;
330
- };
331
- fitPicture();
332
- const onResize = () => fitPicture();
333
- window.addEventListener('resize', onResize);
334
- const boxObserver = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(onResize);
335
- boxObserver?.observe(boxElement);
336
- // Fullscreen transitions need a refit too.
337
- const onFullscreenChange = () => {
338
- fitPicture();
339
- requestAnimationFrame(fitPicture);
340
- };
341
- document.addEventListener('fullscreenchange', onFullscreenChange);
342
- // ----------------------------------------------------------------- emscripten
343
- const jsUrl = config.jsUrl ?? new URL('./rsdkv4.js', import.meta.url).href;
344
- const wasmUrl = config.wasmUrl ?? new URL('./rsdkv4.wasm', import.meta.url).href;
345
- // RSDKv4 keyboard bindings are the shared input script's default preset.
346
- if (typeof window !== 'undefined')
347
- window.__gamepadKeyMap = manifest.input;
348
- const instantiate = async (bust) => {
349
- const withBust = (url) => {
350
- if (!bust)
351
- return url;
352
- const parsed = new URL(url, location.href);
353
- parsed.searchParams.set('_', bust);
354
- return parsed.href;
670
+ this.#pullErrorKey = null;
671
+ this.#pullErrorAt = 0;
672
+ this.#pullErrors = 0;
673
+ }
674
+ /** RSDKv4's Start Menu as data. Available once the engine is up. */
675
+ get game() {
676
+ const Module = this.#requireModule();
677
+ const parse = (fn, fallback, what) => parseJson(fn, fallback, what);
678
+ return {
679
+ type: () => (typeof Module.web_game_type === 'function' ? Module.web_game_type() : 0),
680
+ players: () => parse(Module.web_get_players, [], 'web_get_players'),
681
+ saveSlots: () => parse(Module.web_get_save_slots, [], 'web_get_save_slots'),
682
+ options: () => parse(Module.web_get_game_options, [], 'web_get_game_options'),
683
+ setOption: (key, value) => {
684
+ Module.web_set_game_option?.(String(key), value | 0);
685
+ },
686
+ deleteSave: (slot) => {
687
+ Module.web_delete_save?.(slot | 0);
688
+ if (this.#mirrorSaves)
689
+ void this.#mirrorSaveData();
690
+ },
691
+ start: (slot, player = 0) => {
692
+ Module.web_start_game?.(slot == null ? -1 : slot | 0, player | 0);
693
+ // Whatever drove this is done with the engine — hand it back.
694
+ this.#pauseOwner = null;
695
+ this.#applyPaused(false);
696
+ },
355
697
  };
356
- const mod = await import(/* @vite-ignore */ withBust(jsUrl));
357
- return mod.default({
358
- canvas,
359
- noInitialRun: true, // built with -sINVOKE_RUN=0; we mount data before main()
360
- locateFile: (path) => (path.endsWith('.wasm') ? withBust(wasmUrl) : path),
361
- print: (...a) => console.log('[rsdkv4]', ...a),
362
- printErr: (...a) => console.error('[rsdkv4]', ...a),
363
- onAbort: (reason) => emit({ type: 'error', error: new Error(`rsdkv4 aborted: ${reason}`) }),
364
- });
365
- };
366
- let Module = await instantiate();
367
- // Self-heal a stale engine.
368
- //
369
- // rsdkv4.js/.wasm are big and served by most static hosts with nothing but
370
- // Last-Modified, so a browser will happily keep a build for hours. The
371
- // symptom is nasty: fresh SDK code against an old engine, where the bridges
372
- // this SDK calls simply don't exist and every getter quietly answers "empty" —
373
- // no save slots, no characters, an empty pause menu. Rather than leave that to
374
- // the reader's cache hygiene, notice it and fetch once past the cache.
375
- if (!engineBridgeComplete(Module)) {
376
- console.warn('[rsdkv4] the engine that loaded is missing bridges this SDK needs — refetching past the HTTP cache');
377
- Module = await instantiate(String(Date.now()));
378
- if (!engineBridgeComplete(Module)) {
379
- console.error('[rsdkv4] still missing engine bridges after a cache-busting reload — rsdkv4.wasm is genuinely older than this SDK; rebuild it (`make build-wasm`)');
380
- }
381
- }
382
- // Mount the working dir first, so we can see what's already persisted (OPFS)
383
- // before deciding whether to pull assets.
384
- const { persistent } = mountWorkingDir(Module, config.persist);
385
- const storageNamespace = normalizeStorageNamespace(config.storageNamespace);
386
- const workDir = `${WORK_ROOT}/${storageNamespace}`;
387
- ensureDir(Module, workDir);
388
- const dataPath = `${workDir}/Data.rsdk`;
389
- const settingsPath = `${workDir}/settings.ini`;
390
- // Data.rsdk — precedence: explicit asset > already persisted (skip fetch) > lazy provider.
391
- let dataBytes = toUint8(assets?.data);
392
- if (!dataBytes) {
393
- if (fileExists(Module, dataPath)) {
394
- console.log(`[rsdkv4] Data.rsdk already in persistent storage (${storageNamespace}) — skipping fetch`);
395
- }
396
- else if (config.dataProvider) {
397
- dataBytes = toUint8(await config.dataProvider());
398
- }
399
698
  }
400
- if (dataBytes) {
401
- Module.FS.writeFile(dataPath, dataBytes);
699
+ /** The engine's stage list and loader. Available once the engine is up. */
700
+ get devMenu() {
701
+ const Module = this.#requireModule();
702
+ return {
703
+ getStageList: () => parseJson(Module.web_devmenu_get_stage_list, [], 'web_devmenu_get_stage_list'),
704
+ loadStage: (categoryIdx, stageIdx) => {
705
+ Module.web_devmenu_load_stage?.(categoryIdx | 0, stageIdx | 0);
706
+ },
707
+ setPaused: (paused) => {
708
+ if (paused)
709
+ this.pause('host');
710
+ else
711
+ this.resume(this.#pauseOwner ?? 'host');
712
+ },
713
+ };
402
714
  }
403
- else if (!fileExists(Module, dataPath)) {
404
- throw new Error('rsdkv4: no Data.rsdk — provide assets.data, a dataProvider, or a persisted copy (OPFS)');
715
+ // ---- Bringing the engine up ----
716
+ #requireModule() {
717
+ if (!this.#module) {
718
+ throw new Error('rsdkv4: the engine is not running — await start() before reaching for it');
719
+ }
720
+ return this.#module;
405
721
  }
406
- // settings.ini — explicit asset > persisted > lazy provider > generated from options.
407
- let settingsBytes = toUint8(assets?.settings);
408
- if (!settingsBytes && !fileExists(Module, settingsPath) && config.settingsProvider) {
409
- settingsBytes = toUint8(await config.settingsProvider());
722
+ #ensureBooted() {
723
+ if (this.#destroyed) {
724
+ throw new Error('rsdkv4: this engine has been destroyed and cannot be restarted in process — build a new Rsdkv4SDK');
725
+ }
726
+ // A boot that failed must not poison the next attempt. The common failure is a
727
+ // host that started before handing over `assets.data` — it fixes that and calls
728
+ // `start()` again, and caching the rejection would tell it "no Data.rsdk" forever.
729
+ this.#booting ??= this.#boot().catch((error) => {
730
+ this.#booting = null;
731
+ this.#module = null;
732
+ throw error;
733
+ });
734
+ return this.#booting;
410
735
  }
411
- if (settingsBytes) {
412
- Module.FS.writeFile(settingsPath, settingsBytes);
736
+ async #boot() {
737
+ const canvas = this.#canvas;
738
+ if (!canvas) {
739
+ throw new Error('rsdkv4: mount(target) before start() — the engine draws into a canvas');
740
+ }
741
+ const config = valuesOf(await this.config());
742
+ const assets = valuesOf(await this.assets());
743
+ const storage = valuesOf(await this.storage());
744
+ const Module = await this.#instantiate(canvas, config);
745
+ this.#module = Module;
746
+ // Mount the working dir first, so we can see what is already persisted (OPFS)
747
+ // before deciding whether to pull assets.
748
+ this.#persistent = mountWorkingDir(Module, storage.persist).persistent;
749
+ this.#namespace = normalizeStorageNamespace(storage.namespace);
750
+ this.#workDir = `${WORK_ROOT}/${this.#namespace}`;
751
+ this.#mirrorSaves = storage.persist !== null;
752
+ ensureDir(Module, this.#workDir);
753
+ await this.#writeAssets(Module, assets, config);
754
+ // `persist: null` means the host wants nothing kept, so honour it; otherwise pull
755
+ // any previous SData.bin in before the engine reads it.
756
+ if (this.#mirrorSaves)
757
+ await this.#restoreSaveData(Module);
758
+ Module.FS.chdir(this.#workDir);
759
+ // Run main() from the working dir. simulate_infinite_loop schedules the rAF loop
760
+ // and returns via a benign unwind Emscripten swallows.
761
+ Module.callMain(['UsingCWD']);
762
+ // callMain only *schedules* the loop: Engine::Init runs on the first frame, and
763
+ // until it has, there is no game config, stage list or saveRAM to read. Waiting
764
+ // here means the bridges answer the moment start() resolves.
765
+ await waitForEngine(Module);
766
+ this.#focusCanvas();
767
+ // The engine writes SData.bin at its own pace (new game, checkpoint, options
768
+ // change), so copy it out on a slow timer as well as on the way down.
769
+ if (this.#mirrorSaves) {
770
+ this.#saveTimer = setInterval(() => void this.#mirrorSaveData(), 10_000);
771
+ }
772
+ return Module;
413
773
  }
414
- else if (!fileExists(Module, settingsPath)) {
415
- Module.FS.writeFile(settingsPath, new TextEncoder().encode(buildSettingsIni(options)));
774
+ async #instantiate(canvas, config) {
775
+ const jsUrl = config.jsUrl ?? new URL('./rsdkv4.js', import.meta.url).href;
776
+ const wasmUrl = config.wasmUrl ?? new URL('./rsdkv4.wasm', import.meta.url).href;
777
+ const load = async (bust) => {
778
+ const withBust = (url) => {
779
+ if (!bust)
780
+ return url;
781
+ const parsed = new URL(url, location.href);
782
+ parsed.searchParams.set('_', bust);
783
+ return parsed.href;
784
+ };
785
+ const mod = await import(/* @vite-ignore */ withBust(jsUrl));
786
+ return mod.default({
787
+ canvas,
788
+ noInitialRun: true, // built with -sINVOKE_RUN=0; we mount data before main()
789
+ locateFile: (path) => (path.endsWith('.wasm') ? withBust(wasmUrl) : path),
790
+ print: (...a) => console.log('[rsdkv4]', ...a),
791
+ printErr: (...a) => console.error('[rsdkv4]', ...a),
792
+ onAbort: (reason) => {
793
+ this.emit('error', new Error(`rsdkv4 aborted: ${reason}`));
794
+ },
795
+ });
796
+ };
797
+ let Module = await load();
798
+ // Self-heal a stale engine.
799
+ //
800
+ // rsdkv4.js/.wasm are big and served by most static hosts with nothing but
801
+ // Last-Modified, so a browser will happily keep a build for hours. The symptom is
802
+ // nasty: fresh SDK code against an old engine, where the bridges this SDK calls
803
+ // simply don't exist and every getter quietly answers "empty" — no save slots, no
804
+ // characters, an empty pause menu. Rather than leave that to the reader's cache
805
+ // hygiene, notice it and fetch once past the cache.
806
+ if (!engineBridgeComplete(Module)) {
807
+ console.warn('[rsdkv4] the engine that loaded is missing bridges this SDK needs — refetching past the HTTP cache');
808
+ Module = await load(String(Date.now()));
809
+ if (!engineBridgeComplete(Module)) {
810
+ console.error('[rsdkv4] still missing engine bridges after a cache-busting reload — rsdkv4.wasm is genuinely older than this SDK; rebuild it (`make build-wasm`)');
811
+ }
812
+ }
813
+ return Module;
416
814
  }
417
- // else: keep the persisted settings.ini
418
- // Save data. `persist: null` means the host wants nothing kept, so honour it;
419
- // otherwise pull any previous SData.bin in before the engine reads it.
420
- const mirrorSaves = config.persist !== null;
421
- if (mirrorSaves)
422
- await restoreSaveData(Module, storageNamespace, workDir);
423
- Module.FS.chdir(workDir);
424
- let pauseOwner = null;
425
- const applyPaused = (paused) => {
426
- if (typeof Module.web_devmenu_set_paused === 'function')
427
- Module.web_devmenu_set_paused(paused);
428
- if (typeof Module.web_audio_set_paused === 'function')
429
- Module.web_audio_set_paused(paused);
430
- };
431
- const pauseWith = (owner) => {
432
- if (pauseOwner !== null)
433
- return; // already paused — whoever got there first keeps the claim
434
- pauseOwner = owner;
435
- applyPaused(true);
436
- // A pause is a natural checkpoint for the save mirror.
437
- if (mirrorSaves)
438
- void persistSaveData(Module, storageNamespace, workDir);
439
- };
440
- const resumeFrom = (owner) => {
441
- if (pauseOwner !== owner)
442
- return; // someone else's pause — leave it alone
443
- pauseOwner = null;
444
- applyPaused(false);
445
- };
446
- /** Legacy shape kept for `devMenu.setPaused` — always acts as the host. */
447
- const setPaused = (paused) => {
448
- if (paused)
449
- pauseWith('host');
450
- else
451
- resumeFrom(pauseOwner ?? 'host');
452
- };
453
- const stopAudio = () => {
815
+ /** Data.rsdk and settings.ini into the working dir. See {@link Rsdkv4Assets}. */
816
+ async #writeAssets(Module, assets, config) {
817
+ const dataPath = `${this.#workDir}/Data.rsdk`;
818
+ const settingsPath = `${this.#workDir}/settings.ini`;
819
+ // The pack — the expensive one, so a persisted copy short-circuits the thunk.
820
+ if (fileExists(Module, dataPath)) {
821
+ const explicit = typeof assets.data === 'function' ? null : await resolveAsset(assets.data);
822
+ if (explicit)
823
+ Module.FS.writeFile(dataPath, explicit);
824
+ else {
825
+ console.log(`[rsdkv4] Data.rsdk already in persistent storage (${this.#namespace}) — skipping fetch`);
826
+ }
827
+ }
828
+ else {
829
+ const bytes = await resolveAsset(assets.data);
830
+ if (!bytes) {
831
+ throw new Error('rsdkv4: no Data.rsdk — hand one over as assets.data (bytes or a thunk), or point storage.namespace at a persisted copy');
832
+ }
833
+ Module.FS.writeFile(dataPath, bytes);
834
+ }
835
+ // The settings — cheap, and regenerated every boot so `config` is never shadowed
836
+ // by a file an earlier session left behind. The engine never writes it back (its
837
+ // writeSettings() is #ifndef __EMSCRIPTEN__), so there is nothing to lose.
838
+ const settings = await resolveAsset(assets.settings);
839
+ Module.FS.writeFile(settingsPath, settings ?? new TextEncoder().encode(buildSettingsIni(config)));
840
+ }
841
+ // ---- The save mirror ----
842
+ /**
843
+ * Pull a previously mirrored SData.bin into the wasm before the engine reads it.
844
+ *
845
+ * The working dir is in-memory whenever the OPFS *mount* is unavailable (which is
846
+ * every build without Asyncify/JSPI — see {@link mountWorkingDir}), so SData.bin
847
+ * would die with the page and every slot would read "NEW GAME" forever. The host-side
848
+ * OPFS API has no such limitation, so the SDK copies the file in here and back out as
849
+ * it changes.
850
+ */
851
+ async #restoreSaveData(Module) {
852
+ const dir = await opfsNamespaceDir(this.#namespace, false);
853
+ if (!dir)
854
+ return;
454
855
  try {
455
- Module.web_audio_stop?.();
856
+ const file = await (await dir.getFileHandle(SAVE_FILE)).getFile();
857
+ if (file.size > 0) {
858
+ const bytes = new Uint8Array(await file.arrayBuffer());
859
+ Module.FS.writeFile(`${this.#workDir}/${SAVE_FILE}`, bytes);
860
+ this.#lastSave = bytes;
861
+ }
456
862
  }
457
863
  catch {
458
- /* engine already down */
864
+ /* no save yet */
459
865
  }
460
- };
866
+ }
461
867
  /**
462
- * Call a `web_*` embind getter and parse its JSON.
868
+ * Copy SData.bin out of the wasm into `<namespace>/`, and announce it if it moved.
463
869
  *
464
- * A missing function means the loaded rsdkv4.wasm predates that bridge — the
465
- * usual cause is a browser serving a cached build. Say so out loud: silently
466
- * returning an empty list makes a stale artifact look like an empty save file
467
- * or a game with no playable characters.
870
+ * The division of labour the session settled on: the SDK owns getting the bytes out
871
+ * of the wasm and into the namespace both sides already agree on; a host owns
872
+ * reading, parsing and painting them. `saves` is what tells it to look again — which
873
+ * is why it fires on a change and not on every check.
468
874
  */
469
- const parseJson = (fn, fallback, what) => {
470
- if (typeof fn !== 'function') {
471
- console.error(`[rsdkv4] ${what} is missing from this build of rsdkv4.wasm — the page is probably running a cached copy. Hard-reload (or clear the site's storage) after rebuilding.`);
472
- return fallback;
473
- }
875
+ async #mirrorSaveData() {
876
+ const Module = this.#module;
877
+ if (!Module)
878
+ return;
879
+ // Explicitly over an ArrayBuffer, not the default ArrayBufferLike: OPFS's
880
+ // `write()` will not take a view that might be backed by a SharedArrayBuffer,
881
+ // and on a cross-origin isolated page that is not a hypothetical distinction.
882
+ let bytes;
474
883
  try {
475
- return JSON.parse(fn());
884
+ bytes = Module.FS.readFile(`${this.#workDir}/${SAVE_FILE}`);
476
885
  }
477
- catch (e) {
478
- console.error(`[rsdkv4] ${what} failed`, e);
479
- return fallback;
886
+ catch {
887
+ return; // the engine hasn't written one
480
888
  }
481
- };
482
- const game = {
483
- type: () => (typeof Module.web_game_type === 'function' ? Module.web_game_type() : 0),
484
- players: () => parseJson(Module.web_get_players, [], 'web_get_players'),
485
- saveSlots: () => parseJson(Module.web_get_save_slots, [], 'web_get_save_slots'),
486
- options: () => parseJson(Module.web_get_game_options, [], 'web_get_game_options'),
487
- setOption(key, value) {
488
- Module.web_set_game_option?.(String(key), value | 0);
489
- },
490
- deleteSave(slot) {
491
- Module.web_delete_save?.(slot | 0);
492
- },
493
- start(slot, player = 0) {
494
- Module.web_start_game?.(slot == null ? -1 : slot | 0, player | 0);
495
- // The overlay that drove this is done with the engine — hand it back.
496
- pauseOwner = null;
497
- applyPaused(false);
498
- },
499
- };
500
- const devMenu = {
501
- getStageList() {
502
- if (typeof Module.web_devmenu_get_stage_list !== 'function')
503
- return [];
889
+ if (sameBytes(bytes, this.#lastSave))
890
+ return;
891
+ const dir = await opfsNamespaceDir(this.#namespace, true);
892
+ if (dir) {
504
893
  try {
505
- return JSON.parse(Module.web_devmenu_get_stage_list());
894
+ const handle = await dir.getFileHandle(SAVE_FILE, { create: true });
895
+ const writable = await handle.createWritable();
896
+ await writable.write(bytes);
897
+ await writable.close();
506
898
  }
507
899
  catch (e) {
508
- console.error('[rsdkv4] getStageList failed', e);
509
- return [];
510
- }
511
- },
512
- loadStage(categoryIdx, stageIdx) {
513
- if (typeof Module.web_devmenu_load_stage === 'function') {
514
- Module.web_devmenu_load_stage(categoryIdx | 0, stageIdx | 0);
900
+ console.warn('[rsdkv4] could not persist save data', e);
901
+ return;
515
902
  }
516
- },
517
- setPaused,
903
+ }
904
+ this.#lastSave = bytes;
905
+ this.emit('saves', this.game.saveSlots());
906
+ }
907
+ // ---- The render target ----
908
+ #swallowContextMenu = (event) => event.preventDefault();
909
+ #onPointerDown = () => this.#focusCanvas();
910
+ #onResize = () => this.#fitPicture();
911
+ #onFullscreenChange = () => {
912
+ this.#fitPicture();
913
+ requestAnimationFrame(() => this.#fitPicture());
518
914
  };
519
- // Run main() from the OPFS/WASMFS working dir. simulate_infinite_loop schedules
520
- // the rAF loop and returns via a benign unwind Emscripten swallows.
521
- Module.callMain(['UsingCWD']);
522
- // callMain only *schedules* the loop: Engine::Init runs on the first frame, and
523
- // until it has, there is no game config, stage list or saveRAM to read. Waiting
524
- // here means a host can call devMenu/game getters the moment load() resolves.
525
- await waitForEngine(Module);
526
- focusCanvas();
527
- // The engine writes SData.bin at its own pace (new game, checkpoint, options
528
- // change), so copy it out on a slow timer as well as on the way down.
529
- const saveTimer = mirrorSaves
530
- ? setInterval(() => void persistSaveData(Module, storageNamespace, workDir), 10_000)
531
- : null;
532
- emit({ type: 'ready' });
533
- return {
534
- start() { },
535
- /** `owner` lets a pause overlay avoid resuming a game something else paused. */
536
- pause(owner = 'host') { pauseWith(owner); },
537
- resume(owner = 'host') { resumeFrom(owner); },
538
- reset() {
539
- throw new Error('rsdkv4: reset() is not supported — destroy() and load() again');
540
- },
541
- setInput(preset) {
542
- if (typeof window !== 'undefined') {
543
- window.__gamepadKeyMap = preset ?? manifest.input;
544
- }
545
- },
546
- destroy() {
547
- if (saveTimer !== null)
548
- clearInterval(saveTimer);
549
- // Last chance to keep whatever the player earned this session.
550
- if (mirrorSaves)
551
- void persistSaveData(Module, storageNamespace, workDir);
552
- try {
553
- Module.pauseMainLoop?.();
554
- }
555
- catch { /* noop */ }
556
- try {
557
- setPaused(true);
558
- }
559
- catch { /* noop */ }
560
- // Freezing the loop does not silence the audio callback — without this the
561
- // music kept playing after the host went back to its launcher.
562
- stopAudio();
563
- canvas.removeEventListener('contextmenu', swallowContextMenu);
564
- canvas.removeEventListener('pointerdown', onPointerDown);
565
- document.removeEventListener('fullscreenchange', onFullscreenChange);
566
- window.removeEventListener('resize', onResize);
567
- boxObserver?.disconnect();
568
- if (ownsCanvas)
915
+ #focusCanvas() {
916
+ if (!this.#canvas)
917
+ return;
918
+ if (!document.hasFocus())
919
+ window.focus();
920
+ this.#canvas.focus({ preventScroll: true });
921
+ }
922
+ #fitPicture() {
923
+ if (!this.#ownsCanvas || !this.#canvas || !this.#box)
924
+ return;
925
+ const box = this.#box.getBoundingClientRect();
926
+ if (box.width < 1 || box.height < 1)
927
+ return;
928
+ const { baseWidth, baseHeight } = RSDKV4_VIDEO;
929
+ const scale = Math.min(box.width / baseWidth, box.height / baseHeight);
930
+ this.#canvas.style.width = `${Math.round(baseWidth * scale)}px`;
931
+ this.#canvas.style.height = `${Math.round(baseHeight * scale)}px`;
932
+ }
933
+ /**
934
+ * Move the picture we already have. SDL keeps its canvas; only the parent changes.
935
+ *
936
+ * Pointing a second `mount()` at a *different* `<canvas>` is the one case this
937
+ * refuses: SDL2 resolved `#canvas` once, at instantiation, so swapping the element
938
+ * would leave the engine drawing into an orphan while the host watched a blank one.
939
+ */
940
+ #reparent(target) {
941
+ const canvas = this.#canvas;
942
+ if (!canvas || target === canvas || canvas.parentElement === target)
943
+ return;
944
+ if (target instanceof HTMLCanvasElement) {
945
+ console.warn('[rsdkv4] the canvas SDL draws into cannot be swapped after mounting — ignoring this mount()');
946
+ return;
947
+ }
948
+ target.appendChild(canvas);
949
+ if (this.#box)
950
+ this.#boxObserver?.unobserve(this.#box);
951
+ this.#box = this.#ownsCanvas ? target : canvas;
952
+ if (this.#box)
953
+ this.#boxObserver?.observe(this.#box);
954
+ this.#fitPicture();
955
+ }
956
+ #teardownCanvas() {
957
+ const canvas = this.#canvas;
958
+ if (canvas) {
959
+ canvas.removeEventListener('contextmenu', this.#swallowContextMenu);
960
+ canvas.removeEventListener('pointerdown', this.#onPointerDown);
961
+ if (this.#ownsCanvas)
569
962
  canvas.remove();
570
- },
571
- devMenu,
572
- game,
573
- persistent,
574
- storageNamespace,
575
- purgeStorage() {
576
- return {
577
- data: deleteFileIfExists(Module, dataPath),
578
- settings: deleteFileIfExists(Module, settingsPath),
579
- };
580
- },
581
- };
963
+ }
964
+ document.removeEventListener('fullscreenchange', this.#onFullscreenChange);
965
+ window.removeEventListener('resize', this.#onResize);
966
+ this.#boxObserver?.disconnect();
967
+ this.#boxObserver = null;
968
+ this.#canvas = null;
969
+ this.#box = null;
970
+ }
971
+ // ---- Misc ----
972
+ #applyPaused(paused) {
973
+ const Module = this.#module;
974
+ if (!Module)
975
+ return;
976
+ if (typeof Module.web_devmenu_set_paused === 'function')
977
+ Module.web_devmenu_set_paused(paused);
978
+ if (typeof Module.web_audio_set_paused === 'function')
979
+ Module.web_audio_set_paused(paused);
980
+ }
981
+ /** A character name, as the pack spells it, to the index the engine wants. */
982
+ #playerIndex(player) {
983
+ if (player === undefined)
984
+ return 0;
985
+ const players = this.game.players();
986
+ const index = players.findIndex((name) => name.toLowerCase() === player.toLowerCase());
987
+ if (index < 0) {
988
+ throw new Error(`rsdkv4: "${player}" is not a playable character in this pack — try one of ${players.join(', ') || '(none reported)'}`);
989
+ }
990
+ return index;
991
+ }
992
+ }
993
+ // ---------------------------------------------------------------- the factory
994
+ /**
995
+ * The factory a host imports: identity on the constructor, one live engine per
996
+ * instance, and a `start()` that brings the wasm up and opens a session.
997
+ *
998
+ * Everything on it is the contract's — see the module doc for the shape of a call.
999
+ */
1000
+ export class Rsdkv4SDK extends EngineSDKBase {
1001
+ static id = 'rsdkv4';
1002
+ /** Kept in step with package.json by `node scripts/sync-version.mjs`. */
1003
+ static version = '0.2.0';
1004
+ static name = 'Retro Software Development Kit v4';
1005
+ static description = 'RSDKv4 compiled to WebAssembly via Emscripten. One game-agnostic WASM binary runs both Sonic 1 and Sonic 2 — the difference is only which Data.rsdk the host supplies at runtime. Ships none of the game: the player provides their own Data.rsdk, and it never leaves their browser.';
1006
+ createPlay(init, events) {
1007
+ return new Rsdkv4Play(init, events);
1008
+ }
1009
+ start(options) {
1010
+ return super.start(options);
1011
+ }
1012
+ }
1013
+ /**
1014
+ * The line that puts the contract in CI: if this file stops satisfying
1015
+ * `EngineSDKConstructor`, `make typecheck` says so.
1016
+ */
1017
+ export const RSDKV4_ENGINE = Rsdkv4SDK;
1018
+ export default Rsdkv4SDK;
1019
+ // ---------------------------------------------------------------- module-private helpers
1020
+ /**
1021
+ * Call a `web_*` embind getter and parse its JSON.
1022
+ *
1023
+ * A missing function means the loaded rsdkv4.wasm predates that bridge — the usual
1024
+ * cause is a browser serving a cached build. Say so out loud: silently returning an
1025
+ * empty list makes a stale artifact look like an empty save file or a game with no
1026
+ * playable characters.
1027
+ */
1028
+ function parseJson(fn, fallback, what) {
1029
+ if (typeof fn !== 'function') {
1030
+ console.error(`[rsdkv4] ${what} is missing from this build of rsdkv4.wasm — the page is probably running a cached copy. Hard-reload (or clear the site's storage) after rebuilding.`);
1031
+ return fallback;
1032
+ }
1033
+ try {
1034
+ return JSON.parse(fn());
1035
+ }
1036
+ catch (e) {
1037
+ console.error(`[rsdkv4] ${what} failed`, e);
1038
+ return fallback;
1039
+ }
1040
+ }
1041
+ /**
1042
+ * A claim, checked once — exactly the fourteen buttons, with missing and unknown both
1043
+ * fatal.
1044
+ *
1045
+ * Strict because the two failure modes are silent and asymmetric. A **missing** key
1046
+ * reads `false` on every tick: a dead button, no error anywhere, and easy to blame on
1047
+ * the engine. An **unknown** key is a button the host writes to that nothing ever
1048
+ * reads. The first sketch of this API lost `right` to a duplicated `up` — a duplicate
1049
+ * key in an object literal is legal JavaScript and surfaces only as an absent one.
1050
+ *
1051
+ * `Object.keys`, not `in`: a reactive store's `has` trap can answer `true` for a key
1052
+ * that has been deleted (jq79 does exactly that, deliberately, so a template
1053
+ * expression reading a deleted name takes its else branch instead of dying), and
1054
+ * `ownKeys` has no such licence.
1055
+ */
1056
+ function validateButtons(buttons) {
1057
+ if (typeof buttons !== 'object' || buttons === null) {
1058
+ throw new Error(`rsdkv4: options({ buttons }) takes an object of the 14 buttons or null to release, not ${typeof buttons}`);
1059
+ }
1060
+ const keys = new Set(Object.keys(buttons));
1061
+ const missing = RSDKV4_BUTTONS.filter((button) => !keys.has(button));
1062
+ const unknown = [...keys].filter((key) => !RSDKV4_BUTTONS.includes(key));
1063
+ if (missing.length || unknown.length) {
1064
+ const faults = [
1065
+ missing.length && `missing ${missing.join(', ')}`,
1066
+ unknown.length && `unknown ${unknown.join(', ')}`,
1067
+ ].filter(Boolean);
1068
+ throw new Error(`rsdkv4: the buttons object must carry exactly the 14 buttons (${RSDKV4_BUTTONS.join(', ')}) — ${faults.join('; ')}. A missing button is dead, not neutral, so this is an error rather than a default.`);
1069
+ }
1070
+ }
1071
+ /** The engine's two-level stage list as flat, writable {@link Rsdkv4Stage} values. */
1072
+ function flattenStages(categories) {
1073
+ const out = [];
1074
+ categories.forEach((category, categoryIdx) => {
1075
+ category.stages.forEach((stage, sceneIdx) => {
1076
+ out.push({ category: categoryIdx, scene: sceneIdx, name: `${category.name} · ${stage.name}` });
1077
+ });
1078
+ });
1079
+ return out;
1080
+ }
1081
+ /** A GAME OPTIONS row as a host reads it: a boolean, or the label of the chosen entry. */
1082
+ function fromEngineOption(row) {
1083
+ if (row.type === 'boolean')
1084
+ return row.value !== 0;
1085
+ return row.values?.[row.value] ?? row.value;
1086
+ }
1087
+ /** …and back to the number the engine stores. */
1088
+ function toEngineOption(row, value) {
1089
+ if (typeof value === 'boolean')
1090
+ return value ? 1 : 0;
1091
+ if (typeof value === 'number')
1092
+ return value | 0;
1093
+ if (typeof value === 'string') {
1094
+ const index = (row.values ?? []).findIndex((choice) => choice.toLowerCase() === value.toLowerCase());
1095
+ if (index >= 0)
1096
+ return index;
1097
+ }
1098
+ throw new Error(`rsdkv4: ${JSON.stringify(value)} is not a value "${row.key}" accepts — try one of ${row.type === 'boolean' ? 'true, false' : (row.values ?? []).join(', ')}`);
582
1099
  }
583
- export default { manifest, load };
584
1100
  //# sourceMappingURL=rsdkv4.sdk.js.map