"""Smoke list: the board's pictures against MAME's and Gearcoleco's, with scripted inputs.
python scripts/smoke_pictures.py tests/smoke/m3.tsv [--only TITLE] [--detectors-only] [--mame]
Each row of the list: title (No-Intro stem), snapshot frames (comma-separated), inputs
(space-separated ``START:END:pN.CONTROL``), a note. The detectors' pictures are cached
under ``tests/runs/smoke/
/`` (git-ignored) and made once (MAME first, then
Gearcoleco: one detector process at a time).
Frame numbering follows MAME's frame notifier, measured (``tests/runs/frametimes.lua``):
MAME's notifier for frame k fires at CPU clock 59,736 (k + 1), the start of vertical blank
(raster 244, where it starts after reset). Its frame k holds the active lines drawn just
before, which the board (on MAME's phase) returns as its frame k + 1. MAME sets frame k's
inputs in notifier k - 1, but a field's new value reaches the game only at MAME's next
input update, one notifier later (measured: Donkey Kong's first keypad read showing a
press set in notifier 799 is at clock 47,849,307, after notifier 800 at 47,848,536; every
access before it is identical). So the board applies frame k's inputs at clock
59,736 (k + 1).
Prints one row per snapshot: differing pixels against each detector (0 and 1 one class).
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import os
import subprocess
import sys
import time
from pathlib import Path
from colecovision_python import NTSC, PAL, BoardOptions, ColecoVision, mame_options
from colecovision_python.images import NO_INTRO, load_image
from colecovision_python.pictures import detector_indices, differences
from colecovision_python.video import write_png
ROOT = Path(__file__).resolve().parents[1]
#: Gearcoleco runs as a program: the core built here before 2026-11-24 (sha1 684db6e3), or
#: a shipped libretro build named by GEARCOLECO_CORE. Its source is not fetched (Aubrey,
#: 2026-11-24; docs/validation.md).
GEARCOLECO = Path(
os.environ.get("GEARCOLECO_CORE", ROOT / "reference/build-gearcoleco/gearcoleco_libretro.so")
)
SYSTEM = ROOT / "tests/runs/system"
FRAME_OFFSET = 1 # MAME frame k = board frame k + 1
MACHINE = NTSC # --pal switches to the PAL row (inputs are timed for NTSC only)
def notifier_clock(k: int) -> int:
"""CPU clock of MAME's frame notifier k: 342 x 262 pixels at its 5,369,317 Hz pixel
clock, in 3,579,545 Hz CPU clocks (59,736.0056 each; measured 59,736.005562511)."""
return -(-(k + 1) * 89_604 * 3_579_545 // 5_369_317)
class Inputs:
"""Applies a schedule to the hand controllers when the board's clock reaches MAME's
moment for it: frame k's inputs at notifier k (set by MAME in notifier k - 1)."""
def __init__(self, pads, schedule) -> None:
self.pads, self.schedule, self.k = pads, schedule, 0
self.next = notifier_clock(1)
apply(pads, schedule, 0)
def update(self, clock: int) -> None:
while clock >= self.next:
self.k += 1
self.next = notifier_clock(self.k + 1)
apply(self.pads, self.schedule, self.k)
def read_list(path: Path) -> list[dict]:
rows = []
with path.open(newline="", encoding="utf-8") as handle:
for row in csv.reader(handle, delimiter="\t"):
if not row or row[0].startswith("#"):
continue
title, snaps, inputs = row[0], row[1], row[2] if len(row) > 2 else ""
rows.append(
{
"title": title,
"snaps": [int(s) for s in snaps.split(",")],
"inputs": inputs.split(),
"note": row[3] if len(row) > 3 else "",
}
)
return rows
def parse_input(text: str) -> tuple[int, int, int, str]:
start, end, control = text.split(":", 2)
port, name = control.split(".", 1)
return int(start), int(end), int(port[1:]) - 1, name
def apply(pads, schedule, k: int) -> None:
for pad in pads:
pad.directions, pad.keys = set(), set()
pad.left_fire = pad.right_fire = False
for start, end, port, name in schedule:
if start <= k < end:
pad = pads[port]
if name in ("up", "down", "left", "right"):
pad.directions.add(name)
elif name == "fire_left":
pad.left_fire = True
elif name == "fire_right":
pad.right_fire = True
else:
pad.keys.add(name)
def run_board(image: bytes, schedule, snaps: list[int], options) -> dict[int, tuple[bytes, ...]]:
console = ColecoVision(image, options=options, machine=MACHINE)
board, vdp = console.board, console.board.vdp
inputs = Inputs(console.controllers, schedule)
board.input_hook = inputs.update
wanted, last, n, out = set(snaps), max(snaps), 0, {}
while n <= last + FRAME_OFFSET:
board.step()
inputs.update(board.clock)
frame = vdp.take_frame()
if frame is not None:
if n - FRAME_OFFSET in wanted:
out[n - FRAME_OFFSET] = frame.pixels
n += 1
return out
def detectors(row: dict, cache: Path) -> dict[str, dict[int, Path]]:
zip_path = NO_INTRO / f"{row['title']}.zip"
snap = ",".join(map(str, row["snaps"]))
inputs = [arg for text in row["inputs"] for arg in ("--input", text)]
pal = MACHINE is PAL
mame_dir, gear_dir = cache / ("mame-pal" if pal else "mame"), cache / "gearcoleco"
if not all((mame_dir / f"frame-{f:05d}.png").exists() for f in row["snaps"]):
subprocess.run(
[sys.executable, "-I", str(ROOT / "scripts/mame_frames.py"), "colecop" if pal else "coleco",
str(zip_path), "--snap", snap, "--out", str(mame_dir), *inputs],
check=False,
) # fmt: skip
if pal: # Gearcoleco was not set up for PAL here: MAME only
gear_dir = cache / "no-gearcoleco-for-pal"
elif not all((gear_dir / f"frame-{f:05d}.png").exists() for f in row["snaps"]):
subprocess.run(
[sys.executable, "-I", str(ROOT / "scripts/libretro_run.py"), str(GEARCOLECO), str(zip_path),
"--system", str(SYSTEM), "--frames", str(max(row["snaps"]) + 1), "--snap", snap,
"--snap-dir", str(gear_dir), *inputs],
check=False, stdout=subprocess.DEVNULL,
) # fmt: skip
return {
"mame": {f: mame_dir / f"frame-{f:05d}.png" for f in row["snaps"]},
"gearcoleco": {f: gear_dir / f"frame-{f:05d}.png" for f in row["snaps"]},
}
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("list", type=Path)
parser.add_argument("--only")
parser.add_argument("--mame", action="store_true", help="board with MAME's choice on every switch")
parser.add_argument("--detectors-only", action="store_true")
parser.add_argument("--png", action="store_true", help="also save the board's pictures")
parser.add_argument("--io", action="store_true", help="also replay MAME's port-access log")
parser.add_argument("--pal", action="store_true", help="the PAL row against MAME's colecop (no inputs)")
args = parser.parse_args()
global MACHINE
MACHINE = PAL if args.pal else NTSC
options = mame_options() if args.mame else BoardOptions()
total = 0
for row in read_list(args.list):
if args.only and args.only not in row["title"]:
continue
# One cache per title and input script: runs with different inputs (the M3 list,
# the no-input sweep) must not share detector pictures.
script = hashlib.sha1(" ".join(row["inputs"]).encode()).hexdigest()[:8]
cache = ROOT / "tests/runs/smoke" / row["title"].replace(" ", "_") / f"inputs-{script}"
pictures = detectors(row, cache)
if args.detectors_only:
continue
began = time.perf_counter()
ours = run_board(
load_image(NO_INTRO / f"{row['title']}.zip"), [parse_input(t) for t in row["inputs"]],
row["snaps"], options,
) # fmt: skip
wall = time.perf_counter() - began
for frame in row["snaps"]:
cells = []
found = {}
for name in ("mame", "gearcoleco"):
path = pictures[name][frame]
if path.exists():
found[name] = detector_indices(path)
count = differences(ours[frame], found[name])
total += count
cells.append(f"{name} {count:6d}")
else:
cells.append(f"{name} -")
if len(found) == 2:
cells.append(f"mame-vs-gearcoleco {differences(found['mame'], found['gearcoleco']):6d}")
if args.png:
write_png(cache / f"board-{frame:05d}.png", ours[frame])
print(f"{row['title']:40s} frame {frame:5d} " + " ".join(cells), flush=True)
print(f" ({wall:.1f} s board, {sys.implementation.name})", flush=True)
if args.io:
run = ROOT / "tests/mame_traces" / ("io-" + row["title"].replace(" ", "_"))
if not (run / "error.log").exists():
subprocess.run(
[sys.executable, "-I", str(ROOT / "scripts/mame_io.py"), "coleco",
str(NO_INTRO / f"{row['title']}.zip"), "--frames", str(max(row["snaps"]) + 1),
"--out", str(run), *[a for t in row["inputs"] for a in ("--input", t)]],
check=True, stdout=subprocess.DEVNULL,
) # fmt: skip
from replay_io import replay
compared, diffs, report, _board = replay(run, str(NO_INTRO / f"{row['title']}.zip"), options, 1)
print(
f" I/O replay: {compared:,} accesses compared, {diffs} differences"
+ (f"; first: {report[0]}" if report else ""),
flush=True,
)
return 0
if __name__ == "__main__":
sys.exit(main())