#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Board frames against krom's reference pictures (and Mesen2's frames). nice .venv-pypy/bin/python scripts/ppu_pictures.py tests/test_roms/krom/PPU \ [--frames 60] [--mesen DIR] [--out DIR] [--jobs 8] [--only NAME ...] For every ``.sfc`` with a ``.png`` of the same name beside it (case ignored: krom's ``RedspaceHDMA.png``), runs the board for ``--frames`` frames and compares its picture with the PNG at 5 bits per channel (the SNES's own depth: both sides' 8-bit values shifted right by 3). A board picture half the reference's width or height is doubled first (krom's 512x448 pictures of interlaced or hi-res screens). ``--mesen DIR`` also compares with Mesen2 frames made by ``scripts/mesen_frames.py`` (a closed box: OBSERVED). ``--out DIR`` keeps the board's pictures. Prints one line per ROM: exact / near (only one-step 8-bit differences) / N pixels differ, and a total. Tier: krom's pictures are emulator screenshots shipped with the demos (his README says the ROMs were tested on a console; the pictures themselves are not hardware captures), so a match is tier 3 evidence. """ from __future__ import annotations import argparse import concurrent.futures import os import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from snes_python.board import SNES # noqa: E402 from snes_python.cartridge import Cartridge # noqa: E402 from snes_python.ppu_png import read_png, write_png # noqa: E402 def reference_for(rom: Path) -> Path | None: for png in rom.parent.glob("*.png"): if png.stem.lower() == rom.stem.lower(): return png return None def scale(width: int, height: int, rgb: bytearray, to_w: int, to_h: int) -> bytearray | None: """Double columns and/or rows to reach (to_w, to_h); None if impossible.""" if (width, height) == (to_w, to_h): return rgb fx = to_w // width if to_w % width == 0 else 0 fy = to_h // height if to_h % height == 0 else 0 if fx not in (1, 2) or fy not in (1, 2): return None out = bytearray(to_w * to_h * 3) o = 0 for y in range(to_h): row = (y // fy) * width * 3 for x in range(to_w): i = row + (x // fx) * 3 out[o : o + 3] = rgb[i : i + 3] o += 3 return out def differ(a: bytearray, b: bytearray, n_pixels: int) -> tuple[int, int]: """(pixels whose 5-bit values differ, pixels off by 8 or more in 8 bits). The second count forgives the 8-bit converter of whatever program saved the reference (krom's CPUAND.png shows colour 30 as 248, CPUDEC.png as 247) but still sees any real 5-bit difference of two steps or more. """ strict = loose = 0 for p in range(n_pixels): i = p * 3 if ( a[i] >> 3 != b[i] >> 3 or a[i + 1] >> 3 != b[i + 1] >> 3 or a[i + 2] >> 3 != b[i + 2] >> 3 ): strict += 1 if ( abs(a[i] - b[i]) >= 8 or abs(a[i + 1] - b[i + 1]) >= 8 or abs(a[i + 2] - b[i + 2]) >= 8 ): loose += 1 return strict, loose def compare(picture: tuple[int, int, bytearray], png: Path) -> str: w, h, rgb = picture rw, rh, ref = read_png(png) # krom's HiColor1241DLair.png is 256x225: compare the first 224 lines. if rh == h + 1 and rw == w: rh = h ref = ref[: rw * rh * 3] scaled = scale(w, h, rgb, rw, rh) if scaled is None: return f"size {w}x{h} vs {rw}x{rh}" strict, loose = differ(scaled, ref, rw * rh) if strict == 0: return "exact" if loose == 0: return f"near ({strict} px one step)" return f"{strict} px ({loose} by 8+)" def run_one(rom: Path, frames: int, mesen: Path | None, out: Path | None) -> str: ref = reference_for(rom) start = time.time() try: snes = SNES(Cartridge(rom.read_bytes())) snes.run_frames(frames) picture = snes.ppu.picture() except Exception as error: # noqa: BLE001 - one ROM's failure is a result return f"{rom.stem}\terror {type(error).__name__}: {error}" if out is not None: write_png(out / f"{rom.stem}.png", *picture) fields = [rom.stem, f"krom {compare(picture, ref)}" if ref else "krom -"] if mesen is not None: frame = mesen / f"{rom.stem}.png" fields.append(f"mesen {compare(picture, frame)}" if frame.exists() else "mesen -") fields.append(f"{time.time() - start:.0f}s") return "\t".join(fields) def run_detectors(rom: Path, frames: int, folder: Path, out: Path | None) -> str: """The board against the saved MAME and Mesen2 frames of one ROM.""" start = time.time() try: snes = SNES(Cartridge(rom.read_bytes())) snes.run_frames(frames) picture = snes.ppu.picture() except Exception as error: # noqa: BLE001 return f"{rom.stem}\terror {type(error).__name__}: {error}" if out is not None: write_png(out / f"{rom.stem}.png", *picture) fields = [rom.stem] for name in ("mesen", "mame"): frame = folder / f"{name}.png" fields.append(f"{name} {compare(picture, frame)}" if frame.exists() else f"{name} -") fields.append(f"{time.time() - start:.0f}s") return "\t".join(fields) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("folder", type=Path) parser.add_argument("--frames", type=int, default=60) parser.add_argument("--mesen", type=Path) parser.add_argument("--out", type=Path) parser.add_argument("--jobs", type=int, default=8) parser.add_argument("--only", nargs="*", default=[]) parser.add_argument("--all", action="store_true", help="every ROM, not only those with a picture") parser.add_argument( "--detectors", action="store_true", help="FOLDER is tests/detector_frames: compare with each ROM's saved mesen.png and" " mame.png (300 frames, detectors_compare.py's run length); ROMs found under" " tests/test_roms by name", ) args = parser.parse_args() if args.detectors: sources = {p.stem: p for p in (ROOT / "tests" / "test_roms").rglob("*.sfc")} jobs = [ (sources[d.name], d) for d in sorted(args.folder.iterdir()) if d.name in sources and (not args.only or d.name in args.only) ] frames = args.frames if args.frames != 60 else 300 with concurrent.futures.ProcessPoolExecutor(args.jobs) as pool: futures = [pool.submit(run_detectors, r, frames, d, args.out) for r, d in jobs] for future in futures: print(future.result(), flush=True) return 0 if args.out: args.out.mkdir(parents=True, exist_ok=True) roms = sorted( p for p in args.folder.rglob("*.sfc") if (args.all or reference_for(p)) and (not args.only or p.stem in args.only) ) os.environ.setdefault("PYPY_GC_NURSERY", "1M") exact = near = 0 with concurrent.futures.ProcessPoolExecutor(args.jobs) as pool: futures = [pool.submit(run_one, r, args.frames, args.mesen, args.out) for r in roms] for future in futures: line = future.result() exact += "krom exact" in line near += "krom near" in line print(line, flush=True) print( f"total {len(roms)}: {exact} exact against krom's pictures at 5 bits," f" {near} more within one 8-bit step" ) return 0 if __name__ == "__main__": raise SystemExit(main())