//! The wasm-bindgen surface: a cartridge's bytes in, frames of pixels and sound out, //! the player's input in, battery RAM and save states out and back. Numbers, //! strings and typed arrays only, so the page needs no glue beyond wasm-bindgen's. //! //! The board is famicom-rust-fast, unchanged. Input goes through its `host` //! module, the input half of famicom-python's window (the same one the libretro //! core uses): the page hands over the gamepads, the keys held (by the window's //! pygame names, "K_z"), and the mouse in picture pixels, and `host::apply` //! drives the pads and whatever is plugged in, from the Zapper to the keyboards. //! //! Two things the board reads from files on a desktop come from the page here: //! the palette (pally's, MIT-0, built in) and the Disk System's BIOS (Nintendo's, //! never shipped: the visitor's own file, kept on their device). nes20db, which //! corrects dumps whose headers are wrong, carries no licence and is not built //! in, so the header decides. use std::collections::{HashSet, VecDeque}; use std::io::{Cursor, Read}; use wasm_bindgen::prelude::*; use famicom_rust::cartridge::{self, fds::Fds, fds_disk, RomImage}; use famicom_rust::fds_auto::AutoDisk; use famicom_rust::host::{self, Gamepad, HostInput}; use famicom_rust::peripherals::Plugged; use famicom_rust::{Machine, System}; /// pally's palettes (github.com/Gumball2415/pally, MIT-0), as famicom-python's /// window uses them: the 2C02G for NTSC, the 2C07 for PAL and Dendy. const PALETTE_NTSC: &[u8] = include_bytes!("palettes/2C02G_U_wiki.pal"); const PALETTE_PAL: &[u8] = include_bytes!("palettes/2C07_wiki.pal"); /// The peripherals a visitor can choose (the window's `--device` names, the /// libretro core's list), with their NES 2.0 expansion numbers. pub const DEVICES: [(&str, u8); 15] = [ ("pads", 0x01), ("four-score", 0x02), ("famicom-four-players", 0x03), ("zapper", 0x08), ("two-zappers", 0x09), ("power-pad", 0x0C), ("family-trainer", 0x0E), ("vaus", 0x0F), ("hyper-shot", 0x12), ("keyboard", 0x23), ("subor-keyboard", 0x26), ("snes-mouse", 0x29), ("snes-pads", 0x2B), ("turbo-file", 0x21), ("rob", 0x1F), ]; // The page's gamepad bits (one word a player). pub const UP: u32 = 1 << 0; pub const DOWN: u32 = 1 << 1; pub const LEFT: u32 = 1 << 2; pub const RIGHT: u32 = 1 << 3; pub const SOUTH: u32 = 1 << 4; pub const EAST: u32 = 1 << 5; pub const NORTH: u32 = 1 << 6; pub const BACK: u32 = 1 << 7; pub const START: u32 = 1 << 8; pub const LEFT_SHOULDER: u32 = 1 << 9; pub const RIGHT_SHOULDER: u32 = 1 << 10; /// 512 colours from a 64- or 512-entry .pal (the board's `video::load_palette`, /// in memory). fn palette(data: &[u8], swapped_emphasis: bool) -> Vec<[u8; 3]> { let mut colours: Vec<[u8; 3]> = data.chunks(3).map(|c| [c[0], c[1], c[2]]).collect(); if colours.len() == 64 { colours = colours.repeat(8); } if swapped_emphasis { let swap = |i: usize| (i & !0xC0) | ((i & 0x40) << 1) | ((i & 0x80) >> 1); colours = (0..512).map(|i| colours[swap(i)]).collect(); } colours } fn is_rom(name: &str) -> bool { let lower = name.to_lowercase(); cartridge::ROM_SUFFIXES.iter().any(|s| lower.ends_with(s)) } fn stem(name: &str) -> String { let last = name.rsplit(['/', '\\']).next().unwrap_or(name); match last.rfind('.') { Some(dot) if dot > 0 => last[..dot].to_string(), _ => last.to_string(), } } /// The ROM bytes and a name: the file itself, or the one ROM inside a .zip or .7z. pub fn unpack(bytes: Vec, name: &str) -> Result<(Vec, String), String> { if bytes.starts_with(b"PK\x03\x04") { let mut archive = zip::ZipArchive::new(Cursor::new(&bytes)).map_err(|e| format!("{name}: {e}"))?; let members: Vec = archive .file_names() .filter(|n| is_rom(n)) .map(str::to_owned) .collect(); if members.len() != 1 { return Err(format!("{name}: expected one ROM, found {members:?}")); } let mut entry = archive.by_name(&members[0]).map_err(|e| e.to_string())?; let mut data = Vec::new(); entry.read_to_end(&mut data).map_err(|e| e.to_string())?; return Ok((data, stem(&members[0]))); } if bytes.starts_with(&[b'7', b'z', 0xBC, 0xAF, 0x27, 0x1C]) { use sevenz_rust2::{ArchiveReader, Password}; let mut reader = ArchiveReader::new(Cursor::new(&bytes), Password::empty()) .map_err(|e| format!("{name}: could not read the 7z archive: {e}"))?; let members: Vec = reader .archive() .files .iter() .filter(|f| f.has_stream() && !f.is_directory() && is_rom(f.name())) .map(|f| f.name().to_string()) .collect(); if members.len() != 1 { return Err(format!("{name}: expected one ROM, found {members:?}")); } let data = reader .read_file(&members[0]) .map_err(|e| format!("{name}: could not unpack {}: {e}", members[0]))?; return Ok((data, stem(&members[0]))); } Ok((bytes, stem(name))) } /// Whether `data` is a Disk System image (.fds or .qd). pub fn is_disk(data: &[u8]) -> bool { fds_disk::is_fds(data) || fds_disk::is_qd(data) } /// The console for a name the page offers ("" for the cartridge's own choice). fn machine_for(data: &[u8], key: &str, name: &str) -> Result { if !key.is_empty() { return Machine::by_key(key).ok_or_else(|| format!("unknown console {key}")); } if is_disk(data) { return Ok(Machine::famicom()); } let machine = System::machine_for(data)?; // An iNES 1 header cannot say PAL; No-Intro's name can. if machine.timing.lines == 262 { let upper = name.to_uppercase(); if upper.contains("(EUROPE") || upper.contains("(AUSTRALIA") { return Ok(Machine::pal_nes()); } if upper.contains("(USA") || upper.contains("(CANADA") { return Ok(Machine::nes_001()); } } Ok(machine) } /// A disk image on the RAM adapter, with the visitor's BIOS (the board's /// `cartridge::load` for a disk, with the BIOS in memory, not from a path). fn disk_system(data: &[u8], bios: &[u8], machine: Machine) -> Result { if bios.is_empty() { return Err("A Disk System game needs the Disk System's BIOS (disksys.rom, 8 KiB): choose it in Settings first.".into()); } if bios.len() != 0x2000 { return Err(format!( "The Disk System BIOS is 8 KiB; that file is {} bytes.", bios.len() )); } let image = RomImage { header: Vec::new(), trainer: Vec::new(), prg: bios.to_vec(), chr: Vec::new(), misc: data.to_vec(), board: cartridge::fds_board(), nes2: false, }; let fds = Fds::new(image.clone(), machine.timing.cpu_divider); let mut system = System::new(Box::new(fds), machine); system.image = Some(image); system.source = "FDS image"; Ok(system) } /// One console with one cartridge. #[wasm_bindgen] pub struct Console { system: System, plugged: Plugged, device: String, colours: Vec<[u8; 3]>, title: String, machine: String, frame_rate: f64, input: HostInput, rgba: Vec, sound: Vec, messages: Vec, /// Rewind: a compressed snapshot every [`REWIND_EVERY`] frames, newest last. rewind: VecDeque>, rewind_bytes: usize, 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 of snapshots at 60 frames a second... const REWIND_KEEP: usize = 900; /// ...unless they take more memory than this (a snapshot holds the picture too). const REWIND_BUDGET: usize = 48 << 20; #[wasm_bindgen] impl Console { /// Power on with a cartridge: `bytes` as the file holds them (a .zip or .7z is /// fine), `name` the file's name, `machine` one of `Machine::by_key`'s keys or /// "" for the cartridge's choice, `device` one of [`DEVICES`]' names or "" for /// the cartridge's own, `bios` the Disk System BIOS (empty if none). #[wasm_bindgen(constructor)] pub fn new( bytes: Vec, name: &str, sample_rate: u32, machine: &str, device: &str, bios: Vec, ) -> Result { let (data, rom_name) = unpack(bytes, name).map_err(|e| JsError::new(&e))?; let machine_row = machine_for(&data, machine, &rom_name).map_err(|e| JsError::new(&e))?; let mut system = if is_disk(&data) { disk_system(&data, &bios, machine_row.clone()) } else { System::from_rom(&data, machine_row.clone(), None) } .map_err(|e| JsError::new(&e))?; system.board().set_sample_rate(sample_rate as i64); if let Some(fds) = system.board().ppu.cart.fds() { let auto = AutoDisk::new(fds); system.board().auto_disk = Some(Box::new(auto)); } let timing = machine_row.timing.clone(); let colours = if timing.lines == 262 { palette(PALETTE_NTSC, timing.swapped_emphasis) } else { palette(PALETTE_PAL, timing.swapped_emphasis) }; let number = if device.is_empty() { system.image.as_ref().map_or(0, |i| i.board.expansion) } else { DEVICES .iter() .find(|(n, _)| *n == device) .map(|(_, number)| *number) .ok_or_else(|| JsError::new(&format!("no device {device}")))? }; let famicom = system.cpu.bus.machine.famicom_expansion_port; let plugged = host::plug_for_host(system.board(), number, famicom, Some(colours.clone())); let device_name = DEVICES .iter() .find(|(_, n)| *n == number) .map_or("pads", |(n, _)| n) .to_string(); let frame_rate = timing.master_hz / (timing.lines as f64 * 341.0 * timing.dot_divider as f64); let machine_key = machine_key(&system.cpu.bus.machine).to_string(); Ok(Console { system, plugged, device: device_name, colours, title: rom_name, machine: machine_key, frame_rate, input: HostInput::default(), rgba: vec![255; 256 * 240 * 4], sound: Vec::new(), messages: Vec::new(), rewind: VecDeque::new(), rewind_bytes: 0, frames_since_snapshot: 0, }) } pub fn title(&self) -> String { self.title.clone() } /// The console's key ("famicom", "nes", "pal", "dendy", ...). pub fn machine(&self) -> String { self.machine.clone() } /// The machine's display name ("Famicom (HVC-001)"). pub fn machine_name(&self) -> String { self.system.cpu.bus.machine.name.to_string() } /// The peripheral plugged in, by the page's name ("pads" for none). pub fn device(&self) -> String { self.device.clone() } /// How the cartridge was identified: mapper, sizes, and from what. pub fn cartridge(&self) -> String { match &self.system.image { Some(_) if self.system.source == "FDS image" => { format!("Disk System, {} sides", self.disk_sides()) } Some(image) => format!( "mapper {}.{}, PRG {} KiB, CHR {} KiB ({})", image.board.mapper, image.board.submapper, image.prg.len() / 1024, image.chr.len() / 1024, self.system.source ), None => String::new(), } } pub fn rate(&self) -> f64 { self.frame_rate } // -- input ------------------------------------------------------------------------- /// Player `index`'s controller: the bits above and its left stick (-32768..32767). pub fn set_pad(&mut self, index: usize, mask: u32, stick_x: i32, stick_y: i32) { if index >= 4 { return; } while self.input.gamepads.len() <= index { self.input.gamepads.push(Gamepad::default()); } self.input.gamepads[index] = Gamepad { up: mask & UP != 0, down: mask & DOWN != 0, left: mask & LEFT != 0, right: mask & RIGHT != 0, south: mask & SOUTH != 0, east: mask & EAST != 0, north: mask & NORTH != 0, back: mask & BACK != 0, start: mask & START != 0, left_shoulder: mask & LEFT_SHOULDER != 0, right_shoulder: mask & RIGHT_SHOULDER != 0, stick_x, stick_y, }; } /// Players with a controller (the rest have none: no stale buttons). pub fn set_pad_count(&mut self, count: usize) { self.input.gamepads.truncate(count.min(4)); } /// The keys held, by the window's pygame names, separated by spaces. pub fn set_keys(&mut self, names: &str) { self.input.keys = names .split_whitespace() .map(str::to_owned) .collect::>(); } /// The mouse in picture pixels (0-255, 0-239), whether it is over the picture, /// its motion since the last frame, and its two buttons. #[allow(clippy::too_many_arguments)] pub fn set_mouse( &mut self, x: i32, y: i32, over: bool, dx: i32, dy: i32, left: bool, right: bool, ) { let input = &mut self.input; input.mouse_x = x as i64; input.mouse_y = y as i64; input.mouse_focused = over; input.mouse_dx = dx as i64; input.mouse_dy = dy as i64; input.mouse_left = left; input.mouse_right = right; } /// Whether the plugged device takes the whole keyboard (a keyboard or the /// Jissen Mahjong controller): the page then sends every key, not just the pad's. pub fn wants_keyboard(&self) -> bool { matches!(self.device.as_str(), "keyboard" | "subor-keyboard") } // -- running ----------------------------------------------------------------------- /// Run one frame with the input set; `draw` false skips the picture (catching up). pub fn run_frame(&mut self, draw: bool) { self.real_frame(); if draw { self.paint(); } } /// Run one frame, and show the picture of `ahead` frames later: the console's /// own frame runs as in [`Console::run_frame`] and gives the sound; then it is /// snapshotted, run `ahead` frames further with the same input held, painted, /// and put back. A game that answers a button two frames later shows the answer /// in the frame the button went down, for `ahead` = 2. Costs `ahead` frames of /// emulation and a snapshot each way per frame. False if the snapshot could not /// be taken back (the picture is then the real frame's and the caller should /// stop asking). pub fn run_frame_ahead(&mut self, ahead: u32) -> bool { self.real_frame(); if ahead == 0 { self.paint(); return true; } let snapshot = famicom_rust::state::save_snapshot(&self.system); // AutoDisk lives beside the board, not in its state: it sits the frames ahead out. let auto_disk = self.system.board().auto_disk.take(); self.system.run_frames(ahead as u64); self.paint(); self.system.take_samples(); self.system.board().auto_disk = auto_disk; match famicom_rust::state::load_snapshot(&mut self.system, &snapshot) { Ok(()) => true, Err(error) => { self.messages.push(format!("Run-ahead off: {error}")); false } } } /// The console's own next frame: input, the frame, its messages and its sound. fn real_frame(&mut self) { host::apply( self.system.board(), &mut self.plugged, &self.input, host::VAUS_LOW, ); self.system.run_frames(1); if let Some(command) = host::after_frame(self.system.board(), &mut self.plugged) { self.messages.push(format!("R.O.B.: {command}")); } if let Some(auto) = self.system.board().auto_disk.as_mut() { self.messages.append(&mut auto.messages); } self.frames_since_snapshot += 1; if self.frames_since_snapshot >= REWIND_EVERY { self.frames_since_snapshot = 0; self.keep_snapshot(); } let samples = self.system.take_samples(); self.sound.clear(); for s in samples { let v = s as f32; self.sound.extend_from_slice(&[v, v]); } } /// One snapshot onto the rewind window, the oldest dropped past its limits. fn keep_snapshot(&mut self) { use std::io::Write; let raw = famicom_rust::state::save_snapshot(&self.system); let mut encoder = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::fast()); encoder.write_all(&raw).expect("compressing to memory"); let packed = encoder.finish().expect("compressing to memory"); self.rewind_bytes += packed.len(); self.rewind.push_back(packed); while self.rewind.len() > REWIND_KEEP || (self.rewind_bytes > REWIND_BUDGET && self.rewind.len() > 1) { if let Some(old) = self.rewind.pop_front() { self.rewind_bytes -= old.len(); } } } /// The PPU's picture into the RGBA buffer. fn paint(&mut self) { let picture = &self.system.cpu.bus.ppu.picture; for (pixel, &value) in self.rgba.chunks_exact_mut(4).zip(picture.iter()) { let [r, g, b] = self.colours[value as usize & 0x1FF]; pixel[0] = r; pixel[1] = g; pixel[2] = b; } } /// The last frame's RGBA bytes, 256 × 240 × 4, in the module's memory: a view /// that a later call may move, so copy it before calling again. pub fn frame_ptr(&self) -> *const u8 { self.rgba.as_ptr() } pub fn frame_len(&self) -> usize { self.rgba.len() } /// The last frame's sound, interleaved stereo floats at the page's rate. pub fn sound(&self) -> Vec { self.sound.clone() } /// The next message to show (R.O.B.'s moves, a disk side changed), or "". pub fn take_message(&mut self) -> String { if self.messages.is_empty() { String::new() } else { self.messages.remove(0) } } /// The reset button. pub fn reset(&mut self) { self.system.reset(); } // -- rewind ------------------------------------------------------------------------ /// One step back in place of a frame, while rewind is held: the newest snapshot /// kept is loaded, painted and forgotten, so each call goes [`REWIND_EVERY`] /// frames further back; the oldest one stays, and the game runs on from wherever /// it stops. No sound. False when nothing is kept (or a snapshot would not load). pub fn rewind_step(&mut self) -> bool { let packed = if self.rewind.len() > 1 { let packed = self.rewind.pop_back().expect("not empty"); self.rewind_bytes -= packed.len(); packed } else if let Some(only) = self.rewind.back() { only.clone() } else { return false; }; let mut raw = Vec::new(); if flate2::read::DeflateDecoder::new(packed.as_slice()) .read_to_end(&mut raw) .is_err() { return false; } // AutoDisk lives beside the board, not in its state, as in run-ahead. let auto_disk = self.system.board().auto_disk.take(); let loaded = famicom_rust::state::load_snapshot(&mut self.system, &raw); self.system.board().auto_disk = auto_disk; if let Err(error) = loaded { self.messages.push(format!("Rewind: {error}")); self.rewind.clear(); self.rewind_bytes = 0; return false; } self.frames_since_snapshot = 0; self.sound.clear(); self.paint(); true } /// Seconds of the past the rewind window holds. pub fn rewind_seconds(&self) -> f64 { self.rewind.len() as f64 * REWIND_EVERY as f64 / self.frame_rate } /// The rewind window's memory, in bytes. pub fn rewind_memory(&self) -> usize { self.rewind_bytes } // -- battery RAM and save states --------------------------------------------------- pub fn has_battery(&mut self) -> bool { self.system.board().cart().battery_ram().is_some() } /// The battery-backed RAM, to keep between visits (empty if none). pub fn battery(&mut self) -> Vec { self.system.board().cart().battery_ram().unwrap_or_default() } /// Battery RAM kept from an earlier visit. pub fn load_battery(&mut self, data: &[u8]) { let size = self .system .board() .cart() .battery_ram() .map_or(0, |r| r.len()); if size != 0 && data.len() == size { self.system.board().cart().restore_battery(data); } } /// The whole machine, as famicom-rust's save state. pub fn save_state(&self) -> Vec { famicom_rust::state::save_state(&self.system) } pub fn load_state(&mut self, data: &[u8]) -> Result<(), JsError> { famicom_rust::state::load_state(&mut self.system, data).map_err(|e| JsError::new(&e)) } // -- the Disk System --------------------------------------------------------------- /// Sides of the disk(s) in the image (0 for a cartridge). pub fn disk_sides(&self) -> usize { self.system .cpu .bus .ppu .cart .fds() .map_or(0, |f| f.sides.len()) } /// The side in the drive, or -1 when it is empty. pub fn disk_side(&self) -> i32 { self.system .cpu .bus .ppu .cart .fds() .and_then(|f| f.side) .map_or(-1, |s| s as i32) } /// Put side `side` in the drive (-1 takes the disk out). pub fn insert_disk(&mut self, side: i32) { if let Some(fds) = self.system.board().ppu.cart.fds_mut() { let side = (side >= 0 && (side as usize) < fds.sides.len()).then_some(side as usize); fds.insert(side); } } /// Whether the program has written to the disk since power-on (a save). pub fn disk_written(&self) -> bool { self.system .cpu .bus .ppu .cart .fds() .is_some_and(|f| f.written.iter().any(|&w| w)) } /// The disk as a headerless `.fds` file, saves included (empty for a cartridge), /// to keep and load in place of the original next time. pub fn disk_image(&self) -> Vec { self.system .cpu .bus .ppu .cart .fds() .map(|f| f.sides.iter().flat_map(|s| fds_disk::fds_side(s)).collect()) .unwrap_or_default() } /// A side's name, "disk 1 side A". pub fn side_name(side: i32) -> String { Fds::side_name((side >= 0).then_some(side as usize)) } /// AutoDisk (the sides change as the program asks): on by default. pub fn set_auto_disk(&mut self, on: bool) { let board = self.system.board(); if !on { board.auto_disk = None; } else if board.auto_disk.is_none() { if let Some(fds) = board.ppu.cart.fds() { board.auto_disk = Some(Box::new(AutoDisk::new(fds))); } } } } /// The page's key for a machine row. fn machine_key(machine: &Machine) -> &'static str { for key in ["famicom", "nes", "av-famicom", "nes-101", "pal", "dendy"] { if Machine::by_key(key).is_some_and(|m| m.name == machine.name) { return key; } } "famicom" } /// The board's frames a second, for the bench. pub fn frame_rate_of(machine: &Machine) -> f64 { let t = &machine.timing; t.master_hz / (t.lines as f64 * 341.0 * t.dot_divider as f64) }