//! Input movies: everything a player did, frame by frame from power-on, so //! the deterministic board replays a run exactly. A movie holds only the //! DIP switches and the control bits (no ROM or RAM contents), plus a //! checksum of the board's RAM at the end, which a replay must reproduce. //! //! Frame f's controls are the ones held while the board runs frame f //! (`Machine::set_controls` before `run_frame`). They are stored as change //! points: `[frame, in0, in1]` whenever the pair differs from the frame //! before, starting from nothing pressed. use serde::{Deserialize, Serialize}; use super::bus::Cpu; use super::paths::PathMod; use super::Machine; pub const FORMAT: &str = "galaga-remix movie 1"; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Movie { pub format: String, /// MAME's DSWA and DSWB bytes, set before the first frame. pub dsw_a: u8, pub dsw_b: u8, pub frames: u64, /// `[frame, in0, in1]` change points of the pressed-control bits. pub changes: Vec<(u64, u8, u8)>, /// CRC-32 of video RAM and the three work RAMs after the last frame. pub final_ram_crc32: u32, /// Free text: how it was made, what happens in it. #[serde(default)] pub note: String, /// Remix: program patches applied before the first frame (path mods, /// `galaga::paths::PathMod`); a movie of the unmodified game has none. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub patches: Vec, /// Remix: the path mod played with, as its source text; applied (and /// checked) against the player's ROM before the first frame, so no bytes /// derived from the ROM live in the movie. #[serde(default, skip_serializing_if = "Option::is_none")] pub path_mod: Option, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct ModSource { pub name: String, pub text: String, } /// Bytes laid over one CPU's program space. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Patch { /// "maincpu", "sub" or "sub2" (`Cpu::from_name`). pub cpu: String, pub at: u16, /// Hex. pub bytes: String, /// Which mod it came from. #[serde(default)] pub source: String, } impl Movie { /// A movie of `inputs` (one pair per frame) played from power-on with /// these DIPs; `final_ram_crc32` is filled from `machine`, which must be /// the board that ran them. pub fn from_inputs( dsw_a: u8, dsw_b: u8, inputs: &[[u8; 2]], machine: &Machine, note: &str, ) -> Movie { let mut changes = Vec::new(); let mut last = [0u8; 2]; for (frame, &pair) in inputs.iter().enumerate() { if pair != last { changes.push((frame as u64, pair[0], pair[1])); last = pair; } } Movie { format: FORMAT.to_string(), dsw_a, dsw_b, frames: inputs.len() as u64, changes, final_ram_crc32: ram_crc32(machine), note: note.to_string(), patches: Vec::new(), path_mod: None, } } /// The patches of a path mod over this sub ROM (checksum byte included), /// for a movie played with it. Prefer `path_mod` for new movies. pub fn patches_of(path_mod: &PathMod, sub_rom: &[u8]) -> Vec { path_mod .runs_for(sub_rom) .unwrap() .iter() .map(|(at, bytes)| Patch { cpu: "sub".into(), at: *at, bytes: bytes.iter().map(|b| format!("{b:02x}")).collect(), source: path_mod.name.clone(), }) .collect() } /// A fresh board ready for frame 0: DIPs set, patches applied. pub fn setup(&self, machine: &mut Machine) -> Result<(), String> { machine.set_dips(self.dsw_a, self.dsw_b); for patch in &self.patches { let cpu = Cpu::from_name(&patch.cpu).ok_or(format!("unknown CPU {}", patch.cpu))?; let bytes = (0..patch.bytes.len()) .step_by(2) .map(|i| u8::from_str_radix(&patch.bytes[i..i + 2], 16)) .collect::, _>>() .map_err(|e| format!("patch at 0x{:04x}: {e}", patch.at))?; machine.patch_rom(cpu, patch.at, &bytes)?; } if let Some(source) = &self.path_mod { let path_mod = PathMod::parse(&source.name, &source.text)?; let sub_rom = machine.cpu(Cpu::Sub).bus.program()[..0x1000].to_vec(); path_mod.check(&sub_rom)?; path_mod.apply(machine)?; } Ok(()) } /// The movie's path mod, parsed (for its sprites: `PathMod::apply_video`). pub fn path_mod(&self) -> Result, String> { self.path_mod .as_ref() .map(|source| PathMod::parse(&source.name, &source.text)) .transpose() } /// The controls for every frame. pub fn inputs(&self) -> Vec<[u8; 2]> { let mut out = Vec::with_capacity(self.frames as usize); let mut current = [0u8; 2]; let mut next = 0; for frame in 0..self.frames { while next < self.changes.len() && self.changes[next].0 <= frame { current = [self.changes[next].1, self.changes[next].2]; next += 1; } out.push(current); } out } pub fn from_json(text: &str) -> Result { let movie: Movie = serde_json::from_str(text).map_err(|e| e.to_string())?; if movie.format != FORMAT { return Err(format!("not a {FORMAT:?} file: {:?}", movie.format)); } Ok(movie) } pub fn to_json(&self) -> String { serde_json::to_string(self).unwrap() } } /// CRC-32 over video RAM and work RAMs 1-3, the replay's identity check. pub fn ram_crc32(machine: &Machine) -> u32 { let s = machine.shared.borrow(); let mut h = crc32fast::Hasher::new(); h.update(&s.video_ram); h.update(&s.ram1); h.update(&s.ram2); h.update(&s.ram3); h.finalize() }