# SPDX-License-Identifier: MIT """Save states, proved by continuation: a run saved part way and loaded into a fresh system must go on exactly as the run that was never interrupted. The uninterrupted run records, after every frame, a line of CRCs: the trail of every 68000 step (its clock, PC, and the Z80's clock and PC after it), the picture, work RAM, Z80 RAM, VRAM, CRAM, VSRAM, the cartridge's battery RAM or EEPROM, and the sound the host took for the frame. At ``--save-at`` frames (plus ``--steps`` more 68000 steps, to land part way down a frame, inside a line, or with a DMA under way) it saves a state; a second system, built afresh from the same image, loads it and runs on to ``--frames``, recording the same lines. Every line must match, and so must the two systems' whole states at the end (the state's own body, byte for byte). The pad follows a fixed script from ``--input-from`` on (Start, then a walk through the buttons, eight frames each, six-button ones included with ``--pad 6button``), the same on both sides, so a game leaves its title screen and plays. python scripts/state_roundtrip.py "Sonic The Hedgehog (USA, Europe).zip" \\ --frames 400 --save-at 200 --steps 1500 python scripts/state_roundtrip.py CART --save-at 100,200,300 # one load per point A name without a folder is looked up under $NO_INTRO_DIR (scripts/romdirs.py). Exit status 0 when every load continued identically. """ from __future__ import annotations import argparse import json import sys import time import zlib from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) sys.path.insert(0, str(Path(__file__).resolve().parent)) from megadrive_python import state from megadrive_python.__main__ import load_image from megadrive_python.cartridge import Cartridge from megadrive_python.io import BUTTONS, PAD_TYPES from megadrive_python.machine import MACHINES from megadrive_python.system import System #: What the judge leaves out when it compares two whole states: the format's own #: caches. Fixed here, so a fault that drops more from the format is still seen. JUDGE_SKIPPED = frozenset(state.SKIPPED) def whole(system: System) -> dict: """Everything the system holds, by the format's own walk, for comparing.""" return state._body(system, set(JUDGE_SKIPPED)) def configuration() -> dict[str, int]: """A CRC of every shared table's contents (state._configuration), but the pure lazy caches: a load must leave them all as they were. The copies run in the reference's process, so a load that wrote into a table every console shares would leave both sides agreeing with each other (docs/save-states.md, "What is not saved").""" return { label: zlib.crc32(repr(value).encode()) for label, value in state._configuration().values() if type(value) in (list, dict, set, bytearray) and "cache" not in label } #: The pad script: eight frames per entry, repeating. SCRIPT = ( "start", "", "start", "", "right", "right,c", "right,b", "a", "left", "left,a", "down", "down,b", "up", "c", "x", "y,right", "z", "mode", "", "start", "", ) def pad_mask(frame: int, start: int, six: bool) -> int: if frame < start: return 0 names = SCRIPT[((frame - start) // 8) % len(SCRIPT)] mask = 0 for name in filter(None, names.split(",")): if six or name not in ("x", "y", "z", "mode"): mask |= BUTTONS[name] return mask def build(image: bytes, sub: bytes | None, args: argparse.Namespace) -> System: cartridge = Cartridge.lock_on(image, sub) system = System( MACHINES[args.machine], cartridge, pads=(PAD_TYPES[args.pad](), PAD_TYPES["3button"]()), tmss_rom=load_image(args.tmss_rom) if args.tmss_rom else None, ) if args.no_sound: system.board.fm.enabled = False return system class Recorder: """Steps a system, keeping the CRC trail of its steps for the frame under way.""" def __init__(self, system: System, args: argparse.Namespace) -> None: self.system = system self.args = args self.trail = 0 def step(self) -> None: system = self.system system.step() word = (f"{system.mclk},{system.m68k.PC},{system.z80_mclk},{system.z80.pc};").encode() self.trail = zlib.crc32(word, self.trail) def frame(self, number: int) -> None: """Run frame ``number`` to its end (from wherever in it the system is).""" system = self.system pad = system.board.io.ports[0].device if pad is not None: pad.pressed = pad_mask(number, self.args.input_from, self.args.pad == "6button") vdp = system.vdp frame = vdp.frame while vdp.frame == frame: self.step() system.board.sound_sync(system.mclk) def line(self) -> str: system, board = self.system, self.system.board vdp = system.vdp width, height, rows = vdp.renderer.frame() picture = zlib.crc32(b"".join(bytes(row[:width]) for row in rows), width * 4096 + height) cartridge = board.game_cartridge battery = cartridge.save_bytes() if getattr(cartridge, "battery", "") else b"" sound = zlib.crc32(json.dumps(system.take_audio()).encode()) crc = zlib.crc32 line = ( f"{vdp.frame} steps={self.trail:08x} m68k={system.m68k_instructions} " f"z80={system.z80_instructions} mclk={system.mclk} pic={picture:08x} " f"ram={crc(board.ram):08x} zram={crc(board.z80_ram):08x} " f"vram={crc(bytes(vdp.vram)):08x} cram={crc(repr(vdp.cram).encode()):08x} " f"vsram={crc(repr(vdp.vsram).encode()):08x} batt={crc(battery):08x} " f"snd={sound:08x}" ) self.trail = 0 return line def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("cartridge") parser.add_argument("--lock-on", help="the cartridge on top of a lock-on board") parser.add_argument("--machine", default="genesis", choices=sorted(MACHINES)) parser.add_argument("--pad", default="3button", choices=("3button", "6button")) parser.add_argument("--tmss-rom") parser.add_argument("--frames", type=int, default=300) parser.add_argument("--save-at", default="150", help="frames, comma-separated") parser.add_argument( "--steps", type=int, default=0, help="68000 steps past the frame's end to save at" ) parser.add_argument("--input-from", type=int, default=60) parser.add_argument("--no-sound", action="store_true") parser.add_argument("--quiet", action="store_true") args = parser.parse_args(argv) def find(name: str) -> Path: path = Path(name) if path.exists(): return path from romdirs import rom return rom(name) image = load_image(find(args.cartridge)) sub = load_image(find(args.lock_on)) if args.lock_on else None points = sorted(int(p) for p in args.save_at.split(",")) started = time.perf_counter() reference = Recorder(build(image, sub, args), args) lines: dict[int, str] = {} saved: dict[int, bytes] = {} sizes: dict[int, tuple[int, float, float]] = {} trails: dict[int, int] = {} at_save: dict[int, dict] = {} for number in range(args.frames): reference.frame(number) lines[number] = reference.line() if number + 1 in points: # Part way into the next frame: these steps start its trail. for _ in range(args.steps): reference.step() t0 = time.perf_counter() saved[number + 1] = state.save_state(reference.system) sizes[number + 1] = (len(saved[number + 1]), time.perf_counter() - t0, 0.0) trails[number + 1] = reference.trail at_save[number + 1] = whole(reference.system) final = whole(reference.system) failures = 0 for point in points: data = saved[point] copy = Recorder(build(image, sub, args), args) tables = configuration() t0 = time.perf_counter() state.load_state(copy.system, data) load_seconds = time.perf_counter() - t0 same_tables = configuration() == tables same_start = whole(copy.system) == at_save[point] size, save_seconds, _ = sizes[point] # The reference's trail for the frame under way began at the frame's end, before # the extra steps; the copy's begins at the load. Give the copy the same start. copy.trail = trails[point] first_bad = None for number in range(point, args.frames): copy.frame(number) line = copy.line() if line != lines[number] and first_bad is None: first_bad = (number, lines[number], line) same_end = whole(copy.system) == final ok = first_bad is None and same_end and same_start and same_tables failures += not ok verdict = "identical" if ok else "DIFFERS" print( f"save at frame {point}+{args.steps} steps: {size:,} bytes, save " f"{save_seconds * 1000:.0f} ms, load {load_seconds * 1000:.0f} ms; " f"frames {point}-{args.frames - 1} {verdict}" f"{'' if same_start else ' (the loaded state differs)'}" f"{'' if same_tables else ' (the load wrote a shared table)'}" f"{'' if same_end else ' (final state differs)'}" ) if first_bad is not None: number, want, got = first_bad print(f" first difference at frame {number}:\n want {want}\n got {got}") if not args.quiet: print( f"{args.cartridge}: {len(points)} loads, {failures} failed, " f"{time.perf_counter() - started:.0f} s" ) return 1 if failures else 0 if __name__ == "__main__": sys.exit(main())