// SPDX-License-Identifier: MIT //! Save states (src/state.rs; the reference's tests/test_state.py): a state saved between //! two 68000 steps and loaded into a fresh system continues as the run that was never //! interrupted, on the example cartridges (no ROM): against the reference's own traces //! of them, through `md-trace`'s `--save-at` and `--rewind-at`, and step by step. use std::path::{Path, PathBuf}; use megadrive_rust::cartridge::Cartridge; use megadrive_rust::io::Device; use megadrive_rust::machine::machine; use megadrive_rust::state::{load_snapshot, load_state, save_snapshot, save_state}; use megadrive_rust::system::System; use megadrive_rust::trace::Run; fn examples() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/examples") } fn image(name: &str) -> Vec { std::fs::read(examples().join(name)).unwrap() } fn system(name: &str, machine_name: &str, pad: &str) -> System { System::new( machine(machine_name).unwrap(), Some(Cartridge::from_image(image(name))), Some([ Device::by_name(pad).unwrap(), Device::by_name("3button").unwrap(), ]), None, ) } /// Every step's clocks and PCs, then the memories, the picture and the sound. fn trail(system: &mut System, steps: usize) -> Vec { let mut out = Vec::with_capacity(steps + 1); for _ in 0..steps { system.step().unwrap(); let pc = system.m68k.capture_state().pc; let md = system.md(); out.push(format!("{} {pc} {} {}", md.mclk, md.z80_mclk, md.z80.pc)); } let audio = system.take_audio(); let board = system.board(); out.push(format!( "{:?} {:?} {:?} {:?} {:?}", board.dev.ram, board.dev.z80_ram, board.vdp.s.vram, board.vdp.s.cram, audio )); out } fn continues(name: &str, machine_name: &str, pad: &str, at: usize) { let mut whole = system(name, machine_name, pad); for _ in 0..at { whole.step().unwrap(); } let data = save_state(&whole); let mut copy = system(name, machine_name, pad); load_state(&mut copy, &data).unwrap(); assert_eq!( save_snapshot(©), save_snapshot(&whole), "{name} at {at}: the loaded state" ); assert_eq!( trail(&mut copy, 4000), trail(&mut whole, 4000), "{name} at {at}" ); assert_eq!( save_snapshot(©), save_snapshot(&whole), "{name} at {at}: at the end" ); } #[test] fn board_tour_continues_from_any_step() { // 198 is inside the VRAM fill and 1,409 has a Z80 instruction held part way by a bus // request, as in the reference's test. for at in [0, 1, 187, 198, 1409, 5000, 23_456] { continues("board-tour.bin", "genesis", "3button", at); } } #[test] fn h32_sprites_on_a_pal_console_with_six_buttons() { continues("h32-sprites.bin", "megadrive", "6button", 30_000); } /// `md-trace --save-at` and `--rewind-at` against the reference's trace of the example. fn traced(cartridge: &str, frames: u64, options: &[(&str, &str)]) { let mut run = Run::new(examples().join(cartridge)); run.frames = frames; for (option, value) in options { let mut value = Some(value.to_string()).into_iter(); run.option(option, &mut || { value.next().ok_or_else(|| "no value".to_string()) }) .unwrap(); } let mut ours = Vec::new(); run.trace(&mut ours).unwrap(); let theirs = std::fs::read_to_string(examples().join(cartridge.replace(".bin", ".trace"))).unwrap(); assert_eq!( String::from_utf8(ours).unwrap(), theirs, "{cartridge} {options:?}" ); } #[test] fn the_reference_traces_through_save_states() { traced( "board-tour.bin", 120, &[ ("--save-at", "40+1777"), ("--save-at", "60"), ("--rewind-at", "80"), ], ); traced( "h32-raster.bin", 60, &[("--save-at", "20+999"), ("--rewind-at", "40")], ); } #[test] fn mismatches_are_refused_and_change_nothing() { let mut source = system("board-tour.bin", "genesis", "3button"); for _ in 0..100 { source.step().unwrap(); } let data = save_state(&source); let refused = |target: &mut System, data: &[u8], want: &str| { let before = save_snapshot(target); let error = load_state(target, data).unwrap_err(); assert!(error.contains(want), "{error:?} does not say {want:?}"); assert_eq!( save_snapshot(target), before, "a refused load changed the system" ); }; let mut garbage = b"garbage".to_vec(); garbage.extend(&data); refused( &mut system("board-tour.bin", "genesis", "3button"), &garbage, "not a megadrive-rust", ); refused( &mut system("h32-sprites.bin", "genesis", "3button"), &data, "another cartridge", ); refused( &mut system("board-tour.bin", "megadrive", "3button"), &data, "not the", ); refused( &mut system("board-tour.bin", "genesis", "6button"), &data, "wired otherwise", ); let mut damaged = data.clone(); damaged.truncate(data.len() - 20); let mut target = system("board-tour.bin", "genesis", "3button"); for _ in 0..50 { target.step().unwrap(); } refused(&mut target, &damaged, "damaged body"); } #[test] fn the_host_settings_stay_the_hosts() { let mut whole = system("board-tour.bin", "genesis", "3button"); whole.audio.sample_rate = 22_050; let data = save_state(&whole); let mut copy = system("board-tour.bin", "genesis", "3button"); copy.audio.sample_rate = 48_000; copy.board().dev.fm.enabled = false; copy.board().vdp.s.rendering = false; load_state(&mut copy, &data).unwrap(); assert_eq!(copy.audio.sample_rate, 48_000); assert!(!copy.board().dev.fm.enabled); assert!(!copy.board().vdp.s.rendering); } #[test] fn one_snapshot_loaded_again_and_again() { // Rewind's and run-ahead's use: the same system takes one snapshot back repeatedly. let mut system = system("board-tour.bin", "genesis", "3button"); for _ in 0..2000 { system.step().unwrap(); } let snapshot = save_snapshot(&system); let first = trail(&mut system, 1500); for _ in 0..3 { load_snapshot(&mut system, &snapshot).unwrap(); assert_eq!(trail(&mut system, 1500), first); } } /// Every line table and every frame table comes back as itself. The long and short H40 /// lines are in force only on an interlaced odd field's VSYNC lines, which no save point /// of the save-state rung happens to land on (its seeded fault "the long and short H40 /// lines swapped" went unseen there), so this holds them directly. #[test] fn every_line_and_frame_table_comes_back_as_itself() { use megadrive_rust::state::{hmode_ref, vmode_ref}; use megadrive_rust::vdp::{tables, HMode, VMode}; #[derive(serde::Serialize, serde::Deserialize)] struct Modes { #[serde(with = "hmode_ref")] h: &'static HMode, #[serde(with = "vmode_ref")] v: &'static VMode, } let t = tables(); let hs = [&t.h32, &t.h40, &t.h40_vsync, &t.h40_long, &t.h40_short]; let vs = [&t.v28_ntsc, &t.v30_ntsc, &t.v28_pal, &t.v30_pal]; for h in hs { for v in vs { let bytes = bincode::serialize(&Modes { h, v }).unwrap(); let back: Modes = bincode::deserialize(&bytes).unwrap(); assert!(std::ptr::eq(back.h, h) && std::ptr::eq(back.v, v)); } } } /// Fields the rung's save points find idle, set to live values and carried through a /// load: the Z80's EI delay (non-zero only straight after an EI), a 6-button pad part way /// through its TH sequence (it times out between frames), and a serial EEPROM part way /// through a transaction (the rung's seeded faults on all three went unseen there). #[test] fn fields_the_rung_finds_idle_survive_a_load() { let mut image = image("board-tour.bin"); image.resize(0x80000, 0xFF); let build = || { System::new( machine("genesis").unwrap(), Some(Cartridge::new(image.clone(), "rom_nbajam_alt", 0, "")), Some([ Device::by_name("6button").unwrap(), Device::by_name("3button").unwrap(), ]), None, ) }; let mut whole = build(); for _ in 0..500 { whole.step().unwrap(); } let mut z80 = whole.md().z80.capture_state(); z80.ei_delay = 1; whole.md().z80.restore_state(&z80); let dev = &mut whole.board().dev; if let Some(Device::Pad6(pad)) = &mut dev.io.ports[0].device { pad.edges = 2; pad.th_level = 0; pad.last_change = 12_345; } else { panic!("a 6-button pad on port 1"); } let eeprom = dev .cartridge .eeprom .as_mut() .expect("the NBA Jam board's EEPROM"); eeprom.address = 0x5A; eeprom.bit = 3; eeprom.reading = true; let data = save_state(&whole); let mut copy = build(); load_state(&mut copy, &data).unwrap(); assert_eq!(copy.md().z80.capture_state().ei_delay, 1); let dev = &mut copy.board().dev; match &dev.io.ports[0].device { Some(Device::Pad6(pad)) => { assert_eq!((pad.edges, pad.th_level, pad.last_change), (2, 0, 12_345)) } _ => panic!("a 6-button pad on port 1"), } let eeprom = dev.cartridge.eeprom.as_ref().unwrap(); assert_eq!( (eeprom.address, eeprom.bit, eeprom.reading), (0x5A, 3, true) ); }