//! The Galaxian board, transcribed from galemu's `board.py` and `devices.py`: //! the memory map with its mirrors, the memory-mapped inputs and device //! latches, the vblank NMI scheduler, and the event and snapshot records //! galemu serializes as its canonical run evidence. //! //! galemu's board *is* its CPU, so an event carries the program counter at //! the moment of the write. Here the CPU owns the bus and the bus cannot see //! the CPU, so [`Machine::step`] stamps the events a step produced //! afterwards: a write happens after every byte of its instruction has been //! fetched, so its PC is the pre-step PC plus the fetched length; an NMI //! acceptance pushes the interrupted PC before it jumps, so its pushes carry //! the pre-step PC. use z80_rust::core::{Bus, Fault}; use z80_rust::{CpuState, Z80}; use super::bytes::{Reader, Writer}; pub const CPU_T_STATES_PER_FRAME: u64 = 50_688; pub const VBLANK_START_T_STATES: u64 = 43_008; /// One mapped write, or the two NMI boundaries, as galemu records them. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Event { pub instruction: u64, pub t_states_before: u64, pub pc: u16, pub kind: &'static str, pub address: u16, pub value: u32, } /// galemu's `INPUT_ROUTES`: active-high controls to a port bit. pub const INPUT_ROUTES: [(&str, usize, u8); 12] = [ ("coin_1", 0, 0x01), ("coin_2", 0, 0x02), ("player_1_left", 0, 0x04), ("player_1_right", 0, 0x08), ("player_1_fire", 0, 0x10), ("service_mode", 0, 0x40), ("service_1", 0, 0x80), ("start_1", 1, 0x01), ("start_2", 1, 0x02), ("player_2_left", 1, 0x04), ("player_2_right", 1, 0x08), ("player_2_fire", 1, 0x10), ]; /// The bus: ROM, the three RAMs, inputs, latches, and the event log. pub struct Board { program_rom: Vec, pub work_ram: [u8; 0x400], pub video_ram: [u8; 0x400], pub object_ram: [u8; 0x100], /// IN0, IN1, IN2. galemu's defaults: idle controls, upright cabinet, /// 1C/1C, 7,000-point bonus, three lives. pub inputs: [u8; 3], pub events: Vec, pub trace_memory_writes: bool, pub instruction_count: u64, pub t_states: u64, pub irq_enabled: bool, pub starfield_enabled: bool, pub flip_x: bool, pub flip_y: bool, } impl Board { pub fn new(program_rom: &[u8]) -> Result { if program_rom.len() != 0x2800 { return Err(format!( "expected a 0x2800-byte program ROM image, got 0x{:x}", program_rom.len() )); } Ok(Board { program_rom: program_rom.to_vec(), work_ram: [0; 0x400], video_ram: [0; 0x400], object_ram: [0; 0x100], inputs: [0x00, 0x00, 0x04], events: Vec::new(), trace_memory_writes: true, instruction_count: 0, t_states: 0, irq_enabled: false, starfield_enabled: false, flip_x: false, flip_y: false, }) } pub fn set_input(&mut self, control: &str, pressed: bool) -> Result<(), String> { let &(_, port, mask) = INPUT_ROUTES .iter() .find(|(name, _, _)| *name == control) .ok_or_else(|| format!("unknown Galaxian control: {control}"))?; if pressed { self.inputs[port] |= mask; } else { self.inputs[port] &= !mask; } Ok(()) } /// galemu's `_record`: the PC is stamped by [`Machine::step`]. fn record(&mut self, kind: &'static str, address: u16, value: u32) { self.events.push(Event { instruction: self.instruction_count + 1, t_states_before: self.t_states, pc: 0, kind, address, value, }); } fn write_device(&mut self, addr: u16, value: u8) { let canonical = addr & 0xF807; match canonical { 0x7001 => { self.irq_enabled = value & 1 != 0; self.record("irq_enable", addr, u32::from(value)); } 0x7004 => { self.starfield_enabled = value & 1 != 0; self.record("star_enable", addr, u32::from(value)); } 0x7006 => { self.flip_x = value & 1 != 0; self.record("flip_x", addr, u32::from(value)); } 0x7007 => { self.flip_y = value & 1 != 0; self.record("flip_y", addr, u32::from(value)); } 0x6000 => self.record("start_lamp_1", addr, u32::from(value)), 0x6001 => self.record("start_lamp_2", addr, u32::from(value)), 0x6002 => self.record("coin_lockout", addr, u32::from(value)), 0x6003 => self.record("coin_counter", addr, u32::from(value)), _ => { if let Some((kind, value)) = decode_sound_write(addr, value) { self.record(kind, addr, u32::from(value)); } } } } } /// galemu's `decode_sound_write`, reduced to what the event records. pub fn decode_sound_write(address: u16, value: u8) -> Option<(&'static str, u8)> { if address & 0xF800 == 0x7800 { return Some(("sound_pitch", value)); } let canonical = address & 0xF807; let bit = value & 1; match canonical { 0x6004..=0x6007 => Some(("sound_background_resistor", bit)), 0x6800..=0x6802 => Some(("sound_tone_enable", bit)), 0x6803 => Some(("sound_hit", bit)), 0x6804 => Some(("sound_unused", bit)), 0x6805 => Some(("sound_fire", bit)), 0x6806..=0x6807 => Some(("sound_volume", bit)), _ => None, } } fn object_ram_kind(offset: u16) -> &'static str { match offset { 0x00..=0x3F => "attribute_ram", 0x40..=0x5F => "sprite_ram", 0x60..=0x7F => "bullet_ram", _ => "object_ram_unused", } } impl Bus for Board { #[inline] fn read_byte(&mut self, addr: u16) -> u8 { match addr { 0x0000..=0x27FF => self.program_rom[usize::from(addr)], 0x2800..=0x3FFF => 0xFF, 0x4000..=0x47FF => self.work_ram[usize::from(addr & 0x03FF)], 0x5000..=0x57FF => self.video_ram[usize::from(addr & 0x03FF)], 0x5800..=0x5FFF => self.object_ram[usize::from(addr & 0x00FF)], 0x6000..=0x67FF => self.inputs[0], 0x6800..=0x6FFF => self.inputs[1], 0x7000..=0x77FF => self.inputs[2], _ => 0xFF, } } #[inline] fn write_byte(&mut self, addr: u16, value: u8) { match addr { 0x4000..=0x47FF => { self.work_ram[usize::from(addr & 0x03FF)] = value; if self.trace_memory_writes { self.record("work_ram", addr, u32::from(value)); } } 0x5000..=0x57FF => { self.video_ram[usize::from(addr & 0x03FF)] = value; if self.trace_memory_writes { self.record("video_ram", addr, u32::from(value)); } } 0x5800..=0x5FFF => { let offset = addr & 0x00FF; self.object_ram[usize::from(offset)] = value; if self.trace_memory_writes { self.record(object_ram_kind(offset), addr, u32::from(value)); } } _ => self.write_device(addr, value), } } #[inline] fn read_port(&mut self, _addr: u16) -> u8 { 0xFF } #[inline] fn write_port(&mut self, _addr: u16, _value: u8) {} } /// Everything a [`Machine`] holds at a frame boundary but its ROM, its event /// log and the controls held: the CPU's own state, the three RAMs, the /// latches, the counters and the vblank scheduler. [`Machine::restore`] puts it /// back, so a run continues as it did from there (rewind's snapshot). #[derive(Clone, Debug, PartialEq, Eq)] pub struct MachineState { cpu: CpuState, work_ram: [u8; 0x400], video_ram: [u8; 0x400], object_ram: [u8; 0x100], instruction_count: u64, t_states: u64, irq_enabled: bool, starfield_enabled: bool, flip_x: bool, flip_y: bool, vblank_count: u64, interrupt_accept_count: u64, next_vblank_t_states: u64, } impl MachineState { /// The state as bytes, every field in declaration order (the CPU's in /// `CpuState`'s order), for a save state. [`MachineState::read`] gives it /// back exactly; the machine's behaviour is not touched. pub fn write(&self, w: &mut Writer) { let c = &self.cpu; for v in [c.a, c.f, c.b, c.c, c.d, c.e, c.h, c.l] { w.u8(v); } for v in [c.ix, c.iy, c.sp, c.pc, c.wz] { w.u16(v); } w.u8(c.i); w.u8(c.r); w.bool(c.iff1); w.bool(c.iff2); w.u8(c.im); for v in [c.af_alt, c.bc_alt, c.de_alt, c.hl_alt] { w.u16(v); } w.u8(c.q); w.bool(c.halted); w.u8(c.ei_delay); w.bool(c.reset_pending); w.bool(c.maskable_interrupt_vector.is_some()); w.u8(c.maskable_interrupt_vector.unwrap_or(0)); w.bool(c.non_maskable_interrupt_pending); w.bytes(&self.work_ram); w.bytes(&self.video_ram); w.bytes(&self.object_ram); w.u64(self.instruction_count); w.u64(self.t_states); w.bool(self.irq_enabled); w.bool(self.starfield_enabled); w.bool(self.flip_x); w.bool(self.flip_y); w.u64(self.vblank_count); w.u64(self.interrupt_accept_count); w.u64(self.next_vblank_t_states); } pub fn read(r: &mut Reader) -> Result { let [a, f, b, c, d, e, h, l] = r.array::<8>()?; let (ix, iy, sp, pc, wz) = (r.u16()?, r.u16()?, r.u16()?, r.u16()?, r.u16()?); let (i, rr, iff1, iff2, im) = (r.u8()?, r.u8()?, r.bool()?, r.bool()?, r.u8()?); let (af_alt, bc_alt, de_alt, hl_alt) = (r.u16()?, r.u16()?, r.u16()?, r.u16()?); let (q, halted, ei_delay, reset_pending) = (r.u8()?, r.bool()?, r.u8()?, r.bool()?); let has_vector = r.bool()?; let vector = r.u8()?; let non_maskable_interrupt_pending = r.bool()?; let cpu = CpuState { a, f, b, c, d, e, h, l, ix, iy, sp, pc, wz, i, r: rr, iff1, iff2, im, af_alt, bc_alt, de_alt, hl_alt, q, halted, ei_delay, reset_pending, maskable_interrupt_vector: has_vector.then_some(vector), non_maskable_interrupt_pending, }; Ok(MachineState { cpu, work_ram: r.array()?, video_ram: r.array()?, object_ram: r.array()?, instruction_count: r.u64()?, t_states: r.u64()?, irq_enabled: r.bool()?, starfield_enabled: r.bool()?, flip_x: r.bool()?, flip_y: r.bool()?, vblank_count: r.u64()?, interrupt_accept_count: r.u64()?, next_vblank_t_states: r.u64()?, }) } } /// The board with its CPU and the vblank scheduler: galemu's `GalaxianBoard` /// as a whole. pub struct Machine { pub cpu: Z80, pub enable_vblank: bool, pub vblank_count: u64, pub interrupt_accept_count: u64, next_vblank_t_states: u64, } impl Machine { pub fn new(program_rom: &[u8], enable_vblank: bool) -> Result { Ok(Machine { cpu: Z80::new(Board::new(program_rom)?), enable_vblank, vblank_count: 0, interrupt_accept_count: 0, next_vblank_t_states: VBLANK_START_T_STATES, }) } pub fn board(&self) -> &Board { &self.cpu.bus } pub fn board_mut(&mut self) -> &mut Board { &mut self.cpu.bus } /// The machine's state, for [`Machine::restore`]. pub fn capture(&self) -> MachineState { let b = &self.cpu.bus; MachineState { cpu: self.cpu.capture_state(), work_ram: b.work_ram, video_ram: b.video_ram, object_ram: b.object_ram, instruction_count: b.instruction_count, t_states: b.t_states, irq_enabled: b.irq_enabled, starfield_enabled: b.starfield_enabled, flip_x: b.flip_x, flip_y: b.flip_y, vblank_count: self.vblank_count, interrupt_accept_count: self.interrupt_accept_count, next_vblank_t_states: self.next_vblank_t_states, } } /// Back to a captured state. The controls held now stay held, and the /// event log is emptied (a frame boundary has none left). pub fn restore(&mut self, state: &MachineState) { self.cpu.restore_state(&state.cpu); let b = &mut self.cpu.bus; b.work_ram = state.work_ram; b.video_ram = state.video_ram; b.object_ram = state.object_ram; b.instruction_count = state.instruction_count; b.t_states = state.t_states; b.irq_enabled = state.irq_enabled; b.starfield_enabled = state.starfield_enabled; b.flip_x = state.flip_x; b.flip_y = state.flip_y; b.events.clear(); self.vblank_count = state.vblank_count; self.interrupt_accept_count = state.interrupt_accept_count; self.next_vblank_t_states = state.next_vblank_t_states; } /// One instruction or acceptance boundary, with galemu's bookkeeping. pub fn step(&mut self) -> Result { let pc_before = self.cpu.pc; let nmi_was_pending = self.cpu.non_maskable_interrupt_pending(); let first_event = self.cpu.bus.events.len(); let elapsed = self.cpu.step()?; let nmi_accepted = nmi_was_pending && !self.cpu.non_maskable_interrupt_pending(); let pc_at_write = if nmi_accepted { pc_before } else { pc_before.wrapping_add(self.cpu.last_instruction_bytes().len() as u16) }; for event in &mut self.cpu.bus.events[first_event..] { event.pc = pc_at_write; } let board = &mut self.cpu.bus; if nmi_accepted { self.interrupt_accept_count += 1; let pc = self.cpu.pc; let board = &mut self.cpu.bus; board.events.push(Event { instruction: board.instruction_count, t_states_before: board.t_states, pc, kind: "nmi_accept", address: pc, value: elapsed, }); } else { board.instruction_count += 1; } self.cpu.bus.t_states += u64::from(elapsed); if self.enable_vblank { self.advance_vblank_scheduler(); } Ok(elapsed) } fn advance_vblank_scheduler(&mut self) { while self.cpu.bus.t_states >= self.next_vblank_t_states { self.vblank_count += 1; if self.cpu.bus.irq_enabled && !self.cpu.non_maskable_interrupt_pending() { self.cpu.request_non_maskable_interrupt(); let pc = self.cpu.pc; let board = &mut self.cpu.bus; board.events.push(Event { instruction: board.instruction_count, t_states_before: board.t_states, pc, kind: "vblank_nmi_request", address: 0x7001, value: 1, }); } self.next_vblank_t_states += CPU_T_STATES_PER_FRAME; } } /// Run until the vblank scheduler has advanced one frame (`_advance_frame`). pub fn run_frame(&mut self) -> Result<(), Fault> { debug_assert!(self.enable_vblank, "run_frame needs the vblank scheduler"); let target = self.vblank_count + 1; while self.vblank_count < target { self.step()?; } Ok(()) } }