diff --git a/.gitmodules b/.gitmodules index f8c67366..a2cac3f2 100644 --- a/.gitmodules +++ b/.gitmodules @@ -19,3 +19,9 @@ [submodule "third_party/toml11"] path = third_party/toml11 url = https://github.com/ToruNiina/toml11 +[submodule "cpp-httplib"] + path = third_party/httplib + url = https://github.com/yhirose/cpp-httplib +[submodule "stb"] + path = third_party/stb + url = https://github.com/nothings/stb diff --git a/CMakeLists.txt b/CMakeLists.txt index bea18041..4f844a61 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -34,8 +34,11 @@ include_directories(third_party/cryptopp/) include_directories(third_party/cityhash/include) include_directories(third_party/result/include) include_directories(third_party/xxhash/include) +include_directories(third_party/httplib) +include_directories(third_party/stb) -add_compile_definitions(NOMINMAX) +add_compile_definitions(NOMINMAX) # Make windows.h not define min/max macros because third-party deps don't like it +add_compile_definitions(WIN32_LEAN_AND_MEAN) # Make windows.h not include literally everything add_compile_definitions(SDL_MAIN_HANDLED) set(SDL_STATIC ON CACHE BOOL "" FORCE) @@ -88,6 +91,7 @@ endif() set(SOURCE_FILES src/main.cpp src/emulator.cpp src/io_file.cpp src/gl_state.cpp src/config.cpp src/core/CPU/cpu_dynarmic.cpp src/core/CPU/dynarmic_cycles.cpp src/core/memory.cpp + src/httpserver.cpp ) set(CRYPTO_SOURCE_FILES src/core/crypto/aes_engine.cpp) set(KERNEL_SOURCE_FILES src/core/kernel/kernel.cpp src/core/kernel/resource_limits.cpp @@ -143,7 +147,7 @@ set(HEADER_FILES include/emulator.hpp include/helpers.hpp include/opengl.hpp inc include/result/result_common.hpp include/result/result_fs.hpp include/result/result_fnd.hpp include/result/result_gsp.hpp include/result/result_kernel.hpp include/result/result_os.hpp include/crypto/aes_engine.hpp include/metaprogramming.hpp include/PICA/pica_vertex.hpp include/gl_state.hpp - include/config.hpp include/services/ir_user.hpp + include/config.hpp include/services/ir_user.hpp include/httpserver.hpp ) set(THIRD_PARTY_SOURCE_FILES third_party/imgui/imgui.cpp diff --git a/include/PICA/gpu.hpp b/include/PICA/gpu.hpp index 5f74bdcc..2de48c01 100644 --- a/include/PICA/gpu.hpp +++ b/include/PICA/gpu.hpp @@ -88,6 +88,7 @@ class GPU { void initGraphicsContext() { renderer.initGraphicsContext(); } void getGraphicsContext() { renderer.getGraphicsContext(); } void display() { renderer.display(); } + void screenshot(const std::string& name) { renderer.screenshot(name); } void fireDMA(u32 dest, u32 source, u32 size); void reset(); diff --git a/include/emulator.hpp b/include/emulator.hpp index e1684085..3985c613 100644 --- a/include/emulator.hpp +++ b/include/emulator.hpp @@ -14,6 +14,9 @@ #include "io_file.hpp" #include "memory.hpp" #include "gl_state.hpp" +#ifdef PANDA3DS_ENABLE_HTTP_SERVER +#include "httpserver.hpp" +#endif enum class ROMType { None, ELF, NCSD, CXI }; @@ -46,6 +49,10 @@ class Emulator { ROMType romType = ROMType::None; bool running = true; +#ifdef PANDA3DS_ENABLE_HTTP_SERVER + HttpServer httpServer; +#endif + // Keep the handle for the ROM here to reload when necessary and to prevent deleting it // This is currently only used for ELFs, NCSDs use the IOFile API instead std::ifstream loadedELF; @@ -68,4 +75,8 @@ class Emulator { bool loadELF(const std::filesystem::path& path); bool loadELF(std::ifstream& file); void initGraphicsContext(); + +#ifdef PANDA3DS_ENABLE_HTTP_SERVER + void pollHttpServer(); +#endif }; diff --git a/include/httpserver.hpp b/include/httpserver.hpp new file mode 100644 index 00000000..0526045a --- /dev/null +++ b/include/httpserver.hpp @@ -0,0 +1,22 @@ +#ifdef PANDA3DS_ENABLE_HTTP_SERVER +#pragma once + +#include +#include + +#include "helpers.hpp" + +enum class HttpAction { None, Screenshot, PressKey, ReleaseKey }; + +struct HttpServer { + static constexpr const char* httpServerScreenshotPath = "screenshot.png"; + + std::atomic_bool pendingAction = false; + HttpAction action = HttpAction::None; + std::mutex actionMutex = {}; + u32 pendingKey = 0; + + void startHttpServer(); +}; + +#endif // PANDA3DS_ENABLE_HTTP_SERVER \ No newline at end of file diff --git a/include/renderer_gl/renderer_gl.hpp b/include/renderer_gl/renderer_gl.hpp index 8258c4c7..07f8a63c 100644 --- a/include/renderer_gl/renderer_gl.hpp +++ b/include/renderer_gl/renderer_gl.hpp @@ -1,6 +1,7 @@ #pragma once #include #include +#include #include "PICA/float_types.hpp" #include "gl_state.hpp" @@ -88,6 +89,9 @@ class Renderer { void displayTransfer(u32 inputAddr, u32 outputAddr, u32 inputSize, u32 outputSize, u32 flags); // Perform display transfer void drawVertices(PICA::PrimType primType, std::span vertices); // Draw the given vertices + // Take a screenshot of the screen and store it in a file + void screenshot(const std::string& name); + void setFBSize(u32 width, u32 height) { fbSize.x() = width; fbSize.y() = height; diff --git a/src/core/renderer_gl/renderer_gl.cpp b/src/core/renderer_gl/renderer_gl.cpp index 72f346bc..73fb0919 100644 --- a/src/core/renderer_gl/renderer_gl.cpp +++ b/src/core/renderer_gl/renderer_gl.cpp @@ -669,7 +669,7 @@ void Renderer::initGraphicsContext() { dummyVAO.create(); // Create texture and framebuffer for the 3DS screen - const u32 screenTextureWidth = 2 * 400; // Top screen is 400 pixels wide, bottom is 320 + const u32 screenTextureWidth = 400; // Top screen is 400 pixels wide, bottom is 320 const u32 screenTextureHeight = 2 * 240; // Both screens are 240 pixels tall glGenTextures(1,&lightLUTTextureArray); @@ -1028,4 +1028,29 @@ void Renderer::displayTransfer(u32 inputAddr, u32 outputAddr, u32 inputSize, u32 } OpenGL::draw(OpenGL::TriangleStrip, 4); // Actually draw our 3DS screen +} + +void Renderer::screenshot(const std::string& name) { + constexpr uint width = 400; + constexpr uint height = 2 * 240; + + std::vector pixels, flippedPixels; + pixels.resize(width * height * 4); + flippedPixels.resize(pixels.size());; + + OpenGL::bindScreenFramebuffer(); + glReadPixels(0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, pixels.data()); + + // Flip the image vertically + for (int y = 0; y < height; y++) { + memcpy(&flippedPixels[y * width * 4], &pixels[(height - y - 1) * width * 4], width * 4); + // Swap R and B channels + for (int x = 0; x < width; x++) { + std::swap(flippedPixels[y * width * 4 + x * 4 + 0], flippedPixels[y * width * 4 + x * 4 + 2]); + // Set alpha to 0xFF + flippedPixels[y * width * 4 + x * 4 + 3] = 0xFF; + } + } + + stbi_write_png(name.c_str(), width, height, 4, flippedPixels.data(), 0); } \ No newline at end of file diff --git a/src/emulator.cpp b/src/emulator.cpp index 198c573d..1e30e073 100644 --- a/src/emulator.cpp +++ b/src/emulator.cpp @@ -1,4 +1,6 @@ #include "emulator.hpp" +#define STB_IMAGE_WRITE_IMPLEMENTATION +#include #ifdef _WIN32 #include @@ -67,7 +69,7 @@ void Emulator::reset() { // Reloading r13 and r15 needs to happen after everything has been reset // Otherwise resetting the kernel or cpu might nuke them cpu.setReg(13, VirtualAddrs::StackTop); // Set initial SP - + // If a ROM is active and we reset, reload it. This is necessary to set up stack, executable memory, .data/.rodata/.bss all over again if (romType != ROMType::None && romPath.has_value()) { bool success = loadROM(romPath.value()); @@ -84,9 +86,15 @@ void Emulator::step() {} void Emulator::render() {} void Emulator::run() { - while (running) { - runFrame(); // Run 1 frame of instructions - gpu.display(); // Display graphics +#ifdef PANDA3DS_ENABLE_HTTP_SERVER + httpServer.startHttpServer(); +#endif + while (running) { +#ifdef PANDA3DS_ENABLE_HTTP_SERVER + pollHttpServer(); +#endif + runFrame(); // Run 1 frame of instructions + gpu.display(); // Display graphics ServiceManager& srv = kernel.getServiceManager(); @@ -337,12 +345,12 @@ bool Emulator::loadROM(const std::filesystem::path& path) { romPath = std::nullopt; romType = ROMType::None; } - + return success; } // Used for loading both CXI and NCSD files since they are both so similar and use the same interface -// (We promote CXI files to NCSD internally for ease) +// (We promote CXI files to NCSD internally for ease) bool Emulator::loadNCSD(const std::filesystem::path& path, ROMType type) { romType = type; std::optional opt = (type == ROMType::NCSD) ? memory.loadNCSD(aesEngine, path) : memory.loadCXI(aesEngine, path); @@ -390,3 +398,39 @@ void Emulator::initGraphicsContext() { gl.reset(); // TODO (For when we have multiple backends): Only do this if we are using OpenGL gpu.initGraphicsContext(); } + +#ifdef PANDA3DS_ENABLE_HTTP_SERVER +void Emulator::pollHttpServer() { + std::scoped_lock lock(httpServer.actionMutex); + + ServiceManager& srv = kernel.getServiceManager(); + + if (httpServer.pendingAction) { + switch (httpServer.action) { + case HttpAction::Screenshot: + gpu.screenshot(HttpServer::httpServerScreenshotPath); + break; + + case HttpAction::PressKey: + if (httpServer.pendingKey != 0) { + srv.pressKey(httpServer.pendingKey); + httpServer.pendingKey = 0; + } + break; + + case HttpAction::ReleaseKey: + if (httpServer.pendingKey != 0) { + srv.releaseKey(httpServer.pendingKey); + httpServer.pendingKey = 0; + } + break; + + case HttpAction::None: break; + } + + httpServer.action = HttpAction::None; + httpServer.pendingAction = false; + httpServer.pendingAction.notify_all(); + } +} +#endif \ No newline at end of file diff --git a/src/httpserver.cpp b/src/httpserver.cpp new file mode 100644 index 00000000..fa7ad763 --- /dev/null +++ b/src/httpserver.cpp @@ -0,0 +1,103 @@ +#ifdef PANDA3DS_ENABLE_HTTP_SERVER +#include "httpserver.hpp" + +#include +#include +#include +#include +#include + +#include "httplib.h" +#include "services/hid.hpp" + +u32 stringToKey(const std::string& key_name) { + namespace Keys = HID::Keys; + static std::map keyMap = { + {"A", Keys::A}, + {"B", Keys::B}, + {"Select", Keys::Select}, + {"Start", Keys::Start}, + {"Right", Keys::Right}, + {"Left", Keys::Left}, + {"Up", Keys::Up}, + {"Down", Keys::Down}, + {"R", Keys::R}, + {"L", Keys::L}, + {"X", Keys::X}, + {"Y", Keys::Y}, + {"CirclePadRight", Keys::CirclePadRight}, + {"CirclePadLeft", Keys::CirclePadLeft}, + {"CirclePadUp", Keys::CirclePadUp}, + {"CirclePadDown", Keys::CirclePadDown}, + }; + + if (keyMap.find(key_name) != keyMap.end()) { + return keyMap[key_name]; + } + + return 0; +} + +void HttpServer::startHttpServer() { + std::thread http_thread([this]() { + httplib::Server server; + + server.Get("/ping", [](const httplib::Request&, httplib::Response& response) { response.set_content("pong", "text/plain"); }); + + server.Get("/screen", [this](const httplib::Request&, httplib::Response& response) { + { + std::scoped_lock lock(actionMutex); + pendingAction = true; + action = HttpAction::Screenshot; + } + // wait until the screenshot is ready + pendingAction.wait(true); + std::ifstream image(httpServerScreenshotPath, std::ios::binary); + std::vector buffer(std::istreambuf_iterator(image), {}); + response.set_content(buffer.data(), buffer.size(), "image/png"); + }); + + server.Get("/input", [this](const httplib::Request& request, httplib::Response& response) { + bool ok = false; + for (auto& [keyStr, value] : request.params) { + auto key = stringToKey(keyStr); + printf("Param: %s\n", keyStr.c_str()); + + if (key != 0) { + std::scoped_lock lock(actionMutex); + pendingAction = true; + pendingKey = key; + ok = true; + if (value == "1") { + action = HttpAction::PressKey; + } else if (value == "0") { + action = HttpAction::ReleaseKey; + } else { + // Should not happen but just in case + pendingAction = false; + ok = false; + } + // Not supporting multiple keys at once for now (ever?) + break; + } + } + + if (ok) { + response.set_content("ok", "text/plain"); + } + }); + + server.Get("/step", [this](const httplib::Request&, httplib::Response& response) { + // TODO: implement /step + response.set_content("ok", "text/plain"); + }); + + // TODO: ability to specify host and port + printf("Starting HTTP server on port 1234\n"); + server.listen("localhost", 1234); + }); + + http_thread.detach(); +} + +#endif // PANDA3DS_ENABLE_HTTP_SERVER \ No newline at end of file diff --git a/third_party/httplib b/third_party/httplib new file mode 160000 index 00000000..be07d2d7 --- /dev/null +++ b/third_party/httplib @@ -0,0 +1 @@ +Subproject commit be07d2d7a99c0a54b00526f30f175e93c3588f34 diff --git a/third_party/stb b/third_party/stb new file mode 160000 index 00000000..5736b15f --- /dev/null +++ b/third_party/stb @@ -0,0 +1 @@ +Subproject commit 5736b15f7ea0ffb08dd38af21067c314d6a3aae9