// SPDX-License-Identifier: MIT //! `a2600-play`: the board in a window (SDL2, feature `frontend`), for playing //! and for looking; the reference's `play.py` (pygame-ce) in Rust. //! //! A host, not part of the specification (charter "The tiers": windows run a //! tier, they do not define behaviour): it reads the keyboard and mouse into the //! controllers of controllers.rs and savekey.rs, runs the board a frame at a //! time, shows the television's frames through a palette (palettes.rs), and //! plays the TIA's samples. //! //! Headless judging: run with `SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy` and //! `--frames N --screenshot out.png`; the window then exits after N frames //! (scripts/ladder.sh does). No human has looked at this window yet: it is //! judged headless only. //! //! Keys (the reference's): arrows and Space for the left joystick (Space also //! fires a Driving controller, whose knob is Left/Right; Z and X are a Booster //! Grip's pins 5 and 9); I J K L and Right Shift for the right joystick; the //! mouse's x is paddle 0 (left button its fire) when paddles are in; keypads //! are 1 2 3 / Q W E / A S D / Z X C (left) and the numeric keypad (right). F1 //! Game Select, F2 Game Reset, F3 colour / black-and-white, F4 and F5 the left //! and right difficulty switches, Escape quits. //! //! Differences from play.py beyond the toolkit: the screenshot is this //! program's own PNG of the scaled frame; sound is queued while SDL's queue //! holds less than a frame and a half (pygame's channel keeps one sound //! waiting). use std::path::PathBuf; use sdl2::audio::{AudioQueue, AudioSpecDesired}; use sdl2::event::Event; use sdl2::keyboard::{KeyboardState, Keycode, Scancode}; use sdl2::pixels::PixelFormatEnum; use sdl2::rect::Rect; use a2600::board::Board; use a2600::cartridge::{Options, Rom}; use a2600::controllers::{BoosterGrip, DrivingController, Joystick, Keypads, Paddles, Stick}; use a2600::machine::machine; use a2600::palettes::palette; use a2600::savekey::{default_path, round_half_even, SaveKey}; use a2600::television::{frame_rgb, Television}; use a2600::System; // Host settings, not hardware behaviour: no evidence tag applies. const AUDIO_RATE: i32 = 44_100; const LEFT_DEVICES: [&str; 6] = ["joystick", "paddles", "driving", "booster", "keypad", "none"]; const RIGHT_DEVICES: [&str; 5] = ["joystick", "paddles", "keypad", "savekey", "none"]; struct Args { rom: PathBuf, machine: String, scheme: Option, left: String, right: String, savekey_file: Option, palette: Option, phosphor: bool, scale: u32, mute: bool, frames: Option, screenshot: Option, } fn parse_args() -> Args { let mut it = std::env::args().skip(1); let mut a = Args { rom: PathBuf::new(), machine: "ntsc".into(), scheme: None, left: "joystick".into(), right: "joystick".into(), savekey_file: None, palette: None, phosphor: false, scale: 3, mute: false, frames: None, screenshot: None, }; while let Some(arg) = it.next() { let mut value = || it.next().unwrap_or_else(|| panic!("{arg} needs a value")); match arg.as_str() { "--machine" => a.machine = value(), "--scheme" => a.scheme = Some(value()), "--left" => a.left = value(), "--right" => a.right = value(), "--savekey-file" => a.savekey_file = Some(value().into()), "--palette" => a.palette = Some(value()), "--phosphor" => a.phosphor = true, "--scale" => a.scale = value().parse().expect("scale"), "--mute" => a.mute = true, "--frames" => a.frames = Some(value().parse().expect("frames")), "--screenshot" => a.screenshot = Some(value().into()), "-h" | "--help" => { println!( "a2600-play ROM [--machine ntsc|pal|secam] [--scheme S] [--left {}] [--right {}] \ [--savekey-file F (default {})] [--palette P] [--phosphor] [--scale N] [--mute] \ [--frames N] [--screenshot F]", LEFT_DEVICES.join("|"), RIGHT_DEVICES.join("|"), default_path().display() ); std::process::exit(0); } _ => a.rom = PathBuf::from(arg), } } assert!( LEFT_DEVICES.contains(&a.left.as_str()), "--left: one of {LEFT_DEVICES:?}" ); assert!( RIGHT_DEVICES.contains(&a.right.as_str()), "--right: one of {RIGHT_DEVICES:?}" ); a } enum Left { Joystick(Joystick), Driving(DrivingController), Booster(BoosterGrip), None, } /// The keyboard and mouse, read into the plugged-in devices. struct Controls { paddles: Option, keypads: Option, left_kind: String, right_kind: String, left: Left, right: Option, _savekey: Option, } impl Controls { fn new(system: &mut System, left: &str, right: &str, savekey_file: &std::path::Path) -> Controls { let clock = system.machine.timing.colour_clock_hz; let cpu_hz = system.machine.timing.cpu_hz(); let board: &mut Board = system.board_mut(); let riot_rc = board.riot.clone(); let tia = &mut board.tia; let paddles = if left == "paddles" || right == "paddles" || left == "booster" { Some(Paddles::new(tia, clock)) } else { None }; let keypads = if left == "keypad" || right == "keypad" { Some(Keypads::new(tia, riot_rc.clone())) } else { None }; let mut riot = riot_rc.borrow_mut(); let left_device = match left { "joystick" => Left::Joystick(Joystick::new(0)), "driving" => Left::Driving(DrivingController::new(tia, &mut riot, 0)), "booster" => Left::Booster(BoosterGrip::new(paddles.clone().expect("paddles"), 0)), _ => Left::None, }; let right_device = if right == "joystick" { Some(Joystick::new(1)) } else { None }; let savekey = if right == "savekey" { Some(SaveKey::new(&mut riot, cpu_hz, 1, Some(savekey_file))) } else { None }; if let Some(p) = paddles.as_ref() { for (i, kind) in [(0, left), (2, right)] { if kind == "paddles" { let mut position = p.position.borrow_mut(); position[i] = Some(0.5); position[i + 1] = Some(0.5); } } } Controls { paddles, keypads, left_kind: left.into(), right_kind: right.into(), left: left_device, right: right_device, _savekey: savekey, } } fn update(&mut self, system: &mut System, keys: &KeyboardState, mouse_x: f64, mouse_down: bool) { let k = |code: Scancode| keys.is_scancode_pressed(code); let board = system.board_mut(); let riot_rc = board.riot.clone(); let mut riot = riot_rc.borrow_mut(); let tia = &mut board.tia; let stick = Stick { up: k(Scancode::Up), down: k(Scancode::Down), left: k(Scancode::Left), right: k(Scancode::Right), fire: k(Scancode::Space), }; match &mut self.left { Left::Joystick(j) => j.set(tia, &mut riot, stick), Left::Driving(w) => { w.turn(tia, &mut riot, k(Scancode::Right) as i64 - k(Scancode::Left) as i64); w.press(tia, &mut riot, k(Scancode::Space)); } Left::Booster(g) => g.set(tia, &mut riot, k(Scancode::Z), k(Scancode::X), stick), Left::None => {} } if let Some(right) = &self.right { let stick = Stick { up: k(Scancode::I), down: k(Scancode::K), left: k(Scancode::J), right: k(Scancode::L), fire: k(Scancode::RShift), }; right.set(tia, &mut riot, stick); } if let Some(p) = &self.paddles { if self.left_kind == "paddles" || self.right_kind == "paddles" { // Paddle buttons are SWCHA D7 and D6 (left pair), D3 and D2 (right) (DOC: nocash). let first = if self.left_kind == "paddles" { 0 } else { 2 }; p.position.borrow_mut()[first] = Some(1.0 - mouse_x); let bit = if first == 0 { 0x80 } else { 0x08 }; let input = riot.input_a; riot.set_input_a(if mouse_down { input & !bit } else { input | bit }); } } if let Some(keypads) = &self.keypads { use Scancode as S; let rows = [ [S::Num1, S::Num2, S::Num3], [S::Q, S::W, S::E], [S::A, S::S, S::D], [S::Z, S::X, S::C], ]; let pad = [ [S::Kp7, S::Kp8, S::Kp9], [S::Kp4, S::Kp5, S::Kp6], [S::Kp1, S::Kp2, S::Kp3], [S::KpMultiply, S::Kp0, S::KpDivide], ]; let kinds = [&self.left_kind, &self.right_kind]; for (port, table) in [(0, rows), (1, pad)] { if kinds[port] == "keypad" { let mut pressed = keypads.pressed.borrow_mut(); pressed[port].clear(); for (r, row) in table.iter().enumerate() { for (c, &key) in row.iter().enumerate() { if k(key) { pressed[port].insert((r as u8, c as u8)); } } } } } } } } /// Linear resampling of `samples` (0..1) to AUDIO_RATE, as signed 16-bit mono. fn resample(samples: &[f64], rate_in: f64, phase: f64) -> (Vec, f64) { let mut out = Vec::new(); let step = rate_in / AUDIO_RATE as f64; let mut t = phase; let n = samples.len() as f64; while t < n - 1.0 { let i = t as usize; let f = t - i as f64; let v = samples[i] * (1.0 - f) + samples[i + 1] * f; out.push(round_half_even((v - 0.5) * 32000.0) as i16); t += step; } (out, t - (n - 1.0)) } /// RGB rows as a PNG (the screenshot). fn rgb_png(rows: &[Vec]) -> Vec { use std::io::Write; let width = rows.first().map(|r| r.len() / 3).unwrap_or(0) as u32; let raw: Vec = rows .iter() .flat_map(|r| std::iter::once(0u8).chain(r.iter().copied())) .collect(); let chunk = |kind: &[u8], data: &[u8]| -> Vec { let mut out = (data.len() as u32).to_be_bytes().to_vec(); out.extend_from_slice(kind); out.extend_from_slice(data); let mut crc = crc32fast::Hasher::new(); crc.update(kind); crc.update(data); out.extend_from_slice(&crc.finalize().to_be_bytes()); out }; let mut header = width.to_be_bytes().to_vec(); header.extend_from_slice(&(rows.len() as u32).to_be_bytes()); header.extend_from_slice(&[8, 2, 0, 0, 0]); let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); z.write_all(&raw).unwrap(); let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); png.extend(chunk(b"IHDR", &header)); png.extend(chunk(b"IDAT", &z.finish().unwrap())); png.extend(chunk(b"IEND", b"")); png } fn main() -> Result<(), String> { let args = parse_args(); let row = machine(&format!("Atari VCS ({})", args.machine.to_uppercase())).expect("ntsc, pal or secam"); let mut system = System::from_rom(Rom::Path(&args.rom), row, args.scheme.as_deref(), Options::default())?; let tv = Television::new(&mut system.board_mut().tia); let savekey_file = args.savekey_file.clone().unwrap_or_else(default_path); let mut controls = Controls::new(&mut system, &args.left, &args.right, &savekey_file); let pal = palette(args.palette.as_deref().unwrap_or(row.palette)); let rate_in = 2.0 * row.timing.colour_clock_hz / 228.0; // two audio ticks a line let sdl = sdl2::init()?; let video = sdl.video()?; let sound = !args.mute && std::env::var("SDL_AUDIODRIVER").map(|v| v != "dummy").unwrap_or(true); let queue: Option> = if sound { let audio = sdl.audio()?; let desired = AudioSpecDesired { freq: Some(AUDIO_RATE), channels: Some(1), samples: Some(2048), }; let q: AudioQueue = audio.open_queue(None, &desired)?; q.resume(); Some(q) } else { None }; let (width, height) = (160 * 2 * args.scale, 240 * args.scale); let name = args .rom .file_name() .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default(); let window = video .window(&format!("a2600-play: {name}"), width, height) .build() .map_err(|e| e.to_string())?; let mut canvas = window.into_canvas().software().build().map_err(|e| e.to_string())?; let creator = canvas.texture_creator(); let mut pump = sdl.event_pump()?; let mut phase = 0.0; let mut last: Option>> = None; let mut shown: Option>> = None; let mut frames = 0u64; let mut running = true; while running { for event in pump.poll_iter() { match event { Event::Quit { .. } | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => running = false, Event::KeyDown { keycode: Some(key), .. } => { let toggle = match key { Keycode::F3 => 0x08, Keycode::F4 => 0x40, Keycode::F5 => 0x80, _ => 0, }; system.board().riot.borrow_mut().input_b ^= toggle; } _ => {} } } let keys = pump.keyboard_state(); { // SWCHB D0 Game Reset, D1 Game Select: 0 while held (DOC: Stella Programmer's Guide). let held = (if keys.is_scancode_pressed(Scancode::F2) { 0x01 } else { 0 }) | (if keys.is_scancode_pressed(Scancode::F1) { 0x02 } else { 0 }); let riot = system.board().riot.clone(); let mut riot = riot.borrow_mut(); riot.input_b = (riot.input_b | 0x03) & !held; } let mouse = pump.mouse_state(); let mouse_x = (mouse.x() as f64 / width as f64).clamp(0.0, 1.0); controls.update(&mut system, &keys, mouse_x, mouse.left()); system.run_frames(1); frames += 1; let samples = system.board_mut().tia.audio.take_samples(); if let Some(q) = &queue { if samples.len() > 1 { let (data, next) = resample(&samples, rate_in, phase); phase = next; if (q.size() as usize) < 3 * data.len() { q.queue_audio(&data)?; } } } if let Some(frame) = tv.frame() { if !frame.is_empty() { let visible = &frame[..frame.len().min(240)]; let mut rows = frame_rgb(visible, pal, 1); if args.phosphor { if let Some(prev) = &last { if prev.len() == rows.len() { for (r, p) in rows.iter_mut().zip(prev) { for (a, b) in r.iter_mut().zip(p) { *a = ((*a as u16 + *b as u16) >> 1) as u8; } } } } } let mut texture = creator .create_texture_streaming(PixelFormatEnum::RGB24, 160, rows.len() as u32) .map_err(|e| e.to_string())?; texture .update(None, &rows.concat(), 160 * 3) .map_err(|e| e.to_string())?; canvas.clear(); canvas.copy(&texture, None, Rect::new(0, 0, width, rows.len() as u32 * args.scale))?; canvas.present(); last = Some(rows.clone()); shown = Some(rows); } } if let Some(limit) = args.frames { if frames >= limit { running = false; } } } if let (Some(path), Some(rows)) = (&args.screenshot, &shown) { // The frame as shown: each colour clock 2 x scale wide, each line scale high. let s = args.scale as usize; let scaled: Vec> = rows .iter() .flat_map(|r| { let wide: Vec = r.chunks(3).flat_map(|px| px.repeat(2 * s)).collect(); std::iter::repeat_n(wide, s) }) .collect(); std::fs::write(path, rgb_png(&scaled)).map_err(|e| e.to_string())?; } Ok(()) }