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