PS2 games in the browser: static recompilation to WebAssembly with a native runtime
C++
Pads: vibration and analog trigger pressure
Samir Nuri331f9d5abaf1
diff --git a/README.md b/README.mdindex fc5fd9c..89736f1 100644--- a/README.md+++ b/README.md@@ -69,11 +69,11 @@ Set your expectations accordingly: two games have been brought up so far. AnotheThe page needs WebGPU for the GPU renderer. Chrome and Edge have it on Windows and macOS. On Linux it is off by default in Chrome and Chromium: turn on `chrome://flags/#enable-unsafe-webgpu` and `chrome://flags/#enable-vulkan` and restart the browser, as the page tells you when it finds no usable adapter. Without WebGPU the software renderer takes over, which is fine for menus and far too slow for 3D. On laptops with two GPUs, a canvas drawn on the discrete GPU sometimes cannot be shown on the screen; the page tries both adapters and falls back to copying frames through a 2D canvas.-The 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.+The 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. Their analog triggers reach the game as the DualShock 2's pressure-sensitive L2 and R2, and controllers with motors vibrate when the game asks for it, in browsers that expose vibration (Chrome and Edge do). 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.+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, with the same trigger pressure and vibration as in the browser.```bashbuild/native-mygame/ps2run games/mygame/disc/SLUS_123.45 --disc games/mygame/disc.iso --window --memcard mygame.ps2diff --git a/host/web.cpp b/host/web.cppindex 9369ee2..cd8bb9e 100644--- a/host/web.cpp+++ b/host/web.cpp@@ -322,6 +322,13 @@ extern "C" EMSCRIPTEN_KEEPALIVE void ps2web_pad(int buttons, int lx, int ly, intps2::set_pad_axis(3, static_cast<std::uint8_t>(ly));}+extern "C" EMSCRIPTEN_KEEPALIVE void ps2web_pressure(int a, int b, int c, int d) {+ const int packed[4] = {a, b, c, d};+ for (int i = 0; i < 16; ++i) ps2::set_pad_pressure(i, static_cast<std::uint8_t>(static_cast<unsigned>(packed[i / 4]) >> (i % 4 * 8)));+}++extern "C" EMSCRIPTEN_KEEPALIVE int ps2web_rumble() { return ps2::pad_rumble(); }+extern "C" EMSCRIPTEN_KEEPALIVE void ps2web_resize(int width, int height) {ps2::resize_window(static_cast<std::uint32_t>(width), static_cast<std::uint32_t>(height));}diff --git a/host/window.cpp b/host/window.cppindex f52692e..4ba8d17 100644--- a/host/window.cpp+++ b/host/window.cpp@@ -106,6 +106,18 @@ std::uint8_t axis(SDL_GameControllerAxis a) {return static_cast<std::uint8_t>(std::clamp((v + 32768) >> 8, 0, 255));}+void rumble() {+ static std::uint16_t last = 0;+ static Uint32 sent = 0;+ if (!g_pad) return;+ const std::uint16_t motors = ps2::pad_rumble();+ const Uint32 now = SDL_GetTicks();+ if (motors == last && (!motors || now - sent < 100)) return;+ last = motors;+ sent = now;+ SDL_GameControllerRumble(g_pad, static_cast<Uint16>((motors >> 8) * 257), (motors & 1u) ? 0xFFFF : 0, motors ? 200 : 0);+}+void poll() {SDL_Event e;while (SDL_PollEvent(&e)) {@@ -130,6 +142,7 @@ void poll() {std::uint16_t pressed = 0;for (const KeyBinding &b : kKeys)if (keys[b.key]) pressed |= b.button;+ std::uint8_t l2 = 0xFF, r2 = 0xFF;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;@@ -138,18 +151,27 @@ void poll() {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;+ const auto trigger = [&](SDL_GameControllerAxis a, std::uint16_t bit, std::uint8_t &pressure) {+ const int v = SDL_GameControllerGetAxis(g_pad, a);+ if (v <= 2000 || (pressed & bit)) return;+ pressed |= bit;+ pressure = static_cast<std::uint8_t>(std::max(1, v * 255 / 32767));+ };+ trigger(SDL_CONTROLLER_AXIS_TRIGGERLEFT, kL2, l2);+ trigger(SDL_CONTROLLER_AXIS_TRIGGERRIGHT, kR2, r2);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);}+ rumble();static std::uint64_t last = ~0ull;const std::uint64_t state = pressed | (static_cast<std::uint64_t>(rx) << 16) | (static_cast<std::uint64_t>(ry) << 24) | (static_cast<std::uint64_t>(lx) << 32) |- (static_cast<std::uint64_t>(ly) << 40);+ (static_cast<std::uint64_t>(ly) << 40) | (static_cast<std::uint64_t>(l2) << 48) | (static_cast<std::uint64_t>(r2) << 56);if (state == last) return;last = state;+ ps2::set_pad_pressure(8, l2);+ ps2::set_pad_pressure(9, r2);ps2::set_pad_buttons(pressed);ps2::set_pad_axis(0, rx);ps2::set_pad_axis(1, ry);diff --git a/runtime/include/ps2/system.hpp b/runtime/include/ps2/system.hppindex 864b223..0eb5552 100644--- a/runtime/include/ps2/system.hpp+++ b/runtime/include/ps2/system.hpp@@ -113,6 +113,8 @@ std::uint64_t frames_run();std::uint64_t primitives_drawn();void set_pad_buttons(std::uint16_t pressed);void set_pad_axis(int axis, std::uint8_t value);+void set_pad_pressure(int button, std::uint8_t value);+std::uint16_t pad_rumble();void set_audio_sink(std::function<void(const std::int16_t *samples, std::size_t frames)> sink);}diff --git a/runtime/src/iop/sio2.cpp b/runtime/src/iop/sio2.cppindex b2358ec..60adac5 100644--- a/runtime/src/iop/sio2.cpp+++ b/runtime/src/iop/sio2.cpp@@ -7,6 +7,7 @@#include "ps2/state.hpp"#include <algorithm>+#include <atomic>#include <cstdio>#include <cstdlib>#include <cstring>@@ -30,6 +31,14 @@ struct Pad {std::uint8_t poll_mask[3] = {0xFF, 0xFF, 0x03};};+constexpr std::uint8_t kLibpadMotors[6] = {0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF};++struct Feel {+ std::uint8_t motors[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};+ std::uint8_t pressure[16] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};+ std::atomic<std::uint16_t> rumble{0};+};+struct Dma {bool armed = false;std::uint32_t madr = 0, block_words = 0, blocks = 0;@@ -53,6 +62,7 @@ std::uint32_t g_index = 0;std::uint32_t g_stat = 0;std::deque<std::uint8_t> g_in, g_out;Pad g_pads[2];+Feel g_feel[2];Card g_card;Dma g_dma[2];@@ -64,6 +74,7 @@ void controller(int port, std::size_t at, std::uint32_t out_size) {return;}Pad &p = g_pads[port];+ Feel &f = g_feel[port];const std::vector<std::uint8_t> in(g_in.begin(), g_in.end());const std::uint8_t cmd = in.size() > 1 ? in[1] : 0;auto put = [&](std::size_t i, std::uint8_t v) {@@ -84,7 +95,7 @@ void controller(int port, std::size_t at, std::uint32_t out_size) {}if (p.mode == kPressure) {static const int kBits[12] = {5, 7, 4, 6, 12, 13, 14, 15, 10, 11, 8, 9};- for (int i = 0; i < 12; ++i) put(9 + static_cast<std::size_t>(i), (p.buttons >> kBits[i]) & 1u ? 0xFF : 0x00);+ for (int i = 0; i < 12; ++i) put(9 + static_cast<std::size_t>(i), (p.buttons >> kBits[i]) & 1u ? f.pressure[kBits[i]] : 0x00);}};switch (cmd) {@@ -95,9 +106,16 @@ void controller(int port, std::size_t at, std::uint32_t out_size) {if (p.mode == kDigital) for (int i = 3; i < 9; ++i) put(static_cast<std::size_t>(i), 0);else { put(3, p.poll_mask[0]); put(4, p.poll_mask[1]); put(5, p.poll_mask[2]); put(6, 0); put(7, 0); put(8, 0x5A); }break;- case 0x42:+ case 0x42: {data();+ std::uint8_t small = 0, large = 0;+ for (std::size_t i = 0; i < 6 && 3 + i < in.size(); ++i) {+ if (f.motors[i] == 0x00) small = in[3 + i] & 1u;+ if (f.motors[i] == 0x01) large = in[3 + i];+ }+ f.rumble.store(static_cast<std::uint16_t>(small | (large << 8)), std::memory_order_relaxed);break;+ }case 0x43:if (!p.config) data();else for (int i = 3; i < 9; ++i) put(static_cast<std::size_t>(i), 0);@@ -128,6 +146,8 @@ void controller(int port, std::size_t at, std::uint32_t out_size) {break;case 0x4D:for (int i = 3; i < 9; ++i) put(static_cast<std::size_t>(i), 0xFF);+ for (std::size_t i = 0; i < 6 && 3 + i < in.size(); ++i) f.motors[i] = in[3 + i];+ f.rumble.store(0, std::memory_order_relaxed);break;case 0x4F:if (in.size() > 5) {@@ -291,6 +311,10 @@ void reset() {g_pads[0] = Pad{};g_pads[1] = Pad{};g_pads[0].connected = true;+ for (Feel &f : g_feel) {+ std::fill(std::begin(f.motors), std::end(f.motors), 0xFF);+ f.rumble.store(0);+ }g_dma[0] = g_dma[1] = Dma{};load_card();}@@ -372,6 +396,12 @@ void set_axis(int pad, int axis, std::uint8_t value) {if (pad >= 0 && pad < 2 && axis >= 0 && axis < 4) g_pads[pad].axes[axis] = value;}+void set_pressure(int pad, int button, std::uint8_t value) {+ if (pad >= 0 && pad < 2 && button >= 0 && button < 16) g_feel[pad].pressure[button] = value;+}++std::uint16_t rumble(int pad) { return pad >= 0 && pad < 2 ? g_feel[pad].rumble.load(std::memory_order_relaxed) : 0; }+}namespace ps2::iop::sio2 {@@ -386,6 +416,11 @@ void state(ps2::state::Stream &s) {s.deque(g_in);s.deque(g_out);s.pod(g_pads);+ if (s.loading())+ for (Feel &f : g_feel) {+ std::copy(std::begin(kLibpadMotors), std::end(kLibpadMotors), f.motors);+ f.rumble.store(0);+ }s.pod(g_dma);s.size(g_card.address);s.pod(g_card.term);diff --git a/runtime/src/iop/sio2.hpp b/runtime/src/iop/sio2.hppindex 263422b..262e7a7 100644--- a/runtime/src/iop/sio2.hpp+++ b/runtime/src/iop/sio2.hpp@@ -16,6 +16,8 @@ void write(std::uint32_t a, std::uint32_t v);void arm_dma(int channel, std::uint32_t madr, std::uint32_t block_words, std::uint32_t blocks);void set_buttons(int pad, std::uint16_t pressed_mask);void set_axis(int pad, int axis, std::uint8_t value);+void set_pressure(int pad, int button, std::uint8_t value);+std::uint16_t rumble(int pad);void flush_cards();}diff --git a/runtime/src/system.cpp b/runtime/src/system.cppindex 7dcf8ee..ca8f06c 100644--- a/runtime/src/system.cpp+++ b/runtime/src/system.cpp@@ -524,6 +524,8 @@ std::uint64_t frames_run() { return g_frames; }std::uint64_t primitives_drawn() { return gs::primitives_drawn(); }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_pad_pressure(int button, std::uint8_t value) { iop::sio2::set_pressure(0, button, value); }+std::uint16_t pad_rumble() { return iop::sio2::rumble(0); }void set_audio_sink(std::function<void(const std::int16_t *, std::size_t)> sink) { iop::spu2::set_sink(std::move(sink)); }}diff --git a/web/shell.html b/web/shell.htmlindex cc7320b..8be78b8 100644--- a/web/shell.html+++ b/web/shell.html@@ -395,11 +395,13 @@ window.addEventListener('keyup', (e) => { keys.delete(e.code); });const padButtons = [[0, 14], [1, 13], [2, 15], [3, 12], [4, 10], [5, 11], [6, 8], [7, 9], [8, 0], [9, 3], [10, 1], [11, 2],[12, 4], [13, 6], [14, 7], [15, 5]];const axis = (v) => Math.max(0, Math.min(255, Math.round((v + 1) * 127.5)));-let lastPad = -1;+let lastPad = -1, lastPressure = '', lastRumble = 0, rumbleAt = 0;function pollInput() {- let buttons = 0, lx = 128, ly = 128, rx = 128, ry = 128;+ let buttons = 0, lx = 128, ly = 128, rx = 128, ry = 128, gamepad = null;+ const pressure = new Array(16).fill(255);buttons |= touchPad.buttons;for (const k of keys) if (k in keyMap) buttons |= 1 << keyMap[k];+ const full = buttons;if (keys.has('KeyJ')) lx = 0;if (keys.has('KeyL')) lx = 255;if (keys.has('KeyI')) ly = 0;@@ -410,7 +412,13 @@ function pollInput() {}for (const pad of navigator.getGamepads ? navigator.getGamepads() : []) {if (!pad) continue;- for (const [index, bit] of padButtons) if (pad.buttons[index] && pad.buttons[index].pressed) buttons |= 1 << bit;+ gamepad = pad;+ for (const [index, bit] of padButtons) {+ const b = pad.buttons[index];+ if (!b || !(b.pressed || b.value > 0.05)) continue;+ buttons |= 1 << bit;+ if (!(full & (1 << bit))) pressure[bit] = Math.max(1, Math.round((b.value > 0 ? b.value : 1) * 255));+ }if (pad.axes.length >= 4) {if (lx === 128) lx = axis(pad.axes[0]);if (ly === 128) ly = axis(pad.axes[1]);@@ -424,6 +432,19 @@ function pollInput() {lastPad = state;Module._ps2web_pad(buttons, lx, ly, rx, ry);}+ const packed = [0, 1, 2, 3].map((i) => pressure[i * 4] | (pressure[i * 4 + 1] << 8) | (pressure[i * 4 + 2] << 16) | (pressure[i * 4 + 3] << 24));+ if (packed.join() !== lastPressure) {+ lastPressure = packed.join();+ Module._ps2web_pressure(packed[0], packed[1], packed[2], packed[3]);+ }+ const rumble = Module._ps2web_rumble(), now = performance.now();+ const actuator = gamepad && gamepad.vibrationActuator;+ if (actuator && (rumble !== lastRumble || (rumble && now - rumbleAt > 100))) {+ lastRumble = rumble;+ rumbleAt = now;+ const done = rumble ? actuator.playEffect('dual-rumble', { duration: 200, weakMagnitude: rumble & 1, strongMagnitude: (rumble >> 8) / 255 }) : actuator.reset();+ if (done && done.catch) done.catch(() => {});+ }}// some browsers cannot show a canvas drawn by another GPU (hybrid laptops on Linux), so each adapter draws a few test frames first