all repos — mgba @ 087810a125cabbced5315a05aca105066ca2a210

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		emit gameFailed();
208	}
209}
210
211void GameController::loadBIOS(const QString& path) {
212	if (m_bios == path) {
213		return;
214	}
215	m_bios = path;
216	if (m_gameOpen) {
217		closeGame();
218		openGame();
219	}
220}
221
222void GameController::loadPatch(const QString& path) {
223	m_patch = path;
224	if (m_gameOpen) {
225		closeGame();
226		openGame();
227	}
228}
229
230void GameController::closeGame() {
231	if (!m_gameOpen) {
232		return;
233	}
234	if (GBAThreadIsPaused(&m_threadContext)) {
235		GBAThreadUnpause(&m_threadContext);
236	}
237	GBAThreadEnd(&m_threadContext);
238	GBAThreadJoin(&m_threadContext);
239	if (m_threadContext.fname) {
240		free(const_cast<char*>(m_threadContext.fname));
241		m_threadContext.fname = nullptr;
242	}
243
244	m_patch = QString();
245
246	m_gameOpen = false;
247	emit gameStopped(&m_threadContext);
248}
249
250void GameController::crashGame(const QString& crashMessage) {
251	closeGame();
252	emit gameCrashed(crashMessage);
253}
254
255bool GameController::isPaused() {
256	if (!m_gameOpen) {
257		return false;
258	}
259	return GBAThreadIsPaused(&m_threadContext);
260}
261
262void GameController::setPaused(bool paused) {
263	if (paused == GBAThreadIsPaused(&m_threadContext)) {
264		return;
265	}
266	if (paused) {
267		GBAThreadPause(&m_threadContext);
268		emit gamePaused(&m_threadContext);
269	} else {
270		GBAThreadUnpause(&m_threadContext);
271		emit gameUnpaused(&m_threadContext);
272	}
273}
274
275void GameController::reset() {
276	GBAThreadReset(&m_threadContext);
277}
278
279void GameController::threadInterrupt() {
280	if (m_gameOpen) {
281		GBAThreadInterrupt(&m_threadContext);
282	}
283}
284
285void GameController::threadContinue() {
286	if (m_gameOpen) {
287		GBAThreadContinue(&m_threadContext);
288	}
289}
290
291void GameController::frameAdvance() {
292	m_pauseMutex.lock();
293	m_pauseAfterFrame = true;
294	setPaused(false);
295	m_pauseMutex.unlock();
296}
297
298void GameController::setRewind(bool enable, int capacity, int interval) {
299	if (m_gameOpen) {
300		threadInterrupt();
301		GBARewindSettingsChanged(&m_threadContext, enable ? capacity : 0, enable ? interval : 0);
302		threadContinue();
303	} else {
304		if (enable) {
305			m_threadContext.rewindBufferInterval = interval;
306			m_threadContext.rewindBufferCapacity = capacity;
307		} else {
308			m_threadContext.rewindBufferInterval = 0;
309			m_threadContext.rewindBufferCapacity = 0;
310		}
311	}
312}
313
314void GameController::rewind(int states) {
315	threadInterrupt();
316	if (!states) {
317		GBARewindAll(&m_threadContext);
318	} else {
319		GBARewind(&m_threadContext, states);
320	}
321	threadContinue();
322}
323
324void GameController::keyPressed(int key) {
325	int mappedKey = 1 << key;
326	m_activeKeys |= mappedKey;
327	updateKeys();
328}
329
330void GameController::keyReleased(int key) {
331	int mappedKey = 1 << key;
332	m_activeKeys &= ~mappedKey;
333	updateKeys();
334}
335
336void GameController::clearKeys() {
337	m_activeKeys = 0;
338	updateKeys();
339}
340
341void GameController::setAudioBufferSamples(int samples) {
342	threadInterrupt();
343	redoSamples(samples);
344	threadContinue();
345	QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Q_ARG(int, samples));
346}
347
348void GameController::setFPSTarget(float fps) {
349	threadInterrupt();
350	m_threadContext.fpsTarget = fps;
351	redoSamples(m_audioProcessor->getBufferSamples());
352	threadContinue();
353	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
354}
355
356void GameController::setSkipBIOS(bool set) {
357	threadInterrupt();
358	m_threadContext.skipBios = set;
359	threadContinue();
360}
361
362void GameController::loadState(int slot) {
363	threadInterrupt();
364	GBALoadState(m_threadContext.gba, m_threadContext.stateDir, slot);
365	threadContinue();
366	emit stateLoaded(&m_threadContext);
367	emit frameAvailable(m_drawContext);
368}
369
370void GameController::saveState(int slot) {
371	threadInterrupt();
372	GBASaveState(m_threadContext.gba, m_threadContext.stateDir, slot, true);
373	threadContinue();
374}
375
376void GameController::setVideoSync(bool set) {
377	m_videoSync = set;
378	if (!m_turbo) {
379		threadInterrupt();
380		m_threadContext.sync.videoFrameWait = set;
381		threadContinue();
382	}
383}
384
385void GameController::setAudioSync(bool set) {
386	m_audioSync = set;
387	if (!m_turbo) {
388		threadInterrupt();
389		m_threadContext.sync.audioWait = set;
390		threadContinue();
391	}
392}
393
394void GameController::setFrameskip(int skip) {
395	m_threadContext.frameskip = skip;
396}
397
398void GameController::setTurbo(bool set, bool forced) {
399	if (m_turboForced && !forced) {
400		return;
401	}
402	m_turbo = set;
403	m_turboForced = set && forced;
404	threadInterrupt();
405	m_threadContext.sync.audioWait = set ? false : m_audioSync;
406	m_threadContext.sync.videoFrameWait = set ? false : m_videoSync;
407	threadContinue();
408}
409
410void GameController::setAVStream(GBAAVStream* stream) {
411	threadInterrupt();
412	m_threadContext.stream = stream;
413	threadContinue();
414}
415
416void GameController::clearAVStream() {
417	threadInterrupt();
418	m_threadContext.stream = nullptr;
419	threadContinue();
420}
421
422void GameController::setRealTime() {
423	m_rtc.override = GameControllerRTC::NO_OVERRIDE;
424}
425
426void GameController::setFixedTime(const QDateTime& time) {
427	m_rtc.override = GameControllerRTC::FIXED;
428	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
429}
430
431void GameController::setFakeEpoch(const QDateTime& time) {
432	m_rtc.override = GameControllerRTC::FAKE_EPOCH;
433	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
434}
435
436void GameController::updateKeys() {
437	int activeKeys = m_activeKeys;
438#ifdef BUILD_SDL
439	activeKeys |= m_activeButtons;
440#endif
441	m_threadContext.activeKeys = activeKeys;
442}
443
444void GameController::redoSamples(int samples) {
445#if RESAMPLE_LIBRARY != RESAMPLE_BLIP_BUF
446	float sampleRate = 0x8000;
447	float ratio;
448	if (m_threadContext.gba) {
449		sampleRate = m_threadContext.gba->audio.sampleRate;
450	}
451	ratio = GBAAudioCalculateRatio(sampleRate, m_threadContext.fpsTarget, 44100);
452	m_threadContext.audioBuffers = ceil(samples / ratio);
453#else
454	m_threadContext.audioBuffers = samples;
455#endif
456	if (m_threadContext.gba) {
457		GBAAudioResizeBuffer(&m_threadContext.gba->audio, m_threadContext.audioBuffers);
458	}
459}
460
461void GameController::setLogLevel(int levels) {
462	threadInterrupt();
463	m_logLevels = levels;
464	threadContinue();
465}
466
467void GameController::enableLogLevel(int levels) {
468	threadInterrupt();
469	m_logLevels |= levels;
470	threadContinue();
471}
472
473void GameController::disableLogLevel(int levels) {
474	threadInterrupt();
475	m_logLevels &= ~levels;
476	threadContinue();
477}
478
479#ifdef BUILD_SDL
480void GameController::testSDLEvents() {
481	if (!m_inputController) {
482		return;
483	}
484
485	m_activeButtons = m_inputController->testSDLEvents();
486	updateKeys();
487}
488#endif