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