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