// SPDX-License-Identifier: MIT //! Whole-machine save states: CPU, RAM, ANTIC, GTIA, POKEY, the cartridge and the board. //! //! A state is a plain value (serialisable); `save`/`load` write and read it //! under `~/.local/share/a5200-rust/saves/` unless given a path. The //! cartridge payload and BIOS are not stored, only the cartridge's SHA-1 and its //! bank state: a state is restored onto a console holding the same cartridge. //! //! A transcription of a5200-python's `state.py` (at cf82d44). Rust-forced differences: the //! dict is the [`State`] struct with the same keys as fields, written with bincode (Python //! pickles), so the two boards' files are not interchangeable; the saves folder is //! `a5200-rust` (not the reference's, whose pickles these are not); the CPU's state is //! [`CpuFields`], a serialisable copy of 6502-rust's `CpuState`; `BOARD_FIELDS` is the //! [`BoardFields`] struct; errors are `Err(String)` (Python's `ValueError`), and //! `zip(..., strict=True)`'s `ValueError` is a length check before each loop; a pad's //! key set is copied by `Pad::clone` (`_copied`), the trak-balls' lag outputs are saved as //! `[f64; 2]` pairs. use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; use sixfiveohtwo::CpuState; use crate::antic::ANTIC; use crate::controllers::Pad; use crate::gtia::GTIA; use crate::system::Console; pub fn save_dir() -> PathBuf { let home = std::env::var_os("HOME") .map(PathBuf::from) .unwrap_or_default(); home.join(".local/share/a5200-rust/saves") } // 2: pokey-python e276d27 changed the shape of chip.pot in its snapshots, so // states made at the old pin (5a06587, version 1) do not restore. // 3: the restarted pokey-python (6ed1ffa) has a new snapshot shape, and the pot // capacitors (pokey_python.rc.PotRC) are saved with their charge. // 4: the CX53 trak-balls' lag output, the trak-ball pins and the pot targets are // saved and restored as they stand (restore no longer calls Controllers.apply(), // which stepped the lag once more); the pads' key sets are copied at the save. pub const VERSION: u32 = 4; /// A pad's fields with its key set copied: the frontend mutates it in place. /// /// Rust: `Pad::clone` already copies the `BTreeSet`, so this is the clone. fn _copied(fields: &Pad) -> Pad { fields.clone() } /// `cpu.capture_state()` as plain values. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct CpuFields { pub a: u8, pub x: u8, pub y: u8, pub s: u8, pub pc: u16, pub p: u8, pub halted: bool, pub reset_pending: bool, pub maskable_interrupt_pending: bool, pub non_maskable_interrupt_pending: bool, pub polled_i: Option, pub polled_maskable_interrupt: Option, pub polled_non_maskable_interrupt: Option, pub skipped_poll: bool, } impl From for CpuFields { fn from(s: CpuState) -> Self { CpuFields { a: s.a, x: s.x, y: s.y, s: s.s, pc: s.pc, p: s.p, halted: s.halted, reset_pending: s.reset_pending, maskable_interrupt_pending: s.maskable_interrupt_pending, non_maskable_interrupt_pending: s.non_maskable_interrupt_pending, polled_i: s.polled_i, polled_maskable_interrupt: s.polled_maskable_interrupt, polled_non_maskable_interrupt: s.polled_non_maskable_interrupt, skipped_poll: s.skipped_poll, } } } impl From for CpuState { fn from(s: CpuFields) -> Self { CpuState { a: s.a, x: s.x, y: s.y, s: s.s, pc: s.pc, p: s.p, halted: s.halted, reset_pending: s.reset_pending, maskable_interrupt_pending: s.maskable_interrupt_pending, non_maskable_interrupt_pending: s.non_maskable_interrupt_pending, polled_i: s.polled_i, polled_maskable_interrupt: s.polled_maskable_interrupt, polled_non_maskable_interrupt: s.polled_non_maskable_interrupt, skipped_poll: s.skipped_poll, } } } /// `BOARD_FIELDS`: the board's own counters and latches. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct BoardFields { pub cycles: u64, pub halted_cycles: u64, pub stalled_cycles: u64, pub data_bus: u8, pub frames: u64, pub _irq_line: bool, pub _irq_next: bool, pub _stack_writes: u32, pub _last_read: i32, pub nmis_lost: u64, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PotRcState { pub target: Vec>, pub charge: Vec, pub when: Vec, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct State { pub version: u32, pub machine: String, pub cart_sha1: String, pub cpu: CpuFields, pub ram: Vec, pub frame: Vec, pub antic: ANTIC, pub gtia: GTIA, pub pokey: pokey::State, pub cartridge: Vec, pub board: BoardFields, pub pads: Vec, pub trak_balls: Vec<[f64; 2]>, pub trak_pins: Vec, pub pot_rc: PotRcState, } pub fn snapshot(console: &Console) -> State { let board = console.board(); let controllers = &console.controllers; let rc = controllers.rc.borrow(); State { version: VERSION, machine: console.machine.name.to_string(), cart_sha1: console.cart.sha1.clone(), cpu: console.cpu.capture_state().into(), ram: board.ram.clone(), frame: board.frame.clone(), antic: board.antic.snapshot(), gtia: board.gtia.snapshot(), pokey: board.pokey.snapshot(), cartridge: board.cartridge.snapshot(), board: BoardFields { cycles: board.cycles, halted_cycles: board.halted_cycles, stalled_cycles: board.stalled_cycles, data_bus: board.data_bus, frames: board.frames, _irq_line: board._irq_line, _irq_next: board._irq_next, _stack_writes: board._stack_writes, _last_read: board._last_read, nmis_lost: board.nmis_lost, }, pads: controllers.pads.borrow().iter().map(_copied).collect(), trak_balls: controllers._balls.iter().map(|ball| ball.out).collect(), trak_pins: controllers._trak_pins.get().to_vec(), pot_rc: PotRcState { target: rc.target.clone(), charge: rc.charge.clone(), when: rc.when.clone(), }, } } pub fn restore(console: &mut Console, state: &State) -> Result<(), String> { if state.version != VERSION { return Err(format!( "save state version {} is not {VERSION}", state.version )); } if state.machine != console.machine.name { return Err(format!( "the save state belongs to machine {}", state.machine )); } if state.cart_sha1 != console.cart.sha1 { return Err("the save state belongs to another cartridge".to_string()); } console.cpu.restore_state(&state.cpu.into())?; let board = console.board_mut(); board.ram.copy_from_slice(&state.ram); board.frame.copy_from_slice(&state.frame); board.antic.restore(&state.antic); board.gtia.restore(&state.gtia); board.pokey.restore(&state.pokey); board.cartridge.restore(&state.cartridge); let b = state.board; board.cycles = b.cycles; board.halted_cycles = b.halted_cycles; board.stalled_cycles = b.stalled_cycles; board.data_bus = b.data_bus; board.frames = b.frames; board._irq_line = b._irq_line; board._irq_next = b._irq_next; board._stack_writes = b._stack_writes; board._last_read = b._last_read; board.nmis_lost = b.nmis_lost; let controllers = &mut console.controllers; { let mut pads = controllers.pads.borrow_mut(); // zip(..., strict=True) if pads.len() != state.pads.len() { return Err("zip() arguments differ in length (pads)".to_string()); } for (pad, saved) in pads.iter_mut().zip(state.pads.iter()) { *pad = saved.clone(); } } // What Controllers.apply() derived at the last frame start is restored as it // stood, never re-derived: apply() steps the trak-ball lag and re-sets GTIA's // trigger latches, and the pads may have changed since it ran (a5200-rust's // finding, 2026-11-14). The pot capacitors (pokey_python.rc.PotRC) are // rewired to the restored chip with their targets and charge. // zip(..., strict=True) if controllers._balls.len() != state.trak_balls.len() { return Err("zip() arguments differ in length (trak_balls)".to_string()); } for (ball, out) in controllers._balls.iter_mut().zip(state.trak_balls.iter()) { ball.out = *out; } let mut trak_pins = [false; 8]; trak_pins.copy_from_slice(&state.trak_pins); controllers._trak_pins.set(trak_pins); controllers.wire_pots(&mut console.cpu.bus); let mut rc = controllers.rc.borrow_mut(); rc.target.clone_from(&state.pot_rc.target); rc.charge.copy_from_slice(&state.pot_rc.charge); rc.when.copy_from_slice(&state.pot_rc.when); Ok(()) } pub fn to_bytes(state: &State) -> Vec { bincode::serialize(state).expect("a state serialises") } pub fn from_bytes(data: &[u8]) -> Result { bincode::deserialize(data).map_err(|e| e.to_string()) } pub fn save(console: &Console, path: Option<&Path>) -> std::io::Result { let path = match path { Some(p) => p.to_path_buf(), None => { let dir = save_dir(); std::fs::create_dir_all(&dir)?; dir.join(format!("{}.state", &console.cart.sha1[..12])) } }; std::fs::write(&path, to_bytes(&snapshot(console)))?; Ok(path) } pub fn load(console: &mut Console, path: Option<&Path>) -> Result<(), String> { let path = match path { Some(p) => p.to_path_buf(), None => save_dir().join(format!("{}.state", &console.cart.sha1[..12])), }; let data = std::fs::read(&path).map_err(|e| e.to_string())?; restore(console, &from_bytes(&data)?) }