src/gb/core.c (view raw)
1/* Copyright (c) 2013-2016 Jeffrey Pfau
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6#include <mgba/gb/core.h>
7
8#include <mgba/core/core.h>
9#include <mgba/internal/debugger/symbols.h>
10#include <mgba/internal/gb/cheats.h>
11#include <mgba/internal/gb/debugger/symbols.h>
12#include <mgba/internal/gb/extra/cli.h>
13#include <mgba/internal/gb/io.h>
14#include <mgba/internal/gb/gb.h>
15#include <mgba/internal/gb/mbc.h>
16#include <mgba/internal/gb/overrides.h>
17#include <mgba/internal/gb/renderers/software.h>
18#include <mgba/internal/gb/renderers/proxy.h>
19#include <mgba/internal/gb/serialize.h>
20#include <mgba/internal/lr35902/lr35902.h>
21#include <mgba/internal/lr35902/debugger/debugger.h>
22#include <mgba-util/crc32.h>
23#include <mgba-util/memory.h>
24#include <mgba-util/patch.h>
25#include <mgba-util/vfs.h>
26
27static const struct mCoreChannelInfo _GBVideoLayers[] = {
28 { 0, "bg", "Background", NULL },
29 { 1, "bgwin", "Window", NULL },
30 { 2, "obj", "Objects", NULL },
31};
32
33static const struct mCoreChannelInfo _GBAudioChannels[] = {
34 { 0, "ch1", "Channel 1", "Square/Sweep" },
35 { 1, "ch2", "Channel 2", "Square" },
36 { 2, "ch3", "Channel 3", "PCM" },
37 { 3, "ch4", "Channel 4", "Noise" },
38};
39
40static const struct LR35902Segment _GBSegments[] = {
41 { .name = "ROM", .start = GB_BASE_CART_BANK1, .end = GB_BASE_VRAM },
42 { .name = "RAM", .start = GB_BASE_EXTERNAL_RAM, .end = GB_BASE_WORKING_RAM_BANK0 },
43 { 0 }
44};
45
46static const struct LR35902Segment _GBCSegments[] = {
47 { .name = "ROM", .start = GB_BASE_CART_BANK1, .end = GB_BASE_VRAM },
48 { .name = "RAM", .start = GB_BASE_EXTERNAL_RAM, .end = GB_BASE_WORKING_RAM_BANK0 },
49 { .name = "WRAM", .start = GB_BASE_WORKING_RAM_BANK1, .end = 0xE000 },
50 { .name = "VRAM", .start = GB_BASE_VRAM, .end = GB_BASE_EXTERNAL_RAM },
51 { 0 }
52};
53
54static const struct mCoreMemoryBlock _GBMemoryBlocks[] = {
55 { -1, "mem", "All", "All", 0, 0x10000, 0x10000, mCORE_MEMORY_VIRTUAL },
56 { GB_REGION_CART_BANK0, "cart0", "ROM Bank", "Game Pak (32kiB)", GB_BASE_CART_BANK0, GB_SIZE_CART_BANK0 * 2, 0x800000, mCORE_MEMORY_READ | mCORE_MEMORY_MAPPED, 511 },
57 { GB_REGION_VRAM, "vram", "VRAM", "Video RAM (8kiB)", GB_BASE_VRAM, GB_BASE_VRAM + GB_SIZE_VRAM, GB_SIZE_VRAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
58 { GB_REGION_EXTERNAL_RAM, "sram", "SRAM", "External RAM (8kiB)", GB_BASE_EXTERNAL_RAM, GB_BASE_EXTERNAL_RAM + GB_SIZE_EXTERNAL_RAM, GB_SIZE_EXTERNAL_RAM * 4, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED, 3 },
59 { GB_REGION_WORKING_RAM_BANK0, "wram", "WRAM", "Working RAM (8kiB)", GB_BASE_WORKING_RAM_BANK0, GB_BASE_WORKING_RAM_BANK0 + GB_SIZE_WORKING_RAM_BANK0 * 2 , GB_SIZE_WORKING_RAM_BANK0 * 2, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
60 { GB_BASE_OAM, "oam", "OAM", "OBJ Attribute Memory", GB_BASE_OAM, GB_BASE_OAM + GB_SIZE_OAM, GB_SIZE_OAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
61 { GB_BASE_IO, "io", "MMIO", "Memory-Mapped I/O", GB_BASE_IO, GB_BASE_IO + GB_SIZE_IO, GB_SIZE_IO, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
62 { GB_BASE_HRAM, "hram", "HRAM", "High RAM", GB_BASE_HRAM, GB_BASE_HRAM + GB_SIZE_HRAM, GB_SIZE_HRAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
63};
64
65static const struct mCoreMemoryBlock _GBCMemoryBlocks[] = {
66 { -1, "mem", "All", "All", 0, 0x10000, 0x10000, mCORE_MEMORY_VIRTUAL },
67 { GB_REGION_CART_BANK0, "cart0", "ROM Bank", "Game Pak (32kiB)", GB_BASE_CART_BANK0, GB_SIZE_CART_BANK0 * 2, 0x800000, mCORE_MEMORY_READ | mCORE_MEMORY_MAPPED, 511 },
68 { GB_REGION_VRAM, "vram", "VRAM", "Video RAM (8kiB)", GB_BASE_VRAM, GB_BASE_VRAM + GB_SIZE_VRAM, GB_SIZE_VRAM * 2, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED, 1 },
69 { GB_REGION_EXTERNAL_RAM, "sram", "SRAM", "External RAM (8kiB)", GB_BASE_EXTERNAL_RAM, GB_BASE_EXTERNAL_RAM + GB_SIZE_EXTERNAL_RAM, GB_SIZE_EXTERNAL_RAM * 4, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED, 3 },
70 { GB_REGION_WORKING_RAM_BANK0, "wram", "WRAM", "Working RAM (8kiB)", GB_BASE_WORKING_RAM_BANK0, GB_BASE_WORKING_RAM_BANK0 + GB_SIZE_WORKING_RAM_BANK0 * 2, GB_SIZE_WORKING_RAM_BANK0 * 8, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED, 7 },
71 { GB_BASE_OAM, "oam", "OAM", "OBJ Attribute Memory", GB_BASE_OAM, GB_BASE_OAM + GB_SIZE_OAM, GB_SIZE_OAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
72 { GB_BASE_IO, "io", "MMIO", "Memory-Mapped I/O", GB_BASE_IO, GB_BASE_IO + GB_SIZE_IO, GB_SIZE_IO, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
73 { GB_BASE_HRAM, "hram", "HRAM", "High RAM", GB_BASE_HRAM, GB_BASE_HRAM + GB_SIZE_HRAM, GB_SIZE_HRAM, mCORE_MEMORY_RW | mCORE_MEMORY_MAPPED },
74};
75
76struct mVideoLogContext;
77struct GBCore {
78 struct mCore d;
79 struct GBVideoSoftwareRenderer renderer;
80 struct GBVideoProxyRenderer proxyRenderer;
81 struct mVideoLogContext* logContext;
82 struct mCoreCallbacks logCallbacks;
83 uint8_t keys;
84 struct mCPUComponent* components[CPU_COMPONENT_MAX];
85 const struct Configuration* overrides;
86 struct mDebuggerPlatform* debuggerPlatform;
87 struct mCheatDevice* cheatDevice;
88};
89
90static bool _GBCoreInit(struct mCore* core) {
91 struct GBCore* gbcore = (struct GBCore*) core;
92
93 struct LR35902Core* cpu = anonymousMemoryMap(sizeof(struct LR35902Core));
94 struct GB* gb = anonymousMemoryMap(sizeof(struct GB));
95 if (!cpu || !gb) {
96 free(cpu);
97 free(gb);
98 return false;
99 }
100 core->cpu = cpu;
101 core->board = gb;
102 gbcore->overrides = NULL;
103 gbcore->debuggerPlatform = NULL;
104 gbcore->cheatDevice = NULL;
105
106 GBCreate(gb);
107 memset(gbcore->components, 0, sizeof(gbcore->components));
108 LR35902SetComponents(cpu, &gb->d, CPU_COMPONENT_MAX, gbcore->components);
109 LR35902Init(cpu);
110 mRTCGenericSourceInit(&core->rtc, core);
111 gb->memory.rtc = &core->rtc.d;
112
113 GBVideoSoftwareRendererCreate(&gbcore->renderer);
114 gbcore->renderer.outputBuffer = NULL;
115
116 gbcore->keys = 0;
117 gb->keySource = &gbcore->keys;
118
119#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
120 mDirectorySetInit(&core->dirs);
121#endif
122
123 return true;
124}
125
126static void _GBCoreDeinit(struct mCore* core) {
127 LR35902Deinit(core->cpu);
128 GBDestroy(core->board);
129 mappedMemoryFree(core->cpu, sizeof(struct LR35902Core));
130 mappedMemoryFree(core->board, sizeof(struct GB));
131#if defined USE_DEBUGGERS && (!defined(MINIMAL_CORE) || MINIMAL_CORE < 2)
132 mDirectorySetDeinit(&core->dirs);
133 if (core->symbolTable) {
134 mDebuggerSymbolTableDestroy(core->symbolTable);
135 }
136#endif
137
138 struct GBCore* gbcore = (struct GBCore*) core;
139 free(gbcore->debuggerPlatform);
140 if (gbcore->cheatDevice) {
141 mCheatDeviceDestroy(gbcore->cheatDevice);
142 }
143 free(gbcore->cheatDevice);
144 mCoreConfigFreeOpts(&core->opts);
145 free(core);
146}
147
148static enum mPlatform _GBCorePlatform(const struct mCore* core) {
149 UNUSED(core);
150 return PLATFORM_GB;
151}
152
153static void _GBCoreSetSync(struct mCore* core, struct mCoreSync* sync) {
154 struct GB* gb = core->board;
155 gb->sync = sync;
156}
157
158static void _GBCoreLoadConfig(struct mCore* core, const struct mCoreConfig* config) {
159 UNUSED(config);
160
161 struct GB* gb = core->board;
162 if (core->opts.mute) {
163 gb->audio.masterVolume = 0;
164 } else {
165 gb->audio.masterVolume = core->opts.volume;
166 }
167 gb->video.frameskip = core->opts.frameskip;
168
169 int color;
170 if (mCoreConfigGetIntValue(config, "gb.pal[0]", &color)) {
171 GBVideoSetPalette(&gb->video, 0, color);
172 }
173 if (mCoreConfigGetIntValue(config, "gb.pal[1]", &color)) {
174 GBVideoSetPalette(&gb->video, 1, color);
175 }
176 if (mCoreConfigGetIntValue(config, "gb.pal[2]", &color)) {
177 GBVideoSetPalette(&gb->video, 2, color);
178 }
179 if (mCoreConfigGetIntValue(config, "gb.pal[3]", &color)) {
180 GBVideoSetPalette(&gb->video, 3, color);
181 }
182 if (mCoreConfigGetIntValue(config, "gb.pal[4]", &color)) {
183 GBVideoSetPalette(&gb->video, 4, color);
184 }
185 if (mCoreConfigGetIntValue(config, "gb.pal[5]", &color)) {
186 GBVideoSetPalette(&gb->video, 5, color);
187 }
188 if (mCoreConfigGetIntValue(config, "gb.pal[6]", &color)) {
189 GBVideoSetPalette(&gb->video, 6, color);
190 }
191 if (mCoreConfigGetIntValue(config, "gb.pal[7]", &color)) {
192 GBVideoSetPalette(&gb->video, 7, color);
193 }
194 if (mCoreConfigGetIntValue(config, "gb.pal[8]", &color)) {
195 GBVideoSetPalette(&gb->video, 8, color);
196 }
197 if (mCoreConfigGetIntValue(config, "gb.pal[9]", &color)) {
198 GBVideoSetPalette(&gb->video, 9, color);
199 }
200 if (mCoreConfigGetIntValue(config, "gb.pal[10]", &color)) {
201 GBVideoSetPalette(&gb->video, 10, color);
202 }
203 if (mCoreConfigGetIntValue(config, "gb.pal[11]", &color)) {
204 GBVideoSetPalette(&gb->video, 11, color);
205 }
206
207 mCoreConfigCopyValue(&core->config, config, "gb.bios");
208 mCoreConfigCopyValue(&core->config, config, "sgb.bios");
209 mCoreConfigCopyValue(&core->config, config, "gbc.bios");
210 mCoreConfigCopyValue(&core->config, config, "gb.model");
211 mCoreConfigCopyValue(&core->config, config, "sgb.model");
212 mCoreConfigCopyValue(&core->config, config, "cgb.model");
213 mCoreConfigCopyValue(&core->config, config, "sgb.borders");
214
215#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
216 struct GBCore* gbcore = (struct GBCore*) core;
217 gbcore->overrides = mCoreConfigGetOverridesConst(config);
218#endif
219}
220
221static void _GBCoreDesiredVideoDimensions(struct mCore* core, unsigned* width, unsigned* height) {
222 struct GB* gb = core->board;
223 if (gb && (gb->model != GB_MODEL_SGB || !gb->video.sgbBorders)) {
224 *width = GB_VIDEO_HORIZONTAL_PIXELS;
225 *height = GB_VIDEO_VERTICAL_PIXELS;
226 } else {
227 *width = 256;
228 *height = 224;
229 }
230}
231
232static void _GBCoreSetVideoBuffer(struct mCore* core, color_t* buffer, size_t stride) {
233 struct GBCore* gbcore = (struct GBCore*) core;
234 gbcore->renderer.outputBuffer = buffer;
235 gbcore->renderer.outputBufferStride = stride;
236}
237
238static void _GBCoreGetPixels(struct mCore* core, const void** buffer, size_t* stride) {
239 struct GBCore* gbcore = (struct GBCore*) core;
240 gbcore->renderer.d.getPixels(&gbcore->renderer.d, stride, buffer);
241}
242
243static void _GBCorePutPixels(struct mCore* core, const void* buffer, size_t stride) {
244 struct GBCore* gbcore = (struct GBCore*) core;
245 gbcore->renderer.d.putPixels(&gbcore->renderer.d, stride, buffer);
246}
247
248static struct blip_t* _GBCoreGetAudioChannel(struct mCore* core, int ch) {
249 struct GB* gb = core->board;
250 switch (ch) {
251 case 0:
252 return gb->audio.left;
253 case 1:
254 return gb->audio.right;
255 default:
256 return NULL;
257 }
258}
259
260static void _GBCoreSetAudioBufferSize(struct mCore* core, size_t samples) {
261 struct GB* gb = core->board;
262 GBAudioResizeBuffer(&gb->audio, samples);
263}
264
265static size_t _GBCoreGetAudioBufferSize(struct mCore* core) {
266 struct GB* gb = core->board;
267 return gb->audio.samples;
268}
269
270static void _GBCoreAddCoreCallbacks(struct mCore* core, struct mCoreCallbacks* coreCallbacks) {
271 struct GB* gb = core->board;
272 *mCoreCallbacksListAppend(&gb->coreCallbacks) = *coreCallbacks;
273}
274
275static void _GBCoreClearCoreCallbacks(struct mCore* core) {
276 struct GB* gb = core->board;
277 mCoreCallbacksListClear(&gb->coreCallbacks);
278}
279
280static void _GBCoreSetAVStream(struct mCore* core, struct mAVStream* stream) {
281 struct GB* gb = core->board;
282 gb->stream = stream;
283 if (stream && stream->videoDimensionsChanged) {
284 stream->videoDimensionsChanged(stream, GB_VIDEO_HORIZONTAL_PIXELS, GB_VIDEO_VERTICAL_PIXELS);
285 }
286}
287
288static bool _GBCoreLoadROM(struct mCore* core, struct VFile* vf) {
289 return GBLoadROM(core->board, vf);
290}
291
292static bool _GBCoreLoadBIOS(struct mCore* core, struct VFile* vf, int type) {
293 UNUSED(type);
294 GBLoadBIOS(core->board, vf);
295 return true;
296}
297
298static bool _GBCoreLoadSave(struct mCore* core, struct VFile* vf) {
299 return GBLoadSave(core->board, vf);
300}
301
302static bool _GBCoreLoadTemporarySave(struct mCore* core, struct VFile* vf) {
303 struct GB* gb = core->board;
304 GBSavedataMask(gb, vf, false);
305 return true; // TODO: Return a real value
306}
307
308static bool _GBCoreLoadPatch(struct mCore* core, struct VFile* vf) {
309 if (!vf) {
310 return false;
311 }
312 struct Patch patch;
313 if (!loadPatch(vf, &patch)) {
314 return false;
315 }
316 GBApplyPatch(core->board, &patch);
317 return true;
318}
319
320static void _GBCoreUnloadROM(struct mCore* core) {
321 struct GBCore* gbcore = (struct GBCore*) core;
322 struct LR35902Core* cpu = core->cpu;
323 if (gbcore->cheatDevice) {
324 LR35902HotplugDetach(cpu, CPU_COMPONENT_CHEAT_DEVICE);
325 cpu->components[CPU_COMPONENT_CHEAT_DEVICE] = NULL;
326 mCheatDeviceDestroy(gbcore->cheatDevice);
327 gbcore->cheatDevice = NULL;
328 }
329 return GBUnloadROM(core->board);
330}
331
332static void _GBCoreChecksum(const struct mCore* core, void* data, enum mCoreChecksumType type) {
333 struct GB* gb = (struct GB*) core->board;
334 switch (type) {
335 case CHECKSUM_CRC32:
336 memcpy(data, &gb->romCrc32, sizeof(gb->romCrc32));
337 break;
338 }
339 return;
340}
341
342static void _GBCoreReset(struct mCore* core) {
343 struct GBCore* gbcore = (struct GBCore*) core;
344 struct GB* gb = (struct GB*) core->board;
345 if (gbcore->renderer.outputBuffer) {
346 GBVideoAssociateRenderer(&gb->video, &gbcore->renderer.d);
347 }
348
349 if (gb->memory.rom) {
350 struct GBCartridgeOverride override;
351 const struct GBCartridge* cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
352 override.headerCrc32 = doCrc32(cart, sizeof(*cart));
353 if (GBOverrideFind(gbcore->overrides, &override)) {
354 GBOverrideApply(gb, &override);
355 }
356 }
357
358 const char* modelGB = mCoreConfigGetValue(&core->config, "gb.model");
359 const char* modelCGB = mCoreConfigGetValue(&core->config, "cgb.model");
360 const char* modelSGB = mCoreConfigGetValue(&core->config, "sgb.model");
361 if (modelGB || modelCGB || modelSGB) {
362 GBDetectModel(gb);
363 if (gb->model == GB_MODEL_DMG && modelGB) {
364 gb->model = GBNameToModel(modelGB);
365 } else if (gb->model == GB_MODEL_CGB && modelCGB) {
366 gb->model = GBNameToModel(modelCGB);
367 } else if (gb->model == GB_MODEL_SGB && modelSGB) {
368 gb->model = GBNameToModel(modelSGB);
369 }
370 }
371
372 int fakeBool;
373 if (mCoreConfigGetIntValue(&core->config, "sgb.borders", &fakeBool)) {
374 gb->video.sgbBorders = fakeBool;
375 }
376
377#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
378 if (!gb->biosVf && core->opts.useBios) {
379 struct VFile* bios = NULL;
380 bool found = false;
381 if (core->opts.bios) {
382 bios = VFileOpen(core->opts.bios, O_RDONLY);
383 if (bios && GBIsBIOS(bios)) {
384 found = true;
385 } else if (bios) {
386 bios->close(bios);
387 bios = NULL;
388 }
389 }
390 if (!found) {
391 GBDetectModel(gb);
392 const char* configPath = NULL;
393
394 switch (gb->model) {
395 case GB_MODEL_DMG:
396 case GB_MODEL_MGB: // TODO
397 configPath = mCoreConfigGetValue(&core->config, "gb.bios");
398 break;
399 case GB_MODEL_SGB:
400 case GB_MODEL_SGB2: // TODO
401 configPath = mCoreConfigGetValue(&core->config, "sgb.bios");
402 break;
403 case GB_MODEL_CGB:
404 case GB_MODEL_AGB:
405 configPath = mCoreConfigGetValue(&core->config, "gbc.bios");
406 break;
407 default:
408 break;
409 };
410 if (configPath) {
411 bios = VFileOpen(configPath, O_RDONLY);
412 }
413 if (bios && GBIsBIOS(bios)) {
414 found = true;
415 } else if (bios) {
416 bios->close(bios);
417 bios = NULL;
418 }
419 }
420 if (!found) {
421 char path[PATH_MAX];
422 mCoreConfigDirectory(path, PATH_MAX);
423 switch (gb->model) {
424 case GB_MODEL_DMG:
425 case GB_MODEL_MGB: // TODO
426 strncat(path, PATH_SEP "gb_bios.bin", PATH_MAX - strlen(path));
427 break;
428 case GB_MODEL_SGB:
429 case GB_MODEL_SGB2: // TODO
430 strncat(path, PATH_SEP "sgb_bios.bin", PATH_MAX - strlen(path));
431 break;
432 case GB_MODEL_CGB:
433 case GB_MODEL_AGB:
434 strncat(path, PATH_SEP "gbc_bios.bin", PATH_MAX - strlen(path));
435 break;
436 default:
437 break;
438 };
439 bios = VFileOpen(path, O_RDONLY);
440 if (bios && GBIsBIOS(bios)) {
441 found = true;
442 } else if (bios) {
443 bios->close(bios);
444 bios = NULL;
445 }
446 }
447 if (bios) {
448 GBLoadBIOS(gb, bios);
449 }
450 }
451#endif
452
453 LR35902Reset(core->cpu);
454}
455
456static void _GBCoreRunFrame(struct mCore* core) {
457 struct GB* gb = core->board;
458 int32_t frameCounter = gb->video.frameCounter;
459 while (gb->video.frameCounter == frameCounter) {
460 LR35902Run(core->cpu);
461 }
462}
463
464static void _GBCoreRunLoop(struct mCore* core) {
465 LR35902Run(core->cpu);
466}
467
468static void _GBCoreStep(struct mCore* core) {
469 struct LR35902Core* cpu = core->cpu;
470 do {
471 LR35902Tick(cpu);
472 } while (cpu->executionState != LR35902_CORE_FETCH);
473}
474
475static size_t _GBCoreStateSize(struct mCore* core) {
476 UNUSED(core);
477 return sizeof(struct GBSerializedState);
478}
479
480static bool _GBCoreLoadState(struct mCore* core, const void* state) {
481 return GBDeserialize(core->board, state);
482}
483
484static bool _GBCoreSaveState(struct mCore* core, void* state) {
485 struct LR35902Core* cpu = core->cpu;
486 while (cpu->executionState != LR35902_CORE_FETCH) {
487 LR35902Tick(cpu);
488 }
489 GBSerialize(core->board, state);
490 return true;
491}
492
493static void _GBCoreSetKeys(struct mCore* core, uint32_t keys) {
494 struct GBCore* gbcore = (struct GBCore*) core;
495 gbcore->keys = keys;
496 GBTestKeypadIRQ(core->board);
497}
498
499static void _GBCoreAddKeys(struct mCore* core, uint32_t keys) {
500 struct GBCore* gbcore = (struct GBCore*) core;
501 gbcore->keys |= keys;
502 GBTestKeypadIRQ(core->board);
503}
504
505static void _GBCoreClearKeys(struct mCore* core, uint32_t keys) {
506 struct GBCore* gbcore = (struct GBCore*) core;
507 gbcore->keys &= ~keys;
508}
509
510static int32_t _GBCoreFrameCounter(const struct mCore* core) {
511 const struct GB* gb = core->board;
512 return gb->video.frameCounter;
513}
514
515static int32_t _GBCoreFrameCycles(const struct mCore* core) {
516 UNUSED(core);
517 return GB_VIDEO_TOTAL_LENGTH;
518}
519
520static int32_t _GBCoreFrequency(const struct mCore* core) {
521 UNUSED(core);
522 // TODO: GB differences
523 return DMG_LR35902_FREQUENCY;
524}
525
526static void _GBCoreGetGameTitle(const struct mCore* core, char* title) {
527 GBGetGameTitle(core->board, title);
528}
529
530static void _GBCoreGetGameCode(const struct mCore* core, char* title) {
531 GBGetGameCode(core->board, title);
532}
533
534static void _GBCoreSetPeripheral(struct mCore* core, int type, void* periph) {
535 struct GB* gb = core->board;
536 switch (type) {
537 case mPERIPH_ROTATION:
538 gb->memory.rotation = periph;
539 break;
540 case mPERIPH_RUMBLE:
541 gb->memory.rumble = periph;
542 break;
543 case mPERIPH_IMAGE_SOURCE:
544 gb->memory.cam = periph;
545 break;
546 default:
547 return;
548 }
549}
550
551static uint32_t _GBCoreBusRead8(struct mCore* core, uint32_t address) {
552 struct LR35902Core* cpu = core->cpu;
553 return cpu->memory.load8(cpu, address);
554}
555
556static uint32_t _GBCoreBusRead16(struct mCore* core, uint32_t address) {
557 struct LR35902Core* cpu = core->cpu;
558 return cpu->memory.load8(cpu, address) | (cpu->memory.load8(cpu, address + 1) << 8);
559}
560
561static uint32_t _GBCoreBusRead32(struct mCore* core, uint32_t address) {
562 struct LR35902Core* cpu = core->cpu;
563 return cpu->memory.load8(cpu, address) | (cpu->memory.load8(cpu, address + 1) << 8) |
564 (cpu->memory.load8(cpu, address + 2) << 16) | (cpu->memory.load8(cpu, address + 3) << 24);
565}
566
567static void _GBCoreBusWrite8(struct mCore* core, uint32_t address, uint8_t value) {
568 struct LR35902Core* cpu = core->cpu;
569 cpu->memory.store8(cpu, address, value);
570}
571
572static void _GBCoreBusWrite16(struct mCore* core, uint32_t address, uint16_t value) {
573 struct LR35902Core* cpu = core->cpu;
574 cpu->memory.store8(cpu, address, value);
575 cpu->memory.store8(cpu, address + 1, value >> 8);
576}
577
578static void _GBCoreBusWrite32(struct mCore* core, uint32_t address, uint32_t value) {
579 struct LR35902Core* cpu = core->cpu;
580 cpu->memory.store8(cpu, address, value);
581 cpu->memory.store8(cpu, address + 1, value >> 8);
582 cpu->memory.store8(cpu, address + 2, value >> 16);
583 cpu->memory.store8(cpu, address + 3, value >> 24);
584}
585
586static uint32_t _GBCoreRawRead8(struct mCore* core, uint32_t address, int segment) {
587 struct LR35902Core* cpu = core->cpu;
588 return GBView8(cpu, address, segment);
589}
590
591static uint32_t _GBCoreRawRead16(struct mCore* core, uint32_t address, int segment) {
592 struct LR35902Core* cpu = core->cpu;
593 return GBView8(cpu, address, segment) | (GBView8(cpu, address + 1, segment) << 8);
594}
595
596static uint32_t _GBCoreRawRead32(struct mCore* core, uint32_t address, int segment) {
597 struct LR35902Core* cpu = core->cpu;
598 return GBView8(cpu, address, segment) | (GBView8(cpu, address + 1, segment) << 8) |
599 (GBView8(cpu, address + 2, segment) << 16) | (GBView8(cpu, address + 3, segment) << 24);
600}
601
602static void _GBCoreRawWrite8(struct mCore* core, uint32_t address, int segment, uint8_t value) {
603 struct LR35902Core* cpu = core->cpu;
604 GBPatch8(cpu, address, value, NULL, segment);
605}
606
607static void _GBCoreRawWrite16(struct mCore* core, uint32_t address, int segment, uint16_t value) {
608 struct LR35902Core* cpu = core->cpu;
609 GBPatch8(cpu, address, value, NULL, segment);
610 GBPatch8(cpu, address + 1, value >> 8, NULL, segment);
611}
612
613static void _GBCoreRawWrite32(struct mCore* core, uint32_t address, int segment, uint32_t value) {
614 struct LR35902Core* cpu = core->cpu;
615 GBPatch8(cpu, address, value, NULL, segment);
616 GBPatch8(cpu, address + 1, value >> 8, NULL, segment);
617 GBPatch8(cpu, address + 2, value >> 16, NULL, segment);
618 GBPatch8(cpu, address + 3, value >> 24, NULL, segment);
619}
620
621size_t _GBListMemoryBlocks(const struct mCore* core, const struct mCoreMemoryBlock** blocks) {
622 const struct GB* gb = core->board;
623 switch (gb->model) {
624 case GB_MODEL_DMG:
625 case GB_MODEL_MGB:
626 case GB_MODEL_SGB:
627 case GB_MODEL_SGB2:
628 default:
629 *blocks = _GBMemoryBlocks;
630 return sizeof(_GBMemoryBlocks) / sizeof(*_GBMemoryBlocks);
631 case GB_MODEL_CGB:
632 case GB_MODEL_AGB:
633 *blocks = _GBCMemoryBlocks;
634 return sizeof(_GBCMemoryBlocks) / sizeof(*_GBCMemoryBlocks);
635 }
636}
637
638void* _GBGetMemoryBlock(struct mCore* core, size_t id, size_t* sizeOut) {
639 struct GB* gb = core->board;
640 bool isCgb = gb->model >= GB_MODEL_CGB;
641 switch (id) {
642 default:
643 return NULL;
644 case GB_REGION_CART_BANK0:
645 *sizeOut = gb->memory.romSize;
646 return gb->memory.rom;
647 case GB_REGION_VRAM:
648 *sizeOut = GB_SIZE_WORKING_RAM_BANK0 * (isCgb ? 1 : 2);
649 return gb->video.vram;
650 case GB_REGION_EXTERNAL_RAM:
651 *sizeOut = gb->sramSize;
652 return gb->memory.sram;
653 case GB_REGION_WORKING_RAM_BANK0:
654 *sizeOut = GB_SIZE_VRAM * (isCgb ? 8 : 2);
655 return gb->memory.wram;
656 case GB_BASE_OAM:
657 *sizeOut = GB_SIZE_OAM;
658 return gb->video.oam.raw;
659 case GB_BASE_HRAM:
660 *sizeOut = GB_SIZE_HRAM;
661 return gb->memory.hram;
662 }
663}
664
665#ifdef USE_DEBUGGERS
666static bool _GBCoreSupportsDebuggerType(struct mCore* core, enum mDebuggerType type) {
667 UNUSED(core);
668 switch (type) {
669 case DEBUGGER_CLI:
670 return true;
671 default:
672 return false;
673 }
674}
675
676static struct mDebuggerPlatform* _GBCoreDebuggerPlatform(struct mCore* core) {
677 struct GBCore* gbcore = (struct GBCore*) core;
678 struct GB* gb = core->board;
679 if (!gbcore->debuggerPlatform) {
680 struct LR35902Debugger* platform = (struct LR35902Debugger*) LR35902DebuggerPlatformCreate();
681 if (gb->model >= GB_MODEL_CGB) {
682 platform->segments = _GBCSegments;
683 } else {
684 platform->segments = _GBSegments;
685 }
686 gbcore->debuggerPlatform = &platform->d;
687 }
688 return gbcore->debuggerPlatform;
689}
690
691static struct CLIDebuggerSystem* _GBCoreCliDebuggerSystem(struct mCore* core) {
692 return GBCLIDebuggerCreate(core);
693}
694
695static void _GBCoreAttachDebugger(struct mCore* core, struct mDebugger* debugger) {
696 struct LR35902Core* cpu = core->cpu;
697 if (core->debugger) {
698 LR35902HotplugDetach(cpu, CPU_COMPONENT_DEBUGGER);
699 }
700 cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
701 LR35902HotplugAttach(cpu, CPU_COMPONENT_DEBUGGER);
702 core->debugger = debugger;
703}
704
705static void _GBCoreDetachDebugger(struct mCore* core) {
706 struct LR35902Core* cpu = core->cpu;
707 if (core->debugger) {
708 LR35902HotplugDetach(cpu, CPU_COMPONENT_DEBUGGER);
709 }
710 cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
711 core->debugger = NULL;
712}
713
714static void _GBCoreLoadSymbols(struct mCore* core, struct VFile* vf) {
715 core->symbolTable = mDebuggerSymbolTableCreate();
716#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
717 if (!vf) {
718 vf = mDirectorySetOpenSuffix(&core->dirs, core->dirs.base, ".sym", O_RDONLY);
719 }
720#endif
721 if (!vf) {
722 return;
723 }
724 GBLoadSymbols(core->symbolTable, vf);
725}
726#endif
727
728static struct mCheatDevice* _GBCoreCheatDevice(struct mCore* core) {
729 struct GBCore* gbcore = (struct GBCore*) core;
730 if (!gbcore->cheatDevice) {
731 gbcore->cheatDevice = GBCheatDeviceCreate();
732 ((struct LR35902Core*) core->cpu)->components[CPU_COMPONENT_CHEAT_DEVICE] = &gbcore->cheatDevice->d;
733 LR35902HotplugAttach(core->cpu, CPU_COMPONENT_CHEAT_DEVICE);
734 gbcore->cheatDevice->p = core;
735 }
736 return gbcore->cheatDevice;
737}
738
739static size_t _GBCoreSavedataClone(struct mCore* core, void** sram) {
740 struct GB* gb = core->board;
741 struct VFile* vf = gb->sramVf;
742 if (vf) {
743 *sram = malloc(vf->size(vf));
744 vf->seek(vf, 0, SEEK_SET);
745 return vf->read(vf, *sram, vf->size(vf));
746 }
747 *sram = malloc(gb->sramSize);
748 memcpy(*sram, gb->memory.sram, gb->sramSize);
749 return gb->sramSize;
750}
751
752static bool _GBCoreSavedataRestore(struct mCore* core, const void* sram, size_t size, bool writeback) {
753 struct GB* gb = core->board;
754 if (!writeback) {
755 struct VFile* vf = VFileMemChunk(sram, size);
756 GBSavedataMask(gb, vf, true);
757 return true;
758 }
759 struct VFile* vf = gb->sramVf;
760 if (vf) {
761 vf->seek(vf, 0, SEEK_SET);
762 return vf->write(vf, sram, size) > 0;
763 }
764 if (size > 0x20000) {
765 size = 0x20000;
766 }
767 GBResizeSram(gb, size);
768 memcpy(gb->memory.sram, sram, size);
769 return true;
770}
771
772static size_t _GBCoreListVideoLayers(const struct mCore* core, const struct mCoreChannelInfo** info) {
773 UNUSED(core);
774 *info = _GBVideoLayers;
775 return sizeof(_GBVideoLayers) / sizeof(*_GBVideoLayers);
776}
777
778static size_t _GBCoreListAudioChannels(const struct mCore* core, const struct mCoreChannelInfo** info) {
779 UNUSED(core);
780 *info = _GBAudioChannels;
781 return sizeof(_GBAudioChannels) / sizeof(*_GBAudioChannels);
782}
783
784static void _GBCoreEnableVideoLayer(struct mCore* core, size_t id, bool enable) {
785 struct GB* gb = core->board;
786 switch (id) {
787 case 0:
788 gb->video.renderer->disableBG = !enable;
789 break;
790 case 1:
791 gb->video.renderer->disableOBJ = !enable;
792 break;
793 case 2:
794 gb->video.renderer->disableWIN = !enable;
795 break;
796 default:
797 break;
798 }
799}
800
801static void _GBCoreEnableAudioChannel(struct mCore* core, size_t id, bool enable) {
802 struct GB* gb = core->board;
803 switch (id) {
804 case 0:
805 case 1:
806 case 2:
807 case 3:
808 gb->audio.forceDisableCh[id] = !enable;
809 break;
810 default:
811 break;
812 }
813}
814
815static void _GBCoreStartVideoLog(struct mCore* core, struct mVideoLogContext* context) {
816 struct GBCore* gbcore = (struct GBCore*) core;
817 struct GB* gb = core->board;
818 gbcore->logContext = context;
819
820 int channelId = mVideoLoggerAddChannel(context);
821 gbcore->proxyRenderer.logger = malloc(sizeof(struct mVideoLogger));
822 mVideoLoggerRendererCreate(gbcore->proxyRenderer.logger, false);
823 mVideoLoggerAttachChannel(gbcore->proxyRenderer.logger, context, channelId);
824 gbcore->proxyRenderer.logger->block = false;
825
826 GBVideoProxyRendererCreate(&gbcore->proxyRenderer, &gbcore->renderer.d);
827 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
828}
829
830static void _GBCoreEndVideoLog(struct mCore* core) {
831 struct GBCore* gbcore = (struct GBCore*) core;
832 struct GB* gb = core->board;
833 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
834 free(gbcore->proxyRenderer.logger);
835 gbcore->proxyRenderer.logger = NULL;
836}
837
838struct mCore* GBCoreCreate(void) {
839 struct GBCore* gbcore = malloc(sizeof(*gbcore));
840 struct mCore* core = &gbcore->d;
841 memset(&core->opts, 0, sizeof(core->opts));
842 core->cpu = NULL;
843 core->board = NULL;
844 core->debugger = NULL;
845 core->symbolTable = NULL;
846 core->init = _GBCoreInit;
847 core->deinit = _GBCoreDeinit;
848 core->platform = _GBCorePlatform;
849 core->setSync = _GBCoreSetSync;
850 core->loadConfig = _GBCoreLoadConfig;
851 core->desiredVideoDimensions = _GBCoreDesiredVideoDimensions;
852 core->setVideoBuffer = _GBCoreSetVideoBuffer;
853 core->getPixels = _GBCoreGetPixels;
854 core->putPixels = _GBCorePutPixels;
855 core->getAudioChannel = _GBCoreGetAudioChannel;
856 core->setAudioBufferSize = _GBCoreSetAudioBufferSize;
857 core->getAudioBufferSize = _GBCoreGetAudioBufferSize;
858 core->setAVStream = _GBCoreSetAVStream;
859 core->addCoreCallbacks = _GBCoreAddCoreCallbacks;
860 core->clearCoreCallbacks = _GBCoreClearCoreCallbacks;
861 core->isROM = GBIsROM;
862 core->loadROM = _GBCoreLoadROM;
863 core->loadBIOS = _GBCoreLoadBIOS;
864 core->loadSave = _GBCoreLoadSave;
865 core->loadTemporarySave = _GBCoreLoadTemporarySave;
866 core->loadPatch = _GBCoreLoadPatch;
867 core->unloadROM = _GBCoreUnloadROM;
868 core->checksum = _GBCoreChecksum;
869 core->reset = _GBCoreReset;
870 core->runFrame = _GBCoreRunFrame;
871 core->runLoop = _GBCoreRunLoop;
872 core->step = _GBCoreStep;
873 core->stateSize = _GBCoreStateSize;
874 core->loadState = _GBCoreLoadState;
875 core->saveState = _GBCoreSaveState;
876 core->setKeys = _GBCoreSetKeys;
877 core->addKeys = _GBCoreAddKeys;
878 core->clearKeys = _GBCoreClearKeys;
879 core->frameCounter = _GBCoreFrameCounter;
880 core->frameCycles = _GBCoreFrameCycles;
881 core->frequency = _GBCoreFrequency;
882 core->getGameTitle = _GBCoreGetGameTitle;
883 core->getGameCode = _GBCoreGetGameCode;
884 core->setPeripheral = _GBCoreSetPeripheral;
885 core->busRead8 = _GBCoreBusRead8;
886 core->busRead16 = _GBCoreBusRead16;
887 core->busRead32 = _GBCoreBusRead32;
888 core->busWrite8 = _GBCoreBusWrite8;
889 core->busWrite16 = _GBCoreBusWrite16;
890 core->busWrite32 = _GBCoreBusWrite32;
891 core->rawRead8 = _GBCoreRawRead8;
892 core->rawRead16 = _GBCoreRawRead16;
893 core->rawRead32 = _GBCoreRawRead32;
894 core->rawWrite8 = _GBCoreRawWrite8;
895 core->rawWrite16 = _GBCoreRawWrite16;
896 core->rawWrite32 = _GBCoreRawWrite32;
897 core->listMemoryBlocks = _GBListMemoryBlocks;
898 core->getMemoryBlock = _GBGetMemoryBlock;
899#ifdef USE_DEBUGGERS
900 core->supportsDebuggerType = _GBCoreSupportsDebuggerType;
901 core->debuggerPlatform = _GBCoreDebuggerPlatform;
902 core->cliDebuggerSystem = _GBCoreCliDebuggerSystem;
903 core->attachDebugger = _GBCoreAttachDebugger;
904 core->detachDebugger = _GBCoreDetachDebugger;
905 core->loadSymbols = _GBCoreLoadSymbols;
906#endif
907 core->cheatDevice = _GBCoreCheatDevice;
908 core->savedataClone = _GBCoreSavedataClone;
909 core->savedataRestore = _GBCoreSavedataRestore;
910 core->listVideoLayers = _GBCoreListVideoLayers;
911 core->listAudioChannels = _GBCoreListAudioChannels;
912 core->enableVideoLayer = _GBCoreEnableVideoLayer;
913 core->enableAudioChannel = _GBCoreEnableAudioChannel;
914#ifndef MINIMAL_CORE
915 core->startVideoLog = _GBCoreStartVideoLog;
916 core->endVideoLog = _GBCoreEndVideoLog;
917#endif
918 return core;
919}
920
921#ifndef MINIMAL_CORE
922static void _GBVLPStartFrameCallback(void *context) {
923 struct mCore* core = context;
924 struct GBCore* gbcore = (struct GBCore*) core;
925 struct GB* gb = core->board;
926
927 if (!mVideoLoggerRendererRun(gbcore->proxyRenderer.logger, true)) {
928 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
929 mVideoLogContextRewind(gbcore->logContext, core);
930 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
931 }
932}
933
934static bool _GBVLPInit(struct mCore* core) {
935 struct GBCore* gbcore = (struct GBCore*) core;
936 if (!_GBCoreInit(core)) {
937 return false;
938 }
939 gbcore->proxyRenderer.logger = malloc(sizeof(struct mVideoLogger));
940 mVideoLoggerRendererCreate(gbcore->proxyRenderer.logger, true);
941 GBVideoProxyRendererCreate(&gbcore->proxyRenderer, NULL);
942 memset(&gbcore->logCallbacks, 0, sizeof(gbcore->logCallbacks));
943 gbcore->logCallbacks.videoFrameStarted = _GBVLPStartFrameCallback;
944 gbcore->logCallbacks.context = core;
945 core->addCoreCallbacks(core, &gbcore->logCallbacks);
946 return true;
947}
948
949static void _GBVLPDeinit(struct mCore* core) {
950 struct GBCore* gbcore = (struct GBCore*) core;
951 if (gbcore->logContext) {
952 mVideoLogContextDestroy(core, gbcore->logContext);
953 }
954 _GBCoreDeinit(core);
955}
956
957static void _GBVLPReset(struct mCore* core) {
958 struct GBCore* gbcore = (struct GBCore*) core;
959 struct GB* gb = (struct GB*) core->board;
960 if (gb->video.renderer == &gbcore->proxyRenderer.d) {
961 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
962 } else if (gbcore->renderer.outputBuffer) {
963 struct GBVideoRenderer* renderer = &gbcore->renderer.d;
964 GBVideoAssociateRenderer(&gb->video, renderer);
965 }
966
967 LR35902Reset(core->cpu);
968 mVideoLogContextRewind(gbcore->logContext, core);
969 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
970
971 // Make sure CPU loop never spins
972 GBHalt(gb->cpu);
973 gb->memory.ie = 0;
974 gb->memory.ime = false;
975}
976
977static bool _GBVLPLoadROM(struct mCore* core, struct VFile* vf) {
978 struct GBCore* gbcore = (struct GBCore*) core;
979 gbcore->logContext = mVideoLogContextCreate(NULL);
980 if (!mVideoLogContextLoad(gbcore->logContext, vf)) {
981 mVideoLogContextDestroy(core, gbcore->logContext);
982 gbcore->logContext = NULL;
983 return false;
984 }
985 mVideoLoggerAttachChannel(gbcore->proxyRenderer.logger, gbcore->logContext, 0);
986 return true;
987}
988
989static bool _GBVLPLoadState(struct mCore* core, const void* buffer) {
990 struct GB* gb = (struct GB*) core->board;
991 const struct GBSerializedState* state = buffer;
992
993 gb->timing.root = NULL;
994 gb->model = state->model;
995
996 gb->cpu->pc = GB_BASE_HRAM;
997 gb->cpu->memory.setActiveRegion(gb->cpu, gb->cpu->pc);
998
999 GBVideoDeserialize(&gb->video, state);
1000 GBIODeserialize(gb, state);
1001 GBAudioReset(&gb->audio);
1002
1003 // Make sure CPU loop never spins
1004 GBHalt(gb->cpu);
1005 gb->memory.ie = 0;
1006 gb->memory.ime = false;
1007
1008 return true;
1009}
1010
1011static bool _returnTrue(struct VFile* vf) {
1012 UNUSED(vf);
1013 return true;
1014}
1015
1016struct mCore* GBVideoLogPlayerCreate(void) {
1017 struct mCore* core = GBCoreCreate();
1018 core->init = _GBVLPInit;
1019 core->deinit = _GBVLPDeinit;
1020 core->reset = _GBVLPReset;
1021 core->loadROM = _GBVLPLoadROM;
1022 core->loadState = _GBVLPLoadState;
1023 core->isROM = _returnTrue;
1024 return core;
1025}
1026#else
1027struct mCore* GBVideoLogPlayerCreate(void) {
1028 return false;
1029}
1030#endif