all repos — mgba @ 4fa94019712a9eb6177f65962ea032ed784ed019

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