// SPDX-License-Identifier: MIT //! Save states: the reference's `state.py` (megadrive-python `1e8dcd3`, specified in its //! docs/save-states.md): the whole console between two 68000 steps, as bytes, and back. //! //! As in the reference, a state is what changes as the console runs, not the wiring: it //! is loaded into a [`System`] built from the same cartridge on the same machine with the //! same devices, which keeps its configuration (the `Machine`, the HV unit, the line //! tables, the ROM image and the windows built from it at power-on, the EEPROM's board, //! the lock-on patch ROM, the SVP's ROM words) and the host's settings (the output sample //! rate, the FM generator's switch). Equivalence is the reference's test: a run saved //! between two steps and loaded into another system continues as the run that was never //! interrupted (`md-trace --save-at`, the save-state rung of `scripts/state_rung.py`). //! //! Differences forced by Rust (the precedent is famicom-rust's `state.rs`): //! //! - the format is the crate's own, not the reference's tagged JSON: a header of the same //! content (magic, version, the cartridge images' SHA-1, the machine, the wiring), read //! and checked before the body, then the zlib of the bincode of the serde-derived //! structs. A state is portable between builds of this crate, not to the reference //! (docs/save-states.md in the reference, "For the Rust tiers"); //! - the reference finds what to save by walking the object graph; here each struct says //! so with serde attributes, and a field that is configuration is `#[serde(skip)]` and //! taken from the system being loaded into ([`Config`] below, where every one is //! named). The line tables are saved as which table (`hmode_ref`, `vmode_ref`), as the //! reference saves them by name; //! - the CPUs' parts are the cores' `CpuState`s, mirrored field for field (neither core //! derives serde), and the SSP1601's fields likewise (`ssp1601`): no core changed; //! - the renderer's palettes are shared `Arc`s; they are written once each and shared //! again on loading (`palettes`). use std::sync::Arc; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::audio::AudioPath; use crate::board::Board; use crate::cartridge::Cartridge; use crate::machine::Machine; use crate::mappers::{Kind, Mapper}; use crate::render::Palette; use crate::system::{Md, System}; use crate::vdp::{tables, HMode, HVUnit, VMode}; pub const MAGIC: &[u8; 8] = b"MDRSSTAT"; /// The format's version, refused up front when it differs. Raise it whenever a saved /// field is added, removed, renamed or changes meaning anywhere (cores included). /// Version 3: the header's wiring names the expansion sockets' devices, as the /// reference's has since its sockets (this crate's own number: the formats are not /// shared). pub const VERSION: u32 = 3; // -- placeholders for what a state does not hold -------------------------------------- /// A skipped `Machine` while a state decodes; [`Config`] puts the system's own back. pub fn placeholder_machine() -> Machine { crate::machine::machine("genesis").expect("the genesis machine exists") } /// A skipped HV unit while a state decodes; [`Config`] puts the system's own back. pub fn placeholder_hv_unit() -> &'static HVUnit { &crate::vdp::PAL_MODEL1 } // -- the line tables, by which one ---------------------------------------------------- /// `VdpState::hmode`: the table's `id` (0 H32, 1 H40, 2 H40 on VSYNC lines, 3 long, 4 /// short), as the reference writes `megadrive_python.vdp:H40` and its siblings by name. pub mod hmode_ref { use super::*; pub fn serialize(mode: &&'static HMode, s: S) -> Result { s.serialize_u8(mode.id as u8) } pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<&'static HMode, D::Error> { let t = tables(); Ok(match u8::deserialize(d)? { 0 => &t.h32, 1 => &t.h40, 2 => &t.h40_vsync, 3 => &t.h40_long, 4 => &t.h40_short, id => return Err(serde::de::Error::custom(format!("no line table {id}"))), }) } } /// `VdpState::vmode`: 0 V28 NTSC, 1 V30 NTSC, 2 V28 PAL, 3 V30 PAL. pub mod vmode_ref { use super::*; fn all() -> [&'static VMode; 4] { let t = tables(); [&t.v28_ntsc, &t.v30_ntsc, &t.v28_pal, &t.v30_pal] } pub fn serialize(mode: &&'static VMode, s: S) -> Result { let index = all() .iter() .position(|m| std::ptr::eq(*m, *mode)) .ok_or_else(|| { serde::ser::Error::custom("a VDP frame table that is not one of the four") })?; s.serialize_u8(index as u8) } pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<&'static VMode, D::Error> { let index = u8::deserialize(d)? as usize; all() .get(index) .copied() .ok_or_else(|| serde::de::Error::custom(format!("no frame table {index}"))) } } // -- the renderer's palettes ---------------------------------------------------------- fn flat(palette: &Palette) -> Vec { palette.iter().flatten().copied().collect() } fn unflat(words: &[u32]) -> Option> { if words.len() != 3 * 64 { return None; } let mut palette = [[0u32; 64]; 3]; for (shade, row) in palette.iter_mut().enumerate() { row.copy_from_slice(&words[shade * 64..shade * 64 + 64]); } Some(Arc::new(palette)) } /// `Renderer::palettes`, `done_palettes`: every distinct palette once, and per row the /// (x, which palette) pairs, so the rows share them again when loaded. Only the colours /// matter to the renderer, never which `Arc` holds them. pub mod palettes { use super::*; type Rows = Vec)>>; pub fn serialize(rows: &Rows, s: S) -> Result { let mut table: Vec<&Arc> = Vec::new(); let mut out: Vec> = Vec::with_capacity(rows.len()); for row in rows { let mut line = Vec::with_capacity(row.len()); for (x, palette) in row { // By content, not by pointer, so equal states write equal bytes. let index = match table.iter().position(|p| ***p == **palette) { Some(index) => index, None => { table.push(palette); table.len() - 1 } }; line.push((*x, index as u32)); } out.push(line); } let words: Vec> = table.iter().map(|p| flat(p)).collect(); (words, out).serialize(s) } pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result { let (words, rows) = <(Vec>, Vec>)>::deserialize(d)?; let table: Vec> = words .iter() .map(|w| { unflat(w).ok_or_else(|| serde::de::Error::custom("a palette of the wrong size")) }) .collect::>()?; rows.into_iter() .map(|row| { row.into_iter() .map(|(x, index)| { table .get(index as usize) .map(|p| (x, Arc::clone(p))) .ok_or_else(|| serde::de::Error::custom("a palette not saved")) }) .collect() }) .collect() } } /// `Renderer::palette`. pub mod palette { use super::*; pub fn serialize( palette: &Option>, s: S, ) -> Result { palette.as_deref().map(flat).serialize(s) } pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result>, D::Error> { match Option::>::deserialize(d)? { None => Ok(None), Some(words) => unflat(&words) .map(Some) .ok_or_else(|| serde::de::Error::custom("a palette of the wrong size")), } } } // -- the SVP's DSP ---------------------------------------------------------------------- /// `Svp::dsp`: ssp1601-rust's `Ssp1601`, field for field (every field is public). pub mod ssp1601 { use super::*; use ssp1601_rust::Ssp1601; #[derive(Serialize, Deserialize)] struct Fields { x: u16, y: u16, a: u32, st: u16, pc: u16, ppc: u16, stack: [u16; 6], sp: i32, r: [u8; 8], ram: Vec, cycles: u32, unhandled: u64, } pub fn serialize(dsp: &Ssp1601, s: S) -> Result { Fields { x: dsp.x, y: dsp.y, a: dsp.a, st: dsp.st, pc: dsp.pc, ppc: dsp.ppc, stack: dsp.stack, sp: dsp.sp, r: dsp.r, ram: dsp.ram.to_vec(), cycles: dsp.cycles, unhandled: dsp.unhandled, } .serialize(s) } pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result { let f = Fields::deserialize(d)?; let mut dsp = Ssp1601::new(); if f.ram.len() != dsp.ram.len() { return Err(serde::de::Error::custom("the DSP's RAM is the wrong size")); } dsp.x = f.x; dsp.y = f.y; dsp.a = f.a; dsp.st = f.st; dsp.pc = f.pc; dsp.ppc = f.ppc; dsp.stack = f.stack; dsp.sp = f.sp; dsp.r = f.r; dsp.ram.copy_from_slice(&f.ram); dsp.cycles = f.cycles; dsp.unhandled = f.unhandled; Ok(dsp) } } // -- the CPUs --------------------------------------------------------------------------- /// m68000-rust's `CpuState`, field for field. #[derive(Serialize, Deserialize)] struct M68kFields { d: [u32; 8], a: [u32; 7], usp: u32, ssp: u32, sr: u16, pc: u32, ir: u16, irc: u16, ipl: u8, nmi_edge: bool, trace_pending: bool, stopped: bool, halted: bool, clock: u64, } impl From for M68kFields { fn from(s: m68000_rust::CpuState) -> Self { M68kFields { d: s.d, a: s.a, usp: s.usp, ssp: s.ssp, sr: s.sr, pc: s.pc, ir: s.ir, irc: s.irc, ipl: s.ipl, nmi_edge: s.nmi_edge, trace_pending: s.trace_pending, stopped: s.stopped, halted: s.halted, clock: s.clock, } } } impl From for m68000_rust::CpuState { fn from(f: M68kFields) -> Self { m68000_rust::CpuState { d: f.d, a: f.a, usp: f.usp, ssp: f.ssp, sr: f.sr, pc: f.pc, ir: f.ir, irc: f.irc, ipl: f.ipl, nmi_edge: f.nmi_edge, trace_pending: f.trace_pending, stopped: f.stopped, halted: f.halted, clock: f.clock, } } } /// z80-rust's `CpuState`, field for field. #[derive(Serialize, Deserialize)] struct Z80Fields { a: u8, f: u8, b: u8, c: u8, d: u8, e: u8, h: u8, l: u8, ix: u16, iy: u16, sp: u16, pc: u16, wz: u16, i: u8, r: u8, iff1: bool, iff2: bool, im: u8, af_alt: u16, bc_alt: u16, de_alt: u16, hl_alt: u16, q: u8, halted: bool, ei_delay: u8, reset_pending: bool, maskable_interrupt_vector: Option, non_maskable_interrupt_pending: bool, } impl From for Z80Fields { fn from(s: z80_rust::CpuState) -> Self { Z80Fields { a: s.a, f: s.f, b: s.b, c: s.c, d: s.d, e: s.e, h: s.h, l: s.l, ix: s.ix, iy: s.iy, sp: s.sp, pc: s.pc, wz: s.wz, i: s.i, r: s.r, iff1: s.iff1, iff2: s.iff2, im: s.im, af_alt: s.af_alt, bc_alt: s.bc_alt, de_alt: s.de_alt, hl_alt: s.hl_alt, q: s.q, halted: s.halted, ei_delay: s.ei_delay, reset_pending: s.reset_pending, maskable_interrupt_vector: s.maskable_interrupt_vector, non_maskable_interrupt_pending: s.non_maskable_interrupt_pending, } } } impl From for z80_rust::CpuState { fn from(f: Z80Fields) -> Self { z80_rust::CpuState { a: f.a, f: f.f, b: f.b, c: f.c, d: f.d, e: f.e, h: f.h, l: f.l, ix: f.ix, iy: f.iy, sp: f.sp, pc: f.pc, wz: f.wz, i: f.i, r: f.r, iff1: f.iff1, iff2: f.iff2, im: f.im, af_alt: f.af_alt, bc_alt: f.bc_alt, de_alt: f.de_alt, hl_alt: f.hl_alt, q: f.q, halted: f.halted, ei_delay: f.ei_delay, reset_pending: f.reset_pending, maskable_interrupt_vector: f.maskable_interrupt_vector, non_maskable_interrupt_pending: f.non_maskable_interrupt_pending, } } } // -- the scheduler ---------------------------------------------------------------------- /// `Md`'s own fields, but the Z80 (its `CpuState` and the board are saved apart) and /// `z80_timings`, a pure cache of z80-rust's access offsets by instruction bytes (the /// reference's `SKIPPED`). #[derive(Serialize, Deserialize)] struct MdFields { mclk: i64, z80_mclk: i64, in_z80: bool, m68k_instructions: u64, z80_instructions: u64, z80_deferred: u64, z80_partial: Option<(i64, i64)>, stall_credited: i64, acknowledge_credit: u64, reset_pressed: bool, reset_at: i64, probe_bus_ends: Vec<(i64, i64)>, probe_bus_cart: Vec, } impl MdFields { fn of(md: &Md) -> Self { MdFields { mclk: md.mclk, z80_mclk: md.z80_mclk, in_z80: md.in_z80, m68k_instructions: md.m68k_instructions, z80_instructions: md.z80_instructions, z80_deferred: md.z80_deferred, z80_partial: md.z80_partial, stall_credited: md.stall_credited, acknowledge_credit: md.acknowledge_credit, reset_pressed: md.reset_pressed, reset_at: md.reset_at, probe_bus_ends: md.probe_bus_ends.clone(), probe_bus_cart: md.probe_bus_cart.clone(), } } fn put(self, md: &mut Md) { md.mclk = self.mclk; md.z80_mclk = self.z80_mclk; md.in_z80 = self.in_z80; md.m68k_instructions = self.m68k_instructions; md.z80_instructions = self.z80_instructions; md.z80_deferred = self.z80_deferred; md.z80_partial = self.z80_partial; md.stall_credited = self.stall_credited; md.acknowledge_credit = self.acknowledge_credit; md.reset_pressed = self.reset_pressed; md.reset_at = self.reset_at; md.probe_bus_ends = self.probe_bus_ends; md.probe_bus_cart = self.probe_bus_cart; } } // -- configuration: what a loaded board takes from the system it is loaded into --------- /// The configuration a state does not hold, moved from the live board into the decoded /// one. Every skipped field of the board is here (the reference's "What is not saved"): /// /// - `Devices::machine`, `VdpState::machine`, `VdpState::hv_unit`; /// - per cartridge (the slot's, and a lock-on board's second): `image`, `rom`, `full`, /// `eeprom_board`; its mapper's `rom`, `padded`, `constants`, `time_words`; Rock /// Heaven's word table; Sonic & Knuckles's patch ROM; the SVP's ROM words; /// - the TMSS boot ROM's `image` and `rom`; /// - the expansion sockets' wiring (src/sockets.rs): `Devices::slot_cartridge`, `slot`, /// `port`, `devices`, `device_names`, `pages` (and `low`, made again from them), /// `Cartridge::grounds_cart`, `Vdp::video_timing` and the renderer's picture device. /// What lives only while a device is attached -- the device's own state, the /// renderer's line waiting to be handed over and the rows the device returned, the /// audio path's leftovers of each further source -- is the device's side and is not /// in a state either; the reference saves it only for a device of a package of its /// `MODULES` and refuses a state of any other, where this crate saves the board's side /// alone; /// - and the host's settings `YM2612::enabled` (the FM generator's switch), which the /// core saves with the chip, and `VdpState::rendering` (the drawing switch, since /// version 2, when it stopped changing anything software sees) with /// `VdpState::undrawn_frame`. /// /// [`Config::fits`] checks the two boards have the same shape before anything moves, so /// [`Config::adopt`] cannot fail half way. struct Config; impl Config { fn fits(live: &Board, new: &Board) -> Result<(), String> { Self::cartridge_fits(&live.dev.cartridge, &new.dev.cartridge)?; if live.dev.tmss_rom.is_some() != new.dev.tmss_rom.is_some() { return Err("a state of a console with another boot ROM".into()); } Ok(()) } fn cartridge_fits(live: &Cartridge, new: &Cartridge) -> Result<(), String> { match (&live.board, &new.board) { (None, None) => Ok(()), (Some(l), Some(n)) => Self::mapper_fits(l, n), _ => Err("a state of a cartridge on another board".into()), } } fn mapper_fits(live: &Mapper, new: &Mapper) -> Result<(), String> { if std::mem::discriminant(&live.kind) != std::mem::discriminant(&new.kind) { return Err("a state of a cartridge on another board".into()); } let subs = match (&live.kind, &new.kind) { (Kind::SonicAndKnuckles { sub: l, .. }, Kind::SonicAndKnuckles { sub: n, .. }) | (Kind::GameGenie { sub: l, .. }, Kind::GameGenie { sub: n, .. }) => Some((l, n)), _ => None, }; match subs { Some((Some(l), Some(n))) => Self::cartridge_fits(l, n), Some((None, None)) | None => Ok(()), Some(_) => Err("a state of a lock-on board holding another cartridge".into()), } } /// Move the configuration from `live` into `new` (after [`Config::fits`]). fn adopt(live: &mut Board, new: &mut Board) { new.dev.machine = live.dev.machine; // The host's setting, not the console's (the reference's `HOST`). new.dev.fm.enabled = live.dev.fm.enabled; new.vdp.s.rendering = live.vdp.s.rendering; new.vdp.s.undrawn_frame = live.vdp.s.undrawn_frame; new.vdp.s.machine = live.vdp.s.machine; new.vdp.s.hv_unit = live.vdp.s.hv_unit; Self::adopt_cartridge(&mut live.dev.cartridge, &mut new.dev.cartridge); if let (Some(l), Some(n)) = (&mut live.dev.tmss_rom, &mut new.dev.tmss_rom) { std::mem::swap(&mut l.image, &mut n.image); std::mem::swap(&mut l.rom, &mut n.rom); } // The expansion sockets: their devices and the claims are wiring (the header has // said the devices are the same kinds); what answers $000000-$3FFFFF follows from // them and from the saved TMSS select. let (l, n) = (&mut live.dev, &mut new.dev); n.slot_cartridge = l.slot_cartridge; n.slot = l.slot.take(); n.port = l.port.take(); n.devices = std::mem::take(&mut l.devices); n.device_names = l.device_names; n.pages = l.pages.take(); n.remap(); new.vdp.video_timing = live.vdp.video_timing.take(); new.vdp.renderer.adopt_picture(&mut live.vdp.renderer); } fn adopt_cartridge(live: &mut Cartridge, new: &mut Cartridge) { std::mem::swap(&mut live.image, &mut new.image); std::mem::swap(&mut live.rom, &mut new.rom); std::mem::swap(&mut live.full, &mut new.full); new.eeprom_board = live.eeprom_board; new.grounds_cart = live.grounds_cart; new.sda_line = live.sda_line; if let (Some(l), Some(n)) = (&mut live.board, &mut new.board) { Self::adopt_mapper(l, n); } } fn adopt_mapper(live: &mut Mapper, new: &mut Mapper) { std::mem::swap(&mut live.rom, &mut new.rom); std::mem::swap(&mut live.padded, &mut new.padded); new.constants = live.constants; new.time_words = live.time_words; match (&mut live.kind, &mut new.kind) { (Kind::RockHeaven(l), Kind::RockHeaven(n)) => *n = *l, ( Kind::SonicAndKnuckles { sub: ls, patch: lp, .. }, Kind::SonicAndKnuckles { sub: ns, patch: np, .. }, ) => { std::mem::swap(lp, np); if let (Some(l), Some(n)) = (ls, ns) { Self::adopt_cartridge(l, n); } } (Kind::GameGenie { sub: ls, .. }, Kind::GameGenie { sub: ns, .. }) => { if let (Some(l), Some(n)) = (ls, ns) { Self::adopt_cartridge(l, n); } } (Kind::Svp(l), Kind::Svp(n)) => { std::mem::swap(&mut l.memory.rom_words, &mut n.memory.rom_words); } _ => {} } } } // -- the header ------------------------------------------------------------------------- #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)] struct Wiring { tmss_rom: String, ports: [String; 3], /// The expansion sockets' devices, by name ("" for none; `BusDevice::name`). slot: String, port: String, } #[derive(Serialize, Deserialize)] struct Header { version: u32, rom_sha1: String, machine: String, wiring: Wiring, } fn sha1_hex(parts: &[&[u8]]) -> String { let mut digest = sha1_smol::Sha1::new(); for part in parts { digest.update(part); } digest.digest().to_string() } /// The reference's `rom_sha1`: the slot's cartridge image, then a lock-on board's patch /// ROM and the cartridge plugged into its top, and so on. fn images(cartridge: &Cartridge) -> Vec<&[u8]> { let mut out: Vec<&[u8]> = Vec::new(); let mut at = Some(cartridge); while let Some(cartridge) = at { out.push(&cartridge.image); at = None; if let Some(board) = &cartridge.board { match &board.kind { Kind::SonicAndKnuckles { sub, patch, .. } => { if !patch.is_empty() { out.push(patch); } at = sub.as_deref(); } Kind::GameGenie { sub, .. } => at = sub.as_deref(), _ => {} } } } out } fn header(system: &System) -> Header { let dev = &system.m68k.bus.z80.bus.dev; Header { version: VERSION, // "" for an empty slot (its bus's stand-in is not a cartridge). rom_sha1: if dev.slot_cartridge { sha1_hex(&images(&dev.cartridge)) } else { String::new() }, machine: system.machine.name.to_string(), wiring: Wiring { tmss_rom: dev .tmss_rom .as_ref() .map_or_else(String::new, |boot| sha1_hex(&[&boot.image])), ports: std::array::from_fn(|i| { dev.io.ports[i] .device .as_ref() .map_or_else(String::new, |d| d.kind().to_string()) }), slot: dev.device_names[0].to_string(), port: dev.device_names[1].to_string(), }, } } // -- the body --------------------------------------------------------------------------- #[derive(Serialize)] struct BodyRef<'a> { m68k: M68kFields, z80: Z80Fields, md: MdFields, board: &'a Board, audio: &'a AudioPath, } #[derive(Deserialize)] struct Body { m68k: M68kFields, z80: Z80Fields, md: MdFields, board: Board, audio: AudioPath, } fn body_bytes(system: &System) -> Vec { let md = &system.m68k.bus; let body = BodyRef { m68k: system.m68k.capture_state().into(), z80: md.z80.capture_state().into(), md: MdFields::of(md), board: &md.z80.bus, audio: &system.audio, }; bincode::serialize(&body).expect("a state serializes") } /// All or nothing: the body is decoded, the CPU states validated by their cores' own /// rules and the boards' shapes compared before anything of `system` changes. fn load_body(system: &mut System, mut body: Body) -> Result<(), String> { let m68k: m68000_rust::CpuState = body.m68k.into(); m68k.validate()?; let z80: z80_rust::CpuState = body.z80.into(); z80.validate()?; Config::fits(&system.m68k.bus.z80.bus, &body.board)?; let md = &mut system.m68k.bus; Config::adopt(&mut md.z80.bus, &mut body.board); md.z80.bus = body.board; md.z80.restore_state(&z80); body.md.put(md); body.audio.machine = system.audio.machine; body.audio.sample_rate = system.audio.sample_rate; system.audio = body.audio; system.m68k.restore_state(&m68k); Ok(()) } /// The state of `system` as bytes, between two of its steps ([`System::step`]). pub fn save_state(system: &System) -> Vec { let mut out = MAGIC.to_vec(); out.extend(bincode::serialize(&header(system)).expect("a header serializes")); let mut encoder = flate2::write::ZlibEncoder::new(out, flate2::Compression::new(6)); std::io::Write::write_all(&mut encoder, &body_bytes(system)).expect("compression in memory"); encoder.finish().expect("compression in memory") } /// Put `system` in the state `data` was saved from (the same cartridge, machine and /// wiring); refused before anything changes otherwise. pub fn load_state(system: &mut System, data: &[u8]) -> Result<(), String> { if data.len() < MAGIC.len() || &data[..MAGIC.len()] != MAGIC { return Err("not a megadrive-rust save state".into()); } let mut rest = &data[MAGIC.len()..]; let saved: Header = bincode::deserialize_from(&mut rest).map_err(|e| format!("a damaged header: {e}"))?; if saved.version != VERSION { return Err(format!( "a state of version {}, not {VERSION}", saved.version )); } let live = header(system); if saved.rom_sha1 != live.rom_sha1 { return Err("a state of another cartridge".into()); } if saved.machine != live.machine { return Err(format!( "a state of the {}, not the {}", saved.machine, live.machine )); } if saved.wiring != live.wiring { return Err(format!( "a state of a console wired otherwise ({:?})", saved.wiring )); } let body: Body = bincode::deserialize_from(flate2::read::ZlibDecoder::new(rest)) .map_err(|e| format!("a damaged body: {e}"))?; load_body(system, body) } /// The state of `system` for this same system to take back soon ([`load_snapshot`]): what /// a frontend saves and loads every frame to rewind or to run ahead. It is /// [`save_state`]'s body without the header (whose hash of the ROM costs more than it /// should every frame) and without the compression, so it is not a file to keep: nothing /// checks that it is loaded into the system, or even the build, that made it. pub fn save_snapshot(system: &System) -> Vec { body_bytes(system) } /// Everything of `system`'s state but its picture: [`save_snapshot`]'s bytes with the /// renderer holding only the fields software can see the effects of (`render::SEEN`), as /// the reference's `state.machine_state`. Two runs of one cartridge, one drawing its frames /// and one not (`VdpState::rendering`), give equal bytes at every step. Not a state to load. pub fn machine_snapshot(system: &mut System) -> Vec { let vdp = &mut system.m68k.bus.z80.bus.vdp; let seen = vdp.renderer.seen(); let picture = std::mem::replace(&mut vdp.renderer, seen); let out = body_bytes(system); system.m68k.bus.z80.bus.vdp.renderer = picture; out } /// Put `system` back where [`save_snapshot`] found it. pub fn load_snapshot(system: &mut System, data: &[u8]) -> Result<(), String> { let body: Body = bincode::deserialize(data).map_err(|e| e.to_string())?; load_body(system, body) }