// SPDX-License-Identifier: MIT //! The lockstep gate's Rust side: this board, traced slice by slice, in the lines //! `scripts/a7800_trace.py` writes for the reference (its docstring is the format). //! //! `--save-at N` (7800 mode): after slice N the console is saved (`state::save_state`), //! a fresh console is built from the same cartridge and options, the state is loaded into //! it, and the trace goes on from the fresh one: the save-state round trip the gate's //! `--save-at-half` proves. use std::cell::RefCell; use std::path::PathBuf; use std::rc::Rc; use a2600::cartridge::{Options, Rom}; use a2600::riot::RIOT; use a7800::cartridge::formats::{self, LoadOptions, Source}; use a7800::controllers::{LightGun, ProLine, Stick}; use a7800::machine::{Machine, NTSC, PAL}; use a7800::mode2600::System2600; use a7800::sound::SoundTap; use a7800::state; use a7800::system::System; struct Args { rom: PathBuf, slices: u64, machine: Machine, start: &'static str, mode: String, override_words: Option, presses: Vec<(u64, String, u64, usize)>, aims: Vec<(u64, Option<(u32, u32)>)>, pulls: Vec<(u64, u64)>, difficulty: String, audio: bool, detail: i64, faults: Vec, save_at: i64, out: PathBuf, } fn parse() -> Result { let mut it = std::env::args().skip(1); let mut args = Args { rom: PathBuf::new(), slices: 0, machine: NTSC, start: "bios", mode: "7800".to_string(), override_words: None, presses: Vec::new(), aims: Vec::new(), pulls: Vec::new(), difficulty: String::new(), audio: false, detail: -1, faults: Vec::new(), save_at: -1, out: PathBuf::new(), }; let mut rom = None; let num = |s: &str| s.parse::().map_err(|e| format!("{s}: {e}")); while let Some(arg) = it.next() { let mut value = || it.next().ok_or(format!("{arg} needs a value")); match arg.as_str() { "--slices" => args.slices = num(&value()?)?, "--machine" => { args.machine = match value()?.as_str() { "ntsc" => NTSC, "pal" => PAL, other => return Err(format!("--machine {other}")), } } "--start" => { args.start = match value()?.as_str() { "bios" => "bios", "direct" => "direct", other => return Err(format!("--start {other}")), } } "--mode" => args.mode = value()?, "--as" => args.override_words = Some(value()?), "--press" => { let v = value()?; let parts: Vec<&str> = v.split(':').collect(); let port = if parts.len() > 3 { num(parts[3])? as usize - 1 } else { 0 }; args.presses .push((num(parts[0])?, parts[1].to_string(), num(parts[2])?, port)); } "--gun" => { let v = value()?; let parts: Vec<&str> = v.split(':').collect(); let aim = if parts[1] == "off" { None } else { Some((num(parts[1])? as u32, num(parts[2])? as u32)) }; args.aims.push((num(parts[0])?, aim)); } "--pull" => { let v = value()?; let (f, n) = v.split_once(':').ok_or("--pull FRAME:FRAMES")?; args.pulls.push((num(f)?, num(n)?)); } "--difficulty" => args.difficulty = value()?, "--audio" => args.audio = true, "--detail" => args.detail = value()?.parse().map_err(|e| format!("{e}"))?, "--fault" => args.faults.push(value()?), "--save-at" => args.save_at = value()?.parse().map_err(|e| format!("{e}"))?, "--out" => args.out = PathBuf::from(value()?), other if other.starts_with("--") => return Err(format!("unknown option {other}")), other => rom = Some(PathBuf::from(other)), } } args.rom = rom.ok_or("a ROM")?; Ok(args) } type Log = Rc>>; /// The trace's shared buffers and the attached tap. struct Trace { log: Log, lines: Rc>>, tap: Option, out: String, detail: i64, } fn kind_code(kind: char) -> u64 { match kind { 'R' => 0, 'W' => 1, _ => 2, } } impl Trace { fn finish(&mut self, index: u64, head: &str, tia: Option<&mut a2600::tia::TIA>) { let mut log = self.log.borrow_mut(); let mut lines = self.lines.borrow_mut(); let bus = if log.is_empty() { 0 } else { let mut h = crc32fast::Hasher::new(); for r in log.iter() { h.update(&r.to_le_bytes()); } h.finalize() }; let pic = crc32fast::hash(&lines); self.out.push_str(&format!( "{index} {head} bus={bus:08x}/{} pic={pic:08x}/{}", log.len(), lines.len() )); if let (Some(tap), Some(tia)) = (self.tap.as_ref(), tia) { tia.audio.take_samples(); let samples = std::mem::take(&mut tap.streams.borrow_mut().mixed); let mut h = crc32fast::Hasher::new(); for s in &samples { h.update(&s.to_le_bytes()); } self.out .push_str(&format!(" snd={:08x}/{}", h.finalize(), samples.len())); } self.out.push('\n'); if index as i64 == self.detail { for record in log.iter() { let kind = ['R', 'W', 'D', '?'][((record >> 24) & 3) as usize]; self.out.push_str(&format!( " {} {kind} {:04x} {:02x}\n", record >> 26, (record >> 8) & 0xFFFF, record & 0xFF )); } } log.clear(); lines.clear(); } } fn cpu_text(cpu: &sixfiveohtwo::Mos6502) -> String { format!( "pc={:04x} a={:02x} x={:02x} y={:02x} s={:02x} p={:02x}", cpu.pc, cpu.a, cpu.x, cpu.y, cpu.s, cpu.p ) } fn head7800(system: &System) -> String { let board = system.board(); let maria = &board.maria; format!( "clk={} per={} halt={} stall={} slow={} fr={} ln={} c={} {} ictl={:02x} db={:02x}", board.clocks, board.periods, board.halted_periods, board.stalled_periods, board.slow_cycles, maria.frame, maria.line, maria.clock_in_line, cpu_text(&system.cpu), board.inptctrl, board.data_bus ) } /// Attach the trace and the inputs to a 7800 System as soon as it exists. fn wire(system: &mut System, args: &Args, log: &Log, lines: &Rc>>) -> Result, String> { let board = system.board_mut(); let l = log.clone(); board.bus_observers.push(Box::new(move |kind, address, value, clock| { l.borrow_mut() .push(clock << 26 | kind_code(kind) << 24 | (address as u64) << 8 | value as u64) })); let p = lines.clone(); board.maria.on_line = Some(Box::new(move |_line, pixels, _kill| { p.borrow_mut().extend_from_slice(pixels) })); for fault in &args.faults { board.faults().add(fault)?; } if !args.difficulty.is_empty() { let mut riot = board.riot.borrow_mut(); for (side, bit) in args.difficulty.chars().zip([0x40u8, 0x80]) { if side == 'a' { riot.input_b |= bit; } else { riot.input_b &= !bit; } } } if !args.aims.is_empty() || !args.pulls.is_empty() { LightGun::attach(board, 0); } Ok(if args.audio { Some(SoundTap::new(board, false).attach(board)) } else { None }) } fn apply(frame: u64, args: &Args, controllers: &ProLine, riot: &Rc>, gun: Option<&mut LightGun>) { for port in [0usize, 1] { let held: Vec<&str> = args .presses .iter() .filter(|(f, _, n, p)| *p == port && *f <= frame && frame < f + n) .map(|(_, k, _, _)| k.as_str()) .collect(); let has = |k: &str| held.contains(&k); controllers.set( port, Stick { up: has("up"), down: has("down"), left: has("left"), right: has("right"), left_button: has("b1") || has("b12"), right_button: has("b2") || has("b12"), }, ); } let switches: Vec<&str> = args .presses .iter() .filter(|(f, _, n, _)| *f <= frame && frame < f + n) .map(|(_, k, _, _)| k.as_str()) .collect(); { let mut r = riot.borrow_mut(); for (key, bit) in [("reset", 0x01u8), ("select", 0x02), ("pause", 0x08)] { if switches.contains(&key) { r.input_b &= !bit; } else { r.input_b |= bit; } } } if let Some(gun) = gun { let mut aim = None; for (f, a) in &args.aims { if *f <= frame { aim = *a; } } let trigger = args.pulls.iter().any(|(f, n)| *f <= frame && frame < f + n); gun.set(aim, trigger); } } fn build_7800(args: &Args) -> Result { let overrides = match args.override_words.as_deref() { Some(words) => Some(formats::parse_as(words)?), None => None, }; let options = LoadOptions { overrides, ..LoadOptions::default() }; System::from_rom(Source::Path(&args.rom), args.machine, &options, None, args.start) } fn run() -> Result<(), String> { let args = parse()?; let mut trace = Trace { log: Rc::new(RefCell::new(Vec::new())), lines: Rc::new(RefCell::new(Vec::new())), tap: None, out: String::new(), detail: args.detail, }; if args.mode == "7800" { let mut system = build_7800(&args)?; trace.tap = wire(&mut system, &args, &trace.log, &trace.lines)?; for index in 0..args.slices { let riot = system.board().riot.clone(); let board = &mut system.cpu.bus; apply(index + 1, &args, &system.controllers, &riot, board.light_gun.as_mut()); system.run_frames(1); let head = head7800(&system); trace.finish(index, &head, Some(&mut system.cpu.bus.tia)); if index as i64 == args.save_at { let saved = state::save_state(&system); let mut fresh = build_7800(&args)?; trace.tap = wire(&mut fresh, &args, &trace.log, &trace.lines)?; state::load_state(&mut fresh, &saved)?; system = fresh; } } } else { let data = formats::read_source(Source::Path(&args.rom)).map_err(|e| e.message)?.1; let mut tap = None; let mut failure = None; let mut system = System2600::from_rom_with( Rom::Bytes(&data), args.machine, args.start, None, 0, None, Options::default(), &mut |seven: &mut System| match wire(seven, &args, &trace.log, &trace.lines) { Ok(t) => tap = t, Err(e) => failure = Some(e), }, )?; if let Some(e) = failure { return Err(e); } trace.tap = tap; let head = head7800(&system.seven); trace.finish(0, &head, Some(&mut system.system.board_mut().tia)); let l = trace.log.clone(); system .system .board_mut() .bus_observers .push(Box::new(move |kind, address, value, cycle| { l.borrow_mut() .push(cycle << 26 | kind_code(kind) << 24 | (address as u64) << 8 | value as u64) })); let p = trace.lines.clone(); system.system.board_mut().tia.on_line = Some(Box::new(move |tia| p.borrow_mut().extend_from_slice(&tia.pixels))); let riot = system.system.board().riot.clone(); for index in 1..args.slices { apply(index, &args, &system.seven.controllers, &riot, None); system.system.run_frames(1); let board = system.system.board(); let head = format!( "cyc={} hcyc={} fr={} ln={} {} db={:02x}", board.cycles, board.halted_cycles, board.tia.frame, board.tia.line, cpu_text(&system.system.cpu), board.data_bus ); trace.finish(index, &head, Some(&mut system.system.board_mut().tia)); } } std::fs::write(&args.out, trace.out).map_err(|e| e.to_string()) } fn main() { if let Err(e) = run() { eprintln!("a7800-trace: {e}"); std::process::exit(1); } }