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 "MultiplayerController.h"
11
12#include <QDateTime>
13#include <QThread>
14
15#include <ctime>
16
17extern "C" {
18#include "gba/audio.h"
19#include "gba/gba.h"
20#include "gba/serialize.h"
21#include "gba/sharkport.h"
22#include "gba/renderers/video-software.h"
23#include "gba/supervisor/config.h"
24#include "util/vfs.h"
25}
26
27using namespace QGBA;
28using namespace std;
29
30const int GameController::LUX_LEVELS[10] = { 5, 11, 18, 27, 42, 62, 84, 109, 139, 183 };
31
32GameController::GameController(QObject* parent)
33 : QObject(parent)
34 , m_drawContext(new uint32_t[256 * 256])
35 , m_threadContext()
36 , m_activeKeys(0)
37 , m_inactiveKeys(0)
38 , m_logLevels(0)
39 , m_gameOpen(false)
40 , m_audioThread(new QThread(this))
41 , m_audioProcessor(AudioProcessor::create())
42 , m_videoSync(VIDEO_SYNC)
43 , m_audioSync(AUDIO_SYNC)
44 , m_turbo(false)
45 , m_turboForced(false)
46 , m_inputController(nullptr)
47 , m_multiplayer(nullptr)
48{
49 m_renderer = new GBAVideoSoftwareRenderer;
50 GBAVideoSoftwareRendererCreate(m_renderer);
51 m_renderer->outputBuffer = (color_t*) m_drawContext;
52 m_renderer->outputBufferStride = 256;
53
54 GBACheatDeviceCreate(&m_cheatDevice);
55
56 m_threadContext.state = THREAD_INITIALIZED;
57 m_threadContext.debugger = 0;
58 m_threadContext.frameskip = 0;
59 m_threadContext.bios = 0;
60 m_threadContext.renderer = &m_renderer->d;
61 m_threadContext.userData = this;
62 m_threadContext.rewindBufferCapacity = 0;
63 m_threadContext.cheats = &m_cheatDevice;
64 m_threadContext.logLevel = -1;
65
66 m_lux.p = this;
67 m_lux.sample = [] (GBALuminanceSource* context) {
68 GameControllerLux* lux = static_cast<GameControllerLux*>(context);
69 lux->value = 0xFF - lux->p->m_luxValue;
70 };
71
72 m_lux.readLuminance = [] (GBALuminanceSource* context) {
73 GameControllerLux* lux = static_cast<GameControllerLux*>(context);
74 return lux->value;
75 };
76 setLuminanceLevel(0);
77
78 m_rtc.p = this;
79 m_rtc.override = GameControllerRTC::NO_OVERRIDE;
80 m_rtc.sample = [] (GBARTCSource* context) { };
81 m_rtc.unixTime = [] (GBARTCSource* context) -> time_t {
82 GameControllerRTC* rtc = static_cast<GameControllerRTC*>(context);
83 switch (rtc->override) {
84 case GameControllerRTC::NO_OVERRIDE:
85 default:
86 return time(nullptr);
87 case GameControllerRTC::FIXED:
88 return rtc->value;
89 case GameControllerRTC::FAKE_EPOCH:
90 return rtc->value + rtc->p->m_threadContext.gba->video.frameCounter * (int64_t) VIDEO_TOTAL_LENGTH / GBA_ARM7TDMI_FREQUENCY;
91 }
92 };
93
94 m_threadContext.startCallback = [] (GBAThread* context) {
95 GameController* controller = static_cast<GameController*>(context->userData);
96 controller->m_audioProcessor->setInput(context);
97 // Override the GBA object's log level to prevent stdout spew
98 context->gba->logLevel = GBA_LOG_FATAL;
99 context->gba->luminanceSource = &controller->m_lux;
100 context->gba->rtcSource = &controller->m_rtc;
101#ifdef BUILD_SDL
102 context->gba->rumble = controller->m_inputController->rumble();
103#endif
104 controller->gameStarted(context);
105 };
106
107 m_threadContext.cleanCallback = [] (GBAThread* context) {
108 GameController* controller = static_cast<GameController*>(context->userData);
109 controller->gameStopped(context);
110 };
111
112 m_threadContext.frameCallback = [] (GBAThread* context) {
113 GameController* controller = static_cast<GameController*>(context->userData);
114 controller->m_pauseMutex.lock();
115 if (controller->m_pauseAfterFrame) {
116 GBAThreadPauseFromThread(context);
117 controller->m_pauseAfterFrame = false;
118 controller->gamePaused(&controller->m_threadContext);
119 }
120 controller->m_pauseMutex.unlock();
121 controller->frameAvailable(controller->m_drawContext);
122 };
123
124 m_threadContext.logHandler = [] (GBAThread* context, enum GBALogLevel level, const char* format, va_list args) {
125 static const char* stubMessage = "Stub software interrupt";
126 GameController* controller = static_cast<GameController*>(context->userData);
127 if (level == GBA_LOG_STUB && strncmp(stubMessage, format, strlen(stubMessage)) == 0) {
128 va_list argc;
129 va_copy(argc, args);
130 int immediate = va_arg(argc, int);
131 controller->unimplementedBiosCall(immediate);
132 }
133 if (level == GBA_LOG_FATAL) {
134 QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
135 } else if (!(controller->m_logLevels & level)) {
136 return;
137 }
138 controller->postLog(level, QString().vsprintf(format, args));
139 };
140
141 m_audioThread->start(QThread::TimeCriticalPriority);
142 m_audioProcessor->moveToThread(m_audioThread);
143 connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
144 connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
145 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
146 connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
147
148#ifdef BUILD_SDL
149 connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(testSDLEvents()));
150#endif
151}
152
153GameController::~GameController() {
154 m_audioThread->quit();
155 m_audioThread->wait();
156 disconnect();
157 clearMultiplayerController();
158 closeGame();
159 GBACheatDeviceDestroy(&m_cheatDevice);
160 delete m_renderer;
161 delete[] m_drawContext;
162}
163
164void GameController::setMultiplayerController(std::shared_ptr<MultiplayerController> controller) {
165 if (controller == m_multiplayer) {
166 return;
167 }
168 clearMultiplayerController();
169 m_multiplayer = controller;
170 controller->attachGame(this);
171}
172
173void GameController::clearMultiplayerController() {
174 if (!m_multiplayer) {
175 return;
176 }
177 m_multiplayer->detachGame(this);
178 m_multiplayer.reset();
179}
180
181void GameController::setOverride(const GBACartridgeOverride& override) {
182 m_threadContext.override = override;
183 m_threadContext.hasOverride = true;
184}
185
186void GameController::setOptions(const GBAOptions* opts) {
187 setFrameskip(opts->frameskip);
188 setAudioSync(opts->audioSync);
189 setVideoSync(opts->videoSync);
190 setSkipBIOS(opts->skipBios);
191 setUseBIOS(opts->useBios);
192 setRewind(opts->rewindEnable, opts->rewindBufferCapacity, opts->rewindBufferInterval);
193 setVolume(opts->volume);
194 setMute(opts->mute);
195
196 threadInterrupt();
197 m_threadContext.idleOptimization = opts->idleOptimization;
198 threadContinue();
199}
200
201#ifdef USE_GDB_STUB
202ARMDebugger* GameController::debugger() {
203 return m_threadContext.debugger;
204}
205
206void GameController::setDebugger(ARMDebugger* debugger) {
207 threadInterrupt();
208 if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
209 GBADetachDebugger(m_threadContext.gba);
210 }
211 m_threadContext.debugger = debugger;
212 if (m_threadContext.debugger && GBAThreadIsActive(&m_threadContext)) {
213 GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
214 }
215 threadContinue();
216}
217#endif
218
219void GameController::loadGame(const QString& path, bool dirmode) {
220 closeGame();
221 if (!dirmode) {
222 QFile file(path);
223 if (!file.open(QIODevice::ReadOnly)) {
224 return;
225 }
226 file.close();
227 }
228
229 m_fname = path;
230 m_dirmode = dirmode;
231 openGame();
232}
233
234void GameController::openGame() {
235 m_gameOpen = true;
236
237 m_pauseAfterFrame = false;
238
239 if (m_turbo) {
240 m_threadContext.sync.videoFrameWait = false;
241 m_threadContext.sync.audioWait = false;
242 } else {
243 m_threadContext.sync.videoFrameWait = m_videoSync;
244 m_threadContext.sync.audioWait = m_audioSync;
245 }
246
247 m_threadContext.gameDir = 0;
248 m_threadContext.fname = strdup(m_fname.toLocal8Bit().constData());
249 if (m_dirmode) {
250 m_threadContext.gameDir = VDirOpen(m_threadContext.fname);
251 m_threadContext.stateDir = m_threadContext.gameDir;
252 } else {
253 m_threadContext.rom = VFileOpen(m_threadContext.fname, O_RDONLY);
254#if USE_LIBZIP
255 if (!m_threadContext.gameDir) {
256 m_threadContext.gameDir = VDirOpenZip(m_threadContext.fname, 0);
257 }
258#endif
259#if USE_LZMA
260 if (!m_threadContext.gameDir) {
261 m_threadContext.gameDir = VDirOpen7z(m_threadContext.fname, 0);
262 }
263#endif
264 }
265
266 if (!m_bios.isNull() &&m_useBios) {
267 m_threadContext.bios = VFileOpen(m_bios.toLocal8Bit().constData(), O_RDONLY);
268 } else {
269 m_threadContext.bios = nullptr;
270 }
271
272 if (!m_patch.isNull()) {
273 m_threadContext.patch = VFileOpen(m_patch.toLocal8Bit().constData(), O_RDONLY);
274 }
275
276#ifdef BUILD_SDL
277 m_inputController->recalibrateAxes();
278#endif
279
280 if (!GBAThreadStart(&m_threadContext)) {
281 m_gameOpen = false;
282 emit gameFailed();
283 }
284}
285
286void GameController::loadBIOS(const QString& path) {
287 if (m_bios == path) {
288 return;
289 }
290 m_bios = path;
291 if (m_gameOpen) {
292 closeGame();
293 openGame();
294 }
295}
296
297void GameController::loadPatch(const QString& path) {
298 if (m_gameOpen) {
299 closeGame();
300 m_patch = path;
301 openGame();
302 } else {
303 m_patch = path;
304 }
305}
306
307void GameController::importSharkport(const QString& path) {
308 if (!m_gameOpen) {
309 return;
310 }
311 VFile* vf = VFileOpen(path.toLocal8Bit().constData(), O_RDONLY);
312 if (!vf) {
313 return;
314 }
315 threadInterrupt();
316 GBASavedataImportSharkPort(m_threadContext.gba, vf, false);
317 threadContinue();
318 vf->close(vf);
319}
320
321void GameController::exportSharkport(const QString& path) {
322 if (!m_gameOpen) {
323 return;
324 }
325 VFile* vf = VFileOpen(path.toLocal8Bit().constData(), O_WRONLY | O_CREAT | O_TRUNC);
326 if (!vf) {
327 return;
328 }
329 threadInterrupt();
330 GBASavedataExportSharkPort(m_threadContext.gba, vf);
331 threadContinue();
332 vf->close(vf);
333}
334
335void GameController::closeGame() {
336 if (!m_gameOpen) {
337 return;
338 }
339 if (GBAThreadIsPaused(&m_threadContext)) {
340 GBAThreadUnpause(&m_threadContext);
341 }
342 GBAThreadEnd(&m_threadContext);
343 GBAThreadJoin(&m_threadContext);
344 if (m_threadContext.fname) {
345 free(const_cast<char*>(m_threadContext.fname));
346 m_threadContext.fname = nullptr;
347 }
348
349 m_patch = QString();
350
351 for (size_t i = 0; i < GBACheatSetsSize(&m_cheatDevice.cheats); ++i) {
352 GBACheatSet* set = *GBACheatSetsGetPointer(&m_cheatDevice.cheats, i);
353 GBACheatSetDeinit(set);
354 delete set;
355 }
356 GBACheatSetsClear(&m_cheatDevice.cheats);
357
358 m_gameOpen = false;
359 emit gameStopped(&m_threadContext);
360}
361
362void GameController::crashGame(const QString& crashMessage) {
363 closeGame();
364 emit gameCrashed(crashMessage);
365}
366
367bool GameController::isPaused() {
368 if (!m_gameOpen) {
369 return false;
370 }
371 return GBAThreadIsPaused(&m_threadContext);
372}
373
374void GameController::setPaused(bool paused) {
375 if (!m_gameOpen || paused == GBAThreadIsPaused(&m_threadContext)) {
376 return;
377 }
378 if (paused) {
379 GBAThreadPause(&m_threadContext);
380 emit gamePaused(&m_threadContext);
381 } else {
382 GBAThreadUnpause(&m_threadContext);
383 emit gameUnpaused(&m_threadContext);
384 }
385}
386
387void GameController::reset() {
388 GBAThreadReset(&m_threadContext);
389}
390
391void GameController::threadInterrupt() {
392 if (m_gameOpen) {
393 GBAThreadInterrupt(&m_threadContext);
394 }
395}
396
397void GameController::threadContinue() {
398 if (m_gameOpen) {
399 GBAThreadContinue(&m_threadContext);
400 }
401}
402
403void GameController::frameAdvance() {
404 m_pauseMutex.lock();
405 m_pauseAfterFrame = true;
406 setPaused(false);
407 m_pauseMutex.unlock();
408}
409
410void GameController::setRewind(bool enable, int capacity, int interval) {
411 if (m_gameOpen) {
412 threadInterrupt();
413 GBARewindSettingsChanged(&m_threadContext, enable ? capacity : 0, enable ? interval : 0);
414 threadContinue();
415 } else {
416 if (enable) {
417 m_threadContext.rewindBufferInterval = interval;
418 m_threadContext.rewindBufferCapacity = capacity;
419 } else {
420 m_threadContext.rewindBufferInterval = 0;
421 m_threadContext.rewindBufferCapacity = 0;
422 }
423 }
424}
425
426void GameController::rewind(int states) {
427 threadInterrupt();
428 if (!states) {
429 GBARewindAll(&m_threadContext);
430 } else {
431 GBARewind(&m_threadContext, states);
432 }
433 threadContinue();
434 emit rewound(&m_threadContext);
435 emit frameAvailable(m_drawContext);
436}
437
438void GameController::keyPressed(int key) {
439 int mappedKey = 1 << key;
440 m_activeKeys |= mappedKey;
441 if (!m_inputController->allowOpposing()) {
442 if ((m_activeKeys & 0x30) == 0x30) {
443 m_inactiveKeys |= mappedKey ^ 0x30;
444 m_activeKeys ^= mappedKey ^ 0x30;
445 }
446 if ((m_activeKeys & 0xC0) == 0xC0) {
447 m_inactiveKeys |= mappedKey ^ 0xC0;
448 m_activeKeys ^= mappedKey ^ 0xC0;
449 }
450 }
451 updateKeys();
452}
453
454void GameController::keyReleased(int key) {
455 int mappedKey = 1 << key;
456 m_activeKeys &= ~mappedKey;
457 if (!m_inputController->allowOpposing()) {
458 if (mappedKey & 0x30) {
459 m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
460 m_inactiveKeys &= ~0x30;
461 }
462 if (mappedKey & 0xC0) {
463 m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
464 m_inactiveKeys &= ~0xC0;
465 }
466 }
467 updateKeys();
468}
469
470void GameController::clearKeys() {
471 m_activeKeys = 0;
472 m_inactiveKeys = 0;
473 updateKeys();
474}
475
476void GameController::setAudioBufferSamples(int samples) {
477 threadInterrupt();
478 redoSamples(samples);
479 threadContinue();
480 QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Q_ARG(int, samples));
481}
482
483void GameController::setFPSTarget(float fps) {
484 threadInterrupt();
485 m_threadContext.fpsTarget = fps;
486 redoSamples(m_audioProcessor->getBufferSamples());
487 threadContinue();
488 QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
489}
490
491void GameController::setSkipBIOS(bool set) {
492 threadInterrupt();
493 m_threadContext.skipBios = set;
494 threadContinue();
495}
496
497void GameController::setUseBIOS(bool use) {
498 threadInterrupt();
499 m_useBios = use;
500 threadContinue();
501}
502
503void GameController::loadState(int slot) {
504 threadInterrupt();
505 GBALoadState(&m_threadContext, m_threadContext.stateDir, slot);
506 threadContinue();
507 emit stateLoaded(&m_threadContext);
508 emit frameAvailable(m_drawContext);
509}
510
511void GameController::saveState(int slot) {
512 threadInterrupt();
513 GBASaveState(&m_threadContext, m_threadContext.stateDir, slot, true);
514 threadContinue();
515}
516
517void GameController::setVideoSync(bool set) {
518 m_videoSync = set;
519 if (!m_turbo) {
520 threadInterrupt();
521 m_threadContext.sync.videoFrameWait = set;
522 threadContinue();
523 }
524}
525
526void GameController::setAudioSync(bool set) {
527 m_audioSync = set;
528 if (!m_turbo) {
529 threadInterrupt();
530 m_threadContext.sync.audioWait = set;
531 threadContinue();
532 }
533}
534
535void GameController::setFrameskip(int skip) {
536 m_threadContext.frameskip = skip;
537}
538
539void GameController::setVolume(int volume) {
540 threadInterrupt();
541 m_threadContext.volume = volume;
542 if (m_gameOpen) {
543 m_threadContext.gba->audio.masterVolume = volume;
544 }
545 threadContinue();
546}
547
548void GameController::setMute(bool mute) {
549 threadInterrupt();
550 m_threadContext.mute = mute;
551 if (m_gameOpen) {
552 m_threadContext.gba->audio.masterVolume = mute ? 0 : m_threadContext.volume;
553 }
554 threadContinue();
555}
556
557void GameController::setTurbo(bool set, bool forced) {
558 if (m_turboForced && !forced) {
559 return;
560 }
561 m_turbo = set;
562 m_turboForced = set && forced;
563 threadInterrupt();
564 m_threadContext.sync.audioWait = set ? false : m_audioSync;
565 m_threadContext.sync.videoFrameWait = set ? false : m_videoSync;
566 threadContinue();
567}
568
569void GameController::setAVStream(GBAAVStream* stream) {
570 threadInterrupt();
571 m_threadContext.stream = stream;
572 if (m_gameOpen) {
573 m_threadContext.gba->stream = stream;
574 }
575 threadContinue();
576}
577
578void GameController::clearAVStream() {
579 threadInterrupt();
580 m_threadContext.stream = nullptr;
581 if (m_gameOpen) {
582 m_threadContext.gba->stream = nullptr;
583 }
584 threadContinue();
585}
586
587#ifdef USE_PNG
588void GameController::screenshot() {
589 GBAThreadInterrupt(&m_threadContext);
590 GBAThreadTakeScreenshot(&m_threadContext);
591 GBAThreadContinue(&m_threadContext);
592}
593#endif
594
595void GameController::reloadAudioDriver() {
596 QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
597 int samples = m_audioProcessor->getBufferSamples();
598 delete m_audioProcessor;
599 m_audioProcessor = AudioProcessor::create();
600 m_audioProcessor->setBufferSamples(samples);
601 m_audioProcessor->moveToThread(m_audioThread);
602 connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
603 connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
604 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
605 connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
606 if (isLoaded()) {
607 m_audioProcessor->setInput(&m_threadContext);
608 QMetaObject::invokeMethod(m_audioProcessor, "start");
609 }
610}
611
612void GameController::setLuminanceValue(uint8_t value) {
613 m_luxValue = value;
614 value = std::max<int>(value - 0x16, 0);
615 m_luxLevel = 10;
616 for (int i = 0; i < 10; ++i) {
617 if (value < LUX_LEVELS[i]) {
618 m_luxLevel = i;
619 break;
620 }
621 }
622 emit luminanceValueChanged(m_luxValue);
623}
624
625void GameController::setLuminanceLevel(int level) {
626 int value = 0x16;
627 level = std::max(0, std::min(10, level));
628 if (level > 0) {
629 value += LUX_LEVELS[level - 1];
630 }
631 setLuminanceValue(value);
632}
633
634void GameController::setRealTime() {
635 m_rtc.override = GameControllerRTC::NO_OVERRIDE;
636}
637
638void GameController::setFixedTime(const QDateTime& time) {
639 m_rtc.override = GameControllerRTC::FIXED;
640 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
641}
642
643void GameController::setFakeEpoch(const QDateTime& time) {
644 m_rtc.override = GameControllerRTC::FAKE_EPOCH;
645 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
646}
647
648void GameController::updateKeys() {
649 int activeKeys = m_activeKeys;
650#ifdef BUILD_SDL
651 activeKeys |= m_activeButtons;
652#endif
653 activeKeys &= ~m_inactiveKeys;
654 m_threadContext.activeKeys = activeKeys;
655}
656
657void GameController::redoSamples(int samples) {
658#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
659 float sampleRate = 0x8000;
660 float ratio;
661 if (m_threadContext.gba) {
662 sampleRate = m_threadContext.gba->audio.sampleRate;
663 }
664 ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, 44100);
665 m_threadContext.audioBuffers = ceil(samples / ratio);
666#else
667 m_threadContext.audioBuffers = samples;
668#endif
669 if (m_threadContext.gba) {
670 GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
671 }
672}
673
674void GameController::setLogLevel(int levels) {
675 threadInterrupt();
676 m_logLevels = levels;
677 threadContinue();
678}
679
680void GameController::enableLogLevel(int levels) {
681 threadInterrupt();
682 m_logLevels |= levels;
683 threadContinue();
684}
685
686void GameController::disableLogLevel(int levels) {
687 threadInterrupt();
688 m_logLevels &= ~levels;
689 threadContinue();
690}
691
692#ifdef BUILD_SDL
693void GameController::testSDLEvents() {
694 if (!m_inputController) {
695 return;
696 }
697
698 m_activeButtons = m_inputController->testSDLEvents();
699 updateKeys();
700}
701#endif