Skip to content

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

C++

Merge pull request #25 from riccardogiorato/web-fxaa

Samir Nuri8853b4f7ac31
diff --cc CMakeLists.txt
index 202fcec,15f054c..d97d248
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@@ -103,7 -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,_ps2web_quick_state
- -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_video_options
++ -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,_ps2web_video_options
-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 --cc host/web.cpp
index 2a59bd8,a8e0bfb..8889950
--- a/host/web.cpp
+++ b/host/web.cpp
@@@ -1,6 -1,6 +1,7 @@@
#include "ps2/disc.hpp"
+#include "ps2/state_request.hpp"
#include "ps2/system.hpp"
+ #include "ps2/video.hpp"
#include <emscripten.h>
#include <emscripten/threading.h>
@@@ -342,14 -342,8 +343,16 @@@ extern "C" EMSCRIPTEN_KEEPALIVE void ps
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 void ps2web_video_options(int flags) { ps2::set_video_options(static_cast<std::uint32_t>(flags)); }
+
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 --cc runtime/src/system.cpp
index 2500f2e,0e5bd3a..c09f9c8
--- a/runtime/src/system.cpp
+++ b/runtime/src/system.cpp
@@@ -15,8 -15,8 +15,9 @@@
#include "ps2/generated.hpp"
#include "ps2/memory.hpp"
#include "ps2/state.hpp"
+#include "ps2/state_request.hpp"
#include "ps2/system.hpp"
+ #include "ps2/video.hpp"
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
@@@ -58,11 -57,8 +59,13 @@@ 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::atomic<std::uint32_t> g_video_options{0};
+
std::uint64_t next_event_time() {
std::uint64_t t = UINT64_MAX;
for (const Event &e : g_events) t = std::min(t, e.at);
@@@ -250,15 -243,9 +253,18 @@@ 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;
+}
+
+ void set_video_options(std::uint32_t options) { g_video_options.store(options, std::memory_order_relaxed); }
+ std::uint32_t video_options() { return g_video_options.load(std::memory_order_relaxed); }
+
namespace {
constexpr char kStateMagic[8] = {'P', 'S', '2', 'S', 'T', 'A', 'T', 'E'};
diff --cc web/shell.html
index 3c0454b,a9fde1f..be2b0e2
--- a/web/shell.html
+++ b/web/shell.html
@@@ -116,11 -117,7 +117,12 @@@
<option value="4:3">4:3</option>
<option value="16:9">16:9</option>
</select>
+ <select id="pad" aria-label="Player 1 gamepad" title="Gamepad for player 1, the next connected one is player 2 (press a button on a pad if it is missing)">
+ <option value="">Pad: auto</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>
+ <label id="aa-label" title="Smooth jagged edges, applied immediately"><input id="aa" type="checkbox" disabled> Smooth edges</label>
<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>
@@@ -295,98 -292,21 +297,113 @@@ 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);
+ // Edge antialiasing is a display option, so it lives outside the save state
+ // and takes effect on the next presented frame.
+ const aaInput = document.getElementById('aa');
+ const aaLabel = document.getElementById('aa-label');
+ let aa = false;
+ try { aa = localStorage.getItem('ps2web-aa') === '1'; } catch (e) {}
+ aaInput.checked = aa;
+ function applyVideo() {
+ if (Module._ps2web_video_options) Module._ps2web_video_options(aa ? 1 : 0);
+ }
+ aaInput.addEventListener('change', () => {
+ aa = aaInput.checked;
+ try { localStorage.setItem('ps2web-aa', aa ? '1' : '0'); } catch (e) {}
+ applyVideo();
+ });
const controlsButton = document.getElementById('controls-toggle');
let hideControls = false;
@@@ -706,13 -599,12 +723,19 @@@ var Module =
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.'));
+ },
+ refreshVideoControls: () => {
+ const available = Module.videoEffectsAvailable ?? (!!navigator.gpu && !Module.gpuHelp && !Module.presentCopy && !Module.noSurface);
+ aaInput.disabled = !available;
+ aaLabel.title = available ? 'Smooth jagged edges, applied immediately' : 'Antialiasing needs direct WebGPU presentation';
+ applyVideo();
+ },
print: (text) => console.log(text),
printErr: (text) => console.log(text),
setStatus: (text) => {