all repos — mgba @ b8edf968a4d2d2eb09a521d05a2309ff526eb2be

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