// SPDX-License-Identifier: MIT //! Save states: a restored machine runs on exactly as the original did (a5200-python's //! tests/test_state.py at cf82d44, the tests added there, transcribed). //! //! methodology.md "Save states in the gate": a state loaded into a fresh console //! must continue identically. Saves are taken at frame boundaries and inside a //! frame (any instruction boundary: a WSYNC stall pending, a POKEY interrupt //! rising, a CX53 trak-ball rolling), restored from a serialised copy made after the //! original has played on (so a snapshot that shares a list or set with the live //! machine shows), and restored twice from the same snapshot (as rewind does). //! //! Rust-forced differences: Python's pickle round trip is `state::to_bytes` / //! `from_bytes`; GTIA's and POKEY's snapshots are compared as their serialised bytes //! (GTIA's snapshot type has no `PartialEq`); the slow tests (`pytest -m slow`) are //! `#[ignore]`d: `cargo test --release -- --ignored` with `$NO_INTRO_DIR` and the BIOS. use std::path::{Path, PathBuf}; use a5200::board::Running; use a5200::cartridge::{load_cartridge, Source}; use a5200::media::AudioTap; use a5200::state::{self, CpuFields, State}; use a5200::{Console, A5200}; // -- a synthetic BIOS that keeps every part of the machine busy ---------------- const _LOOP: u16 = 0xF848; /// Display list DMA, a VBI NMI, POKEY timer and keyboard interrupts, two tones, /// pot scans (pot power on every other frame), the keypad, a trigger and a WSYNC /// every 32 passes of the loop. fn _busy_bios() -> Vec { #[rustfmt::skip] let init: &[u8] = &[ 0x78, 0xD8, 0xA2, 0xFF, 0x9A, // SEI CLD LDX #$FF TXS 0xA9, 0x04, 0x8D, 0x1F, 0xC0, // CONSOL = 4: pot power 0xA9, 0x02, 0x8D, 0x0F, 0xE8, // SKCTL = 2: keyboard scan, no debounce (aliased keys) 0xA9, 0x60, 0x8D, 0x00, 0xE8, // AUDF1 0xA9, 0xA8, 0x8D, 0x01, 0xE8, // AUDC1: pure tone 0xA9, 0x30, 0x8D, 0x02, 0xE8, // AUDF2 0xA9, 0xC6, 0x8D, 0x03, 0xE8, // AUDC2 0xA9, 0x41, 0x8D, 0x0E, 0xE8, // IRQEN: keyboard, timer 1 0x8D, 0x09, 0xE8, // STIMER 0x8D, 0x0B, 0xE8, // POTGO 0xA9, 0x00, 0x8D, 0x02, 0xD4, // DLISTL = $00 0xA9, 0x10, 0x8D, 0x03, 0xD4, // DLISTH = $10 0xA9, 0xF8, 0x8D, 0x09, 0xD4, // CHBASE = $F8 0xA9, 0x22, 0x8D, 0x00, 0xD4, // DMACTL: normal playfield, display list 0xA9, 0x40, 0x8D, 0x0E, 0xD4, // NMIEN: VBI 0x58, // CLI ]; assert_eq!(0xF800 + init.len(), _LOOP as usize); #[rustfmt::skip] let lp: &[u8] = &[ 0xE6, 0x80, 0xA5, 0x80, 0x8D, 0x02, 0xE8, // INC $80; AUDF2 = $80 0xAD, 0x0A, 0xE8, 0x85, 0x82, // RANDOM 0xAD, 0x00, 0xE8, 0x85, 0x83, // POT0 0xAD, 0x02, 0xE8, 0x85, 0x88, // POT2 0xAD, 0x09, 0xE8, 0x85, 0x85, // KBCODE 0xAD, 0x0F, 0xE8, 0x85, 0x86, // SKSTAT 0xAD, 0x10, 0xC0, 0x85, 0x87, // TRIG0 0xA5, 0x80, 0x29, 0x1F, 0xD0, 0x03, 0x8D, 0x0A, 0xD4, // every 32nd pass: WSYNC 0x4C, (_LOOP & 0xFF) as u8, (_LOOP >> 8) as u8, ]; #[rustfmt::skip] let nmi: &[u8] = &[ 0x48, 0xE6, 0x81, // PHA INC $81 0xA5, 0x81, 0x29, 0x01, 0x0A, 0x0A, 0x8D, 0x1F, 0xC0, // pot power every other frame 0x8D, 0x0B, 0xE8, 0x68, 0x40, // POTGO PLA RTI ]; #[rustfmt::skip] let irq: &[u8] = &[ 0x48, 0xA9, 0x00, 0x8D, 0x0E, 0xE8, 0xA9, 0x41, 0x8D, 0x0E, 0xE8, // acknowledge 0xE6, 0x84, 0xA5, 0x84, 0x09, 0x40, 0x8D, 0x00, 0xE8, // AUDF1 = $84 | $40 0x68, 0x40, ]; let mut image = vec![0xEA; 2048]; image[..init.len()].copy_from_slice(init); image[init.len()..init.len() + lp.len()].copy_from_slice(lp); image[0x100..0x100 + nmi.len()].copy_from_slice(nmi); image[0x180..0x180 + irq.len()].copy_from_slice(irq); image[0x7FA..0x800].copy_from_slice(&[0x00, 0xF9, 0x00, 0xF8, 0x80, 0xF9]); image } fn _dlist() -> Vec { let mut d = vec![0x70, 0x70, 0x70, 0x42, 0x00, 0x20]; d.extend([0x02; 7]); d.extend([0x41, 0x00, 0x10]); d } fn _busy_console() -> Console { let cart = load_cartridge(Source::Bytes(&vec![0u8; 0x8000]), None, None).unwrap(); let mut console = Console::new(cart, A5200, Some(_busy_bios()), None).unwrap(); let dlist = _dlist(); let ram = &mut console.board_mut().ram; ram[0x1000..0x1000 + dlist.len()].copy_from_slice(&dlist); for i in 0..0x140 { ram[0x2000 + i] = ((i * 7) & 0x7F) as u8; } console } /// Frame f's inputs: on port 1 (the port the program scans) a trak-ball changing /// speed, its buttons and the keypad, the keys set mutated in place as a frontend /// may; a stick on port 2. fn _drive(console: &mut Console, f: u64) { let mut pads = console.controllers.pads.borrow_mut(); { let ball = &mut pads[0]; ball.trakball = true; ball.vx = [3.0, 8.0, -2.0, 0.0, 5.5][(f % 5) as usize]; ball.vy = [-4.0, 1.0, 6.0][(f % 3) as usize]; ball.trigger = f % 4 == 1; ball.top = f % 3 == 2; ball.keys.clear(); if f % 3 != 0 { ball.keys .insert(["1", "5", "start", "#", "0"][(f % 5) as usize].to_string()); } } let pad = &mut pads[1]; pad.x = 20.0 + ((f * 37) % 200) as f64; pad.y = 228.0 - ((f * 11) % 200) as f64; } #[rustfmt::skip] const RECORD_FIELDS: [&str; 10] = [ "frames", "cycles", "frame CRC", "RAM", "CPU", "POKEY", "GTIA", "pot targets", "pot charge", "pad positions", ]; /// One record: each of RECORD_FIELDS as a comparable string (Rust: Python's tuple). fn _record(console: &Console) -> Vec { let board = console.board(); let controllers = &console.controllers; let rc = controllers.rc.borrow(); let cpu: CpuFields = console.cpu.capture_state().into(); vec![ board.frames.to_string(), board.cycles.to_string(), crc32fast::hash(&board.frame).to_string(), format!("{:?}", board.ram), format!("{cpu:?}"), format!("{:?}", bincode::serialize(&board.pokey.snapshot()).unwrap()), format!("{:?}", bincode::serialize(&board.gtia.snapshot()).unwrap()), format!("{:?}", rc.target), format!("{:?}", rc.charge), format!( "{:?}", controllers .pads .borrow() .iter() .map(|p| (p.x, p.y)) .collect::>() ), ] } type Drive = fn(&mut Console, u64); /// Finish the current frame without new inputs, then play `frames` more; the last /// entry is the audio samples (Rust: as a one-field record). fn _continue(console: &mut Console, start: u64, frames: u64, drive: Drive) -> Vec> { let cycle_hz = console.machine.cycle_hz(); console.board_mut().audio = Some(AudioTap::new(cycle_hz, 44100, 8)); console.cpu.run_frame(); let mut records = vec![_record(console)]; for f in start..start + frames { drive(console, f); console.run_frames(1); records.push(_record(console)); } let tap = console.board_mut().audio.take().unwrap(); records.push(vec![format!("{:?}", tap.samples)]); records } /// Restore `saved` into two fresh consoles in turn, one from a serialised copy and one /// from the very value; each must play on exactly as the original did. fn _round_trip( make: &dyn Fn() -> Console, saved: &State, start: u64, frames: u64, expected: &[Vec], drive: Drive, ) { let copied = state::from_bytes(&state::to_bytes(saved)).unwrap(); for source in [&copied, saved] { let mut fresh = make(); state::restore(&mut fresh, source).unwrap(); let got = _continue(&mut fresh, start, frames, drive); assert_eq!(expected.len(), got.len()); for (n, (a, b)) in expected.iter().zip(got.iter()).enumerate() { if n == expected.len() - 1 { assert!(a == b, "audio samples differ"); continue; } for ((field, x), y) in RECORD_FIELDS.iter().zip(a.iter()).zip(b.iter()) { assert!( x == y, "{field} differs at record {n} (0 = the end of the saved frame)" ); } } } } /// Where inside the frame the save is taken: a cycle count past the frame boundary /// (0 = at the boundary), or the first instruction boundary at which a condition holds. enum Where { Cycles(u64), When(fn(&a5200::Cpu) -> bool), } fn save_point(name: &str) -> Where { match name { "frame-boundary" => Where::Cycles(0), "cycle-1" => Where::Cycles(1), "cycle-7001" => Where::Cycles(7001), "cycle-15013" => Where::Cycles(15013), "cycle-29801" => Where::Cycles(29801), "wsync-pending" => Where::When(|cpu| cpu.bus.antic.wsync_at >= 0), "irq-edge-unsynced" => Where::When(|cpu| cpu.bus._irq_next != cpu.bus._irq_line), "irq-held" => Where::When(|cpu| cpu.bus._irq_line && cpu.p & 0x04 != 0), "nmi-pending" => { Where::When(|cpu| Running::capture_state(cpu).non_maskable_interrupt_pending) } _ => panic!("no save point {name}"), } } fn _run_to(console: &mut Console, at: Where) { match at { Where::When(cond) => { for _ in 0..200_000 { console.cpu.board_step(); if cond(&console.cpu) { return; } } panic!("save point never reached"); } Where::Cycles(n) => console.cpu.run_cycles(n), } } fn save_anywhere_continues_identically(name: &str) { let mut original = _busy_console(); for f in 0..3 { _drive(&mut original, f); original.run_frames(1); } _run_to(&mut original, save_point(name)); // The frontend changes the pads after this frame's inputs were applied: the // machine still holds what was applied, and so must the save. { let mut pads = original.controllers.pads.borrow_mut(); pads[0].vx = 7.0; pads[1].x = 3.0; pads[1].trakball = true; } let saved = state::snapshot(&original); let expected = _continue(&mut original, 3, 2, _drive); _round_trip(&_busy_console, &saved, 3, 2, &expected, _drive); } #[test] fn save_anywhere_frame_boundary() { save_anywhere_continues_identically("frame-boundary"); } #[test] fn save_anywhere_cycle_1() { save_anywhere_continues_identically("cycle-1"); } #[test] fn save_anywhere_cycle_7001() { save_anywhere_continues_identically("cycle-7001"); } #[test] fn save_anywhere_cycle_15013() { save_anywhere_continues_identically("cycle-15013"); } #[test] fn save_anywhere_cycle_29801() { save_anywhere_continues_identically("cycle-29801"); } #[test] fn save_anywhere_wsync_pending() { save_anywhere_continues_identically("wsync-pending"); } #[test] fn save_anywhere_irq_edge_unsynced() { save_anywhere_continues_identically("irq-edge-unsynced"); } #[test] fn save_anywhere_irq_held() { save_anywhere_continues_identically("irq-held"); } #[test] fn save_anywhere_nmi_pending() { save_anywhere_continues_identically("nmi-pending"); } /// a5200-rust's finding (2026-11-14): the lag output was not saved, and restore stepped it. #[test] fn trakball_save_mid_roll_restores_the_lag_unstepped() { let mut original = _busy_console(); for f in 0..4 { _drive(&mut original, f); original.run_frames(1); } let saved = state::snapshot(&original); let mut fresh = _busy_console(); state::restore(&mut fresh, &saved).unwrap(); for (a, b) in original .controllers ._balls .iter() .zip(fresh.controllers._balls.iter()) { assert_eq!(a.out, b.out); } assert_eq!( original.controllers.rc.borrow().target, fresh.controllers.rc.borrow().target ); let positions = |c: &Console| { c.controllers .pads .borrow() .iter() .map(|p| (p.x, p.y)) .collect::>() }; assert_eq!(positions(&original), positions(&fresh)); } /// Rust: the state refuses another machine row (state.py's new check), which the /// reference's tests exercise only through `restore` itself. #[test] fn restore_refuses_another_machine_row() { let original = _busy_console(); let mut saved = state::snapshot(&original); saved.machine = "a5200a".to_string(); let mut fresh = _busy_console(); assert!(state::restore(&mut fresh, &saved).is_err()); } // -- commercial images (Rust: #[ignore]; need $NO_INTRO_DIR and the BIOS) -------- fn _image(name: &str) -> Option { let root = std::env::var_os("NO_INTRO_DIR")?; let path = PathBuf::from(root) .join("Atari - Atari 5200") .join(format!("{name}.zip")); path.is_file().then_some(path) } fn _open(path: &Path) -> Console { Console::open(path, A5200, None).unwrap() } /// The repro a5200-rust sent (scripts/trak_state_repro.py there): a trak-ball rolling /// from frame 480, saved at frame 500; lag 164.0 at the save read 139.0 after the /// restore, POT0's target ten frames on 18696 against 18693. #[test] #[ignore] fn missile_command_trakball_save_continues() { let Some(rom) = _image("Missile Command (USA)") else { eprintln!("needs $NO_INTRO_DIR with Missile Command (USA)"); return; }; fn drive(console: &mut Console, f: u64) { let mut pads = console.controllers.pads.borrow_mut(); pads[0].trakball = true; pads[0].vx = if f >= 480 { 4.0 } else { 0.0 }; } let mut original = _open(&rom); for f in 1..501 { drive(&mut original, f); original.run_frames(1); } let saved = state::snapshot(&original); let mut expected = Vec::new(); for f in 501..511 { drive(&mut original, f); original.run_frames(1); expected.push(_record(&original)); } let mut fresh = _open(&rom); state::restore(&mut fresh, &saved).unwrap(); for (n, f) in (501..511).enumerate() { drive(&mut fresh, f); fresh.run_frames(1); assert!(_record(&fresh) == expected[n], "diverged at frame {f}"); } } fn _title_drive(kind: &str, console: &mut Console, f: u64) { let mut pads = console.controllers.pads.borrow_mut(); let pad = &mut pads[0]; pad.keys.clear(); if (300..310).contains(&f) { pad.keys.insert("start".to_string()); } pad.trigger = f >= 400 && f % 20 < 5; if kind == "trak" { pad.trakball = true; pad.vx = [6.0, -3.0, 0.0, 2.5][((f / 7) % 4) as usize]; pad.vy = [-5.0, 4.0, 1.0][((f / 5) % 3) as usize]; } else if kind == "keypad" { if f >= 400 && f % 9 < 3 { pad.keys .insert(["1", "4", "7", "0", "#", "*"][((f / 9) % 6) as usize].to_string()); } pad.x = 114.0 + ((f % 60) as f64 - 30.0) * 3.0; } else { pad.x = [20.0, 114.0, 220.0][((f / 15) % 3) as usize]; pad.y = [114.0, 220.0, 20.0][((f / 25) % 3) as usize]; } } fn mid_frame_save_continues_on_title(name: &str, drive: Drive) { let Some(rom) = _image(name) else { eprintln!("needs $NO_INTRO_DIR with {name}"); return; }; let mut original = _open(&rom); for f in 0..600 { drive(&mut original, f); original.run_frames(1); } _run_to(&mut original, Where::Cycles(12_345)); let saved = state::snapshot(&original); let expected = _continue(&mut original, 600, 6, drive); _round_trip(&|| _open(&rom), &saved, 600, 6, &expected, drive); } #[test] #[ignore] fn mid_frame_save_continues_on_missile_command() { mid_frame_save_continues_on_title("Missile Command (USA)", |c, f| _title_drive("trak", c, f)); } #[test] #[ignore] fn mid_frame_save_continues_on_centipede() { mid_frame_save_continues_on_title("Centipede (USA)", |c, f| _title_drive("trak", c, f)); } #[test] #[ignore] fn mid_frame_save_continues_on_star_raiders() { mid_frame_save_continues_on_title("Star Raiders (USA)", |c, f| _title_drive("keypad", c, f)); } #[test] #[ignore] fn mid_frame_save_continues_on_pac_man() { mid_frame_save_continues_on_title("Pac-Man (USA)", |c, f| _title_drive("stick", c, f)); }