all repos — mgba @ 54ef61f715d59e50429a3b3982c7f32e56b7b8eb

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