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