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