Skip to content

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

C++

Savestates on the web: ?state=file, GS state on the render thread

Samir Nurica8e22dff30b
diff --git a/host/web.cpp b/host/web.cpp
index 1d64746..c2539ee 100644
--- a/host/web.cpp
+++ b/host/web.cpp
@@ -54,6 +54,31 @@ EM_JS(int, ps2web_save_program, (const char *name, const std::uint8_t *code, int
});
EM_JS(double, ps2web_disc_size, (), { return Module.discSize || 0; });
+EM_JS(char *, ps2web_state_url, (), { return Module.stateUrl ? stringToNewUTF8(new URL(Module.stateUrl, location.href).href) : 0; });
+EM_JS(double, ps2web_url_size, (const char *url), {
+ try {
+ const xhr = new XMLHttpRequest();
+ xhr.open('HEAD', UTF8ToString(url), false);
+ xhr.send();
+ return xhr.status === 200 ? Number(xhr.getResponseHeader('Content-Length') || 0) : 0;
+ } catch (e) {
+ return 0;
+ }
+});
+EM_JS(double, ps2web_url_read, (const char *url, std::uint8_t *out, double size), {
+ try {
+ const xhr = new XMLHttpRequest();
+ xhr.open('GET', UTF8ToString(url), false);
+ xhr.responseType = 'arraybuffer';
+ xhr.send();
+ if (xhr.status !== 200) return 0;
+ const bytes = new Uint8Array(xhr.response);
+ HEAPU8.set(bytes.subarray(0, size), out);
+ return bytes.length;
+ } catch (e) {
+ return 0;
+ }
+});
EM_JS(char *, ps2web_disc_url, (), { return stringToNewUTF8(new URL(Module.discUrl, location.href).href); });
EM_JS(void, ps2web_frame_done, (), { if (Module.onFrame) Module.onFrame(); });
EM_JS(void, ps2web_blit, (const std::uint32_t *rgba, int width, int height), {
@@ -111,6 +136,7 @@ AudioRing g_audio;
Slot g_slots[kSlots];
std::uint64_t g_disc_size = 0, g_use_clock = 0, g_last_chunk = ~0ull, g_run = 0;
char *g_disc_url = nullptr;
+char *g_state_url = nullptr;
Slot *find_slot(std::uint64_t index) {
for (Slot &s : g_slots)
@@ -232,6 +258,14 @@ void *emulate(void *data) {
return nullptr;
}
ps2::boot(entry, launch.args);
+ if (g_state_url) {
+ const double size = ps2web_url_size(g_state_url);
+ std::vector<std::uint8_t> data(static_cast<std::size_t>(size));
+ if (size <= 0 || ps2web_url_read(g_state_url, data.data(), size) != size || !ps2::load_state(data.data(), data.size())) {
+ std::fprintf(stderr, "[web] cannot load the state %s\n", g_state_url);
+ return nullptr;
+ }
+ }
ps2::run();
return nullptr;
}
@@ -286,6 +320,7 @@ int main(int argc, char **argv) {
}
g_disc_size = static_cast<std::uint64_t>(ps2web_disc_size());
g_disc_url = ps2web_disc_url();
+ g_state_url = ps2web_state_url();
ps2::g_options.on_vblank = on_vblank;
ps2::g_options.on_vu_program = [](const std::string &name, const std::uint8_t *code, std::size_t size) {
static bool unsupported = false;
diff --git a/runtime/include/ps2/state.hpp b/runtime/include/ps2/state.hpp
index 29bef43..f4e6bd4 100644
--- a/runtime/include/ps2/state.hpp
+++ b/runtime/include/ps2/state.hpp
@@ -27,6 +27,12 @@ public:
bytes(&v, sizeof v);
}
+ void size(std::size_t &v) {
+ std::uint64_t wide = v;
+ pod(wide);
+ v = static_cast<std::size_t>(wide);
+ }
+
void tag(const char *name) {
char text[8] = {};
std::strncpy(text, name, sizeof text);
diff --git a/runtime/include/ps2/system.hpp b/runtime/include/ps2/system.hpp
index d9b7c8c..89b253d 100644
--- a/runtime/include/ps2/system.hpp
+++ b/runtime/include/ps2/system.hpp
@@ -73,6 +73,7 @@ int run();
void halt(const std::string &reason);
bool save_state(const std::string &path);
bool load_state(const std::string &path);
+bool load_state(const std::uint8_t *data, std::size_t size);
bool halted();
std::uint64_t frame_count();
diff --git a/runtime/src/gs/gs.cpp b/runtime/src/gs/gs.cpp
index 368a5f3..379a6c1 100644
--- a/runtime/src/gs/gs.cpp
+++ b/runtime/src/gs/gs.cpp
@@ -12,6 +12,8 @@
#include <algorithm>
#include <atomic>
+#include <stdexcept>
+#include <string>
#include <functional>
#include <cstdio>
#include <cstdlib>
@@ -22,6 +24,8 @@ namespace ps2::gs {
State g_state;
+void serve_state(const void *payload);
+
namespace {
alignas(64) std::uint8_t g_memory[kMemorySize];
@@ -865,6 +869,7 @@ bool render_pending(const std::function<void(const DisplayRegs &)> &on_present)
presented = true;
break;
}
+ case queue::kState: serve_state(payload); break;
case queue::kDownload: {
std::uintptr_t target;
std::memcpy(&target, payload, sizeof target);
@@ -921,8 +926,12 @@ void stats() {
namespace ps2::gs {
-void state(ps2::state::Stream &s) {
- s.tag("gs");
+namespace {
+
+std::atomic<std::uint32_t> g_state_done{0};
+std::string g_state_error;
+
+void render_state(ps2::state::Stream &s) {
flush_and_wait();
s.pod(g_state);
s.pod(g_pmode);
@@ -946,7 +955,7 @@ void state(ps2::state::Stream &s) {
s.pod(g_odd_field);
s.pod(g_transfer);
s.pod(g_carry);
- s.pod(g_carried);
+ s.size(g_carried);
std::vector<std::uint32_t> vram, clut;
std::uint32_t scale = 1;
#ifdef PS2_GPU
@@ -973,3 +982,31 @@ void state(ps2::state::Stream &s) {
}
}
+
+void serve_state(const void *payload) {
+ std::uintptr_t target;
+ std::memcpy(&target, payload, sizeof target);
+ try {
+ render_state(*reinterpret_cast<ps2::state::Stream *>(target));
+ } catch (const std::exception &e) {
+ g_state_error = e.what();
+ }
+ g_state_done.fetch_add(1);
+ queue::notify(g_state_done);
+}
+
+void state(ps2::state::Stream &s) {
+ s.tag("gs");
+ if (!queue::active()) {
+ render_state(s);
+ return;
+ }
+ g_state_error.clear();
+ const std::uint32_t seen = g_state_done.load();
+ const std::uintptr_t target = reinterpret_cast<std::uintptr_t>(&s);
+ queue::post(queue::kState, 0, 0, &target, sizeof target);
+ while (g_state_done.load() == seen) queue::wait(g_state_done, seen);
+ if (!g_state_error.empty()) throw std::runtime_error(g_state_error);
+}
+
+}
diff --git a/runtime/src/gs/queue.hpp b/runtime/src/gs/queue.hpp
index 045cee5..5a74db6 100644
--- a/runtime/src/gs/queue.hpp
+++ b/runtime/src/gs/queue.hpp
@@ -7,7 +7,7 @@
namespace ps2::gs::queue {
-enum Type : std::uint32_t { kWrap, kGif, kGifReset, kReset, kVertexReset, kVblank, kPresent, kDownload, kVif1, kVif1Write, kVuReset };
+enum Type : std::uint32_t { kWrap, kGif, kGifReset, kReset, kVertexReset, kVblank, kPresent, kDownload, kVif1, kVif1Write, kVuReset, kState, kVuFence };
enum class Role { Emulation, Vu, Render };
diff --git a/runtime/src/iop/sio2.cpp b/runtime/src/iop/sio2.cpp
index fa0070e..20a45e2 100644
--- a/runtime/src/iop/sio2.cpp
+++ b/runtime/src/iop/sio2.cpp
@@ -386,7 +386,7 @@ void state(ps2::state::Stream &s) {
s.deque(g_out);
s.pod(g_pads);
s.pod(g_dma);
- s.pod(g_card.address);
+ s.size(g_card.address);
s.pod(g_card.term);
}
diff --git a/runtime/src/ipu/ipu.cpp b/runtime/src/ipu/ipu.cpp
index facd227..4e5a1a1 100644
--- a/runtime/src/ipu/ipu.cpp
+++ b/runtime/src/ipu/ipu.cpp
@@ -690,9 +690,9 @@ namespace ps2::ipu {
void state(ps2::state::Stream &s) {
s.tag("ipu");
s.vec(g_in);
- s.pod(g_bit);
+ s.size(g_bit);
s.vec(g_out);
- s.pod(g_out_pos);
+ s.size(g_out_pos);
s.pod(g_ctrl);
s.pod(g_result);
s.pod(g_command);
diff --git a/runtime/src/system.cpp b/runtime/src/system.cpp
index 8943b0b..86fdf0f 100644
--- a/runtime/src/system.cpp
+++ b/runtime/src/system.cpp
@@ -208,7 +208,7 @@ bool halted() { return g_halted; }
namespace {
constexpr char kStateMagic[8] = {'P', 'S', '2', 'S', 'T', 'A', 'T', 'E'};
-constexpr std::uint32_t kStateVersion = 1;
+constexpr std::uint32_t kStateVersion = 2;
std::function<void()> event_action(int id) {
if (id == hw::kEventVblank) return vblank;
@@ -217,6 +217,15 @@ std::function<void()> event_action(int id) {
return hw::event_action(id);
}
+std::atomic<std::uint32_t> g_vu_fence{0};
+
+void sync_vu_thread() {
+ if (!gs::queue::vu_active()) return;
+ const std::uint32_t seen = g_vu_fence.load();
+ gs::queue::vu().post(gs::queue::kVuFence, 0, 0, nullptr, 0);
+ while (g_vu_fence.load() == seen) gs::queue::wait(g_vu_fence, seen);
+}
+
void machine_state(state::Stream &s) {
char magic[8];
std::memcpy(magic, kStateMagic, sizeof magic);
@@ -242,11 +251,12 @@ void machine_state(state::Stream &s) {
kernel::state(s);
hw::state(s);
dmac::state(s);
+ sync_vu_thread();
vif::state(s);
vu::state(s);
- gif::state(s);
ipu::state(s);
gs::state(s);
+ gif::state(s);
iop::state(s);
sif::state(s);
s.tag("end");
@@ -269,15 +279,12 @@ bool save_state(const std::string &path) {
}
}
-bool load_state(const std::string &path) {
+bool load_state(const std::uint8_t *data, std::size_t size) {
try {
- std::ifstream in(path, std::ios::binary);
- if (!in) throw std::runtime_error("cannot open " + path);
- const std::vector<std::uint8_t> data{std::istreambuf_iterator<char>(in), {}};
- state::Reader r(data.data(), data.size());
+ state::Reader r(data, size);
machine_state(r);
g_resumed = true;
- std::fprintf(stderr, "[state] loaded frame %llu from %s\n", static_cast<unsigned long long>(g_frames), path.c_str());
+ std::fprintf(stderr, "[state] loaded frame %llu\n", static_cast<unsigned long long>(g_frames));
return true;
} catch (const std::exception &e) {
std::fprintf(stderr, "[state] cannot load: %s\n", e.what());
@@ -285,6 +292,16 @@ bool load_state(const std::string &path) {
}
}
+bool load_state(const std::string &path) {
+ std::ifstream in(path, std::ios::binary);
+ if (!in) {
+ std::fprintf(stderr, "[state] cannot open %s\n", path.c_str());
+ return false;
+ }
+ const std::vector<std::uint8_t> data{std::istreambuf_iterator<char>(in), {}};
+ return load_state(data.data(), data.size());
+}
+
std::uint64_t frame_count() { return g_frames; }
bool load_elf(const std::string &path, std::uint32_t &entry) {
@@ -422,6 +439,10 @@ void run_vu_thread() {
vif::reset_vu_side();
vu::reset();
break;
+ case gs::queue::kVuFence:
+ g_vu_fence.fetch_add(1);
+ gs::queue::notify(g_vu_fence);
+ break;
default: gs::queue::render().post(static_cast<gs::queue::Type>(h.type), h.arg0, h.arg1, payload, h.bytes); break;
}
in.pop(h);
diff --git a/web/shell.html b/web/shell.html
index fe85138..6c9f8e5 100644
--- a/web/shell.html
+++ b/web/shell.html
@@ -508,6 +508,7 @@ var Module = {
canvas,
arguments: ['/game/core.elf'].concat(params.has('arg') ? ['--arg', params.get('arg')] : [], params.getAll('press').flatMap((p) => p.split(',').flatMap((x) => ['--press', x]))),
discUrl: params.get('disc') || 'disc.iso',
+ stateUrl: params.get('state'),
noSurface: params.has('nosurface'),
noCard: params.has('nocard'),
presentCopy: params.has('copy'),