# SPDX-License-Identifier: MIT """Run a cartridge with scripted controller input and save PNGs at chosen frames. python scripts/scripted_run.py CART --press 600:start:10 --press 900:1:5 \ --png 700 --png 1200 --out DIR [--frames 1500] ``--press FRAME:KEY:FRAMES[:PORT]`` holds a key on port 1 (or PORT) for FRAMES frames from FRAME (keys: 0-9, *, #, start, pause, reset, trigger, top); ``--stick FRAME:X:Y[:PORT]`` moves a stick; ``--plug N`` plugs controllers into ports 1-N (default 2); ``--log-ports`` prints which ports the program selects through CONSOL and the BIOS's POT shadows ($11-$18, [BUCH]) at the end. PNGs are written as DIR/STEM-FRAME.png with the labelled palette. Used for the diagnostic cartridges (milestones 3-4: [FSM] procedures, results read from the screen). """ from __future__ import annotations import argparse import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from a5200_python.media import AudioTap, write_png # noqa: E402 from a5200_python.system import Console # noqa: E402 class StuckBitRAM(bytearray): """A seeded fault for the diagnostic cartridges: data bit 0 stuck at 0 from $1000 up. The 5200's RAM is eight 16K x 1 chips ([FSM] Table 3-1: failure codes 0-7, one per chip), so a dead chip is one data bit wrong everywhere; the low 4K is spared so that the cartridge's own variables and stack survive. With ``until`` and ``board``, the fault heals at that frame (a transient fault: what PAM v2.3's soft-error list is for). How the cartridges report it (docs/validation.md, milestone 4, "the RAM fault"): v1.1 stops at the first miscompare and counts the failing bit, but redraws its Error Summary only when the next test starts; v2.3 counts a soft error and restarts the pass, and shows its lists only when the test ends, which a permanent fault never lets it do. """ def __init__(self, data, board=None, until: int | None = None) -> None: super().__init__(data) self.board = board self.until = until def __getitem__(self, index): value = super().__getitem__(index) active = self.until is None or self.board.frames < self.until if isinstance(index, int) and index >= 0x1000 and active: return value & 0xFE return value def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("cart") parser.add_argument("--press", action="append", default=[]) parser.add_argument("--png", action="append", type=int, default=[]) parser.add_argument("--frames", type=int) parser.add_argument("--out", type=Path, default=ROOT / "tests" / "detector_runs" / "scripted") parser.add_argument("--machine", default="a5200") parser.add_argument("--wav", type=Path, help="write the audio (POKEY mix and speaker)") parser.add_argument( "--pokey-log", type=Path, help="write every AUDF/AUDC/AUDCTL write as frame cycle reg value" ) parser.add_argument( "--stick", action="append", default=[], help="FRAME:X:Y[:PORT]: a stick from FRAME on" ) parser.add_argument( "--trak", action="append", default=[], help="FRAME:VX:VY[:PORT]: a CX53 trak-ball rolled at VX, VY counts per frame from FRAME", ) parser.add_argument("--plug", type=int, default=2, help="controllers plugged in (ports 1-N)") parser.add_argument( "--log-ports", action="store_true", help="print CONSOL port selections per 100 frames" ) parser.add_argument( "--fault", choices=["ram-bit"], help="seed a fault: RAM data bit 0 reads 0 from $1000 up" ) parser.add_argument( "--fault-until", type=int, metavar="FRAME", help="the seeded fault heals at FRAME" ) args = parser.parse_args() presses = [] for item in args.press: frame, key, length, *port = item.split(":") presses.append((int(frame), key, int(length), int(port[0]) - 1 if port else 0)) last = args.frames or max([*args.png, *(f + n for f, _, n, _ in presses), 1]) console = Console(args.cart, args.machine) board = console.board if args.fault == "ram-bit": board.ram = StuckBitRAM(board.ram, board, args.fault_until) if args.wav: board.audio = AudioTap(board) log: list[str] = [] if args.pokey_log: def watch(kind: str, address: int, value: int, cycle: int) -> None: if kind == "W" and 0xE800 <= address < 0xF000 and address & 0x0F <= 8: log.append(f"{board.frames} {cycle} {address & 0x0F} {value}") board.bus_observers.append(watch) pads = console.controllers.pads for n in range(min(args.plug, len(pads))): pads[n].plugged = True consol_seen: dict[int, set[int]] = {} if args.log_ports: def ports(kind: str, address: int, value: int, cycle: int) -> None: if kind == "W" and 0xC000 <= address < 0xD000 and address & 0x1F == 0x1F: consol_seen.setdefault(board.frames // 100 * 100, set()).add(value & 3) board.bus_observers.append(ports) args.out.mkdir(parents=True, exist_ok=True) stem = Path(args.cart).stem.replace(" ", "_") for frame in range(1, last + 1): for port, pad in enumerate(pads): mine = [(f, k, n) for f, k, n, p in presses if p == port and f <= frame < f + n] pad.keys = {k for _, k, _ in mine if k not in ("trigger", "top")} pad.trigger = any(k == "trigger" for _, k, _ in mine) pad.top = any(k == "top" for _, k, _ in mine) for item in args.stick: f, x, y, *rest = item.split(":") port = int(rest[0]) - 1 if rest else 0 if int(f) == frame and port < len(pads): # a missing port is ignored pads[port].x, pads[port].y = float(x), float(y) for item in args.trak: f, vx, vy, *rest = item.split(":") port = int(rest[0]) - 1 if rest else 0 if int(f) == frame and port < len(pads): pads[port].trakball = True pads[port].vx, pads[port].vy = float(vx), float(vy) console.run_frames(1) if frame in args.png: path = args.out / f"{stem}-{frame}.png" write_png(path, console.board.frame) print(f"wrote {path}", flush=True) if args.wav: board.audio.write(args.wav) print(f"wrote {args.wav}") for window in sorted(consol_seen): print(f"frames {window}-{window + 99}: CONSOL port values {sorted(consol_seen[window])}") if args.log_ports: shadows = " ".join(f"{board.ram[0x11 + n]:3d}" for n in range(8)) print(f"POT shadows $11-$18 at the end: {shadows}") if args.pokey_log: args.pokey_log.write_text("\n".join(log) + "\n", encoding="utf-8") print(f"wrote {args.pokey_log} ({len(log)} writes)") return 0 if __name__ == "__main__": raise SystemExit(main())