// SPDX-License-Identifier: MIT //! A desktop window: play a cartridge with picture, sound, keyboard and a game controller. //! //! a5200-play "Pac-Man (USA).zip" //! a5200-play game.a52 --machine a5200_2port --scale 3 //! //! A host (charter: it runs the tier, it does not define behaviour). The reference has no window //! (its pygame-ce frontend is unbuilt), so the controls follow gameboy-play's conventions mapped //! onto the 5200 controller. Frames run as `Console::run_frames(1)`, the pads set before each, //! as the lockstep trace drives them. Picture: the board's colour-register values through the //! reference's labelled palette (`media::ntsc_palette`, a frontend choice), each line's 456 //! half-clock pixels scaled to a 4:3-ish window. Sound: `media::AudioTap` at 44.1 kHz into an //! SDL queue, which sets the pace (without sound, a timer at the board's 59.92 frames a second). //! The save state is `NAME.a5200-state` beside the image (F5 writes it, F7 reads it back). //! //! Testing without a display: `SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy`, `--frames N` to //! quit after N frames, `--script FILE` to feed key events through SDL's own queue at given //! frames (lines `FRAME down|up SCANCODE-NAME`, e.g. `400 down Return`), `--out PNG` to write //! the last picture and `--frame-crc` to print the CRC-32 of the frame buffer (to compare with //! `a5200-trace`'s `pic=`). use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use std::time::{Duration, Instant}; use a5200::board::{FRAME_LINES, FRAME_WIDTH}; use a5200::cartridge::{load_cartridge, Source}; use a5200::media::{ntsc_palette, png_bytes, AudioTap}; use a5200::{machine_by_name, state, Console}; use sdl2::audio::{AudioQueue, AudioSpecDesired}; use sdl2::controller::{Axis, Button, GameController}; use sdl2::event::Event; use sdl2::keyboard::Scancode; use sdl2::pixels::PixelFormatEnum; const SAMPLE_RATE: u32 = 44_100; /// Frames of sound kept queued ahead of the speaker. const BUFFER_FRAMES: f64 = 3.0; /// Stick counts: the reference's labelled centre (C10) and a full deflection either side /// ([BUCH]'s range 1-228; a host choice). const CENTRE: f64 = 114.0; const SWING: f64 = 113.0; const HELP: &str = "\ Arrows / W A S D stick Z or J lower button X or K upper button Enter Start Space Pause F3 Reset (keypad) 0-9 keypad, - or KP* *, = or KP/ # F5 save state F7 load state P pause the window Tab (hold) fast forward (no sound) F11 fullscreen F12 screenshot (PNG) Esc quit A game controller drives port 1: left stick or d-pad the stick, bottom button lower, right button upper, Start Start, Back Pause."; /// (keypad key, keyboard keys) const KEYPAD: [(&str, &[Scancode]); 15] = [ ("start", &[Scancode::Return, Scancode::KpEnter]), ("pause", &[Scancode::Space]), ("reset", &[Scancode::F3]), ("0", &[Scancode::Num0, Scancode::Kp0]), ("1", &[Scancode::Num1, Scancode::Kp1]), ("2", &[Scancode::Num2, Scancode::Kp2]), ("3", &[Scancode::Num3, Scancode::Kp3]), ("4", &[Scancode::Num4, Scancode::Kp4]), ("5", &[Scancode::Num5, Scancode::Kp5]), ("6", &[Scancode::Num6, Scancode::Kp6]), ("7", &[Scancode::Num7, Scancode::Kp7]), ("8", &[Scancode::Num8, Scancode::Kp8]), ("9", &[Scancode::Num9, Scancode::Kp9]), ("*", &[Scancode::Minus, Scancode::KpMultiply]), ("#", &[Scancode::Equals, Scancode::KpDivide]), ]; struct Args { rom: PathBuf, machine: String, mapping: Option, scale: u32, frames: Option, script: Option, out: Option, frame_crc: bool, } fn parse_args() -> Args { let usage = format!( "usage: a5200-play ROM [--machine a5200|a5200_2port] [--mapping M] [--scale N]\n\ \x20 [--frames N] [--script FILE] [--out PNG] [--frame-crc]\n\n{HELP}" ); let argv: Vec = std::env::args().skip(1).collect(); let mut args = Args { rom: PathBuf::new(), machine: "a5200".into(), mapping: None, scale: 2, frames: None, script: None, out: None, frame_crc: false, }; let mut rom = None; let mut i = 0; while i < argv.len() { let a = argv[i].as_str(); let mut value = || { i += 1; argv.get(i).cloned().unwrap_or_else(|| { eprintln!("{usage}"); std::process::exit(2) }) }; match a { "--machine" => args.machine = value(), "--mapping" => args.mapping = Some(value()), "--scale" => args.scale = value().parse().unwrap_or(2).max(1), "--frames" => args.frames = value().parse().ok(), "--script" => args.script = Some(value().into()), "--out" => args.out = Some(value().into()), "--frame-crc" => args.frame_crc = true, "-h" | "--help" => { println!("{usage}"); std::process::exit(0) } _ if a.starts_with("--") => { eprintln!("{usage}"); std::process::exit(2) } _ => rom = Some(PathBuf::from(a)), } i += 1; } args.rom = rom.unwrap_or_else(|| { eprintln!("{usage}"); std::process::exit(2) }); args } /// `--script`: frame -> key events (down?, scancode). fn read_script(path: &PathBuf) -> HashMap> { let mut out: HashMap> = HashMap::new(); let text = std::fs::read_to_string(path).unwrap_or_else(|e| { eprintln!("{}: {e}", path.display()); std::process::exit(2) }); for line in text.lines() { let words: Vec<&str> = line .split('#') .next() .unwrap_or("") .split_whitespace() .collect(); if words.len() != 3 { continue; } let frame: u64 = words[0].parse().expect("FRAME"); let code = Scancode::from_name(words[2]).unwrap_or_else(|| panic!("no scancode {}", words[2])); out.entry(frame) .or_default() .push((words[1] == "down", code)); } out } fn main() { let args = parse_args(); let Some(machine) = machine_by_name(&args.machine) else { eprintln!("--machine: a5200 or a5200_2port"); std::process::exit(2) }; let cart = load_cartridge(Source::Path(&args.rom), args.mapping.as_deref(), None) .unwrap_or_else(|e| { eprintln!("{e}"); std::process::exit(1) }); let mut console = Console::new(cart, machine, None, None).unwrap_or_else(|e| { eprintln!("{e}"); std::process::exit(1) }); console.board_mut().audio = Some(AudioTap::new(machine.cycle_hz(), SAMPLE_RATE, 8)); let state_path = args.rom.with_extension("a5200-state"); let script = args.script.as_ref().map(read_script).unwrap_or_default(); let sdl = sdl2::init().expect("SDL"); let video = sdl.video().expect("SDL video"); let width = 456 / 2 * args.scale * 2; // two half-clock pixels per colour clock let height = (FRAME_LINES as u32 - 22) * args.scale * 2; let window = video .window( &format!("a5200-play: {}", console.cart.title), width, height, ) .position_centered() .resizable() .build() .expect("a window"); let mut canvas = window.into_canvas().build().expect("a canvas"); let creator = canvas.texture_creator(); let mut texture = creator .create_texture_streaming( PixelFormatEnum::RGB24, FRAME_WIDTH as u32, FRAME_LINES as u32, ) .expect("a texture"); let audio: Option> = sdl.audio().ok().and_then(|a| { let spec = AudioSpecDesired { freq: Some(SAMPLE_RATE as i32), channels: Some(1), samples: Some(1024), }; let queue = a.open_queue::(None, &spec).ok()?; queue.resume(); Some(queue) }); let controllers = sdl.game_controller().ok(); let mut pad: Option = None; let event_queue = sdl.event().expect("SDL events"); let mut pump = sdl.event_pump().expect("SDL event pump"); let palette = ntsc_palette(); let frame_time = Duration::from_secs_f64(1.0 / machine.frame_hz()); let mut next = Instant::now(); let mut held: HashSet = HashSet::new(); let mut paused = false; let mut frame: u64 = 0; 'run: loop { frame += 1; if let Some(events) = script.get(&frame) { for &(down, code) in events { let event = if down { Event::KeyDown { timestamp: 0, window_id: 0, keycode: None, scancode: Some(code), keymod: sdl2::keyboard::Mod::NOMOD, repeat: false, } } else { Event::KeyUp { timestamp: 0, window_id: 0, keycode: None, scancode: Some(code), keymod: sdl2::keyboard::Mod::NOMOD, repeat: false, } }; event_queue.push_event(event).expect("an event"); } } for event in pump.poll_iter() { match event { Event::Quit { .. } => break 'run, Event::KeyDown { scancode: Some(code), repeat: false, .. } => { held.insert(code); match code { Scancode::Escape => break 'run, Scancode::P => paused = !paused, Scancode::F5 => match state::save(&console, Some(&state_path)) { Ok(path) => eprintln!("saved {}", path.display()), Err(e) => eprintln!("save failed: {e}"), }, Scancode::F7 => match state::load(&mut console, Some(&state_path)) { Ok(()) => eprintln!("loaded {}", state_path.display()), Err(e) => eprintln!("load failed: {e}"), }, Scancode::F11 => { use sdl2::video::FullscreenType; let window = canvas.window_mut(); let next = if window.fullscreen_state() == FullscreenType::Off { FullscreenType::Desktop } else { FullscreenType::Off }; let _ = window.set_fullscreen(next); } Scancode::F12 => { let path = args.rom.with_extension(format!("{frame}.png")); let png = png_bytes( &console.board().frame, FRAME_WIDTH, FRAME_LINES, Some(&palette), ); if std::fs::write(&path, png).is_ok() { eprintln!("wrote {}", path.display()); } } _ => {} } } Event::KeyUp { scancode: Some(code), .. } => { held.remove(&code); } Event::ControllerDeviceAdded { which, .. } if pad.is_none() => { pad = controllers.as_ref().and_then(|c| c.open(which).ok()); } _ => {} } } if paused { std::thread::sleep(frame_time); frame -= 1; continue; } // Port 1 from the keyboard and the first game controller. { let key = |codes: &[Scancode]| codes.iter().any(|c| held.contains(c)); let button = |b: Button| pad.as_ref().is_some_and(|p| p.button(b)); let mut x = 0.0f64; let mut y = 0.0f64; if key(&[Scancode::Left, Scancode::A]) || button(Button::DPadLeft) { x -= 1.0; } if key(&[Scancode::Right, Scancode::D]) || button(Button::DPadRight) { x += 1.0; } if key(&[Scancode::Up, Scancode::W]) || button(Button::DPadUp) { y -= 1.0; } if key(&[Scancode::Down, Scancode::S]) || button(Button::DPadDown) { y += 1.0; } if let Some(p) = pad.as_ref() { let ax = p.axis(Axis::LeftX) as f64 / 32767.0; let ay = p.axis(Axis::LeftY) as f64 / 32767.0; if ax.abs() > 0.15 { x = ax.clamp(-1.0, 1.0); } if ay.abs() > 0.15 { y = ay.clamp(-1.0, 1.0); } } let mut pads = console.controllers.pads.borrow_mut(); let p1 = &mut pads[0]; p1.x = CENTRE + x * SWING; p1.y = CENTRE + y * SWING; p1.trigger = key(&[Scancode::Z, Scancode::J]) || button(Button::A); p1.top = key(&[Scancode::X, Scancode::K]) || button(Button::B); p1.keys.clear(); for (name, codes) in KEYPAD { if key(codes) || (name == "start" && button(Button::Start)) || (name == "pause" && button(Button::Back)) { p1.keys.insert(name.to_string()); } } } console.run_frames(1); let samples = std::mem::take(&mut console.board_mut().audio.as_mut().unwrap().samples); let fast = held.contains(&Scancode::Tab); // the picture let board = console.board(); texture .with_lock(None, |buffer: &mut [u8], pitch: usize| { for y in 0..FRAME_LINES { for x in 0..FRAME_WIDTH { let rgb = palette[board.frame[y * FRAME_WIDTH + x] as usize]; let at = y * pitch + 3 * x; buffer[at..at + 3].copy_from_slice(&rgb); } } }) .expect("the texture"); canvas.clear(); let source = sdl2::rect::Rect::new(0, 11, FRAME_WIDTH as u32, FRAME_LINES as u32 - 22); let _ = canvas.copy(&texture, Some(source), None); canvas.present(); if args.frames.is_some_and(|n| frame >= n) { break; } // the pace: the sound queue, else the clock match audio.as_ref() { Some(queue) if !fast => { let words: Vec = samples .chunks_exact(2) .map(|b| i16::from_le_bytes([b[0], b[1]])) .collect(); let _ = queue.queue_audio(&words); let ahead = BUFFER_FRAMES * SAMPLE_RATE as f64 / machine.frame_hz() * 2.0; while queue.size() as f64 > ahead { std::thread::sleep(Duration::from_millis(1)); } } _ if !fast => { next += frame_time; let now = Instant::now(); if next > now { std::thread::sleep(next - now); } else { next = now; } } _ => {} } } if let Some(out) = &args.out { let png = png_bytes( &console.board().frame, FRAME_WIDTH, FRAME_LINES, Some(&palette), ); std::fs::write(out, png).expect("the PNG"); println!("wrote {}", out.display()); } if args.frame_crc { println!( "frame {} pic={:08x}", console.frames(), crc32fast::hash(&console.board().frame) ); } }