#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """The smoke list: each game's frame on the board against Mesen2's (a closed-box detector). Two steps, because Mesen2's runner needs Pillow (system Python) and the board wants PyPy: EMU_TOOLS_GPL=... python3 -I scripts/smoke.py mesen PYPY_GC_NURSERY=1M nice .venv-pypy/bin/python -I scripts/smoke.py board --jobs 6 Games come from ``tests/smoke.txt`` (names in ``$NO_INTRO_DIR/Nintendo - Super Nintendo Entertainment System``); ``--only TEXT`` keeps those whose name holds TEXT. Frames are compared at each ``--at`` checkpoint (default 300 and 900 frames from power-on, no input: title and attract screens). The two machines reset in different phases, so Mesen2's frame is saved from six frames before the checkpoint to three after (uncropped), and the board's frame is matched with each, at the vertical alignments Mesen2's frame allows (its 239-line frame starts 7 rows above line 1 for 224-line pictures; an overscan picture fills it): the verdict is ``exact@k`` (k = Mesen2's frame minus the board's), ``near`` (one 5-bit step) or the fewest differing pixels. A difference is a lead, not a judgement (docs/restart.md rule 6): Mesen2's values are OBSERVED. Mesen2 runs as mesen2-runner (``$EMU_TOOLS_GPL/tools/mesen2/run.py --machine snes``, a GPL tool run as a separate program; ``scripts/emu_tools.py``), with ``--region auto``. Since 2026-11-24 its frames repeat run for run: power-on RAM is zeros (the runner's default, in each run's manifest) and every frame is drawn. The old driver (``mesen_run.py``, until 2026-11-24) left Mesen2's random power-on memory and its frame skipping on, so its frames could differ from run to run (SMW at frame 900 was exact in one run and 3,477 pixels off in the next). Mesen2 is a detector, not a reference; a still screen matches at any offset, so ``exact@-6`` there says nothing about phase. ``--window W`` (board side) also compares the board's frames W either side of each checkpoint, nearest offset first, so a reset-phase lag of up to W frames still shows as ``exact@k``. Everything is written under ``tests/mame_traces/smoke/`` (gitignored: pictures of commercial games are never committed). """ from __future__ import annotations import argparse import concurrent.futures import functools import os import sys import tempfile import time import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) # run with -I: the script directory is not on the path OUT = ROOT / "tests" / "mame_traces" / "smoke" LIST = ROOT / "tests" / "smoke.txt" OFFSETS = (-6, -5, -4, -3, -2, -1, 0, 1, 2, 3) def games(only: str | None) -> list[str]: names = [] for line in LIST.read_text(encoding="utf-8").splitlines(): name = line.split("#", 1)[0].strip() if name and (only is None or only.lower() in name.lower()): names.append(name) return names def image_of(name: str) -> bytes: folder = ( Path(os.environ.get("NO_INTRO_DIR", "")) / "Nintendo - Super Nintendo Entertainment System" ) with zipfile.ZipFile(folder / f"{name}.zip") as z: inner = [n for n in z.namelist() if n.lower().endswith((".sfc", ".smc"))] return z.read(inner[0]) def slug(name: str) -> str: return "".join(c if c.isalnum() else "_" for c in name)[:60] # -- Mesen2 ------------------------------------------------------------------------- def mesen_game(name: str, checkpoints: list[int]) -> str: from emu_tools import mesen2_frames # (scripts/ is on the path: above) from PIL import Image folder = OUT / slug(name) folder.mkdir(parents=True, exist_ok=True) wanted = [ at + k for at in checkpoints for k in OFFSETS if not (folder / f"mesen-raw-{at + k:05d}.png").exists() ] if not wanted: return f"ok\t{name}" with tempfile.TemporaryDirectory() as tmp: rom = Path(tmp) / "game.sfc" rom.write_bytes(image_of(name)) # One mesen2-runner run per game, every frame from it (--frames-at, runner 0.3.0). # --region auto keeps the old driver's region (Mesen2's own). got = mesen2_frames(rom, wanted, Path(tmp) / "runs", region="auto") for n in wanted: if got[n] is None: return f"no frame\t{name}" Image.open(got[n]).convert("RGB").save(folder / f"mesen-raw-{n:05d}.png") return f"ok\t{name}" # -- the board -------------------------------------------------------------------- def aligned_difference(picture: tuple, frame: tuple) -> tuple[int, int]: """(pixels whose 5-bit values differ, pixels off by 8+), at the best vertical alignment. The board's picture is 224 or 239 lines (x2 in interlace), 256 or 512 wide; Mesen2's frame is 256x239 or 512x478 (docs/validation.md: a 224-line picture starts 7 rows down). The board's picture is doubled to Mesen2's width and height scale if needed. """ sys.path.insert(0, str(ROOT / "scripts")) from ppu_pictures import differ, scale w, h, rgb = picture mw, mh, ref = frame fy = 2 if mh > 300 and h < 300 else 1 fx = mw // w if mw % w == 0 else 1 if fx != 1 or fy != 1: rgb = scale(w, h, rgb, w * fx, h * fy) or rgb w, h = w * fx, h * fy if w != mw: return (10**9, 10**9) unit = 2 if mh > 300 else 1 best = (10**9, 10**9) for top in (7 * unit, 0, unit, 8 * unit, 6 * unit): rows = min(h, mh - top) if rows <= 0: continue a = rgb[: rows * w * 3] b = ref[top * w * 3 : (top + rows) * w * 3] best = min(best, differ(a, b, rows * w)) if best[0] == 0: break return best def board_game(name: str, checkpoints: list[int], ipl: bytes, window: int = 0) -> str: sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "scripts")) from snes_python.board import SNES from snes_python.cartridge import Cartridge from snes_python.ppu_png import read_png, write_png folder = OUT / slug(name) folder.mkdir(parents=True, exist_ok=True) began = time.monotonic() fields = [name] try: snes = SNES(Cartridge(image_of(name)), ipl=ipl) done = 0 for at in checkpoints: mesen = { k: read_png(folder / f"mesen-raw-{at + k:05d}.png") for k in OFFSETS if (folder / f"mesen-raw-{at + k:05d}.png").exists() } # With --window W the board's frames at-W .. at+W are compared too, nearest offset # (Mesen2 frame minus board frame) first: a phase lag beyond OFFSETS shows. pictures = {} for lag in range(window, -window - 1, -1): snes.run_frames(at - lag - done) done = at - lag pictures[lag] = snes.ppu.picture() write_png(folder / f"board-{at:05d}.png", *pictures[0]) best = None pairs = sorted( ((lag, k) for lag in pictures for k in mesen), key=lambda t: (abs(t[0] + t[1]), t) ) for lag, k in pairs: strict, loose = aligned_difference(pictures[lag], mesen[k]) if best is None or (strict, loose) < best[:2]: best = (strict, loose, k + lag) if strict == 0: break if best is None: fields.append(f"{at}: no Mesen2 frame") elif best[0] == 0: fields.append(f"{at}: exact@{best[2]:+d}") elif best[1] == 0: fields.append(f"{at}: near@{best[2]:+d}") else: fields.append(f"{at}: {best[0]} px ({best[1]} by 8+)@{best[2]:+d}") except Exception as error: # noqa: BLE001 - one game's failure is a result fields.append(f"error {type(error).__name__}: {error}") fields.append(f"{time.monotonic() - began:.0f} s") return "\t".join(fields) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("side", choices=["mesen", "board"]) parser.add_argument("--at", type=int, action="append", help="checkpoint frames") parser.add_argument("--only") parser.add_argument("--jobs", type=int, default=4) parser.add_argument( "--window", type=int, default=0, help="board: also compare the W frames either side of each checkpoint", ) args = parser.parse_args() checkpoints = sorted(args.at or [300, 900]) names = games(args.only) if args.side == "mesen": import emu_tools emu_tools.require(emu_tools.MESEN2_RUN) # exit 3, naming EMU_TOOLS_GPL, without it work = functools.partial(mesen_game, checkpoints=checkpoints) else: sys.path.insert(0, str(ROOT / "scripts")) from mame_lockstep import ipl_rom work = functools.partial( board_game, checkpoints=checkpoints, ipl=ipl_rom(), window=args.window ) pool_type = ( concurrent.futures.ThreadPoolExecutor if args.side == "mesen" else concurrent.futures.ProcessPoolExecutor ) with pool_type(args.jobs) as pool: for line in pool.map(work, names): print(line, flush=True) return 0 if __name__ == "__main__": sys.exit(main())