//! The three CPUs and their scheduler, which reproduces MAME's //! (`galaga::sched`, `docs/cpu-and-timing.md`): the order in which shared-RAM //! races resolve depends on where slices fall, so the board slices as MAME //! does, in MAME's attosecond arithmetic. //! //! The frame here starts where MAME's does: at the **start of vblank** //! (measured 2026-09-11 from MAME's timestamps: the main CPU acknowledges its //! vblank IRQ about 400 T-states into every MAME frame, and the sub2 NMI //! handlers run at about 20,040 and 44,620). So T = 0 is hardware line 224: //! the level IRQs to main and sub and the 51xx input sample happen there, //! the visible area begins at T = 7,680 (hardware line 0), and the sub2 NMIs //! at hardware lines 64 and 192 fall at T = 19,968 and 44,544. The oracle's //! record for frame N is taken at the end of that frame, the next vblank //! start. //! //! What MAME does that this reproduces on purpose: the sub CPUs are held in //! reset until the main program writes 1 to misc latch bit 3 and are reset //! again when it writes 0; a Z80 starts with F = 0x40 and IX = IY = 0xffff; //! the record the oracle compares is taken at the end of a frame. use std::cell::RefCell; use std::rc::Rc; use z80_rust::Z80; use super::bus::{ Cpu, CpuBus, Event, Shared, EFFECT_CLEAR_MAIN_IRQ, EFFECT_CLEAR_SUB_IRQ, EFFECT_SUBS_HELD, EFFECT_SUBS_RELEASED, }; use super::roms::RomSet; use super::sched::{self, Sched}; pub const T_STATES_PER_LINE: u64 = 192; pub const LINES_PER_FRAME: u64 = 264; pub const T_STATES_PER_FRAME: u64 = T_STATES_PER_LINE * LINES_PER_FRAME; /// Lines of the frame timeline (0 = vblank start = hardware line 224). pub const VBLANK_LINE: u64 = 0; pub const VBLANK_LINES: u64 = 40; pub const SUB2_NMI_LINES: [u64; 2] = [VBLANK_LINES + 64, VBLANK_LINES + 192]; /// Cabinet controls, active high here, to the active-low port bits the 51xx /// samples (`docs/custom-io.md`, "Cabinet inputs"). Names are the ones /// `oracle/mame_dump.lua` accepts. pub const CONTROLS: [(&str, usize, u8); 12] = [ ("p1_right", 0, 0x02), ("p1_left", 0, 0x08), ("p2_right", 0, 0x20), ("p2_left", 0, 0x80), ("p1_fire", 1, 0x01), ("p2_fire", 1, 0x02), ("start1", 1, 0x04), ("start2", 1, 0x08), ("coin1", 1, 0x10), ("coin2", 1, 0x20), ("service", 1, 0x40), ("test", 1, 0x80), ]; pub struct Machine { pub shared: Rc>, cpus: [Z80; 3], /// Each CPU's absolute T-state clock. pub(crate) t: [u64; 3], pub frame: u64, /// Pressed-control bits per port, active high. pub(crate) controls: [u8; 2], /// The video latch as it stood at the end of this frame's vblank, when /// the starfield samples it (`screen_vblank_galaga`). pub videolatch_at_vblank_end: u8, /// MAME's scheduler state (`galaga::sched`). pub(crate) sched: Sched, /// The latch released the boards' reset line during this slice. mcu51_released: bool, } fn new_cpu(cpu: Cpu, rom: &[u8], shared: &Rc>) -> Z80 { let mut z80 = Z80::new(CpuBus::new(cpu, rom, Rc::clone(shared))); // MAME's z80 at power-on (probed 2026-09-11): AF = 0x0040, IX = IY = 0xffff. z80.f.set_byte(0x40); z80.ix = 0xffff; z80.iy = 0xffff; z80 } impl Machine { pub fn new(roms: &RomSet) -> Machine { let shared = Rc::new(RefCell::new(Shared::new())); let cpus = [ new_cpu(Cpu::Main, &roms.main, &shared), new_cpu(Cpu::Sub, &roms.sub, &shared), new_cpu(Cpu::Sub2, &roms.sub2, &shared), ]; Machine { shared, cpus, t: [0; 3], frame: 0, controls: [0; 2], videolatch_at_vblank_end: 0, sched: Sched::new(), mcu51_released: false, } } pub fn set_control(&mut self, name: &str, pressed: bool) -> Result<(), String> { let &(_, port, mask) = CONTROLS .iter() .find(|(n, _, _)| *n == name) .ok_or_else(|| format!("unknown Galaga control: {name}"))?; if pressed { self.controls[port] |= mask; } else { self.controls[port] &= !mask; } Ok(()) } /// The pressed-control bits of IN0 and IN1, active high: what a movie /// records per frame. pub fn controls(&self) -> [u8; 2] { self.controls } /// Remix: patch a CPU's program space (`CpuBus::patch`). pub fn patch_rom(&mut self, cpu: Cpu, at: u16, bytes: &[u8]) -> Result<(), String> { self.cpus[cpu as usize].bus.patch(at, bytes) } pub fn set_controls(&mut self, controls: [u8; 2]) { self.controls = controls; } /// The raw IN0 and IN1 port bytes, active low. pub fn ports(&self) -> [u8; 2] { [!self.controls[0], !self.controls[1]] } pub fn cpu(&self, cpu: Cpu) -> &Z80 { &self.cpus[cpu as usize] } pub(crate) fn cpu_mut_by_index(&mut self, index: usize) -> &mut Z80 { &mut self.cpus[index] } /// The DIP switch bytes as MAME's `DSWA` and `DSWB` ports. pub fn set_dips(&mut self, dsw_a: u8, dsw_b: u8) { let mut s = self.shared.borrow_mut(); s.dsw_a = dsw_a; s.dsw_b = dsw_b; } /// Drain the events recorded since the last call. pub fn take_events(&mut self) -> Vec { std::mem::take(&mut self.shared.borrow_mut().events) } /// Emulate one whole frame, from one vblank start to the next, on /// MAME's scheduler (`galaga::sched`): timers due now fire, then slices /// run up to the next timer, until the next vblank start, whose timer is /// left for the next frame (MAME's frame notifier, where inputs change and /// the oracle records, runs at its start). A CPU may end a frame past the /// boundary (its last instruction) or short of it by under a cycle. pub fn run_frame(&mut self) { let frame_end = u128::from(self.frame + 1) * sched::FRAME; loop { self.run_due_timers(frame_end); if self.sched.base >= frame_end { break; } self.timeslices(); } self.frame += 1; self.shared.borrow_mut().frame = self.frame; } /// The earliest timer expiry. fn next_expiry(&self) -> u128 { let s = &self.sched; let mut next = s .next_vblank_begin .min(s.next_scanline0) .min(s.next_sub2) .min(s.next_sound); if let Some(t) = s.next_vblank_end { next = next.min(t); } if let Some(t) = self.shared.borrow().n06.next_tick() { next = next.min(t); } next } /// Fire every timer due by the base time, earliest first, except the /// vblank start that ends this frame. fn run_due_timers(&mut self, frame_end: u128) { loop { let base = self.sched.base; let n06 = self.shared.borrow().n06.next_tick(); let s = &self.sched; // (expiry, kind): ties go in MAME's allocation order of the timers. let mut due: Option<(u128, u8)> = None; let mut consider = |t: u128, kind: u8| { if t <= base && due.is_none_or(|(d, _)| t < d) { due = Some((t, kind)); } }; if s.next_vblank_begin < frame_end { consider(s.next_vblank_begin, 0); } if let Some(t) = s.next_vblank_end { consider(t, 1); } consider(s.next_scanline0, 2); consider(s.next_sub2, 3); consider(s.next_sound, 4); if let Some(t) = n06 { consider(t, 5); } let Some((now, kind)) = due else { return }; match kind { 0 => { self.sched.vblank_start = now; self.sched.next_vblank_begin = self.sched.time_until_pos(224, now); self.sched.next_vblank_end = Some(now + sched::VBLANK_PERIOD); self.raise_vblank(); } 1 => { self.sched.next_vblank_end = None; self.videolatch_at_vblank_end = self.shared.borrow().videolatch; } 2 => self.sched.next_scanline0 = self.sched.time_until_pos(0, now), 3 => { self.raise_sub2_nmi(); let line = self.sched.sub2_line + 128; self.sched.sub2_line = if line >= 272 { 64 } else { line }; self.sched.next_sub2 = self.sched.time_until_pos(self.sched.sub2_line, now); } 4 => self.sched.next_sound = now + sched::SOUND_UPDATE, _ => { if self.shared.borrow_mut().n06.tick() { self.cpus[Cpu::Main as usize].request_non_maskable_interrupt(); } } } } } /// `device_scheduler::timeslice`: slices until the base reaches the next /// timer. fn timeslices(&mut self) { while self.sched.base < self.next_expiry() { let base = self.sched.base; let mut target = (base + sched::QUANTUM).min(self.next_expiry()); for (index, cpu) in [(0, Cpu::Main), (1, Cpu::Sub), (2, Cpu::Sub2)] { let local = u128::from(self.t[index]) * sched::Z80.aps; if target <= local || target - local < sched::Z80.aps { continue; } let cycles = sched::Z80.cycles_in(target - local); let running = cpu == Cpu::Main || self.shared.borrow().subs_running; // A CPU held in reset eats its cycles (MAME: suspended with // eatcycles); a running one may stop early at a sync. let ran = if running { self.run_cycles(cpu, cycles) } else { cycles }; self.t[index] += ran; let local = u128::from(self.t[index]) * sched::Z80.aps; if local < target { target = local.max(base); } } for j in 0..2 { let local = u128::from(self.sched.mcu[j]) * sched::MCU.aps; if target <= local || target - local < sched::MCU.aps { continue; } let cycles = sched::MCU.cycles_in(target - local); let from = self.sched.mcu[j]; self.sched.mcu[j] += cycles; if j == 0 { // The 51xx's O-port write syncs: its slice ends after it. let state = self.shared.borrow().n51.o_write_state(); if let Some(at) = self.sched.next_o_write(from, state) { if at < from + cycles { self.sched.mcu[0] = at + 1; } } } let local = u128::from(self.sched.mcu[j]) * sched::MCU.aps; if local < target { target = local.max(base); } } // The 51xx is reset (its cycle count restarts) when the latch // releases the boards' reset line, in the sync after this slice; // its credit-mode pattern starts in the frame it enters credit mode. if std::mem::take(&mut self.mcu51_released) { self.sched.mcu51_reset = Some(self.sched.mcu[0]); self.sched.mcu51_credit_frame = None; } if self.sched.mcu51_credit_frame.is_none() { if let (Some(reset), Some(_)) = ( self.sched.mcu51_reset, self.shared.borrow().n51.o_write_state(), ) { let rel = self.sched.mcu[0] - reset; let frame = rel / sched::MCU_FRAME; // A pattern whose first write has passed starts next frame. self.sched.mcu51_credit_frame = Some(if rel % sched::MCU_FRAME < 1582 { frame } else { frame + 1 }); } } self.sched.base = target; } } fn raise_sub2_nmi(&mut self) { let (on, running) = { let s = self.shared.borrow(); (s.sub2_nmi_on, s.subs_running) }; if on && running { self.cpus[Cpu::Sub2 as usize].request_non_maskable_interrupt(); } } fn raise_vblank(&mut self) { let ports = self.ports(); let mut s = self.shared.borrow_mut(); s.n51.sample(ports[0], ports[1]); if s.main_irq_mask { s.main_irq_line = true; } if s.sub_irq_mask { s.sub_irq_line = true; } } /// Run `cpu` for `cycles` (MAME's icount): instructions until the count /// is spent, the last may overshoot; a synchronizing write ends it after /// that instruction (`abort_timeslice`). Returns the cycles run. fn run_cycles(&mut self, cpu: Cpu, cycles: u64) -> u64 { let index = cpu as usize; let start = self.t[index]; while self.t[index] - start < cycles { // Level IRQ lines: keep the request asserted while the line is. match cpu { Cpu::Main if self.shared.borrow().main_irq_line => { self.cpus[index].request_maskable_interrupt(0xff) } Cpu::Sub if self.shared.borrow().sub_irq_line => { self.cpus[index].request_maskable_interrupt(0xff) } _ => {} } { let mut s = self.shared.borrow_mut(); s.now = self.t[index]; s.pc = self.cpus[index].pc; if cpu == Cpu::Main { s.main_t = self.t[index]; } } let pc = self.cpus[index].pc; let elapsed = match self.cpus[index].step() { Ok(t) => u64::from(t), Err(fault) => panic!("{}: {fault} at frame {}", cpu.name(), self.frame), }; self.t[index] += elapsed; if let Some(time) = &mut self.shared.borrow_mut().time_by_pc { time[index * 0x10000 + usize::from(pc)] += elapsed; } self.apply_effects(); if std::mem::take(&mut self.shared.borrow_mut().sync) { break; } } let ran = self.t[index] - start; self.t[index] = start; ran } fn apply_effects(&mut self) { let effects = { let mut s = self.shared.borrow_mut(); std::mem::take(&mut s.effects) }; if effects == 0 { return; } if effects & EFFECT_CLEAR_MAIN_IRQ != 0 { self.cpus[Cpu::Main as usize].clear_maskable_interrupt(); } if effects & EFFECT_CLEAR_SUB_IRQ != 0 { self.cpus[Cpu::Sub as usize].clear_maskable_interrupt(); } if effects & EFFECT_SUBS_RELEASED != 0 { self.mcu51_released = true; for cpu in [Cpu::Sub, Cpu::Sub2] { let z80 = &mut self.cpus[cpu as usize]; z80.clear_maskable_interrupt(); z80.clear_non_maskable_interrupt(); z80.request_reset(); let _ = z80.step(); z80.clear_reset(); z80.i = 0; z80.r = 0; } } if effects & EFFECT_SUBS_HELD != 0 { for cpu in [Cpu::Sub, Cpu::Sub2] { let z80 = &mut self.cpus[cpu as usize]; z80.clear_maskable_interrupt(); z80.clear_non_maskable_interrupt(); } } } }