//! The wasm-bindgen surface: the verified ROM set in, frames of pixels and //! sound out, controls and DIP switches in, a snapshot string for //! save-and-resume, and a rewind window of recent snapshots. Strings and typed //! arrays only, so the JS needs no glue. //! A crate of its own so the board crate stays a plain rlib for its tests //! and tools (a cdylib+rlib lib collides with itself under `cargo test`). use std::collections::VecDeque; use std::io::{Read, Write}; use wasm_bindgen::prelude::*; use emu_galaga::galaga::roms::{self, RomSet}; use emu_galaga::galaga::snapshot::Snapshot; use emu_galaga::galaga::sound::{Sound, SAMPLES_PER_FRAME}; use emu_galaga::galaga::video::{Video, SCREEN_HEIGHT, SCREEN_WIDTH}; use emu_galaga::galaga::Machine; /// What this build is. #[wasm_bindgen] pub fn build_info() -> String { serde_json::json!({ "core_commit": emu_galaga::CORE_COMMIT, "reference_commit": emu_galaga::REFERENCE_COMMIT, "oracle_mame_version": emu_galaga::ORACLE_MAME_VERSION, "screen_width": SCREEN_WIDTH, "screen_height": SCREEN_HEIGHT, }) .to_string() } /// Collects the members of a ROM set (from the page's unzip) so the Rust /// side can verify every one before a byte reaches the bus. #[wasm_bindgen] pub struct RomLoader { files: Vec<(String, Vec)>, } #[wasm_bindgen] impl RomLoader { #[wasm_bindgen(constructor)] pub fn new() -> RomLoader { RomLoader { files: Vec::new() } } /// Add one member by name; a path or different case is fine. pub fn add(&mut self, name: &str, bytes: &[u8]) { let base = name.replace('\\', "/"); let base = base.rsplit('/').next().unwrap_or("").to_ascii_lowercase(); self.files.push((base, bytes.to_vec())); } /// The sixteen member names the set must contain, as a JSON array. pub fn required() -> String { serde_json::to_string( &roms::ROM_SPECS .iter() .map(|s| s.filename) .collect::>(), ) .unwrap() } fn take(&mut self) -> Result { let files = std::mem::take(&mut self.files); RomSet::from_members(|name| { let wanted = name.to_ascii_lowercase(); let spec = roms::ROM_SPECS.iter().find(|s| s.filename == name).unwrap(); let mut candidates = files.iter().filter(|(n, _)| *n == wanted); let first = candidates.next()?; match candidates.next() { None => Some(first.1.clone()), Some(second) => [first, second] .into_iter() .chain(candidates) .find(|(_, b)| b.len() == spec.size) .map(|(_, b)| b.clone()), } }) } } impl Default for RomLoader { fn default() -> Self { Self::new() } } /// The board: run a frame, take its picture and its sound. #[wasm_bindgen] pub struct Galaga { machine: Machine, video: Video, sound: Sound, rgba: Vec, samples: Vec, pcm: Vec, /// Rewind: a compressed snapshot every [`REWIND_EVERY`] frames, newest last. rewind: VecDeque>, frames_since_snapshot: u32, } /// Rewind keeps a snapshot every this many frames, so holding it goes back this /// many times faster than the game runs. const REWIND_EVERY: u32 = 4; /// About a minute at 60 frames a second. const REWIND_KEEP: usize = 900; #[wasm_bindgen] impl Galaga { /// Verify the set and build the board. #[wasm_bindgen(constructor)] pub fn new(loader: &mut RomLoader) -> Result { let roms = loader.take().map_err(|m| JsError::new(&m))?; Ok(Galaga { machine: Machine::new(&roms), video: Video::new(&roms), sound: Sound::new(&roms), rgba: vec![0; SCREEN_WIDTH * SCREEN_HEIGHT * 4], samples: Vec::with_capacity(SAMPLES_PER_FRAME), pcm: vec![0; SAMPLES_PER_FRAME / 2], rewind: VecDeque::new(), frames_since_snapshot: 0, }) } pub fn set_control(&mut self, name: &str, pressed: bool) -> Result<(), JsError> { self.machine .set_control(name, pressed) .map_err(|m| JsError::new(&m)) } /// The DIP switch bytes, MAME's `DSWA` and `DSWB`. pub fn set_dips(&mut self, dsw_a: u8, dsw_b: u8) { self.machine.set_dips(dsw_a, dsw_b); } /// One frame: the board, its picture, its sound. pub fn run_frame(&mut self) { self.machine.run_frame(); self.video.render( &self.machine.shared.borrow(), self.machine.videolatch_at_vblank_end, ); let (wsg_writes, n54_writes) = { let mut s = self.machine.shared.borrow_mut(); ( std::mem::take(&mut s.wsg_writes), std::mem::take(&mut s.n54_writes), ) }; self.samples.clear(); self.sound.render_frame( self.machine.frame - 1, &wsg_writes, &n54_writes, &mut self.samples, ); for (i, pair) in self.samples.chunks(2).enumerate() { let v = pair.iter().sum::() / pair.len() as f32; self.pcm[i] = (v * 32767.0).round().clamp(-32768.0, 32767.0) as i16; } self.frames_since_snapshot += 1; if self.frames_since_snapshot >= REWIND_EVERY { self.frames_since_snapshot = 0; self.keep_snapshot(); } } /// One step back in place of a frame, while rewind is held: the newest /// snapshot kept is loaded, its picture drawn, and forgotten, so each call /// goes [`REWIND_EVERY`] frames further back; the oldest stays, and the game /// runs on from wherever it stops. Silent. False when nothing is kept. pub fn rewind_step(&mut self) -> bool { let packed = match self.rewind.len() { 0 => return false, 1 => self.rewind[0].clone(), _ => self.rewind.pop_back().expect("not empty"), }; let mut json = Vec::new(); if flate2::read::DeflateDecoder::new(packed.as_slice()) .read_to_end(&mut json) .is_err() { return false; } let Ok(snap) = serde_json::from_slice::(&json) else { return false; }; if self .machine .restore(&snap, &mut self.video, &mut self.sound) .is_err() { self.rewind.clear(); return false; } self.video.render( &self.machine.shared.borrow(), self.machine.videolatch_at_vblank_end, ); self.pcm.fill(0); self.frames_since_snapshot = 0; true } /// Seconds of the past the rewind window holds. pub fn rewind_seconds(&self) -> f64 { self.rewind.len() as f64 * REWIND_EVERY as f64 / 60.606 } /// The rewind window's memory, in bytes. pub fn rewind_memory(&self) -> usize { self.rewind.iter().map(Vec::len).sum() } /// The last frame as 224x288 RGBA. pub fn frame_rgba(&mut self) -> Vec { self.video.screen_rgba(&mut self.rgba); self.rgba.clone() } /// The last frame's 792 PCM16 samples at 48 kHz, mono. pub fn frame_pcm(&self) -> Vec { self.pcm.clone() } pub fn frame(&self) -> f64 { self.machine.frame as f64 } /// Credits the 51xx model holds, for the page's coin button. pub fn credits(&self) -> u32 { self.machine.shared.borrow().n51.credits() } /// The whole board at this frame boundary, as JSON. pub fn save_state(&self) -> String { serde_json::to_string(&self.machine.snapshot(&self.video, &self.sound)).unwrap() } pub fn load_state(&mut self, json: &str) -> Result<(), JsError> { let snap: Snapshot = serde_json::from_str(json).map_err(|e| JsError::new(&e.to_string()))?; self.machine .restore(&snap, &mut self.video, &mut self.sound) .map_err(|m| JsError::new(&m)) } } impl Galaga { fn keep_snapshot(&mut self) { let json = serde_json::to_vec(&self.machine.snapshot(&self.video, &self.sound)) .expect("a snapshot serializes"); let mut encoder = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::fast()); encoder.write_all(&json).expect("compressing to memory"); self.rewind .push_back(encoder.finish().expect("compressing to memory")); while self.rewind.len() > REWIND_KEEP { self.rewind.pop_front(); } } }