c64-ready 0.5.1 → 0.6.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.
Files changed (117) hide show
  1. package/README.md +332 -96
  2. package/bin/headless.mjs +7 -3
  3. package/bin/serve.mjs +162 -0
  4. package/dist/assets/CHANGELOG-C1nvP1iO.js +96 -0
  5. package/dist/assets/index-Cioamf6E.js +394 -0
  6. package/dist/assets/marked.esm-BOXuzyNF.js +37 -0
  7. package/dist/assets/purify.es-y41lKIN9.js +2 -0
  8. package/dist/audio-worklet-processor.js +83 -0
  9. package/dist/c64-ready/c64-ready.gif +0 -0
  10. package/dist/c64-ready/index.html +58 -0
  11. package/dist/c64.wasm +0 -0
  12. package/dist/games/cartridges/legend-of-wilf.crt +0 -0
  13. package/dist/index.html +38 -0
  14. package/dist/led-off.svg +20 -0
  15. package/dist/led-on.svg +27 -0
  16. package/dist/vite.svg +15 -0
  17. package/dist-ts/emulator/c64-emulator.d.ts +107 -0
  18. package/dist-ts/emulator/c64-emulator.d.ts.map +1 -0
  19. package/dist-ts/emulator/c64-emulator.js +13 -1
  20. package/dist-ts/emulator/c64-emulator.js.map +1 -0
  21. package/dist-ts/emulator/c64-wasm.d.ts +42 -0
  22. package/dist-ts/emulator/c64-wasm.d.ts.map +1 -0
  23. package/dist-ts/emulator/c64-wasm.js +1 -0
  24. package/dist-ts/emulator/c64-wasm.js.map +1 -0
  25. package/dist-ts/emulator/constants.d.ts +14 -0
  26. package/dist-ts/emulator/constants.d.ts.map +1 -0
  27. package/dist-ts/emulator/constants.js +1 -0
  28. package/dist-ts/emulator/constants.js.map +1 -0
  29. package/dist-ts/emulator/input.d.ts +33 -0
  30. package/dist-ts/emulator/input.d.ts.map +1 -0
  31. package/dist-ts/emulator/input.js +26 -5
  32. package/dist-ts/emulator/input.js.map +1 -0
  33. package/dist-ts/emulator/memory.d.ts +2 -0
  34. package/dist-ts/emulator/memory.d.ts.map +1 -0
  35. package/dist-ts/emulator/memory.js +9 -0
  36. package/dist-ts/emulator/memory.js.map +1 -0
  37. package/dist-ts/headless/audio-capture.d.ts +13 -0
  38. package/dist-ts/headless/audio-capture.d.ts.map +1 -0
  39. package/dist-ts/headless/audio-capture.js +24 -0
  40. package/dist-ts/headless/audio-capture.js.map +1 -0
  41. package/dist-ts/headless/c64-headless.d.ts +36 -0
  42. package/dist-ts/headless/c64-headless.d.ts.map +1 -0
  43. package/dist-ts/headless/c64-headless.js +87 -0
  44. package/dist-ts/headless/c64-headless.js.map +1 -0
  45. package/dist-ts/headless/ffmpeg-runner.d.ts +18 -0
  46. package/dist-ts/headless/ffmpeg-runner.d.ts.map +1 -0
  47. package/dist-ts/headless/ffmpeg-runner.js +67 -0
  48. package/dist-ts/headless/ffmpeg-runner.js.map +1 -0
  49. package/dist-ts/headless/frame-capture.d.ts +13 -0
  50. package/dist-ts/headless/frame-capture.d.ts.map +1 -0
  51. package/dist-ts/headless/frame-capture.js +24 -0
  52. package/dist-ts/headless/frame-capture.js.map +1 -0
  53. package/dist-ts/headless/input-bridge.d.ts +21 -0
  54. package/dist-ts/headless/input-bridge.d.ts.map +1 -0
  55. package/dist-ts/headless/input-bridge.js +41 -0
  56. package/dist-ts/headless/input-bridge.js.map +1 -0
  57. package/dist-ts/src/counter.js +9 -0
  58. package/dist-ts/src/emulator/c64-emulator.js +308 -0
  59. package/dist-ts/src/emulator/c64-emulator.test.js +104 -0
  60. package/dist-ts/src/emulator/c64-wasm.js +149 -0
  61. package/dist-ts/src/emulator/c64-wasm.test.js +65 -0
  62. package/dist-ts/src/emulator/constants.js +9 -0
  63. package/dist-ts/src/emulator/input.js +62 -0
  64. package/dist-ts/src/emulator/input.test.js +53 -0
  65. package/dist-ts/src/emulator/memory.js +1 -0
  66. package/dist-ts/src/headless/audio-capture.js +23 -0
  67. package/dist-ts/src/headless/c64-headless.js +85 -0
  68. package/dist-ts/src/headless/ffmpeg-runner.js +33 -0
  69. package/dist-ts/src/headless/frame-capture.js +23 -0
  70. package/dist-ts/src/headless/headless.cli.test.js +46 -0
  71. package/dist-ts/src/headless/input-bridge.js +37 -0
  72. package/dist-ts/src/main.js +57 -0
  73. package/dist-ts/src/player/audio-engine.js +175 -0
  74. package/dist-ts/src/player/audio-engine.test.js +284 -0
  75. package/dist-ts/src/player/c64-player.js +105 -0
  76. package/dist-ts/src/player/c64-player.test.js +165 -0
  77. package/dist-ts/src/player/canvas-renderer.js +148 -0
  78. package/dist-ts/src/player/canvas-renderer.test.js +135 -0
  79. package/dist-ts/src/player/input-handler.js +13 -0
  80. package/dist-ts/src/player/ui-controller.js +575 -0
  81. package/dist-ts/src/player/ui-controller.test.js +67 -0
  82. package/dist-ts/src/types/emulator.js +1 -0
  83. package/dist-ts/src/types/index.js +4 -0
  84. package/dist-ts/tools/run-wrapper.js +36 -0
  85. package/dist-ts/types/emulator.d.ts +128 -0
  86. package/dist-ts/types/emulator.d.ts.map +1 -0
  87. package/dist-ts/types/emulator.js +2 -0
  88. package/dist-ts/types/emulator.js.map +1 -0
  89. package/dist-ts/types/index.d.ts +51 -0
  90. package/dist-ts/types/index.d.ts.map +1 -0
  91. package/dist-ts/types/index.js +5 -0
  92. package/dist-ts/types/index.js.map +1 -0
  93. package/package.json +40 -6
  94. package/public/audio-worklet-processor.js +83 -0
  95. package/public/led-off.svg +20 -0
  96. package/public/led-on.svg +27 -0
  97. package/src/counter.ts +9 -0
  98. package/src/emulator/c64-emulator.ts +357 -0
  99. package/src/emulator/c64-wasm.ts +180 -0
  100. package/src/emulator/constants.ts +22 -0
  101. package/src/emulator/input.ts +105 -0
  102. package/src/emulator/memory.ts +9 -0
  103. package/src/headless/headless-cli.mjs +105 -19
  104. package/src/headless/input-bridge.ts +13 -4
  105. package/src/headless/input-server.mjs +76 -0
  106. package/src/main.ts +80 -0
  107. package/src/player/audio-engine.ts +216 -0
  108. package/src/player/c64-player.ts +222 -0
  109. package/src/player/canvas-renderer.ts +139 -0
  110. package/src/player/input-handler.ts +116 -0
  111. package/src/player/styles/canvas-renderer.css +41 -0
  112. package/src/player/styles/ui-controller.css +286 -0
  113. package/src/player/ui-controller.ts +485 -0
  114. package/src/style.css +96 -0
  115. package/src/types/emulator.ts +167 -0
  116. package/src/types/index.ts +62 -0
  117. package/src/typescript.svg +1 -0
@@ -0,0 +1,357 @@
1
+ /**
2
+ * C64Emulator — public interface for all emulator interactions.
3
+ *
4
+ * Responsibilities:
5
+ * - Own the C64WASM instance and its lifecycle
6
+ * - Expose clean, meaningful methods to frontend/headless consumers
7
+ * - Manage emulation state (running, paused, frameCount)
8
+ * - Fire onFrame / onAudio callbacks each tick
9
+ *
10
+ * Consumers (C64Player, C64Headless, Vue pages) use this class only.
11
+ * They never touch C64WASM directly.
12
+ */
13
+
14
+ import { C64WASM } from './c64-wasm';
15
+ import type { C64Config, FrameBuffer, AudioBuffer, GameLoadOptions, InputEvent } from '../types';
16
+ import type { JoystickPort, JoystickInput } from './constants';
17
+
18
+ const FRAME_WIDTH = 384;
19
+ const FRAME_HEIGHT = 272;
20
+ const DEFAULT_SAMPLE_RATE = 44100;
21
+
22
+ export class C64Emulator {
23
+ private wasm: C64WASM;
24
+ private config: C64Config;
25
+ private running: boolean = false;
26
+ private frameCount: number = 0;
27
+
28
+ /** Called every tick with the latest video frame */
29
+ onFrame?: (frame: FrameBuffer) => void;
30
+ /** Called every tick with the latest audio samples */
31
+ onAudio?: (audio: AudioBuffer) => void;
32
+
33
+ private constructor(wasm: C64WASM, config: Partial<C64Config> = {}) {
34
+ this.wasm = wasm;
35
+ this.config = {
36
+ videoWidth: FRAME_WIDTH,
37
+ videoHeight: FRAME_HEIGHT,
38
+ sampleRate: DEFAULT_SAMPLE_RATE,
39
+ audioChannels: 1,
40
+ cyclesPerFrame: 50,
41
+ ...config,
42
+ };
43
+ }
44
+
45
+ // ---------------------------------------------------------------------------
46
+ // Factory
47
+ // ---------------------------------------------------------------------------
48
+
49
+ /**
50
+ * Main entry point for any consumer (browser page, headless server, tests).
51
+ *
52
+ * @example
53
+ * const emulator = await C64Emulator.load();
54
+ */
55
+ static async load(
56
+ wasmUrl: string = '/src/emulator/c64.wasm',
57
+ config: Partial<C64Config> = {},
58
+ ): Promise<C64Emulator> {
59
+ const wasm = await C64WASM.load(wasmUrl);
60
+ const emulator = new C64Emulator(wasm, config);
61
+ emulator.init();
62
+ return emulator;
63
+ }
64
+
65
+ // ---------------------------------------------------------------------------
66
+ // Lifecycle
67
+ // ---------------------------------------------------------------------------
68
+
69
+ private init(): void {
70
+ const x = this.wasm.exports;
71
+ if (!x) throw new Error('WASM exports not available');
72
+ x.c64_init();
73
+ // Reference config to avoid unused-private-field warnings in TS and
74
+ // ensure sample rate is applied on init. Guard calls in case the
75
+ // underlying WASM exports don't provide the SID helper (tests/fake
76
+ // instantiations may omit it).
77
+ if (this.config.sampleRate) {
78
+ const fn = (this.wasm.exports as unknown as { sid_setSampleRate?: (rate: number) => unknown })
79
+ .sid_setSampleRate;
80
+ if (typeof fn === 'function') fn(this.config.sampleRate);
81
+ }
82
+ }
83
+
84
+ start(): void {
85
+ this.running = true;
86
+ }
87
+ pause(): void {
88
+ this.running = false;
89
+ }
90
+ isRunning(): boolean {
91
+ return this.running;
92
+ }
93
+ getFrameCount(): number {
94
+ return this.frameCount;
95
+ }
96
+
97
+ reset(): void {
98
+ this.wasm.exports?.c64_reset();
99
+ this.frameCount = 0;
100
+ }
101
+
102
+ // ---------------------------------------------------------------------------
103
+ // Frame loop — call once per animation frame (requestAnimationFrame)
104
+ // ---------------------------------------------------------------------------
105
+
106
+ /**
107
+ * The SID continuously fills a circular audio buffer as CPU cycles execute.
108
+ * Must match the ScriptProcessorNode buffer length used by the original
109
+ * c64.js runtime (4096 samples).
110
+ */
111
+ private static readonly AUDIO_BUFFER_SIZE = 4096;
112
+
113
+ tick(dTime: number = 0): void {
114
+ if (!this.running) return;
115
+ const x = this.wasm.exports!;
116
+
117
+ // Clamp dTime exactly like the original c64.js render loop:
118
+ // if dTime is 0 or > 100 ms, lock to ~60 fps to prevent runaway cycles.
119
+ // if (!dTime || dTime > 100) {
120
+ // dTime = 1000 / 60;
121
+ // }
122
+
123
+ const updated = x.debugger_update(dTime);
124
+ this.frameCount++;
125
+
126
+ // Only push a video frame when the emulator actually advanced
127
+ if (updated && this.onFrame) {
128
+ const ptr = x.c64_getPixelBuffer();
129
+ const data = this.wasm.heap!.heapU8.subarray(ptr, ptr + FRAME_WIDTH * FRAME_HEIGHT * 4);
130
+ this.onFrame({ width: FRAME_WIDTH, height: FRAME_HEIGHT, data, timestamp: this.frameCount });
131
+ }
132
+ }
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // Game loading
136
+ // ---------------------------------------------------------------------------
137
+
138
+ loadGame(options: GameLoadOptions): void {
139
+ const x = this.wasm.exports;
140
+ if (!x || !this.wasm.heap) throw new Error('WASM not ready');
141
+
142
+ const ptr = this.wasm.allocAndWrite(options.data);
143
+ try {
144
+ switch (options.type) {
145
+ case 'prg':
146
+ x.c64_loadPRG(ptr, options.data.length);
147
+ break;
148
+ case 'd64':
149
+ x.c64_insertDisk(ptr, options.data.length);
150
+ break;
151
+ case 'crt':
152
+ x.c64_loadCartridge(ptr, options.data.length);
153
+ break;
154
+ case 'snapshot':
155
+ x.c64_loadSnapshot(ptr, options.data.length);
156
+ break;
157
+ }
158
+ } finally {
159
+ this.wasm.free(ptr);
160
+ }
161
+ }
162
+
163
+ removeCartridge(): void {
164
+ this.wasm.exports?.c64_removeCartridge();
165
+
166
+ this.wasm.exports?.c64_reset();
167
+ this.frameCount = 0;
168
+ }
169
+
170
+ // ---------------------------------------------------------------------------
171
+ // Input
172
+ // ---------------------------------------------------------------------------
173
+
174
+ handleInput(event: InputEvent): void {
175
+ const x = this.wasm.exports;
176
+ if (!x) return;
177
+
178
+ if (event.type === 'key' && event.key !== undefined) {
179
+ x.keyboard_keyPressed(Number(event.key));
180
+ } else if (event.type === 'joystick') {
181
+ const port = (event.joystickPort ?? 1) - 1; // callers use 1/2, WASM uses 0/1
182
+ const dirMap: Record<string, number> = { up: 1, down: 2, left: 4, right: 8 };
183
+ if (event.direction) x.c64_joystick_push(port, dirMap[event.direction] ?? 0);
184
+ if (event.fire1) x.c64_joystick_push(port, 16);
185
+ }
186
+ }
187
+
188
+ keyDown(keyCode: number): void {
189
+ this.wasm.exports?.keyboard_keyPressed(keyCode);
190
+ }
191
+ keyUp(keyCode: number): void {
192
+ this.wasm.exports?.keyboard_keyReleased(keyCode);
193
+ }
194
+
195
+ /**
196
+ * Push (press) a joystick direction or fire button.
197
+ *
198
+ * @param port - 1-based joystick port: `1` = port 1, `2` = port 2
199
+ * @param dir - Bitmask value for the direction or fire button:
200
+ * - `0x01` — Up (`JOYSTICK_DIRECTION.UP`)
201
+ * - `0x02` — Down (`JOYSTICK_DIRECTION.DOWN`)
202
+ * - `0x04` — Left (`JOYSTICK_DIRECTION.LEFT`)
203
+ * - `0x08` — Right (`JOYSTICK_DIRECTION.RIGHT`)
204
+ * - `0x10` — Fire (`JOYSTICK_FIRE_1`)
205
+ *
206
+ * @example
207
+ * emulator.joystickPush(2, JOYSTICK_DIRECTION.UP); // port 2 up
208
+ * emulator.joystickPush(2, JOYSTICK_FIRE_1); // port 2 fire
209
+ */
210
+ joystickPush(port: JoystickPort, dir: JoystickInput): void {
211
+ this.wasm.exports?.c64_joystick_push(port - 1, dir);
212
+ }
213
+
214
+ /**
215
+ * Release a joystick direction or fire button.
216
+ *
217
+ * @param port - 1-based joystick port: `1` = port 1, `2` = port 2
218
+ * @param dir - Bitmask value to release (same values as {@link joystickPush})
219
+ *
220
+ * @example
221
+ * emulator.joystickRelease(2, JOYSTICK_DIRECTION.UP); // release port 2 up
222
+ */
223
+ joystickRelease(port: JoystickPort, dir: JoystickInput): void {
224
+ this.wasm.exports?.c64_joystick_release(port - 1, dir);
225
+ }
226
+ mousePosition(x: number, y: number): void {
227
+ this.wasm.exports?.c64_mouse_position(x, y);
228
+ }
229
+
230
+ // ---------------------------------------------------------------------------
231
+ // Memory access
232
+ // ---------------------------------------------------------------------------
233
+
234
+ ramRead(addr: number): number {
235
+ return this.wasm.exports?.c64_ramRead(addr) ?? 0;
236
+ }
237
+ ramWrite(addr: number, v: number): void {
238
+ this.wasm.exports?.c64_ramWrite(addr, v);
239
+ }
240
+ cpuRead(addr: number): number {
241
+ return this.wasm.exports?.c64_cpuRead(addr) ?? 0;
242
+ }
243
+ cpuWrite(addr: number, v: number): void {
244
+ this.wasm.exports?.c64_cpuWrite(addr, v);
245
+ }
246
+
247
+ // ---------------------------------------------------------------------------
248
+ // CPU state
249
+ // ---------------------------------------------------------------------------
250
+
251
+ getPC(): number {
252
+ return this.wasm.exports?.c64_getPC() ?? 0;
253
+ }
254
+ getRegA(): number {
255
+ return this.wasm.exports?.c64_getRegA() ?? 0;
256
+ }
257
+ getRegX(): number {
258
+ return this.wasm.exports?.c64_getRegX() ?? 0;
259
+ }
260
+ getRegY(): number {
261
+ return this.wasm.exports?.c64_getRegY() ?? 0;
262
+ }
263
+ getSP(): number {
264
+ return this.wasm.exports?.c64_getSP() ?? 0;
265
+ }
266
+ getCycleCount(): number {
267
+ return this.wasm.exports?.c64_getCycleCount() ?? 0;
268
+ }
269
+
270
+ // ---------------------------------------------------------------------------
271
+ // Video
272
+ // ---------------------------------------------------------------------------
273
+
274
+ getFrameBuffer(): FrameBuffer {
275
+ if (!this.wasm.exports || !this.wasm.heap) throw new Error('WASM not ready');
276
+ const ptr = this.wasm.exports.c64_getPixelBuffer();
277
+ const data = this.wasm.heap.heapU8.slice(ptr, ptr + FRAME_WIDTH * FRAME_HEIGHT * 4);
278
+ return { width: FRAME_WIDTH, height: FRAME_HEIGHT, data, timestamp: this.frameCount };
279
+ }
280
+
281
+ // ---------------------------------------------------------------------------
282
+ // Snapshot
283
+ // ---------------------------------------------------------------------------
284
+
285
+ getSnapshot(): Uint8Array {
286
+ const x = this.wasm.exports;
287
+ if (!x || !this.wasm.heap) throw new Error('WASM not ready');
288
+ const size = x.c64_getSnapshotSize();
289
+ const ptr = x.malloc(size);
290
+ x.c64_getSnapshot(ptr);
291
+ const snap = this.wasm.heap.heapU8.slice(ptr, ptr + size);
292
+ x.free(ptr);
293
+ return snap;
294
+ }
295
+
296
+ // ---------------------------------------------------------------------------
297
+ // Debugger
298
+ // ---------------------------------------------------------------------------
299
+
300
+ debuggerPause(): void {
301
+ this.wasm.exports?.debugger_pause();
302
+ }
303
+ debuggerPlay(): void {
304
+ this.wasm.exports?.debugger_play();
305
+ }
306
+ debuggerStep(): void {
307
+ this.wasm.exports?.debugger_step();
308
+ }
309
+ debuggerIsRunning(): boolean {
310
+ return (this.wasm.exports?.debugger_isRunning() ?? 0) !== 0;
311
+ }
312
+ setDebugSpeed(speed: number): void {
313
+ this.wasm.exports?.debugger_set_speed(speed);
314
+ }
315
+
316
+ // ---------------------------------------------------------------------------
317
+ // Audio / SID
318
+ // ---------------------------------------------------------------------------
319
+
320
+ setSampleRate(rate: number): void {
321
+ this.wasm.exports?.sid_setSampleRate(rate);
322
+ }
323
+
324
+ /**
325
+ * Return a snapshot of the SID's circular audio buffer (4096 Float32 samples).
326
+ * This mirrors the original c64.js `audioProcess` which reads
327
+ * `sid_getAudioBuffer()` with a fixed `audioBufferLength` — never calling
328
+ * `sid_dumpBuffer()`.
329
+ */
330
+ getSidBuffer(): Float32Array | null {
331
+ const x = this.wasm.exports;
332
+ if (!x || !this.wasm.heap) return null;
333
+ const ptr = x.sid_getAudioBuffer();
334
+ // Return a copy so the caller owns the data (the SID overwrites this buffer)
335
+ return new Float32Array(
336
+ this.wasm.heap.heapF32.subarray(ptr >> 2, (ptr >> 2) + C64Emulator.AUDIO_BUFFER_SIZE),
337
+ );
338
+ }
339
+
340
+ setSIDModel(model: number): void {
341
+ this.wasm.exports?.sid_setModel(model);
342
+ }
343
+ setVoiceEnabled(voice: number, enabled: boolean): void {
344
+ this.wasm.exports?.sid_setVoiceEnabled(enabled ? voice : 0);
345
+ }
346
+
347
+ // ---------------------------------------------------------------------------
348
+ // Drive
349
+ // ---------------------------------------------------------------------------
350
+
351
+ setDriveEnabled(enabled: boolean): void {
352
+ this.wasm.exports?.c64_setDriveEnabled(enabled ? 1 : 0);
353
+ }
354
+ getDriveEnabled(): boolean {
355
+ return (this.wasm.exports?.c64_getDriveEnabled() ?? 0) !== 0;
356
+ }
357
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Low-level wrapper around the C64 WebAssembly binary (Emscripten-compiled)
3
+ *
4
+ * Responsibilities:
5
+ * - Fetch and instantiate the WASM binary
6
+ * - Provide the Emscripten/WASI imports the binary requires
7
+ * - Manage WebAssembly.Memory and keep heap views up to date
8
+ * - Forward raw WASM export calls to C64Emulator
9
+ *
10
+ * NOT responsible for: game logic, input handling, frame loop, or UI.
11
+ * Consumers should use C64Emulator, not this class directly.
12
+ */
13
+
14
+ import type { WASMExports } from '../types/emulator';
15
+
16
+ export interface HeapViews {
17
+ heapU8: Uint8Array;
18
+ heapF32: Float32Array;
19
+ heapU32: Uint32Array;
20
+ }
21
+
22
+ export class C64WASM {
23
+ /** Raw WASM exports — available to C64Emulator */
24
+ exports: WASMExports | null = null;
25
+
26
+ /** Typed views into WASM linear memory */
27
+ heap: HeapViews | null = null;
28
+
29
+ private wasmMemory: WebAssembly.Memory | null = null;
30
+
31
+ // ---------------------------------------------------------------------------
32
+ // Bootstrap
33
+ // ---------------------------------------------------------------------------
34
+
35
+ /**
36
+ * Fetch, instantiate and initialise the WASM binary.
37
+ * C64Emulator calls this via the static C64Emulator.load() factory.
38
+ */
39
+ static async load(wasmUrl: string = '/src/emulator/c64.wasm'): Promise<C64WASM> {
40
+ const response = await fetch(wasmUrl);
41
+ if (!response.ok) throw new Error(`Failed to fetch ${wasmUrl}: ${response.status}`);
42
+ const binary = await response.arrayBuffer();
43
+ const instance = new C64WASM();
44
+ await instance.instantiate(binary);
45
+ return instance;
46
+ }
47
+
48
+ // Emscripten layout constants (must match the compiled binary)
49
+ private static readonly DYNAMICTOP_PTR = 5583504;
50
+ private static readonly DYNAMIC_BASE = 10826544;
51
+ private static readonly INITIAL_PAGES = 256; // 16 MB
52
+
53
+ async instantiate(wasmBinary: ArrayBuffer, extraEnv?: Record<string, unknown>): Promise<void> {
54
+ const mem = new WebAssembly.Memory({ initial: C64WASM.INITIAL_PAGES });
55
+ this.wasmMemory = mem;
56
+
57
+ const importObject = {
58
+ env: { ...this.makeEnvImports(mem), ...(extraEnv ?? {}) },
59
+ wasi_snapshot_preview1: this.makeWasiImports(mem),
60
+ };
61
+
62
+ try {
63
+ const result = await WebAssembly.instantiate(wasmBinary, importObject);
64
+ this.exports = result.instance.exports as unknown as WASMExports;
65
+ this.updateHeapViews();
66
+
67
+ // Initialise the sbrk heap pointer so malloc knows where free memory starts
68
+ new DataView(mem.buffer).setUint32(C64WASM.DYNAMICTOP_PTR, C64WASM.DYNAMIC_BASE, true);
69
+
70
+ this.exports.__wasm_call_ctors();
71
+ } catch (err) {
72
+ throw new Error(`WASM instantiation failed: ${err}`, { cause: err });
73
+ }
74
+ }
75
+
76
+ // ---------------------------------------------------------------------------
77
+ // Memory
78
+ // ---------------------------------------------------------------------------
79
+
80
+ /** Allocate a buffer in WASM heap, write data, return pointer */
81
+ allocAndWrite(data: Uint8Array): number {
82
+ if (!this.exports || !this.heap) throw new Error('WASM not ready');
83
+ const ptr = this.exports.malloc(data.length);
84
+ // malloc may have grown memory, so refresh views before writing
85
+ this.updateHeapViews();
86
+ this.heap.heapU8.set(data, ptr);
87
+ return ptr;
88
+ }
89
+
90
+ free(ptr: number): void {
91
+ this.exports?.free(ptr);
92
+ }
93
+
94
+ /** Refresh heap views — must be called after any memory.grow() */
95
+ updateHeapViews(): void {
96
+ if (!this.wasmMemory) throw new Error('WASM memory not initialized');
97
+ const buffer = this.wasmMemory.buffer;
98
+ this.heap = {
99
+ heapU8: new Uint8Array(buffer),
100
+ heapF32: new Float32Array(buffer),
101
+ heapU32: new Uint32Array(buffer),
102
+ };
103
+ }
104
+
105
+ // ---------------------------------------------------------------------------
106
+ // Emscripten env imports
107
+ // ---------------------------------------------------------------------------
108
+
109
+ private makeEnvImports(mem: WebAssembly.Memory) {
110
+ return {
111
+ memory: mem,
112
+
113
+ emscripten_get_sbrk_ptr: (): number => C64WASM.DYNAMICTOP_PTR,
114
+
115
+ emscripten_resize_heap: (requestedSize: number): number => {
116
+ const PAGE_MULTIPLE = 65536;
117
+ const maxHeapSize = 2147483648 - PAGE_MULTIPLE;
118
+ if (requestedSize > maxHeapSize) return 0;
119
+
120
+ const oldSize = mem.buffer.byteLength;
121
+ const minHeapSize = 16777216;
122
+ for (let cutDown = 1; cutDown <= 4; cutDown *= 2) {
123
+ let overGrown = oldSize * (1 + 0.2 / cutDown);
124
+ overGrown = Math.min(overGrown, requestedSize + 100663296);
125
+ const newSize = Math.min(
126
+ maxHeapSize,
127
+ Math.ceil(Math.max(minHeapSize, requestedSize, overGrown) / PAGE_MULTIPLE) *
128
+ PAGE_MULTIPLE,
129
+ );
130
+ try {
131
+ mem.grow((newSize - mem.buffer.byteLength + 65535) >>> 16);
132
+ this.updateHeapViews();
133
+ return 1;
134
+ } catch {
135
+ // retry with less aggressive growth
136
+ }
137
+ }
138
+ return 0;
139
+ },
140
+
141
+ emscripten_memcpy_big: (dest: number, src: number, num: number): number => {
142
+ new Uint8Array(mem.buffer).copyWithin(dest, src, src + num);
143
+ return dest;
144
+ },
145
+
146
+ setTempRet0: (_val: number): void => {},
147
+
148
+ emscripten_asm_const_iii: (_code: number, _sig: number, _val: number): number => 0,
149
+
150
+ table: new WebAssembly.Table({ initial: 512, maximum: 512, element: 'anyfunc' }),
151
+ };
152
+ }
153
+
154
+ // ---------------------------------------------------------------------------
155
+ // WASI imports (only fd_write is used by this binary)
156
+ // ---------------------------------------------------------------------------
157
+
158
+ private makeWasiImports(mem: WebAssembly.Memory) {
159
+ return {
160
+ fd_write: (fd: number, iovs: number, iovs_len: number, nwritten: number): number => {
161
+ const view = new DataView(mem.buffer);
162
+ const u8 = new Uint8Array(mem.buffer);
163
+ let written = 0;
164
+ for (let i = 0; i < iovs_len; i++) {
165
+ const ptr = view.getUint32(iovs + i * 8, true);
166
+ const len = view.getUint32(iovs + i * 8 + 4, true);
167
+ // Only forward stderr (fd 2) to the console — stdout (fd 1) is
168
+ // extremely noisy (SID dumps buffer length every frame).
169
+ if (fd === 2) {
170
+ const text = new TextDecoder().decode(u8.subarray(ptr, ptr + len));
171
+ console.error(text);
172
+ }
173
+ written += len;
174
+ }
175
+ view.setUint32(nwritten, written, true);
176
+ return 0;
177
+ },
178
+ };
179
+ }
180
+ }
@@ -0,0 +1,22 @@
1
+ export const JOYSTICK_PORT_1 = 1 as const;
2
+ export const JOYSTICK_PORT_2 = 2 as const;
3
+
4
+ /** 1-based joystick port number */
5
+ export type JoystickPort = typeof JOYSTICK_PORT_1 | typeof JOYSTICK_PORT_2;
6
+
7
+ export const JOYSTICK_DIRECTION = {
8
+ UP: 0x1,
9
+ DOWN: 0x2,
10
+ LEFT: 0x4,
11
+ RIGHT: 0x8,
12
+ } as const;
13
+
14
+ export const JOYSTICK_FIRE_1 = 0x10 as const;
15
+
16
+ /** Any valid joystick direction or fire bitmask */
17
+ export type JoystickInput =
18
+ | typeof JOYSTICK_DIRECTION.UP
19
+ | typeof JOYSTICK_DIRECTION.DOWN
20
+ | typeof JOYSTICK_DIRECTION.LEFT
21
+ | typeof JOYSTICK_DIRECTION.RIGHT
22
+ | typeof JOYSTICK_FIRE_1;
@@ -0,0 +1,105 @@
1
+ import type { C64Emulator } from './c64-emulator';
2
+ import { JOYSTICK_DIRECTION, JOYSTICK_FIRE_1, JOYSTICK_PORT_2 } from './constants';
3
+ import type { JoystickPort } from './constants';
4
+
5
+ export const KEY_TO_JOYSTICK = {
6
+ ArrowUp: JOYSTICK_DIRECTION.UP,
7
+ ArrowDown: JOYSTICK_DIRECTION.DOWN,
8
+ ArrowLeft: JOYSTICK_DIRECTION.LEFT,
9
+ ArrowRight: JOYSTICK_DIRECTION.RIGHT,
10
+ ControlLeft: JOYSTICK_FIRE_1,
11
+ } as const;
12
+
13
+ /**
14
+ * Array of keyboard codes that map to joystick inputs. Exported so
15
+ * external UI/input handlers can derive their blocking behavior from
16
+ * the same canonical mapping used by the emulator.
17
+ */
18
+ export const JOYSTICK_KEY_CODES: Array<keyof typeof KEY_TO_JOYSTICK> = Object.keys(
19
+ KEY_TO_JOYSTICK,
20
+ ) as Array<keyof typeof KEY_TO_JOYSTICK>;
21
+
22
+ type MappedControl = keyof typeof KEY_TO_JOYSTICK;
23
+
24
+ export class EmulatorInput {
25
+ private readonly emulator: C64Emulator;
26
+ private readonly target: EventTarget;
27
+ // Which joystick port keyboard events map to (1 or 2). Default is port 2.
28
+ private keyboardJoystickPort: JoystickPort;
29
+ private readonly pressedControls = new Set<MappedControl>();
30
+ private readonly keyDownHandler = (event: KeyboardEvent): void => {
31
+ this.handleKeyDown(event);
32
+ };
33
+ private readonly keyUpHandler = (event: KeyboardEvent): void => {
34
+ this.handleKeyUp(event);
35
+ };
36
+
37
+ constructor(
38
+ emulator: C64Emulator,
39
+ target: EventTarget = window,
40
+ defaultPort: JoystickPort = JOYSTICK_PORT_2,
41
+ ) {
42
+ this.emulator = emulator;
43
+ this.target = target;
44
+ this.keyboardJoystickPort = defaultPort;
45
+ }
46
+
47
+ attach(): void {
48
+ this.target.addEventListener('keydown', this.keyDownHandler as EventListener);
49
+ this.target.addEventListener('keyup', this.keyUpHandler as EventListener);
50
+ }
51
+
52
+ detach(): void {
53
+ this.target.removeEventListener('keydown', this.keyDownHandler as EventListener);
54
+ this.target.removeEventListener('keyup', this.keyUpHandler as EventListener);
55
+ this.releaseAll();
56
+ }
57
+
58
+ private handleKeyDown(event: KeyboardEvent): void {
59
+ // handle keydown
60
+ const control = this.getMappedControl(event);
61
+ if (!control || this.pressedControls.has(control)) {
62
+ return;
63
+ }
64
+
65
+ this.pressedControls.add(control);
66
+ this.emulator.joystickPush(this.keyboardJoystickPort, KEY_TO_JOYSTICK[control]);
67
+ event.preventDefault();
68
+ }
69
+
70
+ private handleKeyUp(event: KeyboardEvent): void {
71
+ // handle keyup
72
+ const control = this.getMappedControl(event);
73
+ if (!control) {
74
+ return;
75
+ }
76
+
77
+ this.pressedControls.delete(control);
78
+ this.emulator.joystickRelease(this.keyboardJoystickPort, KEY_TO_JOYSTICK[control]);
79
+ event.preventDefault();
80
+ }
81
+
82
+ private getMappedControl(event: KeyboardEvent): MappedControl | null {
83
+ if (event.code in KEY_TO_JOYSTICK) {
84
+ return event.code as MappedControl;
85
+ }
86
+
87
+ return null;
88
+ }
89
+
90
+ private releaseAll(): void {
91
+ for (const control of this.pressedControls) {
92
+ this.emulator.joystickRelease(this.keyboardJoystickPort, KEY_TO_JOYSTICK[control]);
93
+ }
94
+ this.pressedControls.clear();
95
+ }
96
+
97
+ /** Set which joystick port keyboard controls should target (1 or 2). */
98
+ setKeyboardPort(port: JoystickPort): void {
99
+ // If port is unchanged, do nothing.
100
+ if (this.keyboardJoystickPort === port) return;
101
+ // Release any pressed controls on the old port before switching.
102
+ this.releaseAll();
103
+ this.keyboardJoystickPort = port;
104
+ }
105
+ }
@@ -0,0 +1,9 @@
1
+ // This file was removed from the active source tree because it appears to be
2
+ // unused in the codebase. It has been archived here to preserve history
3
+ // and avoid accidental deletion. If you later decide to restore it,
4
+ // move it back into `src/emulator/` and re-export any required symbols.
5
+ //
6
+ // Search results showed no imports/usages of `src/emulator/memory.ts`.
7
+ // Keeping a small stub export so TypeScript treats this as a module.
8
+
9
+ export {};