all repos — mgba @ a05d97a85cc95b935f1b0cf22cf1287239b9b9f6

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#include "LogController.h"
  11#include "MultiplayerController.h"
  12#include "VFileDevice.h"
  13
  14#include <QCoreApplication>
  15#include <QDateTime>
  16
  17#include <ctime>
  18
  19#include <mgba/core/config.h>
  20#include <mgba/core/directories.h>
  21#include <mgba/core/serialize.h>
  22#include <mgba/core/tile-cache.h>
  23#ifdef M_CORE_GBA
  24#include <mgba/gba/interface.h>
  25#include <mgba/internal/gba/gba.h>
  26#include <mgba/gba/core.h>
  27#include <mgba/internal/gba/renderers/tile-cache.h>
  28#include <mgba/internal/gba/sharkport.h>
  29#endif
  30#ifdef M_CORE_GB
  31#include <mgba/internal/gb/gb.h>
  32#include <mgba/internal/gb/renderers/tile-cache.h>
  33#endif
  34#include <mgba-util/vfs.h>
  35
  36using namespace QGBA;
  37using namespace std;
  38
  39GameController::GameController(QObject* parent)
  40	: QObject(parent)
  41	, m_drawContext(nullptr)
  42	, m_frontBuffer(nullptr)
  43	, m_threadContext()
  44	, m_activeKeys(0)
  45	, m_inactiveKeys(0)
  46	, m_logLevels(0)
  47	, m_gameOpen(false)
  48	, m_vf(nullptr)
  49	, m_useBios(false)
  50	, m_audioProcessor(AudioProcessor::create())
  51	, m_pauseAfterFrame(false)
  52	, m_sync(true)
  53	, m_videoSync(VIDEO_SYNC)
  54	, m_audioSync(AUDIO_SYNC)
  55	, m_fpsTarget(-1)
  56	, m_turbo(false)
  57	, m_turboForced(false)
  58	, m_turboSpeed(-1)
  59	, m_wasPaused(false)
  60	, m_audioChannels()
  61	, m_videoLayers()
  62	, m_autofire{}
  63	, m_autofireStatus{}
  64	, m_inputController(nullptr)
  65	, m_multiplayer(nullptr)
  66	, m_stream(nullptr)
  67	, m_stateSlot(1)
  68	, m_backupLoadState(nullptr)
  69	, m_backupSaveState(nullptr)
  70	, m_saveStateFlags(SAVESTATE_SCREENSHOT | SAVESTATE_SAVEDATA | SAVESTATE_CHEATS | SAVESTATE_RTC)
  71	, m_loadStateFlags(SAVESTATE_SCREENSHOT | SAVESTATE_RTC)
  72	, m_preload(false)
  73	, m_override(nullptr)
  74{
  75#ifdef M_CORE_GBA
  76	m_lux.p = this;
  77	m_lux.sample = [](GBALuminanceSource* context) {
  78		GameControllerLux* lux = static_cast<GameControllerLux*>(context);
  79		lux->value = 0xFF - lux->p->m_luxValue;
  80	};
  81
  82	m_lux.readLuminance = [](GBALuminanceSource* context) {
  83		GameControllerLux* lux = static_cast<GameControllerLux*>(context);
  84		return lux->value;
  85	};
  86	setLuminanceLevel(0);
  87#endif
  88
  89	m_threadContext.startCallback = [](mCoreThread* context) {
  90		GameController* controller = static_cast<GameController*>(context->userData);
  91		context->core->setPeripheral(context->core, mPERIPH_ROTATION, controller->m_inputController->rotationSource());
  92		context->core->setPeripheral(context->core, mPERIPH_RUMBLE, controller->m_inputController->rumble());
  93
  94		for (size_t i = 0; i < controller->m_audioChannels.size(); ++i) {
  95			context->core->enableAudioChannel(context->core, i, controller->m_audioChannels[i]);
  96		}
  97		for (size_t i = 0; i < controller->m_videoLayers.size(); ++i) {
  98			context->core->enableVideoLayer(context->core, i, controller->m_videoLayers[i]);
  99		}
 100
 101		switch (context->core->platform(context->core)) {
 102#ifdef M_CORE_GBA
 103		case PLATFORM_GBA:
 104			context->core->setPeripheral(context->core, mPERIPH_GBA_LUMINANCE, &controller->m_lux);
 105			break;
 106#endif
 107		default:
 108			break;
 109		}
 110		controller->m_fpsTarget = context->sync.fpsTarget;
 111
 112		if (controller->m_override) {
 113			controller->m_override->identify(context->core);
 114			controller->m_override->apply(context->core);
 115		}
 116
 117		if (mCoreLoadState(context->core, 0, controller->m_loadStateFlags)) {
 118			mCoreDeleteState(context->core, 0);
 119		}
 120
 121		controller->m_gameOpen = true;
 122		if (controller->m_multiplayer) {
 123			controller->m_multiplayer->attachGame(controller);
 124		}
 125
 126		QString path = controller->m_fname;
 127		if (!controller->m_fsub.isEmpty()) {
 128			path += QDir::separator() + controller->m_fsub;
 129		}
 130		QMetaObject::invokeMethod(controller, "gameStarted", Q_ARG(mCoreThread*, context), Q_ARG(const QString&, path));
 131		QMetaObject::invokeMethod(controller, "startAudio");
 132	};
 133
 134	m_threadContext.resetCallback = [](mCoreThread* context) {
 135		GameController* controller = static_cast<GameController*>(context->userData);
 136		for (auto action : controller->m_resetActions) {
 137			action();
 138		}
 139		controller->m_resetActions.clear();
 140
 141		unsigned width, height;
 142		controller->m_threadContext.core->desiredVideoDimensions(controller->m_threadContext.core, &width, &height);
 143		memset(controller->m_frontBuffer, 0xFF, width * height * BYTES_PER_PIXEL);
 144		QMetaObject::invokeMethod(controller, "frameAvailable", Q_ARG(const uint32_t*, controller->m_frontBuffer));
 145		if (controller->m_pauseAfterFrame.testAndSetAcquire(true, false)) {
 146			mCoreThreadPauseFromThread(context);
 147			QMetaObject::invokeMethod(controller, "gamePaused", Q_ARG(mCoreThread*, context));
 148		}
 149	};
 150
 151	m_threadContext.cleanCallback = [](mCoreThread* context) {
 152		GameController* controller = static_cast<GameController*>(context->userData);
 153
 154		if (controller->m_multiplayer) {
 155			controller->m_multiplayer->detachGame(controller);
 156		}
 157		controller->m_patch = QString();
 158		controller->clearOverride();
 159
 160		QMetaObject::invokeMethod(controller->m_audioProcessor, "pause");
 161
 162		QMetaObject::invokeMethod(controller, "gameStopped", Q_ARG(mCoreThread*, context));
 163		QMetaObject::invokeMethod(controller, "cleanGame");
 164	};
 165
 166	m_threadContext.frameCallback = [](mCoreThread* context) {
 167		GameController* controller = static_cast<GameController*>(context->userData);
 168		unsigned width, height;
 169		controller->m_threadContext.core->desiredVideoDimensions(controller->m_threadContext.core, &width, &height);
 170		memcpy(controller->m_frontBuffer, controller->m_drawContext, width * height * BYTES_PER_PIXEL);
 171		QMetaObject::invokeMethod(controller, "frameAvailable", Q_ARG(const uint32_t*, controller->m_frontBuffer));
 172
 173		// If no one is using the tile cache, disable it
 174		if (controller->m_tileCache && controller->m_tileCache.unique()) {
 175			switch (controller->platform()) {
 176#ifdef M_CORE_GBA
 177			case PLATFORM_GBA: {
 178				GBA* gba = static_cast<GBA*>(context->core->board);
 179				gba->video.renderer->cache = nullptr;
 180				break;
 181			}
 182#endif
 183#ifdef M_CORE_GB
 184			case PLATFORM_GB: {
 185				GB* gb = static_cast<GB*>(context->core->board);
 186				gb->video.renderer->cache = nullptr;
 187				break;
 188			}
 189#endif
 190			default:
 191				break;
 192			}
 193			controller->m_tileCache.reset();
 194		}
 195
 196
 197		if (controller->m_pauseAfterFrame.testAndSetAcquire(true, false)) {
 198			mCoreThreadPauseFromThread(context);
 199			QMetaObject::invokeMethod(controller, "gamePaused", Q_ARG(mCoreThread*, context));
 200		}
 201	};
 202
 203	m_threadContext.sleepCallback = [](mCoreThread* context) {
 204		if (!context) {
 205			return;
 206		}
 207		GameController* controller = static_cast<GameController*>(context->userData);
 208		if (!mCoreSaveState(context->core, 0, controller->m_saveStateFlags)) {
 209			return;
 210		}
 211		QMetaObject::invokeMethod(controller, "closeGame");
 212	};
 213
 214	m_threadContext.logger.d.log = [](mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
 215		mThreadLogger* logContext = reinterpret_cast<mThreadLogger*>(logger);
 216		mCoreThread* context = logContext->p;
 217
 218		static const char* savestateMessage = "State %i loaded";
 219		static const char* savestateFailedMessage = "State %i failed to load";
 220		static int biosCat = -1;
 221		static int statusCat = -1;
 222		if (!context) {
 223			return;
 224		}
 225		GameController* controller = static_cast<GameController*>(context->userData);
 226		QString message;
 227		if (biosCat < 0) {
 228			biosCat = mLogCategoryById("gba.bios");
 229		}
 230		if (statusCat < 0) {
 231			statusCat = mLogCategoryById("core.status");
 232		}
 233#ifdef M_CORE_GBA
 234		if (level == mLOG_STUB && category == biosCat) {
 235			va_list argc;
 236			va_copy(argc, args);
 237			int immediate = va_arg(argc, int);
 238			va_end(argc);
 239			QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
 240		} else
 241#endif
 242		if (category == statusCat) {
 243			// Slot 0 is reserved for suspend points
 244			if (strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
 245				va_list argc;
 246				va_copy(argc, args);
 247				int slot = va_arg(argc, int);
 248				va_end(argc);
 249				if (slot == 0) {
 250					format = "Loaded suspend state";
 251				}
 252			} else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 0) {
 253				va_list argc;
 254				va_copy(argc, args);
 255				int slot = va_arg(argc, int);
 256				va_end(argc);
 257				if (slot == 0) {
 258					return;
 259				}
 260			}
 261			message = QString().vsprintf(format, args);
 262			QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
 263		}
 264		if (level == mLOG_FATAL) {
 265			mCoreThreadMarkCrashed(controller->thread());
 266			QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
 267		} else if (!(controller->m_logLevels & level)) {
 268			return;
 269		}
 270		message = QString().vsprintf(format, args);
 271		QMetaObject::invokeMethod(controller, "postLog", Q_ARG(int, level), Q_ARG(int, category), Q_ARG(const QString&, message));
 272	};
 273
 274	m_threadContext.userData = this;
 275
 276	connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
 277	connect(this, SIGNAL(gameStarted(mCoreThread*, const QString&)), m_audioProcessor, SLOT(setInput(mCoreThread*)));
 278	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(pollEvents()));
 279	connect(this, SIGNAL(frameAvailable(const uint32_t*)), this, SLOT(updateAutofire()));
 280}
 281
 282GameController::~GameController() {
 283	disconnect();
 284	closeGame();
 285	clearMultiplayerController();
 286	delete m_backupLoadState;
 287}
 288
 289void GameController::setMultiplayerController(MultiplayerController* controller) {
 290	if (controller == m_multiplayer) {
 291		return;
 292	}
 293	clearMultiplayerController();
 294	m_multiplayer = controller;
 295	if (isLoaded()) {
 296		mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* thread) {
 297			GameController* controller = static_cast<GameController*>(thread->userData);
 298			controller->m_multiplayer->attachGame(controller);
 299		});
 300	}
 301}
 302
 303void GameController::clearMultiplayerController() {
 304	if (!m_multiplayer) {
 305		return;
 306	}
 307	m_multiplayer->detachGame(this);
 308	m_multiplayer = nullptr;
 309}
 310
 311void GameController::setOverride(Override* override) {
 312	m_override = override;
 313	if (isLoaded()) {
 314		Interrupter interrupter(this);
 315		m_override->identify(m_threadContext.core);
 316	}
 317}
 318
 319void GameController::clearOverride() {
 320	delete m_override;
 321	m_override = nullptr;
 322}
 323
 324void GameController::setConfig(const mCoreConfig* config) {
 325	m_config = config;
 326	if (isLoaded()) {
 327		Interrupter interrupter(this);
 328		mCoreLoadForeignConfig(m_threadContext.core, config);
 329		m_audioSync = m_threadContext.sync.audioWait;
 330		m_videoSync = m_threadContext.sync.videoFrameWait;
 331		m_audioProcessor->setInput(&m_threadContext);
 332	}
 333}
 334
 335#ifdef USE_GDB_STUB
 336mDebugger* GameController::debugger() {
 337	if (!isLoaded()) {
 338		return nullptr;
 339	}
 340	return m_threadContext.core->debugger;
 341}
 342
 343void GameController::setDebugger(mDebugger* debugger) {
 344	Interrupter interrupter(this);
 345	if (debugger) {
 346		mDebuggerAttach(debugger, m_threadContext.core);
 347	} else {
 348		m_threadContext.core->detachDebugger(m_threadContext.core);
 349	}
 350}
 351#endif
 352
 353void GameController::loadGame(const QString& path) {
 354	closeGame();
 355	QFileInfo info(path);
 356	if (!info.isReadable()) {
 357		QString fname = info.fileName();
 358		QString base = info.path();
 359		if (base.endsWith("/") || base.endsWith(QDir::separator())) {
 360			base.chop(1);
 361		}
 362		VDir* dir = VDirOpenArchive(base.toUtf8().constData());
 363		if (dir) {
 364			VFile* vf = dir->openFile(dir, fname.toUtf8().constData(), O_RDONLY);
 365			if (vf) {
 366				struct VFile* vfclone = VFileMemChunk(NULL, vf->size(vf));
 367				uint8_t buffer[2048];
 368				ssize_t read;
 369				while ((read = vf->read(vf, buffer, sizeof(buffer))) > 0) {
 370					vfclone->write(vfclone, buffer, read);
 371				}
 372				vf->close(vf);
 373				vf = vfclone;
 374			}
 375			dir->close(dir);
 376			loadGame(vf, fname, base);
 377		} else {
 378			LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
 379		}
 380		return;
 381	} else {
 382		m_fname = info.canonicalFilePath();
 383		m_fsub = QString();
 384	}
 385	m_vf = nullptr;
 386	openGame();
 387}
 388
 389void GameController::loadGame(VFile* vf, const QString& path, const QString& base) {
 390	closeGame();
 391	QFileInfo info(base);
 392	if (info.isDir()) {
 393		m_fname = QFileInfo(base + '/' + path).canonicalFilePath();
 394		m_fsub = QString();
 395	} else {
 396		m_fname = info.canonicalFilePath();
 397		m_fsub = path;
 398	}
 399	m_vf = vf;
 400	openGame();
 401}
 402
 403void GameController::bootBIOS() {
 404	closeGame();
 405	m_fname = QString();
 406	openGame(true);
 407}
 408
 409void GameController::openGame(bool biosOnly) {
 410	if (m_fname.isEmpty()) {
 411		biosOnly = true;
 412	}
 413	if (isLoaded()) {
 414		// We need to delay if the game is still cleaning up
 415		QTimer::singleShot(10, this, SLOT(openGame()));
 416		return;
 417	} else if(m_gameOpen) {
 418		cleanGame();
 419	}
 420
 421	m_threadContext.core = nullptr;
 422	if (!biosOnly) {
 423		if (m_vf) {
 424			m_threadContext.core = mCoreFindVF(m_vf);
 425		} else {
 426			m_threadContext.core = mCoreFind(m_fname.toUtf8().constData());
 427		}
 428#ifdef M_CORE_GBA
 429	} else {
 430		m_threadContext.core = GBACoreCreate();
 431#endif
 432	}
 433
 434	if (!m_threadContext.core) {
 435		return;
 436	}
 437
 438	m_pauseAfterFrame = false;
 439
 440	if (m_turbo) {
 441		m_threadContext.sync.videoFrameWait = false;
 442		m_threadContext.sync.audioWait = false;
 443	} else {
 444		m_threadContext.sync.videoFrameWait = m_videoSync;
 445		m_threadContext.sync.audioWait = m_audioSync;
 446	}
 447	m_threadContext.core->init(m_threadContext.core);
 448	mCoreInitConfig(m_threadContext.core, nullptr);
 449
 450	unsigned width, height;
 451	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 452	m_drawContext = new uint32_t[width * height];
 453	m_frontBuffer = new uint32_t[width * height];
 454
 455	if (m_config) {
 456		mCoreLoadForeignConfig(m_threadContext.core, m_config);
 457	}
 458
 459	QByteArray bytes;
 460	if (!biosOnly) {
 461		bytes = m_fname.toUtf8();
 462		if (m_preload) {
 463			if (m_vf) {
 464				mCorePreloadVF(m_threadContext.core, m_vf);
 465			} else {
 466				mCorePreloadFile(m_threadContext.core, bytes.constData());
 467				mDirectorySetDetachBase(&m_threadContext.core->dirs);
 468			}
 469		} else {
 470			if (m_vf) {
 471				m_threadContext.core->loadROM(m_threadContext.core, m_vf);
 472			} else {
 473				mCoreLoadFile(m_threadContext.core, bytes.constData());
 474				mDirectorySetDetachBase(&m_threadContext.core->dirs);
 475			}
 476		}
 477	} else {
 478		bytes = m_bios.toUtf8();
 479	}
 480	if (bytes.isNull()) {
 481		return;
 482	}
 483
 484	char dirname[PATH_MAX];
 485	separatePath(bytes.constData(), dirname, m_threadContext.core->dirs.baseName, 0);
 486	mDirectorySetAttachBase(&m_threadContext.core->dirs, VDirOpen(dirname));
 487
 488	m_threadContext.core->setVideoBuffer(m_threadContext.core, m_drawContext, width);
 489
 490	m_inputController->recalibrateAxes();
 491	memset(m_drawContext, 0xF8, width * height * 4);
 492
 493	m_threadContext.core->setAVStream(m_threadContext.core, m_stream);
 494
 495	if (!biosOnly) {
 496		mCoreAutoloadSave(m_threadContext.core);
 497		if (!m_patch.isNull()) {
 498			VFile* patch = VFileDevice::open(m_patch, O_RDONLY);
 499			if (patch) {
 500				m_threadContext.core->loadPatch(m_threadContext.core, patch);
 501			}
 502			patch->close(patch);
 503		} else {
 504			mCoreAutoloadPatch(m_threadContext.core);
 505		}
 506	}
 507	m_vf = nullptr;
 508
 509	if (!mCoreThreadStart(&m_threadContext)) {
 510		emit gameFailed();
 511	}
 512}
 513
 514void GameController::loadBIOS(int platform, const QString& path) {
 515	if (m_bios == path) {
 516		return;
 517	}
 518	if (!m_bios.isNull() && m_gameOpen && this->platform() == platform) {
 519		closeGame();
 520		m_bios = path;
 521		openGame();
 522	} else if (!m_gameOpen || m_bios.isNull()) {
 523		m_bios = path;
 524	}
 525}
 526
 527void GameController::loadSave(const QString& path, bool temporary) {
 528	if (!isLoaded()) {
 529		return;
 530	}
 531	m_resetActions.append([this, path, temporary]() {
 532		VFile* vf = VFileDevice::open(path, temporary ? O_RDONLY : O_RDWR);
 533		if (!vf) {
 534			LOG(QT, ERROR) << tr("Failed to open save file: %1").arg(path);
 535			return;
 536		}
 537
 538		if (temporary) {
 539			m_threadContext.core->loadTemporarySave(m_threadContext.core, vf);
 540		} else {
 541			m_threadContext.core->loadSave(m_threadContext.core, vf);
 542		}
 543	});
 544	reset();
 545}
 546
 547void GameController::yankPak() {
 548	if (!m_gameOpen) {
 549		return;
 550	}
 551	Interrupter interrupter(this);
 552	GBAYankROM(static_cast<GBA*>(m_threadContext.core->board));
 553}
 554
 555void GameController::replaceGame(const QString& path) {
 556	if (!m_gameOpen) {
 557		return;
 558	}
 559
 560	QFileInfo info(path);
 561	if (!info.isReadable()) {
 562		LOG(QT, ERROR) << tr("Failed to open game file: %1").arg(path);
 563		return;
 564	}
 565	m_fname = info.canonicalFilePath();
 566	Interrupter interrupter(this);
 567	mDirectorySetDetachBase(&m_threadContext.core->dirs);
 568	mCoreLoadFile(m_threadContext.core, m_fname.toLocal8Bit().constData());
 569}
 570
 571void GameController::loadPatch(const QString& path) {
 572	if (m_gameOpen) {
 573		closeGame();
 574		m_patch = path;
 575		openGame();
 576	} else {
 577		m_patch = path;
 578	}
 579}
 580
 581void GameController::importSharkport(const QString& path) {
 582	if (!isLoaded()) {
 583		return;
 584	}
 585#ifdef M_CORE_GBA
 586	if (platform() != PLATFORM_GBA) {
 587		return;
 588	}
 589	VFile* vf = VFileDevice::open(path, O_RDONLY);
 590	if (!vf) {
 591		LOG(QT, ERROR) << tr("Failed to open snapshot file for reading: %1").arg(path);
 592		return;
 593	}
 594	threadInterrupt();
 595	GBASavedataImportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf, false);
 596	threadContinue();
 597	vf->close(vf);
 598#endif
 599}
 600
 601void GameController::exportSharkport(const QString& path) {
 602	if (!isLoaded()) {
 603		return;
 604	}
 605#ifdef M_CORE_GBA
 606	if (platform() != PLATFORM_GBA) {
 607		return;
 608	}
 609	VFile* vf = VFileDevice::open(path, O_WRONLY | O_CREAT | O_TRUNC);
 610	if (!vf) {
 611		LOG(QT, ERROR) << tr("Failed to open snapshot file for writing: %1").arg(path);
 612		return;
 613	}
 614	threadInterrupt();
 615	GBASavedataExportSharkPort(static_cast<GBA*>(m_threadContext.core->board), vf);
 616	threadContinue();
 617	vf->close(vf);
 618#endif
 619}
 620
 621void GameController::closeGame() {
 622	if (!m_gameOpen) {
 623		return;
 624	}
 625
 626	if (mCoreThreadIsPaused(&m_threadContext)) {
 627		mCoreThreadUnpause(&m_threadContext);
 628	}
 629	mCoreThreadEnd(&m_threadContext);
 630}
 631
 632void GameController::cleanGame() {
 633	if (!m_gameOpen || mCoreThreadIsActive(&m_threadContext)) {
 634		return;
 635	}
 636
 637	m_audioProcessor->pause();
 638	mCoreThreadJoin(&m_threadContext);
 639
 640	if (m_tileCache) {
 641		mTileCacheDeinit(m_tileCache.get());
 642		m_tileCache.reset();
 643	}
 644
 645	delete[] m_drawContext;
 646	delete[] m_frontBuffer;
 647
 648	m_threadContext.core->deinit(m_threadContext.core);
 649	m_threadContext.core = nullptr;
 650	m_gameOpen = false;
 651}
 652
 653void GameController::crashGame(const QString& crashMessage) {
 654	closeGame();
 655	emit gameCrashed(crashMessage);
 656}
 657
 658bool GameController::isPaused() {
 659	if (!m_gameOpen) {
 660		return false;
 661	}
 662	return mCoreThreadIsPaused(&m_threadContext);
 663}
 664
 665mPlatform GameController::platform() const {
 666	if (!m_gameOpen) {
 667		return PLATFORM_NONE;
 668	}
 669	return m_threadContext.core->platform(m_threadContext.core);
 670}
 671
 672QSize GameController::screenDimensions() const {
 673	if (!m_gameOpen) {
 674		return QSize();
 675	}
 676	unsigned width, height;
 677	m_threadContext.core->desiredVideoDimensions(m_threadContext.core, &width, &height);
 678
 679	return QSize(width, height);
 680}
 681
 682void GameController::setPaused(bool paused) {
 683	if (!isLoaded() || paused == mCoreThreadIsPaused(&m_threadContext)) {
 684		return;
 685	}
 686	m_wasPaused = paused;
 687	if (paused) {
 688		m_pauseAfterFrame.testAndSetRelaxed(false, true);
 689	} else {
 690		mCoreThreadUnpause(&m_threadContext);
 691		startAudio();
 692		emit gameUnpaused(&m_threadContext);
 693	}
 694}
 695
 696void GameController::reset() {
 697	if (!m_gameOpen) {
 698		return;
 699	}
 700	bool wasPaused = isPaused();
 701	setPaused(false);
 702	Interrupter interrupter(this);
 703	mCoreThreadReset(&m_threadContext);
 704	if (wasPaused) {
 705		setPaused(true);
 706	}
 707}
 708
 709void GameController::threadInterrupt() {
 710	if (m_gameOpen) {
 711		mCoreThreadInterrupt(&m_threadContext);
 712	}
 713}
 714
 715void GameController::threadContinue() {
 716	if (m_gameOpen) {
 717		mCoreThreadContinue(&m_threadContext);
 718	}
 719}
 720
 721void GameController::frameAdvance() {
 722	if (m_pauseAfterFrame.testAndSetRelaxed(false, true)) {
 723		setPaused(false);
 724	}
 725}
 726
 727void GameController::setRewind(bool enable, int capacity, bool rewindSave) {
 728	if (m_gameOpen) {
 729		Interrupter interrupter(this);
 730		if (m_threadContext.core->opts.rewindEnable && m_threadContext.core->opts.rewindBufferCapacity > 0) {
 731			mCoreRewindContextDeinit(&m_threadContext.rewind);
 732		}
 733		m_threadContext.core->opts.rewindEnable = enable;
 734		m_threadContext.core->opts.rewindBufferCapacity = capacity;
 735		m_threadContext.core->opts.rewindSave = rewindSave;
 736		if (enable && capacity > 0) {
 737			mCoreRewindContextInit(&m_threadContext.rewind, capacity);
 738			 m_threadContext.rewind.stateFlags = rewindSave ? SAVESTATE_SAVEDATA : 0;
 739		}
 740	}
 741}
 742
 743void GameController::rewind(int states) {
 744	threadInterrupt();
 745	if (!states) {
 746		states = INT_MAX;
 747	}
 748	for (int i = 0; i < states; ++i) {
 749		if (!mCoreRewindRestore(&m_threadContext.rewind, m_threadContext.core)) {
 750			break;
 751		}
 752	}
 753	threadContinue();
 754	emit frameAvailable(m_drawContext);
 755	emit rewound(&m_threadContext);
 756}
 757
 758void GameController::startRewinding() {
 759	if (!isLoaded()) {
 760		return;
 761	}
 762	if (!m_threadContext.core->opts.rewindEnable) {
 763		return;
 764	}
 765	if (m_multiplayer && m_multiplayer->attached() > 1) {
 766		return;
 767	}
 768	if (m_wasPaused) {
 769		setPaused(false);
 770		m_wasPaused = true;
 771	}
 772	mCoreThreadSetRewinding(&m_threadContext, true);
 773}
 774
 775void GameController::stopRewinding() {
 776	if (!isLoaded()) {
 777		return;
 778	}
 779	mCoreThreadSetRewinding(&m_threadContext, false);
 780	bool signalsBlocked = blockSignals(true);
 781	setPaused(m_wasPaused);
 782	blockSignals(signalsBlocked);
 783}
 784
 785void GameController::keyPressed(int key) {
 786	int mappedKey = 1 << key;
 787	m_activeKeys |= mappedKey;
 788	if (!m_inputController->allowOpposing()) {
 789		if ((m_activeKeys & 0x30) == 0x30) {
 790			m_inactiveKeys |= mappedKey ^ 0x30;
 791			m_activeKeys ^= mappedKey ^ 0x30;
 792		}
 793		if ((m_activeKeys & 0xC0) == 0xC0) {
 794			m_inactiveKeys |= mappedKey ^ 0xC0;
 795			m_activeKeys ^= mappedKey ^ 0xC0;
 796		}
 797	}
 798	updateKeys();
 799}
 800
 801void GameController::keyReleased(int key) {
 802	int mappedKey = 1 << key;
 803	m_activeKeys &= ~mappedKey;
 804	if (!m_inputController->allowOpposing()) {
 805		if (mappedKey & 0x30) {
 806			m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
 807			m_inactiveKeys &= ~0x30;
 808		}
 809		if (mappedKey & 0xC0) {
 810			m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
 811			m_inactiveKeys &= ~0xC0;
 812		}
 813	}
 814	updateKeys();
 815}
 816
 817void GameController::cursorLocation(int x, int y) {
 818	if (!isLoaded()) {
 819		return;
 820	}
 821	m_threadContext.core->setCursorLocation(m_threadContext.core, x, y);
 822}
 823
 824void GameController::cursorDown(bool down) {
 825	if (!isLoaded()) {
 826		return;
 827	}
 828	m_threadContext.core->setCursorDown(m_threadContext.core, down);
 829}
 830
 831void GameController::clearKeys() {
 832	m_activeKeys = 0;
 833	m_inactiveKeys = 0;
 834	updateKeys();
 835}
 836
 837void GameController::setAutofire(int key, bool enable) {
 838	if (key >= GBA_KEY_MAX || key < 0) {
 839		return;
 840	}
 841
 842	if (!enable && m_autofireStatus[key]) {
 843		keyReleased(key);
 844	}
 845
 846	m_autofire[key] = enable;
 847	m_autofireStatus[key] = 0;
 848}
 849
 850void GameController::setAudioBufferSamples(int samples) {
 851	if (m_audioProcessor) {
 852		threadInterrupt();
 853		redoSamples(samples);
 854		threadContinue();
 855		m_audioProcessor->setBufferSamples(samples);
 856	}
 857}
 858
 859void GameController::setAudioSampleRate(unsigned rate) {
 860	if (!rate) {
 861		return;
 862	}
 863	if (m_audioProcessor) {
 864		threadInterrupt();
 865		redoSamples(m_audioProcessor->getBufferSamples());
 866		threadContinue();
 867		m_audioProcessor->requestSampleRate(rate);
 868	}
 869}
 870
 871void GameController::setAudioChannelEnabled(int channel, bool enable) {
 872	if (channel > 5 || channel < 0) {
 873		return;
 874	}
 875	m_audioChannels.reserve(channel + 1);
 876	while (m_audioChannels.size() <= channel) {
 877		m_audioChannels.append(true);
 878	}
 879	m_audioChannels[channel] = enable;
 880	if (isLoaded()) {
 881		m_threadContext.core->enableAudioChannel(m_threadContext.core, channel, enable);
 882	}
 883}
 884
 885void GameController::startAudio() {
 886	if (!m_audioProcessor->start()) {
 887		LOG(QT, ERROR) << tr("Failed to start audio processor");
 888		// Don't freeze!
 889		m_audioSync = false;
 890		m_videoSync = true;
 891		m_threadContext.sync.audioWait = false;
 892		m_threadContext.sync.videoFrameWait = true;
 893	}
 894}
 895
 896void GameController::setVideoLayerEnabled(int layer, bool enable) {
 897	if (layer > 4 || layer < 0) {
 898		return;
 899	}
 900	m_videoLayers.reserve(layer + 1);
 901	while (m_videoLayers.size() <= layer) {
 902		m_videoLayers.append(true);
 903	}
 904	m_videoLayers[layer] = enable;
 905	if (isLoaded()) {
 906		m_threadContext.core->enableVideoLayer(m_threadContext.core, layer, enable);
 907	}
 908}
 909
 910void GameController::setFPSTarget(float fps) {
 911	Interrupter interrupter(this);
 912	m_fpsTarget = fps;
 913	m_threadContext.sync.fpsTarget = fps;
 914	if (m_turbo && m_turboSpeed > 0) {
 915		m_threadContext.sync.fpsTarget *= m_turboSpeed;
 916	}
 917	if (m_audioProcessor) {
 918		redoSamples(m_audioProcessor->getBufferSamples());
 919	}
 920}
 921
 922void GameController::setUseBIOS(bool use) {
 923	if (use == m_useBios) {
 924		return;
 925	}
 926	m_useBios = use;
 927	if (m_gameOpen) {
 928		closeGame();
 929		openGame();
 930	}
 931}
 932
 933void GameController::loadState(int slot) {
 934	if (m_fname.isEmpty()) {
 935		// We're in the BIOS
 936		return;
 937	}
 938	if (slot > 0 && slot != m_stateSlot) {
 939		m_stateSlot = slot;
 940		m_backupSaveState.clear();
 941	}
 942	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 943		GameController* controller = static_cast<GameController*>(context->userData);
 944		if (!controller->m_backupLoadState) {
 945			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
 946		}
 947		mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 948		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
 949			controller->frameAvailable(controller->m_drawContext);
 950			controller->stateLoaded(context);
 951		}
 952	});
 953}
 954
 955void GameController::saveState(int slot) {
 956	if (m_fname.isEmpty()) {
 957		// We're in the BIOS
 958		return;
 959	}
 960	if (slot > 0) {
 961		m_stateSlot = slot;
 962	}
 963	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 964		GameController* controller = static_cast<GameController*>(context->userData);
 965		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
 966		if (vf) {
 967			controller->m_backupSaveState.resize(vf->size(vf));
 968			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
 969			vf->close(vf);
 970		}
 971		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
 972	});
 973}
 974
 975void GameController::loadBackupState() {
 976	if (!m_backupLoadState) {
 977		return;
 978	}
 979
 980	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 981		GameController* controller = static_cast<GameController*>(context->userData);
 982		controller->m_backupLoadState->seek(controller->m_backupLoadState, 0, SEEK_SET);
 983		if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
 984			mLOG(STATUS, INFO, "Undid state load");
 985			controller->frameAvailable(controller->m_drawContext);
 986			controller->stateLoaded(context);
 987		}
 988		controller->m_backupLoadState->close(controller->m_backupLoadState);
 989		controller->m_backupLoadState = nullptr;
 990	});
 991}
 992
 993void GameController::saveBackupState() {
 994	if (m_backupSaveState.isEmpty()) {
 995		return;
 996	}
 997
 998	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 999		GameController* controller = static_cast<GameController*>(context->userData);
1000		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
1001		if (vf) {
1002			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
1003			vf->close(vf);
1004			mLOG(STATUS, INFO, "Undid state save");
1005		}
1006		controller->m_backupSaveState.clear();
1007	});
1008}
1009
1010void GameController::setTurbo(bool set, bool forced) {
1011	if (m_turboForced && !forced) {
1012		return;
1013	}
1014	if (m_turbo == set && m_turboForced == (set && forced)) {
1015		// Don't interrupt the thread if we don't need to
1016		return;
1017	}
1018	if (!m_sync) {
1019		return;
1020	}
1021	m_turbo = set;
1022	m_turboForced = set && forced;
1023	enableTurbo();
1024}
1025
1026void GameController::setTurboSpeed(float ratio) {
1027	m_turboSpeed = ratio;
1028	enableTurbo();
1029}
1030
1031void GameController::enableTurbo() {
1032	Interrupter interrupter(this);
1033	bool shouldRedoSamples = false;
1034	if (!m_turbo) {
1035		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1036		m_threadContext.sync.fpsTarget = m_fpsTarget;
1037		m_threadContext.sync.audioWait = m_audioSync;
1038		m_threadContext.sync.videoFrameWait = m_videoSync;
1039	} else if (m_turboSpeed <= 0) {
1040		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1041		m_threadContext.sync.fpsTarget = m_fpsTarget;
1042		m_threadContext.sync.audioWait = false;
1043		m_threadContext.sync.videoFrameWait = false;
1044	} else {
1045		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget * m_turboSpeed;
1046		m_threadContext.sync.fpsTarget = m_fpsTarget * m_turboSpeed;
1047		m_threadContext.sync.audioWait = true;
1048		m_threadContext.sync.videoFrameWait = false;
1049	}
1050	if (m_audioProcessor && shouldRedoSamples) {
1051		redoSamples(m_audioProcessor->getBufferSamples());
1052	}
1053}
1054
1055void GameController::setSync(bool enable) {
1056	m_turbo = false;
1057	m_turboForced = false;
1058	if (!enable) {
1059		m_threadContext.sync.audioWait = false;
1060		m_threadContext.sync.videoFrameWait = false;
1061	} else {
1062		m_threadContext.sync.audioWait = m_audioSync;
1063		m_threadContext.sync.videoFrameWait = m_videoSync;
1064	}
1065	m_sync = enable;
1066}
1067
1068void GameController::setAudioSync(bool enable) {
1069	m_audioSync = enable;
1070	m_threadContext.sync.audioWait = enable;
1071}
1072
1073void GameController::setVideoSync(bool enable) {
1074	m_videoSync = enable;
1075	m_threadContext.sync.videoFrameWait = enable;
1076}
1077
1078void GameController::setAVStream(mAVStream* stream) {
1079	Interrupter interrupter(this);
1080	m_stream = stream;
1081	if (isLoaded()) {
1082		m_threadContext.core->setAVStream(m_threadContext.core, stream);
1083	}
1084}
1085
1086void GameController::clearAVStream() {
1087	Interrupter interrupter(this);
1088	m_stream = nullptr;
1089	if (isLoaded()) {
1090		m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
1091	}
1092}
1093
1094#ifdef USE_PNG
1095void GameController::screenshot() {
1096	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1097		mCoreTakeScreenshot(context->core);
1098	});
1099}
1100#endif
1101
1102void GameController::reloadAudioDriver() {
1103	int samples = 0;
1104	unsigned sampleRate = 0;
1105	if (m_audioProcessor) {
1106		m_audioProcessor->pause();
1107		samples = m_audioProcessor->getBufferSamples();
1108		sampleRate = m_audioProcessor->sampleRate();
1109		delete m_audioProcessor;
1110	}
1111	m_audioProcessor = AudioProcessor::create();
1112	if (samples) {
1113		m_audioProcessor->setBufferSamples(samples);
1114	}
1115	if (sampleRate) {
1116		m_audioProcessor->requestSampleRate(sampleRate);
1117	}
1118	connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
1119	connect(this, SIGNAL(gameStarted(mCoreThread*, const QString&)), m_audioProcessor, SLOT(setInput(mCoreThread*)));
1120	if (isLoaded()) {
1121		m_audioProcessor->setInput(&m_threadContext);
1122		startAudio();
1123	}
1124}
1125
1126void GameController::setSaveStateExtdata(int flags) {
1127	m_saveStateFlags = flags;
1128}
1129
1130void GameController::setLoadStateExtdata(int flags) {
1131	m_loadStateFlags = flags;
1132}
1133
1134void GameController::setPreload(bool preload) {
1135	m_preload = preload;
1136}
1137
1138void GameController::setLuminanceValue(uint8_t value) {
1139	m_luxValue = value;
1140	value = std::max<int>(value - 0x16, 0);
1141	m_luxLevel = 10;
1142	for (int i = 0; i < 10; ++i) {
1143		if (value < GBA_LUX_LEVELS[i]) {
1144			m_luxLevel = i;
1145			break;
1146		}
1147	}
1148	emit luminanceValueChanged(m_luxValue);
1149}
1150
1151void GameController::setLuminanceLevel(int level) {
1152	int value = 0x16;
1153	level = std::max(0, std::min(10, level));
1154	if (level > 0) {
1155		value += GBA_LUX_LEVELS[level - 1];
1156	}
1157	setLuminanceValue(value);
1158}
1159
1160void GameController::setRealTime() {
1161	if (!isLoaded()) {
1162		return;
1163	}
1164	m_threadContext.core->rtc.override = RTC_NO_OVERRIDE;
1165}
1166
1167void GameController::setFixedTime(const QDateTime& time) {
1168	if (!isLoaded()) {
1169		return;
1170	}
1171	m_threadContext.core->rtc.override = RTC_FIXED;
1172	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
1173}
1174
1175void GameController::setFakeEpoch(const QDateTime& time) {
1176	if (!isLoaded()) {
1177		return;
1178	}
1179	m_threadContext.core->rtc.override = RTC_FAKE_EPOCH;
1180	m_threadContext.core->rtc.value = time.toMSecsSinceEpoch();
1181}
1182
1183void GameController::updateKeys() {
1184	int activeKeys = m_activeKeys;
1185	activeKeys |= m_activeButtons;
1186	activeKeys &= ~m_inactiveKeys;
1187	if (isLoaded()) {
1188		m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
1189	}
1190}
1191
1192void GameController::redoSamples(int samples) {
1193	if (m_gameOpen && m_threadContext.core) {
1194		m_threadContext.core->setAudioBufferSize(m_threadContext.core, samples);
1195	}
1196	m_audioProcessor->inputParametersChanged();
1197}
1198
1199void GameController::setLogLevel(int levels) {
1200	Interrupter interrupter(this);
1201	m_logLevels = levels;
1202}
1203
1204void GameController::enableLogLevel(int levels) {
1205	Interrupter interrupter(this);
1206	m_logLevels |= levels;
1207}
1208
1209void GameController::disableLogLevel(int levels) {
1210	Interrupter interrupter(this);
1211	m_logLevels &= ~levels;
1212}
1213
1214void GameController::pollEvents() {
1215	if (!m_inputController) {
1216		return;
1217	}
1218
1219	m_activeButtons = m_inputController->pollEvents();
1220	updateKeys();
1221}
1222
1223void GameController::updateAutofire() {
1224	// TODO: Move all key events onto the CPU thread...somehow
1225	for (int k = 0; k < GBA_KEY_MAX; ++k) {
1226		if (!m_autofire[k]) {
1227			continue;
1228		}
1229		m_autofireStatus[k] ^= 1;
1230		if (m_autofireStatus[k]) {
1231			keyPressed(k);
1232		} else {
1233			keyReleased(k);
1234		}
1235	}
1236}
1237
1238std::shared_ptr<mTileCache> GameController::tileCache() {
1239	if (m_tileCache) {
1240		return m_tileCache;
1241	}
1242	switch (platform()) {
1243#ifdef M_CORE_GBA
1244	case PLATFORM_GBA: {
1245		Interrupter interrupter(this);
1246		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
1247		m_tileCache = std::make_shared<mTileCache>();
1248		GBAVideoTileCacheInit(m_tileCache.get());
1249		GBAVideoTileCacheAssociate(m_tileCache.get(), &gba->video);
1250		mTileCacheSetPalette(m_tileCache.get(), 0);
1251		break;
1252	}
1253#endif
1254#ifdef M_CORE_GB
1255	case PLATFORM_GB: {
1256		Interrupter interrupter(this);
1257		GB* gb = static_cast<GB*>(m_threadContext.core->board);
1258		m_tileCache = std::make_shared<mTileCache>();
1259		GBVideoTileCacheInit(m_tileCache.get());
1260		GBVideoTileCacheAssociate(m_tileCache.get(), &gb->video);
1261		mTileCacheSetPalette(m_tileCache.get(), 0);
1262		break;
1263	}
1264#endif
1265	default:
1266		return nullptr;
1267	}
1268	return m_tileCache;
1269}
1270
1271GameController::Interrupter::Interrupter(GameController* parent, bool fromThread)
1272	: m_parent(parent)
1273	, m_fromThread(fromThread)
1274{
1275	if (!m_fromThread) {
1276		m_parent->threadInterrupt();
1277	} else {
1278		mCoreThreadInterruptFromThread(m_parent->thread());
1279	}
1280}
1281
1282GameController::Interrupter::~Interrupter() {
1283	if (!m_fromThread) {
1284		m_parent->threadContinue();
1285	} else {
1286		mCoreThreadContinue(m_parent->thread());
1287	}
1288}