all repos — mgba @ 67905d281bfecbb06f51f2ca5ac939df378734a5

mGBA Game Boy Advance Emulator

src/feature/gui/gui-runner.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 "gui-runner.h"
  7
  8#include "core/core.h"
  9#include "core/serialize.h"
 10#include "feature/gui/gui-config.h"
 11#include "gba/gba.h"
 12#include "gba/input.h"
 13#include "gba/interface.h"
 14#include "util/gui/file-select.h"
 15#include "util/gui/font.h"
 16#include "util/gui/menu.h"
 17#include "util/memory.h"
 18#include "util/png-io.h"
 19#include "util/vfs.h"
 20
 21#ifdef _3DS
 22#include <3ds.h>
 23#endif
 24
 25#include <sys/time.h>
 26
 27#define FPS_GRANULARITY 120
 28#define FPS_BUFFER_SIZE 3
 29
 30enum {
 31	RUNNER_CONTINUE = 1,
 32	RUNNER_EXIT,
 33	RUNNER_SAVE_STATE,
 34	RUNNER_LOAD_STATE,
 35	RUNNER_SCREENSHOT,
 36	RUNNER_CONFIG,
 37	RUNNER_RESET,
 38	RUNNER_COMMAND_MASK = 0xFFFF,
 39
 40	RUNNER_STATE_1 = 0x10000,
 41	RUNNER_STATE_2 = 0x20000,
 42	RUNNER_STATE_3 = 0x30000,
 43	RUNNER_STATE_4 = 0x40000,
 44	RUNNER_STATE_5 = 0x50000,
 45	RUNNER_STATE_6 = 0x60000,
 46	RUNNER_STATE_7 = 0x70000,
 47	RUNNER_STATE_8 = 0x80000,
 48	RUNNER_STATE_9 = 0x90000,
 49};
 50
 51static void _drawBackground(struct GUIBackground* background, void* context) {
 52	UNUSED(context);
 53	struct mGUIBackground* gbaBackground = (struct mGUIBackground*) background;
 54	if (gbaBackground->p->drawFrame) {
 55		gbaBackground->p->drawFrame(gbaBackground->p, true);
 56	}
 57}
 58
 59static void _drawState(struct GUIBackground* background, void* id) {
 60	struct mGUIBackground* gbaBackground = (struct mGUIBackground*) background;
 61	int stateId = ((int) id) >> 16;
 62	if (gbaBackground->p->drawScreenshot) {
 63		if (gbaBackground->screenshot && gbaBackground->screenshotId == (int) id) {
 64			gbaBackground->p->drawScreenshot(gbaBackground->p, gbaBackground->screenshot, true);
 65			return;
 66		}
 67		struct VFile* vf = mCoreGetState(gbaBackground->p->core, stateId, false);
 68		unsigned w, h;
 69		gbaBackground->p->core->desiredVideoDimensions(gbaBackground->p->core, &w, &h);
 70		uint32_t* pixels = gbaBackground->screenshot;
 71		if (!pixels) {
 72			pixels = anonymousMemoryMap(w * h * 4);
 73			gbaBackground->screenshot = pixels;
 74		}
 75		bool success = false;
 76		if (vf && isPNG(vf) && pixels) {
 77			png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
 78			png_infop info = png_create_info_struct(png);
 79			png_infop end = png_create_info_struct(png);
 80			if (png && info && end) {
 81				success = PNGReadHeader(png, info);
 82				success = success && PNGReadPixels(png, info, pixels, w, h, w);
 83				success = success && PNGReadFooter(png, end);
 84			}
 85			PNGReadClose(png, info, end);
 86		}
 87		if (vf) {
 88			vf->close(vf);
 89		}
 90		if (success) {
 91			gbaBackground->p->drawScreenshot(gbaBackground->p, pixels, true);
 92			gbaBackground->screenshotId = (int) id;
 93		} else if (gbaBackground->p->drawFrame) {
 94			gbaBackground->p->drawFrame(gbaBackground->p, true);
 95		}
 96	}
 97}
 98
 99static void _updateLux(struct GBALuminanceSource* lux) {
100	UNUSED(lux);
101}
102
103static uint8_t _readLux(struct GBALuminanceSource* lux) {
104	struct mGUIRunnerLux* runnerLux = (struct mGUIRunnerLux*) lux;
105	int value = 0x16;
106	if (runnerLux->luxLevel > 0) {
107		value += GBA_LUX_LEVELS[runnerLux->luxLevel - 1];
108	}
109	return 0xFF - value;
110}
111
112void mGUIInit(struct mGUIRunner* runner, const char* port) {
113	GUIInit(&runner->params);
114	runner->port = port;
115	runner->core = NULL;
116	runner->luminanceSource.d.readLuminance = _readLux;
117	runner->luminanceSource.d.sample = _updateLux;
118	runner->luminanceSource.luxLevel = 0;
119	runner->background.d.draw = _drawBackground;
120	runner->background.p = runner;
121	runner->fps = 0;
122	runner->lastFpsCheck = 0;
123	runner->totalDelta = 0;
124	CircleBufferInit(&runner->fpsBuffer, FPS_BUFFER_SIZE * sizeof(uint32_t));
125}
126
127void mGUIDeinit(struct mGUIRunner* runner) {
128	if (runner->teardown) {
129		runner->teardown(runner);
130	}
131	CircleBufferDeinit(&runner->fpsBuffer);
132}
133
134void mGUIRun(struct mGUIRunner* runner, const char* path) {
135	struct mGUIBackground drawState = {
136		.d = {
137			.draw = _drawState
138		},
139		.p = runner,
140		.screenshot = 0,
141		.screenshotId = 0
142	};
143	struct GUIMenu pauseMenu = {
144		.title = "Game Paused",
145		.index = 0,
146		.background = &runner->background.d
147	};
148	struct GUIMenu stateSaveMenu = {
149		.title = "Save state",
150		.index = 0,
151		.background = &drawState.d
152	};
153	struct GUIMenu stateLoadMenu = {
154		.title = "Load state",
155		.index = 0,
156		.background = &drawState.d
157	};
158	GUIMenuItemListInit(&pauseMenu.items, 0);
159	GUIMenuItemListInit(&stateSaveMenu.items, 9);
160	GUIMenuItemListInit(&stateLoadMenu.items, 9);
161	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Unpause", .data = (void*) RUNNER_CONTINUE };
162	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Save state", .submenu = &stateSaveMenu };
163	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Load state", .submenu = &stateLoadMenu };
164
165	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 1", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_1) };
166	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 2", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_2) };
167	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 3", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_3) };
168	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 4", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_4) };
169	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 5", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_5) };
170	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 6", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_6) };
171	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 7", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_7) };
172	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 8", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_8) };
173	*GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 9", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE_9) };
174
175	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 1", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_1) };
176	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 2", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_2) };
177	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 3", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_3) };
178	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 4", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_4) };
179	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 5", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_5) };
180	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 6", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_6) };
181	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 7", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_7) };
182	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 8", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_8) };
183	*GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 9", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE_9) };
184
185	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Take screenshot", .data = (void*) RUNNER_SCREENSHOT };
186	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Configure", .data = (void*) RUNNER_CONFIG };
187	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Reset game", .data = (void*) RUNNER_RESET };
188	*GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Exit game", .data = (void*) RUNNER_EXIT };
189
190	// TODO: Message box API
191	runner->params.drawStart();
192	if (runner->params.guiPrepare) {
193		runner->params.guiPrepare();
194	}
195	GUIFontPrint(runner->params.font, runner->params.width / 2, (GUIFontHeight(runner->params.font) + runner->params.height) / 2, GUI_ALIGN_HCENTER, 0xFFFFFFFF, "Loading...");
196	if (runner->params.guiFinish) {
197		runner->params.guiFinish();
198	}
199	runner->params.drawEnd();
200
201	bool found = false;
202	runner->core = mCoreFind(path);
203	if (runner->core) {
204		runner->core->init(runner->core);
205		mInputMapInit(&runner->core->inputMap, &GBAInputInfo);
206		mCoreInitConfig(runner->core, runner->port);
207		found = mCoreLoadFile(runner->core, path);
208		if (!found) {
209			runner->core->deinit(runner->core);
210		}
211	}
212
213	if (!found) {
214		int i;
215		for (i = 0; i < 240; ++i) {
216			runner->params.drawStart();
217			if (runner->params.guiPrepare) {
218				runner->params.guiPrepare();
219			}
220			GUIFontPrint(runner->params.font, runner->params.width / 2, (GUIFontHeight(runner->params.font) + runner->params.height) / 2, GUI_ALIGN_HCENTER, 0xFFFFFFFF, "Load failed!");
221			if (runner->params.guiFinish) {
222				runner->params.guiFinish();
223			}
224			runner->params.drawEnd();
225		}
226		return;
227	}
228	if (runner->core->platform(runner->core) == PLATFORM_GBA) {
229		((struct GBA*) runner->core->board)->luminanceSource = &runner->luminanceSource.d;
230	}
231	if (runner->core->config.port && runner->keySources) {
232		size_t i;
233		for (i = 0; runner->keySources[i].id; ++i) {
234			mInputMapLoad(&runner->core->inputMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->core->config));
235		}
236	}
237	// TODO: Do we need to load more defaults?
238	mCoreConfigSetDefaultIntValue(&runner->core->config, "volume", 0x100);
239	mCoreConfigSetDefaultValue(&runner->core->config, "idleOptimization", "detect");
240	mCoreLoadConfig(runner->core);
241	mCoreAutoloadSave(runner->core);
242	if (runner->setup) {
243		runner->setup(runner);
244	}
245	runner->core->reset(runner->core);
246	bool running = true;
247	if (runner->gameLoaded) {
248		runner->gameLoaded(runner);
249	}
250	while (running) {
251		CircleBufferClear(&runner->fpsBuffer);
252		runner->totalDelta = 0;
253		runner->fps = 0;
254		struct timeval tv;
255		gettimeofday(&tv, 0);
256		runner->lastFpsCheck = 1000000LL * tv.tv_sec + tv.tv_usec;
257
258		while (true) {
259#ifdef _3DS
260			running = aptMainLoop();
261			if (!running) {
262				break;
263			}
264#endif
265			uint32_t guiKeys;
266			GUIPollInput(&runner->params, &guiKeys, 0);
267			if (guiKeys & (1 << GUI_INPUT_CANCEL)) {
268				break;
269			}
270			if (guiKeys & (1 << mGUI_INPUT_INCREASE_BRIGHTNESS)) {
271				if (runner->luminanceSource.luxLevel < 10) {
272					++runner->luminanceSource.luxLevel;
273				}
274			}
275			if (guiKeys & (1 << mGUI_INPUT_DECREASE_BRIGHTNESS)) {
276				if (runner->luminanceSource.luxLevel > 0) {
277					--runner->luminanceSource.luxLevel;
278				}
279			}
280			if (guiKeys & (1 << mGUI_INPUT_SCREEN_MODE) && runner->incrementScreenMode) {
281				runner->incrementScreenMode(runner);
282			}
283			uint16_t keys = runner->pollGameInput(runner);
284			if (runner->prepareForFrame) {
285				runner->prepareForFrame(runner);
286			}
287			runner->core->setKeys(runner->core, keys);
288			runner->core->runFrame(runner->core);
289			if (runner->drawFrame) {
290				int drawFps = false;
291				mCoreConfigGetIntValue(&runner->core->config, "fpsCounter", &drawFps);
292
293				runner->params.drawStart();
294				runner->drawFrame(runner, false);
295				if (drawFps) {
296					if (runner->params.guiPrepare) {
297						runner->params.guiPrepare();
298					}
299					GUIFontPrintf(runner->params.font, 0, GUIFontHeight(runner->params.font), GUI_ALIGN_LEFT, 0x7FFFFFFF, "%.2f fps", runner->fps);
300					if (runner->params.guiFinish) {
301						runner->params.guiFinish();
302					}
303				}
304				runner->params.drawEnd();
305
306				if (runner->core->frameCounter(runner->core) % FPS_GRANULARITY == 0) {
307					if (drawFps) {
308						struct timeval tv;
309						gettimeofday(&tv, 0);
310						uint64_t t = 1000000LL * tv.tv_sec + tv.tv_usec;
311						uint64_t delta = t - runner->lastFpsCheck;
312						runner->lastFpsCheck = t;
313						if (delta > 0x7FFFFFFFLL) {
314							CircleBufferClear(&runner->fpsBuffer);
315							runner->fps = 0;
316						}
317						if (CircleBufferSize(&runner->fpsBuffer) == CircleBufferCapacity(&runner->fpsBuffer)) {
318							int32_t last;
319							CircleBufferRead32(&runner->fpsBuffer, &last);
320							runner->totalDelta -= last;
321						}
322						CircleBufferWrite32(&runner->fpsBuffer, delta);
323						runner->totalDelta += delta;
324						runner->fps = (CircleBufferSize(&runner->fpsBuffer) * FPS_GRANULARITY * 1000000.0f) / (runner->totalDelta * sizeof(uint32_t));
325					}
326				}
327			}
328		}
329
330		if (runner->paused) {
331			runner->paused(runner);
332		}
333		GUIInvalidateKeys(&runner->params);
334		uint32_t keys = 0xFFFFFFFF; // Huge hack to avoid an extra variable!
335		struct GUIMenuItem* item;
336		enum GUIMenuExitReason reason = GUIShowMenu(&runner->params, &pauseMenu, &item);
337		if (reason == GUI_MENU_EXIT_ACCEPT) {
338			switch (((int) item->data) & RUNNER_COMMAND_MASK) {
339			case RUNNER_EXIT:
340				running = false;
341				keys = 0;
342				break;
343			case RUNNER_RESET:
344				runner->core->reset(runner->core);
345				break;
346			case RUNNER_SAVE_STATE:
347				mCoreSaveState(runner->core, ((int) item->data) >> 16, SAVESTATE_SCREENSHOT);
348				break;
349			case RUNNER_LOAD_STATE:
350				mCoreLoadState(runner->core, ((int) item->data) >> 16, SAVESTATE_SCREENSHOT);
351				break;
352			case RUNNER_SCREENSHOT:
353				mCoreTakeScreenshot(runner->core);
354				break;
355			case RUNNER_CONFIG:
356				mGUIShowConfig(runner, runner->configExtra, runner->nConfigExtra);
357				mCoreLoadConfig(runner->core);
358				break;
359			case RUNNER_CONTINUE:
360				break;
361			}
362		}
363		int frames = 0;
364		GUIPollInput(&runner->params, 0, &keys);
365		while (keys && frames < 30) {
366			++frames;
367			runner->params.drawStart();
368			runner->drawFrame(runner, true);
369			runner->params.drawEnd();
370			GUIPollInput(&runner->params, 0, &keys);
371		}
372		if (runner->unpaused) {
373			runner->unpaused(runner);
374		}
375	}
376	if (runner->gameUnloaded) {
377		runner->gameUnloaded(runner);
378	}
379	runner->core->unloadROM(runner->core);
380	drawState.screenshotId = 0;
381	if (drawState.screenshot) {
382		unsigned w, h;
383		runner->core->desiredVideoDimensions(runner->core, &w, &h);
384		mappedMemoryFree(drawState.screenshot, w * h * 4);
385	}
386
387	if (runner->core->config.port) {
388		if (runner->keySources) {
389			size_t i;
390			for (i = 0; runner->keySources[i].id; ++i) {
391				mInputMapSave(&runner->core->inputMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->core->config));
392			}
393		}
394		mCoreConfigSave(&runner->core->config);
395	}
396	runner->core->deinit(runner->core);
397
398	GUIMenuItemListDeinit(&pauseMenu.items);
399	GUIMenuItemListDeinit(&stateSaveMenu.items);
400	GUIMenuItemListDeinit(&stateLoadMenu.items);
401}
402
403void mGUIRunloop(struct mGUIRunner* runner) {
404	while (true) {
405		char path[PATH_MAX];
406		if (!GUISelectFile(&runner->params, path, sizeof(path), 0)) {
407			break;
408		}
409		mGUIRun(runner, path);
410	}
411}