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