all repos — mgba @ 27a178fe3ce47f50ee5460a0ce7efb0bc523d60c

mGBA Game Boy Advance Emulator

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