all repos — mgba @ 9992282b1c35d8321dc44cd0ea4c11e27a42e8b0

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