PS2 games in the browser: static recompilation to WebAssembly with a native runtime
C++
Native window: emulation, VU1 and GS on their own threads
Samir Nuric3d3f646349f
diff --git a/README.md b/README.mdindex 277dabe..fc5fd9c 100644--- a/README.md+++ b/README.md@@ -71,6 +71,16 @@ The page needs WebGPU for the GPU renderer. Chrome and Edge have it on Windows aThe keyboard maps the face buttons to Z (cross), X (circle), A (square) and S (triangle), the shoulders to Q, W, 1 and 2, start and select to Enter and Backspace, the D-pad to the arrow keys and the left stick to I, J, K and L. Gamepads work through the browser's gamepad API, phones get on-screen controls, and F toggles fullscreen. The resolution selector reloads the page at the new size.+## Playing natively++The runner `port.sh` builds for its exploring runs, `build/native-mygame/ps2run`, also plays the game in a window when SDL2 is installed. It draws through wgpu-native on Vulkan and plays sound through SDL. The keyboard uses the page's keys for the buttons, with the arrow keys as both the D-pad and the left stick, and any game controller SDL recognizes works too, the Steam Deck's own controls included.++```bash+build/native-mygame/ps2run games/mygame/disc/SLUS_123.45 --disc games/mygame/disc.iso --window --memcard mygame.ps2+```++`--fullscreen` starts in fullscreen and F11 switches back and forth. `PS2_SCALE=2` or `3` raises the internal resolution. As in the browser, the emulation, vector unit 1 and the GS each run on their own thread, which takes God of War II from 43 to 60 frames per second at the native resolution on the test laptop; `PS2_ONE_THREAD=1` puts everything back on one thread. The memory card file uses the same layout as the page's exported cards. On a Steam Deck the runner can be added to Steam as a non-Steam game, though nobody has tried it on one yet.+## SavesThe page puts a memory card in slot 1 and keeps it in the browser's storage for the address you play from, so progress survives a reload. Games format and use it as they would a real card. **Export card** downloads it as a `.ps2` file in the layout PCSX2 uses, and **Import card** puts such a file back in the slot, so a card can travel between browsers or come from PCSX2. `?nocard` starts with the slot empty.diff --git a/host/main.cpp b/host/main.cppindex ba8c8cf..4962c70 100644--- a/host/main.cpp+++ b/host/main.cpp@@ -23,7 +23,7 @@ int usage() {"usage: ps2run <elf> [--arg text]... [--frames n] [--ntsc] [--misses file]\n"" [--disc image.iso] [--memcard card.ps2] [--pal | --ntsc] [--trace-syscalls] [--trace-io] [--trace-threads]\n"" [--trace-iop] [--trace-iop-hle] [--frames-dir dir] [--frame-every n]\n"- " [--press frame:button[+button][:frames]]... [--window]\n"+ " [--press frame:button[+button][:frames]]... [--window] [--fullscreen]\n"" [--save-state frame:file] [--load-state file]\n");return 2;}@@ -33,7 +33,7 @@ int usage() {int main(int argc, char **argv) {if (argc < 2) return usage();std::vector<std::string> args{argv[1]};- [[maybe_unused]] bool window = false;+ [[maybe_unused]] bool window = false, fullscreen = false;std::string load_path;for (int i = 2; i < argc; ++i) {const std::string a = argv[i];@@ -59,6 +59,7 @@ int main(int argc, char **argv) {}#ifdef PS2_WINDOWelse if (a == "--window") window = true;+ else if (a == "--fullscreen") window = fullscreen = true;#endifelse if (a == "--frame-every" && i + 1 < argc) ps2::g_options.frame_every = static_cast<std::uint32_t>(std::strtoul(argv[++i], nullptr, 10));else if (a == "--save-state" && i + 1 < argc) {@@ -73,25 +74,31 @@ int main(int argc, char **argv) {}#ifdef PS2_WINDOW- if (window && !open_window()) return 1;+ if (window && !open_window(fullscreen)) return 1;#endifregister_generated_code();register_generated_vu();- std::uint32_t entry = 0;- if (!ps2::load_elf(argv[1], entry)) {- std::fprintf(stderr, "cannot load %s\n", argv[1]);- return 1;- }- ps2::boot(entry, args);- if (!load_path.empty() && !ps2::load_state(load_path)) return 1;+ const auto emulate = [&]() -> int {+ std::uint32_t entry = 0;+ if (!ps2::load_elf(argv[1], entry)) {+ std::fprintf(stderr, "cannot load %s\n", argv[1]);+ return 1;+ }+ ps2::boot(entry, args);+ if (!load_path.empty() && !ps2::load_state(load_path)) return 1;#ifdef PS2_PROFILE- const char *profile = std::getenv("PS2_PROFILE");- const char *profile_from = std::getenv("PS2_PROFILE_FROM");- if (profile) start_profile(profile_from ? std::strtoull(profile_from, nullptr, 10) : 0);- const int result = ps2::run();- if (profile) write_profile(profile);- return result;+ const char *profile = std::getenv("PS2_PROFILE");+ const char *profile_from = std::getenv("PS2_PROFILE_FROM");+ if (profile) start_profile(profile_from ? std::strtoull(profile_from, nullptr, 10) : 0);+ const int result = ps2::run();+ if (profile) write_profile(profile);+ return result;#else- return ps2::run();+ return ps2::run();+#endif+ };+#ifdef PS2_WINDOW+ if (window) return run_window(emulate);#endif+ return emulate();}diff --git a/host/window.cpp b/host/window.cppindex 253cb3a..f52692e 100644--- a/host/window.cpp+++ b/host/window.cpp@@ -8,8 +8,10 @@#include <unistd.h>#include <algorithm>+#include <atomic>#include <cstdio>#include <cstdlib>+#include <thread>#include <vector>namespace {@@ -57,7 +59,7 @@ SDL_GameController *g_pad = nullptr;std::uint32_t g_tex_w = 0, g_tex_h = 0;std::uint64_t g_last = 0;std::vector<std::uint32_t> g_pixels;-bool g_gpu_tried = false, g_gpu_present = false;+bool g_gpu_present = false;bool create_renderer() {g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED);@@ -108,6 +110,11 @@ void poll() {SDL_Event e;while (SDL_PollEvent(&e)) {if (e.type == SDL_QUIT) ps2::halt("window closed");+ if (e.type == SDL_KEYDOWN && e.key.keysym.scancode == SDL_SCANCODE_F11 && !e.key.repeat) {+ const bool full = SDL_GetWindowFlags(g_window) & SDL_WINDOW_FULLSCREEN;+ SDL_SetWindowFullscreen(g_window, full ? 0 : SDL_WINDOW_FULLSCREEN_DESKTOP);+ SDL_ShowCursor(full ? SDL_ENABLE : SDL_DISABLE);+ }if (e.type == SDL_WINDOWEVENT && e.window.event == SDL_WINDOWEVENT_SIZE_CHANGED && g_gpu_present) {int w = 0, h = 0;SDL_GetWindowSizeInPixels(g_window, &w, &h);@@ -150,20 +157,7 @@ void poll() {ps2::set_pad_axis(3, ly);}-void present() {- if (!g_gpu_tried) {- g_gpu_tried = true;- g_gpu_present = attach_gpu();- std::fprintf(stderr, "[window] %s\n", g_gpu_present ? "presenting through WebGPU" : "presenting through SDL");- if (!g_gpu_present && !create_renderer()) ps2::halt("no renderer");- }- if (g_gpu_present) {- ps2::present_frame();- return;- }- if (!g_renderer) return;- std::uint32_t w = 0, h = 0;- if (!ps2::display_frame(g_pixels, w, h)) return;+void show_pixels(const std::uint32_t *rgba, std::uint32_t w, std::uint32_t h) {if (w != g_tex_w || h != g_tex_h) {if (g_texture) SDL_DestroyTexture(g_texture);g_texture = SDL_CreateTexture(g_renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, static_cast<int>(w), static_cast<int>(h));@@ -171,12 +165,21 @@ void present() {g_tex_w = w;g_tex_h = h;}- SDL_UpdateTexture(g_texture, nullptr, g_pixels.data(), static_cast<int>(w * 4));+ SDL_UpdateTexture(g_texture, nullptr, rgba, static_cast<int>(w * 4));SDL_RenderClear(g_renderer);SDL_RenderCopy(g_renderer, g_texture, nullptr, nullptr);SDL_RenderPresent(g_renderer);}+void present() {+ if (g_gpu_present) {+ ps2::present_frame();+ return;+ }+ std::uint32_t w = 0, h = 0;+ if (ps2::display_frame(g_pixels, w, h)) show_pixels(g_pixels.data(), w, h);+}+constexpr Uint32 kAudioBytesPerMs = 48 * 4;void pace() {@@ -249,12 +252,13 @@ void queue_audio(const std::int16_t *samples, std::size_t frames) {}-bool open_window() {+bool open_window(bool fullscreen) {if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER) != 0) {std::fprintf(stderr, "SDL: %s\n", SDL_GetError());return false;}- g_window = SDL_CreateWindow("ps2-web-recomp", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 960, 720, SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);+ const Uint32 flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI | (fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0u);+ g_window = SDL_CreateWindow("ps2-web-recomp", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 960, 720, flags);if (!g_window) {std::fprintf(stderr, "SDL: %s\n", SDL_GetError());return false;@@ -272,6 +276,43 @@ bool open_window() {}for (int i = 0; i < SDL_NumJoysticks() && !g_pad; ++i)if (SDL_IsGameController(i)) g_pad = SDL_GameControllerOpen(i);- ps2::g_options.on_vblank = on_vblank;+ if (fullscreen) SDL_ShowCursor(SDL_DISABLE);return true;}++int run_window(const std::function<int()> &emulate) {+ ps2::init_graphics();+ g_gpu_present = attach_gpu();+ std::fprintf(stderr, "[window] %s\n", g_gpu_present ? "presenting through WebGPU" : "presenting through SDL");+ if (!g_gpu_present && !create_renderer()) return 1;+ const bool threads = !std::getenv("PS2_ONE_THREAD") && !std::getenv("PS2_TIME") && ps2::g_options.frames_dir.empty();+ if (!threads) {+ ps2::g_options.on_vblank = on_vblank;+ return emulate();+ }+ ps2::g_options.on_vblank = [] {+ ps2::post_present();+ pace();+ };+ ps2::start_render_thread();+ if (!std::getenv("PS2_NO_VU_THREAD")) {+ ps2::start_vu_thread();+ std::thread(ps2::run_vu_thread).detach();+ }+ std::atomic<bool> done{false};+ int result = 0;+ std::thread emulation([&] {+ result = emulate();+ done.store(true);+ ps2::wake_render_thread();+ });+ const std::function<void(const std::uint32_t *, std::uint32_t, std::uint32_t)> copy = show_pixels, none;+ while (!done.load()) {+ poll();+ if (ps2::render_pending(g_gpu_present, g_gpu_present ? none : copy, show_speed, 8.0) == ps2::Rendered::idle) ps2::wait_render_work(4);+ }+ emulation.join();+ SDL_Quit();+ std::fflush(nullptr);+ std::_Exit(result);+}diff --git a/host/window.hpp b/host/window.hppindex 414afc7..3174ae9 100644--- a/host/window.hpp+++ b/host/window.hpp@@ -1,3 +1,6 @@#pragma once-bool open_window();+#include <functional>++bool open_window(bool fullscreen);+int run_window(const std::function<int()> &emulate);diff --git a/runtime/src/gs/queue.cpp b/runtime/src/gs/queue.cppindex 61715e9..316ff9c 100644--- a/runtime/src/gs/queue.cpp+++ b/runtime/src/gs/queue.cpp@@ -8,6 +8,11 @@#ifdef __EMSCRIPTEN__#include <emscripten.h>#include <emscripten/threading.h>+#elif defined(__linux__)+#include <ctime>+#include <linux/futex.h>+#include <sys/syscall.h>+#include <unistd.h>#else#include <chrono>#include <thread>@@ -22,6 +27,15 @@ constexpr std::uint64_t align16(std::uint64_t n) { return (n + 15) & ~15ull; }Ring g_render, g_vu;thread_local Role g_role = Role::Emulation;+#if defined(__linux__) && !defined(__EMSCRIPTEN__)+void futex_wait(std::atomic<std::uint32_t> &word, std::uint32_t seen, int timeout_ms) {+ timespec limit{timeout_ms / 1000, static_cast<long>(timeout_ms % 1000) * 1000000L};+ syscall(SYS_futex, reinterpret_cast<std::uint32_t *>(&word), FUTEX_WAIT_PRIVATE, seen, timeout_ms < 0 ? nullptr : &limit, nullptr, 0);+}++void futex_wake(std::atomic<std::uint32_t> &word) { syscall(SYS_futex, reinterpret_cast<std::uint32_t *>(&word), FUTEX_WAKE_PRIVATE, INT_MAX, nullptr, nullptr, 0); }+#endif+}#ifdef __EMSCRIPTEN__@@ -34,6 +48,8 @@ EM_ASYNC_JS(void, ps2_wait_async, (std::atomic<std::uint32_t> *word, std::uint32void wait(std::atomic<std::uint32_t> &value, std::uint32_t seen) {#ifdef __EMSCRIPTEN__emscripten_futex_wait(&value, seen, INFINITY);+#elif defined(__linux__)+ futex_wait(value, seen, -1);#elsevalue.wait(seen);#endif@@ -42,6 +58,8 @@ void wait(std::atomic<std::uint32_t> &value, std::uint32_t seen) {void notify(std::atomic<std::uint32_t> &value) {#ifdef __EMSCRIPTEN__emscripten_futex_wake(&value, INT_MAX);+#elif defined(__linux__)+ futex_wake(value);#elsevalue.notify_all();#endif@@ -130,6 +148,8 @@ void Ring::wait_for_work(int timeout_ms) {#ifdef __EMSCRIPTEN__if (emscripten_is_main_browser_thread()) ps2_wait_async(&posted_, seen, timeout_ms);else emscripten_futex_wait(&posted_, seen, timeout_ms);+#elif defined(__linux__)+ futex_wait(posted_, seen, timeout_ms);#else(void)seen;std::this_thread::sleep_for(std::chrono::milliseconds(std::min(timeout_ms, 1)));diff --git a/scripts/port.sh b/scripts/port.shindex 788ba5c..08f48f5 100755--- a/scripts/port.sh+++ b/scripts/port.sh@@ -143,9 +143,15 @@ if compgen -G "$game/vu1/*.bin" > /dev/null; thenelseecho "none recorded, the page compiles them on the fly"fi+if [ -f "$native/build.ninja" ]; then+ ninja -C "$native" ps2run > "$native/ninja.log" 2>&1 || { tail -30 "$native/ninja.log"; exit 1; }+fiecho "== [6/6] web build""$here/build_web.sh" "$name" "$EMSDK"echoecho "Done. Serve it with: python3 scripts/serve.py build/web-$name games/$name/disc.iso"echo "and open http://localhost:8620/"+if [ -x "$native/ps2run" ]; then+ echo "or play it natively: build/native-$name/ps2run ${elf#$ROOT/} --disc games/$name/disc.iso --window"+fi