#!/usr/bin/env python3 """Save states on real cartridges: one of every board the sweep found, and a disk. For each, a system runs for a while, is saved in the middle of a frame, and runs on; a second system built from the same files, run a different length first, loads the state and runs the same frames. Frames, sound, CPU, RAM and video memory must match (``tests/test_state.py`` does this on a program of its own). The cartridges come from the sweep's records (``tests/compat/*.csv``): the first one of each board. python scripts/state_roundtrip.py # every board, 5 s before the save python scripts/state_roundtrip.py --seconds 8 --match Sonic """ from __future__ import annotations import argparse import contextlib import csv import sys from concurrent.futures import ProcessPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parent.parent sys.path[:0] = [str(ROOT / "src"), str(ROOT / "scripts")] import romsets # noqa: E402 from lockstep_mame import load_bios # noqa: E402 from sms_python.board import MACHINES # noqa: E402 from sms_python.cartridge import Cartridge, load_image # noqa: E402 from sms_python.state import load_state, save_state # noqa: E402 from sms_python.system import System # noqa: E402 CLOCK = 3_579_545 # The machine each romset runs on here, and extra machines for one cartridge each. SYSTEMS = {"sg1000": "sg1000", "mastersystem": "sms2", "gamegear": "gamegear"} EXTRA = ( ("mastersystem", "Sonic The Hedgehog (USA, Europe, Brazil) (En)", "megadrive-pbc"), ("mastersystem", "Sonic The Hedgehog (USA, Europe, Brazil) (En)", "sms1pal"), ("mastersystem", "Phantasy Star (Japan)", "smsj"), # the FM chip playing ("mastersystem", "Sonic The Hedgehog (USA, Europe, Brazil) (En)", "ggsms"), ("sg1000", "BASIC Level III (Europe, Australia, New Zealand) (SC-3000) (Program)", "sc3000"), ) def build(path: Path, machine: str, board: str) -> System: if MACHINES[machine].disk_unit: disk = bytearray(load_image(path)) return System(MACHINES[machine], None, load_bios("sf7000"), disk=disk) cartridge = Cartridge.from_file(path, board=board or None) return System(MACHINES[machine], cartridge) def trace(system: System, frames: int) -> list[tuple]: out = [] for _ in range(frames): frame = system.run_frame() vdp = system.board.vdp out.append( ( tuple(map(tuple, frame)), tuple(system.board.take_samples()), system.cpu.capture_state(), (system.cycles, system.instructions, vdp.line, vdp.m), bytes(vdp.vram), bytes(vdp.cram), bytes(system.board.ram), ) ) return out def run_one(job: tuple[str, str, str, int]) -> tuple[str, str, str, str]: path, machine, board, seconds = job name = Path(path).stem try: first = build(Path(path), machine, board) while first.cycles < seconds * CLOCK: first.run_frame() first.board.take_samples() first.run_cycles(23_456) # into the middle of a frame state = save_state(first) expected = trace(first, 30) second = build(Path(path), machine, board) for _ in range(11): second.run_frame() load_state(second, state) got = trace(second, 30) except Exception as error: return name, machine, board, f"error: {type(error).__name__}: {error}"[:160] if got == expected: return name, machine, board, f"same ({len(state):,} bytes)" frame = next(i for i, (a, b) in enumerate(zip(got, expected, strict=True)) if a != b) part = next( i for i, (a, b) in enumerate(zip(got[frame], expected[frame], strict=True)) if a != b ) what = ("picture", "sound", "CPU", "counters", "VRAM", "CRAM", "RAM")[part] return name, machine, board, f"DIFFERS at frame {frame}: {what}" def jobs(seconds: int, match: str | None) -> list[tuple[str, str, str, int]]: found: list[tuple[str, str, str, int]] = [] for system, machine in SYSTEMS.items(): record = ROOT / "tests" / "compat" / f"{system}.csv" if not record.exists(): continue boards: set[str] = set() for row in csv.DictReader(record.open(encoding="utf-8")): board = row["board"] if board in boards or row["status"] not in ("same", "differs"): continue boards.add(board) path = romsets.find(system, row["name"]) if board == "sf7000": found.append((str(path), "sf7000", "", max(seconds, 8))) # the IPL is loading else: found.append((str(path), machine, board, seconds)) for system, name, machine in EXTRA: with contextlib.suppress(FileNotFoundError): # not in this mirror found.append((str(romsets.find(system, name)), machine, "", seconds)) return [job for job in found if match is None or match.lower() in job[0].lower()] def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--seconds", type=int, default=5, help="time run before the save") parser.add_argument("--jobs", type=int, default=16) parser.add_argument("--match", help="only cartridges whose path contains this") args = parser.parse_args() failed = 0 with ProcessPoolExecutor(args.jobs) as pool: for name, machine, board, verdict in pool.map(run_one, jobs(args.seconds, args.match)): failed += not verdict.startswith("same") print(f"{verdict:<28} {machine:<10} {board:<14} {name}", flush=True) print("all the same" if not failed else f"{failed} not the same") return 1 if failed else 0 if __name__ == "__main__": sys.exit(main())