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