Skip to content

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

C++

Memory card in slot 1

Samir Nuri34b627da97a1
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 14da5b7..ebcc91b 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -90,7 +90,7 @@ if(PS2_GENERATED)
set(PS2_WEB_ELF "" CACHE FILEPATH "Game executable preloaded as /game/core.elf")
add_executable(ps2web host/web.cpp)
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 -sSTACK_SIZE=16777216 -sENVIRONMENT=web
+ 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_resize,_ps2web_gpu_ms,_ps2web_frames,_ps2web_primitives,_ps2web_audio_ring,_ps2web_audio_queued_ms,_ps2web_idle_ms,_ps2web_vu_interpreted
-sEXPORTED_RUNTIME_METHODS=callMain,addRunDependency,removeRunDependency,HEAPU8,ENV
--shell-file ${CMAKE_SOURCE_DIR}/web/shell.html --preload-file ${PS2_WEB_ELF}@/game/core.elf)
diff --git a/host/main.cpp b/host/main.cpp
index 5dd4017..a885286 100644
--- a/host/main.cpp
+++ b/host/main.cpp
@@ -21,7 +21,7 @@ namespace {
int usage() {
std::fprintf(stderr,
"usage: ps2run <elf> [--arg text]... [--frames n] [--ntsc] [--misses file]\n"
- " [--disc image.iso] [--pal | --ntsc] [--trace-syscalls] [--trace-io] [--trace-threads]\n"
+ " [--disc image.iso] [--memcard card.ps2] [--pal | --ntsc] [--trace-syscalls] [--trace-io] [--trace-threads]\n"
" [--trace-iop] [--trace-iop-hle] [--frames-dir dir] [--frame-every n]\n"
" [--press frame:button[+button][:frames]]... [--window]\n");
return 2;
@@ -46,6 +46,7 @@ int main(int argc, char **argv) {
else if (a == "--trace-io") ps2::g_options.trace_io = true;
else if (a == "--trace-threads") ps2::g_options.trace_threads = true;
else if (a == "--disc" && i + 1 < argc) ps2::g_options.disc_path = argv[++i];
+ else if (a == "--memcard" && i + 1 < argc) ps2::g_options.memcard_path = argv[++i];
else if (a == "--trace-iop") ps2::g_options.trace_iop_modules = true;
else if (a == "--trace-iop-hle") ps2::g_options.trace_iop_hle = true;
else if (a == "--frames-dir" && i + 1 < argc) ps2::g_options.frames_dir = argv[++i];
diff --git a/host/web.cpp b/host/web.cpp
index f8291bc..63535b8 100644
--- a/host/web.cpp
+++ b/host/web.cpp
@@ -282,6 +282,10 @@ int main(int argc, char **argv) {
if (status == 200 || status == 201) std::fprintf(stderr, "[web] saved VU1 program %s\n", name.c_str());
else unsupported = true;
};
+ if (!EM_ASM_INT({ return Module.noCard ? 1 : 0; })) {
+ ps2::g_options.memcard_path = "/memcard/Mcd001.ps2";
+ ps2::g_options.on_memcard_saved = [] { MAIN_THREAD_ASYNC_EM_ASM({ if (Module.ps2CardSaved) Module.ps2CardSaved(); }); };
+ }
ps2::set_audio_sink(push_audio);
register_generated_code();
register_generated_vu();
diff --git a/runtime/include/ps2/system.hpp b/runtime/include/ps2/system.hpp
index 7c0e252..3849dc1 100644
--- a/runtime/include/ps2/system.hpp
+++ b/runtime/include/ps2/system.hpp
@@ -37,6 +37,8 @@ struct Options {
std::vector<Press> presses;
std::function<void()> on_vblank;
std::function<void(const std::string &name, const std::uint8_t *code, std::size_t size)> on_vu_program;
+ std::string memcard_path;
+ std::function<void()> on_memcard_saved;
};
extern Options g_options;
diff --git a/runtime/src/iop/libs.cpp b/runtime/src/iop/libs.cpp
index 02521c0..851220a 100644
--- a/runtime/src/iop/libs.cpp
+++ b/runtime/src/iop/libs.cpp
@@ -950,7 +950,8 @@ void install_heaplib() {
void install_misc() {
register_hle_library("secrman", 0x0101);
- for (std::uint32_t i : {4u, 5u, 6u}) def("secrman", i, "secrman", [](Cpu &c) { c.r[2] = 0; });
+ for (std::uint32_t i : {4u, 5u}) def("secrman", i, "secrman", [](Cpu &c) { c.r[2] = 0; });
+ def("secrman", 6, "SecrAuthCard", [](Cpu &c) { c.r[2] = 1; });
}
}
diff --git a/runtime/src/iop/sio2.cpp b/runtime/src/iop/sio2.cpp
index dac7e9f..2d13861 100644
--- a/runtime/src/iop/sio2.cpp
+++ b/runtime/src/iop/sio2.cpp
@@ -2,9 +2,14 @@
#include "hw.hpp"
#include "iop.hpp"
+#include "ps2/system.hpp"
+#include <algorithm>
+#include <cstdio>
+#include <cstdlib>
#include <cstring>
#include <deque>
+#include <fstream>
#include <vector>
namespace ps2::iop::sio2 {
@@ -29,12 +34,25 @@ struct Dma {
std::uint32_t madr = 0, block_words = 0, blocks = 0;
};
+constexpr std::uint32_t kPageBytes = 528, kPages = 0x4000, kBlockPages = 16;
+constexpr std::size_t kCardBytes = static_cast<std::size_t>(kPageBytes) * kPages;
+
+struct Card {
+ bool present = false;
+ std::vector<std::uint8_t> data;
+ std::size_t address = 0;
+ std::uint8_t term = 0x55;
+ bool dirty = false;
+ std::uint32_t quiet = 0;
+};
+
std::uint32_t g_send3[16];
std::uint32_t g_ctrl1[4], g_ctrl2[4];
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];
+Card g_card;
Dma g_dma[2];
void controller(int port, std::size_t at, std::uint32_t out_size) {
@@ -123,6 +141,100 @@ void controller(int port, std::size_t at, std::uint32_t out_size) {
}
}
+std::uint8_t xor_of(const std::uint8_t *p, std::size_t n) {
+ std::uint8_t v = 0;
+ for (std::size_t i = 0; i < n; ++i) v ^= p[i];
+ return v;
+}
+
+void load_card() {
+ if (g_card.present || g_options.memcard_path.empty()) return;
+ g_card.data.assign(kCardBytes, 0xFF);
+ std::ifstream in(g_options.memcard_path, std::ios::binary);
+ if (in) in.read(reinterpret_cast<char *>(g_card.data.data()), static_cast<std::streamsize>(kCardBytes));
+ g_card.present = true;
+ std::fprintf(stderr, "[mc] card in slot 1: %s%s\n", g_options.memcard_path.c_str(), in ? "" : " (new, unformatted)");
+}
+
+void memory_card(std::size_t at, std::uint32_t out_size) {
+ Card &c = g_card;
+ const std::vector<std::uint8_t> in(g_in.begin(), g_in.end());
+ if (!c.present || in.size() < 2 || in[0] != 0x81) {
+ g_stat = kNoDevice;
+ return;
+ }
+ const std::size_t n = out_size;
+ auto put = [&](std::size_t i, std::uint8_t v) {
+ if (i < n) g_out[at + i] = v;
+ };
+ auto ack = [&](std::size_t from) {
+ for (std::size_t i = from; i + 2 < n; ++i) put(i, 0x00);
+ if (n >= 2) put(n - 2, 0x2B);
+ if (n >= 1) put(n - 1, c.term);
+ };
+ const std::uint8_t cmd = in[1];
+ static const bool trace = std::getenv("PS2_TRACE_MC") != nullptr;
+ if (trace) std::fprintf(stderr, "[mc] cmd %02X in %zu out %zu page %zu\n", cmd, in.size(), n, c.address / kPageBytes);
+ switch (cmd) {
+ case 0x21: case 0x22: case 0x23: {
+ const std::uint32_t page = in.size() > 5 ? static_cast<std::uint32_t>(in[2] | (in[3] << 8) | (in[4] << 16) | (in[5] << 24)) : 0u;
+ c.address = static_cast<std::size_t>(std::min(page, kPages - 1)) * kPageBytes;
+ ack(2);
+ break;
+ }
+ case 0x26: {
+ const std::uint8_t spec[8] = {0x00, 0x02, kBlockPages, 0x00, 0x00, 0x40, 0x00, 0x00};
+ put(2, 0x2B);
+ for (std::size_t i = 0; i < 8; ++i) put(3 + i, spec[i]);
+ put(11, xor_of(spec, 8));
+ put(12, c.term);
+ break;
+ }
+ case 0x27:
+ if (in.size() > 2) c.term = in[2];
+ ack(2);
+ break;
+ case 0x28:
+ put(2, 0x2B);
+ put(3, c.term);
+ put(4, 0x55);
+ break;
+ case 0x42: {
+ const std::size_t len = in.size() > 2 ? in[2] : 0;
+ for (std::size_t i = 0; i < len && 3 + i < in.size() && c.address < kCardBytes; ++i) c.data[c.address++] = in[3 + i];
+ c.dirty = true;
+ c.quiet = 0;
+ ack(2);
+ break;
+ }
+ case 0x43: {
+ const std::size_t len = in.size() > 2 ? in[2] : 0;
+ std::uint8_t sum = 0;
+ put(2, 0x00);
+ put(3, 0x2B);
+ for (std::size_t i = 0; i < len; ++i) {
+ const std::uint8_t v = c.address < kCardBytes ? c.data[c.address++] : 0xFF;
+ sum ^= v;
+ put(4 + i, v);
+ }
+ put(4 + len, sum);
+ put(5 + len, c.term);
+ break;
+ }
+ case 0x82: {
+ const std::size_t block = c.address / (static_cast<std::size_t>(kPageBytes) * kBlockPages) * kPageBytes * kBlockPages;
+ std::fill_n(c.data.begin() + static_cast<std::ptrdiff_t>(block), std::min<std::size_t>(kPageBytes * kBlockPages, kCardBytes - block), 0xFF);
+ c.dirty = true;
+ c.quiet = 0;
+ ack(2);
+ break;
+ }
+ default:
+ ack(2);
+ break;
+ }
+}
+
void process() {
const std::uint32_t reg = g_send3[g_index & 15u];
const std::uint32_t in_size = (reg >> 8) & 0x1FFu, out_size = (reg >> 18) & 0x1FFu;
@@ -132,7 +244,8 @@ void process() {
for (std::uint32_t i = 0; i < out_size; ++i) g_out.push_back(0xFF);
g_stat = 0x1100u;
const std::uint32_t device = g_ctrl2[port];
- if (device == 0x5FFFFu || device == 0x00030064u || port >= 2) g_stat = kNoDevice;
+ if (port == 2) memory_card(at, out_size);
+ else if (device == 0x5FFFFu || device == 0x00030064u || port >= 2) g_stat = kNoDevice;
else controller(port, at, out_size);
g_in.clear();
++g_index;
@@ -176,6 +289,21 @@ void reset() {
g_pads[1] = Pad{};
g_pads[0].connected = true;
g_dma[0] = g_dma[1] = Dma{};
+ load_card();
+}
+
+void flush_cards() {
+ Card &c = g_card;
+ if (!c.dirty || ++c.quiet < 50) return;
+ c.dirty = false;
+ std::ofstream out(g_options.memcard_path, std::ios::binary | std::ios::trunc);
+ if (out) out.write(reinterpret_cast<const char *>(c.data.data()), static_cast<std::streamsize>(c.data.size()));
+ if (!out) {
+ std::fprintf(stderr, "[mc] cannot write %s\n", g_options.memcard_path.c_str());
+ return;
+ }
+ out.close();
+ if (g_options.on_memcard_saved) g_options.on_memcard_saved();
}
std::uint32_t read(std::uint32_t a) {
diff --git a/runtime/src/iop/sio2.hpp b/runtime/src/iop/sio2.hpp
index f752281..0a013c1 100644
--- a/runtime/src/iop/sio2.hpp
+++ b/runtime/src/iop/sio2.hpp
@@ -10,5 +10,6 @@ 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 flush_cards();
}
diff --git a/runtime/src/system.cpp b/runtime/src/system.cpp
index a1aaae2..03b83a0 100644
--- a/runtime/src/system.cpp
+++ b/runtime/src/system.cpp
@@ -124,6 +124,7 @@ void vblank() {
time_frames();
apply_presses();
if (g_options.on_vblank) g_options.on_vblank();
+ iop::sio2::flush_cards();
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();
diff --git a/web/shell.html b/web/shell.html
index 6feab2d..293ec67 100644
--- a/web/shell.html
+++ b/web/shell.html
@@ -112,11 +112,76 @@
<option value="3">1920×1536</option>
</select>
<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>
+ <input id="import-file" type="file" accept=".ps2" hidden>
<button id="fullscreen" type="button" title="Fullscreen (F or double click)">Fullscreen</button></div>
<button id="exit-fullscreen" type="button">Exit fullscreen</button>
<div id="overlay"><div id="panel"><p id="help" hidden></p><button id="start" disabled>Loading…</button></div></div>
<script>
const statusEl = document.getElementById('status');
+const CARD_DIR = '/memcard', CARD_FILE = '/memcard/Mcd001.ps2', CARD_BYTES = 8650752;
+let noteTimer = 0, noteRestore = '';
+function note(text) {
+ if (!noteTimer) noteRestore = statusEl.textContent;
+ clearTimeout(noteTimer);
+ statusEl.textContent = text;
+ noteTimer = setTimeout(() => {
+ statusEl.textContent = noteRestore;
+ noteTimer = 0;
+ }, 5000);
+}
+let cardTimer = 0;
+function storeCard(then) {
+ clearTimeout(cardTimer);
+ cardTimer = setTimeout(() => {
+ try {
+ FS.syncfs(false, (err) => {
+ if (err) console.warn('memory card: could not write browser storage', err);
+ if (then) then();
+ });
+ } catch (e) {
+ if (then) then();
+ }
+ }, 300);
+}
+document.getElementById('export-card').addEventListener('click', () => {
+ let data = null;
+ try { data = FS.readFile(CARD_FILE); } catch (e) {}
+ if (!data) {
+ note('Nothing saved on the memory card yet');
+ return;
+ }
+ const link = document.createElement('a');
+ link.href = URL.createObjectURL(new Blob([data], { type: 'application/octet-stream' }));
+ link.download = 'Mcd001.ps2';
+ link.click();
+ setTimeout(() => URL.revokeObjectURL(link.href), 10000);
+});
+const importInput = document.getElementById('import-file');
+document.getElementById('import-card').addEventListener('click', () => importInput.click());
+importInput.addEventListener('change', async () => {
+ const file = importInput.files[0];
+ importInput.value = '';
+ if (!file) return;
+ if (file.size !== CARD_BYTES) {
+ note('That is not an 8 MB PS2 memory card image (' + CARD_BYTES + ' bytes)');
+ return;
+ }
+ const data = new Uint8Array(await file.arrayBuffer());
+ if (new TextDecoder().decode(data.subarray(0, 28)) !== 'Sony PS2 Memory Card Format ') {
+ note('That file is not a formatted PS2 memory card');
+ return;
+ }
+ if (!confirm('Replace the memory card in slot 1 with ' + file.name + '? The page reloads to use it.')) return;
+ try {
+ FS.writeFile(CARD_FILE, data);
+ } catch (e) {
+ note('Import failed: ' + e.message);
+ return;
+ }
+ storeCard(() => location.reload());
+});
const statsEl = document.getElementById('stats');
const canvas = document.getElementById('canvas');
const params = new URLSearchParams(location.search);
@@ -444,6 +509,7 @@ var Module = {
arguments: ['/game/core.elf', '--arg', params.get('arg') || 'cdrom0:\\CORE.GT4;1'].concat(params.getAll('press').flatMap((p) => p.split(',').flatMap((x) => ['--press', x]))),
discUrl: params.get('disc') || 'disc.iso',
noSurface: params.has('nosurface'),
+ noCard: params.has('nocard'),
presentCopy: params.has('copy'),
print: (text) => console.log(text),
printErr: (text) => console.log(text),
@@ -459,6 +525,19 @@ var Module = {
start.textContent = 'Start';
},
preRun: [() => {
+ if (!Module.noCard) {
+ try {
+ FS.mkdir(CARD_DIR);
+ FS.mount(IDBFS, {}, CARD_DIR);
+ Module.addRunDependency('card');
+ FS.syncfs(true, (err) => {
+ if (err) console.warn('memory card: could not read browser storage', err);
+ Module.removeRunDependency('card');
+ });
+ } catch (e) {
+ console.warn('memory card: browser storage is not available', e);
+ }
+ }
for (const [key, value] of params) if (key.startsWith('PS2_')) Module.ENV[key] = value;
Module.ENV.PS2_SCALE = scale;
Module.addRunDependency('disc');
@@ -475,6 +554,7 @@ var Module = {
});
}],
audioQueuedMs: () => Module._ps2web_audio_queued_ms(),
+ ps2CardSaved: () => storeCard(),
onFrame: () => {
pollInput();
++frames;