#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Run a cartridge on megadrive-python with a 32X in the slot and the user's boot ROMs. The acceptance runs of milestones 2 and 3 (testpico, the Mars Check Program, Sega's samples, the 240p suite) and milestone 4's composite runs use it. Two pictures: the one that leaves the console (``fNNNNN.png``: the composite, socket 7, milestone 4; both test programs print their results through the Mega Drive VDP, which it includes) and the 32X VDP's alone (``fNNNNN-32x.png``, 320 wide, a blank-mode row black), with the Mega Drive's own beside them (``fNNNNN-md.png``, for layer-by-layer comparison). In H32 a frame mixing composite rows (320) and the Mega Drive's own (256) is laid on the 32X's grid for the PNG (``composite.rectangle``). python scripts/run_32x.py CART --bios-dir DIR --frames 3000 --out out/ \\ [--png-every 300] [--on-change 42,194,108,212] [--press-reset-at 2400] \\ [--save-32x 400,500] [--press 420:a:6] ``--on-change`` saves every frame on which that rectangle of the picture changes, and the frame before it (as ``scripts/libretro_frames.py`` does for the referees). ``--press-reset-at`` presses the console's reset button at the start of those frames (socket 9's BUTTON). ``--save-32x`` saves the 32X-only frame (and the Mega Drive's) at those frames; ``--png-every`` saves both. ``--press FRAME:BUTTONS[:HOLD]`` holds pad 1's buttons (megadrive-python's names) from FRAME for HOLD frames (4 by default), as ``scripts/libretro_frames.py --press`` does for the referees; ``--press-from-picture N:BUTTONS[:HOLD]`` counts N from the first frame that is not one colour instead, as the referees' option of that name does (the boot's length is where emulators differ most: docs/worklog.md, Sessions 13-14). Each frame's line on stdout gives the wall time, the SH-2s' instructions so far and the 68000's PC. ``--wav out.wav`` writes the sound (16-bit stereo at ``--rate``): the Mega Drive's FM and PSG with the 32X's PWM mixed in through socket 8 (``pwm.py``), from ``--wav-from`` on. The FM is off unless ``--wav`` is given (it is the slowest chip), and ``--no-fm`` keeps it off then too (its samples silent, the PSG and PWM as they are). ``--pwm-log`` writes each take of the PWM's own samples (the duty cycles, before the mix) with their rate, one line per frame, for comparison with the detectors. ``--save-state FILE --save-at N`` saves the whole machine after frame N (``savestate.py``; no ROM or BIOS bytes in it) and goes on; ``--load-state FILE`` starts from one instead of power-on, numbering frames on from the saved one, so ``--frames`` is still the last frame's number and the PNGs are named as a straight run's. The cartridge and ``--bios-dir`` must be the ones it was saved with, and the board and cores the same revisions (``--any-board`` accepts another board revision). Give the run that saves the same sound options as the one that loads (``--wav``, ``--no-fm``): the FM only runs when asked to. """ from __future__ import annotations import argparse import sys import time from pathlib import Path from megadrive_python.board import Lockup from megadrive_python.io import BUTTONS from megadrive_python.png import write_png from megadrive_python.wav import write_wav from sega32x_python.composite import rectangle from sega32x_python.runner import Session from sega32x_python.savestate import StateError def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cartridge", type=Path) parser.add_argument("--bios-dir", type=Path, required=True) parser.add_argument("--machine", default="genesis") parser.add_argument("--frames", type=int, required=True) parser.add_argument("--out", type=Path, required=True) parser.add_argument("--png-every", type=int, default=0) parser.add_argument("--on-change", help="X0,Y0,X1,Y1") parser.add_argument("--press-reset-at", default="", help="comma-separated frame numbers") parser.add_argument("--report-every", type=int, default=1) parser.add_argument("--save-32x", default="", help="comma-separated frame numbers") parser.add_argument("--press", action="append", default=[], help="FRAME:BUTTONS[:HOLD]") parser.add_argument("--press-from-picture", action="append", default=[], help="N:BUTTONS[:HOLD], N frames after the first picture that is " "not one colour") # fmt: skip parser.add_argument("--wav", type=Path, help="write the sound here (16-bit stereo)") parser.add_argument("--wav-from", type=int, default=1, help="first frame of --wav") parser.add_argument("--rate", type=int, default=44_100, help="sample rate of --wav") parser.add_argument("--no-fm", action="store_true", help="the FM silent even with --wav") parser.add_argument("--pwm-log", type=Path, help="write the PWM's own samples here") parser.add_argument("--save-state", type=Path, help="save the machine here (--save-at)") parser.add_argument("--save-at", type=int, help="the frame after which to save") parser.add_argument("--load-state", type=Path, help="start from this saved machine") parser.add_argument("--any-board", action="store_true", help="load a state saved by another board revision") # fmt: skip args = parser.parse_args() if (args.save_state is None) != (args.save_at is None): parser.error("--save-state and --save-at go together") if args.pwm_log and (args.save_state or args.load_state): parser.error("--pwm-log wraps the PWM in a local class a state cannot hold") saves = {int(n) for n in args.save_32x.split(",") if n} def parse_press(spec: str) -> tuple[int, int, int]: parts = spec.split(":") first, hold = int(parts[0]), int(parts[2]) if len(parts) > 2 else 4 mask = 0 for name in (b.strip().lower() for b in parts[1].split(",") if b.strip()): mask |= BUTTONS[name] return first, hold, mask presses = [] for spec in args.press: first, hold, mask = parse_press(spec) presses.append((first, first + hold - 1, mask)) # Counted from the first picture: emulators differ most in how long the boot takes. from_picture = [parse_press(spec) for spec in args.press_from_picture] args.out.mkdir(parents=True, exist_ok=True) region = tuple(int(n) for n in args.on_change.split(",")) if args.on_change else None resets = {int(n) for n in args.press_reset_at.split(",") if n} try: session = Session.start(args.cartridge, args.bios_dir, machine=args.machine, load_state=args.load_state, any_board=args.any_board) # fmt: skip except StateError as refused: parser.error(str(refused)) system, device = session.system, session.device # The FM is the slowest chip: on only for --wav. session.sound(fm=bool(args.wav) and not args.no_fm, rate=args.rate if args.wav else None) audio: list[tuple[int, int]] = [] pwm_log = args.pwm_log.open("w") if args.pwm_log else None if pwm_log is not None: # The PWM's own samples, taken here before System.take_audio would: wrap the # source so both see the same samples. pwm = device.pwm system.audio_sources.remove(pwm) class Logged: gain = pwm.gain @property def rate(self) -> float: return pwm.rate def take_samples(self, mclk: int) -> list[tuple[float, float]]: samples = pwm.take_samples(mclk) pwm_log.write(f"{pwm.rate:.3f} " + " ".join( f"{left:.6f},{right:.6f}" for left, right in samples) + "\n") # fmt: skip return samples system.audio_sources.append(Logged()) sh2 = device.sh2 assert sh2 is not None start = time.time() previous_rows = previous_crop = None def crop(rows: list[list[int]]) -> tuple: x0, y0, x1, y1 = region # type: ignore[misc] return tuple(tuple(row[x0:x1]) for row in rows[y0:y1]) pad = system.board.io.ports[0].device def save_both(frame: int, rows: list[list[int]]) -> None: write_png(args.out / f"f{frame:05d}.png", rows) write_png(args.out / f"f{frame:05d}-32x.png", session.picture_32x()) write_png(args.out / f"f{frame:05d}-md.png", session.picture_md()) for frame in range(session.frame + 1, args.frames + 1): if presses and pad is not None: pad.pressed = 0 for first, last, mask in presses: if first <= frame <= last: pad.pressed |= mask if frame in resets: system.press_reset() print(f"frame {frame}: reset button", flush=True) try: session.run_frame() except Lockup as stop: print(f"frame {frame}: Lockup: {stop}", flush=True) # The picture as far as it got; a lockup in the first frame has none yet (no # line drawn: Star Wars Arcade (USA) (Beta 3), 2026-11-25), and no PNG. rows = session.picture() if rows: write_png(args.out / f"f{frame:05d}-lockup.png", rows) else: print(f"frame {frame}: no picture yet", flush=True) return 2 if args.wav or pwm_log is not None: samples = system.take_audio() if frame >= args.wav_from: audio.extend(samples) rows = session.picture() if from_picture and rows and len({pixel for row in rows for pixel in row}) > 1: for after, hold, mask in from_picture: presses.append((frame + after, frame + after + hold - 1, mask)) print(f"frame {frame}: first picture; presses from it", flush=True) from_picture = [] if region is not None and rows: now = crop(rows) if previous_crop is not None and now != previous_crop: write_png(args.out / f"f{frame - 1:05d}.png", previous_rows) # type: ignore[arg-type] write_png(args.out / f"f{frame:05d}.png", rows) previous_rows, previous_crop = rows, now if rows and (frame in saves or (args.png_every and frame % args.png_every == 0)): save_both(frame, rows) if frame % args.report_every == 0 or frame == args.frames: elapsed = time.time() - start print(f"frame {frame}: {elapsed:.1f} s, SH-2 instructions {sh2.instructions}, " f"68000 PC ${system.m68k.PC:06X}, comm {device.comm}, " f"32X mode {device.vdp.latched_mode} PRI {device.vdp.latched_pri}, " f"MD {system.vdp.hmode.name}", flush=True) # fmt: skip if frame == args.save_at: session.save(args.save_state) save_both(args.frames, rectangle(system.vdp.renderer.frame_rgb())) print(f"[run] frame {args.frames}: 68000 instructions {system.m68k_instructions:,}, " f"Z80 {system.z80_instructions:,}, SH-2 {sh2.instructions}, MCLK {system.mclk:,}", flush=True) # fmt: skip if args.wav: write_wav(args.wav, audio, args.rate) print(f"{len(audio):,} samples at {args.rate} Hz to {args.wav}", flush=True) if pwm_log is not None: pwm_log.close() return 0 if __name__ == "__main__": sys.exit(main())