all repos — mgba @ c50b228243bb6c381c13b290e2d864075dc34194

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
143#ifdef USE_GDB_STUB
144ARMDebugger* GameController::debugger() {
145	return m_threadContext.debugger;
146}
147
148void GameController::setDebugger(ARMDebugger* debugger) {
149	threadInterrupt();
150	if (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {
151		GBADetachDebugger(m_threadContext.gba);
152	}
153	m_threadContext.debugger = debugger;
154	if (m_threadContext.debugger && GBAThreadHasStarted(&m_threadContext)) {
155		GBAAttachDebugger(m_threadContext.gba, m_threadContext.debugger);
156	}
157	threadContinue();
158}
159#endif
160
161void GameController::loadGame(const QString& path, bool dirmode) {
162	closeGame();
163	if (!dirmode) {
164		QFile file(path);
165		if (!file.open(QIODevice::ReadOnly)) {
166			return;
167		}
168		file.close();
169	}
170
171	m_fname = path;
172	m_dirmode = dirmode;
173	openGame();
174}
175
176void GameController::openGame() {
177	m_gameOpen = true;
178
179	m_pauseAfterFrame = false;
180
181	if (m_turbo) {
182		m_threadContext.sync.videoFrameWait = false;
183		m_threadContext.sync.audioWait = false;
184	} else {
185		m_threadContext.sync.videoFrameWait = m_videoSync;
186		m_threadContext.sync.audioWait = m_audioSync;
187	}
188
189	m_threadContext.gameDir = 0;
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		if (!m_threadContext.gameDir) {
198			m_threadContext.gameDir = VDirOpenZip(m_threadContext.fname, 0);
199		}
200#endif
201#if ENABLE_LZMA
202		if (!m_threadContext.gameDir) {
203			m_threadContext.gameDir = VDirOpen7z(m_threadContext.fname, 0);
204		}
205#endif
206	}
207
208	if (!m_bios.isNull()) {
209		m_threadContext.bios = VFileOpen(m_bios.toLocal8Bit().constData(), O_RDONLY);
210	}
211
212	if (!m_patch.isNull()) {
213		m_threadContext.patch = VFileOpen(m_patch.toLocal8Bit().constData(), O_RDONLY);
214	}
215
216	if (!GBAThreadStart(&m_threadContext)) {
217		m_gameOpen = false;
218		emit gameFailed();
219	}
220}
221
222void GameController::loadBIOS(const QString& path) {
223	if (m_bios == path) {
224		return;
225	}
226	m_bios = path;
227	if (m_gameOpen) {
228		closeGame();
229		openGame();
230	}
231}
232
233void GameController::loadPatch(const QString& path) {
234	m_patch = path;
235	if (m_gameOpen) {
236		closeGame();
237		openGame();
238	}
239}
240
241void GameController::closeGame() {
242	if (!m_gameOpen) {
243		return;
244	}
245	if (GBAThreadIsPaused(&m_threadContext)) {
246		GBAThreadUnpause(&m_threadContext);
247	}
248	GBAThreadEnd(&m_threadContext);
249	GBAThreadJoin(&m_threadContext);
250	if (m_threadContext.fname) {
251		free(const_cast<char*>(m_threadContext.fname));
252		m_threadContext.fname = nullptr;
253	}
254
255	m_patch = QString();
256
257	m_gameOpen = false;
258	emit gameStopped(&m_threadContext);
259}
260
261void GameController::crashGame(const QString& crashMessage) {
262	closeGame();
263	emit gameCrashed(crashMessage);
264}
265
266bool GameController::isPaused() {
267	if (!m_gameOpen) {
268		return false;
269	}
270	return GBAThreadIsPaused(&m_threadContext);
271}
272
273void GameController::setPaused(bool paused) {
274	if (paused == GBAThreadIsPaused(&m_threadContext)) {
275		return;
276	}
277	if (paused) {
278		GBAThreadPause(&m_threadContext);
279		emit gamePaused(&m_threadContext);
280	} else {
281		GBAThreadUnpause(&m_threadContext);
282		emit gameUnpaused(&m_threadContext);
283	}
284}
285
286void GameController::reset() {
287	GBAThreadReset(&m_threadContext);
288}
289
290void GameController::threadInterrupt() {
291	if (m_gameOpen) {
292		GBAThreadInterrupt(&m_threadContext);
293	}
294}
295
296void GameController::threadContinue() {
297	if (m_gameOpen) {
298		GBAThreadContinue(&m_threadContext);
299	}
300}
301
302void GameController::frameAdvance() {
303	m_pauseMutex.lock();
304	m_pauseAfterFrame = true;
305	setPaused(false);
306	m_pauseMutex.unlock();
307}
308
309void GameController::setRewind(bool enable, int capacity, int interval) {
310	if (m_gameOpen) {
311		threadInterrupt();
312		GBARewindSettingsChanged(&m_threadContext, enable ? capacity : 0, enable ? interval : 0);
313		threadContinue();
314	} else {
315		if (enable) {
316			m_threadContext.rewindBufferInterval = interval;
317			m_threadContext.rewindBufferCapacity = capacity;
318		} else {
319			m_threadContext.rewindBufferInterval = 0;
320			m_threadContext.rewindBufferCapacity = 0;
321		}
322	}
323}
324
325void GameController::rewind(int states) {
326	threadInterrupt();
327	if (!states) {
328		GBARewindAll(&m_threadContext);
329	} else {
330		GBARewind(&m_threadContext, states);
331	}
332	threadContinue();
333}
334
335void GameController::keyPressed(int key) {
336	int mappedKey = 1 << key;
337	m_activeKeys |= mappedKey;
338	updateKeys();
339}
340
341void GameController::keyReleased(int key) {
342	int mappedKey = 1 << key;
343	m_activeKeys &= ~mappedKey;
344	updateKeys();
345}
346
347void GameController::clearKeys() {
348	m_activeKeys = 0;
349	updateKeys();
350}
351
352void GameController::setAudioBufferSamples(int samples) {
353	threadInterrupt();
354	redoSamples(samples);
355	threadContinue();
356	QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Q_ARG(int, samples));
357}
358
359void GameController::setFPSTarget(float fps) {
360	threadInterrupt();
361	m_threadContext.fpsTarget = fps;
362	redoSamples(m_audioProcessor->getBufferSamples());
363	threadContinue();
364	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
365}
366
367void GameController::setSkipBIOS(bool set) {
368	threadInterrupt();
369	m_threadContext.skipBios = set;
370	threadContinue();
371}
372
373void GameController::loadState(int slot) {
374	threadInterrupt();
375	GBALoadState(&m_threadContext, m_threadContext.stateDir, slot);
376	threadContinue();
377	emit stateLoaded(&m_threadContext);
378	emit frameAvailable(m_drawContext);
379}
380
381void GameController::saveState(int slot) {
382	threadInterrupt();
383	GBASaveState(&m_threadContext, m_threadContext.stateDir, slot, true);
384	threadContinue();
385}
386
387void GameController::setVideoSync(bool set) {
388	m_videoSync = set;
389	if (!m_turbo) {
390		threadInterrupt();
391		m_threadContext.sync.videoFrameWait = set;
392		threadContinue();
393	}
394}
395
396void GameController::setAudioSync(bool set) {
397	m_audioSync = set;
398	if (!m_turbo) {
399		threadInterrupt();
400		m_threadContext.sync.audioWait = set;
401		threadContinue();
402	}
403}
404
405void GameController::setFrameskip(int skip) {
406	m_threadContext.frameskip = skip;
407}
408
409void GameController::setTurbo(bool set, bool forced) {
410	if (m_turboForced && !forced) {
411		return;
412	}
413	m_turbo = set;
414	m_turboForced = set && forced;
415	threadInterrupt();
416	m_threadContext.sync.audioWait = set ? false : m_audioSync;
417	m_threadContext.sync.videoFrameWait = set ? false : m_videoSync;
418	threadContinue();
419}
420
421void GameController::setAVStream(GBAAVStream* stream) {
422	threadInterrupt();
423	m_threadContext.stream = stream;
424	threadContinue();
425}
426
427void GameController::clearAVStream() {
428	threadInterrupt();
429	m_threadContext.stream = nullptr;
430	threadContinue();
431}
432
433void GameController::setLuminanceValue(uint8_t value) {
434	m_luxValue = value;
435	value = std::max<int>(value - 0x16, 0);
436	m_luxLevel = 10;
437	for (int i = 0; i < 10; ++i) {
438		if (value < LUX_LEVELS[i]) {
439			m_luxLevel = i;
440			break;
441		}
442	}
443}
444
445void GameController::setLuminanceLevel(int level) {
446	int value = 0x16;
447	level = std::max(0, std::min(10, level));
448	if (level > 0) {
449		value += LUX_LEVELS[level - 1];
450	}
451	setLuminanceValue(value);
452}
453
454void GameController::setRealTime() {
455	m_rtc.override = GameControllerRTC::NO_OVERRIDE;
456}
457
458void GameController::setFixedTime(const QDateTime& time) {
459	m_rtc.override = GameControllerRTC::FIXED;
460	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
461}
462
463void GameController::setFakeEpoch(const QDateTime& time) {
464	m_rtc.override = GameControllerRTC::FAKE_EPOCH;
465	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
466}
467
468void GameController::updateKeys() {
469	int activeKeys = m_activeKeys;
470#ifdef BUILD_SDL
471	activeKeys |= m_activeButtons;
472#endif
473	m_threadContext.activeKeys = activeKeys;
474}
475
476void GameController::redoSamples(int samples) {
477#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
478	float sampleRate = 0x8000;
479	float ratio;
480	if (m_threadContext.gba) {
481		sampleRate = m_threadContext.gba->audio.sampleRate;
482	}
483	ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, 44100);
484	m_threadContext.audioBuffers = ceil(samples / ratio);
485#else
486	m_threadContext.audioBuffers = samples;
487#endif
488	if (m_threadContext.gba) {
489		GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
490	}
491}
492
493void GameController::setLogLevel(int levels) {
494	threadInterrupt();
495	m_logLevels = levels;
496	threadContinue();
497}
498
499void GameController::enableLogLevel(int levels) {
500	threadInterrupt();
501	m_logLevels |= levels;
502	threadContinue();
503}
504
505void GameController::disableLogLevel(int levels) {
506	threadInterrupt();
507	m_logLevels &= ~levels;
508	threadContinue();
509}
510
511#ifdef BUILD_SDL
512void GameController::testSDLEvents() {
513	if (!m_inputController) {
514		return;
515	}
516
517	m_activeButtons = m_inputController->testSDLEvents();
518	updateKeys();
519}
520#endif