# SPDX-License-Identifier: MIT """Milestone 7: every local dump against Atari800's frame at a fixed frame (detectors only). For each distinct payload (No-Intro first, then retrobat images whose payload is not already in the No-Intro set) this runs Atari800 (libatari800, GPL, run as an external library through ``atari800_run.py``, a GPL tool: $EMU_TOOLS_GPL2/tools/atari800/) and the board to frame N, aligns the two screens (colour-register values, compare_atari800.py) and records how many half-clock pixels differ, and whether the board jammed. Atari800 is told the cartridge class the board's loader chose (CART type), so both read the dump the same way. A difference is a question for [AHRM] and Acid5200, never a verdict. python scripts/sweep_atari800.py --frame 900 --out DIR [--shard I/N] [--list FILE] Writes DIR/sweep-I.tsv and, for every image that differs, the two pictures. Temporary copies go to DIR/work-I (ignored) and are removed after each run. The search's offset is kept for comparison with older tables, but the search samples every 8th row and can pick a wrong offset on full-width or sparse screens (build-progress trap 9). So every pair is also compared at the fixed offset (32 colour clocks, 8 lines), with the edge columns $22-$2B and $D4-$DD (where Atari800 departs from [AHRM] 4.3/6.5) counted apart from the interior: columns `interior` and `edge`. With ``--raw`` both frames are saved (DIR/STEM-board.raw 456x262, DIR/STEM-atari800.raw 384x240). """ from __future__ import annotations import argparse import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) sys.path.insert(0, str(ROOT / "scripts")) from compare_atari800 import HEIGHT, WIDTH, atari800_run, best_alignment, compare # noqa: E402 from formats_sweep import images # noqa: E402 from a5200_python.cartridge import CartridgeError, load_cartridge # noqa: E402 from a5200_python.media import write_png # noqa: E402 from a5200_python.system import Console # noqa: E402 CAR_TYPE = {"4k": 20, "8k": 19, "16k-one": 16, "16k-two": 6, "32k": 4, "bbsb": 7} FIXED_DX, FIXED_DY = 64, 8 # half-clocks, lines: Atari800 pixel 0 is colour clock $20 EDGE = frozenset( i for i in range(WIDTH) if 0x22 <= 0x20 + i // 2 <= 0x2B or 0xD4 <= 0x20 + i // 2 <= 0xDD ) def fixed_counts(ours: bytes, theirs: bytes) -> tuple[int, int]: """(interior, edge) differing half-clock pixels at the fixed offset (32, 8).""" interior = edge = 0 for y in range(HEIGHT): row = (y + FIXED_DY) * 456 + FIXED_DX a = ours[row : row + WIDTH] b = theirs[y * WIDTH : (y + 1) * WIDTH] for i, (p, q) in enumerate(zip(a, b)): if p != q: if i in EDGE: edge += 1 else: interior += 1 return interior, edge def atari800(cart: Path, frame: int, kind: int, work: Path) -> bytes | None: pgm = work / "frame.pgm" prefix, env = atari800_run() command = [*prefix, str(cart), "--frames", str(frame), "--every", str(frame), "--pgm", str(pgm), "--cart-type", str(kind), "--work", str(work)] # fmt: skip try: subprocess.run(command, check=True, capture_output=True, text=True, timeout=600, env=env) data = pgm.read_bytes() except (subprocess.SubprocessError, OSError): return None finally: for leftover in ("cart.a52", "bios-orig.rom", "bios-a.rom", "frame.pgm"): path = work / leftover if path.exists(): path.unlink() return data[data.index(b"255\n") + 4 :] def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--frame", type=int, default=900) parser.add_argument("--out", type=Path, required=True) parser.add_argument("--shard", default="0/1") parser.add_argument("--list", type=Path, help="only these file names (one per line)") parser.add_argument("--raw", action="store_true", help="save both raw frames of every pair") args = parser.parse_args() shard, shards = (int(v) for v in args.shard.split("/")) wanted = None if args.list: wanted = {ln.strip() for ln in args.list.read_text("utf-8").splitlines() if ln.strip()} seen: set[str] = set() todo = [] for _set_name, path in images(None): if wanted is not None and path.name not in wanted: continue try: cart = load_cartridge(path) except CartridgeError: continue if cart.sha1 in seen or cart.mapping not in CAR_TYPE: continue seen.add(cart.sha1) todo.append((path, cart)) work = args.out / f"work-{shard}" work.mkdir(parents=True, exist_ok=True) tsv = args.out / f"sweep-{shard}.tsv" lines = ["file\tsha1\tmapping\tmapping_from\tboard\tdiffer\trows\toffset\tinterior\tedge"] for path, cart in todo[shard::shards]: start = time.perf_counter() theirs = atari800(path, args.frame, CAR_TYPE[cart.mapping], work) console = Console(cart) outcome = "ran" for _ in range(args.frame): console.run_frames(1) if console.board.cpu.halted: outcome = f"JAM at {console.board.frames}" break ours = bytes(console.board.frame) stem = path.stem.replace(" ", "_") if args.raw: (args.out / f"{stem}-board.raw").write_bytes(ours) if theirs is not None: (args.out / f"{stem}-atari800.raw").write_bytes(theirs) if theirs is None: differ, rows, offset, interior, edge = "atari800 failed", "-", "-", "-", "-" else: dx, dy, _ = best_alignment(ours, theirs) total, bad = compare(ours, theirs, dx, dy) differ, rows, offset = str(total), str(len(bad)), f"{dx // 2},{dy}" interior, edge = (str(n) for n in fixed_counts(ours, theirs)) if total or interior != "0" or edge != "0": write_png(args.out / f"{stem}-board.png", ours) padded = bytearray(456 * 262) for y in range(HEIGHT): row = (y + dy) * 456 + dx padded[row : row + WIDTH] = theirs[y * WIDTH : (y + 1) * WIDTH] write_png(args.out / f"{stem}-atari800.png", bytes(padded)) lines.append( f"{path.name}\t{cart.sha1}\t{cart.mapping}\t{cart.mapping_from}\t{outcome}" f"\t{differ}\t{rows}\t{offset}\t{interior}\t{edge}" ) tsv.write_text("\n".join(lines) + "\n", encoding="utf-8") print(f"{path.name}: {outcome}; differ {differ}; fixed {interior}/{edge} [{time.perf_counter() - start:.0f}s]", flush=True) # fmt: skip return 0 if __name__ == "__main__": raise SystemExit(main())