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
11#include <QDateTime>
12#include <QThread>
13
14#include <ctime>
15
16extern "C" {
17#include "gba/audio.h"
18#include "gba/gba.h"
19#include "gba/serialize.h"
20#include "gba/renderers/video-software.h"
21#include "gba/supervisor/config.h"
22#include "util/vfs.h"
23}
24
25using namespace QGBA;
26using namespace std;
27
28const int GameController::LUX_LEVELS[10] = { 5, 11, 18, 27, 42, 62, 84, 109, 139, 183 };
29
30GameController::GameController(QObject* parent)
31 : QObject(parent)
32 , m_drawContext(new uint32_t[256 * 256])
33 , m_threadContext()
34 , m_activeKeys(0)
35 , m_logLevels(0)
36 , m_gameOpen(false)
37 , m_audioThread(new QThread(this))
38 , m_audioProcessor(AudioProcessor::create())
39 , m_videoSync(VIDEO_SYNC)
40 , m_audioSync(AUDIO_SYNC)
41 , m_turbo(false)
42 , m_turboForced(false)
43 , m_inputController(nullptr)
44{
45 m_renderer = new GBAVideoSoftwareRenderer;
46 GBAVideoSoftwareRendererCreate(m_renderer);
47 m_renderer->outputBuffer = (color_t*) m_drawContext;
48 m_renderer->outputBufferStride = 256;
49
50 GBACheatDeviceCreate(&m_cheatDevice);
51
52 m_threadContext.state = THREAD_INITIALIZED;
53 m_threadContext.debugger = 0;
54 m_threadContext.frameskip = 0;
55 m_threadContext.bios = 0;
56 m_threadContext.renderer = &m_renderer->d;
57 m_threadContext.userData = this;
58 m_threadContext.rewindBufferCapacity = 0;
59 m_threadContext.cheats = &m_cheatDevice;
60 m_threadContext.logLevel = -1;
61
62 m_lux.p = this;
63 m_lux.sample = [] (GBALuminanceSource* context) {
64 GameControllerLux* lux = static_cast<GameControllerLux*>(context);
65 lux->value = 0xFF - lux->p->m_luxValue;
66 };
67
68 m_lux.readLuminance = [] (GBALuminanceSource* context) {
69 GameControllerLux* lux = static_cast<GameControllerLux*>(context);
70 return lux->value;
71 };
72 setLuminanceLevel(0);
73
74 m_rtc.p = this;
75 m_rtc.override = GameControllerRTC::NO_OVERRIDE;
76 m_rtc.sample = [] (GBARTCSource* context) { };
77 m_rtc.unixTime = [] (GBARTCSource* context) -> time_t {
78 GameControllerRTC* rtc = static_cast<GameControllerRTC*>(context);
79 switch (rtc->override) {
80 case GameControllerRTC::NO_OVERRIDE:
81 default:
82 return time(nullptr);
83 case GameControllerRTC::FIXED:
84 return rtc->value;
85 case GameControllerRTC::FAKE_EPOCH:
86 return rtc->value + rtc->p->m_threadContext.gba->video.frameCounter * (int64_t) VIDEO_TOTAL_LENGTH / GBA_ARM7TDMI_FREQUENCY;
87 }
88 };
89
90 m_threadContext.startCallback = [] (GBAThread* context) {
91 GameController* controller = static_cast<GameController*>(context->userData);
92 controller->m_audioProcessor->setInput(context);
93 // Override the GBA object's log level to prevent stdout spew
94 context->gba->logLevel = GBA_LOG_FATAL;
95 context->gba->luminanceSource = &controller->m_lux;
96 context->gba->rtcSource = &controller->m_rtc;
97 controller->gameStarted(context);
98 };
99
100 m_threadContext.cleanCallback = [] (GBAThread* context) {
101 GameController* controller = static_cast<GameController*>(context->userData);
102 controller->gameStopped(context);
103 };
104
105 m_threadContext.frameCallback = [] (GBAThread* context) {
106 GameController* controller = static_cast<GameController*>(context->userData);
107 controller->m_pauseMutex.lock();
108 if (controller->m_pauseAfterFrame) {
109 GBAThreadPauseFromThread(context);
110 controller->m_pauseAfterFrame = false;
111 controller->gamePaused(&controller->m_threadContext);
112 }
113 controller->m_pauseMutex.unlock();
114 controller->frameAvailable(controller->m_drawContext);
115 };
116
117 m_threadContext.logHandler = [] (GBAThread* context, enum GBALogLevel level, const char* format, va_list args) {
118 GameController* controller = static_cast<GameController*>(context->userData);
119 if (level == GBA_LOG_FATAL) {
120 QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
121 } else if (!(controller->m_logLevels & level)) {
122 return;
123 }
124 controller->postLog(level, QString().vsprintf(format, args));
125 };
126
127 m_audioThread->start(QThread::TimeCriticalPriority);
128 m_audioProcessor->moveToThread(m_audioThread);
129 connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
130 connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
131 connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
132 connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
133
134#ifdef BUILD_SDL
135 connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(testSDLEvents()));
136#endif
137}
138
139GameController::~GameController() {
140 m_audioThread->quit();
141 m_audioThread->wait();
142 disconnect();
143 closeGame();
144 delete m_renderer;
145 delete[] m_drawContext;
146}
147
148void GameController::setOverride(const GBACartridgeOverride& override) {
149 m_threadContext.override = override;
150 m_threadContext.hasOverride = true;
151}
152
153void GameController::setOptions(const GBAOptions* opts) {
154 setFrameskip(opts->frameskip);
155 setAudioSync(opts->audioSync);
156 setVideoSync(opts->videoSync);
157 setSkipBIOS(opts->skipBios);
158 setRewind(opts->rewindEnable, opts->rewindBufferCapacity, opts->rewindBufferInterval);
159
160 threadInterrupt();
161 m_threadContext.idleOptimization = opts->idleOptimization;
162 threadContinue();
163}
164
165#ifdef USE_GDB_STUB
166ARMDebugger* GameController::debugger() {
167 return m_threadContext.debugger;
168}
169
170void GameController::setDebugger(ARMDebugger* debugger) {
171 threadInterrupt();
172 if (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {
173 GBADetachDebugger(m_threadContext.gba);
174 }
175 m_threadContext.debugger = debugger;
176 if (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {
177 GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
178 }
179 threadContinue();
180}
181#endif
182
183void GameController::loadGame(const QString& path, bool dirmode) {
184 closeGame();
185 if (!dirmode) {
186 QFile file(path);
187 if (!file.open(QIODevice::ReadOnly)) {
188 return;
189 }
190 file.close();
191 }
192
193 m_fname = path;
194 m_dirmode = dirmode;
195 openGame();
196}
197
198void GameController::openGame() {
199 m_gameOpen = true;
200
201 m_pauseAfterFrame = false;
202
203 if (m_turbo) {
204 m_threadContext.sync.videoFrameWait = false;
205 m_threadContext.sync.audioWait = false;
206 } else {
207 m_threadContext.sync.videoFrameWait = m_videoSync;
208 m_threadContext.sync.audioWait = m_audioSync;
209 }
210
211 m_threadContext.gameDir = 0;
212 m_threadContext.fname = strdup(m_fname.toLocal8Bit().constData());
213 if (m_dirmode) {
214 m_threadContext.gameDir = VDirOpen(m_threadContext.fname);
215 m_threadContext.stateDir = m_threadContext.gameDir;
216 } else {
217 m_threadContext.rom = VFileOpen(m_threadContext.fname, O_RDONLY);
218#if ENABLE_LIBZIP
219 if (!m_threadContext.gameDir) {
220 m_threadContext.gameDir = VDirOpenZip(m_threadContext.fname, 0);
221 }
222#endif
223#if ENABLE_LZMA
224 if (!m_threadContext.gameDir) {
225 m_threadContext.gameDir = VDirOpen7z(m_threadContext.fname, 0);
226 }
227#endif
228 }
229
230 if (!m_bios.isNull()) {
231 m_threadContext.bios = VFileOpen(m_bios.toLocal8Bit().constData(), O_RDONLY);
232 }
233
234 if (!m_patch.isNull()) {
235 m_threadContext.patch = VFileOpen(m_patch.toLocal8Bit().constData(), O_RDONLY);
236 }
237
238 if (!GBAThreadStart(&m_threadContext)) {
239 m_gameOpen = false;
240 emit gameFailed();
241 }
242}
243
244void GameController::loadBIOS(const QString& path) {
245 if (m_bios == path) {
246 return;
247 }
248 m_bios = path;
249 if (m_gameOpen) {
250 closeGame();
251 openGame();
252 }
253}
254
255void GameController::loadPatch(const QString& path) {
256 m_patch = path;
257 if (m_gameOpen) {
258 closeGame();
259 openGame();
260 }
261}
262
263void GameController::closeGame() {
264 if (!m_gameOpen) {
265 return;
266 }
267 if (GBAThreadIsPaused(&m_threadContext)) {
268 GBAThreadUnpause(&m_threadContext);
269 }
270 GBAThreadEnd(&m_threadContext);
271 GBAThreadJoin(&m_threadContext);
272 if (m_threadContext.fname) {
273 free(const_cast<char*>(m_threadContext.fname));
274 m_threadContext.fname = nullptr;
275 }
276
277 m_patch = QString();
278
279 m_gameOpen = false;
280 emit gameStopped(&m_threadContext);
281}
282
283void GameController::crashGame(const QString& crashMessage) {
284 closeGame();
285 emit gameCrashed(crashMessage);
286}
287
288bool GameController::isPaused() {
289 if (!m_gameOpen) {
290 return false;
291 }
292 return GBAThreadIsPaused(&m_threadContext);
293}
294
295void GameController::setPaused(bool paused) {
296 if (paused == GBAThreadIsPaused(&m_threadContext)) {
297 return;
298 }
299 if (paused) {
300 GBAThreadPause(&m_threadContext);
301 emit gamePaused(&m_threadContext);
302 } else {
303 GBAThreadUnpause(&m_threadContext);
304 emit gameUnpaused(&m_threadContext);
305 }
306}
307
308void GameController::reset() {
309 GBAThreadReset(&m_threadContext);
310}
311
312void GameController::threadInterrupt() {
313 if (m_gameOpen) {
314 GBAThreadInterrupt(&m_threadContext);
315 }
316}
317
318void GameController::threadContinue() {
319 if (m_gameOpen) {
320 GBAThreadContinue(&m_threadContext);
321 }
322}
323
324void GameController::frameAdvance() {
325 m_pauseMutex.lock();
326 m_pauseAfterFrame = true;
327 setPaused(false);
328 m_pauseMutex.unlock();
329}
330
331void GameController::setRewind(bool enable, int capacity, int interval) {
332 if (m_gameOpen) {
333 threadInterrupt();
334 GBARewindSettingsChanged(&m_threadContext, enable ? capacity : 0, enable ? interval : 0);
335 threadContinue();
336 } else {
337 if (enable) {
338 m_threadContext.rewindBufferInterval = interval;
339 m_threadContext.rewindBufferCapacity = capacity;
340 } else {
341 m_threadContext.rewindBufferInterval = 0;
342 m_threadContext.rewindBufferCapacity = 0;
343 }
344 }
345}
346
347void GameController::rewind(int states) {
348 threadInterrupt();
349 if (!states) {
350 GBARewindAll(&m_threadContext);
351 } else {
352 GBARewind(&m_threadContext, states);
353 }
354 threadContinue();
355}
356
357void GameController::keyPressed(int key) {
358 int mappedKey = 1 << key;
359 m_activeKeys |= mappedKey;
360 updateKeys();
361}
362
363void GameController::keyReleased(int key) {
364 int mappedKey = 1 << key;
365 m_activeKeys &= ~mappedKey;
366 updateKeys();
367}
368
369void GameController::clearKeys() {
370 m_activeKeys = 0;
371 updateKeys();
372}
373
374void GameController::setAudioBufferSamples(int samples) {
375 threadInterrupt();
376 redoSamples(samples);
377 threadContinue();
378 QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Q_ARG(int, samples));
379}
380
381void GameController::setFPSTarget(float fps) {
382 threadInterrupt();
383 m_threadContext.fpsTarget = fps;
384 redoSamples(m_audioProcessor->getBufferSamples());
385 threadContinue();
386 QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
387}
388
389void GameController::setSkipBIOS(bool set) {
390 threadInterrupt();
391 m_threadContext.skipBios = set;
392 threadContinue();
393}
394
395void GameController::loadState(int slot) {
396 threadInterrupt();
397 GBALoadState(&m_threadContext, m_threadContext.stateDir, slot);
398 threadContinue();
399 emit stateLoaded(&m_threadContext);
400 emit frameAvailable(m_drawContext);
401}
402
403void GameController::saveState(int slot) {
404 threadInterrupt();
405 GBASaveState(&m_threadContext, m_threadContext.stateDir, slot, true);
406 threadContinue();
407}
408
409void GameController::setVideoSync(bool set) {
410 m_videoSync = set;
411 if (!m_turbo) {
412 threadInterrupt();
413 m_threadContext.sync.videoFrameWait = set;
414 threadContinue();
415 }
416}
417
418void GameController::setAudioSync(bool set) {
419 m_audioSync = set;
420 if (!m_turbo) {
421 threadInterrupt();
422 m_threadContext.sync.audioWait = set;
423 threadContinue();
424 }
425}
426
427void GameController::setFrameskip(int skip) {
428 m_threadContext.frameskip = skip;
429}
430
431void GameController::setTurbo(bool set, bool forced) {
432 if (m_turboForced && !forced) {
433 return;
434 }
435 m_turbo = set;
436 m_turboForced = set && forced;
437 threadInterrupt();
438 m_threadContext.sync.audioWait = set ? false : m_audioSync;
439 m_threadContext.sync.videoFrameWait = set ? false : m_videoSync;
440 threadContinue();
441}
442
443void GameController::setAVStream(GBAAVStream* stream) {
444 threadInterrupt();
445 m_threadContext.stream = stream;
446 threadContinue();
447}
448
449void GameController::clearAVStream() {
450 threadInterrupt();
451 m_threadContext.stream = nullptr;
452 threadContinue();
453}
454
455void GameController::setLuminanceValue(uint8_t value) {
456 m_luxValue = value;
457 value = std::max<int>(value - 0x16, 0);
458 m_luxLevel = 10;
459 for (int i = 0; i < 10; ++i) {
460 if (value < LUX_LEVELS[i]) {
461 m_luxLevel = i;
462 break;
463 }
464 }
465}
466
467void GameController::setLuminanceLevel(int level) {
468 int value = 0x16;
469 level = std::max(0, std::min(10, level));
470 if (level > 0) {
471 value += LUX_LEVELS[level - 1];
472 }
473 setLuminanceValue(value);
474}
475
476void GameController::setRealTime() {
477 m_rtc.override = GameControllerRTC::NO_OVERRIDE;
478}
479
480void GameController::setFixedTime(const QDateTime& time) {
481 m_rtc.override = GameControllerRTC::FIXED;
482 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
483}
484
485void GameController::setFakeEpoch(const QDateTime& time) {
486 m_rtc.override = GameControllerRTC::FAKE_EPOCH;
487 m_rtc.value = time.toMSecsSinceEpoch() / 1000;
488}
489
490void GameController::updateKeys() {
491 int activeKeys = m_activeKeys;
492#ifdef BUILD_SDL
493 activeKeys |= m_activeButtons;
494#endif
495 m_threadContext.activeKeys = activeKeys;
496}
497
498void GameController::redoSamples(int samples) {
499#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
500 float sampleRate = 0x8000;
501 float ratio;
502 if (m_threadContext.gba) {
503 sampleRate = m_threadContext.gba->audio.sampleRate;
504 }
505 ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, 44100);
506 m_threadContext.audioBuffers = ceil(samples / ratio);
507#else
508 m_threadContext.audioBuffers = samples;
509#endif
510 if (m_threadContext.gba) {
511 GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
512 }
513}
514
515void GameController::setLogLevel(int levels) {
516 threadInterrupt();
517 m_logLevels = levels;
518 threadContinue();
519}
520
521void GameController::enableLogLevel(int levels) {
522 threadInterrupt();
523 m_logLevels |= levels;
524 threadContinue();
525}
526
527void GameController::disableLogLevel(int levels) {
528 threadInterrupt();
529 m_logLevels &= ~levels;
530 threadContinue();
531}
532
533#ifdef BUILD_SDL
534void GameController::testSDLEvents() {
535 if (!m_inputController) {
536 return;
537 }
538
539 m_activeButtons = m_inputController->testSDLEvents();
540 updateKeys();
541}
542#endif