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 <mgba/core/core.h>
9#include <mgba/core/serialize.h>
10#include "feature/gui/gui-config.h"
11#include <mgba/internal/gba/gba.h>
12#include <mgba/internal/gba/input.h>
13#include <mgba/gba/interface.h>
14#include <mgba-util/gui/file-select.h>
15#include <mgba-util/gui/font.h>
16#include <mgba-util/gui/menu.h>
17#include <mgba-util/memory.h>
18#include <mgba-util/png-io.h>
19#include <mgba-util/vfs.h>
20
21#include <sys/time.h>
22
23mLOG_DECLARE_CATEGORY(GUI_RUNNER);
24mLOG_DEFINE_CATEGORY(GUI_RUNNER, "GUI Runner", "gui.runner");
25
26#define AUTOSAVE_GRANULARITY 600
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
41#define RUNNER_STATE(X) ((X) << 16)
42
43static const struct mInputPlatformInfo _mGUIKeyInfo = {
44 .platformName = "gui",
45 .keyId = (const char*[GUI_INPUT_MAX]) {
46 "Select",
47 "Back",
48 "Cancel",
49 "Up",
50 "Down",
51 "Left",
52 "Right",
53 [mGUI_INPUT_INCREASE_BRIGHTNESS] = "Increase solar brightness",
54 [mGUI_INPUT_DECREASE_BRIGHTNESS] = "Decrease solar brightness",
55 [mGUI_INPUT_SCREEN_MODE] = "Screen mode",
56 [mGUI_INPUT_SCREENSHOT] = "Take screenshot",
57 [mGUI_INPUT_FAST_FORWARD_HELD] = "Fast forward (held)",
58 [mGUI_INPUT_FAST_FORWARD_TOGGLE] = "Fast forward (toggle)",
59 [mGUI_INPUT_MUTE_TOGGLE] = "Mute (toggle)",
60 },
61 .nKeys = GUI_INPUT_MAX
62};
63
64static void _log(struct mLogger*, int category, enum mLogLevel level, const char* format, va_list args);
65
66static struct mGUILogger {
67 struct mLogger d;
68 struct VFile* vf;
69 int logLevel;
70} logger = {
71 .d = {
72 .log = _log
73 },
74 .vf = NULL,
75 .logLevel = 0
76};
77
78static bool _testExtensions(const char* name) {
79 char ext[PATH_MAX] = {};
80 separatePath(name, NULL, NULL, ext);
81
82 if (!strncmp(ext, "sav", PATH_MAX)) {
83 return false;
84 }
85 if (!strncmp(ext, "png", PATH_MAX)) {
86 return false;
87 }
88 if (!strncmp(ext, "ini", PATH_MAX)) {
89 return false;
90 }
91 if (!strncmp(ext, "ss", 2)) {
92 return false;
93 }
94
95 return true;
96}
97
98static void _drawBackground(struct GUIBackground* background, void* context) {
99 UNUSED(context);
100 struct mGUIBackground* gbaBackground = (struct mGUIBackground*) background;
101 if (gbaBackground->p->drawFrame) {
102 gbaBackground->p->drawFrame(gbaBackground->p, true);
103 }
104}
105
106static void _drawState(struct GUIBackground* background, void* id) {
107 struct mGUIBackground* gbaBackground = (struct mGUIBackground*) background;
108 int stateId = ((int) id) >> 16;
109 if (gbaBackground->p->drawScreenshot) {
110 unsigned w, h;
111 gbaBackground->p->core->desiredVideoDimensions(gbaBackground->p->core, &w, &h);
112 if (gbaBackground->screenshot && gbaBackground->screenshotId == (int) id) {
113 gbaBackground->p->drawScreenshot(gbaBackground->p, gbaBackground->screenshot, w, h, true);
114 return;
115 }
116 struct VFile* vf = mCoreGetState(gbaBackground->p->core, stateId, false);
117 color_t* pixels = gbaBackground->screenshot;
118 if (!pixels) {
119 pixels = anonymousMemoryMap(w * h * 4);
120 gbaBackground->screenshot = pixels;
121 }
122 bool success = false;
123 if (vf && isPNG(vf) && pixels) {
124 png_structp png = PNGReadOpen(vf, PNG_HEADER_BYTES);
125 png_infop info = png_create_info_struct(png);
126 png_infop end = png_create_info_struct(png);
127 if (png && info && end) {
128 success = PNGReadHeader(png, info);
129 success = success && PNGReadPixels(png, info, pixels, w, h, w);
130 success = success && PNGReadFooter(png, end);
131 }
132 PNGReadClose(png, info, end);
133 }
134 if (vf) {
135 vf->close(vf);
136 }
137 if (success) {
138 gbaBackground->p->drawScreenshot(gbaBackground->p, pixels, w, h, true);
139 gbaBackground->screenshotId = (int) id;
140 } else if (gbaBackground->p->drawFrame) {
141 gbaBackground->p->drawFrame(gbaBackground->p, true);
142 }
143 }
144}
145
146static void _updateLux(struct GBALuminanceSource* lux) {
147 UNUSED(lux);
148}
149
150static uint8_t _readLux(struct GBALuminanceSource* lux) {
151 struct mGUIRunnerLux* runnerLux = (struct mGUIRunnerLux*) lux;
152 int value = 0x16;
153 if (runnerLux->luxLevel > 0) {
154 value += GBA_LUX_LEVELS[runnerLux->luxLevel - 1];
155 }
156 return 0xFF - value;
157}
158
159static void _tryAutosave(struct mGUIRunner* runner) {
160 int autosave = false;
161 mCoreConfigGetIntValue(&runner->config, "autosave", &autosave);
162 if (!autosave) {
163 return;
164 }
165
166#ifdef DISABLE_THREADING
167 mCoreSaveState(runner->core, 0, SAVESTATE_SAVEDATA | SAVESTATE_RTC | SAVESTATE_METADATA);
168#else
169 if (!runner->autosave.buffer) {
170 runner->autosave.buffer = VFileMemChunk(NULL, 0);
171 }
172 MutexLock(&runner->autosave.mutex);
173 runner->autosave.core = runner->core;
174 mCoreSaveStateNamed(runner->core, runner->autosave.buffer, SAVESTATE_SAVEDATA | SAVESTATE_RTC | SAVESTATE_METADATA);
175 ConditionWake(&runner->autosave.cond);
176 MutexUnlock(&runner->autosave.mutex);
177#endif
178}
179
180void mGUIInit(struct mGUIRunner* runner, const char* port) {
181 GUIInit(&runner->params);
182 runner->port = port;
183 runner->core = NULL;
184 runner->luminanceSource.d.readLuminance = _readLux;
185 runner->luminanceSource.d.sample = _updateLux;
186 runner->luminanceSource.luxLevel = 0;
187 runner->background.d.draw = _drawBackground;
188 runner->background.p = runner;
189 runner->fps = 0;
190 runner->lastFpsCheck = 0;
191 runner->totalDelta = 0;
192 CircleBufferInit(&runner->fpsBuffer, FPS_BUFFER_SIZE * sizeof(uint32_t));
193
194 mInputMapInit(&runner->params.keyMap, &_mGUIKeyInfo);
195 mCoreConfigInit(&runner->config, runner->port);
196 // TODO: Do we need to load more defaults?
197 mCoreConfigSetDefaultIntValue(&runner->config, "volume", 0x100);
198 mCoreConfigSetDefaultValue(&runner->config, "idleOptimization", "detect");
199 mCoreConfigSetDefaultIntValue(&runner->config, "autoload", true);
200#ifdef DISABLE_THREADING
201 mCoreConfigSetDefaultIntValue(&runner->config, "autosave", false);
202#else
203 mCoreConfigSetDefaultIntValue(&runner->config, "autosave", true);
204#endif
205 mCoreConfigSetDefaultIntValue(&runner->config, "showOSD", true);
206 mCoreConfigLoad(&runner->config);
207 mCoreConfigGetIntValue(&runner->config, "logLevel", &logger.logLevel);
208
209 char path[PATH_MAX];
210 mCoreConfigDirectory(path, PATH_MAX);
211 strncat(path, PATH_SEP "log", PATH_MAX - strlen(path));
212 logger.vf = VFileOpen(path, O_CREAT | O_WRONLY | O_APPEND);
213 mLogSetDefaultLogger(&logger.d);
214
215 const char* lastPath = mCoreConfigGetValue(&runner->config, "lastDirectory");
216 if (lastPath) {
217 struct VDir* dir = VDirOpen(lastPath);
218 if (dir) {
219 dir->close(dir);
220 strncpy(runner->params.currentPath, lastPath, PATH_MAX - 1);
221 runner->params.currentPath[PATH_MAX - 1] = '\0';
222 }
223 }
224
225#ifndef DISABLE_THREADING
226 if (!runner->autosave.running) {
227 runner->autosave.running = true;
228 runner->autosave.core = NULL;
229 MutexInit(&runner->autosave.mutex);
230 ConditionInit(&runner->autosave.cond);
231 ThreadCreate(&runner->autosave.thread, mGUIAutosaveThread, &runner->autosave);
232 }
233#endif
234}
235
236void mGUIDeinit(struct mGUIRunner* runner) {
237#ifndef DISABLE_THREADING
238 MutexLock(&runner->autosave.mutex);
239 runner->autosave.running = false;
240 ConditionWake(&runner->autosave.cond);
241 MutexUnlock(&runner->autosave.mutex);
242
243 ThreadJoin(&runner->autosave.thread);
244
245 ConditionDeinit(&runner->autosave.cond);
246 MutexDeinit(&runner->autosave.mutex);
247
248 if (runner->autosave.buffer) {
249 runner->autosave.buffer->close(runner->autosave.buffer);
250 }
251#endif
252
253 if (runner->teardown) {
254 runner->teardown(runner);
255 }
256 CircleBufferDeinit(&runner->fpsBuffer);
257 mInputMapDeinit(&runner->params.keyMap);
258 mCoreConfigDeinit(&runner->config);
259 if (logger.vf) {
260 logger.vf->close(logger.vf);
261 logger.vf = NULL;
262 }
263}
264
265static void _log(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
266 struct mGUILogger* guiLogger = (struct mGUILogger*) logger;
267 if (!guiLogger->vf) {
268 return;
269 }
270 if (!(guiLogger->logLevel & level)) {
271 return;
272 }
273
274 char log[256] = {0};
275 vsnprintf(log, sizeof(log) - 1, format, args);
276 char log2[256] = {0};
277 size_t len = snprintf(log2, sizeof(log2) - 1, "%s: %s\n", mLogCategoryName(category), log);
278 if (len >= sizeof(log2)) {
279 len = sizeof(log2) - 1;
280 }
281 if (guiLogger->vf->write(guiLogger->vf, log2, len) < 0) {
282 char path[PATH_MAX];
283 mCoreConfigDirectory(path, PATH_MAX);
284 strncat(path, PATH_SEP "log", PATH_MAX - strlen(path));
285 guiLogger->vf->close(guiLogger->vf);
286 guiLogger->vf = VFileOpen(path, O_CREAT | O_WRONLY | O_APPEND);
287 if (guiLogger->vf->write(guiLogger->vf, log2, len) < 0) {
288 guiLogger->vf->close(guiLogger->vf);
289 guiLogger->vf = NULL;
290 }
291 }
292#ifdef GEKKO
293 puts(log2);
294#endif
295}
296
297static void _updateLoading(size_t read, size_t size, void* context) {
298 struct mGUIRunner* runner = context;
299 runner->params.drawStart();
300 if (runner->params.guiPrepare) {
301 runner->params.guiPrepare();
302 }
303 GUIFontPrintf(runner->params.font, runner->params.width / 2, (GUIFontHeight(runner->params.font) + runner->params.height) / 2, GUI_ALIGN_HCENTER, 0xFFFFFFFF, "Loading...%i%%", 100 * read / size);
304 if (runner->params.guiFinish) {
305 runner->params.guiFinish();
306 }
307 runner->params.drawEnd();
308}
309
310void mGUIRun(struct mGUIRunner* runner, const char* path) {
311 struct mGUIBackground drawState = {
312 .d = {
313 .draw = _drawState
314 },
315 .p = runner,
316 .screenshot = 0,
317 .screenshotId = 0
318 };
319 struct GUIMenu pauseMenu = {
320 .title = "Game Paused",
321 .index = 0,
322 .background = &runner->background.d
323 };
324 struct GUIMenu stateSaveMenu = {
325 .title = "Save state",
326 .index = 0,
327 .background = &drawState.d
328 };
329 struct GUIMenu stateLoadMenu = {
330 .title = "Load state",
331 .index = 0,
332 .background = &drawState.d
333 };
334 GUIMenuItemListInit(&pauseMenu.items, 0);
335 GUIMenuItemListInit(&stateSaveMenu.items, 9);
336 GUIMenuItemListInit(&stateLoadMenu.items, 9);
337 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Unpause", .data = (void*) RUNNER_CONTINUE };
338 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Save state", .submenu = &stateSaveMenu };
339 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Load state", .submenu = &stateLoadMenu };
340
341 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 1", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(1)) };
342 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 2", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(2)) };
343 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 3", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(3)) };
344 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 4", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(4)) };
345 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 5", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(5)) };
346 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 6", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(6)) };
347 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 7", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(7)) };
348 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 8", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(8)) };
349 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 9", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(9)) };
350
351 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "Autosave", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(0)) };
352 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 1", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(1)) };
353 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 2", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(2)) };
354 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 3", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(3)) };
355 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 4", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(4)) };
356 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 5", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(5)) };
357 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 6", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(6)) };
358 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 7", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(7)) };
359 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 8", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(8)) };
360 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 9", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(9)) };
361
362 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Take screenshot", .data = (void*) RUNNER_SCREENSHOT };
363 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Configure", .data = (void*) RUNNER_CONFIG };
364 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Reset game", .data = (void*) RUNNER_RESET };
365 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Exit game", .data = (void*) RUNNER_EXIT };
366
367 runner->params.drawStart();
368 if (runner->params.guiPrepare) {
369 runner->params.guiPrepare();
370 }
371 GUIFontPrint(runner->params.font, runner->params.width / 2, (GUIFontHeight(runner->params.font) + runner->params.height) / 2, GUI_ALIGN_HCENTER, 0xFFFFFFFF, "Loading...");
372 if (runner->params.guiFinish) {
373 runner->params.guiFinish();
374 }
375 runner->params.drawEnd();
376
377 bool found = false;
378 mLOG(GUI_RUNNER, INFO, "Attempting to load %s", path);
379 runner->core = mCoreFind(path);
380 if (runner->core) {
381 mLOG(GUI_RUNNER, INFO, "Found core");
382 runner->core->init(runner->core);
383 mCoreInitConfig(runner->core, runner->port);
384 mInputMapInit(&runner->core->inputMap, &GBAInputInfo);
385
386 struct VFile* rom = mDirectorySetOpenPath(&runner->core->dirs, path, runner->core->isROM);
387 if (runner->setFrameLimiter) {
388 runner->setFrameLimiter(runner, false);
389 }
390 found = mCorePreloadVFCB(runner->core, rom, _updateLoading, runner);
391 if (runner->setFrameLimiter) {
392 runner->setFrameLimiter(runner, true);
393 }
394
395#ifdef FIXED_ROM_BUFFER
396 extern size_t romBufferSize;
397 if (!found && rom && (size_t) rom->size(rom) > romBufferSize) {
398 found = runner->core->loadROM(runner->core, rom);
399 }
400#endif
401 if (!found) {
402 if (rom) {
403 rom->close(rom);
404 }
405 mLOG(GUI_RUNNER, WARN, "Failed to load %s!", path);
406 mCoreConfigDeinit(&runner->core->config);
407 runner->core->deinit(runner->core);
408 }
409 }
410
411 if (!found) {
412 mLOG(GUI_RUNNER, WARN, "Failed to find core for %s!", path);
413 GUIShowMessageBox(&runner->params, GUI_MESSAGE_BOX_OK, 240, "Load failed!");
414 return;
415 }
416 if (runner->core->platform(runner->core) == mPLATFORM_GBA) {
417 runner->core->setPeripheral(runner->core, mPERIPH_GBA_LUMINANCE, &runner->luminanceSource.d);
418 }
419 mLOG(GUI_RUNNER, DEBUG, "Loading config...");
420 mCoreLoadForeignConfig(runner->core, &runner->config);
421
422 mLOG(GUI_RUNNER, DEBUG, "Loading save...");
423 mCoreAutoloadSave(runner->core);
424 mCoreAutoloadCheats(runner->core);
425 if (runner->setup) {
426 mLOG(GUI_RUNNER, DEBUG, "Setting up runner...");
427 runner->setup(runner);
428 }
429 if (runner->config.port && runner->keySources) {
430 mLOG(GUI_RUNNER, DEBUG, "Loading key sources for %s...", runner->config.port);
431 size_t i;
432 for (i = 0; runner->keySources[i].id; ++i) {
433 mInputMapLoad(&runner->core->inputMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
434 }
435 }
436 mLOG(GUI_RUNNER, DEBUG, "Reseting...");
437 runner->core->reset(runner->core);
438 mLOG(GUI_RUNNER, DEBUG, "Reset!");
439
440
441 int autoload = false;
442 mCoreConfigGetIntValue(&runner->config, "autoload", &autoload);
443 if (autoload) {
444 mCoreLoadState(runner->core, 0, SAVESTATE_SCREENSHOT | SAVESTATE_RTC);
445 }
446
447 int showOSD = true;
448 mCoreConfigGetIntValue(&runner->config, "showOSD", &showOSD);
449
450 int drawFps = false;
451 mCoreConfigGetIntValue(&runner->config, "fpsCounter", &drawFps);
452
453 bool running = true;
454
455#ifndef DISABLE_THREADING
456 MutexLock(&runner->autosave.mutex);
457 runner->autosave.core = runner->core;
458 MutexUnlock(&runner->autosave.mutex);
459#endif
460
461 if (runner->gameLoaded) {
462 runner->gameLoaded(runner);
463 }
464 mLOG(GUI_RUNNER, INFO, "Game starting");
465 while (running) {
466 CircleBufferClear(&runner->fpsBuffer);
467 runner->totalDelta = 0;
468 runner->fps = 0;
469 struct timeval tv;
470 gettimeofday(&tv, 0);
471 runner->lastFpsCheck = 1000000LL * tv.tv_sec + tv.tv_usec;
472
473 int frame = 0;
474 bool fastForward = false;
475 while (running) {
476 if (runner->running) {
477 running = runner->running(runner);
478 if (!running) {
479 break;
480 }
481 }
482 uint32_t guiKeys;
483 uint32_t heldKeys;
484 GUIPollInput(&runner->params, &guiKeys, &heldKeys);
485 if (guiKeys & (1 << GUI_INPUT_CANCEL)) {
486 break;
487 }
488 if (guiKeys & (1 << mGUI_INPUT_INCREASE_BRIGHTNESS)) {
489 if (runner->luminanceSource.luxLevel < 10) {
490 ++runner->luminanceSource.luxLevel;
491 }
492 }
493 if (guiKeys & (1 << mGUI_INPUT_DECREASE_BRIGHTNESS)) {
494 if (runner->luminanceSource.luxLevel > 0) {
495 --runner->luminanceSource.luxLevel;
496 }
497 }
498 if (guiKeys & (1 << mGUI_INPUT_SCREEN_MODE) && runner->incrementScreenMode) {
499 runner->incrementScreenMode(runner);
500 }
501 if (guiKeys & (1 << mGUI_INPUT_SCREENSHOT)) {
502 mCoreTakeScreenshot(runner->core);
503 }
504 if (runner->setFrameLimiter) {
505 if (guiKeys & (1 << mGUI_INPUT_FAST_FORWARD_TOGGLE)) {
506 fastForward = !fastForward;
507 }
508 if (fastForward || (heldKeys & (1 << mGUI_INPUT_FAST_FORWARD_HELD))) {
509 runner->setFrameLimiter(runner, false);
510 } else {
511 runner->setFrameLimiter(runner, true);
512 }
513 }
514 if (guiKeys & (1 << mGUI_INPUT_MUTE_TOGGLE)) {
515 int mute = !runner->core->opts.mute;
516 mCoreConfigSetUIntValue(&runner->config, "mute", mute);
517 runner->core->reloadConfigOption(runner->core, "mute", &runner->config);
518 }
519 uint16_t keys = runner->pollGameInput(runner);
520 if (runner->prepareForFrame) {
521 runner->prepareForFrame(runner);
522 }
523 runner->core->setKeys(runner->core, keys);
524 runner->core->runFrame(runner->core);
525 if (runner->drawFrame) {
526 runner->params.drawStart();
527 runner->drawFrame(runner, false);
528 if (showOSD || drawFps) {
529 if (runner->params.guiPrepare) {
530 runner->params.guiPrepare();
531 }
532 if (drawFps) {
533 GUIFontPrintf(runner->params.font, 0, GUIFontHeight(runner->params.font), GUI_ALIGN_LEFT, 0x7FFFFFFF, "%.2f fps", runner->fps);
534 }
535 if (showOSD) {
536 unsigned origin = runner->params.width - GUIFontHeight(runner->params.font) / 2;
537 unsigned w;
538 if (fastForward || (heldKeys & (1 << mGUI_INPUT_FAST_FORWARD_HELD))) {
539 GUIFontDrawIcon(runner->params.font, origin, GUIFontHeight(runner->params.font) / 2, GUI_ALIGN_RIGHT, 0, 0x7FFFFFFF, GUI_ICON_STATUS_FAST_FORWARD);
540 GUIFontIconMetrics(runner->params.font, GUI_ICON_STATUS_FAST_FORWARD, &w, NULL);
541 origin -= w + GUIFontHeight(runner->params.font) / 2;
542 }
543 if (runner->core->opts.mute) {
544 GUIFontDrawIcon(runner->params.font, origin, GUIFontHeight(runner->params.font) / 2, GUI_ALIGN_RIGHT, 0, 0x7FFFFFFF, GUI_ICON_STATUS_MUTE);
545 GUIFontIconMetrics(runner->params.font, GUI_ICON_STATUS_MUTE, &w, NULL);
546 origin -= w + GUIFontHeight(runner->params.font) / 2;
547 }
548 }
549 if (runner->params.guiFinish) {
550 runner->params.guiFinish();
551 }
552 }
553 runner->params.drawEnd();
554
555 if (runner->core->frameCounter(runner->core) % FPS_GRANULARITY == 0) {
556 if (drawFps) {
557 struct timeval tv;
558 gettimeofday(&tv, 0);
559 uint64_t t = 1000000LL * tv.tv_sec + tv.tv_usec;
560 uint64_t delta = t - runner->lastFpsCheck;
561 runner->lastFpsCheck = t;
562 if (delta > 0x7FFFFFFFLL) {
563 CircleBufferClear(&runner->fpsBuffer);
564 runner->fps = 0;
565 }
566 if (CircleBufferSize(&runner->fpsBuffer) == CircleBufferCapacity(&runner->fpsBuffer)) {
567 int32_t last;
568 CircleBufferRead32(&runner->fpsBuffer, &last);
569 runner->totalDelta -= last;
570 }
571 CircleBufferWrite32(&runner->fpsBuffer, delta);
572 runner->totalDelta += delta;
573 runner->fps = (CircleBufferSize(&runner->fpsBuffer) * FPS_GRANULARITY * 1000000.0f) / (runner->totalDelta * sizeof(uint32_t));
574 }
575 }
576 if (frame == AUTOSAVE_GRANULARITY) {
577 frame = 0;
578 _tryAutosave(runner);
579 }
580 ++frame;
581 }
582 }
583 if (!running) {
584 break;
585 }
586
587 if (runner->paused) {
588 runner->paused(runner);
589 }
590 if (runner->setFrameLimiter) {
591 runner->setFrameLimiter(runner, true);
592 }
593
594 GUIInvalidateKeys(&runner->params);
595 uint32_t keys = 0xFFFFFFFF; // Huge hack to avoid an extra variable!
596 struct GUIMenuItem* item;
597 enum GUIMenuExitReason reason = GUIShowMenu(&runner->params, &pauseMenu, &item);
598 if (reason == GUI_MENU_EXIT_ACCEPT) {
599 switch (((int) item->data) & RUNNER_COMMAND_MASK) {
600 case RUNNER_EXIT:
601 running = false;
602 keys = 0;
603 break;
604 case RUNNER_RESET:
605 runner->core->reset(runner->core);
606 break;
607 case RUNNER_SAVE_STATE:
608 mCoreSaveState(runner->core, ((int) item->data) >> 16, SAVESTATE_SCREENSHOT | SAVESTATE_SAVEDATA | SAVESTATE_RTC | SAVESTATE_METADATA);
609 break;
610 case RUNNER_LOAD_STATE:
611 mCoreLoadState(runner->core, ((int) item->data) >> 16, SAVESTATE_SCREENSHOT | SAVESTATE_RTC);
612 break;
613 case RUNNER_SCREENSHOT:
614 mCoreTakeScreenshot(runner->core);
615 break;
616 case RUNNER_CONFIG:
617 mGUIShowConfig(runner, runner->configExtra, runner->nConfigExtra);
618 break;
619 case RUNNER_CONTINUE:
620 break;
621 }
622 }
623 int frames = 0;
624 GUIPollInput(&runner->params, 0, &keys);
625 while (keys && frames < 30) {
626 ++frames;
627 runner->params.drawStart();
628 runner->drawFrame(runner, true);
629 runner->params.drawEnd();
630#ifdef _3DS
631 // XXX: Why does this fix #1294?
632 usleep(1000);
633#endif
634 GUIPollInput(&runner->params, 0, &keys);
635 }
636 if (runner->unpaused) {
637 runner->unpaused(runner);
638 }
639 mCoreConfigGetIntValue(&runner->config, "fpsCounter", &drawFps);
640 mCoreConfigGetIntValue(&runner->config, "showOSD", &showOSD);
641 }
642 mLOG(GUI_RUNNER, DEBUG, "Shutting down...");
643 if (runner->gameUnloaded) {
644 runner->gameUnloaded(runner);
645 }
646#ifndef DISABLE_THREADING
647 MutexLock(&runner->autosave.mutex);
648 runner->autosave.core = NULL;
649 MutexUnlock(&runner->autosave.mutex);
650#endif
651
652 int autosave = false;
653 mCoreConfigGetIntValue(&runner->config, "autosave", &autosave);
654 if (autosave) {
655 mCoreSaveState(runner->core, 0, SAVESTATE_SAVEDATA | SAVESTATE_RTC | SAVESTATE_METADATA);
656 }
657
658 mLOG(GUI_RUNNER, DEBUG, "Unloading game...");
659 runner->core->unloadROM(runner->core);
660 drawState.screenshotId = 0;
661 if (drawState.screenshot) {
662 unsigned w, h;
663 runner->core->desiredVideoDimensions(runner->core, &w, &h);
664 mappedMemoryFree(drawState.screenshot, w * h * 4);
665 }
666
667 if (runner->config.port) {
668 mLOG(GUI_RUNNER, DEBUG, "Saving key sources...");
669 if (runner->keySources) {
670 size_t i;
671 for (i = 0; runner->keySources[i].id; ++i) {
672 mInputMapSave(&runner->core->inputMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
673 mInputMapSave(&runner->params.keyMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
674 }
675 }
676 mCoreConfigSave(&runner->config);
677 }
678 mInputMapDeinit(&runner->core->inputMap);
679 mLOG(GUI_RUNNER, DEBUG, "Deinitializing core...");
680 mCoreConfigDeinit(&runner->core->config);
681 runner->core->deinit(runner->core);
682 runner->core = NULL;
683
684 GUIMenuItemListDeinit(&pauseMenu.items);
685 GUIMenuItemListDeinit(&stateSaveMenu.items);
686 GUIMenuItemListDeinit(&stateLoadMenu.items);
687 mLOG(GUI_RUNNER, INFO, "Game stopped!");
688}
689
690void mGUIRunloop(struct mGUIRunner* runner) {
691 if (runner->keySources) {
692 mLOG(GUI_RUNNER, DEBUG, "Loading key sources for %s...", runner->config.port);
693 size_t i;
694 for (i = 0; runner->keySources[i].id; ++i) {
695 mInputMapLoad(&runner->params.keyMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
696 }
697 }
698 while (!runner->running || runner->running(runner)) {
699 char path[PATH_MAX];
700 const char* preselect = mCoreConfigGetValue(&runner->config, "lastGame");
701 if (preselect) {
702 preselect = strrchr(preselect, '/');
703 }
704 if (preselect) {
705 ++preselect;
706 }
707 if (!GUISelectFile(&runner->params, path, sizeof(path), _testExtensions, NULL, preselect)) {
708 break;
709 }
710 mCoreConfigSetValue(&runner->config, "lastDirectory", runner->params.currentPath);
711 mCoreConfigSetValue(&runner->config, "lastGame", path);
712 mCoreConfigSave(&runner->config);
713 mGUIRun(runner, path);
714 }
715}
716
717#ifndef DISABLE_THREADING
718THREAD_ENTRY mGUIAutosaveThread(void* context) {
719 struct mGUIAutosaveContext* autosave = context;
720 MutexLock(&autosave->mutex);
721 while (autosave->running) {
722 ConditionWait(&autosave->cond, &autosave->mutex);
723 if (autosave->running && autosave->core) {
724 struct VFile* vf = mCoreGetState(autosave->core, 0, true);
725 void* mem = autosave->buffer->map(autosave->buffer, autosave->buffer->size(autosave->buffer), MAP_READ);
726 vf->write(vf, mem, autosave->buffer->size(autosave->buffer));
727 autosave->buffer->unmap(autosave->buffer, mem, autosave->buffer->size(autosave->buffer));
728 vf->close(vf);
729 }
730 }
731 MutexUnlock(&autosave->mutex);
732}
733#endif