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