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