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
214 int fakeBool;
215 if (mCoreConfigGetIntValue(config, "sgb.borders", &fakeBool)) {
216 gb->video.sgbBorders = fakeBool;
217 gb->video.renderer->enableSGBBorder(gb->video.renderer, fakeBool);
218 }
219
220#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
221 struct GBCore* gbcore = (struct GBCore*) core;
222 gbcore->overrides = mCoreConfigGetOverridesConst(config);
223#endif
224}
225
226static void _GBCoreDesiredVideoDimensions(struct mCore* core, unsigned* width, unsigned* height) {
227 struct GB* gb = core->board;
228 if (gb && (gb->model != GB_MODEL_SGB || !gb->video.sgbBorders)) {
229 *width = GB_VIDEO_HORIZONTAL_PIXELS;
230 *height = GB_VIDEO_VERTICAL_PIXELS;
231 } else {
232 *width = 256;
233 *height = 224;
234 }
235}
236
237static void _GBCoreSetVideoBuffer(struct mCore* core, color_t* buffer, size_t stride) {
238 struct GBCore* gbcore = (struct GBCore*) core;
239 gbcore->renderer.outputBuffer = buffer;
240 gbcore->renderer.outputBufferStride = stride;
241}
242
243static void _GBCoreGetPixels(struct mCore* core, const void** buffer, size_t* stride) {
244 struct GBCore* gbcore = (struct GBCore*) core;
245 gbcore->renderer.d.getPixels(&gbcore->renderer.d, stride, buffer);
246}
247
248static void _GBCorePutPixels(struct mCore* core, const void* buffer, size_t stride) {
249 struct GBCore* gbcore = (struct GBCore*) core;
250 gbcore->renderer.d.putPixels(&gbcore->renderer.d, stride, buffer);
251}
252
253static struct blip_t* _GBCoreGetAudioChannel(struct mCore* core, int ch) {
254 struct GB* gb = core->board;
255 switch (ch) {
256 case 0:
257 return gb->audio.left;
258 case 1:
259 return gb->audio.right;
260 default:
261 return NULL;
262 }
263}
264
265static void _GBCoreSetAudioBufferSize(struct mCore* core, size_t samples) {
266 struct GB* gb = core->board;
267 GBAudioResizeBuffer(&gb->audio, samples);
268}
269
270static size_t _GBCoreGetAudioBufferSize(struct mCore* core) {
271 struct GB* gb = core->board;
272 return gb->audio.samples;
273}
274
275static void _GBCoreAddCoreCallbacks(struct mCore* core, struct mCoreCallbacks* coreCallbacks) {
276 struct GB* gb = core->board;
277 *mCoreCallbacksListAppend(&gb->coreCallbacks) = *coreCallbacks;
278}
279
280static void _GBCoreClearCoreCallbacks(struct mCore* core) {
281 struct GB* gb = core->board;
282 mCoreCallbacksListClear(&gb->coreCallbacks);
283}
284
285static void _GBCoreSetAVStream(struct mCore* core, struct mAVStream* stream) {
286 struct GB* gb = core->board;
287 gb->stream = stream;
288 if (stream && stream->videoDimensionsChanged) {
289 unsigned width, height;
290 core->desiredVideoDimensions(core, &width, &height);
291 stream->videoDimensionsChanged(stream, width, height);
292 }
293}
294
295static bool _GBCoreLoadROM(struct mCore* core, struct VFile* vf) {
296 return GBLoadROM(core->board, vf);
297}
298
299static bool _GBCoreLoadBIOS(struct mCore* core, struct VFile* vf, int type) {
300 UNUSED(type);
301 GBLoadBIOS(core->board, vf);
302 return true;
303}
304
305static bool _GBCoreLoadSave(struct mCore* core, struct VFile* vf) {
306 return GBLoadSave(core->board, vf);
307}
308
309static bool _GBCoreLoadTemporarySave(struct mCore* core, struct VFile* vf) {
310 struct GB* gb = core->board;
311 GBSavedataMask(gb, vf, false);
312 return true; // TODO: Return a real value
313}
314
315static bool _GBCoreLoadPatch(struct mCore* core, struct VFile* vf) {
316 if (!vf) {
317 return false;
318 }
319 struct Patch patch;
320 if (!loadPatch(vf, &patch)) {
321 return false;
322 }
323 GBApplyPatch(core->board, &patch);
324 return true;
325}
326
327static void _GBCoreUnloadROM(struct mCore* core) {
328 struct GBCore* gbcore = (struct GBCore*) core;
329 struct LR35902Core* cpu = core->cpu;
330 if (gbcore->cheatDevice) {
331 LR35902HotplugDetach(cpu, CPU_COMPONENT_CHEAT_DEVICE);
332 cpu->components[CPU_COMPONENT_CHEAT_DEVICE] = NULL;
333 mCheatDeviceDestroy(gbcore->cheatDevice);
334 gbcore->cheatDevice = NULL;
335 }
336 return GBUnloadROM(core->board);
337}
338
339static void _GBCoreChecksum(const struct mCore* core, void* data, enum mCoreChecksumType type) {
340 struct GB* gb = (struct GB*) core->board;
341 switch (type) {
342 case CHECKSUM_CRC32:
343 memcpy(data, &gb->romCrc32, sizeof(gb->romCrc32));
344 break;
345 }
346 return;
347}
348
349static void _GBCoreReset(struct mCore* core) {
350 struct GBCore* gbcore = (struct GBCore*) core;
351 struct GB* gb = (struct GB*) core->board;
352 if (gbcore->renderer.outputBuffer) {
353 GBVideoAssociateRenderer(&gb->video, &gbcore->renderer.d);
354 }
355
356 if (gb->memory.rom) {
357 struct GBCartridgeOverride override;
358 const struct GBCartridge* cart = (const struct GBCartridge*) &gb->memory.rom[0x100];
359 override.headerCrc32 = doCrc32(cart, sizeof(*cart));
360 if (GBOverrideFind(gbcore->overrides, &override)) {
361 GBOverrideApply(gb, &override);
362 }
363 }
364
365 const char* modelGB = mCoreConfigGetValue(&core->config, "gb.model");
366 const char* modelCGB = mCoreConfigGetValue(&core->config, "cgb.model");
367 const char* modelSGB = mCoreConfigGetValue(&core->config, "sgb.model");
368 if (modelGB || modelCGB || modelSGB) {
369 GBDetectModel(gb);
370 if (gb->model == GB_MODEL_DMG && modelGB) {
371 gb->model = GBNameToModel(modelGB);
372 } else if (gb->model == GB_MODEL_CGB && modelCGB) {
373 gb->model = GBNameToModel(modelCGB);
374 } else if (gb->model == GB_MODEL_SGB && modelSGB) {
375 gb->model = GBNameToModel(modelSGB);
376 }
377 }
378
379#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
380 if (!gb->biosVf && core->opts.useBios) {
381 struct VFile* bios = NULL;
382 bool found = false;
383 if (core->opts.bios) {
384 bios = VFileOpen(core->opts.bios, O_RDONLY);
385 if (bios && GBIsBIOS(bios)) {
386 found = true;
387 } else if (bios) {
388 bios->close(bios);
389 bios = NULL;
390 }
391 }
392 if (!found) {
393 GBDetectModel(gb);
394 const char* configPath = NULL;
395
396 switch (gb->model) {
397 case GB_MODEL_DMG:
398 case GB_MODEL_MGB: // TODO
399 configPath = mCoreConfigGetValue(&core->config, "gb.bios");
400 break;
401 case GB_MODEL_SGB:
402 case GB_MODEL_SGB2: // TODO
403 configPath = mCoreConfigGetValue(&core->config, "sgb.bios");
404 break;
405 case GB_MODEL_CGB:
406 case GB_MODEL_AGB:
407 configPath = mCoreConfigGetValue(&core->config, "gbc.bios");
408 break;
409 default:
410 break;
411 };
412 if (configPath) {
413 bios = VFileOpen(configPath, O_RDONLY);
414 }
415 if (bios && GBIsBIOS(bios)) {
416 found = true;
417 } else if (bios) {
418 bios->close(bios);
419 bios = NULL;
420 }
421 }
422 if (!found) {
423 char path[PATH_MAX];
424 mCoreConfigDirectory(path, PATH_MAX);
425 switch (gb->model) {
426 case GB_MODEL_DMG:
427 case GB_MODEL_MGB: // TODO
428 strncat(path, PATH_SEP "gb_bios.bin", PATH_MAX - strlen(path));
429 break;
430 case GB_MODEL_SGB:
431 case GB_MODEL_SGB2: // TODO
432 strncat(path, PATH_SEP "sgb_bios.bin", PATH_MAX - strlen(path));
433 break;
434 case GB_MODEL_CGB:
435 case GB_MODEL_AGB:
436 strncat(path, PATH_SEP "gbc_bios.bin", PATH_MAX - strlen(path));
437 break;
438 default:
439 break;
440 };
441 bios = VFileOpen(path, O_RDONLY);
442 if (bios && GBIsBIOS(bios)) {
443 found = true;
444 } else if (bios) {
445 bios->close(bios);
446 bios = NULL;
447 }
448 }
449 if (bios) {
450 GBLoadBIOS(gb, bios);
451 }
452 }
453#endif
454
455 LR35902Reset(core->cpu);
456
457 if (core->opts.skipBios) {
458 GBSkipBIOS(core->board);
459 }
460}
461
462static void _GBCoreRunFrame(struct mCore* core) {
463 struct GB* gb = core->board;
464 int32_t frameCounter = gb->video.frameCounter;
465 while (gb->video.frameCounter == frameCounter) {
466 LR35902Run(core->cpu);
467 }
468}
469
470static void _GBCoreRunLoop(struct mCore* core) {
471 LR35902Run(core->cpu);
472}
473
474static void _GBCoreStep(struct mCore* core) {
475 struct LR35902Core* cpu = core->cpu;
476 do {
477 LR35902Tick(cpu);
478 } while (cpu->executionState != LR35902_CORE_FETCH);
479}
480
481static size_t _GBCoreStateSize(struct mCore* core) {
482 UNUSED(core);
483 return sizeof(struct GBSerializedState);
484}
485
486static bool _GBCoreLoadState(struct mCore* core, const void* state) {
487 return GBDeserialize(core->board, state);
488}
489
490static bool _GBCoreSaveState(struct mCore* core, void* state) {
491 struct LR35902Core* cpu = core->cpu;
492 while (cpu->executionState != LR35902_CORE_FETCH) {
493 LR35902Tick(cpu);
494 }
495 GBSerialize(core->board, state);
496 return true;
497}
498
499static void _GBCoreSetKeys(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 _GBCoreAddKeys(struct mCore* core, uint32_t keys) {
506 struct GBCore* gbcore = (struct GBCore*) core;
507 gbcore->keys |= keys;
508 GBTestKeypadIRQ(core->board);
509}
510
511static void _GBCoreClearKeys(struct mCore* core, uint32_t keys) {
512 struct GBCore* gbcore = (struct GBCore*) core;
513 gbcore->keys &= ~keys;
514}
515
516static int32_t _GBCoreFrameCounter(const struct mCore* core) {
517 const struct GB* gb = core->board;
518 return gb->video.frameCounter;
519}
520
521static int32_t _GBCoreFrameCycles(const struct mCore* core) {
522 UNUSED(core);
523 return GB_VIDEO_TOTAL_LENGTH;
524}
525
526static int32_t _GBCoreFrequency(const struct mCore* core) {
527 UNUSED(core);
528 // TODO: GB differences
529 return DMG_LR35902_FREQUENCY;
530}
531
532static void _GBCoreGetGameTitle(const struct mCore* core, char* title) {
533 GBGetGameTitle(core->board, title);
534}
535
536static void _GBCoreGetGameCode(const struct mCore* core, char* title) {
537 GBGetGameCode(core->board, title);
538}
539
540static void _GBCoreSetPeripheral(struct mCore* core, int type, void* periph) {
541 struct GB* gb = core->board;
542 switch (type) {
543 case mPERIPH_ROTATION:
544 gb->memory.rotation = periph;
545 break;
546 case mPERIPH_RUMBLE:
547 gb->memory.rumble = periph;
548 break;
549 case mPERIPH_IMAGE_SOURCE:
550 gb->memory.cam = periph;
551 break;
552 default:
553 return;
554 }
555}
556
557static uint32_t _GBCoreBusRead8(struct mCore* core, uint32_t address) {
558 struct LR35902Core* cpu = core->cpu;
559 return cpu->memory.load8(cpu, address);
560}
561
562static uint32_t _GBCoreBusRead16(struct mCore* core, uint32_t address) {
563 struct LR35902Core* cpu = core->cpu;
564 return cpu->memory.load8(cpu, address) | (cpu->memory.load8(cpu, address + 1) << 8);
565}
566
567static uint32_t _GBCoreBusRead32(struct mCore* core, uint32_t address) {
568 struct LR35902Core* cpu = core->cpu;
569 return cpu->memory.load8(cpu, address) | (cpu->memory.load8(cpu, address + 1) << 8) |
570 (cpu->memory.load8(cpu, address + 2) << 16) | (cpu->memory.load8(cpu, address + 3) << 24);
571}
572
573static void _GBCoreBusWrite8(struct mCore* core, uint32_t address, uint8_t value) {
574 struct LR35902Core* cpu = core->cpu;
575 cpu->memory.store8(cpu, address, value);
576}
577
578static void _GBCoreBusWrite16(struct mCore* core, uint32_t address, uint16_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}
583
584static void _GBCoreBusWrite32(struct mCore* core, uint32_t address, uint32_t value) {
585 struct LR35902Core* cpu = core->cpu;
586 cpu->memory.store8(cpu, address, value);
587 cpu->memory.store8(cpu, address + 1, value >> 8);
588 cpu->memory.store8(cpu, address + 2, value >> 16);
589 cpu->memory.store8(cpu, address + 3, value >> 24);
590}
591
592static uint32_t _GBCoreRawRead8(struct mCore* core, uint32_t address, int segment) {
593 struct LR35902Core* cpu = core->cpu;
594 return GBView8(cpu, address, segment);
595}
596
597static uint32_t _GBCoreRawRead16(struct mCore* core, uint32_t address, int segment) {
598 struct LR35902Core* cpu = core->cpu;
599 return GBView8(cpu, address, segment) | (GBView8(cpu, address + 1, segment) << 8);
600}
601
602static uint32_t _GBCoreRawRead32(struct mCore* core, uint32_t address, int segment) {
603 struct LR35902Core* cpu = core->cpu;
604 return GBView8(cpu, address, segment) | (GBView8(cpu, address + 1, segment) << 8) |
605 (GBView8(cpu, address + 2, segment) << 16) | (GBView8(cpu, address + 3, segment) << 24);
606}
607
608static void _GBCoreRawWrite8(struct mCore* core, uint32_t address, int segment, uint8_t value) {
609 struct LR35902Core* cpu = core->cpu;
610 GBPatch8(cpu, address, value, NULL, segment);
611}
612
613static void _GBCoreRawWrite16(struct mCore* core, uint32_t address, int segment, uint16_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}
618
619static void _GBCoreRawWrite32(struct mCore* core, uint32_t address, int segment, uint32_t value) {
620 struct LR35902Core* cpu = core->cpu;
621 GBPatch8(cpu, address, value, NULL, segment);
622 GBPatch8(cpu, address + 1, value >> 8, NULL, segment);
623 GBPatch8(cpu, address + 2, value >> 16, NULL, segment);
624 GBPatch8(cpu, address + 3, value >> 24, NULL, segment);
625}
626
627size_t _GBListMemoryBlocks(const struct mCore* core, const struct mCoreMemoryBlock** blocks) {
628 const struct GB* gb = core->board;
629 switch (gb->model) {
630 case GB_MODEL_DMG:
631 case GB_MODEL_MGB:
632 case GB_MODEL_SGB:
633 case GB_MODEL_SGB2:
634 default:
635 *blocks = _GBMemoryBlocks;
636 return sizeof(_GBMemoryBlocks) / sizeof(*_GBMemoryBlocks);
637 case GB_MODEL_CGB:
638 case GB_MODEL_AGB:
639 *blocks = _GBCMemoryBlocks;
640 return sizeof(_GBCMemoryBlocks) / sizeof(*_GBCMemoryBlocks);
641 }
642}
643
644void* _GBGetMemoryBlock(struct mCore* core, size_t id, size_t* sizeOut) {
645 struct GB* gb = core->board;
646 bool isCgb = gb->model >= GB_MODEL_CGB;
647 switch (id) {
648 default:
649 return NULL;
650 case GB_REGION_CART_BANK0:
651 *sizeOut = gb->memory.romSize;
652 return gb->memory.rom;
653 case GB_REGION_VRAM:
654 *sizeOut = GB_SIZE_WORKING_RAM_BANK0 * (isCgb ? 1 : 2);
655 return gb->video.vram;
656 case GB_REGION_EXTERNAL_RAM:
657 *sizeOut = gb->sramSize;
658 return gb->memory.sram;
659 case GB_REGION_WORKING_RAM_BANK0:
660 *sizeOut = GB_SIZE_VRAM * (isCgb ? 8 : 2);
661 return gb->memory.wram;
662 case GB_BASE_OAM:
663 *sizeOut = GB_SIZE_OAM;
664 return gb->video.oam.raw;
665 case GB_BASE_HRAM:
666 *sizeOut = GB_SIZE_HRAM;
667 return gb->memory.hram;
668 }
669}
670
671#ifdef USE_DEBUGGERS
672static bool _GBCoreSupportsDebuggerType(struct mCore* core, enum mDebuggerType type) {
673 UNUSED(core);
674 switch (type) {
675 case DEBUGGER_CLI:
676 return true;
677 default:
678 return false;
679 }
680}
681
682static struct mDebuggerPlatform* _GBCoreDebuggerPlatform(struct mCore* core) {
683 struct GBCore* gbcore = (struct GBCore*) core;
684 struct GB* gb = core->board;
685 if (!gbcore->debuggerPlatform) {
686 struct LR35902Debugger* platform = (struct LR35902Debugger*) LR35902DebuggerPlatformCreate();
687 if (gb->model >= GB_MODEL_CGB) {
688 platform->segments = _GBCSegments;
689 } else {
690 platform->segments = _GBSegments;
691 }
692 gbcore->debuggerPlatform = &platform->d;
693 }
694 return gbcore->debuggerPlatform;
695}
696
697static struct CLIDebuggerSystem* _GBCoreCliDebuggerSystem(struct mCore* core) {
698 return GBCLIDebuggerCreate(core);
699}
700
701static void _GBCoreAttachDebugger(struct mCore* core, struct mDebugger* debugger) {
702 struct LR35902Core* cpu = core->cpu;
703 if (core->debugger) {
704 LR35902HotplugDetach(cpu, CPU_COMPONENT_DEBUGGER);
705 }
706 cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
707 LR35902HotplugAttach(cpu, CPU_COMPONENT_DEBUGGER);
708 core->debugger = debugger;
709}
710
711static void _GBCoreDetachDebugger(struct mCore* core) {
712 struct LR35902Core* cpu = core->cpu;
713 if (core->debugger) {
714 LR35902HotplugDetach(cpu, CPU_COMPONENT_DEBUGGER);
715 }
716 cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
717 core->debugger = NULL;
718}
719
720static void _GBCoreLoadSymbols(struct mCore* core, struct VFile* vf) {
721 core->symbolTable = mDebuggerSymbolTableCreate();
722#if !defined(MINIMAL_CORE) || MINIMAL_CORE < 2
723 if (!vf) {
724 vf = mDirectorySetOpenSuffix(&core->dirs, core->dirs.base, ".sym", O_RDONLY);
725 }
726#endif
727 if (!vf) {
728 return;
729 }
730 GBLoadSymbols(core->symbolTable, vf);
731}
732
733static bool _GBCoreLookupIdentifier(struct mCore* core, const char* name, int32_t* value, int* segment) {
734 UNUSED(core);
735 *segment = -1;
736 int i;
737 for (i = 0; i < REG_MAX; ++i) {
738 const char* reg = GBIORegisterNames[i];
739 if (reg && strcasecmp(reg, name) == 0) {
740 *value = GB_BASE_IO | i;
741 return true;
742 }
743 }
744 return false;
745}
746#endif
747
748static struct mCheatDevice* _GBCoreCheatDevice(struct mCore* core) {
749 struct GBCore* gbcore = (struct GBCore*) core;
750 if (!gbcore->cheatDevice) {
751 gbcore->cheatDevice = GBCheatDeviceCreate();
752 ((struct LR35902Core*) core->cpu)->components[CPU_COMPONENT_CHEAT_DEVICE] = &gbcore->cheatDevice->d;
753 LR35902HotplugAttach(core->cpu, CPU_COMPONENT_CHEAT_DEVICE);
754 gbcore->cheatDevice->p = core;
755 }
756 return gbcore->cheatDevice;
757}
758
759static size_t _GBCoreSavedataClone(struct mCore* core, void** sram) {
760 struct GB* gb = core->board;
761 struct VFile* vf = gb->sramVf;
762 if (vf) {
763 *sram = malloc(vf->size(vf));
764 vf->seek(vf, 0, SEEK_SET);
765 return vf->read(vf, *sram, vf->size(vf));
766 }
767 *sram = malloc(gb->sramSize);
768 memcpy(*sram, gb->memory.sram, gb->sramSize);
769 return gb->sramSize;
770}
771
772static bool _GBCoreSavedataRestore(struct mCore* core, const void* sram, size_t size, bool writeback) {
773 struct GB* gb = core->board;
774 if (!writeback) {
775 struct VFile* vf = VFileMemChunk(sram, size);
776 GBSavedataMask(gb, vf, true);
777 return true;
778 }
779 struct VFile* vf = gb->sramVf;
780 if (vf) {
781 vf->seek(vf, 0, SEEK_SET);
782 return vf->write(vf, sram, size) > 0;
783 }
784 if (size > 0x20000) {
785 size = 0x20000;
786 }
787 GBResizeSram(gb, size);
788 memcpy(gb->memory.sram, sram, size);
789 return true;
790}
791
792static size_t _GBCoreListVideoLayers(const struct mCore* core, const struct mCoreChannelInfo** info) {
793 UNUSED(core);
794 if (info) {
795 *info = _GBVideoLayers;
796 }
797 return sizeof(_GBVideoLayers) / sizeof(*_GBVideoLayers);
798}
799
800static size_t _GBCoreListAudioChannels(const struct mCore* core, const struct mCoreChannelInfo** info) {
801 UNUSED(core);
802 if (info) {
803 *info = _GBAudioChannels;
804 }
805 return sizeof(_GBAudioChannels) / sizeof(*_GBAudioChannels);
806}
807
808static void _GBCoreEnableVideoLayer(struct mCore* core, size_t id, bool enable) {
809 struct GB* gb = core->board;
810 switch (id) {
811 case 0:
812 gb->video.renderer->disableBG = !enable;
813 break;
814 case 1:
815 gb->video.renderer->disableOBJ = !enable;
816 break;
817 case 2:
818 gb->video.renderer->disableWIN = !enable;
819 break;
820 default:
821 break;
822 }
823}
824
825static void _GBCoreEnableAudioChannel(struct mCore* core, size_t id, bool enable) {
826 struct GB* gb = core->board;
827 switch (id) {
828 case 0:
829 case 1:
830 case 2:
831 case 3:
832 gb->audio.forceDisableCh[id] = !enable;
833 break;
834 default:
835 break;
836 }
837}
838
839static void _GBCoreAdjustVideoLayer(struct mCore* core, size_t id, int32_t x, int32_t y) {
840 struct GBCore* gbcore = (struct GBCore*) core;
841 switch (id) {
842 case 0:
843 gbcore->renderer.offsetScx = x;
844 gbcore->renderer.offsetScy = y;
845 break;
846 case 1:
847 gbcore->renderer.offsetWx = x;
848 gbcore->renderer.offsetWy = y;
849 break;
850 case 2:
851 gbcore->renderer.objOffsetX = x;
852 gbcore->renderer.objOffsetY = y;
853 break;
854 default:
855 return;
856 }
857}
858
859#ifndef MINIMAL_CORE
860static void _GBCoreStartVideoLog(struct mCore* core, struct mVideoLogContext* context) {
861 struct GBCore* gbcore = (struct GBCore*) core;
862 struct GB* gb = core->board;
863 gbcore->logContext = context;
864
865 int channelId = mVideoLoggerAddChannel(context);
866 gbcore->proxyRenderer.logger = malloc(sizeof(struct mVideoLogger));
867 mVideoLoggerRendererCreate(gbcore->proxyRenderer.logger, false);
868 mVideoLoggerAttachChannel(gbcore->proxyRenderer.logger, context, channelId);
869 gbcore->proxyRenderer.logger->block = false;
870
871 GBVideoProxyRendererCreate(&gbcore->proxyRenderer, &gbcore->renderer.d);
872 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
873}
874
875static void _GBCoreEndVideoLog(struct mCore* core) {
876 struct GBCore* gbcore = (struct GBCore*) core;
877 struct GB* gb = core->board;
878 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
879 free(gbcore->proxyRenderer.logger);
880 gbcore->proxyRenderer.logger = NULL;
881}
882#endif
883
884struct mCore* GBCoreCreate(void) {
885 struct GBCore* gbcore = malloc(sizeof(*gbcore));
886 struct mCore* core = &gbcore->d;
887 memset(&core->opts, 0, sizeof(core->opts));
888 core->cpu = NULL;
889 core->board = NULL;
890 core->debugger = NULL;
891 core->symbolTable = NULL;
892 core->init = _GBCoreInit;
893 core->deinit = _GBCoreDeinit;
894 core->platform = _GBCorePlatform;
895 core->setSync = _GBCoreSetSync;
896 core->loadConfig = _GBCoreLoadConfig;
897 core->desiredVideoDimensions = _GBCoreDesiredVideoDimensions;
898 core->setVideoBuffer = _GBCoreSetVideoBuffer;
899 core->getPixels = _GBCoreGetPixels;
900 core->putPixels = _GBCorePutPixels;
901 core->getAudioChannel = _GBCoreGetAudioChannel;
902 core->setAudioBufferSize = _GBCoreSetAudioBufferSize;
903 core->getAudioBufferSize = _GBCoreGetAudioBufferSize;
904 core->setAVStream = _GBCoreSetAVStream;
905 core->addCoreCallbacks = _GBCoreAddCoreCallbacks;
906 core->clearCoreCallbacks = _GBCoreClearCoreCallbacks;
907 core->isROM = GBIsROM;
908 core->loadROM = _GBCoreLoadROM;
909 core->loadBIOS = _GBCoreLoadBIOS;
910 core->loadSave = _GBCoreLoadSave;
911 core->loadTemporarySave = _GBCoreLoadTemporarySave;
912 core->loadPatch = _GBCoreLoadPatch;
913 core->unloadROM = _GBCoreUnloadROM;
914 core->checksum = _GBCoreChecksum;
915 core->reset = _GBCoreReset;
916 core->runFrame = _GBCoreRunFrame;
917 core->runLoop = _GBCoreRunLoop;
918 core->step = _GBCoreStep;
919 core->stateSize = _GBCoreStateSize;
920 core->loadState = _GBCoreLoadState;
921 core->saveState = _GBCoreSaveState;
922 core->setKeys = _GBCoreSetKeys;
923 core->addKeys = _GBCoreAddKeys;
924 core->clearKeys = _GBCoreClearKeys;
925 core->frameCounter = _GBCoreFrameCounter;
926 core->frameCycles = _GBCoreFrameCycles;
927 core->frequency = _GBCoreFrequency;
928 core->getGameTitle = _GBCoreGetGameTitle;
929 core->getGameCode = _GBCoreGetGameCode;
930 core->setPeripheral = _GBCoreSetPeripheral;
931 core->busRead8 = _GBCoreBusRead8;
932 core->busRead16 = _GBCoreBusRead16;
933 core->busRead32 = _GBCoreBusRead32;
934 core->busWrite8 = _GBCoreBusWrite8;
935 core->busWrite16 = _GBCoreBusWrite16;
936 core->busWrite32 = _GBCoreBusWrite32;
937 core->rawRead8 = _GBCoreRawRead8;
938 core->rawRead16 = _GBCoreRawRead16;
939 core->rawRead32 = _GBCoreRawRead32;
940 core->rawWrite8 = _GBCoreRawWrite8;
941 core->rawWrite16 = _GBCoreRawWrite16;
942 core->rawWrite32 = _GBCoreRawWrite32;
943 core->listMemoryBlocks = _GBListMemoryBlocks;
944 core->getMemoryBlock = _GBGetMemoryBlock;
945#ifdef USE_DEBUGGERS
946 core->supportsDebuggerType = _GBCoreSupportsDebuggerType;
947 core->debuggerPlatform = _GBCoreDebuggerPlatform;
948 core->cliDebuggerSystem = _GBCoreCliDebuggerSystem;
949 core->attachDebugger = _GBCoreAttachDebugger;
950 core->detachDebugger = _GBCoreDetachDebugger;
951 core->loadSymbols = _GBCoreLoadSymbols;
952 core->lookupIdentifier = _GBCoreLookupIdentifier;
953#endif
954 core->cheatDevice = _GBCoreCheatDevice;
955 core->savedataClone = _GBCoreSavedataClone;
956 core->savedataRestore = _GBCoreSavedataRestore;
957 core->listVideoLayers = _GBCoreListVideoLayers;
958 core->listAudioChannels = _GBCoreListAudioChannels;
959 core->enableVideoLayer = _GBCoreEnableVideoLayer;
960 core->enableAudioChannel = _GBCoreEnableAudioChannel;
961 core->adjustVideoLayer = _GBCoreAdjustVideoLayer;
962#ifndef MINIMAL_CORE
963 core->startVideoLog = _GBCoreStartVideoLog;
964 core->endVideoLog = _GBCoreEndVideoLog;
965#endif
966 return core;
967}
968
969#ifndef MINIMAL_CORE
970static void _GBVLPStartFrameCallback(void *context) {
971 struct mCore* core = context;
972 struct GBCore* gbcore = (struct GBCore*) core;
973 struct GB* gb = core->board;
974
975 if (!mVideoLoggerRendererRun(gbcore->proxyRenderer.logger, true)) {
976 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
977 mVideoLogContextRewind(gbcore->logContext, core);
978 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
979 }
980}
981
982static bool _GBVLPInit(struct mCore* core) {
983 struct GBCore* gbcore = (struct GBCore*) core;
984 if (!_GBCoreInit(core)) {
985 return false;
986 }
987 gbcore->proxyRenderer.logger = malloc(sizeof(struct mVideoLogger));
988 mVideoLoggerRendererCreate(gbcore->proxyRenderer.logger, true);
989 GBVideoProxyRendererCreate(&gbcore->proxyRenderer, NULL);
990 memset(&gbcore->logCallbacks, 0, sizeof(gbcore->logCallbacks));
991 gbcore->logCallbacks.videoFrameStarted = _GBVLPStartFrameCallback;
992 gbcore->logCallbacks.context = core;
993 core->addCoreCallbacks(core, &gbcore->logCallbacks);
994 return true;
995}
996
997static void _GBVLPDeinit(struct mCore* core) {
998 struct GBCore* gbcore = (struct GBCore*) core;
999 if (gbcore->logContext) {
1000 mVideoLogContextDestroy(core, gbcore->logContext);
1001 }
1002 _GBCoreDeinit(core);
1003}
1004
1005static void _GBVLPReset(struct mCore* core) {
1006 struct GBCore* gbcore = (struct GBCore*) core;
1007 struct GB* gb = (struct GB*) core->board;
1008 if (gb->video.renderer == &gbcore->proxyRenderer.d) {
1009 GBVideoProxyRendererUnshim(&gb->video, &gbcore->proxyRenderer);
1010 } else if (gbcore->renderer.outputBuffer) {
1011 struct GBVideoRenderer* renderer = &gbcore->renderer.d;
1012 GBVideoAssociateRenderer(&gb->video, renderer);
1013 }
1014
1015 LR35902Reset(core->cpu);
1016 mVideoLogContextRewind(gbcore->logContext, core);
1017 GBVideoProxyRendererShim(&gb->video, &gbcore->proxyRenderer);
1018
1019 // Make sure CPU loop never spins
1020 GBHalt(gb->cpu);
1021 gb->memory.ie = 0;
1022 gb->memory.ime = false;
1023}
1024
1025static bool _GBVLPLoadROM(struct mCore* core, struct VFile* vf) {
1026 struct GBCore* gbcore = (struct GBCore*) core;
1027 gbcore->logContext = mVideoLogContextCreate(NULL);
1028 if (!mVideoLogContextLoad(gbcore->logContext, vf)) {
1029 mVideoLogContextDestroy(core, gbcore->logContext);
1030 gbcore->logContext = NULL;
1031 return false;
1032 }
1033 mVideoLoggerAttachChannel(gbcore->proxyRenderer.logger, gbcore->logContext, 0);
1034 return true;
1035}
1036
1037static bool _GBVLPLoadState(struct mCore* core, const void* buffer) {
1038 struct GB* gb = (struct GB*) core->board;
1039 const struct GBSerializedState* state = buffer;
1040
1041 gb->timing.root = NULL;
1042 gb->model = state->model;
1043
1044 gb->cpu->pc = GB_BASE_HRAM;
1045 gb->cpu->memory.setActiveRegion(gb->cpu, gb->cpu->pc);
1046
1047 GBVideoDeserialize(&gb->video, state);
1048 GBIODeserialize(gb, state);
1049 GBAudioReset(&gb->audio);
1050
1051 // Make sure CPU loop never spins
1052 GBHalt(gb->cpu);
1053 gb->memory.ie = 0;
1054 gb->memory.ime = false;
1055
1056 return true;
1057}
1058
1059static bool _returnTrue(struct VFile* vf) {
1060 UNUSED(vf);
1061 return true;
1062}
1063
1064struct mCore* GBVideoLogPlayerCreate(void) {
1065 struct mCore* core = GBCoreCreate();
1066 core->init = _GBVLPInit;
1067 core->deinit = _GBVLPDeinit;
1068 core->reset = _GBVLPReset;
1069 core->loadROM = _GBVLPLoadROM;
1070 core->loadState = _GBVLPLoadState;
1071 core->isROM = _returnTrue;
1072 return core;
1073}
1074#else
1075struct mCore* GBVideoLogPlayerCreate(void) {
1076 return false;
1077}
1078#endif