all repos — mgba @ 2da8c63ec2be3b5816a5f5741c9737789afeb653

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#include <QThread>
  17
  18#include <ctime>
  19
  20#include <mgba/core/config.h>
  21#include <mgba/core/directories.h>
  22#include <mgba/core/serialize.h>
  23#include <mgba/core/tile-cache.h>
  24#ifdef M_CORE_GBA
  25#include <mgba/gba/interface.h>
  26#include <mgba/internal/gba/bios.h>
  27#include <mgba/internal/gba/gba.h>
  28#include <mgba/gba/core.h>
  29#include <mgba/internal/gba/renderers/tile-cache.h>
  30#include <mgba/internal/gba/sharkport.h>
  31#endif
  32#ifdef M_CORE_GB
  33#include <mgba/internal/gb/gb.h>
  34#include <mgba/internal/gb/renderers/tile-cache.h>
  35#endif
  36#include <mgba-util/vfs.h>
  37
  38using namespace QGBA;
  39using namespace std;
  40
  41GameController::GameController(QObject* parent)
  42	: QObject(parent)
  43	, m_drawContext(nullptr)
  44	, m_frontBuffer(nullptr)
  45	, m_threadContext()
  46	, m_activeKeys(0)
  47	, m_inactiveKeys(0)
  48	, m_logLevels(0)
  49	, m_gameOpen(false)
  50	, m_vf(nullptr)
  51	, m_useBios(false)
  52	, m_audioThread(new QThread(this))
  53	, m_audioProcessor(AudioProcessor::create())
  54	, m_pauseAfterFrame(false)
  55	, m_sync(true)
  56	, m_videoSync(VIDEO_SYNC)
  57	, m_audioSync(AUDIO_SYNC)
  58	, m_fpsTarget(-1)
  59	, m_turbo(false)
  60	, m_turboForced(false)
  61	, m_turboSpeed(-1)
  62	, m_wasPaused(false)
  63	, m_audioChannels{ true, true, true, true, true, true }
  64	, m_videoLayers{ true, true, true, true, true }
  65	, m_autofire{}
  66	, m_autofireStatus{}
  67	, m_inputController(nullptr)
  68	, m_multiplayer(nullptr)
  69	, m_stream(nullptr)
  70	, m_stateSlot(1)
  71	, m_backupLoadState(nullptr)
  72	, m_backupSaveState(nullptr)
  73	, m_saveStateFlags(SAVESTATE_SCREENSHOT | SAVESTATE_SAVEDATA | SAVESTATE_CHEATS)
  74	, m_loadStateFlags(SAVESTATE_SCREENSHOT)
  75	, m_override(nullptr)
  76{
  77#ifdef M_CORE_GBA
  78	m_lux.p = this;
  79	m_lux.sample = [](GBALuminanceSource* context) {
  80		GameControllerLux* lux = static_cast<GameControllerLux*>(context);
  81		lux->value = 0xFF - lux->p->m_luxValue;
  82	};
  83
  84	m_lux.readLuminance = [](GBALuminanceSource* context) {
  85		GameControllerLux* lux = static_cast<GameControllerLux*>(context);
  86		return lux->value;
  87	};
  88	setLuminanceLevel(0);
  89#endif
  90
  91	m_threadContext.startCallback = [](mCoreThread* context) {
  92		GameController* controller = static_cast<GameController*>(context->userData);
  93		mRTCGenericSourceInit(&controller->m_rtc, context->core);
  94		context->core->setRTC(context->core, &controller->m_rtc.d);
  95		context->core->setRotation(context->core, controller->m_inputController->rotationSource());
  96		context->core->setRumble(context->core, controller->m_inputController->rumble());
  97
  98#ifdef M_CORE_GBA
  99		GBA* gba = static_cast<GBA*>(context->core->board);
 100#endif
 101#ifdef M_CORE_GB
 102		GB* gb = static_cast<GB*>(context->core->board);
 103#endif
 104		switch (context->core->platform(context->core)) {
 105#ifdef M_CORE_GBA
 106		case PLATFORM_GBA:
 107			gba->luminanceSource = &controller->m_lux;
 108			gba->audio.psg.forceDisableCh[0] = !controller->m_audioChannels[0];
 109			gba->audio.psg.forceDisableCh[1] = !controller->m_audioChannels[1];
 110			gba->audio.psg.forceDisableCh[2] = !controller->m_audioChannels[2];
 111			gba->audio.psg.forceDisableCh[3] = !controller->m_audioChannels[3];
 112			gba->audio.forceDisableChA = !controller->m_audioChannels[4];
 113			gba->audio.forceDisableChB = !controller->m_audioChannels[5];
 114			gba->video.renderer->disableBG[0] = !controller->m_videoLayers[0];
 115			gba->video.renderer->disableBG[1] = !controller->m_videoLayers[1];
 116			gba->video.renderer->disableBG[2] = !controller->m_videoLayers[2];
 117			gba->video.renderer->disableBG[3] = !controller->m_videoLayers[3];
 118			gba->video.renderer->disableOBJ = !controller->m_videoLayers[4];
 119			break;
 120#endif
 121#ifdef M_CORE_GB
 122		case PLATFORM_GB:
 123			gb->audio.forceDisableCh[0] = !controller->m_audioChannels[0];
 124			gb->audio.forceDisableCh[1] = !controller->m_audioChannels[1];
 125			gb->audio.forceDisableCh[2] = !controller->m_audioChannels[2];
 126			gb->audio.forceDisableCh[3] = !controller->m_audioChannels[3];
 127			break;
 128#endif
 129		default:
 130			break;
 131		}
 132		controller->m_fpsTarget = context->sync.fpsTarget;
 133
 134		if (controller->m_override) {
 135			controller->m_override->identify(context->core);
 136			controller->m_override->apply(context->core);
 137		}
 138
 139		if (mCoreLoadState(context->core, 0, controller->m_loadStateFlags)) {
 140			mCoreDeleteState(context->core, 0);
 141		}
 142
 143		controller->m_gameOpen = true;
 144		if (controller->m_multiplayer) {
 145			controller->m_multiplayer->attachGame(controller);
 146		}
 147
 148		QString path = controller->m_fname;
 149		if (!controller->m_fsub.isEmpty()) {
 150			path += QDir::separator() + controller->m_fsub;
 151		}
 152		QMetaObject::invokeMethod(controller, "gameStarted", Q_ARG(mCoreThread*, context), Q_ARG(const QString&, path));
 153		QMetaObject::invokeMethod(controller, "startAudio");
 154	};
 155
 156	m_threadContext.resetCallback = [](mCoreThread* context) {
 157		GameController* controller = static_cast<GameController*>(context->userData);
 158		for (auto action : controller->m_resetActions) {
 159			action();
 160		}
 161		controller->m_resetActions.clear();
 162
 163		unsigned width, height;
 164		controller->m_threadContext.core->desiredVideoDimensions(controller->m_threadContext.core, &width, &height);
 165		memset(controller->m_frontBuffer, 0xFF, width * height * BYTES_PER_PIXEL);
 166		QMetaObject::invokeMethod(controller, "frameAvailable", Q_ARG(const uint32_t*, controller->m_frontBuffer));
 167		if (controller->m_pauseAfterFrame.testAndSetAcquire(true, false)) {
 168			mCoreThreadPauseFromThread(context);
 169			QMetaObject::invokeMethod(controller, "gamePaused", Q_ARG(mCoreThread*, context));
 170		}
 171	};
 172
 173	m_threadContext.cleanCallback = [](mCoreThread* context) {
 174		GameController* controller = static_cast<GameController*>(context->userData);
 175
 176		if (controller->m_multiplayer) {
 177			controller->m_multiplayer->detachGame(controller);
 178		}
 179		controller->m_patch = QString();
 180		controller->clearOverride();
 181
 182		QMetaObject::invokeMethod(controller->m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
 183
 184		QMetaObject::invokeMethod(controller, "gameStopped", Q_ARG(mCoreThread*, context));
 185		QMetaObject::invokeMethod(controller, "cleanGame");
 186	};
 187
 188	m_threadContext.frameCallback = [](mCoreThread* context) {
 189		GameController* controller = static_cast<GameController*>(context->userData);
 190		unsigned width, height;
 191		controller->m_threadContext.core->desiredVideoDimensions(controller->m_threadContext.core, &width, &height);
 192		memcpy(controller->m_frontBuffer, controller->m_drawContext, width * height * BYTES_PER_PIXEL);
 193		QMetaObject::invokeMethod(controller, "frameAvailable", Q_ARG(const uint32_t*, controller->m_frontBuffer));
 194
 195		// If no one is using the tile cache, disable it
 196		if (controller->m_tileCache && controller->m_tileCache.unique()) {
 197			switch (controller->platform()) {
 198#ifdef M_CORE_GBA
 199			case PLATFORM_GBA: {
 200				GBA* gba = static_cast<GBA*>(context->core->board);
 201				gba->video.renderer->cache = nullptr;
 202				break;
 203			}
 204#endif
 205#ifdef M_CORE_GB
 206			case PLATFORM_GB: {
 207				GB* gb = static_cast<GB*>(context->core->board);
 208				gb->video.renderer->cache = nullptr;
 209				break;
 210			}
 211#endif
 212			default:
 213				break;
 214			}
 215			controller->m_tileCache.reset();
 216		}
 217
 218
 219		if (controller->m_pauseAfterFrame.testAndSetAcquire(true, false)) {
 220			mCoreThreadPauseFromThread(context);
 221			QMetaObject::invokeMethod(controller, "gamePaused", Q_ARG(mCoreThread*, context));
 222		}
 223	};
 224
 225	// TODO: Put back
 226	/*m_threadContext.stopCallback = [](mCoreThread* context) {
 227		if (!context) {
 228			return false;
 229		}
 230		GameController* controller = static_cast<GameController*>(context->userData);
 231		if (!mCoreSaveState(context->core, 0, controller->m_saveStateFlags)) {
 232			return false;
 233		}
 234		QMetaObject::invokeMethod(controller, "closeGame");
 235		return true;
 236	};*/
 237
 238	m_threadContext.logger.d.log = [](mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
 239		mThreadLogger* logContext = reinterpret_cast<mThreadLogger*>(logger);
 240		mCoreThread* context = logContext->p;
 241
 242		static const char* savestateMessage = "State %i loaded";
 243		static const char* savestateFailedMessage = "State %i failed to load";
 244		if (!context) {
 245			return;
 246		}
 247		GameController* controller = static_cast<GameController*>(context->userData);
 248		QString message;
 249#ifdef M_CORE_GBA
 250		if (level == mLOG_STUB && category == _mLOG_CAT_GBA_BIOS()) {
 251			va_list argc;
 252			va_copy(argc, args);
 253			int immediate = va_arg(argc, int);
 254			va_end(argc);
 255			QMetaObject::invokeMethod(controller, "unimplementedBiosCall", Q_ARG(int, immediate));
 256		} else
 257#endif
 258		if (category == _mLOG_CAT_STATUS()) {
 259			// Slot 0 is reserved for suspend points
 260			if (strncmp(savestateMessage, format, strlen(savestateMessage)) == 0) {
 261				va_list argc;
 262				va_copy(argc, args);
 263				int slot = va_arg(argc, int);
 264				va_end(argc);
 265				if (slot == 0) {
 266					format = "Loaded suspend state";
 267				}
 268			} else if (strncmp(savestateFailedMessage, format, strlen(savestateFailedMessage)) == 0) {
 269				va_list argc;
 270				va_copy(argc, args);
 271				int slot = va_arg(argc, int);
 272				va_end(argc);
 273				if (slot == 0) {
 274					return;
 275				}
 276			}
 277			message = QString().vsprintf(format, args);
 278			QMetaObject::invokeMethod(controller, "statusPosted", Q_ARG(const QString&, message));
 279		}
 280		if (level == mLOG_FATAL) {
 281			mCoreThreadMarkCrashed(controller->thread());
 282			QMetaObject::invokeMethod(controller, "crashGame", Q_ARG(const QString&, QString().vsprintf(format, args)));
 283		} else if (!(controller->m_logLevels & level)) {
 284			return;
 285		}
 286		message = QString().vsprintf(format, args);
 287		QMetaObject::invokeMethod(controller, "postLog", Q_ARG(int, level), Q_ARG(int, category), Q_ARG(const QString&, message));
 288	};
 289
 290	m_threadContext.userData = this;
 291
 292	m_audioThread->setObjectName("Audio Thread");
 293	m_audioThread->start(QThread::TimeCriticalPriority);
 294	m_audioProcessor->moveToThread(m_audioThread);
 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	m_audioThread->quit();
 305	m_audioThread->wait();
 306	clearMultiplayerController();
 307	delete m_backupLoadState;
 308}
 309
 310void GameController::setMultiplayerController(MultiplayerController* controller) {
 311	if (controller == m_multiplayer) {
 312		return;
 313	}
 314	clearMultiplayerController();
 315	m_multiplayer = controller;
 316	if (isLoaded()) {
 317		mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* thread) {
 318			GameController* controller = static_cast<GameController*>(thread->userData);
 319			controller->m_multiplayer->attachGame(controller);
 320		});
 321	}
 322}
 323
 324void GameController::clearMultiplayerController() {
 325	if (!m_multiplayer) {
 326		return;
 327	}
 328	m_multiplayer->detachGame(this);
 329	m_multiplayer = nullptr;
 330}
 331
 332void GameController::setOverride(Override* override) {
 333	m_override = override;
 334	if (isLoaded()) {
 335		Interrupter interrupter(this);
 336		m_override->identify(m_threadContext.core);
 337	}
 338}
 339
 340void GameController::clearOverride() {
 341	delete m_override;
 342	m_override = nullptr;
 343}
 344
 345void GameController::setConfig(const mCoreConfig* config) {
 346	m_config = config;
 347	if (isLoaded()) {
 348		Interrupter interrupter(this);
 349		mCoreLoadForeignConfig(m_threadContext.core, config);
 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 = base + QDir::separator() + path;
 413		m_fsub = QString();
 414	} else {
 415		m_fname = base;
 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) {
 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		if (enable && capacity > 0) {
 743			mCoreRewindContextInit(&m_threadContext.rewind, capacity);
 744		}
 745	}
 746}
 747
 748void GameController::rewind(int states) {
 749	threadInterrupt();
 750	if (!states) {
 751		states = INT_MAX;
 752	}
 753	for (int i = 0; i < states; ++i) {
 754		if (!mCoreRewindRestore(&m_threadContext.rewind, m_threadContext.core)) {
 755			break;
 756		}
 757	}
 758	threadContinue();
 759	emit frameAvailable(m_drawContext);
 760	emit rewound(&m_threadContext);
 761}
 762
 763void GameController::startRewinding() {
 764	if (!isLoaded()) {
 765		return;
 766	}
 767	if (!m_threadContext.core->opts.rewindEnable) {
 768		return;
 769	}
 770	if (m_multiplayer && m_multiplayer->attached() > 1) {
 771		return;
 772	}
 773	if (m_wasPaused) {
 774		setPaused(false);
 775		m_wasPaused = true;
 776	}
 777	mCoreThreadSetRewinding(&m_threadContext, true);
 778}
 779
 780void GameController::stopRewinding() {
 781	if (!isLoaded()) {
 782		return;
 783	}
 784	mCoreThreadSetRewinding(&m_threadContext, false);
 785	bool signalsBlocked = blockSignals(true);
 786	setPaused(m_wasPaused);
 787	blockSignals(signalsBlocked);
 788}
 789
 790void GameController::keyPressed(int key) {
 791	int mappedKey = 1 << key;
 792	m_activeKeys |= mappedKey;
 793	if (!m_inputController->allowOpposing()) {
 794		if ((m_activeKeys & 0x30) == 0x30) {
 795			m_inactiveKeys |= mappedKey ^ 0x30;
 796			m_activeKeys ^= mappedKey ^ 0x30;
 797		}
 798		if ((m_activeKeys & 0xC0) == 0xC0) {
 799			m_inactiveKeys |= mappedKey ^ 0xC0;
 800			m_activeKeys ^= mappedKey ^ 0xC0;
 801		}
 802	}
 803	updateKeys();
 804}
 805
 806void GameController::keyReleased(int key) {
 807	int mappedKey = 1 << key;
 808	m_activeKeys &= ~mappedKey;
 809	if (!m_inputController->allowOpposing()) {
 810		if (mappedKey & 0x30) {
 811			m_activeKeys |= m_inactiveKeys & (0x30 ^ mappedKey);
 812			m_inactiveKeys &= ~0x30;
 813		}
 814		if (mappedKey & 0xC0) {
 815			m_activeKeys |= m_inactiveKeys & (0xC0 ^ mappedKey);
 816			m_inactiveKeys &= ~0xC0;
 817		}
 818	}
 819	updateKeys();
 820}
 821
 822void GameController::cursorLocation(int x, int y) {
 823	if (!isLoaded()) {
 824		return;
 825	}
 826	m_threadContext.core->setCursorLocation(m_threadContext.core, x, y);
 827}
 828
 829void GameController::cursorDown(bool down) {
 830	if (!isLoaded()) {
 831		return;
 832	}
 833	m_threadContext.core->setCursorDown(m_threadContext.core, down);
 834}
 835
 836void GameController::clearKeys() {
 837	m_activeKeys = 0;
 838	m_inactiveKeys = 0;
 839	updateKeys();
 840}
 841
 842void GameController::setAutofire(int key, bool enable) {
 843	if (key >= GBA_KEY_MAX || key < 0) {
 844		return;
 845	}
 846
 847	if (!enable && m_autofireStatus[key]) {
 848		keyReleased(key);
 849	}
 850
 851	m_autofire[key] = enable;
 852	m_autofireStatus[key] = 0;
 853}
 854
 855void GameController::setAudioBufferSamples(int samples) {
 856	if (m_audioProcessor) {
 857		threadInterrupt();
 858		redoSamples(samples);
 859		threadContinue();
 860		QMetaObject::invokeMethod(m_audioProcessor, "setBufferSamples", Qt::BlockingQueuedConnection, Q_ARG(int, samples));
 861	}
 862}
 863
 864void GameController::setAudioSampleRate(unsigned rate) {
 865	if (!rate) {
 866		return;
 867	}
 868	if (m_audioProcessor) {
 869		threadInterrupt();
 870		redoSamples(m_audioProcessor->getBufferSamples());
 871		threadContinue();
 872		QMetaObject::invokeMethod(m_audioProcessor, "requestSampleRate", Q_ARG(unsigned, rate));
 873	}
 874}
 875
 876void GameController::setAudioChannelEnabled(int channel, bool enable) {
 877	if (channel > 5 || channel < 0) {
 878		return;
 879	}
 880#ifdef M_CORE_GBA
 881	GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
 882#endif
 883#ifdef M_CORE_GB
 884	GB* gb = static_cast<GB*>(m_threadContext.core->board);
 885#endif
 886	m_audioChannels[channel] = enable;
 887	if (isLoaded()) {
 888		switch (channel) {
 889		case 0:
 890		case 1:
 891		case 2:
 892		case 3:
 893			switch (m_threadContext.core->platform(m_threadContext.core)) {
 894#ifdef M_CORE_GBA
 895			case PLATFORM_GBA:
 896				gba->audio.psg.forceDisableCh[channel] = !enable;
 897				break;
 898#endif
 899#ifdef M_CORE_GB
 900			case PLATFORM_GB:
 901				gb->audio.forceDisableCh[channel] = !enable;
 902				break;
 903#endif
 904			default:
 905				break;
 906			}
 907			break;
 908#ifdef M_CORE_GBA
 909		case 4:
 910			if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 911				gba->audio.forceDisableChA = !enable;
 912			}
 913			break;
 914		case 5:
 915			if (m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 916				gba->audio.forceDisableChB = !enable;
 917			}
 918			break;
 919#endif
 920		}
 921	}
 922}
 923
 924void GameController::startAudio() {
 925	bool started = false;
 926	QMetaObject::invokeMethod(m_audioProcessor, "start", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, started));
 927	if (!started) {
 928		LOG(QT, ERROR) << tr("Failed to start audio processor");
 929		// Don't freeze!
 930		m_audioSync = false;
 931		m_videoSync = true;
 932		m_threadContext.sync.audioWait = false;
 933		m_threadContext.sync.videoFrameWait = true;
 934	}
 935}
 936
 937void GameController::setVideoLayerEnabled(int layer, bool enable) {
 938	if (layer > 4 || layer < 0) {
 939		return;
 940	}
 941	m_videoLayers[layer] = enable;
 942#ifdef M_CORE_GBA
 943	if (isLoaded() && m_threadContext.core->platform(m_threadContext.core) == PLATFORM_GBA) {
 944		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
 945		switch (layer) {
 946		case 0:
 947		case 1:
 948		case 2:
 949		case 3:
 950			gba->video.renderer->disableBG[layer] = !enable;
 951			break;
 952		case 4:
 953			gba->video.renderer->disableOBJ = !enable;
 954			break;
 955		}
 956	}
 957#endif
 958}
 959
 960void GameController::setFPSTarget(float fps) {
 961	Interrupter interrupter(this);
 962	m_fpsTarget = fps;
 963	m_threadContext.sync.fpsTarget = fps;
 964	if (m_turbo && m_turboSpeed > 0) {
 965		m_threadContext.sync.fpsTarget *= m_turboSpeed;
 966	}
 967	if (m_audioProcessor) {
 968		redoSamples(m_audioProcessor->getBufferSamples());
 969	}
 970}
 971
 972void GameController::setUseBIOS(bool use) {
 973	if (use == m_useBios) {
 974		return;
 975	}
 976	m_useBios = use;
 977	if (m_gameOpen) {
 978		closeGame();
 979		openGame();
 980	}
 981}
 982
 983void GameController::loadState(int slot) {
 984	if (m_fname.isEmpty()) {
 985		// We're in the BIOS
 986		return;
 987	}
 988	if (slot > 0 && slot != m_stateSlot) {
 989		m_stateSlot = slot;
 990		m_backupSaveState.clear();
 991	}
 992	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
 993		GameController* controller = static_cast<GameController*>(context->userData);
 994		if (!controller->m_backupLoadState) {
 995			controller->m_backupLoadState = VFileMemChunk(nullptr, 0);
 996		}
 997		mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_saveStateFlags);
 998		if (mCoreLoadState(context->core, controller->m_stateSlot, controller->m_loadStateFlags)) {
 999			controller->frameAvailable(controller->m_drawContext);
1000			controller->stateLoaded(context);
1001		}
1002	});
1003}
1004
1005void GameController::saveState(int slot) {
1006	if (m_fname.isEmpty()) {
1007		// We're in the BIOS
1008		return;
1009	}
1010	if (slot > 0) {
1011		m_stateSlot = slot;
1012	}
1013	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1014		GameController* controller = static_cast<GameController*>(context->userData);
1015		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, false);
1016		if (vf) {
1017			controller->m_backupSaveState.resize(vf->size(vf));
1018			vf->read(vf, controller->m_backupSaveState.data(), controller->m_backupSaveState.size());
1019			vf->close(vf);
1020		}
1021		mCoreSaveState(context->core, controller->m_stateSlot, controller->m_saveStateFlags);
1022	});
1023}
1024
1025void GameController::loadBackupState() {
1026	if (!m_backupLoadState) {
1027		return;
1028	}
1029
1030	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1031		GameController* controller = static_cast<GameController*>(context->userData);
1032		controller->m_backupLoadState->seek(controller->m_backupLoadState, 0, SEEK_SET);
1033		if (mCoreLoadStateNamed(context->core, controller->m_backupLoadState, controller->m_loadStateFlags)) {
1034			mLOG(STATUS, INFO, "Undid state load");
1035			controller->frameAvailable(controller->m_drawContext);
1036			controller->stateLoaded(context);
1037		}
1038		controller->m_backupLoadState->close(controller->m_backupLoadState);
1039		controller->m_backupLoadState = nullptr;
1040	});
1041}
1042
1043void GameController::saveBackupState() {
1044	if (m_backupSaveState.isEmpty()) {
1045		return;
1046	}
1047
1048	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1049		GameController* controller = static_cast<GameController*>(context->userData);
1050		VFile* vf = mCoreGetState(context->core, controller->m_stateSlot, true);
1051		if (vf) {
1052			vf->write(vf, controller->m_backupSaveState.constData(), controller->m_backupSaveState.size());
1053			vf->close(vf);
1054			mLOG(STATUS, INFO, "Undid state save");
1055		}
1056		controller->m_backupSaveState.clear();
1057	});
1058}
1059
1060void GameController::setTurbo(bool set, bool forced) {
1061	if (m_turboForced && !forced) {
1062		return;
1063	}
1064	if (m_turbo == set && m_turboForced == (set && forced)) {
1065		// Don't interrupt the thread if we don't need to
1066		return;
1067	}
1068	if (!m_sync) {
1069		return;
1070	}
1071	m_turbo = set;
1072	m_turboForced = set && forced;
1073	enableTurbo();
1074}
1075
1076void GameController::setTurboSpeed(float ratio) {
1077	m_turboSpeed = ratio;
1078	enableTurbo();
1079}
1080
1081void GameController::enableTurbo() {
1082	Interrupter interrupter(this);
1083	bool shouldRedoSamples = false;
1084	if (!m_turbo) {
1085		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1086		m_threadContext.sync.fpsTarget = m_fpsTarget;
1087		m_threadContext.sync.audioWait = m_audioSync;
1088		m_threadContext.sync.videoFrameWait = m_videoSync;
1089	} else if (m_turboSpeed <= 0) {
1090		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget;
1091		m_threadContext.sync.fpsTarget = m_fpsTarget;
1092		m_threadContext.sync.audioWait = false;
1093		m_threadContext.sync.videoFrameWait = false;
1094	} else {
1095		shouldRedoSamples = m_threadContext.sync.fpsTarget != m_fpsTarget * m_turboSpeed;
1096		m_threadContext.sync.fpsTarget = m_fpsTarget * m_turboSpeed;
1097		m_threadContext.sync.audioWait = true;
1098		m_threadContext.sync.videoFrameWait = false;
1099	}
1100	if (m_audioProcessor && shouldRedoSamples) {
1101		redoSamples(m_audioProcessor->getBufferSamples());
1102	}
1103}
1104
1105void GameController::setSync(bool enable) {
1106	m_turbo = false;
1107	m_turboForced = false;
1108	if (!enable) {
1109		m_threadContext.sync.audioWait = false;
1110		m_threadContext.sync.videoFrameWait = false;
1111	} else {
1112		m_threadContext.sync.audioWait = m_audioSync;
1113		m_threadContext.sync.videoFrameWait = m_videoSync;
1114	}
1115	m_sync = enable;
1116}
1117void GameController::setAVStream(mAVStream* stream) {
1118	Interrupter interrupter(this);
1119	m_stream = stream;
1120	if (isLoaded()) {
1121		m_threadContext.core->setAVStream(m_threadContext.core, stream);
1122	}
1123}
1124
1125void GameController::clearAVStream() {
1126	Interrupter interrupter(this);
1127	m_stream = nullptr;
1128	if (isLoaded()) {
1129		m_threadContext.core->setAVStream(m_threadContext.core, nullptr);
1130	}
1131}
1132
1133#ifdef USE_PNG
1134void GameController::screenshot() {
1135	mCoreThreadRunFunction(&m_threadContext, [](mCoreThread* context) {
1136		mCoreTakeScreenshot(context->core);
1137	});
1138}
1139#endif
1140
1141void GameController::reloadAudioDriver() {
1142	int samples = 0;
1143	unsigned sampleRate = 0;
1144	if (m_audioProcessor) {
1145		QMetaObject::invokeMethod(m_audioProcessor, "pause", Qt::BlockingQueuedConnection);
1146		samples = m_audioProcessor->getBufferSamples();
1147		sampleRate = m_audioProcessor->sampleRate();
1148		delete m_audioProcessor;
1149	}
1150	m_audioProcessor = AudioProcessor::create();
1151	if (samples) {
1152		m_audioProcessor->setBufferSamples(samples);
1153	}
1154	if (sampleRate) {
1155		m_audioProcessor->requestSampleRate(sampleRate);
1156	}
1157	m_audioProcessor->moveToThread(m_audioThread);
1158	connect(this, SIGNAL(gamePaused(mCoreThread*)), m_audioProcessor, SLOT(pause()));
1159	connect(this, SIGNAL(gameStarted(mCoreThread*, const QString&)), m_audioProcessor, SLOT(setInput(mCoreThread*)));
1160	if (isLoaded()) {
1161		m_audioProcessor->setInput(&m_threadContext);
1162		startAudio();
1163	}
1164}
1165
1166void GameController::setSaveStateExtdata(int flags) {
1167	m_saveStateFlags = flags;
1168}
1169
1170void GameController::setLoadStateExtdata(int flags) {
1171	m_loadStateFlags = flags;
1172}
1173
1174void GameController::setLuminanceValue(uint8_t value) {
1175	m_luxValue = value;
1176	value = std::max<int>(value - 0x16, 0);
1177	m_luxLevel = 10;
1178	for (int i = 0; i < 10; ++i) {
1179		if (value < GBA_LUX_LEVELS[i]) {
1180			m_luxLevel = i;
1181			break;
1182		}
1183	}
1184	emit luminanceValueChanged(m_luxValue);
1185}
1186
1187void GameController::setLuminanceLevel(int level) {
1188	int value = 0x16;
1189	level = std::max(0, std::min(10, level));
1190	if (level > 0) {
1191		value += GBA_LUX_LEVELS[level - 1];
1192	}
1193	setLuminanceValue(value);
1194}
1195
1196void GameController::setRealTime() {
1197	m_rtc.override = RTC_NO_OVERRIDE;
1198}
1199
1200void GameController::setFixedTime(const QDateTime& time) {
1201	m_rtc.override = RTC_FIXED;
1202	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
1203}
1204
1205void GameController::setFakeEpoch(const QDateTime& time) {
1206	m_rtc.override = RTC_FAKE_EPOCH;
1207	m_rtc.value = time.toMSecsSinceEpoch() / 1000;
1208}
1209
1210void GameController::updateKeys() {
1211	int activeKeys = m_activeKeys;
1212	activeKeys |= m_activeButtons;
1213	activeKeys &= ~m_inactiveKeys;
1214	if (isLoaded()) {
1215		m_threadContext.core->setKeys(m_threadContext.core, activeKeys);
1216	}
1217}
1218
1219void GameController::redoSamples(int samples) {
1220	if (m_threadContext.core) {
1221		m_threadContext.core->setAudioBufferSize(m_threadContext.core, samples);
1222	}
1223	QMetaObject::invokeMethod(m_audioProcessor, "inputParametersChanged");
1224}
1225
1226void GameController::setLogLevel(int levels) {
1227	Interrupter interrupter(this);
1228	m_logLevels = levels;
1229}
1230
1231void GameController::enableLogLevel(int levels) {
1232	Interrupter interrupter(this);
1233	m_logLevels |= levels;
1234}
1235
1236void GameController::disableLogLevel(int levels) {
1237	Interrupter interrupter(this);
1238	m_logLevels &= ~levels;
1239}
1240
1241void GameController::pollEvents() {
1242	if (!m_inputController) {
1243		return;
1244	}
1245
1246	m_activeButtons = m_inputController->pollEvents();
1247	updateKeys();
1248}
1249
1250void GameController::updateAutofire() {
1251	// TODO: Move all key events onto the CPU thread...somehow
1252	for (int k = 0; k < GBA_KEY_MAX; ++k) {
1253		if (!m_autofire[k]) {
1254			continue;
1255		}
1256		m_autofireStatus[k] ^= 1;
1257		if (m_autofireStatus[k]) {
1258			keyPressed(k);
1259		} else {
1260			keyReleased(k);
1261		}
1262	}
1263}
1264
1265std::shared_ptr<mTileCache> GameController::tileCache() {
1266	if (m_tileCache) {
1267		return m_tileCache;
1268	}
1269	switch (platform()) {
1270#ifdef M_CORE_GBA
1271	case PLATFORM_GBA: {
1272		Interrupter interrupter(this);
1273		GBA* gba = static_cast<GBA*>(m_threadContext.core->board);
1274		m_tileCache = std::make_shared<mTileCache>();
1275		GBAVideoTileCacheInit(m_tileCache.get());
1276		GBAVideoTileCacheAssociate(m_tileCache.get(), &gba->video);
1277		mTileCacheSetPalette(m_tileCache.get(), 0);
1278		break;
1279	}
1280#endif
1281#ifdef M_CORE_GB
1282	case PLATFORM_GB: {
1283		Interrupter interrupter(this);
1284		GB* gb = static_cast<GB*>(m_threadContext.core->board);
1285		m_tileCache = std::make_shared<mTileCache>();
1286		GBVideoTileCacheInit(m_tileCache.get());
1287		GBVideoTileCacheAssociate(m_tileCache.get(), &gb->video);
1288		mTileCacheSetPalette(m_tileCache.get(), 0);
1289		break;
1290	}
1291#endif
1292	default:
1293		return nullptr;
1294	}
1295	return m_tileCache;
1296}
1297
1298GameController::Interrupter::Interrupter(GameController* parent, bool fromThread)
1299	: m_parent(parent)
1300	, m_fromThread(fromThread)
1301{
1302	if (!m_fromThread) {
1303		m_parent->threadInterrupt();
1304	} else {
1305		mCoreThreadInterruptFromThread(m_parent->thread());
1306	}
1307}
1308
1309GameController::Interrupter::~Interrupter() {
1310	if (!m_fromThread) {
1311		m_parent->threadContinue();
1312	} else {
1313		mCoreThreadContinue(m_parent->thread());
1314	}
1315}