all repos — mgba @ 1dcf70d6d3eb2d08651c73c55613f5524158f395

mGBA Game Boy Advance Emulator

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