Skip to content

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

C++

port.sh takes BIN/CUE images and archives holding them

Samir Nuri0d720931ee5a
diff --git a/README.md b/README.md
index 343b36b..606a26b 100644
--- a/README.md
+++ b/README.md
@@ -50,7 +50,7 @@ Along the way it also needed a boot path like the BIOS gives, a module loaded fr
## Port a game of your own
-You need git, CMake, Ninja, a C++20 compiler (clang is preferred and picked up automatically), Python 3, and 7-Zip if your disc image is in a `.7z`. Everything has been run on Linux on x86-64, and the scripts also build on macOS on Apple silicon, where the scripts need a newer bash than the system 3.2 (`brew install bash cmake ninja sevenzip`) and the native runner links wgpu-native against Metal. The first run installs the Emscripten SDK into `tools/emsdk`, or uses the one `EMSDK` points to, and downloads wgpu-native for the native runner. With `--native-only` the script skips the browser build and never installs the SDK; the native window then needs the SDL2 development files. Expect about 300 MB of disk space per game for the generated code and the builds; the disc image itself is linked, not copied.
+You need git, CMake, Ninja, a C++20 compiler (clang is preferred and picked up automatically), Python 3, and 7-Zip if your disc image is in a `.7z`. Everything has been run on Linux on x86-64, and the scripts also build on macOS on Apple silicon, where the scripts need a newer bash than the system 3.2 (`brew install bash cmake ninja sevenzip`) and the native runner links wgpu-native against Metal. The first run installs the Emscripten SDK into `tools/emsdk`, or uses the one `EMSDK` points to, and downloads wgpu-native for the native runner. With `--native-only` the script skips the browser build and never installs the SDK; the native window then needs the SDL2 development files. Expect about 300 MB of disk space per game for the generated code and the builds; an ISO is linked, not copied, while an archive or a BIN is unpacked into `games/<name>/disc.iso`.
```bash
git clone https://github.com/snuri00/ps2-web-recomp.git
@@ -59,7 +59,7 @@ scripts/port.sh mygame "My Game.iso"
python3 scripts/serve.py build/web-mygame games/mygame/disc.iso # http://localhost:8620/
```
-`port.sh` takes a disc image (an ISO, or a ZIP or 7z archive holding one) and does the whole job. It reads the boot program named in the disc's `SYSTEM.CNF`, translates its machine code to C++, and then runs the game headless a few times. Static analysis cannot see every function a game reaches through pointers, so each run writes down the addresses it could not find, the script adds them as entry points and translates again, until a run gets through without new ones. The same runs record the vector unit microprograms the game uploads, which are compiled ahead of time as well. Last it builds the page into `build/web-mygame` and the native runner into `build/native-mygame`. God of War II goes from ISO to page in three and a half minutes on an 8-core laptop.
+`port.sh` takes a disc image (an ISO, a CD dumped as BIN and CUE, or a ZIP or 7z archive holding one) and does the whole job. CD images with 2352-byte sectors are turned into an ISO on the way, so the BIN/CUE pair needs no converting by hand. It reads the boot program named in the disc's `SYSTEM.CNF`, translates its machine code to C++, and then runs the game headless a few times. Static analysis cannot see every function a game reaches through pointers, so each run writes down the addresses it could not find, the script adds them as entry points and translates again, until a run gets through without new ones. The same runs record the vector unit microprograms the game uploads, which are compiled ahead of time as well. Last it builds the page into `build/web-mygame` and the native runner into `build/native-mygame`. God of War II goes from ISO to page in three and a half minutes on an 8-core laptop.
The 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.
diff --git a/scripts/disc.py b/scripts/disc.py
index 474ecef..c57dc50 100644
--- a/scripts/disc.py
+++ b/scripts/disc.py
@@ -2,7 +2,9 @@ import argparse
import fnmatch
import os
import struct
+import shutil
import sys
+import zipfile
SECTOR = 2048
@@ -134,14 +136,54 @@ def modules(image, destination):
print('%d SNR2 modules extracted to %s' % (len(found), destination))
+def open_source(source):
+ lower = source.lower()
+ if lower.endswith('.zip'):
+ archive = zipfile.ZipFile(source)
+ members = archive.infolist()
+ for ending in ('.iso', '.bin', '.img'):
+ found = [m for m in members if m.filename.lower().endswith(ending)]
+ if found:
+ return archive.open(max(found, key=lambda m: m.file_size))
+ sys.exit('no .iso, .bin or .img inside the archive')
+ if lower.endswith('.cue'):
+ with open(source, errors='replace') as cue:
+ for line in cue:
+ parts = line.strip().split('"')
+ if line.strip().upper().startswith('FILE') and len(parts) >= 2:
+ return open(os.path.join(os.path.dirname(source), parts[1]), 'rb')
+ sys.exit('the cue sheet names no file')
+ return open(source, 'rb')
+
+
+def to_iso(source, target):
+ sync = b'\x00' + b'\xff' * 10 + b'\x00'
+ with open_source(source) as src, open(target, 'wb') as dst:
+ first = src.read(2352)
+ if len(first) < 2352 or first[:12] != sync:
+ dst.write(first)
+ shutil.copyfileobj(src, dst, 1 << 24)
+ return
+ start = 16 if first[15] == 1 else 24
+ sector = first
+ while len(sector) == 2352:
+ dst.write(sector[start:start + SECTOR])
+ sector = src.read(2352)
+
+
def main():
parser = argparse.ArgumentParser(description='Read files from PS2 CD and DVD images, including both layers of a DVD9.')
- parser.add_argument('command', choices=['info', 'list', 'extract', 'modules'])
+ parser.add_argument('command', choices=['info', 'list', 'extract', 'modules', 'iso'])
parser.add_argument('image')
parser.add_argument('destination', nargs='?')
parser.add_argument('patterns', nargs='*', help='paths or globs to extract, everything below --limit if omitted')
parser.add_argument('--limit', type=int, default=64, help='MiB; larger files stay in the image unless named')
args = parser.parse_args()
+ if args.command == 'iso':
+ if not args.destination:
+ parser.error('iso needs the .iso file to write')
+ to_iso(args.image, args.destination)
+ return
image = Image(args.image)
if args.command == 'info':
info(image)
diff --git a/scripts/port.sh b/scripts/port.sh
index 01717f7..3e50423 100755
--- a/scripts/port.sh
+++ b/scripts/port.sh
@@ -5,7 +5,7 @@ here="$ROOT/scripts"
usage() {
cat <<'EOF'
-usage: scripts/port.sh <name> <game.iso | game.zip | game.7z> [options]
+usage: scripts/port.sh <name> <game.iso | game.bin | game.cue | game.zip | game.7z> [options]
Turns a PS2 disc image you own into a browser build in build/web-<name> and a
native one in build/native-<name>. It reads the boot program named in
@@ -67,17 +67,7 @@ if [ -e "$iso" ]; then
echo "already in place"
else
case "${source_path,,}" in
- *.zip)
- python3 -I - "$source_path" "$iso" <<'EOF'
-import shutil, sys, zipfile
-with zipfile.ZipFile(sys.argv[1]) as archive:
- images = [m for m in archive.infolist() if m.filename.lower().endswith('.iso')]
- if not images:
- sys.exit('no .iso inside the archive')
- with archive.open(max(images, key=lambda m: m.file_size)) as src, open(sys.argv[2], 'wb') as dst:
- shutil.copyfileobj(src, dst, 1 << 24)
-EOF
- ;;
+ *.zip|*.bin|*.cue|*.img) python3 -I "$here/disc.py" iso "$source_path" "$iso" ;;
*.7z) 7z e -so -r "$source_path" '*.iso' > "$iso" ;;
*) ln -s "$(realpath "$source_path")" "$iso" ;;
esac