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