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