// SPDX-License-Identifier: MIT //! Save states: the whole console (the reference has none: its sprite engine is a Python //! generator, which cannot be pickled; this is the transcription's own, and the lockstep //! gate's `--save-at-half` proves it continues identically). //! //! A state is the CPU's `CpuState` (w65c02's, saved between steps, where the core's //! in-step fields are idle) and every board register, memory, chip and in-flight event //! (`Hw`'s fields, serde), bincode-encoded behind a header. Left out, and kept from the //! console the state is loaded into: the cart images, the boot ROM, the machine row, the //! EEPROM's save path, the trace log and the test hook. use serde::{Deserialize, Serialize}; use w65c02::CpuState; use crate::board::{Hw, Lynx}; const MAGIC: &[u8; 8] = b"LYNXRS01"; #[derive(Serialize, Deserialize)] struct Cpu { regs: [u8; 4], // a, x, y, s pc: u16, p: u8, flags: [bool; 7], // waiting, stopped, halted, reset, irq, nmi, skipped_poll polled: [Option; 3], // i, irq, nmi } impl Cpu { fn from(s: &CpuState) -> Cpu { Cpu { regs: [s.a, s.x, s.y, s.s], pc: s.pc, p: s.p, flags: [ s.waiting, s.stopped, s.halted, s.reset_pending, s.maskable_interrupt_pending, s.non_maskable_interrupt_pending, s.skipped_poll, ], polled: [ s.polled_i, s.polled_maskable_interrupt, s.polled_non_maskable_interrupt, ], } } fn to(&self) -> CpuState { let (r, f) = (self.regs, self.flags); CpuState { a: r[0], x: r[1], y: r[2], s: r[3], pc: self.pc, p: self.p, waiting: f[0], stopped: f[1], halted: f[2], reset_pending: f[3], maskable_interrupt_pending: f[4], non_maskable_interrupt_pending: f[5], polled_i: self.polled[0], polled_maskable_interrupt: self.polled[1], polled_non_maskable_interrupt: self.polled[2], skipped_poll: f[6], } } } #[derive(Serialize, Deserialize)] struct State { cpu: Cpu, opcode: u8, hw: Hw, } impl Lynx { /// The whole console's state, between steps. pub fn save_state(&self) -> Vec { let state = State { cpu: Cpu::from(&self.cpu.capture_state()), opcode: self.cpu.opcode, hw: self.cpu.bus.clone(), }; let mut out = MAGIC.to_vec(); out.extend(bincode::serialize(&state).expect("serialise")); out } /// Load a state saved by `save_state` into this console (same cart, boot ROM and row). pub fn load_state(&mut self, data: &[u8]) -> Result<(), String> { if data.len() < 8 || &data[..8] != MAGIC { return Err("not a lynx-rust state (or another version)".into()); } let state: State = bincode::deserialize(&data[8..]).map_err(|e| e.to_string())?; let mut hw = state.hw; hw.trace = self.cpu.bus.trace.take(); let old = &self.cpu.bus; hw.port.banks = old.port.banks.clone(); if let (Some(e), Some(old_e)) = (hw.port.eeprom.as_mut(), old.port.eeprom.as_ref()) { e.path = old_e.path.clone(); } hw.rom = old.rom.clone(); hw.machine = old.machine; hw.on_sleep = old.on_sleep; self.cpu.bus = hw; self.cpu.opcode = state.opcode; self.cpu.restore_state(&state.cpu.to()) } }