//! The wasm-bindgen surface: a HuCard's bytes or a disc's cue sheet in, frames of //! pixels and sound out, the pads in, backup RAM and save states out and back. //! Numbers, strings, typed arrays and one JavaScript function (the disc's reader), //! so the page needs no glue beyond wasm-bindgen's. //! //! The boards are pcengine-rust (the PC Engine and TurboGrafx-16), supergrafx-rust //! (the SuperGrafx) and pcenginecd-rust (the CD-ROM² unit, the Super System Card's //! RAM, the Arcade Card), unchanged. All three give a `pcengine_rust::system::System`, //! so one `Console` wraps them all. //! //! **The disc is never in wasm memory.** The CD crate reads sectors synchronously //! through its `ImageReader`; here that is a JavaScript function `(file, offset, //! length) -> Uint8Array` the host supplies (in the page: `FileReaderSync` over a //! slice of the visitor's own file, inside the Web Worker the console runs in; under //! Node: `fs.readSync`). `Blocks` keeps the last few 64 KiB blocks it returned, so a //! sector costs a call only when the drive moves on, and `Console::read_ahead` fetches, //! between frames, where the drive is seeking to and the block after the one it is in, //! so the drive rarely waits for the file inside a frame at all. //! //! Nothing is built in that is not ours: no card, no System Card, no disc, no title //! database. Which machine a card wants is the board's own test (`is_supergrafx_card`) //! and the file's name ("(USA)" is a TurboGrafx-16 card); which discs want the Arcade //! Card is a dozen title words below. The page's settings override both. use std::cell::RefCell; use std::collections::VecDeque; use std::io::{Cursor, Read}; use std::rc::Rc; use wasm_bindgen::prelude::*; use pcengine_rust::board::{Board, BoardOptions}; use pcengine_rust::cards::{make_card, strip_copier_header, TennokoeCard}; use pcengine_rust::machine::{Machine, MASTER_HZ, PC_ENGINE, TURBOGRAFX_16}; use pcengine_rust::pads::{self, MultiTap, Pad2, Pad6}; use pcengine_rust::sockets::ControllerPort; use pcengine_rust::state; use pcengine_rust::system::System; use pcenginecd_rust::board::{self as cd, CdSwitches, PcEngineCd}; use pcenginecd_rust::cdda as cd_cdda; use pcenginecd_rust::disc::{parse_cue, CueSheet, CueSource, Disc}; use pcenginecd_rust::scsi as cd_scsi; use supergrafx_rust::{is_supergrafx_card, set_compat, SuperGrafx, SuperGrafxOptions}; /// The board's sound: 44,100 Hz stereo. pub const BOARD_RATE: u32 = 44_100; /// The lines of a picture (frame lines 14-255). pub const LINES: usize = 242; /// The part of a 1365-clock row the page shows: 1152 master clocks from clock 32, which is 288, /// 384 or 576 dots by the dot clock. A 256-dot picture (clocks 96-1120: dot 24 of the row at the /// 5 MHz clock, pcengine-rust's origin since its clean rewrite of 2026-11-19; it was dot 32, and /// this view started at clock 64) sits in the middle with 16 dots of border each side; the 336- /// and 352-dot pictures of the 7 MHz clock and the 512-dot ones of the 10 MHz clock fit whole. /// What is left out is the blanking a television does not show either. Measured on the new /// board: thirteen HuCards and SuperGrafx cards, every full 256-dot screen at dots 16-271. pub const VIEW_START: usize = 32; pub const VIEW_CLOCKS: usize = 1152; // The page's pad bits: the board's own (`pcengine_rust::pads`), and two turbo switches. pub const TURBO_I: u32 = 0x1000; pub const TURBO_II: u32 = 0x2000; /// Words in a disc's name that say it wants the Arcade Card (the titles sold as Arcade /// CD-ROM²: they do not start without it). Other discs only use it when it is there; the /// page's setting fits it for those. const ARCADE_TITLES: [&str; 13] = [ "ryuuko no ken", "art of fighting", "garou densetsu 2", "garou densetsu special", "fatal fury 2", "fatal fury special", "world heroes 2", "kabuki ittou ryoudan", "strider hiryuu", "strider hiryu", "mad stalker", "sapphire", "madou monogatari", ]; const BLOCK: u64 = 64 * 1024; const BLOCKS_KEPT: usize = 24; fn is_card_name(name: &str) -> bool { let lower = name.to_lowercase(); lower.ends_with(".pce") || lower.ends_with(".sgx") } fn base_name(name: &str) -> &str { name.rsplit(['/', '\\']).next().unwrap_or(name) } fn stem(name: &str) -> String { let last = base_name(name); match last.rfind('.') { Some(dot) if dot > 0 => last[..dot].to_string(), _ => last.to_string(), } } /// The card's bytes and its file name: the file itself, or the one card inside a .zip or .7z /// (the one `.pce` or `.sgx`, or the only file there is). pub fn unpack(bytes: Vec, name: &str) -> Result<(Vec, String), String> { let pick = |names: Vec| -> Result { let cards: Vec<&String> = names.iter().filter(|n| is_card_name(n)).collect(); match (cards.len(), names.len()) { (1, _) => Ok(cards[0].clone()), (0, 1) => Ok(names[0].clone()), (0, _) if names.iter().any(|n| n.to_lowercase().ends_with(".cue")) => Err(format!( "{name} holds a disc: unpack it and choose the .cue and its .bin files together" )), _ => Err(format!("{name}: expected one card (.pce), found {names:?}")), } }; if bytes.starts_with(b"PK\x03\x04") { let mut archive = zip::ZipArchive::new(Cursor::new(&bytes)).map_err(|e| format!("{name}: {e}"))?; let names: Vec = archive .file_names() .filter(|n| !n.ends_with('/')) .map(str::to_owned) .collect(); let member = pick(names)?; let mut entry = archive.by_name(&member).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, base_name(&member).to_string())); } 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 names: Vec = reader .archive() .files .iter() .filter(|f| f.has_stream() && !f.is_directory()) .map(|f| f.name().to_string()) .collect(); let member = pick(names)?; let data = reader .read_file(&member) .map_err(|e| format!("{name}: could not unpack {member}: {e}"))?; return Ok((data, base_name(&member).to_string())); } Ok((bytes, base_name(name).to_string())) } /// Whether a disc of this name is one sold for the Arcade Card. #[wasm_bindgen] pub fn wants_arcade_card(name: &str) -> bool { let lower = name.to_lowercase(); ARCADE_TITLES.iter().any(|title| lower.contains(title)) } /// The files a cue sheet names, in its order (the page matches them to the files chosen). #[wasm_bindgen] pub fn cue_files(text: &str) -> Result, JsError> { let mut names = Vec::new(); parse_cue(text, &mut |name| { names.push(name.to_string()); Ok(2352) }) .map_err(|e| JsError::new(&e))?; Ok(names) } /// A pad for the port by the page's name: "2", "6" (the 6-button pad), "tap2", "tap6" (five /// of them behind the multitap). With it, how many players it takes. fn make_pad(kind: &str) -> Result<(Box, usize), String> { let six = kind.ends_with('6'); let one = || -> Box { if six { Box::new(Pad6::new()) } else { Box::new(Pad2::new()) } }; if kind.starts_with("tap") { let pads = (0..MultiTap::PORTS).map(|_| Some(one())).collect(); Ok((Box::new(MultiTap::new(pads)?), MultiTap::PORTS)) } else { Ok((one(), 1)) } } fn pad_name(kind: &str) -> &'static str { match kind { "6" => "6-button pad", "tap2" => "multitap, five 2-button pads", "tap6" => "multitap, five 6-button pads", _ => "2-button pad", } } /// The last blocks of the disc's files the host's reader returned. struct Blocks { read: js_sys::Function, lengths: Vec, kept: VecDeque<(usize, u64, Vec)>, /// the block the drive last read from last: Option<(usize, u64)>, error: Rc>>, } impl Blocks { fn block(&mut self, file: usize, index: u64) -> &[u8] { if let Some(at) = self .kept .iter() .position(|(f, i, _)| *f == file && *i == index) { if at != 0 { let entry = self.kept.remove(at).unwrap(); self.kept.push_front(entry); } return &self.kept[0].2; } let from = index * BLOCK; let length = self.lengths.get(file).copied().unwrap_or(0); let want = length.saturating_sub(from).min(BLOCK) as usize; let mut data = vec![0u8; want]; if want > 0 { let answer = self.read.call3( &JsValue::NULL, &JsValue::from(file as u32), &JsValue::from(from as f64), &JsValue::from(want as u32), ); match answer { Ok(value) if value.is_instance_of::() => { let array: js_sys::Uint8Array = value.unchecked_into(); let got = (array.length() as usize).min(want); array.subarray(0, got as u32).copy_to(&mut data[..got]); } Ok(_) => *self.error.borrow_mut() = Some("the reader gave no bytes".to_string()), Err(error) => { let text = js_sys::Reflect::get(&error, &JsValue::from("message")) .ok() .and_then(|m| m.as_string()) .unwrap_or_else(|| "the file could not be read".to_string()); *self.error.borrow_mut() = Some(text); } } } self.kept.push_front((file, index, data)); self.kept.truncate(BLOCKS_KEPT); &self.kept[0].2 } /// Read the block after the one the drive is in, if it is not kept yet: called between /// frames, so that a drive reading on (a streamed video, a long load) finds its next /// sectors already here and the wait for the file falls in the frame's spare time. fn read_ahead(&mut self) -> bool { let Some((file, index)) = self.last else { return false; }; let next = index + 1; let length = self.lengths.get(file).copied().unwrap_or(0); if next * BLOCK >= length || self.kept.iter().any(|(f, i, _)| *f == file && *i == next) { return false; } self.block(file, next); true } /// Have the block that holds byte `offset` of `file` here; true if it had to be read. fn ensure(&mut self, file: usize, offset: u64) -> bool { let index = offset / BLOCK; if self.kept.iter().any(|(f, i, _)| *f == file && *i == index) { return false; } self.block(file, index); true } fn read_at(&mut self, file: usize, offset: u64, out: &mut [u8]) -> usize { let mut done = 0; while done < out.len() { let at = offset + done as u64; let within = (at % BLOCK) as usize; self.last = Some((file, at / BLOCK)); let block = self.block(file, at / BLOCK); if within >= block.len() { break; } let count = (block.len() - within).min(out.len() - done); out[done..done + count].copy_from_slice(&block[within..within + count]); done += count; } done } } /// What went into the machine, for the page to say. #[derive(Clone, Copy, PartialEq, Eq)] enum Kind { Card, SuperGrafx, Cd, } /// One console with one card or one disc. #[wasm_bindgen] pub struct Console { system: System, kind: Kind, title: String, machine: &'static str, described: String, tennokoe: bool, arcade: bool, ports: usize, held: [u32; 5], colours: Vec<[u8; 3]>, rgba: Vec, width: usize, sample_rate: u32, sound: Vec, resample_at: f64, resample_last: (f32, f32), frame_ms: f64, messages: Vec, disc_error: Rc>>, blocks: Option>>, sheet: Option, /// where CD audio last started from (the sector fetched ahead for it) audio_from: Option, /// Rewind: a snapshot every [`REWIND_EVERY`] frames. rewind: Rewind, frames_since_snapshot: u32, rewind_on: bool, } /// Rewind's window: the newest snapshot as it is, and each older one as the deflated XOR of /// it with the one after it (a reverse delta). Four frames apart, most of a snapshot has not /// changed (the System Card's RAM, the ADPCM RAM, the Arcade Card's 2 MiB), so a delta is /// mostly zeros: it deflates to a few KiB, and quickly. play-nes deflates each snapshot whole; /// here a CD game's snapshot deflates to about 230 KiB (a 48 MiB window then holds 14 s) and an /// Arcade Card game's in play to about 1.6 MiB (2 s), and deflating that costs a frame 2 to 12 /// ms (README, "Rewind"). *Provisional*. /// /// Snapshots change length from one to the next by a few bytes (the board's sound buffers and /// event lists), which moves everything after them, so the XOR is taken block by block /// ([`DELTA_BLOCK`] bytes of the older snapshot): each block against the newer snapshot at the /// same offset or at the same distance from its end, whichever leaves fewer bytes set. A delta /// is the older snapshot's length (four bytes), one byte a block for the alignment chosen, and /// the XORed bytes (beyond the newer snapshot's ends they are XORed with 0). Stepping back loads /// the newest, then rebuilds the one before it from its delta; dropping the oldest just forgets /// it (nothing depends on it). struct Rewind { /// newest last, the newest not among them older: VecDeque>, newest: Option>, bytes: usize, } const DELTA_BLOCK: usize = 4096; /// The part of `newer` that lines up with `older[range]` at `shift`, when all of it is inside /// `newer` (nearly every block is; the slow paths below take the others). fn lined_up<'a>(newer: &'a [u8], range: &std::ops::Range, shift: isize) -> Option<&'a [u8]> { let start = range.start as isize + shift; let end = range.end as isize + shift; (start >= 0 && end as usize <= newer.len()).then(|| &newer[start as usize..end as usize]) } /// `older[i] ^= newer[i + shift]` over `range`, with 0 outside `newer`. fn xor_shifted(older: &mut [u8], newer: &[u8], range: std::ops::Range, shift: isize) { if let Some(other) = lined_up(newer, &range, shift) { for (a, b) in older[range].iter_mut().zip(other) { *a ^= b; } return; } for i in range { let j = i as isize + shift; if j >= 0 && (j as usize) < newer.len() { older[i] ^= newer[j as usize]; } } } /// The bytes of `older[range]` that differ from `newer` at `shift`. fn differing(older: &[u8], newer: &[u8], range: std::ops::Range, shift: isize) -> usize { if let Some(other) = lined_up(newer, &range, shift) { let ours = &older[range]; if ours == other { return 0; } return ours.iter().zip(other).map(|(a, b)| (a != b) as usize).sum(); } range .filter(|&i| { let j = i as isize + shift; let other = if j >= 0 && (j as usize) < newer.len() { newer[j as usize] } else { 0 }; older[i] != other }) .count() } /// `older` turned into its delta against `newer`: the alignments, then `older` XORed in place. fn delta(older: &mut [u8], newer: &[u8]) -> Vec { let end_shift = newer.len() as isize - older.len() as isize; let mut alignments = Vec::with_capacity(older.len().div_ceil(DELTA_BLOCK)); for start in (0..older.len()).step_by(DELTA_BLOCK) { let range = start..(start + DELTA_BLOCK).min(older.len()); let at_start = differing(older, newer, range.clone(), 0); let by_end = end_shift != 0 && at_start != 0 && differing(older, newer, range.clone(), end_shift) < at_start; alignments.push(by_end as u8); if at_start == 0 && !by_end { older[range].fill(0); } else { xor_shifted(older, newer, range, if by_end { end_shift } else { 0 }); } } alignments } /// The older snapshot back from its delta (`alignments`, then the XORed bytes) and the newer. fn undo_delta(alignments: &[u8], mut older: Vec, newer: &[u8]) -> Vec { let end_shift = newer.len() as isize - older.len() as isize; for (block, &by_end) in alignments.iter().enumerate() { let start = block * DELTA_BLOCK; let range = start..(start + DELTA_BLOCK).min(older.len()); xor_shifted(&mut older, newer, range, if by_end != 0 { end_shift } else { 0 }); } older } impl Rewind { fn new() -> Rewind { Rewind { older: VecDeque::new(), newest: None, bytes: 0 } } fn len(&self) -> usize { self.older.len() + self.newest.is_some() as usize } fn clear(&mut self) { *self = Rewind::new(); } fn push(&mut self, raw: Vec) { use std::io::Write; if let Some(mut previous) = self.newest.take() { self.bytes -= previous.len(); let length = previous.len() as u32; let alignments = delta(&mut previous, &raw); let mut encoder = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::fast()); encoder .write_all(&length.to_le_bytes()) .and_then(|_| encoder.write_all(&alignments)) .and_then(|_| encoder.write_all(&previous)) .expect("compressing to memory"); let packed = encoder.finish().expect("compressing to memory"); self.bytes += packed.len(); self.older.push_back(packed); } self.bytes += raw.len(); self.newest = Some(raw); while self.len() > REWIND_KEEP || (self.bytes > REWIND_BUDGET && !self.older.is_empty()) { if let Some(old) = self.older.pop_front() { self.bytes -= old.len(); } } } /// The snapshot to load for one step back: the newest, which is then forgotten and the one /// before it rebuilt in its place; the oldest stays. None when nothing is kept, or a delta /// would not inflate (then nothing is kept any more). fn step(&mut self) -> Option> { let newest = self.newest.take()?; let Some(packed) = self.older.pop_back() else { self.newest = Some(newest.clone()); return Some(newest); }; self.bytes -= newest.len() + packed.len(); let mut plain = Vec::new(); if flate2::read::DeflateDecoder::new(packed.as_slice()) .read_to_end(&mut plain) .is_err() || plain.len() < 4 { self.clear(); return None; } let length = u32::from_le_bytes(plain[..4].try_into().unwrap()) as usize; let blocks = length.div_ceil(DELTA_BLOCK); if plain.len() != 4 + blocks + length { self.clear(); return None; } let xored = plain.split_off(4 + blocks); let previous = undo_delta(&plain[4..], xored, &newest); self.bytes += previous.len(); self.newest = Some(previous); Some(newest) } } /// Rewind keeps a snapshot every this many frames, so holding it goes back this many times /// faster than the game runs (play-nes's rewind). *Provisional*: measured cheap enough here /// (README, "Rewind"). 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 board's last captured /// picture as well as the machine; an Arcade Card's holds its 2 MiB of RAM, so on those discs /// the budget, not the count, is the limit (README, "Rewind"). *Provisional*. const REWIND_BUDGET: usize = 48 << 20; fn row_for(machine: &str, name: &str) -> Result { match machine { "pce" => Ok(PC_ENGINE), "tg16" => Ok(TURBOGRAFX_16), // A HuCard has no header: No-Intro's name says which side of the Pacific it is from. "" if name.to_uppercase().contains("(USA") => Ok(TURBOGRAFX_16), "" => Ok(PC_ENGINE), other => Err(format!("unknown console {other}")), } } #[wasm_bindgen] impl Console { /// Power on with a HuCard: `bytes` as the file holds them (a .zip or .7z is fine), `name` /// the file's name. `machine`: "" (the card's: SuperGrafx for the five known cards and a /// `.sgx`, TurboGrafx-16 for a "(USA)" name, else PC Engine), "pce", "tg16" or "sgx". /// `compat`: the SuperGrafx's back-panel switch in PC Engine position. `pad`: "2", "6", /// "tap2" or "tap6". `backup_unit`: the CD unit's 2 KiB backup RAM on the expansion port, /// with no disc (a PC Engine with the Interface Unit: card games that save, save there). /// `backup`: backup RAM kept from an earlier visit (empty for none). pub fn card( bytes: Vec, name: &str, sample_rate: u32, machine: &str, compat: bool, pad: &str, backup_unit: bool, backup: Vec, ) -> Result { Console::card_inner( bytes, name, sample_rate, machine, compat, pad, backup_unit, backup, ) .map_err(|e| JsError::new(&e)) } /// Power on with a disc. `system_card`: the visitor's own System Card image (256 KiB is a /// Super System Card). `cue`: the cue sheet's text. `lengths`: the byte length of each file /// the sheet names, in the sheet's order ([`cue_files`]). `read`: `(file, offset, length) -> /// Uint8Array`, synchronous, bytes of file `file` (the sheet's order again). `machine`: "" /// or "pce", or "tg16" (a TurboGrafx-16 with a US System Card). `arcade`: "on", "off" or "" /// (on for the titles sold as Arcade CD-ROM², by `name`). `bram`: backup RAM kept from an /// earlier visit (empty: formatted and empty). #[allow(clippy::too_many_arguments)] pub fn disc( system_card: Vec, cue: &str, lengths: Vec, read: js_sys::Function, name: &str, sample_rate: u32, machine: &str, arcade: &str, pad: &str, bram: Vec, ) -> Result { Console::disc_inner( system_card, cue, lengths, read, name, sample_rate, machine, arcade, pad, bram, ) .map_err(|e| JsError::new(&e)) } pub fn title(&self) -> String { self.title.clone() } /// "pce", "tg16", "sgx" or "cd". pub fn machine(&self) -> String { self.machine.to_string() } /// The machine and what is in it, for the page to show. pub fn describe(&self) -> String { self.described.clone() } /// Whether the Arcade Card is fitted. pub fn arcade(&self) -> bool { self.arcade } /// The pads plugged in: 1, or 5 behind the multitap. pub fn ports(&self) -> usize { self.ports } // -- input ------------------------------------------------------------------------- /// Player `index`'s pad: the board's bits (up 1, right 2, down 4, left 8, I $10, II $20, /// Select $40, Run $80, III-VI $100-$800) and the turbo switches ($1000 I, $2000 II). pub fn set_pad(&mut self, index: usize, mask: u32) { if index < self.held.len() { self.held[index] = mask; } } // -- 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. False if the /// snapshot could not be taken back (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 = state::save_snapshot(&self.system); for _ in 0..ahead { self.press(); self.system.run_frame(); } self.paint(); self.system.board_mut().take_audio(); match state::load_snapshot(&mut self.system, &snapshot) { Ok(()) => true, Err(error) => { self.messages.push(format!("Run-ahead off: {error}")); false } } } /// The pads as the board sees them this frame: opposite directions cancel, and a turbo /// switch presses its button on two frames of four (15 presses a second), by the console's /// own frame counter, so a save state and a frame run ahead agree about it. fn press(&mut self) { let phase = self.system.frame() & 2 == 0; for port in 0..self.ports { let mut mask = self.held[port]; if phase && mask & TURBO_I != 0 { mask |= pads::I as u32; } if phase && mask & TURBO_II != 0 { mask |= pads::II as u32; } let (ud, lr) = ((pads::UP | pads::DOWN) as u32, (pads::LEFT | pads::RIGHT) as u32); if mask & ud == ud { mask &= !ud; } if mask & lr == lr { mask &= !lr; } self.system .board_mut() .set_pressed(port, (mask & 0xFFF) as u16); } } /// The console's own next frame: input, the frame, how long it was, its sound. fn real_frame(&mut self) { self.press(); let before = self.system.board().mclk; self.system.run_frame(); let board = self.system.board_mut(); self.frame_ms = (board.mclk - before) as f64 * 1000.0 / MASTER_HZ as f64; let samples = board.take_audio(); self.sound.clear(); let scale = 1.0 / 32768.0; if self.sample_rate == BOARD_RATE { for (l, r) in samples { self.sound.push(l as f32 * scale); self.sound.push(r as f32 * scale); } } else { // The page's context would not run at the board's rate: straight lines between // the board's samples. let step = BOARD_RATE as f64 / self.sample_rate as f64; let count = samples.len() as f64; while self.resample_at < count { let index = self.resample_at as usize; let t = (self.resample_at - index as f64) as f32; let (al, ar) = if index == 0 { self.resample_last } else { let (l, r) = samples[index - 1]; (l as f32 * scale, r as f32 * scale) }; let (bl, br) = samples[index]; self.sound.push(al + (bl as f32 * scale - al) * t); self.sound.push(ar + (br as f32 * scale - ar) * t); self.resample_at += step; } self.resample_at -= count; if let Some(&(l, r)) = samples.last() { self.resample_last = (l as f32 * scale, r as f32 * scale); } } if let Some(error) = self.disc_error.borrow_mut().take() { self.messages .push(format!("The disc could not be read: {error}")); } if self.rewind_on { self.frames_since_snapshot += 1; if self.frames_since_snapshot >= REWIND_EVERY { self.frames_since_snapshot = 0; self.keep_snapshot(); } } } /// One snapshot onto the rewind window ([`Rewind`]), the oldest dropped past its limits. fn keep_snapshot(&mut self) { let raw = state::save_snapshot(&self.system); self.rewind.push(raw); } /// The board's picture into the RGBA buffer: the shown part of each row, every row at the /// width of the frame's finest dot clock. fn paint(&mut self) { let Some(frame) = self.system.board().capture.last_frame.as_ref() else { return; }; let finest = frame.dividers.iter().copied().min().unwrap_or(4).max(1) as usize; let width = VIEW_CLOCKS / finest; if width != self.width || self.rgba.len() != width * LINES * 4 { self.width = width; self.rgba = vec![255; width * LINES * 4]; } for ((row, ÷r), line) in frame .rows .iter() .zip(&frame.dividers) .zip(self.rgba.chunks_exact_mut(width * 4)) { let divider = (divider as usize).max(1); if row.is_empty() { continue; } let last = row.len() - 1; for (x, pixel) in line.chunks_exact_mut(4).enumerate() { let dot = if divider == finest { VIEW_START / divider + x } else { (VIEW_START + x * finest + finest / 2) / divider }; let [r, g, b] = self.colours[row[dot.min(last)] as usize & 0x1FF]; pixel[0] = r; pixel[1] = g; pixel[2] = b; } } } /// The picture's width in dots: 288, 384 or 576 by the dot clock (it can change from one /// frame to the next). Its height is always 242. pub fn width(&self) -> usize { self.width } pub fn height(&self) -> usize { LINES } /// The last frame's RGBA bytes, width × 242 × 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() } /// How long the last frame was on the machine, in milliseconds: 262 or 263 lines (16.65 /// or 16.72), as the program set the VCE. pub fn frame_ms(&self) -> f64 { self.frame_ms } /// Between frames: read the disc where the drive is going, if that is not here yet. The /// drive takes its time to seek (the board's seek model), so the sector a READ command /// has named, and the one CD audio will start from, are fetched while it is still on /// its way; and a drive reading on gets the block after the one it is in. True if /// anything was read (the host counts these apart from the drive's own reads). pub fn read_ahead(&mut self) -> bool { let Some(blocks) = self.blocks.clone() else { return false; }; let mut wanted = Vec::new(); if let Some(unit) = cd::unit(self.system.board_mut()) { if let Some(next) = read_pending(&unit.bus) { wanted.push(next); } let audio = unit.cdda().anchor_sample.div_euclid(588); if self.audio_from != Some(audio) { self.audio_from = Some(audio); wanted.push(audio); } } let mut blocks = blocks.borrow_mut(); let mut read = false; for lba in wanted { if let Some((file, offset)) = self.sheet.as_ref().and_then(|sheet| sheet.locate(lba)) { read |= blocks.ensure(file, offset); } } read | blocks.read_ahead() } /// What the CD unit is doing, for the checks (0 without one): 1 a READ still delivering /// (seeking to it included), 2 CD audio seeking, 4 CD audio playing, 8 ADPCM playing. pub fn cd_activity(&mut self) -> u32 { let Some(unit) = cd::unit(self.system.board_mut()) else { return 0; }; let mut bits = 0; if read_pending(&unit.bus).is_some() { bits |= 1; } match unit.bus.cdda.status { cd_cdda::Status::Seeking => bits |= 2, cd_cdda::Status::Playing => bits |= 4, _ => {} } if unit.adpcm.playing { bits |= 8; } bits } /// The next message to show (the disc could not be read), or "". pub fn take_message(&mut self) -> String { if self.messages.is_empty() { String::new() } else { self.messages.remove(0) } } // -- the SuperGrafx's switch ------------------------------------------------------- /// The back-panel switch (PC Engine position is `true`), moved while it runs. pub fn set_compat(&mut self, compat: bool) { if self.kind == Kind::SuperGrafx { set_compat(&mut self.system, compat); } } // -- backup RAM and save states ---------------------------------------------------- /// What `backup` is: "cd" (the CD unit's 2 KiB, one store for every game, as on the /// machine), "tennokoe" (the Tennokoe Bank card's 8 KiB) or "" (none). pub fn backup_kind(&self) -> String { if self.tennokoe { "tennokoe".to_string() } else if self.has_unit() { "cd".to_string() } else { String::new() } } fn has_unit(&self) -> bool { self.system.board().port.is_some() } /// The backup RAM, to keep between visits (empty if none). pub fn backup(&mut self) -> Vec { let board = self.system.board_mut(); if self.tennokoe { return tennokoe(board).map_or(Vec::new(), |card| card.ram.clone()); } cd::unit(board).map_or(Vec::new(), |unit| unit.bram().to_vec()) } /// Backup RAM into the running machine (an import). pub fn load_backup(&mut self, data: &[u8]) { let board = self.system.board_mut(); if self.tennokoe { if let Some(card) = tennokoe(board) { if data.len() == card.ram.len() { card.ram.copy_from_slice(data); } } } else if let Some(unit) = cd::unit(board) { unit.set_bram(data); } } /// The whole machine, as the board's save state (a disc is named in it, not stored). pub fn save_state(&self) -> Vec { state::save_state(&self.system) } pub fn load_state(&mut self, data: &[u8]) -> Result<(), JsError> { state::load_state(&mut self.system, data).map_err(|e| JsError::new(&e)) } // -- snapshots and rewind ---------------------------------------------------------- /// The board's in-memory snapshot (`state::save_snapshot`): the body of a save state with /// no header, no check and no compression, for this console only (run-ahead and rewind). /// Not for keeping: [`Console::save_state`] is. pub fn save_snapshot(&self) -> Vec { state::save_snapshot(&self.system) } /// Back to a [`Console::save_snapshot`] of this same console. Nothing is checked: a /// snapshot of another console is undefined (an error at best). pub fn load_snapshot(&mut self, data: &[u8]) -> Result<(), JsError> { state::load_snapshot(&mut self.system, data).map_err(|e| JsError::new(&e)) } /// 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). play-nes's `rewind_step`. pub fn rewind_step(&mut self) -> bool { let Some(raw) = self.rewind.step() else { return false; }; if let Err(error) = state::load_snapshot(&mut self.system, &raw) { self.messages.push(format!("Rewind: {error}")); self.rewind.clear(); 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_ms / 1000.0 } /// The rewind window's memory, in bytes. pub fn rewind_memory(&self) -> usize { self.rewind.bytes } /// The snapshots kept. pub fn rewind_count(&self) -> usize { self.rewind.len() } /// Rewind's snapshots on or off (on at power-on). Off forgets them: for the checks, which /// time the console with and without them. pub fn set_rewind(&mut self, on: bool) { self.rewind_on = on; if !on { self.rewind.clear(); self.frames_since_snapshot = 0; } } } /// The sector a READ(6) still has to deliver next, from what the bus shows: its command block /// (kept until the next selection), the data-in phase, and the head (the LBA after the last /// sector delivered). Before the first sector the head is wherever it was, so the READ's own /// LBA is the one wanted. pcenginecd-rust keeps the READ's counters private since its clean /// SCSI rewrite (3d75dd7); this asks only for its public fields. fn read_pending(bus: &cd_scsi::ScsiBus) -> Option { let cdb = &bus.cdb; if bus.phase != cd_scsi::Phase::DataIn || cdb.len() < 6 || cdb[0] != 0x08 || cdb[4] == 0 { return None; } let lba = ((cdb[1] & 0x1F) as i64) << 16 | (cdb[2] as i64) << 8 | cdb[3] as i64; let end = lba + cdb[4] as i64; // A head past the end may be a finished READ or one that has not started from further on: // the READ's LBA then, which is already kept in the first case (nothing is read again). Some(if bus.head > lba && bus.head < end { bus.head } else { lba }) } fn tennokoe(board: &mut Board) -> Option<&mut TennokoeCard> { board.slot.card.as_mut()?.as_any_mut().downcast_mut() } impl Console { fn finish( system: System, kind: Kind, title: String, machine: &'static str, described: String, ports: usize, sample_rate: u32, ) -> Console { let colours = system .board() .vce .rgb_table .iter() .map(|&(r, g, b)| [r, g, b]) .collect(); let width = VIEW_CLOCKS / 4; Console { system, kind, title, machine, described, tennokoe: false, arcade: false, ports, held: [0; 5], colours, rgba: vec![255; width * LINES * 4], width, sample_rate: if sample_rate == 0 { BOARD_RATE } else { sample_rate }, sound: Vec::new(), resample_at: 0.0, resample_last: (0.0, 0.0), frame_ms: 1000.0 * 263.0 * 1365.0 / MASTER_HZ as f64, messages: Vec::new(), disc_error: Rc::new(RefCell::new(None)), blocks: None, sheet: None, audio_from: None, rewind: Rewind::new(), frames_since_snapshot: 0, rewind_on: true, } } #[allow(clippy::too_many_arguments)] fn card_inner( bytes: Vec, name: &str, sample_rate: u32, machine: &str, compat: bool, pad: &str, backup_unit: bool, backup: Vec, ) -> Result { let (data, card_name) = unpack(bytes, name)?; let size = strip_copier_header(&data).len(); if size == 0 { return Err(format!("{card_name} is empty")); } if size > 16 * 1024 * 1024 { return Err(format!( "{card_name} is too large for a HuCard: a disc is a .cue and its .bin files, chosen together" )); } let (port, ports) = make_pad(pad)?; let kib = size / 1024; let supergrafx = machine == "sgx" || (machine.is_empty() && is_supergrafx_card(&data, Some(&card_name))); if supergrafx { let mut options = SuperGrafxOptions { compat, ..SuperGrafxOptions::default() }; options.board.card = Some(make_card(&data)?); options.board.pad = Some(port); let system = SuperGrafx::new(options)?.build(); let described = format!( "SuperGrafx{}, HuCard {kib} KiB, {}", if compat { " (switch in PC Engine position)" } else { "" }, pad_name(pad) ); return Ok(Console::finish( system, Kind::SuperGrafx, stem(&card_name), "sgx", described, ports, sample_rate, )); } // The names that may say what the card is: the file's, and the archive's it came in. let names = format!("{name} {card_name}"); let row = row_for(machine, &names)?; // Tennokoe Bank has no header to know it by: its name does. let tennokoe = names.to_lowercase().contains("tennokoe bank"); let card: Box = if tennokoe { let mut card = TennokoeCard::new(&data)?; if backup.len() == card.ram.len() { card.ram.copy_from_slice(&backup); } Box::new(card) } else { make_card(&data)? }; let unit = (backup_unit && !tennokoe) .then(|| { let kept = (!backup.is_empty()).then_some(backup.as_slice()); PcEngineCd::make_unit(None, kept, false, &CdSwitches::default()) }) .transpose()?; let with_unit = unit.is_some(); let board = Board::new(BoardOptions { machine: row, card: Some(card), pad: Some(port), port: unit.map(|unit| Box::new(unit) as _), ..BoardOptions::default() })?; let described = format!( "{}, HuCard {kib} KiB{}, {}", row.name, if tennokoe { " with 8 KiB of backup RAM" } else if with_unit { ", backup RAM unit" } else { "" }, pad_name(pad) ); let mut console = Console::finish( System::new(board), Kind::Card, stem(&card_name), if row.country_pc_engine { "pce" } else { "tg16" }, described, ports, sample_rate, ); console.tennokoe = tennokoe; Ok(console) } #[allow(clippy::too_many_arguments)] fn disc_inner( system_card: Vec, cue: &str, lengths: Vec, read: js_sys::Function, name: &str, sample_rate: u32, machine: &str, arcade: &str, pad: &str, bram: Vec, ) -> Result { if system_card.is_empty() { return Err("A CD game needs a System Card: choose your own image of one first (Super System Card 3.0 runs everything).".to_string()); } let (card_image, _) = unpack(system_card, "System Card")?; let card_size = strip_copier_header(&card_image).len(); if card_size == 0 || card_size % 8192 != 0 || card_size > 1024 * 1024 { return Err(format!( "That is not a System Card image ({card_size} bytes; Super System Card 3.0 is 262,144)." )); } let lengths: Vec = lengths.iter().map(|&l| l.max(0.0) as u64).collect(); let mut asked = 0; let sheet = parse_cue(cue, &mut |file| { let length = lengths .get(asked) .copied() .ok_or_else(|| format!("the cue sheet names {file}, which was not chosen"))?; asked += 1; Ok(length) })?; let disc_error = Rc::new(RefCell::new(None)); let blocks = Rc::new(RefCell::new(Blocks { read, lengths, kept: VecDeque::new(), last: None, error: disc_error.clone(), })); let drive = blocks.clone(); let reader = move |file: usize, offset: u64, out: &mut [u8]| drive.borrow_mut().read_at(file, offset, out); let disc = Disc::from_cue(&sheet, Box::new(CueSource::new(&sheet, reader))); let tracks = disc.tracks.len(); let data_tracks = disc.tracks.iter().filter(|t| t.is_data).count(); let megabytes = sheet.sector_count as f64 * 2352.0 / (1024.0 * 1024.0); if data_tracks == 0 { return Err("That disc has no data track: it is a music CD, not a game.".to_string()); } let us = machine == "tg16"; let fit_arcade = match arcade { "on" => true, "off" => false, _ => wants_arcade_card(name), }; let (port, ports) = make_pad(pad)?; let mut unit = PcEngineCd::new(&card_image, Some(disc)); unit.arcade_card = fit_arcade; unit.region_us = us; unit.bram = (!bram.is_empty()).then_some(bram); unit.board.machine = if us { TURBOGRAFX_16 } else { PC_ENGINE }; unit.board.pad = Some(port); let system = unit.build()?; let described = format!( "{} with {}{}, {}; disc of {tracks} tracks, {megabytes:.0} MiB", if us { "TurboGrafx-16" } else { "PC Engine" }, if card_size == 256 * 1024 { "the Super System Card" } else { "a System Card (CD-ROM² only: Super CD games need the 256 KiB card)" }, if fit_arcade { " and the Arcade Card" } else { "" }, pad_name(pad), ); let mut console = Console::finish( system, Kind::Cd, stem(name), "cd", described, ports, sample_rate, ); console.arcade = fit_arcade; console.disc_error = disc_error; console.blocks = Some(blocks); console.sheet = Some(sheet); Ok(console) } } /// Whether the board would build a SuperGrafx for this card (one of the five known images, or /// a `.sgx` name), for the page's settings to say. #[wasm_bindgen] pub fn is_supergrafx(bytes: Vec, name: &str) -> bool { match unpack(bytes, name) { Ok((data, card_name)) => is_supergrafx_card(&data, Some(&card_name)), Err(_) => false, } } #[cfg(test)] mod tests { use super::*; /// The window gives back every snapshot pushed, newest first, whatever their lengths, and /// then keeps giving the oldest. #[test] fn rewind_gives_back_every_snapshot() { let snapshots: Vec> = (0..40u32) .map(|n| { let length = 1000 + (n as usize % 7) * 37; // lengths change, as a picture's width does (0..length).map(|i| ((i as u32 * 31 + n * 17) % 251) as u8).collect() }) .collect(); let mut rewind = Rewind::new(); for s in &snapshots { rewind.push(s.clone()); } assert_eq!(rewind.len(), snapshots.len()); for s in snapshots.iter().rev() { assert_eq!(rewind.step().as_ref(), Some(s)); } assert_eq!(rewind.step().as_ref(), snapshots.first()); assert_eq!(rewind.len(), 1); assert_eq!(rewind.bytes, snapshots[0].len()); } /// A length that changes in the middle (as the board's sound buffers do) moves everything /// after it: the delta still comes back exact, and stays small. #[test] fn rewind_survives_a_length_change_in_the_middle() { let tail: Vec = (0..100_000u32).map(|i| (i * 7 % 253) as u8).collect(); let make = |n: usize| { let mut s = vec![1u8; 5000]; s.extend(std::iter::repeat(n as u8).take(n % 5 * 8)); s.extend(&tail); s[70_000] = n as u8; // something in the moved part changes too s }; let snapshots: Vec> = (0..20).map(make).collect(); let mut rewind = Rewind::new(); for s in &snapshots { rewind.push(s.clone()); } let deltas = rewind.bytes - snapshots.last().unwrap().len(); assert!(deltas < 19 * 2000, "deltas take {deltas} bytes"); for s in snapshots.iter().rev() { assert_eq!(rewind.step().as_ref(), Some(s)); } } /// Past its budget the window drops the oldest, and what it keeps still comes back whole. #[test] fn rewind_drops_the_oldest_past_its_budget() { let mut rewind = Rewind::new(); let mut last = Vec::new(); for n in 0..(REWIND_KEEP + 50) { last = vec![n as u8; 64]; rewind.push(last.clone()); } assert_eq!(rewind.len(), REWIND_KEEP); assert_eq!(rewind.step(), Some(last)); let mut steps = 1; while rewind.len() > 1 { rewind.step().unwrap(); steps += 1; } assert_eq!(steps, REWIND_KEEP - 1); assert_eq!(rewind.step(), Some(vec![50u8; 64])); } }