all repos — mgba @ 10fe4a743c1b01c496987b5cac2dfc479e89c8dc

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