all repos — mgba @ 569e6ef7db2ac225af64ecd43e916147a6ae3141

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			MutexLock(&controller->m_threadContext.stateMutex);
113			controller->m_threadContext.state = THREAD_EXITING;
114			MutexUnlock(&controller->m_threadContext.stateMutex);
115			QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
116		} else if (!(controller->m_logLevels & level)) {
117			return;
118		}
119		controller->postLog(level, QString().vsprintf(format, args));
120	};
121
122	m_audioThread->start(QThread::TimeCriticalPriority);
123	m_audioProcessor->moveToThread(m_audioThread);
124	connect(this, SIGNAL(gameStarted(GBAThread*)), m_audioProcessor, SLOT(start()));
125	connect(this, SIGNAL(gameStopped(GBAThread*)), m_audioProcessor, SLOT(pause()));
126	connect(this, SIGNAL(gamePaused(GBAThread*)), m_audioProcessor, SLOT(pause()));
127	connect(this, SIGNAL(gameUnpaused(GBAThread*)), m_audioProcessor, SLOT(start()));
128
129#ifdef BUILD_SDL
130	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(testSDLEvents()));
131#endif
132}
133
134GameController::~GameController() {
135	m_audioThread->quit();
136	m_audioThread->wait();
137	disconnect();
138	closeGame();
139	delete m_renderer;
140	delete[] m_drawContext;
141}
142
143#ifdef USE_GDB_STUB
144ARMDebugger* GameController::debugger() {
145	return m_threadContext.debugger;
146}
147
148void GameController::setDebugger(ARMDebugger* debugger) {
149	bool wasPaused = isPaused();
150	setPaused(true);
151	if (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {
152		GBADetachDebugger(m_threadContext.gba);
153	}
154	m_threadContext.debugger = debugger;
155	if (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {
156		GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
157	}
158	setPaused(wasPaused);
159}
160#endif
161
162void GameController::loadGame(const QString& path, bool dirmode) {
163	closeGame();
164	if (!dirmode) {
165		QFile file(path);
166		if (!file.open(QIODevice::ReadOnly)) {
167			return;
168		}
169		file.close();
170	}
171
172	m_fname = path;
173	m_dirmode = dirmode;
174	openGame();
175}
176
177void GameController::openGame() {
178	m_gameOpen = true;
179
180	m_pauseAfterFrame = false;
181
182	if (m_turbo) {
183		m_threadContext.sync.videoFrameWait = false;
184		m_threadContext.sync.audioWait = false;
185	} else {
186		m_threadContext.sync.videoFrameWait = m_videoSync;
187		m_threadContext.sync.audioWait = m_audioSync;
188	}
189
190	m_threadContext.fname = strdup(m_fname.toLocal8Bit().constData());
191	if (m_dirmode) {
192		m_threadContext.gameDir = VDirOpen(m_threadContext.fname);
193		m_threadContext.stateDir = m_threadContext.gameDir;
194	} else {
195		m_threadContext.rom = VFileOpen(m_threadContext.fname, O_RDONLY);
196#if ENABLE_LIBZIP
197		m_threadContext.gameDir = VDirOpenZip(m_threadContext.fname, 0);
198#endif
199	}
200
201	if (!m_bios.isNull()) {
202		m_threadContext.bios = VFileOpen(m_bios.toLocal8Bit().constData(), O_RDONLY);
203	}
204
205	if (!m_patch.isNull()) {
206		m_threadContext.patch = VFileOpen(m_patch.toLocal8Bit().constData(), O_RDONLY);
207	}
208
209	if (!GBAThreadStart(&m_threadContext)) {
210		m_gameOpen = false;
211	}
212}
213
214void GameController::loadBIOS(const QString& path) {
215	if (m_bios == path) {
216		return;
217	}
218	m_bios = path;
219	if (m_gameOpen) {
220		closeGame();
221		openGame();
222	}
223}
224
225void GameController::loadPatch(const QString& path) {
226	m_patch = path;
227	if (m_gameOpen) {
228		closeGame();
229		openGame();
230	}
231}
232
233void GameController::closeGame() {
234	if (!m_gameOpen) {
235		return;
236	}
237	if (GBAThreadIsPaused(&m_threadContext)) {
238		GBAThreadUnpause(&m_threadContext);
239	}
240	GBAThreadEnd(&m_threadContext);
241	GBAThreadJoin(&m_threadContext);
242	if (m_threadContext.fname) {
243		free(const_cast<char*>(m_threadContext.fname));
244		m_threadContext.fname = nullptr;
245	}
246
247	m_patch = QString();
248
249	m_gameOpen = false;
250	emit gameStopped(&m_threadContext);
251}
252
253void GameController::crashGame(const QString& crashMessage) {
254	closeGame();
255	emit gameCrashed(crashMessage);
256}
257
258bool GameController::isPaused() {
259	if (!m_gameOpen) {
260		return false;
261	}
262	return GBAThreadIsPaused(&m_threadContext);
263}
264
265void GameController::setPaused(bool paused) {
266	if (paused == GBAThreadIsPaused(&m_threadContext)) {
267		return;
268	}
269	if (paused) {
270		GBAThreadPause(&m_threadContext);
271		emit gamePaused(&m_threadContext);
272	} else {
273		GBAThreadUnpause(&m_threadContext);
274		emit gameUnpaused(&m_threadContext);
275	}
276}
277
278void GameController::reset() {
279	GBAThreadReset(&m_threadContext);
280}
281
282void GameController::threadInterrupt() {
283	if (m_gameOpen) {
284		GBAThreadInterrupt(&m_threadContext);
285	}
286}
287
288void GameController::threadContinue() {
289	if (m_gameOpen) {
290		GBAThreadContinue(&m_threadContext);
291	}
292}
293
294void GameController::frameAdvance() {
295	m_pauseMutex.lock();
296	m_pauseAfterFrame = true;
297	setPaused(false);
298	m_pauseMutex.unlock();
299}
300
301void GameController::keyPressed(int key) {
302	int mappedKey = 1 << key;
303	m_activeKeys |= mappedKey;
304	updateKeys();
305}
306
307void GameController::keyReleased(int key) {
308	int mappedKey = 1 << key;
309	m_activeKeys &= ~mappedKey;
310	updateKeys();
311}
312
313void GameController::clearKeys() {
314	m_activeKeys = 0;
315	updateKeys();
316}
317
318void GameController::setAudioBufferSamples(int samples) {
319	threadInterrupt();
320	redoSamples(samples);
321	threadContinue();
322	QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Q_ARG(int, samples));
323}
324
325void GameController::setFPSTarget(float fps) {
326	threadInterrupt();
327	m_threadContext.fpsTarget = fps;
328	redoSamples(m_audioProcessor->getBufferSamples());
329	threadContinue();
330	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
331}
332
333void GameController::setSkipBIOS(bool set) {
334	threadInterrupt();
335	m_threadContext.skipBios = set;
336	threadContinue();
337}
338
339void GameController::loadState(int slot) {
340	threadInterrupt();
341	GBALoadState(m_threadContext.gba, m_threadContext.stateDir, slot);
342	threadContinue();
343	emit stateLoaded(&m_threadContext);
344	emit frameAvailable(m_drawContext);
345}
346
347void GameController::saveState(int slot) {
348	threadInterrupt();
349	GBASaveState(m_threadContext.gba, m_threadContext.stateDir, slot, true);
350	threadContinue();
351}
352
353void GameController::setVideoSync(bool set) {
354	m_videoSync = set;
355	if (!m_turbo) {
356		threadInterrupt();
357		m_threadContext.sync.videoFrameWait = set;
358		threadContinue();
359	}
360}
361
362void GameController::setAudioSync(bool set) {
363	m_audioSync = set;
364	if (!m_turbo) {
365		threadInterrupt();
366		m_threadContext.sync.audioWait = set;
367		threadContinue();
368	}
369}
370
371void GameController::setFrameskip(int skip) {
372	m_threadContext.frameskip = skip;
373}
374
375void GameController::setTurbo(bool set, bool forced) {
376	if (m_turboForced && !forced) {
377		return;
378	}
379	m_turbo = set;
380	if (set) {
381		m_turboForced = forced;
382	} else {
383		m_turboForced = false;
384	}
385	threadInterrupt();
386	m_threadContext.sync.audioWait = set ? false : m_audioSync;
387	m_threadContext.sync.videoFrameWait = set ? false : m_videoSync;
388	threadContinue();
389}
390
391void GameController::setAVStream(GBAAVStream* stream) {
392	threadInterrupt();
393	m_threadContext.stream = stream;
394	threadContinue();
395}
396
397void GameController::clearAVStream() {
398	threadInterrupt();
399	m_threadContext.stream = nullptr;
400	threadContinue();
401}
402
403void GameController::setRealTime() {
404	m_rtc.override = GameControllerRTC::NO_OVERRIDE;
405}
406
407void GameController::setFixedTime(const QDateTime& time) {
408	m_rtc.override = GameControllerRTC::FIXED;
409	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
410}
411
412void GameController::setFakeEpoch(const QDateTime& time) {
413	m_rtc.override = GameControllerRTC::FAKE_EPOCH;
414	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
415}
416
417void GameController::updateKeys() {
418	int activeKeys = m_activeKeys;
419#ifdef BUILD_SDL
420	activeKeys |= m_activeButtons;
421#endif
422	m_threadContext.activeKeys = activeKeys;
423}
424
425void GameController::redoSamples(int samples) {
426#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
427	float sampleRate = 0x8000;
428	float ratio;
429	if (m_threadContext.gba) {
430		sampleRate = m_threadContext.gba->audio.sampleRate;
431	}
432	ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, 44100);
433	m_threadContext.audioBuffers = ceil(samples / ratio);
434#else
435	m_threadContext.audioBuffers = samples;
436#endif
437	if (m_threadContext.gba) {
438		GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
439	}
440}
441
442void GameController::setLogLevel(int levels) {
443	threadInterrupt();
444	m_logLevels = levels;
445	threadContinue();
446}
447
448void GameController::enableLogLevel(int levels) {
449	threadInterrupt();
450	m_logLevels |= levels;
451	threadContinue();
452}
453
454void GameController::disableLogLevel(int levels) {
455	threadInterrupt();
456	m_logLevels &= ~levels;
457	threadContinue();
458}
459
460#ifdef BUILD_SDL
461void GameController::testSDLEvents() {
462	if (!m_inputController) {
463		return;
464	}
465
466	m_activeButtons = m_inputController->testSDLEvents();
467	updateKeys();
468}
469#endif