@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/README.md +54 -0
- package/dist/rsdkv4/rsdkv4.options.d.ts +350 -23
- package/dist/rsdkv4/rsdkv4.options.d.ts.map +1 -1
- package/dist/rsdkv4/rsdkv4.options.js +164 -52
- package/dist/rsdkv4/rsdkv4.options.js.map +1 -1
- package/dist/rsdkv4/rsdkv4.sdk.d.ts +201 -64
- package/dist/rsdkv4/rsdkv4.sdk.d.ts.map +1 -1
- package/dist/rsdkv4/rsdkv4.sdk.js +950 -434
- package/dist/rsdkv4/rsdkv4.sdk.js.map +1 -1
- package/package.json +7 -12
- package/src/rsdkv4.options.ts +476 -73
- package/src/rsdkv4.sdk.ts +1164 -508
- package/dist/manifest.json +0 -94
- package/dist/rsdkv4/rsdkv4.manifest.d.ts +0 -4
- package/dist/rsdkv4/rsdkv4.manifest.d.ts.map +0 -1
- package/dist/rsdkv4/rsdkv4.manifest.js +0 -51
- package/dist/rsdkv4/rsdkv4.manifest.js.map +0 -1
- package/src/rsdkv4.manifest.ts +0 -57
package/src/rsdkv4.sdk.ts
CHANGED
|
@@ -1,30 +1,93 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
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
|
-
*
|
|
98
|
+
* The picture's native size, which is what the SDK scales to fit its mount.
|
|
36
99
|
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
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
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
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
|
|
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:
|
|
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
|
-
*
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
*
|
|
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:
|
|
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,
|
|
120
|
-
*
|
|
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
|
-
*
|
|
127
|
-
*
|
|
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(
|
|
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
|
-
*
|
|
203
|
-
*
|
|
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
|
-
*
|
|
223
|
-
*
|
|
224
|
-
*
|
|
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
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
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
|
-
|
|
245
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
/**
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
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
|
-
*
|
|
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
|
-
*
|
|
321
|
-
*
|
|
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
|
-
|
|
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
|
-
*
|
|
334
|
-
*
|
|
335
|
-
*
|
|
336
|
-
*
|
|
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
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
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
|
-
*
|
|
352
|
-
*
|
|
353
|
-
*
|
|
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
|
|
356
|
-
|
|
357
|
-
|
|
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
|
-
*
|
|
360
|
-
*
|
|
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
|
-
|
|
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
|
-
/**
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
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
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
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
|
-
|
|
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
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
523
|
+
if (this.#saveTimer !== null) {
|
|
524
|
+
clearInterval(this.#saveTimer);
|
|
525
|
+
this.#saveTimer = null;
|
|
526
|
+
}
|
|
386
527
|
|
|
387
|
-
|
|
388
|
-
|
|
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
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
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
|
-
|
|
552
|
+
|
|
553
|
+
this.#teardownCanvas();
|
|
554
|
+
this.#module = null;
|
|
555
|
+
this.#booting = null;
|
|
398
556
|
}
|
|
399
557
|
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
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
|
-
|
|
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
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
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
|
-
|
|
417
|
-
|
|
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
|
-
|
|
420
|
-
|
|
421
|
-
canvas.focus({ preventScroll: true });
|
|
422
|
-
};
|
|
613
|
+
this.#fitPicture();
|
|
614
|
+
}
|
|
423
615
|
|
|
424
|
-
|
|
425
|
-
|
|
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
|
-
//
|
|
651
|
+
// ---- The one place this engine does not simply inherit ----
|
|
428
652
|
|
|
429
|
-
/**
|
|
430
|
-
|
|
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
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
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
|
-
|
|
438
|
-
|
|
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
|
-
|
|
713
|
+
override restart(options?: Partial<Rsdkv4Options>): Rsdkv4Session {
|
|
714
|
+
return super.restart(options) as Rsdkv4Session;
|
|
715
|
+
}
|
|
445
716
|
|
|
446
|
-
|
|
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
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
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
|
-
|
|
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
|
-
|
|
461
|
-
|
|
742
|
+
/** Who is holding the engine paused, or null. */
|
|
743
|
+
get pausedBy(): string | null {
|
|
744
|
+
return this.#pauseOwner;
|
|
745
|
+
}
|
|
462
746
|
|
|
463
|
-
|
|
464
|
-
|
|
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
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
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
|
-
|
|
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
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
)
|
|
500
|
-
|
|
501
|
-
if (!
|
|
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]
|
|
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
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
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
|
-
|
|
516
|
-
|
|
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
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
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
|
-
|
|
526
|
-
|
|
877
|
+
this.#pullErrorKey = key;
|
|
878
|
+
this.#pullErrorAt = now;
|
|
879
|
+
this.#pullErrors = 0;
|
|
527
880
|
}
|
|
528
881
|
}
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
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
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
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
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
Module
|
|
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
|
-
//
|
|
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
|
-
|
|
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
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
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
|
-
|
|
573
|
-
|
|
574
|
-
if (
|
|
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
|
-
|
|
578
|
-
|
|
579
|
-
|
|
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
|
-
|
|
586
|
-
|
|
587
|
-
pauseOwner = null;
|
|
588
|
-
applyPaused(false);
|
|
589
|
-
};
|
|
970
|
+
const Module = await this.#instantiate(canvas, config);
|
|
971
|
+
this.#module = Module;
|
|
590
972
|
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
/*
|
|
1116
|
+
/* no save yet */
|
|
602
1117
|
}
|
|
603
|
-
}
|
|
1118
|
+
}
|
|
604
1119
|
|
|
605
1120
|
/**
|
|
606
|
-
*
|
|
1121
|
+
* Copy SData.bin out of the wasm into `<namespace>/`, and announce it if it moved.
|
|
607
1122
|
*
|
|
608
|
-
*
|
|
609
|
-
*
|
|
610
|
-
*
|
|
611
|
-
*
|
|
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
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
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
|
-
|
|
622
|
-
} catch
|
|
623
|
-
|
|
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
|
-
|
|
648
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
//
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
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
|
-
|
|
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
|
+
}
|