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