//! The wasm-bindgen surface. Strings in, a JSON string out, so the JS side //! needs no glue beyond `JSON.parse`. use wasm_bindgen::prelude::*; /// Run one manifest against its reference trace; returns the JSON of /// [`crate::check::CheckResult`], or throws with the loader's message. #[wasm_bindgen] pub fn check_manifest(manifest_json: &str, reference_jsonl: &str) -> Result { crate::check::check_manifest(manifest_json, reference_jsonl) .map(|result| result.to_json()) .map_err(|message| JsError::new(&message)) } /// What this build is: the core tag and commit, the reference commit, the /// trace schema version. #[wasm_bindgen] pub fn build_info() -> String { serde_json::json!({ "core_tag": crate::CORE_TAG, "core_commit": crate::CORE_COMMIT, "reference_commit": crate::REFERENCE_COMMIT, "trace_schema_version": crate::TRACE_SCHEMA_VERSION, }) .to_string() } /// A resumable untraced run (`z80-bench`'s loop) for the worker: construct /// with the manifest JSON and the one file it may reference, then call /// `run(budget)` until the returned JSON's `stopped` is not null. #[wasm_bindgen] pub struct Runner { inner: crate::runner::Runner, } #[wasm_bindgen] impl Runner { #[wasm_bindgen(constructor)] pub fn new(manifest_json: &str, file_name: &str, file_bytes: &[u8]) -> Result { let inner = crate::runner::Runner::new(manifest_json, |name| { (name == file_name).then(|| file_bytes.to_vec()) }) .map_err(|message| JsError::new(&message))?; Ok(Runner { inner }) } pub fn name(&self) -> String { self.inner.name().to_string() } /// Run up to `budget` instructions; returns [`crate::runner::Progress`] as JSON. pub fn run(&mut self, budget: f64) -> String { self.inner.run(budget as u64).to_json() } } // --- Galaxian ---------------------------------------------------------------- use crate::galaxian::roms::{self, RomSet}; use crate::galaxian::trace::{parse_inputs, run_frames, run_trace}; /// Collects the files 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 file by its basename (matched case-insensitively). pub fn add(&mut self, name: &str, bytes: &[u8]) { self.files.push((name.to_ascii_lowercase(), bytes.to_vec())); } /// The basenames the set needs, as a JSON array. pub fn required() -> String { serde_json::to_string( &roms::required_files() .map(|s| s.filename) .collect::>(), ) .unwrap() } fn take(&mut self) -> Result { let files = std::mem::take(&mut self.files); roms::load(|name| { files .iter() .find(|(n, _)| n == &name.to_ascii_lowercase()) .map(|(_, b)| b.clone()) }) } } impl Default for RomLoader { fn default() -> Self { Self::new() } } /// 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 (a snapshot is about 2.5 KB). const REWIND_KEEP: usize = 900; /// A save state's first bytes, and its format's version: 1 is /// `Snapshot::to_bytes` of 2026-11-23 (src/galaxian/bytes.rs). A change to what /// a snapshot holds or its order must raise the version, so an older state is /// refused rather than misread. const STATE_MAGIC: &[u8; 8] = b"GALAXIAN"; const STATE_VERSION: u32 = 1; /// The board, verified ROMs in, frames out. #[wasm_bindgen] pub struct Galaxian { inner: crate::galaxian::Galaxian, rgba: Vec, /// Rewind: a snapshot every [`REWIND_EVERY`] frames, newest last. rewind: std::collections::VecDeque, frames_since_snapshot: u32, } #[wasm_bindgen] impl Galaxian { /// Verify the set and build the board. `enable_vblank` false gives the /// headless board the oracle's instruction-count runs use. #[wasm_bindgen(constructor)] pub fn new( loader: &mut RomLoader, enable_vblank: bool, trace_memory_writes: bool, ) -> Result { let roms = loader.take().map_err(|m| JsError::new(&m))?; let mut inner = crate::galaxian::Galaxian::new(&roms, enable_vblank).map_err(|m| JsError::new(&m))?; inner.machine.board_mut().trace_memory_writes = trace_memory_writes; Ok(Galaxian { inner, rgba: vec![0; 224 * 256 * 4], rewind: std::collections::VecDeque::new(), frames_since_snapshot: 0, }) } pub fn set_input(&mut self, control: &str, pressed: bool) -> Result<(), JsError> { self.inner .machine .board_mut() .set_input(control, pressed) .map_err(|m| JsError::new(&m)) } /// Run one frame (to the next vblank), synthesize its sound, compose it. pub fn run_frame(&mut self) -> Result<(), JsError> { self.inner.run_frame().map_err(|m| JsError::new(&m))?; self.frames_since_snapshot += 1; if self.frames_since_snapshot >= REWIND_EVERY { self.frames_since_snapshot = 0; self.rewind.push_back(self.inner.snapshot()); if self.rewind.len() > REWIND_KEEP { self.rewind.pop_front(); } } Ok(()) } /// One step back in place of a frame, while rewind is held: the newest /// snapshot kept is restored, its frame composed, 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 snapshot = match self.rewind.len() { 0 => return false, 1 => self.rewind[0].clone(), _ => self.rewind.pop_back().expect("not empty"), }; self.inner.restore(&snapshot); self.frames_since_snapshot = 0; true } /// The game as a save state: [`STATE_MAGIC`], the format's version /// ([`STATE_VERSION`], u32 little-endian), then the snapshot's bytes (the /// machine and the sound, ~2.5 KB). The picture is composed again on load. pub fn save_state(&self) -> Vec { let mut out = STATE_MAGIC.to_vec(); out.extend_from_slice(&STATE_VERSION.to_le_bytes()); out.extend(self.inner.snapshot().to_bytes()); out } /// Back to a [`Galaxian::save_state`]. Refused, with the game untouched, if /// the bytes are not a Galaxian state, are of another version, or are not /// exactly one state's worth. The controls held now stay held. pub fn load_state(&mut self, data: &[u8]) -> Result<(), JsError> { let head = STATE_MAGIC.len() + 4; if data.len() < head || &data[..STATE_MAGIC.len()] != STATE_MAGIC { return Err(JsError::new("not a Galaxian save state")); } let version = u32::from_le_bytes(data[STATE_MAGIC.len()..head].try_into().unwrap()); if version != STATE_VERSION { return Err(JsError::new(&format!( "a save state of version {version}, not {STATE_VERSION}" ))); } let snapshot = crate::galaxian::Snapshot::from_bytes(&data[head..]) .map_err(|m| JsError::new(&m))?; self.inner.restore(&snapshot); self.frames_since_snapshot = 0; Ok(()) } /// 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 last frame's 792 PCM16 samples at 48 kHz, mono. pub fn frame_pcm(&self) -> Vec { self.inner.pcm.to_vec() } /// The last composed frame as portrait 224x256 RGBA. pub fn frame_rgba(&mut self) -> Vec { self.inner.frame.portrait_rgba(&mut self.rgba); self.rgba.clone() } pub fn vblank_count(&self) -> f64 { self.inner.machine.vblank_count as f64 } pub fn instruction_count(&self) -> f64 { self.inner.machine.board().instruction_count as f64 } /// The oracle's instruction-count run: canonical JSON, galemu's bytes. pub fn run_trace(&mut self, instructions: f64, inputs_json: &str) -> Result { let specs: Vec = serde_json::from_str(inputs_json).map_err(|e| JsError::new(&e.to_string()))?; let inputs = parse_inputs(&specs).map_err(|m| JsError::new(&m))?; run_trace(&mut self.inner.machine, instructions as u64, &inputs) .map_err(|m| JsError::new(&m)) } /// The oracle's frame-count run. pub fn run_frames_trace(&mut self, frames: f64, inputs_json: &str) -> Result { let specs: Vec = serde_json::from_str(inputs_json).map_err(|e| JsError::new(&e.to_string()))?; let inputs = parse_inputs(&specs).map_err(|m| JsError::new(&m))?; run_frames(&mut self.inner.machine, frames as u64, &inputs).map_err(|m| JsError::new(&m)) } }