c64-ready 0.5.1 → 0.6.1

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 +164 -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,308 @@
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
+ import { C64WASM } from './c64-wasm';
14
+ const FRAME_WIDTH = 384;
15
+ const FRAME_HEIGHT = 272;
16
+ const DEFAULT_SAMPLE_RATE = 44100;
17
+ export class C64Emulator {
18
+ wasm;
19
+ // @ts-expect-error Config is assigned in constructor for future use
20
+ config;
21
+ running = false;
22
+ frameCount = 0;
23
+ /** Called every tick with the latest video frame */
24
+ onFrame;
25
+ /** Called every tick with the latest audio samples */
26
+ onAudio;
27
+ constructor(wasm, config = {}) {
28
+ this.wasm = wasm;
29
+ this.config = {
30
+ videoWidth: FRAME_WIDTH,
31
+ videoHeight: FRAME_HEIGHT,
32
+ sampleRate: DEFAULT_SAMPLE_RATE,
33
+ audioChannels: 1,
34
+ cyclesPerFrame: 50,
35
+ ...config,
36
+ };
37
+ }
38
+ // ---------------------------------------------------------------------------
39
+ // Factory
40
+ // ---------------------------------------------------------------------------
41
+ /**
42
+ * Main entry point for any consumer (browser page, headless server, tests).
43
+ *
44
+ * @example
45
+ * const emulator = await C64Emulator.load();
46
+ */
47
+ static async load(wasmUrl = '/src/emulator/c64.wasm', config = {}) {
48
+ const wasm = await C64WASM.load(wasmUrl);
49
+ const emulator = new C64Emulator(wasm, config);
50
+ emulator.init();
51
+ return emulator;
52
+ }
53
+ // ---------------------------------------------------------------------------
54
+ // Lifecycle
55
+ // ---------------------------------------------------------------------------
56
+ init() {
57
+ const x = this.wasm.exports;
58
+ if (!x)
59
+ throw new Error('WASM exports not available');
60
+ x.c64_init();
61
+ }
62
+ start() {
63
+ this.running = true;
64
+ }
65
+ pause() {
66
+ this.running = false;
67
+ }
68
+ isRunning() {
69
+ return this.running;
70
+ }
71
+ getFrameCount() {
72
+ return this.frameCount;
73
+ }
74
+ reset() {
75
+ this.wasm.exports?.c64_reset();
76
+ this.frameCount = 0;
77
+ }
78
+ // ---------------------------------------------------------------------------
79
+ // Frame loop — call once per animation frame (requestAnimationFrame)
80
+ // ---------------------------------------------------------------------------
81
+ /**
82
+ * The SID continuously fills a circular audio buffer as CPU cycles execute.
83
+ * Must match the ScriptProcessorNode buffer length used by the original
84
+ * c64.js runtime (4096 samples).
85
+ */
86
+ static AUDIO_BUFFER_SIZE = 4096;
87
+ tick(dTime = 0) {
88
+ if (!this.running)
89
+ return;
90
+ const x = this.wasm.exports;
91
+ // Clamp dTime exactly like the original c64.js render loop:
92
+ // if dTime is 0 or > 100 ms, lock to ~60 fps to prevent runaway cycles.
93
+ if (!dTime || dTime > 100) {
94
+ dTime = 1000 / 60;
95
+ }
96
+ const updated = x.debugger_update(dTime);
97
+ this.frameCount++;
98
+ // Only push a video frame when the emulator actually advanced
99
+ if (updated && this.onFrame) {
100
+ const ptr = x.c64_getPixelBuffer();
101
+ const data = this.wasm.heap.heapU8.subarray(ptr, ptr + FRAME_WIDTH * FRAME_HEIGHT * 4);
102
+ this.onFrame({ width: FRAME_WIDTH, height: FRAME_HEIGHT, data, timestamp: this.frameCount });
103
+ }
104
+ }
105
+ // ---------------------------------------------------------------------------
106
+ // Game loading
107
+ // ---------------------------------------------------------------------------
108
+ loadGame(options) {
109
+ const x = this.wasm.exports;
110
+ if (!x || !this.wasm.heap)
111
+ throw new Error('WASM not ready');
112
+ const ptr = this.wasm.allocAndWrite(options.data);
113
+ try {
114
+ switch (options.type) {
115
+ case 'prg':
116
+ x.c64_loadPRG(ptr, options.data.length);
117
+ break;
118
+ case 'd64':
119
+ x.c64_insertDisk(ptr, options.data.length);
120
+ break;
121
+ case 'crt':
122
+ x.c64_loadCartridge(ptr, options.data.length);
123
+ break;
124
+ case 'snapshot':
125
+ x.c64_loadSnapshot(ptr, options.data.length);
126
+ break;
127
+ }
128
+ }
129
+ finally {
130
+ this.wasm.free(ptr);
131
+ }
132
+ }
133
+ removeCartridge() {
134
+ this.wasm.exports?.c64_removeCartridge();
135
+ }
136
+ // ---------------------------------------------------------------------------
137
+ // Input
138
+ // ---------------------------------------------------------------------------
139
+ handleInput(event) {
140
+ const x = this.wasm.exports;
141
+ if (!x)
142
+ return;
143
+ if (event.type === 'key' && event.key !== undefined) {
144
+ ``;
145
+ x.keyboard_keyPressed(Number(event.key));
146
+ }
147
+ else if (event.type === 'joystick') {
148
+ const port = (event.joystickPort ?? 1) - 1; // callers use 1/2, WASM uses 0/1
149
+ const dirMap = { up: 1, down: 2, left: 4, right: 8 };
150
+ if (event.direction)
151
+ x.c64_joystick_push(port, dirMap[event.direction] ?? 0);
152
+ if (event.fire1)
153
+ x.c64_joystick_push(port, 16);
154
+ }
155
+ }
156
+ keyDown(keyCode) {
157
+ this.wasm.exports?.keyboard_keyPressed(keyCode);
158
+ }
159
+ keyUp(keyCode) {
160
+ this.wasm.exports?.keyboard_keyReleased(keyCode);
161
+ }
162
+ /**
163
+ * Push (press) a joystick direction or fire button.
164
+ *
165
+ * @param port - 1-based joystick port: `1` = port 1, `2` = port 2
166
+ * @param dir - Bitmask value for the direction or fire button:
167
+ * - `0x01` — Up (`JOYSTICK_DIRECTION.UP`)
168
+ * - `0x02` — Down (`JOYSTICK_DIRECTION.DOWN`)
169
+ * - `0x04` — Left (`JOYSTICK_DIRECTION.LEFT`)
170
+ * - `0x08` — Right (`JOYSTICK_DIRECTION.RIGHT`)
171
+ * - `0x10` — Fire (`JOYSTICK_FIRE_1`)
172
+ *
173
+ * @example
174
+ * emulator.joystickPush(2, JOYSTICK_DIRECTION.UP); // port 2 up
175
+ * emulator.joystickPush(2, JOYSTICK_FIRE_1); // port 2 fire
176
+ */
177
+ joystickPush(port, dir) {
178
+ this.wasm.exports?.c64_joystick_push(port - 1, dir);
179
+ }
180
+ /**
181
+ * Release a joystick direction or fire button.
182
+ *
183
+ * @param port - 1-based joystick port: `1` = port 1, `2` = port 2
184
+ * @param dir - Bitmask value to release (same values as {@link joystickPush})
185
+ *
186
+ * @example
187
+ * emulator.joystickRelease(2, JOYSTICK_DIRECTION.UP); // release port 2 up
188
+ */
189
+ joystickRelease(port, dir) {
190
+ this.wasm.exports?.c64_joystick_release(port - 1, dir);
191
+ }
192
+ mousePosition(x, y) {
193
+ this.wasm.exports?.c64_mouse_position(x, y);
194
+ }
195
+ // ---------------------------------------------------------------------------
196
+ // Memory access
197
+ // ---------------------------------------------------------------------------
198
+ ramRead(addr) {
199
+ return this.wasm.exports?.c64_ramRead(addr) ?? 0;
200
+ }
201
+ ramWrite(addr, v) {
202
+ this.wasm.exports?.c64_ramWrite(addr, v);
203
+ }
204
+ cpuRead(addr) {
205
+ return this.wasm.exports?.c64_cpuRead(addr) ?? 0;
206
+ }
207
+ cpuWrite(addr, v) {
208
+ this.wasm.exports?.c64_cpuWrite(addr, v);
209
+ }
210
+ // ---------------------------------------------------------------------------
211
+ // CPU state
212
+ // ---------------------------------------------------------------------------
213
+ getPC() {
214
+ return this.wasm.exports?.c64_getPC() ?? 0;
215
+ }
216
+ getRegA() {
217
+ return this.wasm.exports?.c64_getRegA() ?? 0;
218
+ }
219
+ getRegX() {
220
+ return this.wasm.exports?.c64_getRegX() ?? 0;
221
+ }
222
+ getRegY() {
223
+ return this.wasm.exports?.c64_getRegY() ?? 0;
224
+ }
225
+ getSP() {
226
+ return this.wasm.exports?.c64_getSP() ?? 0;
227
+ }
228
+ getCycleCount() {
229
+ return this.wasm.exports?.c64_getCycleCount() ?? 0;
230
+ }
231
+ // ---------------------------------------------------------------------------
232
+ // Video
233
+ // ---------------------------------------------------------------------------
234
+ getFrameBuffer() {
235
+ if (!this.wasm.exports || !this.wasm.heap)
236
+ throw new Error('WASM not ready');
237
+ const ptr = this.wasm.exports.c64_getPixelBuffer();
238
+ const data = this.wasm.heap.heapU8.slice(ptr, ptr + FRAME_WIDTH * FRAME_HEIGHT * 4);
239
+ return { width: FRAME_WIDTH, height: FRAME_HEIGHT, data, timestamp: this.frameCount };
240
+ }
241
+ // ---------------------------------------------------------------------------
242
+ // Snapshot
243
+ // ---------------------------------------------------------------------------
244
+ getSnapshot() {
245
+ const x = this.wasm.exports;
246
+ if (!x || !this.wasm.heap)
247
+ throw new Error('WASM not ready');
248
+ const size = x.c64_getSnapshotSize();
249
+ const ptr = x.malloc(size);
250
+ x.c64_getSnapshot(ptr);
251
+ const snap = this.wasm.heap.heapU8.slice(ptr, ptr + size);
252
+ x.free(ptr);
253
+ return snap;
254
+ }
255
+ // ---------------------------------------------------------------------------
256
+ // Debugger
257
+ // ---------------------------------------------------------------------------
258
+ debuggerPause() {
259
+ this.wasm.exports?.debugger_pause();
260
+ }
261
+ debuggerPlay() {
262
+ this.wasm.exports?.debugger_play();
263
+ }
264
+ debuggerStep() {
265
+ this.wasm.exports?.debugger_step();
266
+ }
267
+ debuggerIsRunning() {
268
+ return (this.wasm.exports?.debugger_isRunning() ?? 0) !== 0;
269
+ }
270
+ setDebugSpeed(speed) {
271
+ this.wasm.exports?.debugger_set_speed(speed);
272
+ }
273
+ // ---------------------------------------------------------------------------
274
+ // Audio / SID
275
+ // ---------------------------------------------------------------------------
276
+ setSampleRate(rate) {
277
+ this.wasm.exports?.sid_setSampleRate(rate);
278
+ }
279
+ /**
280
+ * Return a snapshot of the SID's circular audio buffer (4096 Float32 samples).
281
+ * This mirrors the original c64.js `audioProcess` which reads
282
+ * `sid_getAudioBuffer()` with a fixed `audioBufferLength` — never calling
283
+ * `sid_dumpBuffer()`.
284
+ */
285
+ getSidBuffer() {
286
+ const x = this.wasm.exports;
287
+ if (!x || !this.wasm.heap)
288
+ return null;
289
+ const ptr = x.sid_getAudioBuffer();
290
+ // Return a copy so the caller owns the data (the SID overwrites this buffer)
291
+ return new Float32Array(this.wasm.heap.heapF32.subarray(ptr >> 2, (ptr >> 2) + C64Emulator.AUDIO_BUFFER_SIZE));
292
+ }
293
+ setSIDModel(model) {
294
+ this.wasm.exports?.sid_setModel(model);
295
+ }
296
+ setVoiceEnabled(voice, enabled) {
297
+ this.wasm.exports?.sid_setVoiceEnabled(enabled ? voice : 0);
298
+ }
299
+ // ---------------------------------------------------------------------------
300
+ // Drive
301
+ // ---------------------------------------------------------------------------
302
+ setDriveEnabled(enabled) {
303
+ this.wasm.exports?.c64_setDriveEnabled(enabled ? 1 : 0);
304
+ }
305
+ getDriveEnabled() {
306
+ return (this.wasm.exports?.c64_getDriveEnabled() ?? 0) !== 0;
307
+ }
308
+ }
@@ -0,0 +1,104 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { C64Emulator } from './c64-emulator';
3
+ import { C64WASM } from './c64-wasm';
4
+ const FRAME_BYTES = 384 * 272 * 4;
5
+ describe('C64Emulator', () => {
6
+ beforeEach(() => {
7
+ vi.restoreAllMocks();
8
+ });
9
+ function makeFakeWasm() {
10
+ const heapU8 = new Uint8Array(FRAME_BYTES + 64);
11
+ for (let i = 0; i < 16; i++) {
12
+ heapU8[i] = i + 1;
13
+ }
14
+ const heapF32 = new Float32Array(4096 + 32);
15
+ heapF32[0] = 0.25;
16
+ heapF32[1] = -0.5;
17
+ const exports = {
18
+ c64_init: vi.fn(),
19
+ c64_reset: vi.fn(),
20
+ debugger_update: vi.fn(() => 1),
21
+ c64_getPixelBuffer: vi.fn(() => 0),
22
+ sid_getAudioBuffer: vi.fn(() => 0),
23
+ sid_dumpBuffer: vi.fn(() => 2),
24
+ c64_loadPRG: vi.fn(),
25
+ c64_insertDisk: vi.fn(),
26
+ c64_loadCartridge: vi.fn(),
27
+ c64_loadSnapshot: vi.fn(),
28
+ c64_ramRead: vi.fn(() => 0xab),
29
+ c64_getSnapshotSize: vi.fn(() => 4),
30
+ malloc: vi.fn(() => 8),
31
+ c64_getSnapshot: vi.fn((ptr) => {
32
+ heapU8.set([9, 8, 7, 6], ptr);
33
+ }),
34
+ free: vi.fn(),
35
+ };
36
+ const wasm = {
37
+ exports,
38
+ heap: {
39
+ heapU8,
40
+ heapF32,
41
+ heapU32: new Uint32Array(heapU8.buffer),
42
+ },
43
+ allocAndWrite: vi.fn(() => 16),
44
+ free: vi.fn(),
45
+ };
46
+ return { wasm, exports, heapU8 };
47
+ }
48
+ it('loads and initializes through C64WASM.load', async () => {
49
+ const { wasm, exports } = makeFakeWasm();
50
+ vi.spyOn(C64WASM, 'load').mockResolvedValue(wasm);
51
+ const emulator = await C64Emulator.load('/custom.wasm');
52
+ expect(C64WASM.load).toHaveBeenCalledWith('/custom.wasm');
53
+ expect(exports.c64_init).toHaveBeenCalledOnce();
54
+ expect(emulator.ramRead(0)).toBe(0xab);
55
+ });
56
+ it('does not tick when paused', async () => {
57
+ const { wasm, exports } = makeFakeWasm();
58
+ vi.spyOn(C64WASM, 'load').mockResolvedValue(wasm);
59
+ const emulator = await C64Emulator.load();
60
+ emulator.tick(12);
61
+ expect(exports.debugger_update).not.toHaveBeenCalled();
62
+ expect(emulator.getFrameCount()).toBe(0);
63
+ });
64
+ it('emits frame callback while running', async () => {
65
+ const { wasm, exports } = makeFakeWasm();
66
+ vi.spyOn(C64WASM, 'load').mockResolvedValue(wasm);
67
+ const emulator = await C64Emulator.load();
68
+ const onFrame = vi.fn();
69
+ emulator.onFrame = onFrame;
70
+ emulator.start();
71
+ emulator.tick(10);
72
+ expect(exports.debugger_update).toHaveBeenCalledWith(10);
73
+ expect(emulator.getFrameCount()).toBe(1);
74
+ expect(onFrame).toHaveBeenCalledOnce();
75
+ expect(onFrame.mock.calls[0][0].width).toBe(384);
76
+ });
77
+ it('provides SID audio buffer via getSidBuffer', async () => {
78
+ const { wasm } = makeFakeWasm();
79
+ vi.spyOn(C64WASM, 'load').mockResolvedValue(wasm);
80
+ const emulator = await C64Emulator.load();
81
+ const buf = emulator.getSidBuffer();
82
+ expect(buf).toBeInstanceOf(Float32Array);
83
+ expect(buf.length).toBe(4096);
84
+ });
85
+ it('always frees allocated memory after loadGame', async () => {
86
+ const { wasm, exports } = makeFakeWasm();
87
+ exports.c64_loadPRG.mockImplementation(() => {
88
+ throw new Error('bad prg');
89
+ });
90
+ vi.spyOn(C64WASM, 'load').mockResolvedValue(wasm);
91
+ const emulator = await C64Emulator.load();
92
+ expect(() => emulator.loadGame({ type: 'prg', data: new Uint8Array([1, 2]) })).toThrow('bad prg');
93
+ expect(wasm.free).toHaveBeenCalledWith(16);
94
+ });
95
+ it('returns a copied framebuffer in getFrameBuffer', async () => {
96
+ const { wasm, heapU8 } = makeFakeWasm();
97
+ vi.spyOn(C64WASM, 'load').mockResolvedValue(wasm);
98
+ const emulator = await C64Emulator.load();
99
+ const frame = emulator.getFrameBuffer();
100
+ heapU8[0] = 250;
101
+ expect(frame.data[0]).toBe(1);
102
+ expect(frame.data.length).toBe(FRAME_BYTES);
103
+ });
104
+ });
@@ -0,0 +1,149 @@
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
+ export class C64WASM {
14
+ /** Raw WASM exports — available to C64Emulator */
15
+ exports = null;
16
+ /** Typed views into WASM linear memory */
17
+ heap = null;
18
+ wasmMemory = null;
19
+ // ---------------------------------------------------------------------------
20
+ // Bootstrap
21
+ // ---------------------------------------------------------------------------
22
+ /**
23
+ * Fetch, instantiate and initialise the WASM binary.
24
+ * C64Emulator calls this via the static C64Emulator.load() factory.
25
+ */
26
+ static async load(wasmUrl = '/src/emulator/c64.wasm') {
27
+ const response = await fetch(wasmUrl);
28
+ if (!response.ok)
29
+ throw new Error(`Failed to fetch ${wasmUrl}: ${response.status}`);
30
+ const binary = await response.arrayBuffer();
31
+ const instance = new C64WASM();
32
+ await instance.instantiate(binary);
33
+ return instance;
34
+ }
35
+ // Emscripten layout constants (must match the compiled binary)
36
+ static DYNAMICTOP_PTR = 5583504;
37
+ static DYNAMIC_BASE = 10826544;
38
+ static INITIAL_PAGES = 256; // 16 MB
39
+ async instantiate(wasmBinary, extraEnv) {
40
+ const mem = new WebAssembly.Memory({ initial: C64WASM.INITIAL_PAGES });
41
+ this.wasmMemory = mem;
42
+ const importObject = {
43
+ env: { ...this.makeEnvImports(mem), ...(extraEnv ?? {}) },
44
+ wasi_snapshot_preview1: this.makeWasiImports(mem),
45
+ };
46
+ try {
47
+ const result = await WebAssembly.instantiate(wasmBinary, importObject);
48
+ this.exports = result.instance.exports;
49
+ this.updateHeapViews();
50
+ // Initialise the sbrk heap pointer so malloc knows where free memory starts
51
+ new DataView(mem.buffer).setUint32(C64WASM.DYNAMICTOP_PTR, C64WASM.DYNAMIC_BASE, true);
52
+ this.exports.__wasm_call_ctors();
53
+ }
54
+ catch (err) {
55
+ throw new Error(`WASM instantiation failed: ${err}`, { cause: err });
56
+ }
57
+ }
58
+ // ---------------------------------------------------------------------------
59
+ // Memory
60
+ // ---------------------------------------------------------------------------
61
+ /** Allocate a buffer in WASM heap, write data, return pointer */
62
+ allocAndWrite(data) {
63
+ if (!this.exports || !this.heap)
64
+ throw new Error('WASM not ready');
65
+ const ptr = this.exports.malloc(data.length);
66
+ // malloc may have grown memory, so refresh views before writing
67
+ this.updateHeapViews();
68
+ this.heap.heapU8.set(data, ptr);
69
+ return ptr;
70
+ }
71
+ free(ptr) {
72
+ this.exports?.free(ptr);
73
+ }
74
+ /** Refresh heap views — must be called after any memory.grow() */
75
+ updateHeapViews() {
76
+ if (!this.wasmMemory)
77
+ throw new Error('WASM memory not initialized');
78
+ const buffer = this.wasmMemory.buffer;
79
+ this.heap = {
80
+ heapU8: new Uint8Array(buffer),
81
+ heapF32: new Float32Array(buffer),
82
+ heapU32: new Uint32Array(buffer),
83
+ };
84
+ }
85
+ // ---------------------------------------------------------------------------
86
+ // Emscripten env imports
87
+ // ---------------------------------------------------------------------------
88
+ makeEnvImports(mem) {
89
+ return {
90
+ memory: mem,
91
+ emscripten_get_sbrk_ptr: () => C64WASM.DYNAMICTOP_PTR,
92
+ emscripten_resize_heap: (requestedSize) => {
93
+ const PAGE_MULTIPLE = 65536;
94
+ const maxHeapSize = 2147483648 - PAGE_MULTIPLE;
95
+ if (requestedSize > maxHeapSize)
96
+ return 0;
97
+ const oldSize = mem.buffer.byteLength;
98
+ const minHeapSize = 16777216;
99
+ for (let cutDown = 1; cutDown <= 4; cutDown *= 2) {
100
+ let overGrown = oldSize * (1 + 0.2 / cutDown);
101
+ overGrown = Math.min(overGrown, requestedSize + 100663296);
102
+ const newSize = Math.min(maxHeapSize, Math.ceil(Math.max(minHeapSize, requestedSize, overGrown) / PAGE_MULTIPLE) *
103
+ PAGE_MULTIPLE);
104
+ try {
105
+ mem.grow((newSize - mem.buffer.byteLength + 65535) >>> 16);
106
+ this.updateHeapViews();
107
+ return 1;
108
+ }
109
+ catch {
110
+ // retry with less aggressive growth
111
+ }
112
+ }
113
+ return 0;
114
+ },
115
+ emscripten_memcpy_big: (dest, src, num) => {
116
+ new Uint8Array(mem.buffer).copyWithin(dest, src, src + num);
117
+ return dest;
118
+ },
119
+ setTempRet0: (_val) => { },
120
+ emscripten_asm_const_iii: (_code, _sig, _val) => 0,
121
+ table: new WebAssembly.Table({ initial: 512, maximum: 512, element: 'anyfunc' }),
122
+ };
123
+ }
124
+ // ---------------------------------------------------------------------------
125
+ // WASI imports (only fd_write is used by this binary)
126
+ // ---------------------------------------------------------------------------
127
+ makeWasiImports(mem) {
128
+ return {
129
+ fd_write: (fd, iovs, iovs_len, nwritten) => {
130
+ const view = new DataView(mem.buffer);
131
+ const u8 = new Uint8Array(mem.buffer);
132
+ let written = 0;
133
+ for (let i = 0; i < iovs_len; i++) {
134
+ const ptr = view.getUint32(iovs + i * 8, true);
135
+ const len = view.getUint32(iovs + i * 8 + 4, true);
136
+ // Only forward stderr (fd 2) to the console — stdout (fd 1) is
137
+ // extremely noisy (SID dumps buffer length every frame).
138
+ if (fd === 2) {
139
+ const text = new TextDecoder().decode(u8.subarray(ptr, ptr + len));
140
+ console.error(text);
141
+ }
142
+ written += len;
143
+ }
144
+ view.setUint32(nwritten, written, true);
145
+ return 0;
146
+ },
147
+ };
148
+ }
149
+ }
@@ -0,0 +1,65 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { C64WASM } from './c64-wasm';
3
+ describe('C64WASM', () => {
4
+ beforeEach(() => {
5
+ vi.restoreAllMocks();
6
+ });
7
+ it('throws when updateHeapViews is called before memory init', () => {
8
+ const wasm = new C64WASM();
9
+ expect(() => wasm.updateHeapViews()).toThrow('WASM memory not initialized');
10
+ });
11
+ it('instantiates wasm and calls ctors', async () => {
12
+ const ctors = vi.fn();
13
+ const instantiateSpy = vi.spyOn(WebAssembly, 'instantiate').mockResolvedValue({
14
+ instance: {
15
+ exports: {
16
+ __wasm_call_ctors: ctors,
17
+ },
18
+ },
19
+ module: {},
20
+ });
21
+ const wasm = new C64WASM();
22
+ await wasm.instantiate(new ArrayBuffer(8));
23
+ expect(instantiateSpy).toHaveBeenCalledOnce();
24
+ expect(wasm.exports).toBeTruthy();
25
+ expect(wasm.heap).toBeTruthy();
26
+ expect(ctors).toHaveBeenCalledOnce();
27
+ });
28
+ it('wraps instantiate failures with a clear error', async () => {
29
+ vi.spyOn(WebAssembly, 'instantiate').mockRejectedValue(new Error('boom'));
30
+ const wasm = new C64WASM();
31
+ await expect(wasm.instantiate(new ArrayBuffer(8))).rejects.toThrow('WASM instantiation failed');
32
+ });
33
+ it('allocates and writes bytes to heap', () => {
34
+ const mem = new WebAssembly.Memory({ initial: 1 });
35
+ const wasm = new C64WASM();
36
+ // Expose the private wasmMemory so updateHeapViews works
37
+ wasm.wasmMemory = mem;
38
+ wasm.exports = {
39
+ malloc: vi.fn(() => 4),
40
+ free: vi.fn(),
41
+ };
42
+ wasm.updateHeapViews();
43
+ const data = new Uint8Array([10, 20, 30]);
44
+ const ptr = wasm.allocAndWrite(data);
45
+ expect(ptr).toBe(4);
46
+ expect(Array.from(wasm.heap.heapU8.slice(4, 7))).toEqual([10, 20, 30]);
47
+ });
48
+ it('load fetches binary and delegates to instantiate', async () => {
49
+ const arrayBuffer = new ArrayBuffer(16);
50
+ const fetchMock = vi.fn().mockResolvedValue({
51
+ ok: true,
52
+ arrayBuffer: vi.fn().mockResolvedValue(arrayBuffer),
53
+ });
54
+ vi.stubGlobal('fetch', fetchMock);
55
+ const instantiateSpy = vi.spyOn(C64WASM.prototype, 'instantiate').mockResolvedValue();
56
+ const wasm = await C64WASM.load('/roms/c64.wasm');
57
+ expect(fetchMock).toHaveBeenCalledWith('/roms/c64.wasm');
58
+ expect(instantiateSpy).toHaveBeenCalledWith(arrayBuffer);
59
+ expect(wasm).toBeInstanceOf(C64WASM);
60
+ });
61
+ it('load throws when fetch is not ok', async () => {
62
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 404 }));
63
+ await expect(C64WASM.load('/missing.wasm')).rejects.toThrow('Failed to fetch /missing.wasm: 404');
64
+ });
65
+ });
@@ -0,0 +1,9 @@
1
+ export const JOYSTICK_PORT_1 = 1;
2
+ export const JOYSTICK_PORT_2 = 2;
3
+ export const JOYSTICK_DIRECTION = {
4
+ UP: 0x1,
5
+ DOWN: 0x2,
6
+ LEFT: 0x4,
7
+ RIGHT: 0x8,
8
+ };
9
+ export const JOYSTICK_FIRE_1 = 0x10;