PS2 games in the browser: static recompilation to WebAssembly with a native runtime
C++
A 16:9 setting, and PCSX2 patch files applied when porting
Samir Nuric0f476e6af94
diff --git a/CMakeLists.txt b/CMakeLists.txtindex f865e63..20f54f1 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -93,10 +93,14 @@ if(PS2_GENERATED)if(EMSCRIPTEN)set(PS2_WEB_ELF "" CACHE FILEPATH "Game executable preloaded as /game/core.elf")set(PS2_WEB_BOOT_FILE "" CACHE FILEPATH "Text file holding the argv[0] the game sees, preloaded as /game/boot.txt")+ set(PS2_WEB_PATCHES "" CACHE FILEPATH "Patch list the runtime writes into memory, preloaded as /game/patches.txt")add_executable(ps2web host/web.cpp)if(PS2_WEB_BOOT_FILE)target_link_options(ps2web PRIVATE "SHELL:--preload-file \"${PS2_WEB_BOOT_FILE}@/game/boot.txt\"")endif()+ if(PS2_WEB_PATCHES)+ target_link_options(ps2web PRIVATE "SHELL:--preload-file \"${PS2_WEB_PATCHES}@/game/patches.txt\"")+ 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_interpreteddiff --git a/README.md b/README.mdindex 285c250..488f0f1 100644--- a/README.md+++ b/README.md@@ -63,6 +63,8 @@ python3 scripts/serve.py build/web-mygame games/mygame/disc.iso # http://locaThe exploring runs press start and then cross every five seconds, which gets most games through their title screens, and put an empty memory card in slot 1 the way the page does, so they follow the path a player takes. `--press 900:cross` replaces that with your own inputs and `--frames` sets how long each run lasts. Frames from the last run land in `games/mygame/shots`, which is the quickest way to see how far a new game gets. `scripts/build_web.sh mygame` rebuilds only the page.+Patch files made for PCSX2 work as well. `port.sh` prints the CRC that PCSX2 puts in a game's patch file name, and `--pnach SCUS-97481_2F123FD8.pnach --pnach-section "Widescreen 16:9"` applies the lines outside any section plus the sections you name, the way ticking them in PCSX2 does. Patches that land in the executable are written into it before it is translated, so patches to code take effect, and every patch is also written into memory at boot or every frame as its line asks.+A game may also rewrite its own code: its executable declares an executable segment with no file contents and unpacks a different image into it as the game goes, the way Kingdom Hearts II swaps the module running its boot and menus. No single translation of such a segment can be right, so the exploring runs capture each image the game puts there, translate one per distinct code, and the runtime serves a call into the window from the image whose code is actually in place, checking it word by word. Data in the window the game rewrites freely never matches wrong, and a recapture of a known image folds into the image of the same code.Set your expectations accordingly: two games have been brought up so far. Another game will most likely stop at a system call or an IOP library function nobody implemented yet, which the runner logs as `[sys] unhandled syscall` or `[iop] missing <library> #<n>`, or use a GS feature the renderer does not handle yet.@@ -71,7 +73,7 @@ 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. 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.+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, and so does the 4:3/16:9 selector, which tells the game the TV is widescreen the way the PS2's system settings do and shows the picture at that shape. Most games need a widescreen patch or their own menu option to draw for it.## Playing natively@@ -81,7 +83,7 @@ The native runner, `build/native-mygame/ps2run`, plays the game in a window whenbuild/native-mygame/ps2run games/mygame/disc/SLUS_123.45 --disc games/mygame/disc.iso --window --memcard mygame.ps2```-`--fullscreen` starts in fullscreen and F11 switches back and forth. `PS2_SCALE=2` or `3` raises the internal resolution. As in the browser, the emulation, vector unit 1 and the GS each run on their own thread, which takes God of War II from 43 to 60 frames per second at the native resolution on the test laptop; `PS2_ONE_THREAD=1` puts everything back on one thread. The memory card file uses the same layout as the page's exported cards. On a Steam Deck the runner can be added to Steam as a non-Steam game, though nobody has tried it on one yet.+`--fullscreen` starts in fullscreen and F11 switches back and forth. `--widescreen` is the 16:9 setting, and `--patches games/mygame/patches.txt` writes the patches `port.sh` collected, which it prints in the line to run. `PS2_SCALE=2` or `3` raises the internal resolution. As in the browser, the emulation, vector unit 1 and the GS each run on their own thread, which takes God of War II from 43 to 60 frames per second at the native resolution on the test laptop; `PS2_ONE_THREAD=1` puts everything back on one thread. The memory card file uses the same layout as the page's exported cards. On a Steam Deck the runner can be added to Steam as a non-Steam game, though nobody has tried it on one yet.## Savesdiff --git a/host/main.cpp b/host/main.cppindex f998c37..9e5e1e4 100644--- a/host/main.cpp+++ b/host/main.cpp@@ -24,7 +24,7 @@ int usage() {" [--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] [--fullscreen]\n"- " [--save-state frame:file] [--load-state file]\n");+ " [--save-state frame:file] [--load-state file] [--widescreen] [--patches file]\n");return 2;}@@ -45,6 +45,10 @@ int main(int argc, char **argv) {}else if (a == "--misses" && i + 1 < argc) ps2::g_options.misses_path = argv[++i];else if (a == "--trace-syscalls") ps2::g_options.trace_syscalls = true;+ else if (a == "--widescreen") ps2::g_options.widescreen = true;+ else if (a == "--patches" && i + 1 < argc) {+ if (!ps2::load_patches(argv[++i])) return usage();+ }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];diff --git a/host/web.cpp b/host/web.cppindex 6e3c0d6..efae408 100644--- a/host/web.cpp+++ b/host/web.cpp@@ -98,7 +98,7 @@ EM_JS(void, ps2web_frame_done, (), {EM_ASYNC_JS(void, ps2web_wait_shown, (), {if (Module.shownPending) await new Promise((resolve) => Module.shownWaiters.push(resolve));});-EM_JS(void, ps2web_blit, (const std::uint32_t *rgba, int width, int height), {+EM_JS(void, ps2web_blit, (const std::uint32_t *rgba, int width, int height, int wide), {const canvas = Module.canvas;if (!Module.blitContext) Module.blitContext = canvas.getContext('2d');if (!Module.blitImage || Module.blitImage.width !== width || Module.blitImage.height !== height) {@@ -108,8 +108,9 @@ EM_JS(void, ps2web_blit, (const std::uint32_t *rgba, int width, int height), {Module.blitImage.data.set(HEAPU8.subarray(rgba, rgba + width * height * 4));Module.blitSource.getContext('2d').putImageData(Module.blitImage, 0, 0);const ctx = Module.blitContext;- const scale = Math.min(canvas.width / 4, canvas.height / 3);- const w = scale * 4, h = scale * 3;+ const across = wide ? 16 : 4, down = wide ? 9 : 3;+ const scale = Math.min(canvas.width / across, canvas.height / down);+ const w = scale * across, h = scale * down;const sx = Math.max(1, Math.floor(w / width)), sy = Math.max(1, Math.floor(h / height));let source = Module.blitSource;if (sx > 1 || sy > 1) {@@ -295,6 +296,7 @@ void *emulate(void *data) {const Launch &launch = *static_cast<const Launch *>(data);if (g_disc_size && !ps2::disc::open("disc", g_disc_size, read_disc, disc_ready)) std::fprintf(stderr, "[web] cannot read the disc image\n");std::uint32_t entry = 0;+ ps2::load_patches("/game/patches.txt");if (!ps2::load_elf("/game/core.elf", entry)) {std::fprintf(stderr, "cannot load the game executable\n");return nullptr;@@ -356,6 +358,7 @@ int main(int argc, char **argv) {const std::string a = argv[i];if (a == "--arg" && i + 1 < argc) launch.args.push_back(argv[++i]);else if (a == "--frames" && i + 1 < argc) ps2::g_options.max_frames = std::strtoull(argv[++i], nullptr, 10);+ else if (a == "--widescreen") ps2::g_options.widescreen = true;else if (a == "--press" && i + 1 < argc) {ps2::Press press;if (ps2::parse_press(argv[++i], press)) ps2::g_options.presses.push_back(press);@@ -428,7 +431,7 @@ int main(int argc, char **argv) {return 1;}const std::function<void(const std::uint32_t *, std::uint32_t, std::uint32_t)> blit = [](const std::uint32_t *rgba, std::uint32_t width, std::uint32_t height) {- ps2web_blit(rgba, static_cast<int>(width), static_cast<int>(height));+ ps2web_blit(rgba, static_cast<int>(width), static_cast<int>(height), ps2::g_options.widescreen ? 1 : 0);};const std::function<void(const std::uint32_t *, std::uint32_t, std::uint32_t)> none;const std::function<void()> wait_shown = [] {diff --git a/host/window.cpp b/host/window.cppindex 509d01b..8289130 100644--- a/host/window.cpp+++ b/host/window.cpp@@ -217,7 +217,7 @@ void show_pixels(const std::uint32_t *rgba, std::uint32_t w, std::uint32_t h) {if (w != g_tex_w || h != g_tex_h) {if (g_texture) SDL_DestroyTexture(g_texture);g_texture = SDL_CreateTexture(g_renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, static_cast<int>(w), static_cast<int>(h));- SDL_RenderSetLogicalSize(g_renderer, static_cast<int>(w), static_cast<int>(w) * 3 / 4);+ SDL_RenderSetLogicalSize(g_renderer, static_cast<int>(w), static_cast<int>(w) * (ps2::g_options.widescreen ? 9 : 3) / (ps2::g_options.widescreen ? 16 : 4));g_tex_w = w;g_tex_h = h;}@@ -314,7 +314,7 @@ bool open_window(bool fullscreen) {return false;}const Uint32 flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI | (fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0u);- g_window = SDL_CreateWindow("ps2-web-recomp", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 960, 720, flags);+ g_window = SDL_CreateWindow("ps2-web-recomp", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, ps2::g_options.widescreen ? 1280 : 960, 720, flags);if (!g_window) {std::fprintf(stderr, "SDL: %s\n", SDL_GetError());return false;diff --git a/runtime/include/ps2/system.hpp b/runtime/include/ps2/system.hppindex 1018867..d794aee 100644--- a/runtime/include/ps2/system.hpp+++ b/runtime/include/ps2/system.hpp@@ -22,6 +22,13 @@ struct Press {std::uint8_t stick = 0;};+struct Patch {+ std::uint8_t place;+ std::uint8_t bytes;+ std::uint32_t address;+ std::uint64_t value;+};+struct AxisPress {std::uint64_t frame;std::uint32_t frames;@@ -34,6 +41,7 @@ struct Options {bool trace_io = false;bool trace_threads = false;bool pal = true;+ bool widescreen = false;bool rate_forced = false;std::uint64_t max_frames = 0;std::string misses_path;@@ -44,6 +52,7 @@ struct Options {std::uint32_t frame_every = 60;std::vector<Press> presses;std::vector<AxisPress> axis_presses;+ std::vector<Patch> patches;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;@@ -119,6 +128,7 @@ void wake_render_thread();bool copy_frame(std::vector<std::uint32_t> &rgba, std::uint32_t &width, std::uint32_t &height);bool parse_press(const std::string &spec, Press &press);bool parse_axis(const std::string &spec, AxisPress &press);+bool load_patches(const std::string &path);double gpu_busy_ms();void browser_yield();std::uint64_t frames_run();diff --git a/runtime/src/gs/gpu/gpu.cpp b/runtime/src/gs/gpu/gpu.cppindex f3f0992..dc1f3b2 100644--- a/runtime/src/gs/gpu/gpu.cpp+++ b/runtime/src/gs/gpu/gpu.cpp@@ -905,7 +905,8 @@ void submit(WGPUTextureView present_view = nullptr) {rd.colorAttachments = &color;WGPURenderPassEncoder rp = wgpuCommandEncoderBeginRenderPass(enc, &rd);const float w = static_cast<float>(g_surface_width), h = static_cast<float>(g_surface_height);- const float vw = std::min(w, h * 4.0f / 3.0f), vh = vw * 3.0f / 4.0f;+ const float aspect = g_options.widescreen ? 16.0f / 9.0f : 4.0f / 3.0f;+ const float vw = std::min(w, h * aspect), vh = vw / aspect;wgpuRenderPassEncoderSetViewport(rp, (w - vw) * 0.5f, (h - vh) * 0.5f, vw, vh, 0.0f, 1.0f);wgpuRenderPassEncoderSetPipeline(rp, g_blit);wgpuRenderPassEncoderSetBindGroup(rp, 0, g_blit_group, 0, nullptr);@@ -1744,7 +1745,8 @@ bool present(const DisplaySource &src) {const std::uint32_t param = push_params({src.fbp, src.fbw, src.psm, src.dbx, src.dby, src.width, src.height, src.halved ? 1u : 0u, current});g_commands.push_back({kDisplay, (src.width * g_scale + 7) / 8, (src.height * g_scale + 7) / 8, param});const float sw = static_cast<float>(g_surface_width), sh = static_cast<float>(g_surface_height);- const float vw = std::min(sw, sh * 4.0f / 3.0f), vh = vw * 3.0f / 4.0f;+ const float aspect = g_options.widescreen ? 16.0f / 9.0f : 4.0f / 3.0f;+ const float vw = std::min(sw, sh * aspect), vh = vw / aspect;const std::uint32_t blit[8] = {src.width * g_scale, src.height * g_scale, current, previous, blend ? 1u : 0u, static_cast<std::uint32_t>(vw), static_cast<std::uint32_t>(vh), 0};wgpuQueueWriteBuffer(g_queue, g_blit_params, 0, blit, sizeof blit);++g_field;diff --git a/runtime/src/kernel.cpp b/runtime/src/kernel.cppindex 60eb712..4e5b000 100644--- a/runtime/src/kernel.cpp+++ b/runtime/src/kernel.cpp@@ -380,6 +380,7 @@ void reset() {g_next_handler = 1;g_in_handler = g_reschedule = false;g_pending_alarms.clear();+ g_osd_config = g_options.widescreen ? 2u << 1 : 0u;std::memset(g_ram + kSyscallTable, 0, 0x400);}diff --git a/runtime/src/system.cpp b/runtime/src/system.cppindex d03b867..35802ac 100644--- a/runtime/src/system.cpp+++ b/runtime/src/system.cpp@@ -138,10 +138,23 @@ void time_frames() {}}+void apply_patches(bool boot) {+ for (const Patch &p : g_options.patches) {+ if (boot ? p.place == 1 : p.place == 0) continue;+ switch (p.bytes) {+ case 1: st8(p.address, static_cast<std::uint8_t>(p.value)); break;+ case 2: st16(p.address, static_cast<std::uint16_t>(p.value)); break;+ case 4: st32(p.address, static_cast<std::uint32_t>(p.value)); break;+ default: st64(p.address, p.value); break;+ }+ }+}+void vblank() {++g_frames;time_frames();apply_presses();+ apply_patches(false);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()));@@ -384,6 +397,7 @@ void boot(std::uint32_t entry, const std::vector<std::string> &args) {}store<std::uint32_t>(g_ram + argv + 4 * guest_args.size(), 0);kernel::start_main_thread(entry, 0, static_cast<std::uint32_t>(guest_args.size()), argv);+ apply_patches(true);schedule(hw::kEventVblank, frame_cycles(), vblank);}@@ -533,6 +547,18 @@ bool parse_press(const std::string &spec, Press &press) {return true;}+bool load_patches(const std::string &path) {+ std::FILE *f = std::fopen(path.c_str(), "r");+ if (!f) return false;+ unsigned place = 0, bytes = 0;+ unsigned long address = 0;+ unsigned long long value = 0;+ while (std::fscanf(f, "%u %lx %u %llx", &place, &address, &bytes, &value) == 4)+ g_options.patches.push_back({static_cast<std::uint8_t>(place), static_cast<std::uint8_t>(bytes), static_cast<std::uint32_t>(address), value});+ std::fclose(f);+ return true;+}+bool parse_axis(const std::string &spec, AxisPress &press) {static const char *const kNames[4] = {"rx", "ry", "lx", "ly"};std::size_t at = 0;diff --git a/scripts/build_web.sh b/scripts/build_web.shindex a5b610f..d4bdfce 100755--- a/scripts/build_web.sh+++ b/scripts/build_web.sh@@ -7,7 +7,8 @@ game=${1:-gt4}emsdk=${2:-${EMSDK:-$here/tools/emsdk}}out="$here/build/web-$game"boot=$(sed -n 's/^BOOT2 *= *//p' "$here/games/$game/disc/SYSTEM.CNF" | tr -d '\r')-elf="$here/games/$game/core.elf"+elf=$(ls "$here/games/$game/patched/"* 2>/dev/null | head -1)+[ -n "$elf" ] || elf="$here/games/$game/core.elf"if [ ! -f "$elf" ]; thenname=${boot#*\\}elf="$here/games/$game/disc/${name%;*}"@@ -16,7 +17,8 @@ mkdir -p "$out"printf '%s\n' "$boot" > "$out/boot.txt"source "$emsdk/emsdk_env.sh" > /dev/null 2>&1emcmake cmake -S "$here" -B "$out" -G Ninja -DCMAKE_BUILD_TYPE=Release \- -DPS2_GENERATED="$here/generated/$game" -DPS2_WEB_ELF="$elf" -DPS2_WEB_BOOT_FILE="$out/boot.txt"+ -DPS2_GENERATED="$here/generated/$game" -DPS2_WEB_ELF="$elf" -DPS2_WEB_BOOT_FILE="$out/boot.txt" \+ -DPS2_WEB_PATCHES="$([ -f "$here/games/$game/patches.txt" ] && echo "$here/games/$game/patches.txt")"ninja -C "$out" ps2webgzip -kf9 "$out/ps2web.wasm" "$out/ps2web.data" "$out/ps2web.js"printf 'built %s/ps2web.html; serve it with scripts/serve.py %q %q\n' "$out" "build/web-$game" "games/$game/disc.iso"diff --git a/scripts/pnach.py b/scripts/pnach.pynew file mode 100755index 0000000..13ccca0--- /dev/null+++ b/scripts/pnach.py@@ -0,0 +1,112 @@+#!/usr/bin/env python3+import struct+import sys++USAGE = 'usage: pnach.py crc <elf> | pnach.py apply <elf> <patched elf> <runtime list> [--section NAME]... <pnach>...'+SIZES = {'byte': 1, 'short': 2, 'word': 4, 'double': 8, 'beshort': 2, 'beword': 4, 'bedouble': 8}+EXTENDED = {0: 1, 1: 2, 2: 4}+++def crc(data):+ value = 0+ for (word,) in struct.iter_unpack('<I', data[:len(data) & ~3]):+ value ^= word+ return value+++def segments(elf):+ phoff, = struct.unpack_from('<I', elf, 28)+ phentsize, phnum = struct.unpack_from('<HH', elf, 42)+ for i in range(phnum):+ kind, offset, vaddr, _, filesz = struct.unpack_from('<5I', elf, phoff + i * phentsize)+ if kind == 1 and filesz:+ yield vaddr & 0x1FFFFFFF, offset, filesz+++def parse(path, wanted, sections, skipped):+ patches = []+ section = None+ for number, raw in enumerate(open(path, encoding='utf-8', errors='replace'), 1):+ line = raw.split('//', 1)[0].strip()+ if line.startswith('[') and line.endswith(']'):+ section = line[1:-1].strip()+ sections.setdefault(section, {'used': section in wanted, 'aspect': None})+ continue+ if section is not None and section not in wanted:+ continue+ if line.lower().startswith('gsaspectratio=') and section is not None:+ sections[section]['aspect'] = line.split('=', 1)[1].strip()+ if not line.lower().startswith('patch='):+ continue+ fields = [f.strip() for f in line[6:].split(',')]+ if len(fields) != 5:+ skipped.append('%s:%d malformed' % (path, number))+ continue+ place, cpu, address, kind, value = fields+ kind = kind.lower()+ if cpu.upper() != 'EE':+ skipped.append('%s:%d %s patch' % (path, number, cpu))+ continue+ try:+ place, address, value = int(place), int(address, 16), int(value, 16)+ except ValueError:+ skipped.append('%s:%d malformed' % (path, number))+ continue+ if kind == 'extended':+ size = EXTENDED.get(address >> 28)+ if not size:+ skipped.append('%s:%d extended code type %X' % (path, number, address >> 28))+ continue+ address &= 0x0FFFFFFF+ elif kind in SIZES:+ size = SIZES[kind]+ if kind.startswith('be'):+ value = int.from_bytes(value.to_bytes(size, 'big'), 'little')+ else:+ skipped.append('%s:%d %s patch' % (path, number, kind))+ continue+ patches.append((place, address & 0x1FFFFFFF, size, value & ((1 << (8 * size)) - 1)))+ return patches+++def main():+ if len(sys.argv) == 3 and sys.argv[1] == 'crc':+ print('%08X' % crc(open(sys.argv[2], 'rb').read()))+ return+ if len(sys.argv) < 6 or sys.argv[1] != 'apply':+ sys.exit(USAGE)+ elf = bytearray(open(sys.argv[2], 'rb').read())+ args, wanted, files = sys.argv[5:], set(), []+ while args:+ if args[0] == '--section' and len(args) > 1:+ wanted.add(args[1])+ args = args[2:]+ else:+ files.append(args.pop(0))+ skipped, patches, sections = [], [], {}+ for path in files:+ patches += parse(path, wanted, sections, skipped)+ loads = list(segments(elf))+ in_elf = 0+ for place, address, size, value in patches:+ for vaddr, offset, filesz in loads:+ if vaddr <= address and address + size <= vaddr + filesz:+ at = offset + address - vaddr+ elf[at:at + size] = value.to_bytes(size, 'little')+ in_elf += 1+ break+ open(sys.argv[3], 'wb').write(elf)+ with open(sys.argv[4], 'w') as out:+ for place, address, size, value in patches:+ out.write('%d %08X %d %X\n' % (place, address, size, value))+ print('%d patches, %d of them in the executable' % (len(patches), in_elf))+ for name, info in sections.items():+ print('%s [%s]%s' % ('applied' if info['used'] else 'left out', name, ', meant for a %s screen' % info['aspect'] if info['aspect'] else ''))+ for name in sorted(wanted - set(sections)):+ print('no section named [%s]' % name)+ for reason in skipped:+ print('skipped', reason)+++if __name__ == '__main__':+ main()diff --git a/scripts/port.sh b/scripts/port.shindex a2005e3..01717f7 100755--- a/scripts/port.sh+++ b/scripts/port.sh@@ -20,12 +20,18 @@ options:--rounds N exploring runs at most (default 8)--no-explore translate and build without running the game--native-only skip the browser build and the Emscripten SDK it needs+ --pnach FILE apply a PCSX2 patch file, repeatable; patches that land in+ the executable are translated with it, the rest are+ written into memory at boot or every frame+ --pnach-section S also apply the patches under [S] in those files, the way+ enabling them in PCSX2 does; lines outside any section+ always applyEOF}[ $# -ge 2 ] || { usage; exit 2; }name="$1"; source_path="$2"; shift 2-frames=3600; rounds=8; explore=1; web=1; presses=()+frames=3600; rounds=8; explore=1; web=1; presses=(); pnach=()while [ $# -gt 0 ]; docase "$1" in--frames) frames="$2"; shift ;;@@ -33,6 +39,8 @@ while [ $# -gt 0 ]; do--rounds) rounds="$2"; shift ;;--no-explore) explore=0 ;;--native-only) web=0 ;;+ --pnach) pnach+=("$(realpath "$2")"); shift ;;+ --pnach-section) pnach=(--section "$2" "${pnach[@]}"); shift ;;-h|--help) usage; exit 0 ;;*) echo "unknown option $1" >&2; exit 2 ;;esac@@ -81,6 +89,7 @@ program=${program%;*}[ -n "$program" ] || { echo "SYSTEM.CNF names no BOOT2 program" >&2; exit 1; }python3 -I "$here/disc.py" extract "$iso" "$game/disc" "$program" > /dev/nullecho "boots $boot"+echo "PCSX2 patch files for it end in _$(python3 -I "$here/pnach.py" crc "$game/disc/$program").pnach"echo "== [2/6] executable"elf="$game/disc/$program"@@ -91,6 +100,12 @@ elif python3 -I "$here/disc.py" list "$iso" | awk '{print $4}' | grep -qx CORE.Gpython3 -I "$here/gt4_core.py" "$game/disc/CORE.GT4" "$game/core.elf" > /dev/nullelf="$game/core.elf"fi+rm -rf "$game/patched" "$game/patches.txt"+if [ ${#pnach[@]} -gt 0 ]; then+ mkdir -p "$game/patched"+ python3 -I "$here/pnach.py" apply "$elf" "$game/patched/$(basename "$elf")" "$game/patches.txt" "${pnach[@]}"+ elf="$game/patched/$(basename "$elf")"+fiecho "${elf#$ROOT/}"modules=()if grep -q SNR2 "$elf"; then@@ -171,4 +186,6 @@ if [ "$web" = 1 ]; thenprintf 'Done. Serve it with: python3 scripts/serve.py %q %q\n' "build/web-$name" "games/$name/disc.iso"echo "and open http://localhost:8620/"fi-printf 'Play it natively: %q %q --disc %q --window\n' "build/native-$name/ps2run" "${elf#$ROOT/}" "games/$name/disc.iso"+play=$(printf '%q %q --disc %q --window' "build/native-$name/ps2run" "${elf#$ROOT/}" "games/$name/disc.iso")+[ -f "$game/patches.txt" ] && play="$play --patches $(printf '%q' "games/$name/patches.txt")"+echo "Play it natively: $play"diff --git a/web/shell.html b/web/shell.htmlindex 4d09f55..41aa0ec 100644--- a/web/shell.html+++ b/web/shell.html@@ -21,6 +21,7 @@.controls { display: none; }body.touch { overscroll-behavior: none; touch-action: none; -webkit-user-select: none; user-select: none; }body.touch #stage { flex: none; width: 100%; aspect-ratio: 4 / 3; max-height: 60vh; }+ body.touch.wide #stage { aspect-ratio: 16 / 9; }body.touch .controls {flex: 1; display: grid; grid-template-columns: 1fr 1fr; grid-template-areas: "mid mid" "left right";gap: 10px 8px; align-content: center; padding: 8px 12px calc(8px + env(safe-area-inset-bottom));@@ -111,6 +112,10 @@<option value="2">1280×1024</option><option value="3">1920×1536</option></select>+ <select id="aspect" aria-label="Aspect ratio" title="Screen shape the game is told about, the page reloads to apply it">+ <option value="4:3">4:3</option>+ <option value="16:9">16:9</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>@@ -270,6 +275,21 @@ scaleSelect.addEventListener('change', () => {location.href = url.href;});+const aspectSelect = document.getElementById('aspect');+let aspect = params.get('aspect');+if (!aspect) {+ try { aspect = localStorage.getItem('ps2web-aspect'); } catch (e) {}+}+aspect = aspect === '16:9' ? '16:9' : '4:3';+aspectSelect.value = aspect;+document.body.classList.toggle('wide', aspect === '16:9');+aspectSelect.addEventListener('change', () => {+ try { localStorage.setItem('ps2web-aspect', aspectSelect.value); } catch (e) {}+ const url = new URL(location.href);+ url.searchParams.delete('aspect');+ location.href = url.href;+});+const controlsButton = document.getElementById('controls-toggle');let hideControls = false;try { hideControls = localStorage.getItem('ps2web-hide-controls') === '1'; } catch (e) {}@@ -549,7 +569,7 @@ const countShown = () => {requestAnimationFrame(countShown);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]))),+ arguments: ['/game/core.elf'].concat(params.has('arg') ? ['--arg', params.get('arg')] : [], aspect === '16:9' ? ['--widescreen'] : [], 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'),