// SPDX-License-Identifier: MIT //! `lynx-play`: a window for the board (SDL2), a host, not a specification (the //! reference's `lynx-play`, `play.py`, which uses pygame-ce). //! //! lynx-play CART [--machine lynx2] [--scale 3] [--rotation left|right|none] //! [--flip] [--eeprom TYPE[:ORG]] [--mute] [--frames N] //! lynx-play CART --judge [--frames N] [--flip] [--presses N] [--fault NAME] //! //! What the host does, and the board's numbers it uses (charter: hosts run a tier and do //! not define behaviour): //! //! - Picture: each finished frame (`Display::rgb`) turned for the cart's rotation field //! (lynx::picture: right = a quarter turn clockwise) and scaled. `--flip` turns it half //! a turn and swaps the direction keys, for a left-handed player of a game without its //! own flip; a game's own flip (DISPCTL bit 1, SPRSYS Lefthand) is the game's drawing //! and is shown as drawn (C11: a host that also flips doubles it). //! - Pace: the frame period the board measures (`Display::frame_period`, ticks of 16 MHz), //! not a fixed 60 Hz; the window title shows it. //! - Sound: Mikey's 32 kHz stereo samples (`Mikey::mix`), queued as they are made. //! - Input: arrows = joypad, Z = A (outer), X = B (inner), 1 / 2 = Option 1 / 2, //! Enter = Pause; Escape closes. //! - The cart's EEPROM is saved under `$XDG_DATA_HOME/lynx-python/eeprom/`. //! //! No human has looked at this window yet. It is judged headless (`--judge`, SDL's dummy //! drivers, as the reference's scripts/m8_frontend.py judges its window): for every frame //! the window's pixels must equal the board's frame turned for the cart's rotation (and //! the flip) and scaled by nearest neighbour; the host's pace must equal the period the //! board measured; with `--flip` and `--presses` the board must receive the opposite //! directions; at the end the samples queued to SDL must equal the board's samples. //! `--fault NAME` seeds one host fault (rotation-reversed, stale-frame, audio-dropped, //! fixed-60hz, keys-unflipped), which the judge must catch. //! //! Differences from the reference forced by the library: SDL2 instead of pygame-ce; the //! picture is turned in software with `lynx::picture::rotate` (pygame's //! `transform.rotate` does the same quarter turns) and scaled by SDL's copy. use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; use sdl2::audio::{AudioQueue, AudioSpecDesired}; use sdl2::event::Event; use sdl2::keyboard::Keycode; use sdl2::pixels::PixelFormatEnum; use sdl2::render::Canvas; use sdl2::video::Window; use lynx::cart::{load_path, CartDescription}; use lynx::mikey::display::{HEIGHT, WIDTH}; use lynx::mikey::SAMPLE_RATE; use lynx::picture::{rotate, scale}; use lynx::run::{boot, run_frames}; use lynx::{machine_named, Lynx}; const TICKS_PER_SECOND: f64 = 16_000_000.0; // JOYSTICK bits as Suzy stores them (DOC Appx 2, Lefthand = 1 column; Suzy swaps the // directions for a game running with Lefthand = 0): up, down, left, right, option 1, // option 2, inner (B), outer (A). SWITCHES bit 0 = pause. const UP: u8 = 0x80; const DOWN: u8 = 0x40; const LEFT: u8 = 0x20; const RIGHT: u8 = 0x10; const OPTION1: u8 = 8; const OPTION2: u8 = 4; const INNER: u8 = 2; const OUTER: u8 = 1; /// The window, the sound queue and the pace around one board. struct Host { description: CartDescription, board: Lynx, rotation: String, flip: bool, scale: u32, size: (u32, u32), canvas: Canvas, audio: Option>, sent: usize, // samples (left and right counted separately) handed to the mixer frame_interval: f64, queued: Vec, // for the headless judge: every sample queued fault: String, previous: Option>, // the stale-frame fault's frame } impl Host { #[allow(clippy::too_many_arguments)] fn new( sdl: &sdl2::Sdl, cart: &Path, machine: &str, scale: u32, rotation: Option, flip: bool, eeprom: Option, audio: bool, fault: String, ) -> Result { 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)).map_err(|e| e.to_string())?; let mut board = boot( &description, machine_named(machine).ok_or("--machine: lynx1 or lynx2")?, )?; let rotation = rotation.unwrap_or(description.rotation.clone()); let turned = rotation == "left" || rotation == "right"; let size = if turned { (HEIGHT as u32, WIDTH as u32) } else { (WIDTH as u32, HEIGHT as u32) }; let video = sdl.video()?; let window = video .window( &format!("lynx-play: {}", description.name), size.0 * scale, size.1 * scale, ) .build() .map_err(|e| e.to_string())?; let canvas = window .into_canvas() .software() .build() .map_err(|e| e.to_string())?; let audio = if audio { let subsystem = sdl.audio()?; let spec = AudioSpecDesired { freq: Some(SAMPLE_RATE as i32), channels: Some(2), samples: Some(1024), }; let queue: AudioQueue = subsystem.open_queue(None, &spec)?; queue.resume(); let tick = board.tick(); board.hw_mut().mikey.start_audio(tick); Some(queue) } else { None }; Ok(Host { description, board, rotation, flip, scale, size, canvas, audio, sent: 0, frame_interval: 0.0, queued: Vec::new(), fault, previous: None, }) } // -- one frame ------------------------------------------------------------------------ fn step(&mut self, keys: u8, pause: bool) -> Result<(), String> { let joystick = self.turn_keys(keys); let suzy = &mut self.board.hw_mut().suzy; suzy.joystick = joystick; suzy.switches = (suzy.switches & !1) | pause as u8; run_frames(&mut self.board, 1); self.present()?; if self.audio.is_some() { self.queue_audio(); } let period = self.board.hw().mikey.display.frame_period; if period != 0 { self.frame_interval = period as f64 / TICKS_PER_SECOND; // the board's measured period } if self.fault == "fixed-60hz" { self.frame_interval = 1.0 / 60.0; } Ok(()) } fn turn_keys(&self, keys: u8) -> u8 { if !self.flip || self.fault == "keys-unflipped" { return keys; } let mut swapped = keys & 0x0F; swapped |= if keys & DOWN != 0 { UP } else { 0 }; swapped |= if keys & UP != 0 { DOWN } else { 0 }; swapped |= if keys & RIGHT != 0 { LEFT } else { 0 }; swapped |= if keys & LEFT != 0 { RIGHT } else { 0 }; swapped } /// The board's last frame turned for the cart (and the flip): (rgb, width, height). fn frame_picture(&mut self) -> (Vec, usize, usize) { let mut rgb = self.board.hw().mikey.display.rgb(); if self.fault == "stale-frame" { let current = rgb.clone(); if let Some(previous) = self.previous.take() { rgb = previous; } self.previous = Some(current); } let rotation = if self.fault == "rotation-reversed" { match self.rotation.as_str() { "left" => "right", "right" => "left", other => other, } .to_string() } else { self.rotation.clone() }; let (mut turned, mut w, mut h) = rotate(&rgb, &rotation, WIDTH, HEIGHT); if self.flip { (turned, w, h) = rotate(&turned, "right", w, h); (turned, w, h) = rotate(&turned, "right", w, h); } (turned, w, h) } fn present(&mut self) -> Result<(), String> { let (picture, w, h) = self.frame_picture(); let creator = self.canvas.texture_creator(); let mut texture = creator .create_texture_streaming(PixelFormatEnum::RGB24, w as u32, h as u32) .map_err(|e| e.to_string())?; texture .update(None, &picture, w * 3) .map_err(|e| e.to_string())?; self.canvas.copy(&texture, None, None)?; self.canvas.present(); Ok(()) } fn queue_audio(&mut self) { let Some(samples) = self.board.hw().mikey.samples.as_ref() else { return; }; let new = &samples[self.sent..]; if new.is_empty() { return; } let new = new.to_vec(); self.sent = samples.len(); let frame_count = self.board.hw().mikey.display.frames; if self.fault == "audio-dropped" && frame_count % 60 == 1 { return; // the first buffer of each second never queued } self.queued.extend_from_slice(&new); if let Some(queue) = &self.audio { let _ = queue.queue_audio(&new); } } // -- the loop --------------------------------------------------------------------------- fn run(&mut self, sdl: &sdl2::Sdl, frames: u64) -> Result<(), String> { let mut events = sdl.event_pump()?; let mut keys: u8 = 0; let mut pause = false; let mut count = 0; let mut due = Instant::now(); while frames == 0 || count < frames { for event in events.poll_iter() { match event { Event::Quit { .. } | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => return Ok(()), Event::KeyDown { keycode: Some(k), .. } | Event::KeyUp { keycode: Some(k), .. } => { let down = matches!(event, Event::KeyDown { .. }); if k == Keycode::Return { pause = down; } else if let Some(bit) = keymap(k) { keys = if down { keys | bit } else { keys & !bit }; } } _ => {} } } self.step(keys, pause)?; count += 1; if self.frame_interval != 0.0 { let title = format!( "lynx-play: {} ({:.2} Hz)", self.description.name, 1.0 / self.frame_interval ); let _ = self.canvas.window_mut().set_title(&title); } due += Duration::from_secs_f64(self.frame_interval); let now = Instant::now(); if due > now { std::thread::sleep(due - now); } else { due = now; // behind real time: do not try to catch up } } Ok(()) } // -- the headless judge --------------------------------------------------------------- fn judge(&mut self, frames: u64, presses: u64) -> Result { let (mut good, mut bad) = (0, 0); let (mut pace_ok, mut keys_ok) = (true, true); let fault = std::mem::take(&mut self.fault); for frame in 0..frames { let keys = if presses != 0 && frame % presses == 0 { UP | RIGHT } else { 0 }; self.fault = fault.clone(); self.step(keys, false)?; self.fault.clear(); if self.flip && keys != 0 { // A flipped host hands the board the opposite directions. keys_ok &= self.board.hw().suzy.joystick == DOWN | LEFT; } // The reference picture: the board's frame turned and scaled (no fault). let saved = (self.previous.clone(), self.rotation.clone()); let (turned, w, h) = self.frame_picture(); (self.previous, self.rotation) = saved; let want = scale(&turned, w, h, self.scale as usize); let got = self .canvas .read_pixels(None, PixelFormatEnum::RGB24) .map_err(|e| e.to_string())?; if got == want { good += 1; } else { bad += 1; } let period = self.board.hw().mikey.display.frame_period; if period != 0 && (self.frame_interval * TICKS_PER_SECOND - period as f64).abs() > 1e-3 { pace_ok = false; } } let samples = self.board.hw().mikey.samples.clone().unwrap_or_default(); let audio_ok = self.audio.is_none() || self.queued == samples; let period = self.board.hw().mikey.display.frame_period; let hz = if period != 0 { TICKS_PER_SECOND / period as f64 } else { 0.0 }; let ok = bad == 0 && pace_ok && keys_ok && audio_ok; println!( "{}: window frames {good}/{} identical, pace {}, keys {}, sound {} ({} sample pairs, \ non-zero {}, {hz:.2} Hz, rotation {}){}", self.description.name, good + bad, if pace_ok { "ok" } else { "WRONG" }, if keys_ok { "ok" } else { "WRONG" }, if audio_ok { "ok" } else { "WRONG" }, samples.len() / 2, samples.iter().filter(|s| **s != 0).count(), self.rotation, if fault.is_empty() { String::new() } else { format!(" [fault {fault}: {}]", if ok { "MISSED" } else { "caught" }) } ); Ok(ok) } } fn keymap(k: Keycode) -> Option { Some(match k { Keycode::Up => UP, Keycode::Down => DOWN, Keycode::Left => LEFT, Keycode::Right => RIGHT, Keycode::Num1 => OPTION1, Keycode::Num2 => OPTION2, Keycode::X => INNER, Keycode::Z => OUTER, _ => return None, }) } fn main() { let mut cart: Option = None; let mut machine = "lynx2".to_string(); let mut scale_factor: u32 = 3; let mut rotation: Option = None; let mut flip = false; let mut eeprom: Option = None; let mut mute = false; let mut frames: u64 = 0; let mut judge = false; let mut presses: u64 = 0; let mut fault = String::new(); let mut args = std::env::args().skip(1); while let Some(a) = args.next() { match a.as_str() { "--machine" => machine = args.next().unwrap(), "--scale" => scale_factor = args.next().unwrap().parse().unwrap(), "--rotation" => rotation = Some(args.next().unwrap()), "--flip" => flip = true, "--eeprom" => eeprom = Some(args.next().unwrap()), "--mute" => mute = true, "--frames" => frames = args.next().unwrap().parse().unwrap(), "--judge" => judge = true, "--presses" => presses = args.next().unwrap().parse().unwrap(), "--fault" => fault = args.next().unwrap(), _ if cart.is_none() => cart = Some(a.into()), _ => { eprintln!("unknown argument {a}"); std::process::exit(2); } } } let Some(cart) = cart else { eprintln!("lynx-play CART [--machine lynx2] [--scale 3] [--rotation left|right|none] [--flip] [--eeprom TYPE[:ORG]] [--mute] [--frames N]"); std::process::exit(2); }; if judge { std::env::set_var("SDL_VIDEODRIVER", "dummy"); std::env::set_var("SDL_AUDIODRIVER", "dummy"); if frames == 0 { frames = 600; } scale_factor = 2; } let result = (|| -> Result { let sdl = sdl2::init()?; let mut host = Host::new( &sdl, &cart, &machine, scale_factor, rotation, flip, eeprom, !mute, if judge { fault } else { String::new() }, )?; if judge { return host.judge(frames, presses); } let _ = host.size; host.run(&sdl, frames)?; Ok(true) })(); match result { Ok(true) => {} Ok(false) => std::process::exit(1), Err(e) => { eprintln!("error: {e}"); std::process::exit(1); } } }