PS2 games in the browser: static recompilation to WebAssembly with a native runtime
C++
Quick saves in the web shell, without a build step
Riccardo Gioratoa62921a3d708
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 20f54f1..202fcec 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -103,7 +103,7 @@ if(PS2_GENERATED)endif()target_link_libraries(ps2web PRIVATE ps2game ps2runtime)target_link_options(ps2web PRIVATE --profiling-funcs -sJSPI -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=268435456 -sPTHREAD_POOL_SIZE=2 -sALLOW_TABLE_GROWTH=1 -lidbfs.js -sSTACK_SIZE=16777216 -sENVIRONMENT=web- -sEXPORTED_FUNCTIONS=_main,_ps2web_pad,_ps2web_pad_connected,_ps2web_resize,_ps2web_gpu_ms,_ps2web_frames,_ps2web_primitives,_ps2web_audio_ring,_ps2web_audio_queued_ms,_ps2web_idle_ms,_ps2web_vu_interpreted+ -sEXPORTED_FUNCTIONS=_main,_ps2web_pad,_ps2web_pad_connected,_ps2web_resize,_ps2web_gpu_ms,_ps2web_frames,_ps2web_primitives,_ps2web_audio_ring,_ps2web_audio_queued_ms,_ps2web_idle_ms,_ps2web_vu_interpreted,_ps2web_quick_state-sEXPORTED_RUNTIME_METHODS=callMain,addRunDependency,removeRunDependency,HEAPU8,ENV--shell-file ${CMAKE_SOURCE_DIR}/web/shell.html --preload-file ${PS2_WEB_ELF}@/game/core.elf)set_target_properties(ps2web PROPERTIES SUFFIX ".html" LINK_DEPENDS ${CMAKE_SOURCE_DIR}/web/shell.html)diff --git a/host/web.cpp b/host/web.cppindex efae408..2a59bd8 100644--- a/host/web.cpp+++ b/host/web.cpp@@ -1,4 +1,5 @@#include "ps2/disc.hpp"+#include "ps2/state_request.hpp"#include "ps2/system.hpp"#include <emscripten.h>@@ -341,6 +342,14 @@ 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));}+extern "C" EMSCRIPTEN_KEEPALIVE int ps2web_quick_state(int loading) {+ return ps2::request_state_operation(loading != 0, "/quicksave.state", [](bool load, bool success) {+ MAIN_THREAD_ASYNC_EM_ASM({+ if (Module.onQuickState) Module.onQuickState(!!$0, !!$1);+ }, load, success);+ }) ? 1 : 0;+}+extern "C" EMSCRIPTEN_KEEPALIVE double ps2web_gpu_ms() { return ps2::gpu_busy_ms(); }extern "C" EMSCRIPTEN_KEEPALIVE double ps2web_frames() { return static_cast<double>(ps2::frames_run()); }extern "C" EMSCRIPTEN_KEEPALIVE double ps2web_primitives() { return static_cast<double>(ps2::primitives_drawn()); }diff --git a/runtime/include/ps2/state_request.hpp b/runtime/include/ps2/state_request.hppnew file mode 100644index 0000000..869efea--- /dev/null+++ b/runtime/include/ps2/state_request.hpp@@ -0,0 +1,10 @@+#pragma once++namespace ps2 {++// Queue a state operation from the UI thread. It runs after generated code has+// unwound, on the emulation thread. Only one request may be outstanding.+// The completion callback also runs on the emulation thread.+bool request_state_operation(bool loading, const char *path, void (*complete)(bool loading, bool success));++}diff --git a/runtime/src/system.cpp b/runtime/src/system.cppindex 76865f5..b402856 100644--- a/runtime/src/system.cpp+++ b/runtime/src/system.cpp@@ -15,6 +15,7 @@#include "ps2/generated.hpp"#include "ps2/memory.hpp"#include "ps2/state.hpp"+#include "ps2/state_request.hpp"#include "ps2/system.hpp"#ifdef __EMSCRIPTEN__@@ -30,6 +31,7 @@#include <fstream>#include <cstdlib>#include <iterator>+#include <mutex>#include <stdexcept>namespace ps2 {@@ -56,6 +58,10 @@ std::uint64_t g_frames = 0;std::uint64_t g_iop_synced = 0;bool g_state_request = false;bool g_resumed = false;+std::atomic<int> g_state_operation{0};+std::mutex g_state_mutex;+std::string g_state_path;+void (*g_state_complete)(bool, bool) = nullptr;std::uint64_t next_event_time() {std::uint64_t t = UINT64_MAX;@@ -229,7 +235,7 @@ std::uint64_t scheduled_at(int event) {bool preempt(Cpu &c) {run_due_events();refill(c);- return g_halted || g_state_request || kernel::must_unwind();+ return g_halted || g_state_request || g_state_operation.load(std::memory_order_relaxed) || kernel::must_unwind();}void halt(const std::string &reason) {@@ -241,6 +247,15 @@ void halt(const std::string &reason) {bool halted() { return g_halted; }const std::string &halt_reason() { return g_halt_reason; }+bool request_state_operation(bool loading, const char *path, void (*complete)(bool, bool)) {+ std::lock_guard<std::mutex> lock(g_state_mutex);+ if (g_state_operation.load(std::memory_order_acquire)) return false;+ g_state_path = path;+ g_state_complete = complete;+ g_state_operation.store(loading ? 2 : 1, std::memory_order_release);+ return true;+}+namespace {constexpr char kStateMagic[8] = {'P', 'S', '2', 'S', 'T', 'A', 'T', 'E'};@@ -405,6 +420,18 @@ int run() {Cpu &c = g_cpu;if (!g_resumed) set_budget(c, kMaxSlice);while (!g_halted) {+ if (const int operation = g_state_operation.load(std::memory_order_acquire)) {+ // Request fields stay immutable until completion; never serialize+ // from the browser thread while the emulated CPUs are running.+ const bool loading = operation == 2;+ const bool success = loading ? load_state(g_state_path) : save_state(g_state_path);+ const auto complete = g_state_complete;+ g_state_operation.store(0, std::memory_order_release);+ if (complete) complete(loading, success);+ // A malformed state may have partially replaced machine memory.+ if (loading && !success) halt("Quick load failed. Reload the player to continue safely.");+ if (g_halted) break;+ }if (g_state_request) {g_state_request = false;save_state(g_options.save_state_path);diff --git a/web/shell.html b/web/shell.htmlindex 41aa0ec..3c8aa59 100644--- a/web/shell.html+++ b/web/shell.html@@ -116,6 +116,8 @@<option value="4:3">4:3</option><option value="16:9">16:9</option></select>+ <button id="save-state" type="button" disabled title="Save the game to this device">Save state</button>+ <button id="load-state" type="button" disabled title="Load the quick save from this device">Load state</button><button id="controls-toggle" type="button" hidden>Hide controls</button><button id="export-card" type="button" title="Download the memory card in slot 1 as a .ps2 file">Export card</button><button id="import-card" type="button" title="Put a .ps2 memory card file in slot 1">Import card</button>@@ -290,6 +292,99 @@ aspectSelect.addEventListener('change', () => {location.href = url.href;});+// One quick save per player URL, kept in this browser's IndexedDB. The state+// file itself is captured by the emulation thread, so saving never pauses it+// mid-instruction.+const saveStateButton = document.getElementById('save-state');+const loadStateButton = document.getElementById('load-state');+const STATE_FILE = '/quicksave.state';+let stateBusy = false, statePending = null;++function stateKey() {+ return location.pathname + '|' + new URL(Module.discUrl, location.href).href;+}++function stateSlot(value) {+ return new Promise((resolve, reject) => {+ const open = indexedDB.open('ps2-player-quicksave', 1);+ open.onupgradeneeded = () => open.result.createObjectStore('slots');+ open.onerror = () => reject(open.error);+ open.onblocked = () => reject(new Error('Close other player tabs and try again.'));+ open.onsuccess = () => {+ const db = open.result;+ // A put commits atomically: a failed write preserves the previous save.+ const transaction = db.transaction('slots', value === undefined ? 'readonly' : 'readwrite');+ const store = transaction.objectStore('slots');+ const request = value === undefined ? store.get(stateKey()) : store.put(value, stateKey());+ transaction.oncomplete = () => { db.close(); resolve(request.result); };+ transaction.onabort = () => { db.close(); reject(transaction.error || new Error('Browser storage write failed.')); };+ };+ });+}++async function stateDigest(bytes) {+ if (!crypto.subtle) return '';+ const hash = await crypto.subtle.digest('SHA-256', bytes);+ return Array.from(new Uint8Array(hash), (byte) => byte.toString(16).padStart(2, '0')).join('');+}++function requestState(loading) {+ return new Promise((resolve, reject) => {+ statePending = { loading, resolve, reject };+ if (!Module._ps2web_quick_state(loading ? 1 : 0)) {+ statePending = null;+ reject(new Error('The player is busy. Try again.'));+ }+ });+}++function setStateBusy(busy) {+ stateBusy = busy;+ saveStateButton.disabled = loadStateButton.disabled = busy || !Module.running;+}++async function saveState() {+ if (stateBusy || !Module.running) return;+ setStateBusy(true);+ note('Saving…');+ try {+ await requestState(false);+ const bytes = FS.readFile(STATE_FILE);+ const record = { bytes, digest: await stateDigest(bytes), savedAt: Date.now() };+ await stateSlot(record);+ note('Saved ' + new Date(record.savedAt).toLocaleString());+ } catch (error) {+ note(error.name === 'QuotaExceededError' ? 'Not enough device storage. Your previous quick save is unchanged.' : error.message);+ } finally {+ try { FS.unlink(STATE_FILE); } catch (e) {}+ setStateBusy(false);+ }+}++async function loadState() {+ if (stateBusy || !Module.running) return;+ setStateBusy(true);+ note('Loading quick save…');+ try {+ const record = await stateSlot();+ if (!record) throw new Error('No quick save yet.');+ if (!(record.bytes instanceof Uint8Array) || (record.digest && await stateDigest(record.bytes) !== record.digest)) {+ throw new Error('The quick save is damaged. It has not been loaded.');+ }+ FS.writeFile(STATE_FILE, record.bytes);+ await requestState(true);+ note('Quick save loaded.');+ } catch (error) {+ note(error.message);+ } finally {+ try { FS.unlink(STATE_FILE); } catch (e) {}+ setStateBusy(false);+ }+}++saveStateButton.addEventListener('click', saveState);+loadStateButton.addEventListener('click', loadState);+const controlsButton = document.getElementById('controls-toggle');let hideControls = false;try { hideControls = localStorage.getItem('ps2web-hide-controls') === '1'; } catch (e) {}@@ -576,11 +671,22 @@ var Module = {noCard: params.has('nocard'),presentCopy: params.has('copy'),onHalt: (reason) => {+ if (statePending) {+ statePending.reject(new Error('The game stopped before the operation completed.'));+ statePending = null;+ }clearTimeout(noteTimer);noteTimer = 0;statusEl.textContent = 'Halted: ' + reason;statusEl.style.color = '#f66';},+ onQuickState: (loading, success) => {+ if (!statePending || statePending.loading !== loading) return;+ const { resolve, reject } = statePending;+ statePending = null;+ if (success) resolve();+ else reject(new Error(loading ? 'Quick load failed. Reload the player to continue safely.' : 'Could not capture the game. Your previous quick save is unchanged.'));+ },print: (text) => console.log(text),printErr: (text) => console.log(text),setStatus: (text) => {@@ -668,6 +774,7 @@ document.getElementById('start').addEventListener('click', async () => {await startAudio();statusEl.textContent = 'Running, ' + Module.gpuInfo;Module.running = true;+ setStateBusy(false);Module.callMain(Module.arguments);});</script>