Skip to content

PS2 games in the browser: static recompilation to WebAssembly with a native runtime

C++

A window for the native runner

Samir Nurie64b32a9227b
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 1a34b3f..a6eb85a 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -53,4 +53,10 @@ if(PS2_GENERATED)
add_executable(ps2run host/main.cpp)
target_link_libraries(ps2run PRIVATE ps2game ps2runtime)
+ find_package(SDL2 QUIET)
+ if(SDL2_FOUND AND NOT EMSCRIPTEN)
+ target_sources(ps2run PRIVATE host/window.cpp)
+ target_compile_definitions(ps2run PRIVATE PS2_WINDOW)
+ target_link_libraries(ps2run PRIVATE SDL2::SDL2)
+ endif()
endif()
diff --git a/host/main.cpp b/host/main.cpp
index 615fc2e..dd884dd 100644
--- a/host/main.cpp
+++ b/host/main.cpp
@@ -1,5 +1,9 @@
#include "ps2/system.hpp"
+#ifdef PS2_WINDOW
+#include "window.hpp"
+#endif
+
#include <cstdio>
#include <cstdlib>
#include <cstring>
@@ -44,7 +48,7 @@ int usage() {
"usage: ps2run <elf> [--arg text]... [--frames n] [--ntsc] [--misses file]\n"
" [--disc image.iso] [--trace-syscalls] [--trace-io] [--trace-threads]\n"
" [--trace-iop] [--trace-iop-hle] [--frames-dir dir] [--frame-every n]\n"
- " [--press frame:button[+button][:frames]]...\n");
+ " [--press frame:button[+button][:frames]]... [--window]\n");
return 2;
}
@@ -53,6 +57,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;
for (int i = 2; i < argc; ++i) {
const std::string a = argv[i];
if (a == "--arg" && i + 1 < argc) args.push_back(argv[++i]);
@@ -71,10 +76,16 @@ int main(int argc, char **argv) {
if (!parse_press(argv[++i], press)) return usage();
ps2::g_options.presses.push_back(press);
}
+#ifdef PS2_WINDOW
+ else if (a == "--window") window = true;
+#endif
else if (a == "--frame-every" && i + 1 < argc) ps2::g_options.frame_every = static_cast<std::uint32_t>(std::strtoul(argv[++i], nullptr, 10));
else return usage();
}
+#ifdef PS2_WINDOW
+ if (window && !open_window()) return 1;
+#endif
register_generated_code();
std::uint32_t entry = 0;
if (!ps2::load_elf(argv[1], entry)) {
diff --git a/host/window.cpp b/host/window.cpp
new file mode 100644
index 0000000..75c287f
--- /dev/null
+++ b/host/window.cpp
@@ -0,0 +1,166 @@
+#include "window.hpp"
+
+#include "ps2/system.hpp"
+
+#include <SDL.h>
+
+#include <algorithm>
+#include <cstdio>
+#include <vector>
+
+namespace {
+
+enum Button : std::uint16_t {
+ kSelect = 1u << 0, kL3 = 1u << 1, kR3 = 1u << 2, kStart = 1u << 3,
+ kUp = 1u << 4, kRight = 1u << 5, kDown = 1u << 6, kLeft = 1u << 7,
+ kL2 = 1u << 8, kR2 = 1u << 9, kL1 = 1u << 10, kR1 = 1u << 11,
+ kTriangle = 1u << 12, kCircle = 1u << 13, kCross = 1u << 14, kSquare = 1u << 15,
+};
+
+struct KeyBinding {
+ SDL_Scancode key;
+ std::uint16_t button;
+};
+
+constexpr KeyBinding kKeys[] = {
+ {SDL_SCANCODE_UP, kUp}, {SDL_SCANCODE_DOWN, kDown}, {SDL_SCANCODE_LEFT, kLeft},
+ {SDL_SCANCODE_RIGHT, kRight}, {SDL_SCANCODE_Z, kCross}, {SDL_SCANCODE_X, kCircle},
+ {SDL_SCANCODE_A, kSquare}, {SDL_SCANCODE_S, kTriangle}, {SDL_SCANCODE_Q, kL1},
+ {SDL_SCANCODE_W, kR1}, {SDL_SCANCODE_1, kL2}, {SDL_SCANCODE_2, kR2},
+ {SDL_SCANCODE_RETURN, kStart}, {SDL_SCANCODE_BACKSPACE, kSelect},
+};
+
+struct PadBinding {
+ SDL_GameControllerButton button;
+ std::uint16_t mask;
+};
+
+constexpr PadBinding kPadButtons[] = {
+ {SDL_CONTROLLER_BUTTON_A, kCross}, {SDL_CONTROLLER_BUTTON_B, kCircle},
+ {SDL_CONTROLLER_BUTTON_X, kSquare}, {SDL_CONTROLLER_BUTTON_Y, kTriangle},
+ {SDL_CONTROLLER_BUTTON_LEFTSHOULDER, kL1}, {SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, kR1},
+ {SDL_CONTROLLER_BUTTON_LEFTSTICK, kL3}, {SDL_CONTROLLER_BUTTON_RIGHTSTICK, kR3},
+ {SDL_CONTROLLER_BUTTON_BACK, kSelect}, {SDL_CONTROLLER_BUTTON_START, kStart},
+ {SDL_CONTROLLER_BUTTON_DPAD_UP, kUp}, {SDL_CONTROLLER_BUTTON_DPAD_DOWN, kDown},
+ {SDL_CONTROLLER_BUTTON_DPAD_LEFT, kLeft}, {SDL_CONTROLLER_BUTTON_DPAD_RIGHT, kRight},
+};
+
+SDL_Window *g_window = nullptr;
+SDL_Renderer *g_renderer = nullptr;
+SDL_Texture *g_texture = nullptr;
+SDL_AudioDeviceID g_audio = 0;
+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;
+
+std::uint8_t axis(SDL_GameControllerAxis a) {
+ const int v = SDL_GameControllerGetAxis(g_pad, a);
+ return static_cast<std::uint8_t>(std::clamp((v + 32768) >> 8, 0, 255));
+}
+
+void poll() {
+ SDL_Event e;
+ while (SDL_PollEvent(&e)) {
+ if (e.type == SDL_QUIT) ps2::halt("window closed");
+ if (e.type == SDL_CONTROLLERDEVICEADDED && !g_pad) g_pad = SDL_GameControllerOpen(e.cdevice.which);
+ if (e.type == SDL_CONTROLLERDEVICEREMOVED && g_pad && e.cdevice.which == SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(g_pad))) {
+ SDL_GameControllerClose(g_pad);
+ g_pad = nullptr;
+ }
+ }
+ const Uint8 *keys = SDL_GetKeyboardState(nullptr);
+ std::uint16_t pressed = 0;
+ for (const KeyBinding &b : kKeys)
+ if (keys[b.key]) pressed |= b.button;
+ std::uint8_t lx = 0x80, ly = 0x80, rx = 0x80, ry = 0x80;
+ if (keys[SDL_SCANCODE_LEFT]) lx = 0x00;
+ if (keys[SDL_SCANCODE_RIGHT]) lx = 0xFF;
+ if (keys[SDL_SCANCODE_UP]) ly = 0x00;
+ if (keys[SDL_SCANCODE_DOWN]) ly = 0xFF;
+ if (g_pad) {
+ for (const PadBinding &b : kPadButtons)
+ if (SDL_GameControllerGetButton(g_pad, b.button)) pressed |= b.mask;
+ if (SDL_GameControllerGetAxis(g_pad, SDL_CONTROLLER_AXIS_TRIGGERLEFT) > 8000) pressed |= kL2;
+ if (SDL_GameControllerGetAxis(g_pad, SDL_CONTROLLER_AXIS_TRIGGERRIGHT) > 8000) pressed |= kR2;
+ if (lx == 0x80) lx = axis(SDL_CONTROLLER_AXIS_LEFTX);
+ if (ly == 0x80) ly = axis(SDL_CONTROLLER_AXIS_LEFTY);
+ rx = axis(SDL_CONTROLLER_AXIS_RIGHTX);
+ ry = axis(SDL_CONTROLLER_AXIS_RIGHTY);
+ }
+ ps2::set_pad_buttons(pressed);
+ ps2::set_pad_axis(0, rx);
+ ps2::set_pad_axis(1, ry);
+ ps2::set_pad_axis(2, lx);
+ ps2::set_pad_axis(3, ly);
+}
+
+void present() {
+ std::uint32_t w = 0, h = 0;
+ if (!ps2::display_frame(g_pixels, w, h)) return;
+ 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));
+ SDL_RenderSetLogicalSize(g_renderer, static_cast<int>(w), static_cast<int>(w) * 3 / 4);
+ g_tex_w = w;
+ g_tex_h = h;
+ }
+ SDL_UpdateTexture(g_texture, nullptr, g_pixels.data(), static_cast<int>(w * 4));
+ SDL_RenderClear(g_renderer);
+ SDL_RenderCopy(g_renderer, g_texture, nullptr, nullptr);
+ SDL_RenderPresent(g_renderer);
+}
+
+void pace() {
+ const std::uint64_t frequency = SDL_GetPerformanceFrequency();
+ const std::uint64_t period = frequency / (ps2::g_options.pal ? 50 : 60);
+ const std::uint64_t now = SDL_GetPerformanceCounter();
+ if (g_last && now - g_last < period) {
+ SDL_Delay(static_cast<Uint32>((period - (now - g_last)) * 1000 / frequency));
+ g_last += period;
+ } else {
+ g_last = now;
+ }
+}
+
+void on_vblank() {
+ poll();
+ present();
+ pace();
+}
+
+void queue_audio(const std::int16_t *samples, std::size_t frames) {
+ if (SDL_GetQueuedAudioSize(g_audio) > 48000u * 4u / 5u) return;
+ SDL_QueueAudio(g_audio, samples, static_cast<Uint32>(frames * 4));
+}
+
+}
+
+bool open_window() {
+ 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);
+ g_renderer = g_window ? SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED) : nullptr;
+ if (g_window && !g_renderer) g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_SOFTWARE);
+ if (!g_renderer) {
+ std::fprintf(stderr, "SDL: %s\n", SDL_GetError());
+ return false;
+ }
+ SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
+ SDL_AudioSpec want{}, have{};
+ want.freq = 48000;
+ want.format = AUDIO_S16SYS;
+ want.channels = 2;
+ want.samples = 1024;
+ g_audio = SDL_OpenAudioDevice(nullptr, 0, &want, &have, 0);
+ if (g_audio) {
+ SDL_PauseAudioDevice(g_audio, 0);
+ ps2::set_audio_sink(queue_audio);
+ }
+ 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;
+ return true;
+}
diff --git a/host/window.hpp b/host/window.hpp
new file mode 100644
index 0000000..414afc7
--- /dev/null
+++ b/host/window.hpp
@@ -0,0 +1,3 @@
+#pragma once
+
+bool open_window();
diff --git a/runtime/include/ps2/system.hpp b/runtime/include/ps2/system.hpp
index f001a4c..9e69f96 100644
--- a/runtime/include/ps2/system.hpp
+++ b/runtime/include/ps2/system.hpp
@@ -34,6 +34,7 @@ struct Options {
std::string frames_dir;
std::uint32_t frame_every = 60;
std::vector<Press> presses;
+ std::function<void()> on_vblank;
};
extern Options g_options;
@@ -67,4 +68,9 @@ void halt(const std::string &reason);
bool halted();
std::uint64_t frame_count();
+bool display_frame(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32_t &height);
+void set_pad_buttons(std::uint16_t pressed);
+void set_pad_axis(int axis, std::uint8_t value);
+void set_audio_sink(std::function<void(const std::int16_t *samples, std::size_t frames)> sink);
+
}
diff --git a/runtime/src/iop/spu2.cpp b/runtime/src/iop/spu2.cpp
index 795c260..73ba7ac 100644
--- a/runtime/src/iop/spu2.cpp
+++ b/runtime/src/iop/spu2.cpp
@@ -75,6 +75,7 @@ Core g_cores[2];
std::uint16_t g_spdif_out = 0, g_spdif_mode = 0, g_spdif_media = 0;
std::vector<std::int16_t> g_audio;
bool g_record = false;
+std::function<void(const std::int16_t *, std::size_t)> g_sink;
std::uint64_t g_next_tick = 0;
void check_irq(std::uint32_t address, std::uint32_t words) {
@@ -219,6 +220,7 @@ void render_input(int core, std::int32_t &left, std::int32_t &right) {
std::int32_t master(std::uint16_t reg) { return reg & 0x8000u ? 0x7FFF : static_cast<std::int16_t>(reg << 1); }
void tick() {
+ std::int16_t out[kBatch * 2];
for (unsigned n = 0; n < kBatch; ++n) {
std::int32_t mix[2] = {};
for (int c = 0; c < 2; ++c) {
@@ -229,11 +231,11 @@ void tick() {
mix[0] += left * master(k.mvol[0]) >> 15;
mix[1] += right * master(k.mvol[1]) >> 15;
}
- if (g_record) {
- g_audio.push_back(static_cast<std::int16_t>(std::clamp(mix[0], -32768, 32767)));
- g_audio.push_back(static_cast<std::int16_t>(std::clamp(mix[1], -32768, 32767)));
- }
+ out[n * 2] = static_cast<std::int16_t>(std::clamp(mix[0], -32768, 32767));
+ out[n * 2 + 1] = static_cast<std::int16_t>(std::clamp(mix[1], -32768, 32767));
}
+ if (g_record) g_audio.insert(g_audio.end(), out, out + kBatch * 2);
+ if (g_sink) g_sink(out, kBatch);
feed_input(0);
feed_input(1);
g_next_tick = kernel::now() + kBatch * kCyclesPerSample;
@@ -472,6 +474,8 @@ void dma(int core, std::uint32_t madr, std::uint32_t words, bool to_spu, std::fu
kernel::schedule(kernel::now() + 64 + words / 4, std::move(done));
}
+void set_sink(std::function<void(const std::int16_t *, std::size_t)> sink) { g_sink = std::move(sink); }
+
void dump_audio(const char *path) {
std::FILE *f = std::fopen(path, "wb");
if (!f) return;
diff --git a/runtime/src/iop/spu2.hpp b/runtime/src/iop/spu2.hpp
index 7198c81..5dfb8c3 100644
--- a/runtime/src/iop/spu2.hpp
+++ b/runtime/src/iop/spu2.hpp
@@ -11,5 +11,6 @@ std::uint32_t read(std::uint32_t a, unsigned size);
void write(std::uint32_t a, std::uint32_t v, unsigned size);
void dma(int core, std::uint32_t madr, std::uint32_t words, bool to_spu, std::function<void()> done);
void dump_audio(const char *path);
+void set_sink(std::function<void(const std::int16_t *samples, std::size_t frames)> sink);
}
diff --git a/runtime/src/system.cpp b/runtime/src/system.cpp
index b459c8a..320356b 100644
--- a/runtime/src/system.cpp
+++ b/runtime/src/system.cpp
@@ -98,6 +98,7 @@ void apply_presses() {
void vblank() {
++g_frames;
apply_presses();
+ if (g_options.on_vblank) g_options.on_vblank();
if (g_options.trace_iop_modules && g_frames % 25 == 0) std::fprintf(stderr, "[frame] %llu prims %llu\n", static_cast<unsigned long long>(g_frames), static_cast<unsigned long long>(gs::primitives_drawn()));
if (!g_options.frames_dir.empty() && g_options.frame_every && g_frames % g_options.frame_every == 0) dump_frame();
hw::vblank_start();
@@ -271,4 +272,9 @@ int run() {
return 0;
}
+bool display_frame(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32_t &height) { return gs::display(rgba, width, height); }
+void set_pad_buttons(std::uint16_t pressed) { iop::sio2::set_buttons(0, pressed); }
+void set_pad_axis(int axis, std::uint8_t value) { iop::sio2::set_axis(0, axis, value); }
+void set_audio_sink(std::function<void(const std::int16_t *, std::size_t)> sink) { iop::spu2::set_sink(std::move(sink)); }
+
}