src/platform/qt/GameController.cpp (view raw)
1/* Copyright (c) 2013-2014 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 "GameController.h"
7
8#include "AudioProcessor.h"
9#include "InputController.h"
10#include "LogController.h"
11#include "MultiplayerController.h"
12#include "VFileDevice.h"
13
14#include <QDateTime>
15#include <QThread>
16
17#include <ctime>
18
19extern "C" {
20#include "gba/audio.h"
21#include "gba/context/config.h"
22#include "gba/gba.h"
23#include "gba/serialize.h"
24#include "gba/sharkport.h"
25#include "gba/renderers/video-software.h"
26#include "util/vfs.h"
27}
28
29using namespace QGBA;
30using namespace std;
31
32GameController::GameController(QObject* parent)
33 : QObject(parent)
34 , m_drawContext(new uint32_t[256 * VIDEO_HORIZONTAL_PIXELS])
35 , m_frontBuffer(new uint32_t[256 * 256])
36 , m_threadContext()
37 , m_activeKeys(0)
38 , m_inactiveKeys(0)
39 , m_logLevels(0)
40 , m_gameOpen(false)
41 , m_audioThread(new QThread(this))
42 , m_audioProcessor(AudioProcessor::create())
43 , m_pauseAfterFrame(false)
44 , m_videoSync(VIDEO_SYNC)
45 , m_audioSync(AUDIO_SYNC)
46 , m_fpsTarget(-1)
47 , m_turbo(false)
48 , m_turboForced(false)
49 , m_turboSpeed(-1)
50 , m_wasPaused(false)
51 , m_audioChannels{ true, true, true, true, true, true }
52 , m_videoLayers{ true, true, true, true, true }
53 , m_inputController(nullptr)
54 , m_multiplayer(nullptr)
55 , m_stateSlot(1)
56 , m_backupLoadState(nullptr)
57 , m_backupSaveState(nullptr)
58{
59 m_renderer = new GBAVideoSoftwareRenderer;
60 GBAVideoSoftwareRendererCreate(m_renderer);
61 m_renderer->outputBuffer = (color_t*) m_drawContext;
62 m_renderer->outputBufferStride = 256;
63
64 GBACheatDeviceCreate(&m_cheatDevice);
65
66 m_threadContext.state = THREAD_INITIALIZED;
67 m_threadContext.debugger = 0;
68 m_threadContext.frameskip = 0;
69 m_threadContext.bios = 0;
70 m_threadContext.renderer = &m_renderer->d;
71 m_threadContext.userData = this;
72 m_threadContext.rewindBufferCapacity = 0;
73 m_threadContext.cheats = &m_cheatDevice;
74 m_threadContext.logLevel = GBA_LOG_ALL;
75
76 m_lux.p = this;
77 m_lux.sample = [](GBALuminanceSource* context) {
78 GameControllerLux* lux = static_cast<GameControllerLux*>(context);
79 lux->value = 0xFF - lux->p->m_luxValue;
80 };
81
82 m_lux.readLuminance = [](GBALuminanceSource* context) {
83 GameControllerLux* lux = static_cast<GameControllerLux*>(context);
84 return lux->value;
85 };
86 setLuminanceLevel(0);
87
88 m_threadContext.startCallback = [](GBAThread* context) {
89 GameController* controller = static_cast<GameController*>(context->userData);
90 if (controller->m_audioProcessor) {
91 controller->m_audioProcessor->setInput(context);
92 }
93 context->gba->luminanceSource = &controller->m_lux;
94 GBARTCGenericSourceInit(&controller->m_rtc, context->gba);
95 context->gba->rtcSource = &controller->m_rtc.d;
96 context->gba->rumble = controller->m_inputController->rumble();
97 context->gba->rotationSource = controller->m_inputController->rotationSource();
98 context->gba->audio.forceDisableCh[0] = !controller->m_audioChannels[0];
99 context->gba->audio.forceDisableCh[1] = !controller->m_audioChannels[1];
100 context->gba->audio.forceDisableCh[2] = !controller->m_audioChannels[2];
101 context->gba->audio.forceDisableCh[3] = !controller->m_audioChannels[3];
102 context->gba->audio.forceDisableChA = !controller->m_audioChannels[4];
103 context->gba->audio.forceDisableChB = !controller->m_audioChannels[5];
104 context->gba->video.renderer->disableBG[0] = !controller->m_videoLayers[0];
105 context->gba->video.renderer->disableBG[1] = !controller->m_videoLayers[1];
106 context->gba->video.renderer->disableBG[2] = !controller->m_videoLayers[2];
107 context->gba->video.renderer->disableBG[3] = !controller->m_videoLayers[3];
108 context->gba->video.renderer->disableOBJ = !controller->m_videoLayers[4];
109 controller->m_fpsTarget = context->fpsTarget;
110
111 if (GBALoadState(context, context->stateDir, 0)) {
112 VFile* vf = GBAGetState(context->gba, context->stateDir, 0, true);
113 if (vf) {
114 vf->truncate(vf, 0);
115 }
116 }
117 QMetaObject::invokeMethod(controller, "gameStarted", Q_ARG(GBAThread*, context));
118 };
119
120 m_threadContext.cleanCallback = [](GBAThread* context) {
121 GameController* controller = static_cast<GameController*>(context->userData);
122 QMetaObject::invokeMethod(controller, "gameStopped", Q_ARG(GBAThread*, context));
123 };
124
125 m_threadContext.frameCallback = [](GBAThread* context) {
126 GameController* controller = static_cast<GameController*>(context->userData);
127 memcpy(controller->m_frontBuffer, controller->m_drawContext, 256 * VIDEO_HORIZONTAL_PIXELS * BYTES_PER_PIXEL);
128 QMetaObject::invokeMethod(controller, "frameAvailable", Q_ARG(const uint32_t*, controller->m_frontBuffer));
129 if (controller->m_pauseAfterFrame.testAndSetAcquire(true, false)) {
130 GBAThreadPauseFromThread(context);
131 QMetaObject::invokeMethod(controller, "gamePaused", Q_ARG(GBAThread*, context));
132 }
133 };
134
135 m_threadContext.stopCallback = [](GBAThread* context) {
136 if (!context) {
137 return false;
138 }
139 GameController* controller = static_cast<GameController*>(context->userData);
140 if (!GBASaveState(context, context->stateDir, 0, true)) {
141 return false;
142 }
143 QMetaObject::invokeMethod(controller, "closeGame");
144 return true;
145 };
146
147 m_threadContext.logHandler = [](GBAThread* context, enum GBALogLevel level, const char* format, va_list args) {
148 static const char* stubMessage = "Stub software interrupt: %02X";
149 static const char* savestateMessage = "State %i loaded";
150 static const char* savestateFailedMessage = "State %i failed to load";
151 if (!context) {
152 return;
153 }
154 GameController* controller = static_cast<GameController*>(context->userData);
155 if (level == GBA_LOG_STUB && strncmp(stubMessage, format, strlen(stubMessage)) == 0) {
156 va_list argc;
157 va_copy(argc, args);
158 int immediate = va_arg(argc, int);
159 va_end(argc);
160 QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
161 } else if (level == GBA_LOG_STATUS) {
162 // Slot 0 is reserved for suspend points
163 if (strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
164 va_list argc;
165 va_copy(argc, args);
166 int slot = va_arg(argc, int);
167 va_end(argc);
168 if (slot == 0) {
169 format = "Loaded suspend state";
170 }
171 } else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 0) {
172 va_list argc;
173 va_copy(argc, args);
174 int slot = va_arg(argc, int);
175 va_end(argc);
176 if (slot == 0) {
177 return;
178 }
179 }
180 }
181 if (level == GBA_LOG_FATAL) {
182 QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
183 } else if (!(controller->m_logLevels & level)) {
184 return;
185 }
186 QString message(QString().vsprintf(format, args));
187 if (level == GBA_LOG_STATUS) {
188 QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
189 }
190 QMetaObject::invokeMethod(controller, "postLog", Q_ARG(int, level), Q_ARG(const QString&, message));
191 };
192
193 connect(&m_rewindTimer, &QTimer::timeout, [this]() {
194 GBARewind(&m_threadContext, 1);
195 emit frameAvailable(m_drawContext);
196 emit rewound(&m_threadContext);
197 });
198 m_rewindTimer.setInterval(100);
199
200 m_audioThread->setObjectName("Audio Thread");
201 m_audioThread->start(QThread::TimeCriticalPriority);
202 m_audioProcessor->moveToThread(m_audioThread);
203 connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
204 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
205 connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
206 connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(pollEvents()));
207}
208
209GameController::~GameController() {
210 m_audioThread->quit();
211 m_audioThread->wait();
212 disconnect();
213 clearMultiplayerController();
214 closeGame();
215 GBACheatDeviceDestroy(&m_cheatDevice);
216 delete m_renderer;
217 delete[] m_drawContext;
218 delete[] m_frontBuffer;
219 delete m_backupLoadState;
220}
221
222void GameController::setMultiplayerController(MultiplayerController* controller) {
223 if (controller == m_multiplayer) {
224 return;
225 }
226 clearMultiplayerController();
227 m_multiplayer = controller;
228 controller->attachGame(this);
229}
230
231void GameController::clearMultiplayerController() {
232 if (!m_multiplayer) {
233 return;
234 }
235 m_multiplayer->detachGame(this);
236 m_multiplayer = nullptr;
237}
238
239void GameController::setOverride(const GBACartridgeOverride& override) {
240 m_threadContext.override = override;
241 m_threadContext.hasOverride = true;
242}
243
244void GameController::setOptions(const GBAOptions* opts) {
245 setFrameskip(opts->frameskip);
246 setAudioSync(opts->audioSync);
247 setVideoSync(opts->videoSync);
248 setSkipBIOS(opts->skipBios);
249 setUseBIOS(opts->useBios);
250 setRewind(opts->rewindEnable, opts->rewindBufferCapacity, opts->rewindBufferInterval);
251 setVolume(opts->volume);
252 setMute(opts->mute);
253
254 threadInterrupt();
255 m_threadContext.idleOptimization = opts->idleOptimization;
256 threadContinue();
257}
258
259#ifdef USE_GDB_STUB
260ARMDebugger* GameController::debugger() {
261 return m_threadContext.debugger;
262}
263
264void GameController::setDebugger(ARMDebugger* debugger) {
265 threadInterrupt();
266 if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
267 GBADetachDebugger(m_threadContext.gba);
268 }
269 m_threadContext.debugger = debugger;
270 if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
271 GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
272 }
273 threadContinue();
274}
275#endif
276
277void GameController::loadGame(const QString& path, bool dirmode) {
278 closeGame();
279 if (!dirmode) {
280 QFile file(path);
281 if (!file.open(QIODevice::ReadOnly)) {
282 postLog(GBA_LOG_ERROR, tr("Failed to open game file: %1").arg(path));
283 return;
284 }
285 file.close();
286 }
287
288 m_fname = path;
289 m_dirmode = dirmode;
290 openGame();
291}
292
293void GameController::bootBIOS() {
294 closeGame();
295 m_fname = QString();
296 m_dirmode = false;
297 openGame(true);
298}
299
300void GameController::openGame(bool biosOnly) {
301 if (biosOnly && (!m_useBios || m_bios.isNull())) {
302 return;
303 }
304
305 m_gameOpen = true;
306
307 m_pauseAfterFrame = false;
308
309 if (m_turbo) {
310 m_threadContext.sync.videoFrameWait = false;
311 m_threadContext.sync.audioWait = false;
312 } else {
313 m_threadContext.sync.videoFrameWait = m_videoSync;
314 m_threadContext.sync.audioWait = m_audioSync;
315 }
316
317 m_threadContext.gameDir = 0;
318 m_threadContext.bootBios = biosOnly;
319 if (biosOnly) {
320 m_threadContext.fname = nullptr;
321 } else {
322 m_threadContext.fname = strdup(m_fname.toUtf8().constData());
323 if (m_dirmode) {
324 m_threadContext.gameDir = VDirOpen(m_threadContext.fname);
325 m_threadContext.stateDir = m_threadContext.gameDir;
326 } else {
327 GBAThreadLoadROM(&m_threadContext, m_threadContext.fname);
328 }
329 }
330
331 if (!m_bios.isNull() && m_useBios) {
332 m_threadContext.bios = VFileDevice::open(m_bios, O_RDONLY);
333 } else {
334 m_threadContext.bios = nullptr;
335 }
336
337 if (!m_patch.isNull()) {
338 m_threadContext.patch = VFileDevice::open(m_patch, O_RDONLY);
339 }
340
341 m_inputController->recalibrateAxes();
342 memset(m_drawContext, 0xF8, 1024 * VIDEO_HORIZONTAL_PIXELS);
343
344 if (!GBAThreadStart(&m_threadContext)) {
345 m_gameOpen = false;
346 emit gameFailed();
347 }
348}
349
350void GameController::loadBIOS(const QString& path) {
351 if (m_bios == path) {
352 return;
353 }
354 m_bios = path;
355 if (m_gameOpen) {
356 closeGame();
357 openGame();
358 }
359}
360
361void GameController::yankPak() {
362 if (!m_gameOpen) {
363 return;
364 }
365 threadInterrupt();
366 GBAYankROM(m_threadContext.gba);
367 threadContinue();
368}
369
370void GameController::replaceGame(const QString& path) {
371 if (!m_gameOpen) {
372 return;
373 }
374
375 m_fname = path;
376 threadInterrupt();
377 m_threadContext.fname = strdup(m_fname.toLocal8Bit().constData());
378 GBAThreadReplaceROM(&m_threadContext, m_threadContext.fname);
379 threadContinue();
380}
381
382void GameController::loadPatch(const QString& path) {
383 if (m_gameOpen) {
384 closeGame();
385 m_patch = path;
386 openGame();
387 } else {
388 m_patch = path;
389 }
390}
391
392void GameController::importSharkport(const QString& path) {
393 if (!isLoaded()) {
394 return;
395 }
396 VFile* vf = VFileDevice::open(path, O_RDONLY);
397 if (!vf) {
398 postLog(GBA_LOG_ERROR, tr("Failed to open snapshot file for reading: %1").arg(path));
399 return;
400 }
401 threadInterrupt();
402 GBASavedataImportSharkPort(m_threadContext.gba, vf, false);
403 threadContinue();
404 vf->close(vf);
405}
406
407void GameController::exportSharkport(const QString& path) {
408 if (!isLoaded()) {
409 return;
410 }
411 VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
412 if (!vf) {
413 postLog(GBA_LOG_ERROR, tr("Failed to open snapshot file for writing: %1").arg(path));
414 return;
415 }
416 threadInterrupt();
417 GBASavedataExportSharkPort(m_threadContext.gba, vf);
418 threadContinue();
419 vf->close(vf);
420}
421
422void GameController::closeGame() {
423 if (!m_gameOpen) {
424 return;
425 }
426 m_rewindTimer.stop();
427 if (GBAThreadIsPaused(&m_threadContext)) {
428 GBAThreadUnpause(&m_threadContext);
429 }
430 m_audioProcessor->pause();
431 GBAThreadEnd(&m_threadContext);
432 GBAThreadJoin(&m_threadContext);
433 if (m_threadContext.fname) {
434 free(const_cast<char*>(m_threadContext.fname));
435 m_threadContext.fname = nullptr;
436 }
437
438 m_patch = QString();
439
440 for (size_t i = 0; i < GBACheatSetsSize(&m_cheatDevice.cheats); ++i) {
441 GBACheatSet* set = *GBACheatSetsGetPointer(&m_cheatDevice.cheats, i);
442 GBACheatSetDeinit(set);
443 delete set;
444 }
445 GBACheatSetsClear(&m_cheatDevice.cheats);
446
447 m_gameOpen = false;
448 emit gameStopped(&m_threadContext);
449}
450
451void GameController::crashGame(const QString& crashMessage) {
452 closeGame();
453 emit gameCrashed(crashMessage);
454 emit gameStopped(&m_threadContext);
455}
456
457bool GameController::isPaused() {
458 if (!m_gameOpen) {
459 return false;
460 }
461 return GBAThreadIsPaused(&m_threadContext);
462}
463
464void GameController::setPaused(bool paused) {
465 if (!isLoaded() || m_rewindTimer.isActive() || paused == GBAThreadIsPaused(&m_threadContext)) {
466 return;
467 }
468 if (paused) {
469 m_pauseAfterFrame.testAndSetRelaxed(false, true);
470 } else {
471 GBAThreadUnpause(&m_threadContext);
472 emit gameUnpaused(&m_threadContext);
473 }
474}
475
476void GameController::reset() {
477 GBAThreadReset(&m_threadContext);
478}
479
480void GameController::threadInterrupt() {
481 if (m_gameOpen) {
482 GBAThreadInterrupt(&m_threadContext);
483 }
484}
485
486void GameController::threadContinue() {
487 if (m_gameOpen) {
488 GBAThreadContinue(&m_threadContext);
489 }
490}
491
492void GameController::frameAdvance() {
493 if (m_rewindTimer.isActive()) {
494 return;
495 }
496 if (m_pauseAfterFrame.testAndSetRelaxed(false, true)) {
497 setPaused(false);
498 }
499}
500
501void GameController::setRewind(bool enable, int capacity, int interval) {
502 if (m_gameOpen) {
503 threadInterrupt();
504 GBARewindSettingsChanged(&m_threadContext, enable ? capacity : 0, enable ? interval : 0);
505 threadContinue();
506 } else {
507 if (enable) {
508 m_threadContext.rewindBufferInterval = interval;
509 m_threadContext.rewindBufferCapacity = capacity;
510 } else {
511 m_threadContext.rewindBufferInterval = 0;
512 m_threadContext.rewindBufferCapacity = 0;
513 }
514 }
515}
516
517void GameController::rewind(int states) {
518 threadInterrupt();
519 if (!states) {
520 GBARewindAll(&m_threadContext);
521 } else {
522 GBARewind(&m_threadContext, states);
523 }
524 threadContinue();
525 emit frameAvailable(m_drawContext);
526 emit rewound(&m_threadContext);
527}
528
529void GameController::startRewinding() {
530 if (!m_gameOpen || m_rewindTimer.isActive()) {
531 return;
532 }
533 if (m_multiplayer && m_multiplayer->attached() > 1) {
534 return;
535 }
536 m_wasPaused = isPaused();
537 if (!GBAThreadIsPaused(&m_threadContext)) {
538 GBAThreadPause(&m_threadContext);
539 }
540 m_rewindTimer.start();
541}
542
543void GameController::stopRewinding() {
544 if (!m_rewindTimer.isActive()) {
545 return;
546 }
547 m_rewindTimer.stop();
548 bool signalsBlocked = blockSignals(true);
549 setPaused(m_wasPaused);
550 blockSignals(signalsBlocked);
551}
552
553void GameController::keyPressed(int key) {
554 int mappedKey = 1 << key;
555 m_activeKeys |= mappedKey;
556 if (!m_inputController->allowOpposing()) {
557 if ((m_activeKeys & 0x30) == 0x30) {
558 m_inactiveKeys |= mappedKey ^ 0x30;
559 m_activeKeys ^= mappedKey ^ 0x30;
560 }
561 if ((m_activeKeys & 0xC0) == 0xC0) {
562 m_inactiveKeys |= mappedKey ^ 0xC0;
563 m_activeKeys ^= mappedKey ^ 0xC0;
564 }
565 }
566 updateKeys();
567}
568
569void GameController::keyReleased(int key) {
570 int mappedKey = 1 << key;
571 m_activeKeys &= ~mappedKey;
572 if (!m_inputController->allowOpposing()) {
573 if (mappedKey & 0x30) {
574 m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
575 m_inactiveKeys &= ~0x30;
576 }
577 if (mappedKey & 0xC0) {
578 m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
579 m_inactiveKeys &= ~0xC0;
580 }
581 }
582 updateKeys();
583}
584
585void GameController::clearKeys() {
586 m_activeKeys = 0;
587 m_inactiveKeys = 0;
588 updateKeys();
589}
590
591void GameController::setAudioBufferSamples(int samples) {
592 if (m_audioProcessor) {
593 threadInterrupt();
594 redoSamples(samples);
595 threadContinue();
596 QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Q_ARG(int, samples));
597 }
598}
599
600void GameController::setAudioSampleRate(unsigned rate) {
601 if (!rate) {
602 return;
603 }
604 if (m_audioProcessor) {
605 threadInterrupt();
606 redoSamples(m_audioProcessor->getBufferSamples());
607 threadContinue();
608 QMetaObject::invokeMethod(m_audioProcessor, "requestSampleRate", Q_ARG(unsigned, rate));
609 }
610}
611
612void GameController::setAudioChannelEnabled(int channel, bool enable) {
613 if (channel > 5 || channel < 0) {
614 return;
615 }
616 m_audioChannels[channel] = enable;
617 if (isLoaded()) {
618 switch (channel) {
619 case 0:
620 case 1:
621 case 2:
622 case 3:
623 m_threadContext.gba->audio.forceDisableCh[channel] = !enable;
624 break;
625 case 4:
626 m_threadContext.gba->audio.forceDisableChA = !enable;
627 break;
628 case 5:
629 m_threadContext.gba->audio.forceDisableChB = !enable;
630 break;
631 }
632 }
633}
634
635void GameController::setVideoLayerEnabled(int layer, bool enable) {
636 if (layer > 4 || layer < 0) {
637 return;
638 }
639 m_videoLayers[layer] = enable;
640 if (isLoaded()) {
641 switch (layer) {
642 case 0:
643 case 1:
644 case 2:
645 case 3:
646 m_threadContext.gba->video.renderer->disableBG[layer] = !enable;
647 break;
648 case 4:
649 m_threadContext.gba->video.renderer->disableOBJ = !enable;
650 break;
651 }
652 }
653}
654
655void GameController::setFPSTarget(float fps) {
656 threadInterrupt();
657 m_fpsTarget = fps;
658 m_threadContext.fpsTarget = fps;
659 if (m_turbo && m_turboSpeed > 0) {
660 m_threadContext.fpsTarget *= m_turboSpeed;
661 }
662 if (m_audioProcessor) {
663 redoSamples(m_audioProcessor->getBufferSamples());
664 }
665 threadContinue();
666}
667
668void GameController::setSkipBIOS(bool set) {
669 threadInterrupt();
670 m_threadContext.skipBios = set;
671 threadContinue();
672}
673
674void GameController::setUseBIOS(bool use) {
675 if (use == m_useBios) {
676 return;
677 }
678 m_useBios = use;
679 if (m_gameOpen) {
680 closeGame();
681 openGame();
682 }
683}
684
685void GameController::loadState(int slot) {
686 if (slot > 0 && slot != m_stateSlot) {
687 m_stateSlot = slot;
688 m_backupSaveState.clear();
689 }
690 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
691 GameController* controller = static_cast<GameController*>(context->userData);
692 if (!controller->m_backupLoadState) {
693 controller->m_backupLoadState = new GBASerializedState;
694 }
695 GBASerialize(context->gba, controller->m_backupLoadState);
696 if (GBALoadState(context, context->stateDir, controller->m_stateSlot)) {
697 controller->frameAvailable(controller->m_drawContext);
698 controller->stateLoaded(context);
699 }
700 });
701}
702
703void GameController::saveState(int slot) {
704 if (slot > 0) {
705 m_stateSlot = slot;
706 }
707 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
708 GameController* controller = static_cast<GameController*>(context->userData);
709 VFile* vf = GBAGetState(context->gba, context->stateDir, controller->m_stateSlot, false);
710 if (vf) {
711 controller->m_backupSaveState.resize(vf->size(vf));
712 vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
713 vf->close(vf);
714 }
715 GBASaveState(context, context->stateDir, controller->m_stateSlot, true);
716 });
717}
718
719void GameController::loadBackupState() {
720 if (!m_backupLoadState) {
721 return;
722 }
723
724 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
725 GameController* controller = static_cast<GameController*>(context->userData);
726 if (GBADeserialize(context->gba, controller->m_backupLoadState)) {
727 GBALog(context->gba, GBA_LOG_STATUS, "Undid state load");
728 controller->frameAvailable(controller->m_drawContext);
729 controller->stateLoaded(context);
730 }
731 delete controller->m_backupLoadState;
732 controller->m_backupLoadState = nullptr;
733 });
734}
735
736void GameController::saveBackupState() {
737 if (m_backupSaveState.isEmpty()) {
738 return;
739 }
740
741 GBARunOnThread(&m_threadContext, [](GBAThread* context) {
742 GameController* controller = static_cast<GameController*>(context->userData);
743 VFile* vf = GBAGetState(context->gba, context->stateDir, controller->m_stateSlot, true);
744 if (vf) {
745 vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
746 vf->close(vf);
747 GBALog(context->gba, GBA_LOG_STATUS, "Undid state save");
748 }
749 controller->m_backupSaveState.clear();
750 });
751}
752
753void GameController::setVideoSync(bool set) {
754 m_videoSync = set;
755 if (!m_turbo) {
756 threadInterrupt();
757 m_threadContext.sync.videoFrameWait = set;
758 threadContinue();
759 }
760}
761
762void GameController::setAudioSync(bool set) {
763 m_audioSync = set;
764 if (!m_turbo) {
765 threadInterrupt();
766 m_threadContext.sync.audioWait = set;
767 threadContinue();
768 }
769}
770
771void GameController::setFrameskip(int skip) {
772 threadInterrupt();
773 m_threadContext.frameskip = skip;
774 if (isLoaded()) {
775 m_threadContext.gba->video.frameskip = skip;
776 }
777 threadContinue();
778}
779
780void GameController::setVolume(int volume) {
781 threadInterrupt();
782 m_threadContext.volume = volume;
783 if (isLoaded()) {
784 m_threadContext.gba->audio.masterVolume = volume;
785 }
786 threadContinue();
787}
788
789void GameController::setMute(bool mute) {
790 threadInterrupt();
791 m_threadContext.mute = mute;
792 if (isLoaded()) {
793 m_threadContext.gba->audio.masterVolume = mute ? 0 : m_threadContext.volume;
794 }
795 threadContinue();
796}
797
798void GameController::setTurbo(bool set, bool forced) {
799 if (m_turboForced && !forced) {
800 return;
801 }
802 if (m_turbo == set && m_turboForced == forced) {
803 // Don't interrupt the thread if we don't need to
804 return;
805 }
806 m_turbo = set;
807 m_turboForced = set && forced;
808 enableTurbo();
809}
810
811void GameController::setTurboSpeed(float ratio) {
812 m_turboSpeed = ratio;
813 enableTurbo();
814}
815
816void GameController::enableTurbo() {
817 threadInterrupt();
818 if (!m_turbo) {
819 m_threadContext.fpsTarget = m_fpsTarget;
820 m_threadContext.sync.audioWait = m_audioSync;
821 m_threadContext.sync.videoFrameWait = m_videoSync;
822 } else if (m_turboSpeed <= 0) {
823 m_threadContext.fpsTarget = m_fpsTarget;
824 m_threadContext.sync.audioWait = false;
825 m_threadContext.sync.videoFrameWait = false;
826 } else {
827 m_threadContext.fpsTarget = m_fpsTarget * m_turboSpeed;
828 m_threadContext.sync.audioWait = true;
829 m_threadContext.sync.videoFrameWait = false;
830 }
831 if (m_audioProcessor) {
832 redoSamples(m_audioProcessor->getBufferSamples());
833 }
834 threadContinue();
835}
836
837void GameController::setAVStream(GBAAVStream* stream) {
838 threadInterrupt();
839 m_threadContext.stream = stream;
840 if (isLoaded()) {
841 m_threadContext.gba->stream = stream;
842 }
843 threadContinue();
844}
845
846void GameController::clearAVStream() {
847 threadInterrupt();
848 m_threadContext.stream = nullptr;
849 if (isLoaded()) {
850 m_threadContext.gba->stream = nullptr;
851 }
852 threadContinue();
853}
854
855#ifdef USE_PNG
856void GameController::screenshot() {
857 GBARunOnThread(&m_threadContext, GBAThreadTakeScreenshot);
858}
859#endif
860
861void GameController::reloadAudioDriver() {
862 int samples = 0;
863 unsigned sampleRate = 0;
864 if (m_audioProcessor) {
865 QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
866 samples = m_audioProcessor->getBufferSamples();
867 sampleRate = m_audioProcessor->sampleRate();
868 delete m_audioProcessor;
869 }
870 m_audioProcessor = AudioProcessor::create();
871 if (samples) {
872 m_audioProcessor->setBufferSamples(samples);
873 }
874 if (sampleRate) {
875 m_audioProcessor->requestSampleRate(sampleRate);
876 }
877 m_audioProcessor->moveToThread(m_audioThread);
878 connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
879 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
880 connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
881 if (isLoaded()) {
882 m_audioProcessor->setInput(&m_threadContext);
883 QMetaObject::invokeMethod(m_audioProcessor, "start");
884 }
885}
886
887void GameController::setLuminanceValue(uint8_t value) {
888 m_luxValue = value;
889 value = std::max<int>(value - 0x16, 0);
890 m_luxLevel = 10;
891 for (int i = 0; i < 10; ++i) {
892 if (value < GBA_LUX_LEVELS[i]) {
893 m_luxLevel = i;
894 break;
895 }
896 }
897 emit luminanceValueChanged(m_luxValue);
898}
899
900void GameController::setLuminanceLevel(int level) {
901 int value = 0x16;
902 level = std::max(0, std::min(10, level));
903 if (level > 0) {
904 value += GBA_LUX_LEVELS[level - 1];
905 }
906 setLuminanceValue(value);
907}
908
909void GameController::setRealTime() {
910 m_rtc.override = GBARTCGenericSource::RTC_NO_OVERRIDE;
911}
912
913void GameController::setFixedTime(const QDateTime& time) {
914 m_rtc.override = GBARTCGenericSource::RTC_FIXED;
915 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
916}
917
918void GameController::setFakeEpoch(const QDateTime& time) {
919 m_rtc.override = GBARTCGenericSource::RTC_FAKE_EPOCH;
920 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
921}
922
923void GameController::updateKeys() {
924 int activeKeys = m_activeKeys;
925 activeKeys |= m_activeButtons;
926 activeKeys &= ~m_inactiveKeys;
927 m_threadContext.activeKeys = activeKeys;
928}
929
930void GameController::redoSamples(int samples) {
931#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
932 float sampleRate = 0x8000;
933 float ratio;
934 if (m_threadContext.gba) {
935 sampleRate = m_threadContext.gba->audio.sampleRate;
936 }
937 ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, m_audioProcess->sampleRate());
938 m_threadContext.audioBuffers = ceil(samples / ratio);
939#else
940 m_threadContext.audioBuffers = samples;
941#endif
942 if (m_threadContext.gba) {
943 GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
944 }
945 QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
946}
947
948void GameController::setLogLevel(int levels) {
949 threadInterrupt();
950 m_logLevels = levels;
951 threadContinue();
952}
953
954void GameController::enableLogLevel(int levels) {
955 threadInterrupt();
956 m_logLevels |= levels;
957 threadContinue();
958}
959
960void GameController::disableLogLevel(int levels) {
961 threadInterrupt();
962 m_logLevels &= ~levels;
963 threadContinue();
964}
965
966void GameController::pollEvents() {
967 if (!m_inputController) {
968 return;
969 }
970
971 m_activeButtons = m_inputController->pollEvents();
972 updateKeys();
973}