all repos — mgba @ 871c21fb6cf9041b4ac7c7f7074e0b2eb77484fe

mGBA Game Boy Advance Emulator

src/gb/video.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/internal/gb/video.h>
  7
  8#include <mgba/core/sync.h>
  9#include <mgba/core/thread.h>
 10#include <mgba/core/tile-cache.h>
 11#include <mgba/internal/gb/gb.h>
 12#include <mgba/internal/gb/io.h>
 13#include <mgba/internal/gb/serialize.h>
 14#include <mgba/internal/lr35902/lr35902.h>
 15
 16#include <mgba-util/memory.h>
 17
 18static void GBVideoDummyRendererInit(struct GBVideoRenderer* renderer, enum GBModel model);
 19static void GBVideoDummyRendererDeinit(struct GBVideoRenderer* renderer);
 20static uint8_t GBVideoDummyRendererWriteVideoRegister(struct GBVideoRenderer* renderer, uint16_t address, uint8_t value);
 21static void GBVideoDummyRendererWriteSGBPacket(struct GBVideoRenderer* renderer, uint8_t* data);
 22static void GBVideoDummyRendererWritePalette(struct GBVideoRenderer* renderer, int index, uint16_t value);
 23static void GBVideoDummyRendererWriteVRAM(struct GBVideoRenderer* renderer, uint16_t address);
 24static void GBVideoDummyRendererWriteOAM(struct GBVideoRenderer* renderer, uint16_t oam);
 25static void GBVideoDummyRendererDrawRange(struct GBVideoRenderer* renderer, int startX, int endX, int y, struct GBObj* obj, size_t oamMax);
 26static void GBVideoDummyRendererFinishScanline(struct GBVideoRenderer* renderer, int y);
 27static void GBVideoDummyRendererFinishFrame(struct GBVideoRenderer* renderer);
 28static void GBVideoDummyRendererGetPixels(struct GBVideoRenderer* renderer, size_t* stride, const void** pixels);
 29static void GBVideoDummyRendererPutPixels(struct GBVideoRenderer* renderer, size_t stride, const void* pixels);
 30
 31static void _cleanOAM(struct GBVideo* video, int y);
 32
 33static void _endMode0(struct mTiming* timing, void* context, uint32_t cyclesLate);
 34static void _endMode1(struct mTiming* timing, void* context, uint32_t cyclesLate);
 35static void _endMode2(struct mTiming* timing, void* context, uint32_t cyclesLate);
 36static void _endMode3(struct mTiming* timing, void* context, uint32_t cyclesLate);
 37static void _updateFrameCount(struct mTiming* timing, void* context, uint32_t cyclesLate);
 38
 39static struct GBVideoRenderer dummyRenderer = {
 40	.init = GBVideoDummyRendererInit,
 41	.deinit = GBVideoDummyRendererDeinit,
 42	.writeVideoRegister = GBVideoDummyRendererWriteVideoRegister,
 43	.writeSGBPacket = GBVideoDummyRendererWriteSGBPacket,
 44	.writeVRAM = GBVideoDummyRendererWriteVRAM,
 45	.writeOAM = GBVideoDummyRendererWriteOAM,
 46	.writePalette = GBVideoDummyRendererWritePalette,
 47	.drawRange = GBVideoDummyRendererDrawRange,
 48	.finishScanline = GBVideoDummyRendererFinishScanline,
 49	.finishFrame = GBVideoDummyRendererFinishFrame,
 50	.getPixels = GBVideoDummyRendererGetPixels,
 51	.putPixels = GBVideoDummyRendererPutPixels,
 52};
 53
 54void GBVideoInit(struct GBVideo* video) {
 55	video->renderer = &dummyRenderer;
 56	video->renderer->cache = NULL;
 57	video->renderer->sgbRenderMode = 0;
 58	video->vram = 0;
 59	video->frameskip = 0;
 60
 61	video->modeEvent.context = video;
 62	video->modeEvent.name = "GB Video Mode";
 63	video->modeEvent.callback = NULL;
 64	video->modeEvent.priority = 8;
 65	video->frameEvent.context = video;
 66	video->frameEvent.name = "GB Video Frame";
 67	video->frameEvent.callback = _updateFrameCount;
 68	video->frameEvent.priority = 9;
 69
 70	video->dmgPalette[0] = 0x7FFF;
 71	video->dmgPalette[1] = 0x56B5;
 72	video->dmgPalette[2] = 0x294A;
 73	video->dmgPalette[3] = 0x0000;
 74
 75	video->renderer->sgbCharRam = NULL;
 76	video->renderer->sgbMapRam = NULL;
 77	video->renderer->sgbPalRam = NULL;
 78	video->renderer->sgbAttributes = NULL;
 79	video->renderer->sgbAttributeFiles = NULL;
 80}
 81
 82void GBVideoReset(struct GBVideo* video) {
 83	video->ly = 0;
 84	video->x = 0;
 85	video->mode = 1;
 86	video->stat = 1;
 87
 88	video->frameCounter = 0;
 89	video->frameskipCounter = 0;
 90
 91	if (video->vram) {
 92		mappedMemoryFree(video->vram, GB_SIZE_VRAM);
 93	}
 94	video->vram = anonymousMemoryMap(GB_SIZE_VRAM);
 95	GBVideoSwitchBank(video, 0);
 96	video->renderer->vram = video->vram;
 97	memset(&video->oam, 0, sizeof(video->oam));
 98	video->renderer->oam = &video->oam;
 99	memset(&video->palette, 0, sizeof(video->palette));
100
101	if (video->p->model == GB_MODEL_SGB) {
102		video->renderer->sgbCharRam = anonymousMemoryMap(SGB_SIZE_CHAR_RAM);
103		video->renderer->sgbMapRam = anonymousMemoryMap(SGB_SIZE_MAP_RAM);
104		video->renderer->sgbPalRam = anonymousMemoryMap(SGB_SIZE_PAL_RAM);
105		video->renderer->sgbAttributeFiles = anonymousMemoryMap(SGB_SIZE_ATF_RAM);
106		video->renderer->sgbAttributes = malloc(90 * 45);
107		memset(video->renderer->sgbAttributes, 0, 90 * 45);
108		video->sgbCommandHeader = 0;
109	}
110
111	video->palette[0] = video->dmgPalette[0];
112	video->palette[1] = video->dmgPalette[1];
113	video->palette[2] = video->dmgPalette[2];
114	video->palette[3] = video->dmgPalette[3];
115	video->palette[8 * 4 + 0] = video->dmgPalette[0];
116	video->palette[8 * 4 + 1] = video->dmgPalette[1];
117	video->palette[8 * 4 + 2] = video->dmgPalette[2];
118	video->palette[8 * 4 + 3] = video->dmgPalette[3];
119	video->palette[9 * 4 + 0] = video->dmgPalette[0];
120	video->palette[9 * 4 + 1] = video->dmgPalette[1];
121	video->palette[9 * 4 + 2] = video->dmgPalette[2];
122	video->palette[9 * 4 + 3] = video->dmgPalette[3];
123
124	video->renderer->deinit(video->renderer);
125	video->renderer->init(video->renderer, video->p->model);
126
127	video->renderer->writePalette(video->renderer, 0, video->palette[0]);
128	video->renderer->writePalette(video->renderer, 1, video->palette[1]);
129	video->renderer->writePalette(video->renderer, 2, video->palette[2]);
130	video->renderer->writePalette(video->renderer, 3, video->palette[3]);
131	video->renderer->writePalette(video->renderer, 8 * 4 + 0, video->palette[8 * 4 + 0]);
132	video->renderer->writePalette(video->renderer, 8 * 4 + 1, video->palette[8 * 4 + 1]);
133	video->renderer->writePalette(video->renderer, 8 * 4 + 2, video->palette[8 * 4 + 2]);
134	video->renderer->writePalette(video->renderer, 8 * 4 + 3, video->palette[8 * 4 + 3]);
135	video->renderer->writePalette(video->renderer, 9 * 4 + 0, video->palette[9 * 4 + 0]);
136	video->renderer->writePalette(video->renderer, 9 * 4 + 1, video->palette[9 * 4 + 1]);
137	video->renderer->writePalette(video->renderer, 9 * 4 + 2, video->palette[9 * 4 + 2]);
138	video->renderer->writePalette(video->renderer, 9 * 4 + 3, video->palette[9 * 4 + 3]);
139}
140
141void GBVideoDeinit(struct GBVideo* video) {
142	GBVideoAssociateRenderer(video, &dummyRenderer);
143	mappedMemoryFree(video->vram, GB_SIZE_VRAM);
144	if (video->renderer->sgbCharRam) {
145		mappedMemoryFree(video->renderer->sgbCharRam, SGB_SIZE_CHAR_RAM);
146		video->renderer->sgbCharRam = NULL;
147	}
148	if (video->renderer->sgbMapRam) {
149		mappedMemoryFree(video->renderer->sgbMapRam, SGB_SIZE_MAP_RAM);
150		video->renderer->sgbMapRam = NULL;
151	}
152	if (video->renderer->sgbPalRam) {
153		mappedMemoryFree(video->renderer->sgbPalRam, SGB_SIZE_PAL_RAM);
154		video->renderer->sgbPalRam = NULL;
155	}
156	if (video->renderer->sgbAttributeFiles) {
157		mappedMemoryFree(video->renderer->sgbAttributeFiles, SGB_SIZE_ATF_RAM);
158		video->renderer->sgbAttributeFiles = NULL;
159	}
160	if (video->renderer->sgbAttributes) {
161		free(video->renderer->sgbAttributes);
162		video->renderer->sgbAttributes = NULL;
163	}
164}
165
166void GBVideoAssociateRenderer(struct GBVideo* video, struct GBVideoRenderer* renderer) {
167	video->renderer->deinit(video->renderer);
168	renderer->cache = video->renderer->cache;
169	renderer->sgbRenderMode = video->renderer->sgbRenderMode;
170	renderer->sgbCharRam = video->renderer->sgbCharRam;
171	renderer->sgbMapRam = video->renderer->sgbMapRam;
172	renderer->sgbPalRam = video->renderer->sgbPalRam;
173	renderer->sgbAttributeFiles = video->renderer->sgbAttributeFiles;
174	renderer->sgbAttributes = video->renderer->sgbAttributes;
175	video->renderer = renderer;
176	renderer->vram = video->vram;
177	video->renderer->init(video->renderer, video->p->model);
178}
179
180static bool _statIRQAsserted(struct GBVideo* video, GBRegisterSTAT stat) {
181	// TODO: variable for the IRQ line value?
182	if (GBRegisterSTATIsLYCIRQ(stat) && GBRegisterSTATIsLYC(stat)) {
183		return true;
184	}
185	switch (GBRegisterSTATGetMode(stat)) {
186	case 0:
187		if (GBRegisterSTATIsHblankIRQ(stat)) {
188			return true;
189		}
190		break;
191	case 1:
192		if (GBRegisterSTATIsVblankIRQ(stat)) {
193			return true;
194		}
195		break;
196	case 2:
197		if (GBRegisterSTATIsOAMIRQ(stat)) {
198			return true;
199		}
200		break;
201	case 3:
202		break;
203	}
204	return false;
205}
206
207void _endMode0(struct mTiming* timing, void* context, uint32_t cyclesLate) {
208	struct GBVideo* video = context;
209	if (video->frameskipCounter <= 0) {
210		video->renderer->finishScanline(video->renderer, video->ly);
211	}
212	int lyc = video->p->memory.io[REG_LYC];
213	int32_t next;
214	++video->ly;
215	video->p->memory.io[REG_LY] = video->ly;
216	GBRegisterSTAT oldStat = video->stat;
217	video->stat = GBRegisterSTATSetLYC(video->stat, lyc == video->ly);
218	if (video->ly < GB_VIDEO_VERTICAL_PIXELS) {
219		// TODO: Cache SCX & 7 in case it changes during mode 2
220		next = GB_VIDEO_MODE_2_LENGTH + (video->p->memory.io[REG_SCX] & 7);
221		video->mode = 2;
222		video->modeEvent.callback = _endMode2;
223	} else {
224		next = GB_VIDEO_HORIZONTAL_LENGTH;
225		video->mode = 1;
226		video->modeEvent.callback = _endMode1;
227
228		mTimingSchedule(&video->p->timing, &video->frameEvent, -cyclesLate);
229
230		if (!_statIRQAsserted(video, oldStat) && GBRegisterSTATIsOAMIRQ(video->stat)) {
231			video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
232		}
233		video->p->memory.io[REG_IF] |= (1 << GB_IRQ_VBLANK);
234	}
235	video->stat = GBRegisterSTATSetMode(video->stat, video->mode);
236	if (!_statIRQAsserted(video, oldStat) && _statIRQAsserted(video, video->stat)) {
237		video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
238	}
239	GBUpdateIRQs(video->p);
240	video->p->memory.io[REG_STAT] = video->stat;
241	mTimingSchedule(timing, &video->modeEvent, (next << video->p->doubleSpeed) - cyclesLate);
242}
243
244void _endMode1(struct mTiming* timing, void* context, uint32_t cyclesLate) {
245	struct GBVideo* video = context;
246	if (!GBRegisterLCDCIsEnable(video->p->memory.io[REG_LCDC])) {
247		return;
248	}
249	int lyc = video->p->memory.io[REG_LYC];
250	// TODO: One M-cycle delay
251	++video->ly;
252	int32_t next;
253	if (video->ly == GB_VIDEO_VERTICAL_TOTAL_PIXELS + 1) {
254		video->ly = 0;
255		video->p->memory.io[REG_LY] = video->ly;
256		next = GB_VIDEO_MODE_2_LENGTH + (video->p->memory.io[REG_SCX] & 7);
257		video->mode = 2;
258		video->modeEvent.callback = _endMode2;
259	} else if (video->ly == GB_VIDEO_VERTICAL_TOTAL_PIXELS) {
260		video->p->memory.io[REG_LY] = 0;
261		next = GB_VIDEO_HORIZONTAL_LENGTH - 8;
262	} else if (video->ly == GB_VIDEO_VERTICAL_TOTAL_PIXELS - 1) {
263		video->p->memory.io[REG_LY] = video->ly;
264		next = 8;
265	} else {
266		video->p->memory.io[REG_LY] = video->ly;
267		next = GB_VIDEO_HORIZONTAL_LENGTH;
268	}
269
270	GBRegisterSTAT oldStat = video->stat;
271	video->stat = GBRegisterSTATSetMode(video->stat, video->mode);
272	video->stat = GBRegisterSTATSetLYC(video->stat, lyc == video->p->memory.io[REG_LY]);
273	if (!_statIRQAsserted(video, oldStat) && _statIRQAsserted(video, video->stat)) {
274		video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
275		GBUpdateIRQs(video->p);
276	}
277	video->p->memory.io[REG_STAT] = video->stat;
278	mTimingSchedule(timing, &video->modeEvent, (next << video->p->doubleSpeed) - cyclesLate);
279}
280
281void _endMode2(struct mTiming* timing, void* context, uint32_t cyclesLate) {
282	struct GBVideo* video = context;
283	_cleanOAM(video, video->ly);
284	video->x = 0;
285	video->dotClock = mTimingCurrentTime(timing) - cyclesLate;
286	int32_t next = GB_VIDEO_MODE_3_LENGTH_BASE + video->objMax * 6 - (video->p->memory.io[REG_SCX] & 7);
287	video->mode = 3;
288	video->modeEvent.callback = _endMode3;
289	GBRegisterSTAT oldStat = video->stat;
290	video->stat = GBRegisterSTATSetMode(video->stat, video->mode);
291	if (!_statIRQAsserted(video, oldStat) && _statIRQAsserted(video, video->stat)) {
292		video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
293		GBUpdateIRQs(video->p);
294	}
295	video->p->memory.io[REG_STAT] = video->stat;
296	mTimingSchedule(timing, &video->modeEvent, (next << video->p->doubleSpeed) - cyclesLate);
297}
298
299void _endMode3(struct mTiming* timing, void* context, uint32_t cyclesLate) {
300	struct GBVideo* video = context;
301	GBVideoProcessDots(video);
302	if (video->ly < GB_VIDEO_VERTICAL_PIXELS && video->p->memory.isHdma && video->p->memory.io[REG_HDMA5] != 0xFF) {
303		video->p->memory.hdmaRemaining = 0x10;
304		mTimingDeschedule(timing, &video->p->memory.hdmaEvent);
305		mTimingSchedule(timing, &video->p->memory.hdmaEvent, 0);
306	}
307	video->mode = 0;
308	video->modeEvent.callback = _endMode0;
309	GBRegisterSTAT oldStat = video->stat;
310	video->stat = GBRegisterSTATSetMode(video->stat, video->mode);
311	if (!_statIRQAsserted(video, oldStat) && _statIRQAsserted(video, video->stat)) {
312		video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
313		GBUpdateIRQs(video->p);
314	}
315	video->p->memory.io[REG_STAT] = video->stat;
316	int32_t next = GB_VIDEO_MODE_0_LENGTH_BASE - video->objMax * 6;
317	mTimingSchedule(timing, &video->modeEvent, (next << video->p->doubleSpeed) - cyclesLate);
318}
319
320void _updateFrameCount(struct mTiming* timing, void* context, uint32_t cyclesLate) {
321	UNUSED(cyclesLate);
322	struct GBVideo* video = context;
323	if (video->p->cpu->executionState != LR35902_CORE_FETCH) {
324		mTimingSchedule(timing, &video->frameEvent, 4 - ((video->p->cpu->executionState + 1) & 3));
325		return;
326	}
327
328	size_t c;
329	for (c = 0; c < mCoreCallbacksListSize(&video->p->coreCallbacks); ++c) {
330		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&video->p->coreCallbacks, c);
331		if (callbacks->videoFrameEnded) {
332			callbacks->videoFrameEnded(callbacks->context);
333		}
334	}
335
336	GBFrameEnded(video->p);
337	--video->frameskipCounter;
338	if (video->frameskipCounter < 0) {
339		video->renderer->finishFrame(video->renderer);
340		mCoreSyncPostFrame(video->p->sync);
341		video->frameskipCounter = video->frameskip;
342	}
343	++video->frameCounter;
344
345	// TODO: Move to common code
346	if (video->p->stream && video->p->stream->postVideoFrame) {
347		const color_t* pixels;
348		size_t stride;
349		video->renderer->getPixels(video->renderer, &stride, (const void**) &pixels);
350		video->p->stream->postVideoFrame(video->p->stream, pixels, stride);
351	}
352
353	if (!GBRegisterLCDCIsEnable(video->p->memory.io[REG_LCDC])) {
354		mTimingSchedule(timing, &video->frameEvent, GB_VIDEO_TOTAL_LENGTH);
355	}
356
357	for (c = 0; c < mCoreCallbacksListSize(&video->p->coreCallbacks); ++c) {
358		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&video->p->coreCallbacks, c);
359		if (callbacks->videoFrameStarted) {
360			callbacks->videoFrameStarted(callbacks->context);
361		}
362	}
363}
364
365static void _cleanOAM(struct GBVideo* video, int y) {
366	// TODO: GBC differences
367	// TODO: Optimize
368	video->objMax = 0;
369	int spriteHeight = 8;
370	if (GBRegisterLCDCIsObjSize(video->p->memory.io[REG_LCDC])) {
371		spriteHeight = 16;
372	}
373	int o = 0;
374	int i;
375	for (i = 0; i < 40; ++i) {
376		uint8_t oy = video->oam.obj[i].y;
377		if (y < oy - 16 || y >= oy - 16 + spriteHeight) {
378			continue;
379		}
380		// TODO: Sort
381		video->objThisLine[o] = video->oam.obj[i];
382		++o;
383		if (o == 10) {
384			break;
385		}
386	}
387	video->objMax = o;
388}
389
390void GBVideoProcessDots(struct GBVideo* video) {
391	if (video->mode != 3) {
392		return;
393	}
394	int oldX = video->x;
395	video->x = (video->p->timing.masterCycles - video->dotClock + video->p->cpu->cycles) >> video->p->doubleSpeed;
396	if (video->x > GB_VIDEO_HORIZONTAL_PIXELS) {
397		video->x = GB_VIDEO_HORIZONTAL_PIXELS;
398	} else if (video->x < 0) {
399		mLOG(GB, FATAL, "Video dot clock went negative!");
400		video->x = oldX;
401	}
402	if (video->frameskipCounter <= 0) {
403		video->renderer->drawRange(video->renderer, oldX, video->x, video->ly, video->objThisLine, video->objMax);
404	}
405}
406
407void GBVideoWriteLCDC(struct GBVideo* video, GBRegisterLCDC value) {
408	if (!GBRegisterLCDCIsEnable(video->p->memory.io[REG_LCDC]) && GBRegisterLCDCIsEnable(value)) {
409		video->mode = 2;
410		video->modeEvent.callback = _endMode2;
411		int32_t next = GB_VIDEO_MODE_2_LENGTH - 5; // TODO: Why is this fudge factor needed? Might be related to T-cycles for load/store differing
412		mTimingSchedule(&video->p->timing, &video->modeEvent, next << video->p->doubleSpeed);
413
414		video->ly = 0;
415		video->p->memory.io[REG_LY] = 0;
416		// TODO: Does this read as 0 for 4 T-cycles?
417		GBRegisterSTAT oldStat = video->stat;
418		video->stat = GBRegisterSTATSetMode(video->stat, 2);
419		video->stat = GBRegisterSTATSetLYC(video->stat, video->ly == video->p->memory.io[REG_LYC]);
420		if (!_statIRQAsserted(video, oldStat) && _statIRQAsserted(video, video->stat)) {
421			video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
422			GBUpdateIRQs(video->p);
423		}
424		video->p->memory.io[REG_STAT] = video->stat;
425		video->renderer->writePalette(video->renderer, 0, video->palette[0]);
426
427		mTimingDeschedule(&video->p->timing, &video->frameEvent);
428	}
429	if (GBRegisterLCDCIsEnable(video->p->memory.io[REG_LCDC]) && !GBRegisterLCDCIsEnable(value)) {
430		// TODO: Fix serialization; this gets internal and visible modes out of sync
431		video->stat = GBRegisterSTATSetMode(video->stat, 0);
432		video->p->memory.io[REG_STAT] = video->stat;
433		video->ly = 0;
434		video->p->memory.io[REG_LY] = 0;
435		video->renderer->writePalette(video->renderer, 0, video->dmgPalette[0]);
436	
437		mTimingDeschedule(&video->p->timing, &video->modeEvent);
438		mTimingSchedule(&video->p->timing, &video->frameEvent, GB_VIDEO_TOTAL_LENGTH);
439	}
440	video->p->memory.io[REG_STAT] = video->stat;
441}
442
443void GBVideoWriteSTAT(struct GBVideo* video, GBRegisterSTAT value) {
444	GBRegisterSTAT oldStat = video->stat;
445	video->stat = (video->stat & 0x7) | (value & 0x78);
446	if (video->p->model < GB_MODEL_CGB && !_statIRQAsserted(video, oldStat) && video->mode < 3) {
447		// TODO: variable for the IRQ line value?
448		video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
449		GBUpdateIRQs(video->p);
450	}
451}
452
453void GBVideoWriteLYC(struct GBVideo* video, uint8_t value) {
454	GBRegisterSTAT oldStat = video->stat;
455	video->stat = GBRegisterSTATSetLYC(video->stat, value == video->ly);
456	if (!_statIRQAsserted(video, oldStat) && _statIRQAsserted(video, video->stat)) {
457		video->p->memory.io[REG_IF] |= (1 << GB_IRQ_LCDSTAT);
458		GBUpdateIRQs(video->p);
459	}
460	video->p->memory.io[REG_STAT] = video->stat;
461}
462
463void GBVideoWritePalette(struct GBVideo* video, uint16_t address, uint8_t value) {
464	if (video->p->model < GB_MODEL_SGB) {
465		switch (address) {
466		case REG_BGP:
467			video->palette[0] = video->dmgPalette[value & 3];
468			video->palette[1] = video->dmgPalette[(value >> 2) & 3];
469			video->palette[2] = video->dmgPalette[(value >> 4) & 3];
470			video->palette[3] = video->dmgPalette[(value >> 6) & 3];
471			video->renderer->writePalette(video->renderer, 0, video->palette[0]);
472			video->renderer->writePalette(video->renderer, 1, video->palette[1]);
473			video->renderer->writePalette(video->renderer, 2, video->palette[2]);
474			video->renderer->writePalette(video->renderer, 3, video->palette[3]);
475			break;
476		case REG_OBP0:
477			video->palette[8 * 4 + 0] = video->dmgPalette[value & 3];
478			video->palette[8 * 4 + 1] = video->dmgPalette[(value >> 2) & 3];
479			video->palette[8 * 4 + 2] = video->dmgPalette[(value >> 4) & 3];
480			video->palette[8 * 4 + 3] = video->dmgPalette[(value >> 6) & 3];
481			video->renderer->writePalette(video->renderer, 8 * 4 + 0, video->palette[8 * 4 + 0]);
482			video->renderer->writePalette(video->renderer, 8 * 4 + 1, video->palette[8 * 4 + 1]);
483			video->renderer->writePalette(video->renderer, 8 * 4 + 2, video->palette[8 * 4 + 2]);
484			video->renderer->writePalette(video->renderer, 8 * 4 + 3, video->palette[8 * 4 + 3]);
485			break;
486		case REG_OBP1:
487			video->palette[9 * 4 + 0] = video->dmgPalette[value & 3];
488			video->palette[9 * 4 + 1] = video->dmgPalette[(value >> 2) & 3];
489			video->palette[9 * 4 + 2] = video->dmgPalette[(value >> 4) & 3];
490			video->palette[9 * 4 + 3] = video->dmgPalette[(value >> 6) & 3];
491			video->renderer->writePalette(video->renderer, 9 * 4 + 0, video->palette[9 * 4 + 0]);
492			video->renderer->writePalette(video->renderer, 9 * 4 + 1, video->palette[9 * 4 + 1]);
493			video->renderer->writePalette(video->renderer, 9 * 4 + 2, video->palette[9 * 4 + 2]);
494			video->renderer->writePalette(video->renderer, 9 * 4 + 3, video->palette[9 * 4 + 3]);
495			break;
496		}
497	} else if (video->p->model == GB_MODEL_SGB) {
498		video->renderer->writeVideoRegister(video->renderer, address, value);
499	} else {
500		switch (address) {
501		case REG_BCPD:
502			if (video->bcpIndex & 1) {
503				video->palette[video->bcpIndex >> 1] &= 0x00FF;
504				video->palette[video->bcpIndex >> 1] |= value << 8;
505			} else {
506				video->palette[video->bcpIndex >> 1] &= 0xFF00;
507				video->palette[video->bcpIndex >> 1] |= value;
508			}
509			video->renderer->writePalette(video->renderer, video->bcpIndex >> 1, video->palette[video->bcpIndex >> 1]);
510			if (video->bcpIncrement) {
511				++video->bcpIndex;
512				video->bcpIndex &= 0x3F;
513				video->p->memory.io[REG_BCPS] &= 0x80;
514				video->p->memory.io[REG_BCPS] |= video->bcpIndex;
515			}
516			video->p->memory.io[REG_BCPD] = video->palette[video->bcpIndex >> 1] >> (8 * (video->bcpIndex & 1));
517			break;
518		case REG_OCPD:
519			if (video->ocpIndex & 1) {
520				video->palette[8 * 4 + (video->ocpIndex >> 1)] &= 0x00FF;
521				video->palette[8 * 4 + (video->ocpIndex >> 1)] |= value << 8;
522			} else {
523				video->palette[8 * 4 + (video->ocpIndex >> 1)] &= 0xFF00;
524				video->palette[8 * 4 + (video->ocpIndex >> 1)] |= value;
525			}
526			video->renderer->writePalette(video->renderer, 8 * 4 + (video->ocpIndex >> 1), video->palette[8 * 4 + (video->ocpIndex >> 1)]);
527			if (video->ocpIncrement) {
528				++video->ocpIndex;
529				video->ocpIndex &= 0x3F;
530				video->p->memory.io[REG_OCPS] &= 0x80;
531				video->p->memory.io[REG_OCPS] |= video->ocpIndex;
532			}
533			video->p->memory.io[REG_OCPD] = video->palette[8 * 4 + (video->ocpIndex >> 1)] >> (8 * (video->ocpIndex & 1));
534			break;
535		}
536	}
537}
538
539void GBVideoSwitchBank(struct GBVideo* video, uint8_t value) {
540	value &= 1;
541	video->vramBank = &video->vram[value * GB_SIZE_VRAM_BANK0];
542	video->vramCurrentBank = value;
543}
544
545void GBVideoSetPalette(struct GBVideo* video, unsigned index, uint32_t color) {
546	if (index >= 4) {
547		return;
548	}
549	video->dmgPalette[index] = M_RGB8_TO_RGB5(color);
550}
551
552void GBVideoWriteSGBPacket(struct GBVideo* video, uint8_t* data) {
553	int i;
554	if (!(video->sgbCommandHeader & 7)) {
555		video->sgbCommandHeader = data[0];
556	}
557	--video->sgbCommandHeader;
558	switch (video->sgbCommandHeader >> 3) {
559	case SGB_PAL01:
560		video->palette[0] = data[1] | (data[2] << 8);
561		video->palette[1] = data[3] | (data[4] << 8);
562		video->palette[2] = data[5] | (data[6] << 8);
563		video->palette[3] = data[7] | (data[8] << 8);
564
565		video->palette[17] = data[9] | (data[10] << 8);
566		video->palette[18] = data[11] | (data[12] << 8);
567		video->palette[19] = data[13] | (data[14] << 8);
568
569		video->renderer->writePalette(video->renderer, 0, video->palette[0]);
570		video->renderer->writePalette(video->renderer, 1, video->palette[1]);
571		video->renderer->writePalette(video->renderer, 2, video->palette[2]);
572		video->renderer->writePalette(video->renderer, 3, video->palette[3]);
573		video->renderer->writePalette(video->renderer, 16, video->palette[0]);
574		video->renderer->writePalette(video->renderer, 17, video->palette[17]);
575		video->renderer->writePalette(video->renderer, 18, video->palette[18]);
576		video->renderer->writePalette(video->renderer, 19, video->palette[19]);
577		video->renderer->writePalette(video->renderer, 32, video->palette[0]);
578		video->renderer->writePalette(video->renderer, 48, video->palette[0]);
579		break;
580	case SGB_PAL23:
581		video->palette[32] = data[1] | (data[2] << 8);
582		video->palette[33] = data[3] | (data[4] << 8);
583		video->palette[34] = data[5] | (data[6] << 8);
584		video->palette[35] = data[7] | (data[8] << 8);
585
586		video->palette[49] = data[9] | (data[10] << 8);
587		video->palette[50] = data[11] | (data[12] << 8);
588		video->palette[51] = data[13] | (data[14] << 8);
589		video->renderer->writePalette(video->renderer, 33, video->palette[33]);
590		video->renderer->writePalette(video->renderer, 34, video->palette[34]);
591		video->renderer->writePalette(video->renderer, 35, video->palette[35]);
592		video->renderer->writePalette(video->renderer, 49, video->palette[49]);
593		video->renderer->writePalette(video->renderer, 50, video->palette[50]);
594		video->renderer->writePalette(video->renderer, 51, video->palette[51]);
595		break;
596	case SGB_PAL03:
597		video->palette[0] = data[1] | (data[2] << 8);
598		video->palette[1] = data[3] | (data[4] << 8);
599		video->palette[2] = data[5] | (data[6] << 8);
600		video->palette[3] = data[7] | (data[8] << 8);
601
602		video->palette[48] = data[1] | (data[2] << 8);
603		video->palette[49] = data[9] | (data[10] << 8);
604		video->palette[50] = data[11] | (data[12] << 8);
605		video->palette[51] = data[13] | (data[14] << 8);
606		video->renderer->writePalette(video->renderer, 0, video->palette[0]);
607		video->renderer->writePalette(video->renderer, 1, video->palette[1]);
608		video->renderer->writePalette(video->renderer, 2, video->palette[2]);
609		video->renderer->writePalette(video->renderer, 3, video->palette[3]);
610		video->renderer->writePalette(video->renderer, 16, video->palette[0]);
611		video->renderer->writePalette(video->renderer, 32, video->palette[0]);
612		video->renderer->writePalette(video->renderer, 48, video->palette[0]);
613		video->renderer->writePalette(video->renderer, 49, video->palette[49]);
614		video->renderer->writePalette(video->renderer, 50, video->palette[50]);
615		video->renderer->writePalette(video->renderer, 51, video->palette[51]);
616		break;
617	case SGB_PAL12:
618		video->palette[16] = data[1] | (data[2] << 8);
619		video->palette[17] = data[3] | (data[4] << 8);
620		video->palette[18] = data[5] | (data[6] << 8);
621		video->palette[19] = data[7] | (data[8] << 8);
622
623		video->palette[33] = data[9] | (data[10] << 8);
624		video->palette[34] = data[11] | (data[12] << 8);
625		video->palette[35] = data[13] | (data[14] << 8);
626		video->renderer->writePalette(video->renderer, 17, video->palette[17]);
627		video->renderer->writePalette(video->renderer, 18, video->palette[18]);
628		video->renderer->writePalette(video->renderer, 19, video->palette[19]);
629		video->renderer->writePalette(video->renderer, 33, video->palette[33]);
630		video->renderer->writePalette(video->renderer, 34, video->palette[34]);
631		video->renderer->writePalette(video->renderer, 35, video->palette[35]);
632		break;
633	case SGB_PAL_SET:
634		for (i = 0; i < 4; ++i) {
635			uint16_t entry = (data[2 + (i * 2)] << 8) | data[1 + (i * 2)];
636			if (entry >= 0x200) {
637				mLOG(GB, STUB, "Unimplemented SGB palette overflow: %03X", entry);
638				continue;
639			}
640			LOAD_16LE(video->palette[i * 4 + 0], entry * 8 + 0, video->renderer->sgbPalRam);
641			video->renderer->writePalette(video->renderer, i * 4 + 0, video->palette[0]);
642			LOAD_16LE(video->palette[i * 4 + 1], entry * 8 + 2, video->renderer->sgbPalRam);
643			video->renderer->writePalette(video->renderer, i * 4 + 1, video->palette[i * 4 + 1]);
644			LOAD_16LE(video->palette[i * 4 + 2], entry * 8 + 4, video->renderer->sgbPalRam);
645			video->renderer->writePalette(video->renderer, i * 4 + 2, video->palette[i * 4 + 2]);
646			LOAD_16LE(video->palette[i * 4 + 3], entry * 8 + 6, video->renderer->sgbPalRam);
647			video->renderer->writePalette(video->renderer, i * 4 + 3, video->palette[i * 4 + 3]);
648		}
649		break;
650	case SGB_ATTR_BLK:
651	case SGB_PAL_TRN:
652	case SGB_CHR_TRN:
653	case SGB_PCT_TRN:
654	case SGB_ATTR_TRN:
655	case SGB_ATTR_SET:
656		break;
657	case SGB_MLT_REG:
658		return;
659	case SGB_MASK_EN:
660		video->renderer->sgbRenderMode = data[1] & 0x3;
661		break;
662	default:
663		mLOG(GB, STUB, "Unimplemented SGB command: %02X", data[0] >> 3);
664		return;
665	}
666	video->renderer->writeSGBPacket(video->renderer, data);
667}
668
669static void GBVideoDummyRendererInit(struct GBVideoRenderer* renderer, enum GBModel model) {
670	UNUSED(renderer);
671	UNUSED(model);
672	// Nothing to do
673}
674
675static void GBVideoDummyRendererDeinit(struct GBVideoRenderer* renderer) {
676	UNUSED(renderer);
677	// Nothing to do
678}
679
680static uint8_t GBVideoDummyRendererWriteVideoRegister(struct GBVideoRenderer* renderer, uint16_t address, uint8_t value) {
681	UNUSED(renderer);
682	UNUSED(address);
683	return value;
684}
685
686static void GBVideoDummyRendererWriteSGBPacket(struct GBVideoRenderer* renderer, uint8_t* data) {
687	UNUSED(renderer);
688	UNUSED(data);
689}
690
691static void GBVideoDummyRendererWriteVRAM(struct GBVideoRenderer* renderer, uint16_t address) {
692	if (renderer->cache) {
693		mTileCacheWriteVRAM(renderer->cache, address);
694	}
695}
696
697static void GBVideoDummyRendererWriteOAM(struct GBVideoRenderer* renderer, uint16_t oam) {
698	UNUSED(renderer);
699	UNUSED(oam);
700	// Nothing to do
701}
702
703static void GBVideoDummyRendererWritePalette(struct GBVideoRenderer* renderer, int index, uint16_t value) {
704	UNUSED(value);
705	if (renderer->cache) {
706		mTileCacheWritePalette(renderer->cache, index << 1);
707	}
708}
709
710static void GBVideoDummyRendererDrawRange(struct GBVideoRenderer* renderer, int startX, int endX, int y, struct GBObj* obj, size_t oamMax) {
711	UNUSED(renderer);
712	UNUSED(endX);
713	UNUSED(startX);
714	UNUSED(y);
715	UNUSED(obj);
716	UNUSED(oamMax);
717	// Nothing to do
718}
719
720static void GBVideoDummyRendererFinishScanline(struct GBVideoRenderer* renderer, int y) {
721	UNUSED(renderer);
722	UNUSED(y);
723	// Nothing to do
724}
725
726static void GBVideoDummyRendererFinishFrame(struct GBVideoRenderer* renderer) {
727	UNUSED(renderer);
728	// Nothing to do
729}
730
731static void GBVideoDummyRendererGetPixels(struct GBVideoRenderer* renderer, size_t* stride, const void** pixels) {
732	UNUSED(renderer);
733	UNUSED(stride);
734	UNUSED(pixels);
735	// Nothing to do
736}
737
738static void GBVideoDummyRendererPutPixels(struct GBVideoRenderer* renderer, size_t stride, const void* pixels) {
739	UNUSED(renderer);
740	UNUSED(stride);
741	UNUSED(pixels);
742	// Nothing to do
743}
744
745void GBVideoSerialize(const struct GBVideo* video, struct GBSerializedState* state) {
746	STORE_16LE(video->x, 0, &state->video.x);
747	STORE_16LE(video->ly, 0, &state->video.ly);
748	STORE_32LE(video->frameCounter, 0, &state->video.frameCounter);
749	state->video.vramCurrentBank = video->vramCurrentBank;
750
751	GBSerializedVideoFlags flags = 0;
752	flags = GBSerializedVideoFlagsSetBcpIncrement(flags, video->bcpIncrement);
753	flags = GBSerializedVideoFlagsSetOcpIncrement(flags, video->ocpIncrement);
754	flags = GBSerializedVideoFlagsSetMode(flags, video->mode);
755	flags = GBSerializedVideoFlagsSetNotModeEventScheduled(flags, !mTimingIsScheduled(&video->p->timing, &video->modeEvent));
756	flags = GBSerializedVideoFlagsSetNotFrameEventScheduled(flags, !mTimingIsScheduled(&video->p->timing, &video->frameEvent));
757	state->video.flags = flags;
758	STORE_16LE(video->bcpIndex, 0, &state->video.bcpIndex);
759	STORE_16LE(video->ocpIndex, 0, &state->video.ocpIndex);
760
761	size_t i;
762	for (i = 0; i < 64; ++i) {
763		STORE_16LE(video->palette[i], i * 2, state->video.palette);
764	}
765
766	STORE_32LE(video->modeEvent.when - mTimingCurrentTime(&video->p->timing), 0, &state->video.nextMode);
767	STORE_32LE(video->frameEvent.when - mTimingCurrentTime(&video->p->timing), 0, &state->video.nextFrame);
768
769	memcpy(state->vram, video->vram, GB_SIZE_VRAM);
770	memcpy(state->oam, &video->oam.raw, GB_SIZE_OAM);
771}
772
773void GBVideoDeserialize(struct GBVideo* video, const struct GBSerializedState* state) {
774	LOAD_16LE(video->x, 0, &state->video.x);
775	LOAD_16LE(video->ly, 0, &state->video.ly);
776	LOAD_32LE(video->frameCounter, 0, &state->video.frameCounter);
777	video->vramCurrentBank = state->video.vramCurrentBank;
778
779	GBSerializedVideoFlags flags = state->video.flags;
780	video->bcpIncrement = GBSerializedVideoFlagsGetBcpIncrement(flags);
781	video->ocpIncrement = GBSerializedVideoFlagsGetOcpIncrement(flags);
782	video->mode = GBSerializedVideoFlagsGetMode(flags);
783	LOAD_16LE(video->bcpIndex, 0, &state->video.bcpIndex);
784	video->bcpIndex &= 0x3F;
785	LOAD_16LE(video->ocpIndex, 0, &state->video.ocpIndex);
786	video->ocpIndex &= 0x3F;
787
788	switch (video->mode) {
789	case 0:
790		video->modeEvent.callback = _endMode0;
791		break;
792	case 1:
793		video->modeEvent.callback = _endMode1;
794		break;
795	case 2:
796		video->modeEvent.callback = _endMode2;
797		break;
798	case 3:
799		video->modeEvent.callback = _endMode3;
800		break;
801	}
802
803	uint32_t when;
804	if (!GBSerializedVideoFlagsIsNotModeEventScheduled(flags)) {
805		LOAD_32LE(when, 0, &state->video.nextMode);
806		mTimingSchedule(&video->p->timing, &video->modeEvent, when);
807	}
808	if (!GBSerializedVideoFlagsIsNotFrameEventScheduled(flags)) {
809		LOAD_32LE(when, 0, &state->video.nextFrame);
810		mTimingSchedule(&video->p->timing, &video->frameEvent, when);
811	}
812
813	size_t i;
814	for (i = 0; i < 64; ++i) {
815		LOAD_16LE(video->palette[i], i * 2, state->video.palette);
816		video->renderer->writePalette(video->renderer, i, video->palette[i]);
817	}
818
819	memcpy(video->vram, state->vram, GB_SIZE_VRAM);
820	memcpy(&video->oam.raw, state->oam, GB_SIZE_OAM);
821
822	_cleanOAM(video, video->ly);
823	GBVideoSwitchBank(video, video->vramCurrentBank);
824
825	video->renderer->deinit(video->renderer);
826	video->renderer->init(video->renderer, video->p->model);
827}