Merge pull request #50 from nadiaholmquist/feature/basic-controller-input

Add basic controller input using the SDL2 GameController API
This commit is contained in:
wheremyfoodat 2023-06-28 02:56:24 +03:00 committed by GitHub
commit 6dde41f7c3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 338 additions and 228 deletions

View file

@ -1,80 +1,101 @@
#pragma once #pragma once
#include <filesystem>
#include <fstream>
#include <SDL.h> #include <SDL.h>
#include <glad/gl.h> #include <glad/gl.h>
#include <filesystem>
#include <fstream>
#include "PICA/gpu.hpp"
#include "cpu.hpp" #include "cpu.hpp"
#include "crypto/aes_engine.hpp" #include "crypto/aes_engine.hpp"
#include "io_file.hpp" #include "io_file.hpp"
#include "memory.hpp" #include "memory.hpp"
#include "opengl.hpp" #include "opengl.hpp"
#include "PICA/gpu.hpp"
enum class ROMType { enum class ROMType { None, ELF, NCSD };
None, ELF, NCSD
};
class Emulator { class Emulator {
CPU cpu; CPU cpu;
GPU gpu; GPU gpu;
Memory memory; Memory memory;
Kernel kernel; Kernel kernel;
Crypto::AESEngine aesEngine; Crypto::AESEngine aesEngine;
SDL_Window* window; SDL_Window* window;
SDL_GLContext glContext; SDL_GLContext glContext;
SDL_GameController* gameController;
int gameControllerID;
static constexpr u32 width = 400; // Variables to keep track of whether the user is controlling the 3DS analog stick with their keyboard
static constexpr u32 height = 240 * 2; // * 2 because 2 screens // This is done so when a gamepad is connected, we won't automatically override the 3DS analog stick settings with the gamepad's state
ROMType romType = ROMType::None; // And so the user can still use the keyboard to control the analog
bool running = true; bool keyboardAnalogX = false;
bool keyboardAnalogY = false;
// Keep the handle for the ROM here to reload when necessary and to prevent deleting it static constexpr u32 width = 400;
// This is currently only used for ELFs, NCSDs use the IOFile API instead static constexpr u32 height = 240 * 2; // * 2 because 2 screens
std::ifstream loadedELF; ROMType romType = ROMType::None;
NCSD loadedNCSD; bool running = true;
public: // Keep the handle for the ROM here to reload when necessary and to prevent deleting it
Emulator() : kernel(cpu, memory, gpu), cpu(memory, kernel), gpu(memory), memory(cpu.getTicksRef()) { // This is currently only used for ELFs, NCSDs use the IOFile API instead
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) < 0) { std::ifstream loadedELF;
Helpers::panic("Failed to initialize SDL2"); NCSD loadedNCSD;
}
// Request OpenGL 4.1 Core (Max available on MacOS) public:
// MacOS gets mad if we don't explicitly demand a core profile Emulator() : kernel(cpu, memory, gpu), cpu(memory, kernel), gpu(memory), memory(cpu.getTicksRef()) {
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) < 0) {
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4); Helpers::panic("Failed to initialize SDL2");
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); }
window = SDL_CreateWindow("Alber", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL);
if (window == nullptr) { // Make SDL use consistent positional button mapping
Helpers::panic("Window creation failed: %s", SDL_GetError()); SDL_SetHint(SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS, "0");
} if (SDL_Init(SDL_INIT_GAMECONTROLLER) < 0) {
Helpers::warn("Failed to initialize SDL2 GameController: %s", SDL_GetError());
}
glContext = SDL_GL_CreateContext(window); // Request OpenGL 4.1 Core (Max available on MacOS)
// MacOS gets mad if we don't explicitly demand a core profile
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
window = SDL_CreateWindow("Alber", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL);
if (glContext == nullptr) { if (window == nullptr) {
Helpers::panic("OpenGL context creation failed: %s", SDL_GetError()); Helpers::panic("Window creation failed: %s", SDL_GetError());
} }
if(!gladLoadGL(reinterpret_cast<GLADloadfunc>(SDL_GL_GetProcAddress))) { glContext = SDL_GL_CreateContext(window);
Helpers::panic("OpenGL init failed: %s", SDL_GetError()); if (glContext == nullptr) {
} Helpers::panic("OpenGL context creation failed: %s", SDL_GetError());
}
reset(); if (!gladLoadGL(reinterpret_cast<GLADloadfunc>(SDL_GL_GetProcAddress))) {
} Helpers::panic("OpenGL init failed: %s", SDL_GetError());
}
void step(); if (SDL_WasInit(SDL_INIT_GAMECONTROLLER)) {
void render(); gameController = SDL_GameControllerOpen(0);
void reset();
void run();
void runFrame();
bool loadROM(const std::filesystem::path& path); if (gameController != nullptr) {
bool loadNCSD(const std::filesystem::path& path); SDL_Joystick* stick = SDL_GameControllerGetJoystick(gameController);
bool loadELF(const std::filesystem::path& path); gameControllerID = SDL_JoystickInstanceID(stick);
bool loadELF(std::ifstream& file); }
void initGraphicsContext() { gpu.initGraphicsContext(); } }
reset();
}
void step();
void render();
void reset();
void run();
void runFrame();
bool loadROM(const std::filesystem::path& path);
bool loadNCSD(const std::filesystem::path& path);
bool loadELF(const std::filesystem::path& path);
bool loadELF(std::ifstream& file);
void initGraphicsContext() { gpu.initGraphicsContext(); }
}; };

View file

@ -1,6 +1,7 @@
#pragma once #pragma once
#include <array> #include <array>
#include <optional> #include <optional>
#include "helpers.hpp" #include "helpers.hpp"
#include "kernel_types.hpp" #include "kernel_types.hpp"
#include "logger.hpp" #include "logger.hpp"
@ -22,12 +23,12 @@ namespace HID::Keys {
X = 1 << 10, X = 1 << 10,
Y = 1 << 11, Y = 1 << 11,
GPIO0Inv = 1 << 12, // Inverted value of GPIO bit 0 GPIO0Inv = 1 << 12, // Inverted value of GPIO bit 0
GPIO14Inv = 1 << 13, // Inverted value of GPIO bit 14 GPIO14Inv = 1 << 13, // Inverted value of GPIO bit 14
CirclePadRight = 1 << 28, // X >= 41 CirclePadRight = 1 << 28, // X >= 41
CirclePadLeft = 1 << 29, // X <= -41 CirclePadLeft = 1 << 29, // X <= -41
CirclePadUp = 1 << 30, // Y >= 41 CirclePadUp = 1 << 30, // Y >= 41
CirclePadDown = 1u << 31 // Y <= -41 CirclePadDown = 1u << 31 // Y <= -41
}; };
} }
@ -39,18 +40,18 @@ class HIDService {
Handle handle = KernelHandles::HID; Handle handle = KernelHandles::HID;
Memory& mem; Memory& mem;
Kernel& kernel; Kernel& kernel;
u8* sharedMem = nullptr; // Pointer to HID shared memory u8* sharedMem = nullptr; // Pointer to HID shared memory
uint nextPadIndex; uint nextPadIndex;
uint nextTouchscreenIndex; uint nextTouchscreenIndex;
uint nextAccelerometerIndex; uint nextAccelerometerIndex;
uint nextGyroIndex; uint nextGyroIndex;
u32 newButtons; // The button state currently being edited u32 newButtons; // The button state currently being edited
u32 oldButtons; // The previous pad state u32 oldButtons; // The previous pad state
s16 circlePadX, circlePadY; // Circlepad state s16 circlePadX, circlePadY; // Circlepad state
s16 touchScreenX, touchScreenY; // Touchscreen state s16 touchScreenX, touchScreenY; // Touchscreen state
bool accelerometerEnabled; bool accelerometerEnabled;
bool eventsInitialized; bool eventsInitialized;
@ -79,7 +80,7 @@ class HIDService {
*(T*)&sharedMem[offset] = value; *(T*)&sharedMem[offset] = value;
} }
public: public:
HIDService(Memory& mem, Kernel& kernel) : mem(mem), kernel(kernel) {} HIDService(Memory& mem, Kernel& kernel) : mem(mem), kernel(kernel) {}
void reset(); void reset();
void handleSyncRequest(u32 messagePointer); void handleSyncRequest(u32 messagePointer);
@ -87,15 +88,18 @@ public:
void pressKey(u32 mask) { newButtons |= mask; } void pressKey(u32 mask) { newButtons |= mask; }
void releaseKey(u32 mask) { newButtons &= ~mask; } void releaseKey(u32 mask) { newButtons &= ~mask; }
s16 getCirclepadX() { return circlePadX; }
s16 getCirclepadY() { return circlePadY; }
void setCirclepadX(s16 x) { void setCirclepadX(s16 x) {
circlePadX = x; circlePadX = x;
// Turn bits 28 and 29 off in the new button state, which indicate whether the circlepad is steering left or right // Turn bits 28 and 29 off in the new button state, which indicate whether the circlepad is steering left or right
// Then, set them according to the new value of x // Then, set them according to the new value of x
newButtons &= ~0x3000'0000; newButtons &= ~0x3000'0000;
if (x >= 41) // Pressing right if (x >= 41) // Pressing right
newButtons |= 1 << 28; newButtons |= 1 << 28;
else if (x <= -41) // Pressing left else if (x <= -41) // Pressing left
newButtons |= 1 << 29; newButtons |= 1 << 29;
} }
@ -105,9 +109,9 @@ public:
// Turn bits 30 and 31 off in the new button state, which indicate whether the circlepad is steering up or down // Turn bits 30 and 31 off in the new button state, which indicate whether the circlepad is steering up or down
// Then, set them according to the new value of y // Then, set them according to the new value of y
newButtons &= ~0xC000'0000; newButtons &= ~0xC000'0000;
if (y >= 41) // Pressing up if (y >= 41) // Pressing up
newButtons |= 1 << 30; newButtons |= 1 << 30;
else if (y <= -41) // Pressing down else if (y <= -41) // Pressing down
newButtons |= 1 << 31; newButtons |= 1 << 31;
} }
@ -115,7 +119,7 @@ public:
void setSharedMem(u8* ptr) { void setSharedMem(u8* ptr) {
sharedMem = ptr; sharedMem = ptr;
if (ptr != nullptr) { // Zero-fill shared memory in case the process tries to read stale service data or vice versa if (ptr != nullptr) { // Zero-fill shared memory in case the process tries to read stale service data or vice versa
std::memset(ptr, 0, 0x2b0); std::memset(ptr, 0, 0x2b0);
} }
} }

View file

@ -90,8 +90,10 @@ class ServiceManager {
// Input function wrappers // Input function wrappers
void pressKey(u32 key) { hid.pressKey(key); } void pressKey(u32 key) { hid.pressKey(key); }
void releaseKey(u32 key) { hid.releaseKey(key); } void releaseKey(u32 key) { hid.releaseKey(key); }
void setCirclepadX(u16 x) { hid.setCirclepadX(x); } s16 getCirclepadX() { return hid.getCirclepadX(); }
void setCirclepadY(u16 y) { hid.setCirclepadY(y); } s16 getCirclepadY() { return hid.getCirclepadY(); }
void setCirclepadX(s16 x) { hid.setCirclepadX(x); }
void setCirclepadY(s16 y) { hid.setCirclepadY(y); }
void updateInputs(u64 currentTimestamp) { hid.updateInputs(currentTimestamp); } void updateInputs(u64 currentTimestamp) { hid.updateInputs(currentTimestamp); }
void setTouchScreenPress(u16 x, u16 y) { hid.setTouchScreenPress(x, y); } void setTouchScreenPress(u16 x, u16 y) { hid.setTouchScreenPress(x, y); }
void releaseTouchScreen() { hid.releaseTouchScreen(); } void releaseTouchScreen() { hid.releaseTouchScreen(); }

View file

@ -1,203 +1,286 @@
#include "emulator.hpp" #include "emulator.hpp"
void Emulator::reset() { void Emulator::reset() {
cpu.reset(); cpu.reset();
gpu.reset(); gpu.reset();
memory.reset(); memory.reset();
// Kernel must be reset last because it depends on CPU/Memory state // Kernel must be reset last because it depends on CPU/Memory state
kernel.reset(); kernel.reset();
// Reloading r13 and r15 needs to happen after everything has been reset // Reloading r13 and r15 needs to happen after everything has been reset
// Otherwise resetting the kernel or cpu might nuke them // Otherwise resetting the kernel or cpu might nuke them
cpu.setReg(13, VirtualAddrs::StackTop); // Set initial SP cpu.setReg(13, VirtualAddrs::StackTop); // Set initial SP
if (romType == ROMType::ELF) { // Reload ELF if we're using one if (romType == ROMType::ELF) { // Reload ELF if we're using one
loadELF(loadedELF); loadELF(loadedELF);
} }
} }
void Emulator::step() {} void Emulator::step() {}
void Emulator::render() {}
void Emulator::render() {
}
void Emulator::run() { void Emulator::run() {
while (running) { while (running) {
gpu.getGraphicsContext(); // Give the GPU a rendering context gpu.getGraphicsContext(); // Give the GPU a rendering context
runFrame(); // Run 1 frame of instructions runFrame(); // Run 1 frame of instructions
gpu.display(); // Display graphics gpu.display(); // Display graphics
ServiceManager& srv = kernel.getServiceManager(); ServiceManager& srv = kernel.getServiceManager();
// Send VBlank interrupts // Send VBlank interrupts
srv.sendGPUInterrupt(GPUInterrupt::VBlank0); srv.sendGPUInterrupt(GPUInterrupt::VBlank0);
srv.sendGPUInterrupt(GPUInterrupt::VBlank1); srv.sendGPUInterrupt(GPUInterrupt::VBlank1);
SDL_Event event; SDL_Event event;
while (SDL_PollEvent(&event)) { while (SDL_PollEvent(&event)) {
namespace Keys = HID::Keys; namespace Keys = HID::Keys;
switch (event.type) { switch (event.type) {
case SDL_QUIT: case SDL_QUIT:
printf("Bye :(\n"); printf("Bye :(\n");
running = false; running = false;
return; return;
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_l: srv.pressKey(Keys::A); break;
case SDLK_k: srv.pressKey(Keys::B); break;
case SDLK_o: srv.pressKey(Keys::X); break;
case SDLK_i: srv.pressKey(Keys::Y); break;
case SDLK_q: srv.pressKey(Keys::L); break; case SDL_KEYDOWN:
case SDLK_p: srv.pressKey(Keys::R); break; switch (event.key.keysym.sym) {
case SDLK_l: srv.pressKey(Keys::A); break;
case SDLK_k: srv.pressKey(Keys::B); break;
case SDLK_o: srv.pressKey(Keys::X); break;
case SDLK_i: srv.pressKey(Keys::Y); break;
case SDLK_RIGHT: srv.pressKey(Keys::Right); break; case SDLK_q: srv.pressKey(Keys::L); break;
case SDLK_LEFT: srv.pressKey(Keys::Left); break; case SDLK_p: srv.pressKey(Keys::R); break;
case SDLK_UP: srv.pressKey(Keys::Up); break;
case SDLK_DOWN: srv.pressKey(Keys::Down); break;
case SDLK_w: srv.setCirclepadY(0x9C); break; case SDLK_RIGHT: srv.pressKey(Keys::Right); break;
case SDLK_a: srv.setCirclepadX(-0x9C); break; case SDLK_LEFT: srv.pressKey(Keys::Left); break;
case SDLK_s: srv.setCirclepadY(-0x9C); break; case SDLK_UP: srv.pressKey(Keys::Up); break;
case SDLK_d: srv.setCirclepadX(0x9C); break; case SDLK_DOWN: srv.pressKey(Keys::Down); break;
case SDLK_RETURN: srv.pressKey(Keys::Start); break; case SDLK_w:
case SDLK_BACKSPACE: srv.pressKey(Keys::Select); break; srv.setCirclepadY(0x9C);
} keyboardAnalogY = true;
break; break;
case SDL_KEYUP:
switch (event.key.keysym.sym) {
case SDLK_l: srv.releaseKey(Keys::A); break;
case SDLK_k: srv.releaseKey(Keys::B); break;
case SDLK_o: srv.releaseKey(Keys::X); break;
case SDLK_i: srv.releaseKey(Keys::Y); break;
case SDLK_q: srv.releaseKey(Keys::L); break; case SDLK_a:
case SDLK_p: srv.releaseKey(Keys::R); break; srv.setCirclepadX(-0x9C);
keyboardAnalogX = true;
break;
case SDLK_RIGHT: srv.releaseKey(Keys::Right); break; case SDLK_s:
case SDLK_LEFT: srv.releaseKey(Keys::Left); break; srv.setCirclepadY(-0x9C);
case SDLK_UP: srv.releaseKey(Keys::Up); break; keyboardAnalogY = true;
case SDLK_DOWN: srv.releaseKey(Keys::Down); break; break;
// Err this is probably not ideal case SDLK_d:
case SDLK_w: srv.setCirclepadY(0); break; srv.setCirclepadX(0x9C);
case SDLK_a: srv.setCirclepadX(0); break; keyboardAnalogX = true;
case SDLK_s: srv.setCirclepadY(0); break; break;
case SDLK_d: srv.setCirclepadX(0); break;
case SDLK_RETURN: srv.releaseKey(Keys::Start); break; case SDLK_RETURN: srv.pressKey(Keys::Start); break;
case SDLK_BACKSPACE: srv.releaseKey(Keys::Select); break; case SDLK_BACKSPACE: srv.pressKey(Keys::Select); break;
} }
break; break;
case SDL_MOUSEBUTTONDOWN: { case SDL_KEYUP:
if (event.button.button == SDL_BUTTON_LEFT) { switch (event.key.keysym.sym) {
const s32 x = event.button.x; case SDLK_l: srv.releaseKey(Keys::A); break;
const s32 y = event.button.y; case SDLK_k: srv.releaseKey(Keys::B); break;
case SDLK_o: srv.releaseKey(Keys::X); break;
case SDLK_i: srv.releaseKey(Keys::Y); break;
// Check if touch falls in the touch screen area case SDLK_q: srv.releaseKey(Keys::L); break;
if (y >= 240 && y <= 480 && x >= 40 && x < 40 + 320) { case SDLK_p: srv.releaseKey(Keys::R); break;
// Convert to 3DS coordinates
u16 x_converted = static_cast<u16>(x) - 40;
u16 y_converted = static_cast<u16>(y) - 240;
srv.setTouchScreenPress(x_converted, y_converted); case SDLK_RIGHT: srv.releaseKey(Keys::Right); break;
} case SDLK_LEFT: srv.releaseKey(Keys::Left); break;
else { case SDLK_UP: srv.releaseKey(Keys::Up); break;
srv.releaseTouchScreen(); case SDLK_DOWN: srv.releaseKey(Keys::Down); break;
}
}
break;
}
case SDL_MOUSEBUTTONUP: // Err this is probably not ideal
if (event.button.button == SDL_BUTTON_LEFT) { case SDLK_w:
srv.releaseTouchScreen(); case SDLK_s:
} srv.setCirclepadY(0);
break; keyboardAnalogY = false;
} break;
}
// Update inputs in the HID module case SDLK_a:
srv.updateInputs(cpu.getTicks()); case SDLK_d:
SDL_GL_SwapWindow(window); srv.setCirclepadX(0);
} keyboardAnalogX = false;
break;
case SDLK_RETURN: srv.releaseKey(Keys::Start); break;
case SDLK_BACKSPACE: srv.releaseKey(Keys::Select); break;
}
break;
case SDL_MOUSEBUTTONDOWN: {
if (event.button.button == SDL_BUTTON_LEFT) {
const s32 x = event.button.x;
const s32 y = event.button.y;
// Check if touch falls in the touch screen area
if (y >= 240 && y <= 480 && x >= 40 && x < 40 + 320) {
// Convert to 3DS coordinates
u16 x_converted = static_cast<u16>(x) - 40;
u16 y_converted = static_cast<u16>(y) - 240;
srv.setTouchScreenPress(x_converted, y_converted);
} else {
srv.releaseTouchScreen();
}
}
break;
}
case SDL_MOUSEBUTTONUP:
if (event.button.button == SDL_BUTTON_LEFT) {
srv.releaseTouchScreen();
}
break;
case SDL_CONTROLLERDEVICEADDED:
if (gameController == nullptr) {
gameController = SDL_GameControllerOpen(event.cdevice.which);
gameControllerID = event.cdevice.which;
}
break;
case SDL_CONTROLLERDEVICEREMOVED:
if (event.cdevice.which == gameControllerID) {
SDL_GameControllerClose(gameController);
gameController = nullptr;
gameControllerID = 0;
}
break;
case SDL_CONTROLLERBUTTONUP:
case SDL_CONTROLLERBUTTONDOWN: {
u32 key = 0;
switch (event.cbutton.button) {
case SDL_CONTROLLER_BUTTON_A: key = Keys::B; break;
case SDL_CONTROLLER_BUTTON_B: key = Keys::A; break;
case SDL_CONTROLLER_BUTTON_X: key = Keys::Y; break;
case SDL_CONTROLLER_BUTTON_Y: key = Keys::X; break;
case SDL_CONTROLLER_BUTTON_LEFTSHOULDER: key = Keys::L; break;
case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: key = Keys::R; break;
case SDL_CONTROLLER_BUTTON_DPAD_LEFT: key = Keys::Left; break;
case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: key = Keys::Right; break;
case SDL_CONTROLLER_BUTTON_DPAD_UP: key = Keys::Up; break;
case SDL_CONTROLLER_BUTTON_DPAD_DOWN: key = Keys::Down; break;
case SDL_CONTROLLER_BUTTON_BACK: key = Keys::Select; break;
case SDL_CONTROLLER_BUTTON_START: key = Keys::Start; break;
}
if (key != 0) {
if (event.cbutton.state == SDL_PRESSED) {
srv.pressKey(key);
} else {
srv.releaseKey(key);
}
}
}
}
}
if (gameController != nullptr) {
const s16 stickX = SDL_GameControllerGetAxis(gameController, SDL_CONTROLLER_AXIS_LEFTX);
const s16 stickY = SDL_GameControllerGetAxis(gameController, SDL_CONTROLLER_AXIS_LEFTY);
constexpr s16 deadzone = 3276;
constexpr s16 maxValue = 0x9C;
constexpr s16 div = 0x8000 / maxValue;
// Avoid overriding the keyboard's circlepad input
if (abs(stickX) < deadzone && !keyboardAnalogX) {
srv.setCirclepadX(0);
} else {
srv.setCirclepadX(stickX / div);
}
if (abs(stickY) < deadzone && !keyboardAnalogY) {
srv.setCirclepadY(0);
} else {
srv.setCirclepadY(-(stickY / div));
}
}
// Update inputs in the HID module
srv.updateInputs(cpu.getTicks());
SDL_GL_SwapWindow(window);
}
} }
void Emulator::runFrame() { void Emulator::runFrame() { cpu.runFrame(); }
cpu.runFrame();
}
bool Emulator::loadROM(const std::filesystem::path& path) { bool Emulator::loadROM(const std::filesystem::path& path) {
// Get path for saving files (AppData on Windows, /home/user/.local/share/ApplcationName on Linux, etc) // Get path for saving files (AppData on Windows, /home/user/.local/share/ApplcationName on Linux, etc)
// Inside that path, we be use a game-specific folder as well. Eg if we were loading a ROM called PenguinDemo.3ds, the savedata would be in // Inside that path, we be use a game-specific folder as well. Eg if we were loading a ROM called PenguinDemo.3ds, the savedata would be in
// %APPDATA%/Alber/PenguinDemo/SaveData on Windows, and so on. We do this because games save data in their own filesystem on the cart // %APPDATA%/Alber/PenguinDemo/SaveData on Windows, and so on. We do this because games save data in their own filesystem on the cart
char* appData = SDL_GetPrefPath(nullptr, "Alber"); char* appData = SDL_GetPrefPath(nullptr, "Alber");
const std::filesystem::path appDataPath = std::filesystem::path(appData); const std::filesystem::path appDataPath = std::filesystem::path(appData);
const std::filesystem::path dataPath = appDataPath / path.filename().stem(); const std::filesystem::path dataPath = appDataPath / path.filename().stem();
const std::filesystem::path aesKeysPath = appDataPath / "sysdata" / "aes_keys.txt"; const std::filesystem::path aesKeysPath = appDataPath / "sysdata" / "aes_keys.txt";
IOFile::setAppDataDir(dataPath); IOFile::setAppDataDir(dataPath);
SDL_free(appData); SDL_free(appData);
// Open the text file containing our AES keys if it exists. We use the std::filesystem::exists overload that takes an error code param to // Open the text file containing our AES keys if it exists. We use the std::filesystem::exists overload that takes an error code param to
// avoid the call throwing exceptions // avoid the call throwing exceptions
std::error_code ec; std::error_code ec;
if (std::filesystem::exists(aesKeysPath, ec) && !ec) { if (std::filesystem::exists(aesKeysPath, ec) && !ec) {
aesEngine.loadKeys(aesKeysPath); aesEngine.loadKeys(aesKeysPath);
} }
kernel.initializeFS(); kernel.initializeFS();
auto extension = path.extension(); auto extension = path.extension();
if (extension == ".elf" || extension == ".axf") if (extension == ".elf" || extension == ".axf")
return loadELF(path); return loadELF(path);
else if (extension == ".3ds") else if (extension == ".3ds")
return loadNCSD(path); return loadNCSD(path);
else { else {
printf("Unknown file type\n"); printf("Unknown file type\n");
return false; return false;
} }
} }
bool Emulator::loadNCSD(const std::filesystem::path& path) { bool Emulator::loadNCSD(const std::filesystem::path& path) {
romType = ROMType::NCSD; romType = ROMType::NCSD;
std::optional<NCSD> opt = memory.loadNCSD(aesEngine, path); std::optional<NCSD> opt = memory.loadNCSD(aesEngine, path);
if (!opt.has_value()) { if (!opt.has_value()) {
return false; return false;
} }
loadedNCSD = opt.value(); loadedNCSD = opt.value();
cpu.setReg(15, loadedNCSD.entrypoint); cpu.setReg(15, loadedNCSD.entrypoint);
if (loadedNCSD.entrypoint & 1) { if (loadedNCSD.entrypoint & 1) {
Helpers::panic("Misaligned NCSD entrypoint; should this start the CPU in Thumb mode?"); Helpers::panic("Misaligned NCSD entrypoint; should this start the CPU in Thumb mode?");
} }
return true; return true;
} }
bool Emulator::loadELF(const std::filesystem::path& path) { bool Emulator::loadELF(const std::filesystem::path& path) {
loadedELF.open(path, std::ios_base::binary); // Open ROM in binary mode loadedELF.open(path, std::ios_base::binary); // Open ROM in binary mode
romType = ROMType::ELF; romType = ROMType::ELF;
return loadELF(loadedELF); return loadELF(loadedELF);
} }
bool Emulator::loadELF(std::ifstream& file) { bool Emulator::loadELF(std::ifstream& file) {
// Rewind ifstream // Rewind ifstream
loadedELF.clear(); loadedELF.clear();
loadedELF.seekg(0); loadedELF.seekg(0);
std::optional<u32> entrypoint = memory.loadELF(loadedELF); std::optional<u32> entrypoint = memory.loadELF(loadedELF);
if (!entrypoint.has_value()) if (!entrypoint.has_value()) {
return false; return false;
}
cpu.setReg(15, entrypoint.value()); // Set initial PC cpu.setReg(15, entrypoint.value()); // Set initial PC
if (entrypoint.value() & 1) { if (entrypoint.value() & 1) {
Helpers::panic("Misaligned ELF entrypoint. TODO: Check if ELFs can boot in thumb mode"); Helpers::panic("Misaligned ELF entrypoint. TODO: Check if ELFs can boot in thumb mode");
} }
return true; return true;
} }