//! A desktop window: play a cartridge with picture, sound, keyboard and game controllers //! (gameboy-python's `frontend.py`, on SDL2 instead of pygame; the controls are play-gb's). //! //! gameboy-play "Tetris (World) (Rev 1).zip" //! gameboy-play game.gbc --machine cgb --scale 5 //! gameboy-play game.gb --boot skip --palette green //! //! Machine: a Game Boy Color for a cartridge whose header has $0143 bit 7 set, else the DMG; //! `--machine` takes any key of `machines.rs`. It boots from your boot ROM when one is found //! (`boot::find_boot_rom`), else from the skip-boot state. //! //! Picture: the DMG's four shades through `--palette`; a CGB's RGB555 words through SameBoy's //! "modern balanced" screen model (play-gb's), or widened as they are with `--raw-colours`. //! Sound: the APU's stereo at the device's rate; the queue sets the pace (without sound, a //! timer at 59.73 frames a second does). Frames run by board time, 70224 T each, as play-gb's. //! //! Files, all beside the image: battery RAM in `NAME.sav`, read at power-on and written on //! quit (raw RAM; an MBC3's clock follows as the 48-byte trailer BGB, SameBoy and mGBA share); //! the save state in `NAME.state` (F5 writes it, F7 reads it back). //! //! Testing without a display: `SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy`, `--frames N` to //! quit after N ticks, `--script FILE` to feed key and controller events through SDL's own //! queue at given ticks (a virtual controller is attached for `pad` lines), and `--out PNG` to //! write the last picture. use std::collections::{HashSet, VecDeque}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; use gameboy_rust::boot::{find_boot_rom, read_image}; use gameboy_rust::machines::MACHINES; use gameboy_rust::{load_cartridge, machine, Clock, GameBoy}; use sdl2::audio::{AudioQueue, AudioSpecDesired}; use sdl2::controller::{Axis, Button, GameController}; use sdl2::event::{Event, WindowEvent}; use sdl2::keyboard::{Mod, Scancode}; use sdl2::pixels::PixelFormatEnum; /// T-cycles in a frame (154 lines of 456 dots) and the clock. const FRAME_T: u64 = 70224; const CLOCK_HZ: f64 = 4_194_304.0; /// LCD frames a second: 59.73. const RATE: f64 = CLOCK_HZ / FRAME_T as f64; const WIDTH: u32 = 160; const HEIGHT: u32 = 144; const SAMPLE_RATE: i32 = 48_000; /// Frames of sound kept queued ahead of the speaker. const BUFFER_FRAMES: f64 = 3.0; /// Rewind keeps a snapshot every this many frames, so holding it goes back this many times /// faster than the game runs (play-gb's numbers)... const REWIND_EVERY: u32 = 4; /// ...about a minute of them... const REWIND_KEEP: usize = 900; /// ...unless they take more memory than this. const REWIND_BUDGET: usize = 48 << 20; const HELP: &str = "\ Arrows / W A S D D-pad Z or J B X or K A Shift Select Enter Start F5 save state F7 load state P / Pause pause Backspace (hold) rewind Tab (hold) fast forward (no sound) F11 fullscreen F12 screenshot (PNG) Esc quit Controllers by position: bottom B, right A, Back Select, Start, d-pad or left stick; left trigger (hold) rewinds."; /// (button, keys) const KEYS: [(&str, &[Scancode]); 8] = [ ("up", &[Scancode::Up, Scancode::W]), ("down", &[Scancode::Down, Scancode::S]), ("left", &[Scancode::Left, Scancode::A]), ("right", &[Scancode::Right, Scancode::D]), ("b", &[Scancode::Z, Scancode::J]), ("a", &[Scancode::X, Scancode::K]), ("select", &[Scancode::LShift, Scancode::RShift]), ("start", &[Scancode::Return, Scancode::KpEnter]), ]; /// (button, controller buttons), by position: the pad's bottom face button is B, its right A. const PAD_BUTTONS: [(&str, Button); 8] = [ ("up", Button::DPadUp), ("down", Button::DPadDown), ("left", Button::DPadLeft), ("right", Button::DPadRight), ("b", Button::A), ("a", Button::B), ("select", Button::Back), ("start", Button::Start), ]; /// The DMG's four shades, lightest first, as 0xRRGGBB. `grey` is the reference's neutral ramp; /// `green` a by-eye fit of the DMG's reflective LCD, not measured; `pocket` the grey of a Game /// Boy Pocket's screen (play-gb's "grey"). const PALETTES: [(&str, [u32; 4]); 3] = [ ("grey", [0xFFFFFF, 0xAAAAAA, 0x555555, 0x000000]), ("green", [0xC4CFA1, 0x8B956D, 0x4D533C, 0x1F1F1F]), ("pocket", [0xE8E8E8, 0xA0A0A0, 0x585858, 0x101010]), ]; /// A Game Boy Color's screen, as SameBoy models it ("modern balanced", its default): each /// channel through the LCD's brightness curve, then green mixed with a quarter of blue at gamma /// 1.6. Copied from play-gb, which transcribed it from SameBoy's Core/display.c /// `GB_convert_rgb15` (scale_channel_with_curve and the MODERN_BALANCED branch). SameBoy: /// Copyright (c) 2015-2026 Lior Halphon, Expat licence: "Permission is hereby granted, free of /// charge, to any person obtaining a copy of this software and associated documentation files /// (the "Software"), to deal in the Software without restriction, including without limitation /// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies /// of the Software, and to permit persons to whom the Software is furnished to do so, subject /// to the following conditions: The above copyright notice and this permission notice shall be /// included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED /// "AS IS", WITHOUT WARRANTY OF ANY KIND." const CGB_CURVE: [u8; 32] = [ 0, 6, 12, 20, 28, 36, 45, 56, 66, 76, 88, 100, 113, 125, 137, 149, 161, 172, 182, 192, 202, 210, 218, 225, 232, 238, 243, 247, 250, 252, 254, 255, ]; fn cgb_screen(word: u16) -> u32 { let r = CGB_CURVE[(word & 31) as usize]; let g = CGB_CURVE[((word >> 5) & 31) as usize]; let b = CGB_CURVE[((word >> 10) & 31) as usize]; let g = if g == b { g } else { let gamma = 1.6f64; let mixed = ((g as f64 / 255.0).powf(gamma) * 3.0 + (b as f64 / 255.0).powf(gamma)) / 4.0; (mixed.powf(1.0 / gamma) * 255.0).round() as u8 }; (r as u32) << 16 | (g as u32) << 8 | b as u32 } /// RGB555 widened as the reference's image.py does, with no screen modelled. fn cgb_raw(word: u16) -> u32 { let five = |c: u16| ((c & 31) as f64 * 255.0 / 31.0).round() as u32; five(word) << 16 | five(word >> 5) << 8 | five(word >> 10) } // -- the console ---------------------------------------------------------------------------- /// The board, its cartridge's files and the rewind window; no SDL. struct Console { gb: GameBoy, rom: PathBuf, sample_rate: u32, shades: [u32; 4], /// a CGB's RGB555 words as 0xRRGGBB colours: Vec, held: HashSet<&'static str>, rewind: VecDeque>, rewind_bytes: usize, frames_since_snapshot: u32, } impl Console { /// `NAME.ext` beside the image. fn beside(&self, ext: &str) -> PathBuf { self.rom.with_extension(ext) } /// One frame by the board's clock, from where the last one ended (a STOP or LCD-off frame /// is as long as any); a rewind snapshot now and then; the sound, interleaved i16 stereo. fn run_frame(&mut self) -> Vec { let end = (self.gb.hw.t / FRAME_T + 1) * FRAME_T; while self.gb.hw.t < end { self.gb.step(); } self.frames_since_snapshot += 1; if self.frames_since_snapshot >= REWIND_EVERY { self.frames_since_snapshot = 0; self.keep_snapshot(); } self.gb.hw.apu.take_samples() } /// Hold exactly `pressed`; the board sees each change as the pad's lines. fn press(&mut self, pressed: HashSet<&'static str>) { for name in self.held.symmetric_difference(&pressed) { if self.gb.hw.sgb.is_some() { // on a Super Game Boy the buttons are the SNES pad's; the ICD2 drives the lines self.gb.sgb_set_pressed(name, pressed.contains(name), 0); } else { self.gb.set_pressed(name, pressed.contains(name)); } } self.held = pressed; } fn keep_snapshot(&mut self) { let mut encoder = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::fast()); encoder .write_all(&self.gb.save_state()) .expect("compressing to memory"); let packed = encoder.finish().expect("compressing to memory"); self.rewind_bytes += packed.len(); self.rewind.push_back(packed); while self.rewind.len() > REWIND_KEEP || (self.rewind_bytes > REWIND_BUDGET && self.rewind.len() > 1) { if let Some(old) = self.rewind.pop_front() { self.rewind_bytes -= old.len(); } } } /// One step back in place of a frame (play-gb's): the newest snapshot is loaded and /// forgotten; the oldest stays. False when nothing is kept. fn rewind_step(&mut self) -> bool { let packed = if self.rewind.len() > 1 { let packed = self.rewind.pop_back().expect("not empty"); self.rewind_bytes -= packed.len(); packed } else if let Some(only) = self.rewind.back() { only.clone() } else { return false; }; let mut raw = Vec::new(); if flate2::read::DeflateDecoder::new(packed.as_slice()) .read_to_end(&mut raw) .is_err() { return false; } if let Err(error) = self.load_state(&raw) { eprintln!("rewind: {error}"); self.rewind.clear(); self.rewind_bytes = 0; return false; } self.frames_since_snapshot = 0; true } /// A state, then the host's settings back: the APU's output rate and capture flag are in /// the saved state, and a state written at another device rate would bring its rate along. fn load_state(&mut self, data: &[u8]) -> Result<(), String> { self.gb.load_state(data)?; self.gb.hw.apu.set_sample_rate(self.sample_rate); self.gb.hw.apu.capture = true; self.gb.hw.apu.take_samples(); Ok(()) } fn save_state_file(&self) -> Result { let path = self.beside("state"); std::fs::write(&path, self.gb.save_state()) .map_err(|e| format!("{}: {e}", path.display()))?; Ok(path) } fn load_state_file(&mut self) -> Result { let path = self.beside("state"); let data = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?; self.load_state(&data)?; Ok(path) } fn load_battery(&mut self) { let path = self.beside("sav"); if let Ok(data) = std::fs::read(&path) { let t = self.gb.hw.t; if self.gb.hw.cartridge.save_ram(t).is_some() { self.gb.hw.cartridge.load_ram(&data, t); eprintln!("battery: read {}", path.display()); } } } fn save_battery(&mut self) { let t = self.gb.hw.t; if let Some(data) = self.gb.hw.cartridge.save_ram(t) { let path = self.beside("sav"); match std::fs::write(&path, data) { Ok(()) => eprintln!("battery: wrote {}", path.display()), Err(error) => eprintln!("battery: {}: {error}", path.display()), } } } /// The picture's size: the LCD's 160 x 144, or a Super Game Boy's 256 x 224 (its border /// with the LCD at (48, 40)). fn picture_size(&self) -> (u32, u32) { if self.gb.hw.sgb.is_some() { (256, 224) } else { (WIDTH, HEIGHT) } } /// The picture as 0xRRGGBB words, `picture_size` of them. fn paint(&mut self, out: &mut Vec) { out.clear(); if self.gb.hw.sgb.is_some() { // the SNES picture, BGR555 words, each channel widened as snes-python widens it // (sgb_render first takes any border-fade steps due at the board's time) let widen = |c: u16| ((c & 31) << 3 | (c & 31) >> 2) as u32; out.extend( self.gb .sgb_render() .iter() .map(|&w| widen(w) << 16 | widen(w >> 5) << 8 | widen(w >> 10)), ); return; } let frame = &self.gb.hw.ppu.frame; if self.gb.hw.cgb { out.extend(frame.iter().map(|&w| self.colours[(w & 0x7FFF) as usize])); } else { out.extend(frame.iter().map(|&s| self.shades[(s & 3) as usize])); } } } // -- PNG ------------------------------------------------------------------------------------ fn chunk(out: &mut Vec, kind: &[u8; 4], data: &[u8]) { out.extend((data.len() as u32).to_be_bytes()); let mut crc = crc32fast::Hasher::new(); crc.update(kind); crc.update(data); out.extend(kind); out.extend(data); out.extend(crc.finalize().to_be_bytes()); } /// 0xRRGGBB words as an RGB PNG. fn png(words: &[u32], width: u32, height: u32) -> Vec { let mut raw = Vec::with_capacity(words.len() * 3 + height as usize); for row in words.chunks(width as usize) { raw.push(0u8); for &w in row { raw.extend([(w >> 16) as u8, (w >> 8) as u8, w as u8]); } } let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); z.write_all(&raw).expect("compressing to memory"); let mut out = b"\x89PNG\r\n\x1a\n".to_vec(); let mut ihdr = Vec::new(); ihdr.extend(width.to_be_bytes()); ihdr.extend(height.to_be_bytes()); ihdr.extend([8, 2, 0, 0, 0]); chunk(&mut out, b"IHDR", &ihdr); chunk( &mut out, b"IDAT", &z.finish().expect("compressing to memory"), ); chunk(&mut out, b"IEND", &[]); out } // -- the test script ------------------------------------------------------------------------ /// One line of `--script`: `TICK key down|up SCANCODE NAME`, `TICK pad down|up BUTTON`, /// `TICK pad axis AXIS VALUE` (SDL's mapping names: a, b, back, start, dpup, lefttrigger, ...) /// or `TICK quit`. Keys go through SDL's event queue; pad lines move a virtual controller. enum Action { Key(Scancode, bool), PadButton(Button, bool), PadAxis(Axis, i16), Quit, } fn parse_script(text: &str) -> Result, String> { let mut out = Vec::new(); for (n, line) in text.lines().enumerate() { let words: Vec<&str> = line .split('#') .next() .unwrap_or("") .split_whitespace() .collect(); if words.is_empty() { continue; } let bad = || format!("script line {}: {line}", n + 1); let tick: u64 = words[0].parse().map_err(|_| bad())?; let down = |w: &str| match w { "down" => Ok(true), "up" => Ok(false), _ => Err(bad()), }; let action = match words.get(1..) { Some(["quit"]) => Action::Quit, Some(["key", state, name @ ..]) if !name.is_empty() => Action::Key( Scancode::from_name(&name.join(" ")).ok_or_else(bad)?, down(state)?, ), Some(["pad", "axis", axis, value]) => Action::PadAxis( Axis::from_string(axis).ok_or_else(bad)?, value.parse().map_err(|_| bad())?, ), Some(["pad", state, button]) => { Action::PadButton(Button::from_string(button).ok_or_else(bad)?, down(state)?) } _ => return Err(bad()), }; out.push((tick, action)); } out.sort_by_key(|(tick, _)| *tick); Ok(out) } /// The raw input a controller's mapping binds `name` to: ('b', 3), ('a', 2) or ('h', hat, /// mask) packed as (kind, index, mask). fn binding(pad: &GameController, name: &str) -> Option<(char, i32, i32)> { let mapping = pad.mapping(); let target = mapping .split(',') .find_map(|item| item.strip_prefix(name)?.strip_prefix(':'))?; let target = target.trim_start_matches(['+', '-']); let kind = target.chars().next()?; let rest = &target[1..]; match kind { 'h' => { let (hat, mask) = rest.split_once('.')?; Some(('h', hat.parse().ok()?, mask.parse().ok()?)) } 'a' | 'b' => Some((kind, rest.trim_end_matches('~').parse().ok()?, 0)), _ => None, } } /// Move the virtual controller (the first one open) as `action` says. fn move_virtual_pad(pads: &[GameController], action: &Action) { let Some(pad) = pads.first() else { eprintln!("script: no controller open"); return; }; let (name, value) = match action { Action::PadButton(button, down) => (button.string(), *down as i32), Action::PadAxis(axis, value) => (axis.string(), *value as i32), _ => return, }; let Some((kind, index, mask)) = binding(pad, &name) else { eprintln!("script: the controller's mapping has no {name}"); return; }; // SAFETY: the joystick behind an open controller, alive while `pad` is unsafe { let joystick = sdl2::sys::SDL_JoystickFromInstanceID(pad.instance_id() as i32); match kind { 'b' => { sdl2::sys::SDL_JoystickSetVirtualButton(joystick, index, value as u8); } 'a' => { let raw = if matches!(action, Action::PadButton(..)) { value * 32767 } else { value }; sdl2::sys::SDL_JoystickSetVirtualAxis(joystick, index, raw as i16); } _ => { let hat = if value != 0 { mask as u8 } else { 0 }; sdl2::sys::SDL_JoystickSetVirtualHat(joystick, index, hat); } } } } // -- arguments ------------------------------------------------------------------------------ struct Args { rom: PathBuf, machine: Option, boot: String, palette: [u32; 4], raw_colours: bool, scale: u32, audio: bool, fullscreen: bool, frames: Option, script: Option, out: Option, } fn fail(message: &str) -> ! { eprintln!("gameboy-play: {message}"); std::process::exit(2); } fn usage() -> String { let machines: Vec<&str> = MACHINES.iter().map(|(k, _)| *k).collect(); let palettes: Vec<&str> = PALETTES.iter().map(|(k, _)| *k).collect(); format!( "usage: gameboy-play ROM [--machine {}] [--boot auto|skip|real|PATH]\n\ \x20 [--palette {}] [--raw-colours] [--scale N] [--no-audio] [--fullscreen]\n\ \x20 [--frames N] [--script FILE] [--out PNG]\n\n{HELP}", machines.join("|"), palettes.join("|") ) } fn parse() -> Args { let mut args = Args { rom: PathBuf::new(), machine: None, boot: "auto".into(), palette: PALETTES[0].1, raw_colours: false, scale: 4, audio: true, fullscreen: false, frames: None, script: None, out: None, }; let mut rom = None; let mut it = std::env::args().skip(1); while let Some(arg) = it.next() { let mut value = || { it.next() .unwrap_or_else(|| fail(&format!("{arg} needs a value"))) }; match arg.as_str() { "--machine" => { let key = value(); if machine(&key).is_none() { fail(&format!("no machine {key}\n{}", usage())); } args.machine = Some(key); } "--boot" => args.boot = value(), "--palette" => { let name = value(); args.palette = PALETTES .iter() .find(|(k, _)| *k == name) .unwrap_or_else(|| fail(&format!("no palette {name}\n{}", usage()))) .1; } "--raw-colours" => args.raw_colours = true, "--scale" => { args.scale = value() .parse::() .unwrap_or_else(|_| fail("--scale needs a number")) .max(1) } "--no-audio" => args.audio = false, "--fullscreen" => args.fullscreen = true, "--frames" => { args.frames = Some( value() .parse() .unwrap_or_else(|_| fail("--frames needs a number")), ) } "--script" => args.script = Some(PathBuf::from(value())), "--out" => args.out = Some(PathBuf::from(value())), "-h" | "--help" => { println!("{}", usage()); std::process::exit(0); } other if other.starts_with("--") => fail(&format!("unknown option {other}")), _ => rom = Some(PathBuf::from(arg)), } } args.rom = rom.unwrap_or_else(|| fail(&usage())); args } /// Power on: the image, its machine, its boot ROM, its battery RAM. fn power_on(args: &Args) -> Console { let data = read_image(&args.rom).unwrap_or_else(|e| fail(&format!("{}: {e}", args.rom.display()))); if data.len() < 0x150 { fail(&format!( "{}: too short for a cartridge", args.rom.display() )); } let cart = load_cartridge(&data, Clock::Wall).unwrap_or_else(|e| fail(&e)); let key = args.machine.clone().unwrap_or_else(|| { if cart.header.cgb_flag & 0x80 != 0 { "cgb".into() } else if cart.header.sgb_flag == 0x03 { "sgb".into() // a Super Game Boy for a game made for one: its border and colours } else { "dmg".into() } }); let row = machine(&key).expect("checked"); let (boot_rom, label) = match args.boot.as_str() { "skip" => (None, "skip-boot state".to_string()), "auto" => find_boot_rom(row.boot_rom, None), "real" => { let (image, label) = find_boot_rom(row.boot_rom, None); if label != "real boot ROM" { fail(&format!("no real {} boot ROM ({label})", row.boot_rom)); } (image, label) } path => { let image = read_image(Path::new(path)) .unwrap_or_else(|e| fail(&format!("boot ROM {path}: {e}"))); (Some(image), format!("boot ROM {path}")) } }; let header = &cart.header; eprintln!( "machine: {} ({key}); {:?}, {:?}; {label}", row.name, header.title, header.board ); let mut gb = GameBoy::new(cart, row, boot_rom).unwrap_or_else(|e| fail(&e)); if row.model == "sgb" || row.model == "sgb2" { // the SGB's palettes start as the window's DMG shades (the BIOS's built-in palettes are // Nintendo's data): a game that sends none keeps them let words = args.palette.map(|rgb| { let five = |shift: u32| ((rgb >> shift) & 0xFF) as u16 >> 3; five(16) | five(8) << 5 | five(0) << 10 }); gb.attach_sgb(words).unwrap_or_else(|e| fail(&e)); } gb.hw.apu.capture = true; let mut console = Console { sample_rate: gb.hw.apu.sample_rate, gb, rom: args.rom.clone(), shades: args.palette, colours: (0..0x8000u16) .map(if args.raw_colours { cgb_raw } else { cgb_screen }) .collect(), held: HashSet::new(), rewind: VecDeque::new(), rewind_bytes: 0, frames_since_snapshot: 0, }; console.load_battery(); console } // -- the window ----------------------------------------------------------------------------- fn main() { let args = parse(); let script = args.script.as_ref().map(|path| { let text = std::fs::read_to_string(path) .unwrap_or_else(|e| fail(&format!("{}: {e}", path.display()))); parse_script(&text).unwrap_or_else(|e| fail(&e)) }); let mut script: VecDeque<(u64, Action)> = script.unwrap_or_default().into(); let mut console = power_on(&args); println!("{HELP}"); let name = args .rom .file_stem() .unwrap_or_default() .to_string_lossy() .into_owned(); sdl2::hint::set("SDL_GAMECONTROLLER_USE_BUTTON_LABELS", "0"); // positions, not labels let sdl = sdl2::init().unwrap_or_else(|e| fail(&format!("SDL: {e}"))); let video = sdl .video() .unwrap_or_else(|e| fail(&format!("SDL video: {e}"))); let controllers = sdl .game_controller() .unwrap_or_else(|e| fail(&format!("SDL game controllers: {e}"))); let event_queue = sdl .event() .unwrap_or_else(|e| fail(&format!("SDL events: {e}"))); let (mut width, mut height) = console.picture_size(); let mut builder = video.window( &format!("{name} — gameboy-rust-fast"), width * args.scale, height * args.scale, ); builder.position_centered().resizable(); if args.fullscreen { builder.fullscreen_desktop(); } let window = builder .build() .unwrap_or_else(|e| fail(&format!("a window: {e}"))); let mut canvas = window .into_canvas() .present_vsync() .build() .unwrap_or_else(|e| fail(&format!("a canvas: {e}"))); let _ = canvas.set_logical_size(width, height); // whole picture, kept in proportion let creator = canvas.texture_creator(); let mut texture = creator .create_texture_streaming(PixelFormatEnum::ARGB8888, width, height) .expect("a texture"); let audio: Option> = if args.audio { sdl.audio().ok().and_then(|subsystem| { let spec = AudioSpecDesired { freq: Some(SAMPLE_RATE), channels: Some(2), samples: Some(512), }; match subsystem.open_queue::(None, &spec) { Ok(queue) => { queue.resume(); Some(queue) } Err(error) => { eprintln!("no sound: {error}"); None } } }) } else { None }; if let Some(queue) = &audio { console.sample_rate = queue.spec().freq as u32; console.gb.hw.apu.set_sample_rate(console.sample_rate); eprintln!("sound: {} Hz stereo", console.sample_rate); } let target = (BUFFER_FRAMES * console.sample_rate as f64 / RATE) as u32 * 4; // bytes // a virtual controller for the script's pad lines if script .iter() .any(|(_, a)| matches!(a, Action::PadButton(..) | Action::PadAxis(..))) { // SAFETY: plain SDL calls after the joystick subsystem is up let index = unsafe { sdl2::sys::SDL_JoystickAttachVirtual( sdl2::sys::SDL_JoystickType::SDL_JOYSTICK_TYPE_GAMECONTROLLER, 6, 15, 1, ) }; if index < 0 { eprintln!("script: no virtual controller: {}", sdl2::get_error()); } } let mut events = sdl .event_pump() .unwrap_or_else(|e| fail(&format!("events: {e}"))); let mut pads: Vec = Vec::new(); let mut keys: HashSet = HashSet::new(); let (mut paused, mut fast, mut rewinding_key) = (false, false, false); let mut was_rewinding = false; let mut notice: Option<(String, Instant)> = None; let mut words: Vec = Vec::new(); let mut tick = 0u64; let (mut frames, mut since) = (0u32, Instant::now()); let mut next_frame = Instant::now(); let say = |text: String, notice: &mut Option<(String, Instant)>| { eprintln!("{text}"); *notice = Some((text, Instant::now())); }; 'running: loop { // -- the script's events for this tick, into SDL's own queue while script.front().is_some_and(|(at, _)| *at <= tick) { let (_, action) = script.pop_front().expect("not empty"); match action { Action::Quit => break 'running, Action::Key(scancode, down) => { let event = if down { Event::KeyDown { timestamp: 0, window_id: canvas.window().id(), keycode: None, scancode: Some(scancode), keymod: Mod::NOMOD, repeat: false, } } else { Event::KeyUp { timestamp: 0, window_id: canvas.window().id(), keycode: None, scancode: Some(scancode), keymod: Mod::NOMOD, repeat: false, } }; if let Err(error) = event_queue.push_event(event) { eprintln!("script: {error}"); } } pad => move_virtual_pad(&pads, &pad), } } for event in events.poll_iter() { match event { Event::Quit { .. } => break 'running, Event::ControllerDeviceAdded { which, .. } => { if let Ok(pad) = controllers.open(which) { say(format!("controller: {}", pad.name()), &mut notice); pads.push(pad); } } Event::ControllerDeviceRemoved { which, .. } => { pads.retain(|p| p.instance_id() != which) } Event::Window { win_event: WindowEvent::FocusLost, .. } => { keys.clear(); // keys released elsewhere never come back up rewinding_key = false; fast = false; } Event::KeyDown { scancode: Some(key), repeat, .. } => { keys.insert(key); if repeat { continue; } match key { Scancode::Escape => break 'running, Scancode::P | Scancode::Pause => { paused = !paused; if let Some(queue) = &audio { queue.clear(); } let state = if paused { "paused" } else { "running" }; say(state.into(), &mut notice); } Scancode::F5 => match console.save_state_file() { Ok(path) => say(format!("saved state {}", path.display()), &mut notice), Err(error) => say(format!("state not saved: {error}"), &mut notice), }, Scancode::F7 => { match console.load_state_file() { Ok(path) => { say(format!("loaded state {}", path.display()), &mut notice) } Err(error) => { say(format!("state not loaded: {error}"), &mut notice) } } if let Some(queue) = &audio { queue.clear(); } } Scancode::Backspace => rewinding_key = true, Scancode::Tab => { fast = true; if let Some(queue) = &audio { queue.clear(); } } Scancode::F11 => { let window = canvas.window_mut(); let next = if window.fullscreen_state() == sdl2::video::FullscreenType::Off { sdl2::video::FullscreenType::Desktop } else { sdl2::video::FullscreenType::Off }; let _ = window.set_fullscreen(next); } Scancode::F12 => { let _ = std::fs::create_dir_all("screenshots"); let stamp = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_secs()); let path = format!("screenshots/{name}-{stamp}.png"); console.paint(&mut words); match std::fs::write(&path, png(&words, width, height)) { Ok(()) => say(format!("saved {path}"), &mut notice), Err(error) => say(format!("{path}: {error}"), &mut notice), } } _ => {} } } Event::KeyUp { scancode: Some(key), .. } => { keys.remove(&key); match key { Scancode::Backspace => rewinding_key = false, Scancode::Tab => fast = false, _ => {} } } _ => {} } } let rewinding = rewinding_key || pads .iter() .any(|pad| pad.axis(Axis::TriggerLeft) > i16::MAX / 2); // -- pace: the sound queue while the game runs with sound, else a timer let by_sound = audio.is_some() && !paused && !rewinding; let waiting = if fast { false } else if by_sound { audio.as_ref().is_some_and(|queue| queue.size() >= target) } else { Instant::now() < next_frame }; if waiting { std::thread::sleep(Duration::from_millis(1)); continue; } next_frame += Duration::from_secs_f64(1.0 / RATE); if Instant::now() > next_frame + Duration::from_millis(100) { next_frame = Instant::now(); // fell behind: do not try to catch up } // -- inputs, as the reference's _apply_inputs let mut pressed: HashSet<&'static str> = KEYS .iter() .filter(|(_, codes)| codes.iter().any(|c| keys.contains(c))) .map(|(button, _)| *button) .collect(); for pad in &pads { for (button, code) in PAD_BUTTONS { if pad.button(code) { pressed.insert(button); } } let x = pad.axis(Axis::LeftX) as f64 / 32768.0; let y = pad.axis(Axis::LeftY) as f64 / 32768.0; for (button, held) in [ ("left", x < -0.5), ("right", x > 0.5), ("up", y < -0.5), ("down", y > 0.5), ] { if held { pressed.insert(button); } } } if args.script.is_some() && pressed != console.held { let mut list: Vec<&str> = pressed.iter().copied().collect(); list.sort(); eprintln!("tick {tick}: buttons {list:?}"); } console.press(pressed); // -- a frame, a step back, or nothing (paused) if paused { } else if rewinding { if !console.rewind_step() && !was_rewinding { say("nothing to rewind yet".into(), &mut notice); } if !was_rewinding { if let Some(queue) = &audio { queue.clear(); } } frames += 1; } else { for _ in 0..if fast { 4 } else { 1 } { let samples = console.run_frame(); if let Some(queue) = &audio { if !fast { let _ = queue.queue_audio(&samples); } } frames += 1; } } if rewinding != was_rewinding { let seconds = console.rewind.len() as f64 * REWIND_EVERY as f64 / RATE; eprintln!( "tick {tick}: rewind {} ({:.1} s kept, {} KiB)", if rewinding { "held" } else { "released" }, seconds, console.rewind_bytes / 1024 ); } was_rewinding = rewinding; // -- the picture let size = console.picture_size(); if size != (width, height) { (width, height) = size; texture = creator .create_texture_streaming(PixelFormatEnum::ARGB8888, width, height) .expect("a texture"); let _ = canvas.set_logical_size(width, height); } console.paint(&mut words); texture .with_lock(None, |buffer, pitch| { for (y, row) in words.chunks(width as usize).enumerate() { for (x, &word) in row.iter().enumerate() { let at = y * pitch + 4 * x; buffer[at..at + 4].copy_from_slice(&(word | 0xFF00_0000).to_le_bytes()); } } }) .expect("the texture"); canvas.clear(); canvas.copy(&texture, None, None).expect("draw"); canvas.present(); tick += 1; let now = Instant::now(); if now - since >= Duration::from_secs(1) { let fps = frames as f64 / (now - since).as_secs_f64(); let state = if paused { " (paused)" } else if rewinding { " (rewind)" } else if fast { " (fast)" } else { "" }; let shown = match ¬ice { Some((text, at)) if now - *at < Duration::from_secs(3) => format!(" — {text}"), _ => String::new(), }; let title = format!("{name} — {fps:.1} fps{state}{shown} — gameboy-rust-fast"); let _ = canvas.window_mut().set_title(&title); frames = 0; since = now; } if args.frames.is_some_and(|limit| tick >= limit) { break; } } console.save_battery(); if let Some(path) = &args.out { console.paint(&mut words); match std::fs::write(path, png(&words, width, height)) { Ok(()) => eprintln!("picture: {} after {tick} ticks", path.display()), Err(error) => eprintln!("{}: {error}", path.display()), } } } #[cfg(test)] mod tests { use super::*; #[test] fn colours() { assert_eq!(cgb_raw(0x7FFF), 0xFFFFFF); assert_eq!(cgb_raw(0x001F), 0xFF0000); assert_eq!(cgb_screen(0x7FFF), 0xFFFFFF); assert_eq!(cgb_screen(0), 0); // green mixed with a quarter of blue: pure green comes out darker than the curve's 255 assert_eq!(cgb_screen(0x03E0) >> 16, 0); assert!((cgb_screen(0x03E0) >> 8 & 0xFF) < 255); } #[test] fn script() { let actions = parse_script( "# a comment\n20 key up Left Shift\n10 key down Return\n30 pad down start\n\ 40 pad axis lefttrigger 32000\n50 quit\n", ) .unwrap(); let ticks: Vec = actions.iter().map(|(t, _)| *t).collect(); assert_eq!(ticks, [10, 20, 30, 40, 50]); assert!(matches!(actions[0].1, Action::Key(Scancode::Return, true))); assert!(matches!(actions[1].1, Action::Key(Scancode::LShift, false))); assert!(matches!( actions[2].1, Action::PadButton(Button::Start, true) )); assert!(matches!( actions[3].1, Action::PadAxis(Axis::TriggerLeft, 32000) )); assert!(matches!(actions[4].1, Action::Quit)); assert!(parse_script("1 key sideways Return").is_err()); assert!(parse_script("1 key down NoSuchKey").is_err()); } #[test] fn png_header() { let out = png(&[0xFF0000; 4], 2, 2); assert_eq!(&out[..8], b"\x89PNG\r\n\x1a\n"); assert_eq!(&out[12..16], b"IHDR"); } }