// SPDX-License-Identifier: MIT //! The lockstep gate's Rust side: this board, traced slice by slice, writing the lines //! `scripts/lynx_trace.py` writes for the reference (see its docstring for the fields). //! //! lynx-trace CART --slices N [--machine lynx1|lynx2] [--input FILE] [--audio] //! [--timeline measured|paths] [--eeprom TYPE[:ORG]] [--picture] //! [--detail SLICE] [--save-at SLICE] --out FILE //! //! `--save-at SLICE`: before that slice the console's state is saved, a fresh console is //! booted from the same cart, the state is loaded into it, and the run continues on the //! fresh console (the save-state round trip of the gate's `--save-at-half`). use std::collections::BTreeMap; use std::io::Write; use std::path::PathBuf; use lynx::cart::load_path; use lynx::picture::{rotate, HEIGHT, WIDTH}; use lynx::run::boot; use lynx::{machine_named, Lynx}; const SLICE_TICKS: i64 = 266_667; fn button(name: &str) -> u8 { match name { "up" => 0x80, "down" => 0x40, "left" => 0x20, "right" => 0x10, "opt1" => 0x08, "opt2" => 0x04, "b" => 0x02, "a" => 0x01, _ => panic!("unknown button {name}"), } } fn read_inputs(path: &Option) -> BTreeMap> { let mut out = BTreeMap::new(); if let Some(path) = path { let text = std::fs::read_to_string(path).expect("input file"); for line in text.lines() { let words: Vec<&str> = line.split('#').next().unwrap().split_whitespace().collect(); if let Some((first, rest)) = words.split_first() { out.insert( first.parse().expect("slice"), rest.iter() .filter(|w| **w != "-") .map(|w| w.to_string()) .collect(), ); } } } out } fn main() { let mut args = std::env::args().skip(1); let mut cart: Option = None; let mut slices = 0usize; let mut machine = "lynx2".to_string(); let mut input: Option = None; let mut audio = false; let mut detail: i64 = -1; let mut save_at: i64 = -1; let mut out_path: Option = None; let mut eeprom: Option = None; let mut picture_line = false; while let Some(a) = args.next() { match a.as_str() { "--slices" => slices = args.next().unwrap().parse().unwrap(), "--machine" => machine = args.next().unwrap(), "--input" => input = Some(args.next().unwrap().into()), "--audio" => audio = true, "--timeline" => std::env::set_var("LYNX_SUZY_TIMELINE", args.next().unwrap()), "--eeprom" => eeprom = Some(args.next().unwrap()), "--picture" => picture_line = true, "--detail" => detail = args.next().unwrap().parse().unwrap(), "--save-at" => save_at = args.next().unwrap().parse().unwrap(), "--out" => out_path = Some(args.next().unwrap().into()), _ if cart.is_none() && !a.starts_with("--") => cart = Some(a.into()), _ => panic!("unknown argument {a}"), } } let cart = cart.expect("a cart"); let machine = machine_named(&machine).expect("a machine row"); let mut overrides = serde_json::Map::new(); if let Some(e) = eeprom { overrides.insert("eeprom".into(), serde_json::Value::String(e)); } let description = load_path(&cart, Some(&overrides)).unwrap_or_else(|e| panic!("{e}")); let mut board: Lynx = boot(&description, machine).unwrap_or_else(|e| panic!("{e}")); if audio { let tick = board.tick(); board.hw_mut().mikey.start_audio(tick); } board.hw_mut().trace = Some(Vec::new()); let inputs = read_inputs(&input); let mut sent = 0usize; let mut out = std::io::BufWriter::new(std::fs::File::create(out_path.expect("--out")).unwrap()); for index in 0..slices { if index as i64 == save_at { let state = board.save_state(); let mut fresh = boot(&description, machine).unwrap(); fresh.hw_mut().trace = board.hw_mut().trace.take(); fresh.load_state(&state).expect("load state"); board = fresh; } if let Some(names) = inputs.get(&index) { let mut keys = 0u8; for name in names { if name != "pause" { keys |= button(name); } } let suzy = &mut board.hw_mut().suzy; suzy.joystick = keys; suzy.switches = (suzy.switches & !1) | names.iter().any(|n| n == "pause") as u8; } let end = (index as i64 + 1) * SLICE_TICKS; while board.tick() < end { board.step(); } let cpu = &board.cpu; let hw = board.hw(); let log = hw.trace.as_ref().unwrap(); let bus = if log.is_empty() { 0 } else { let mut hasher = crc32fast::Hasher::new(); for record in log { hasher.update(&record[0].to_le_bytes()); hasher.update(&record[1].to_le_bytes()); } hasher.finalize() }; let display = &hw.mikey.display; let picture = crc32fast::hash(&display.frame); let ram = crc32fast::hash(&hw.ram); write!( out, "{index} t={} pc={:04x} a={:02x} x={:02x} y={:02x} s={:02x} p={:02x} irq={:02x} \ line={} map={:02x} frames={} period={} li={} busy={} eng={} sdone={} \ cart={:02x}/{:03x} bus={bus:08x}/{} pic={picture:08x} ram={ram:08x}", hw.tick, cpu.pc, cpu.a, cpu.x, cpu.y, cpu.s, cpu.p, hw.mikey.irq_bits(), hw.irq_line as u8, hw.mapctl, display.frames, display.frame_period, display.line_index, hw.suzy.sprite_busy, hw.suzy.engine.steps.is_some() as u8, hw.mikey.sdone_pending, hw.port.shift, hw.port.counter, log.len(), ) .unwrap(); if audio { let samples = hw.mikey.samples.as_ref().unwrap(); let chunk: Vec = samples[sent..] .iter() .flat_map(|s| s.to_le_bytes()) .collect(); sent = samples.len(); write!( out, " snd={:08x}/{}", crc32fast::hash(&chunk), chunk.len() / 2 ) .unwrap(); } if let Some(e) = &hw.port.eeprom { write!( out, " eep={:08x}/{}/{}", crc32fast::hash(&e.image()), e.writes, e.reads ) .unwrap(); } if picture_line { let (turned, width, height) = rotate(&display.rgb(), &description.rotation, WIDTH, HEIGHT); write!( out, " rgb={:08x}/{width}x{height}", crc32fast::hash(&turned) ) .unwrap(); } writeln!(out).unwrap(); if index as i64 == detail { for record in log { let word = record[1]; writeln!( out, " {} {} {:04x} {:02x}", record[0], if word >> 24 != 0 { 'w' } else { 'r' }, (word >> 8) & 0xFFFF, word & 0xFF ) .unwrap(); } } board.hw_mut().trace.as_mut().unwrap().clear(); } }