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
292static void _updateLoading(size_t read, size_t size, void* context) {
293 struct mGUIRunner* runner = context;
294 if (read & 0x3FFFF) {
295 return;
296 }
297
298 runner->params.drawStart();
299 if (runner->params.guiPrepare) {
300 runner->params.guiPrepare();
301 }
302 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);
303 if (runner->params.guiFinish) {
304 runner->params.guiFinish();
305 }
306 runner->params.drawEnd();
307}
308
309void mGUIRun(struct mGUIRunner* runner, const char* path) {
310 struct mGUIBackground drawState = {
311 .d = {
312 .draw = _drawState
313 },
314 .p = runner,
315 .screenshot = 0,
316 .screenshotId = 0
317 };
318 struct GUIMenu pauseMenu = {
319 .title = "Game Paused",
320 .index = 0,
321 .background = &runner->background.d
322 };
323 struct GUIMenu stateSaveMenu = {
324 .title = "Save state",
325 .index = 0,
326 .background = &drawState.d
327 };
328 struct GUIMenu stateLoadMenu = {
329 .title = "Load state",
330 .index = 0,
331 .background = &drawState.d
332 };
333 GUIMenuItemListInit(&pauseMenu.items, 0);
334 GUIMenuItemListInit(&stateSaveMenu.items, 9);
335 GUIMenuItemListInit(&stateLoadMenu.items, 9);
336 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Unpause", .data = (void*) RUNNER_CONTINUE };
337 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Save state", .submenu = &stateSaveMenu };
338 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Load state", .submenu = &stateLoadMenu };
339
340 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 1", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(1)) };
341 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 2", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(2)) };
342 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 3", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(3)) };
343 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 4", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(4)) };
344 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 5", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(5)) };
345 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 6", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(6)) };
346 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 7", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(7)) };
347 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 8", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(8)) };
348 *GUIMenuItemListAppend(&stateSaveMenu.items) = (struct GUIMenuItem) { .title = "State 9", .data = (void*) (RUNNER_SAVE_STATE | RUNNER_STATE(9)) };
349
350 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "Autosave", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(0)) };
351 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 1", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(1)) };
352 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 2", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(2)) };
353 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 3", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(3)) };
354 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 4", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(4)) };
355 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 5", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(5)) };
356 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 6", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(6)) };
357 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 7", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(7)) };
358 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 8", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(8)) };
359 *GUIMenuItemListAppend(&stateLoadMenu.items) = (struct GUIMenuItem) { .title = "State 9", .data = (void*) (RUNNER_LOAD_STATE | RUNNER_STATE(9)) };
360
361 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Take screenshot", .data = (void*) RUNNER_SCREENSHOT };
362 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Configure", .data = (void*) RUNNER_CONFIG };
363 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Reset game", .data = (void*) RUNNER_RESET };
364 *GUIMenuItemListAppend(&pauseMenu.items) = (struct GUIMenuItem) { .title = "Exit game", .data = (void*) RUNNER_EXIT };
365
366 runner->params.drawStart();
367 if (runner->params.guiPrepare) {
368 runner->params.guiPrepare();
369 }
370 GUIFontPrint(runner->params.font, runner->params.width / 2, (GUIFontHeight(runner->params.font) + runner->params.height) / 2, GUI_ALIGN_HCENTER, 0xFFFFFFFF, "Loading...");
371 if (runner->params.guiFinish) {
372 runner->params.guiFinish();
373 }
374 runner->params.drawEnd();
375
376 bool found = false;
377 mLOG(GUI_RUNNER, INFO, "Attempting to load %s", path);
378 runner->core = mCoreFind(path);
379 if (runner->core) {
380 mLOG(GUI_RUNNER, INFO, "Found core");
381 runner->core->init(runner->core);
382 mCoreInitConfig(runner->core, runner->port);
383 mInputMapInit(&runner->core->inputMap, &GBAInputInfo);
384
385 found = mCorePreloadFileCB(runner->core, path, _updateLoading, runner);
386 if (!found) {
387 mLOG(GUI_RUNNER, WARN, "Failed to load %s!", path);
388 mCoreConfigDeinit(&runner->core->config);
389 runner->core->deinit(runner->core);
390 }
391 }
392
393 if (!found) {
394 mLOG(GUI_RUNNER, WARN, "Failed to find core for %s!", path);
395 GUIShowMessageBox(&runner->params, GUI_MESSAGE_BOX_OK, 240, "Load failed!");
396 return;
397 }
398 if (runner->core->platform(runner->core) == PLATFORM_GBA) {
399 runner->core->setPeripheral(runner->core, mPERIPH_GBA_LUMINANCE, &runner->luminanceSource.d);
400 }
401 mLOG(GUI_RUNNER, DEBUG, "Loading config...");
402 mCoreLoadForeignConfig(runner->core, &runner->config);
403
404 mLOG(GUI_RUNNER, DEBUG, "Loading save...");
405 mCoreAutoloadSave(runner->core);
406 mCoreAutoloadCheats(runner->core);
407 if (runner->setup) {
408 mLOG(GUI_RUNNER, DEBUG, "Setting up runner...");
409 runner->setup(runner);
410 }
411 if (runner->config.port && runner->keySources) {
412 mLOG(GUI_RUNNER, DEBUG, "Loading key sources for %s...", runner->config.port);
413 size_t i;
414 for (i = 0; runner->keySources[i].id; ++i) {
415 mInputMapLoad(&runner->core->inputMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
416 }
417 }
418 mLOG(GUI_RUNNER, DEBUG, "Reseting...");
419 runner->core->reset(runner->core);
420 mLOG(GUI_RUNNER, DEBUG, "Reset!");
421
422
423 int autoload = false;
424 mCoreConfigGetIntValue(&runner->config, "autoload", &autoload);
425 if (autoload) {
426 mCoreLoadState(runner->core, 0, SAVESTATE_SCREENSHOT | SAVESTATE_RTC);
427 }
428
429 bool running = true;
430
431#ifndef DISABLE_THREADING
432 MutexLock(&runner->autosave.mutex);
433 runner->autosave.core = runner->core;
434 MutexUnlock(&runner->autosave.mutex);
435#endif
436
437 if (runner->gameLoaded) {
438 runner->gameLoaded(runner);
439 }
440 mLOG(GUI_RUNNER, INFO, "Game starting");
441 while (running) {
442 CircleBufferClear(&runner->fpsBuffer);
443 runner->totalDelta = 0;
444 runner->fps = 0;
445 struct timeval tv;
446 gettimeofday(&tv, 0);
447 runner->lastFpsCheck = 1000000LL * tv.tv_sec + tv.tv_usec;
448
449 int frame = 0;
450 bool fastForward = false;
451 while (running) {
452 if (runner->running) {
453 running = runner->running(runner);
454 if (!running) {
455 break;
456 }
457 }
458 uint32_t guiKeys;
459 uint32_t heldKeys;
460 GUIPollInput(&runner->params, &guiKeys, &heldKeys);
461 if (guiKeys & (1 << GUI_INPUT_CANCEL)) {
462 break;
463 }
464 if (guiKeys & (1 << mGUI_INPUT_INCREASE_BRIGHTNESS)) {
465 if (runner->luminanceSource.luxLevel < 10) {
466 ++runner->luminanceSource.luxLevel;
467 }
468 }
469 if (guiKeys & (1 << mGUI_INPUT_DECREASE_BRIGHTNESS)) {
470 if (runner->luminanceSource.luxLevel > 0) {
471 --runner->luminanceSource.luxLevel;
472 }
473 }
474 if (guiKeys & (1 << mGUI_INPUT_SCREEN_MODE) && runner->incrementScreenMode) {
475 runner->incrementScreenMode(runner);
476 }
477 if (guiKeys & (1 << mGUI_INPUT_SCREENSHOT)) {
478 mCoreTakeScreenshot(runner->core);
479 }
480 if (runner->setFrameLimiter) {
481 if (guiKeys & (1 << mGUI_INPUT_FAST_FORWARD_TOGGLE)) {
482 fastForward = !fastForward;
483 }
484 if (fastForward || (heldKeys & (1 << mGUI_INPUT_FAST_FORWARD_HELD))) {
485 runner->setFrameLimiter(runner, false);
486 } else {
487 runner->setFrameLimiter(runner, true);
488 }
489 }
490 uint16_t keys = runner->pollGameInput(runner);
491 if (runner->prepareForFrame) {
492 runner->prepareForFrame(runner);
493 }
494 runner->core->setKeys(runner->core, keys);
495 runner->core->runFrame(runner->core);
496 if (runner->drawFrame) {
497 int drawFps = false;
498 mCoreConfigGetIntValue(&runner->config, "fpsCounter", &drawFps);
499
500 runner->params.drawStart();
501 runner->drawFrame(runner, false);
502 if (drawFps) {
503 if (runner->params.guiPrepare) {
504 runner->params.guiPrepare();
505 }
506 GUIFontPrintf(runner->params.font, 0, GUIFontHeight(runner->params.font), GUI_ALIGN_LEFT, 0x7FFFFFFF, "%.2f fps", runner->fps);
507 if (runner->params.guiFinish) {
508 runner->params.guiFinish();
509 }
510 }
511 runner->params.drawEnd();
512
513 if (runner->core->frameCounter(runner->core) % FPS_GRANULARITY == 0) {
514 if (drawFps) {
515 struct timeval tv;
516 gettimeofday(&tv, 0);
517 uint64_t t = 1000000LL * tv.tv_sec + tv.tv_usec;
518 uint64_t delta = t - runner->lastFpsCheck;
519 runner->lastFpsCheck = t;
520 if (delta > 0x7FFFFFFFLL) {
521 CircleBufferClear(&runner->fpsBuffer);
522 runner->fps = 0;
523 }
524 if (CircleBufferSize(&runner->fpsBuffer) == CircleBufferCapacity(&runner->fpsBuffer)) {
525 int32_t last;
526 CircleBufferRead32(&runner->fpsBuffer, &last);
527 runner->totalDelta -= last;
528 }
529 CircleBufferWrite32(&runner->fpsBuffer, delta);
530 runner->totalDelta += delta;
531 runner->fps = (CircleBufferSize(&runner->fpsBuffer) * FPS_GRANULARITY * 1000000.0f) / (runner->totalDelta * sizeof(uint32_t));
532 }
533 }
534 if (frame == AUTOSAVE_GRANULARITY) {
535 frame = 0;
536 _tryAutosave(runner);
537 }
538 ++frame;
539 }
540 }
541
542 if (runner->paused) {
543 runner->paused(runner);
544 }
545 if (runner->setFrameLimiter) {
546 runner->setFrameLimiter(runner, true);
547 }
548
549 GUIInvalidateKeys(&runner->params);
550 uint32_t keys = 0xFFFFFFFF; // Huge hack to avoid an extra variable!
551 struct GUIMenuItem* item;
552 enum GUIMenuExitReason reason = GUIShowMenu(&runner->params, &pauseMenu, &item);
553 if (reason == GUI_MENU_EXIT_ACCEPT) {
554 switch (((int) item->data) & RUNNER_COMMAND_MASK) {
555 case RUNNER_EXIT:
556 running = false;
557 keys = 0;
558 break;
559 case RUNNER_RESET:
560 runner->core->reset(runner->core);
561 break;
562 case RUNNER_SAVE_STATE:
563 mCoreSaveState(runner->core, ((int) item->data) >> 16, SAVESTATE_SCREENSHOT | SAVESTATE_SAVEDATA | SAVESTATE_RTC | SAVESTATE_METADATA);
564 break;
565 case RUNNER_LOAD_STATE:
566 mCoreLoadState(runner->core, ((int) item->data) >> 16, SAVESTATE_SCREENSHOT | SAVESTATE_RTC);
567 break;
568 case RUNNER_SCREENSHOT:
569 mCoreTakeScreenshot(runner->core);
570 break;
571 case RUNNER_CONFIG:
572 mGUIShowConfig(runner, runner->configExtra, runner->nConfigExtra);
573 break;
574 case RUNNER_CONTINUE:
575 break;
576 }
577 }
578 int frames = 0;
579 GUIPollInput(&runner->params, 0, &keys);
580 while (keys && frames < 30) {
581 ++frames;
582 runner->params.drawStart();
583 runner->drawFrame(runner, true);
584 runner->params.drawEnd();
585#ifdef _3DS
586 // XXX: Why does this fix #1294?
587 usleep(1000);
588#endif
589 GUIPollInput(&runner->params, 0, &keys);
590 }
591 if (runner->unpaused) {
592 runner->unpaused(runner);
593 }
594 }
595 mLOG(GUI_RUNNER, DEBUG, "Shutting down...");
596 if (runner->gameUnloaded) {
597 runner->gameUnloaded(runner);
598 }
599#ifndef DISABLE_THREADING
600 MutexLock(&runner->autosave.mutex);
601 runner->autosave.core = NULL;
602 MutexUnlock(&runner->autosave.mutex);
603#endif
604
605 int autosave = false;
606 mCoreConfigGetIntValue(&runner->config, "autosave", &autosave);
607 if (autosave) {
608 mCoreSaveState(runner->core, 0, SAVESTATE_SAVEDATA | SAVESTATE_RTC | SAVESTATE_METADATA);
609 }
610
611 mLOG(GUI_RUNNER, DEBUG, "Unloading game...");
612 runner->core->unloadROM(runner->core);
613 drawState.screenshotId = 0;
614 if (drawState.screenshot) {
615 unsigned w, h;
616 runner->core->desiredVideoDimensions(runner->core, &w, &h);
617 mappedMemoryFree(drawState.screenshot, w * h * 4);
618 }
619
620 if (runner->config.port) {
621 mLOG(GUI_RUNNER, DEBUG, "Saving key sources...");
622 if (runner->keySources) {
623 size_t i;
624 for (i = 0; runner->keySources[i].id; ++i) {
625 mInputMapSave(&runner->core->inputMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
626 mInputMapSave(&runner->params.keyMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
627 }
628 }
629 mCoreConfigSave(&runner->config);
630 }
631 mInputMapDeinit(&runner->core->inputMap);
632 mLOG(GUI_RUNNER, DEBUG, "Deinitializing core...");
633 mCoreConfigDeinit(&runner->core->config);
634 runner->core->deinit(runner->core);
635 runner->core = NULL;
636
637 GUIMenuItemListDeinit(&pauseMenu.items);
638 GUIMenuItemListDeinit(&stateSaveMenu.items);
639 GUIMenuItemListDeinit(&stateLoadMenu.items);
640 mLOG(GUI_RUNNER, INFO, "Game stopped!");
641}
642
643void mGUIRunloop(struct mGUIRunner* runner) {
644 if (runner->keySources) {
645 mLOG(GUI_RUNNER, DEBUG, "Loading key sources for %s...", runner->config.port);
646 size_t i;
647 for (i = 0; runner->keySources[i].id; ++i) {
648 mInputMapLoad(&runner->params.keyMap, runner->keySources[i].id, mCoreConfigGetInput(&runner->config));
649 }
650 }
651 while (true) {
652 char path[PATH_MAX];
653 const char* preselect = mCoreConfigGetValue(&runner->config, "lastGame");
654 if (preselect) {
655 preselect = strrchr(preselect, '/');
656 }
657 if (preselect) {
658 ++preselect;
659 }
660 if (!GUISelectFile(&runner->params, path, sizeof(path), _testExtensions, NULL, preselect)) {
661 break;
662 }
663 mCoreConfigSetValue(&runner->config, "lastDirectory", runner->params.currentPath);
664 mCoreConfigSetValue(&runner->config, "lastGame", path);
665 mCoreConfigSave(&runner->config);
666 mGUIRun(runner, path);
667 }
668}
669
670#ifndef DISABLE_THREADING
671THREAD_ENTRY mGUIAutosaveThread(void* context) {
672 struct mGUIAutosaveContext* autosave = context;
673 MutexLock(&autosave->mutex);
674 while (autosave->running) {
675 ConditionWait(&autosave->cond, &autosave->mutex);
676 if (autosave->running && autosave->core) {
677 struct VFile* vf = mCoreGetState(autosave->core, 0, true);
678 void* mem = autosave->buffer->map(autosave->buffer, autosave->buffer->size(autosave->buffer), MAP_READ);
679 vf->write(vf, mem, autosave->buffer->size(autosave->buffer));
680 autosave->buffer->unmap(autosave->buffer, mem, autosave->buffer->size(autosave->buffer));
681 vf->close(vf);
682 }
683 }
684 MutexUnlock(&autosave->mutex);
685}
686#endif