pcengine_rust/
board.rs

1//! The board: one timeline in master clocks, the page table, and the devices around the CPU
2//! (`board.py`).
3//!
4//! The CPU core (huc6280-rust) calls `read`, `write` and `idle` once per CPU cycle with a
5//! 21-bit physical address. **The board prices the cycle**: 12 master clocks at low speed, 3 at high
6//! speed (`pins.high_speed`), plus the VDC/VCE stretch and any `hold`, all inside the callback; it
7//! never adds `step()`'s return on top (the reference's docs/handoff-brief.md, the bus contract).
8//!
9//! Where inside a cycle a device sees the access is U21 (provisional): the base cycle elapses, then
10//! the access happens at that instant, then the stretch cycle for a VDC or VCE address elapses.
11//!
12//! Differences forced by Rust:
13//!
14//! - **The CPU owns the board** (`cpu.bus`), so the board cannot hold the CPU. What the
15//!   reference's board does to its CPU (`set_irq_lines`, `irq_disable`, reading `high_speed`)
16//!   goes through the `Pins` each bus callback is handed, at the same points of the cycle and
17//!   in the same order; `attach_cpu` is `System::new`'s. With no CPU (`advance` called on a
18//!   bare board, as the reference's tests do) the lines are tracked and nothing is delivered.
19//! - **The decode is here**: `page_read` and `page_write` turn the page table's `Handler` names
20//!   into calls (pagetable.rs).
21//! - **The constructor's keyword arguments** are the fields of `BoardOptions`, which also
22//!   carries the switches the reference keeps as class attributes (`Psg`'s, `Timer`'s).
23//! - **The pixel path** is the board's field (`pixel_path`); the capture is handed the mixed
24//!   row. **The mixer** is handed the sources in the reference's order: the PSG, the port
25//!   device's own, then `audio_sources`.
26//! - **`bus_log`** is the tap the reference's scripts make by wrapping the three callables
27//!   (`scripts/state_roundtrip.py`, `observe`): when it is `Some`, every cycle appends the same
28//!   words.
29
30use huc6280::{Bus, Pins};
31
32use crate::cpu_io::CpuIo;
33use crate::hardware_page::map_hardware_page;
34use crate::machine::{
35    Machine, ADDRESS_MASK, CPU_CLOCKS_HIGH, CPU_CLOCKS_LOW, HARDWARE_FIRST_PAGE, HSYNC_CLOCKS,
36    LINE_CLOCKS, PAGE_BITS, PC_ENGINE,
37};
38use crate::mixer::Mixer;
39use crate::mt::PythonRandom;
40use crate::pagetable::{Handler, PageTable, Ram};
41use crate::psg::{Psg, PsgSwitches};
42use crate::sockets::{
43    AudioSource, BoardPins, Card, CardSlot, ControllerPort, DirectPath, IrqLine, PixelPath,
44    PortDevice, ResetKind, VideoTiming,
45};
46use crate::vce::Vce;
47use crate::vdc::Vdc;
48use crate::video::{Capture, Timeline};
49
50/// The reference's `Board(...)` arguments, with its defaults.
51pub struct BoardOptions {
52    pub machine: Machine,
53    pub card: Option<Box<dyn Card>>,
54    pub port: Option<Box<dyn PortDevice>>,
55    pub pad: Option<Box<dyn ControllerPort>>,
56    pub pixel_path: Option<Box<dyn PixelPath>>,
57    /// `None` powers up with zeros (U7, deterministic); a seed randomises RAM, VRAM, the
58    /// sprite table and the colour table reproducibly (Python's `random.Random(seed)`).
59    pub power_on_seed: Option<i64>,
60    /// The raster line at time zero (U1: the real power-up phase is not published).
61    pub start_line: i64,
62    pub start_offset: i64,
63    /// U19: see `vdc::sequencer::Sequencer::vblank_dots`.
64    pub vblank_dots: Option<i64>,
65    pub vertical_at_line_start: bool,
66    /// C7: see vdc/dma.rs.
67    pub dma_resumes: bool,
68    /// The PSG's switches (class attributes of the reference's `Psg`).
69    pub psg: PsgSwitches,
70    /// C25 (the reference's `Timer.underflow_window_mclk`).
71    pub timer_underflow_window_mclk: i64,
72}
73
74impl Default for BoardOptions {
75    fn default() -> Self {
76        BoardOptions {
77            machine: PC_ENGINE,
78            card: None,
79            port: None,
80            pad: None,
81            pixel_path: None,
82            power_on_seed: None,
83            start_line: 0,
84            start_offset: 0,
85            vblank_dots: Some(-8),
86            vertical_at_line_start: false,
87            dma_resumes: true,
88            psg: PsgSwitches::default(),
89            timer_underflow_window_mclk: 15,
90        }
91    }
92}
93
94pub struct Board {
95    pub machine: Machine,
96    pub mclk: i64,
97    pub(crate) held: i64,
98    pub(crate) lines: (bool, bool, bool),
99    /// set by the first new line
100    pub(crate) row_end: Option<i64>,
101    /// VideoTiming of the line whose row is still being drawn
102    pub(crate) row_timing: Option<VideoTiming>,
103    pub irq2: IrqLine,
104    pub vce: Vce,
105    /// One VDC instance per `machine.vdc_count` (docs/sockets.md socket 12). `vdcs[0]` is the
106    /// first; the others are run, synced and read for pixels and IRQ1 by the board, but have
107    /// no decode of their own: an add-on (the SuperGrafx's VPC) claims their pages.
108    pub vdcs: Vec<Vdc>,
109    pub psg: Psg,
110    pub cpu_io: CpuIo,
111    pub ram: Ram,
112    pub slot: CardSlot,
113    pub port: Option<Box<dyn PortDevice>>,
114    /// Further mixer inputs, after the PSG and the port device's own.
115    pub audio_sources: Vec<Box<dyn AudioSource>>,
116    pub mixer: Mixer,
117    pub timeline: Timeline,
118    pub capture: Capture,
119    pub pixel_path: Box<dyn PixelPath>,
120    pub pages: PageTable,
121    /// The opcode the CPU is running, as the last bus callback's `Pins` showed it.
122    pub(crate) opcode: u8,
123    /// When `Some`, every CPU cycle appends: for a read or a write `address << 8 | value`
124    /// then `mclk << 2 | kind` (0 read, 1 write); for an idle cycle `mclk << 2 | 2` alone.
125    pub bus_log: Option<Vec<u64>>,
126    /// When `Some`, every CPU cycle appends (kind, address, value, mclk): kind 0 read, 1 write,
127    /// 2 idle (address and value 0). The lockstep gate's per-cycle mode.
128    pub bus_detail: Option<Vec<(u8, u32, u8, i64)>>,
129}
130
131impl Board {
132    pub fn new(options: BoardOptions) -> Result<Board, String> {
133        let machine = options.machine;
134        let mut rng = options.power_on_seed.map(PythonRandom::new);
135
136        let vce = Vce::new(rng.as_mut());
137        let vdcs: Vec<Vdc> = (0..machine.vdc_count)
138            .map(|_| {
139                Vdc::new(
140                    rng.as_mut(),
141                    options.vblank_dots,
142                    options.vertical_at_line_start,
143                    options.dma_resumes,
144                )
145            })
146            .collect();
147        if vdcs.is_empty() {
148            return Err("a machine has at least one VDC".to_string());
149        }
150        let psg = Psg::new(44100.0, options.psg);
151        let mut cpu_io = CpuIo::new(machine.country_pc_engine, options.pad);
152        cpu_io.timer.underflow_window_mclk = options.timer_underflow_window_mclk;
153        let mut ram = Ram::new(machine.work_ram_bytes);
154        if let Some(rng) = rng.as_mut() {
155            for byte in ram.data.iter_mut() {
156                *byte = rng.getrandbits(8) as u8;
157            }
158        }
159        let timeline = Timeline::new(&machine, &vce, options.start_line, options.start_offset)?;
160        let capture = Capture::new(&vce);
161
162        let mut pages = PageTable::new();
163        // [hw: pcetech 3] banks $F8-$FB work RAM ($F9-$FB mirror $F8), $FF the hardware page.
164        pages.set_base(0x1F00, 0x1F7F, Handler::Ram);
165        map_hardware_page(&mut pages);
166        if let Some(card) = options.card.as_ref() {
167            for (first, last) in card.claims() {
168                pages.claim(first, last, Handler::Card)?;
169            }
170        }
171        if let Some(port) = options.port.as_ref() {
172            for (first, last) in port.claims() {
173                pages.claim(first, last, Handler::Port)?;
174            }
175        }
176        let pixel_path = options.pixel_path.unwrap_or_else(|| Box::new(DirectPath));
177        for (first, last) in pixel_path.claims() {
178            pages.claim(first, last, Handler::PixelPath)?;
179        }
180
181        let mut board = Board {
182            machine,
183            mclk: 0,
184            held: 0,
185            lines: (false, false, false),
186            row_end: None,
187            row_timing: None,
188            irq2: IrqLine::new("IRQ2"),
189            vce,
190            vdcs,
191            psg,
192            cpu_io,
193            ram,
194            slot: CardSlot::new(options.card),
195            port: options.port,
196            audio_sources: Vec::new(),
197            mixer: Mixer::default(),
198            timeline,
199            capture,
200            pixel_path,
201            pages,
202            opcode: 0,
203            bus_log: None,
204            bus_detail: None,
205        };
206        let divider = board.vce.dot_divider();
207        for vdc in board.vdcs.iter_mut() {
208            vdc.hsync(board.timeline.line_start, divider);
209            if board.timeline.line >= board.timeline.frame_lines - 3 {
210                vdc.vsync();
211            }
212        }
213        Ok(board)
214    }
215
216    /// The first VDC (the reference's `board.vdc`).
217    pub fn vdc(&mut self) -> &mut Vdc {
218        &mut self.vdcs[0]
219    }
220
221    /// Mixed stereo samples (44.1 kHz) of every audio source up to the clock now.
222    pub fn take_audio(&mut self) -> Vec<(i16, i16)> {
223        let mut sources: Vec<&mut dyn AudioSource> = vec![&mut self.psg];
224        if let Some(port) = self.port.as_mut() {
225            sources.extend(port.audio_sources());
226        }
227        for source in self.audio_sources.iter_mut() {
228            sources.push(source.as_mut());
229        }
230        self.mixer.take(self.mclk, sources)
231    }
232
233    /// The buttons held on pad `port` (`ControllerPort::set_pressed`; the reference's host
234    /// sets `pad.pressed` on the object it kept).
235    pub fn set_pressed(&mut self, port: usize, pressed: u16) {
236        if let Some(device) = self.cpu_io.port.device.as_mut() {
237            device.set_pressed(port, pressed);
238        }
239    }
240
241    // -- the decode -------------------------------------------------------------------------------
242
243    fn cd_attached(&self) -> bool {
244        self.port.as_ref().is_some_and(|port| port.present())
245    }
246
247    /// The reference's `pages.read`: one decode for every bus master.
248    pub fn page_read(&mut self, address: u32, mclk: i64) -> u8 {
249        let address = address & ADDRESS_MASK;
250        match self.pages.handler(address) {
251            Handler::Unmapped => 0xFF,
252            Handler::Ram => self.ram.read(address),
253            Handler::Vdc => self.vdcs[0].read(address & 3, mclk),
254            Handler::Vce => self.vce.read(address & 7, mclk),
255            Handler::CpuIo => {
256                let cd_attached = self.cd_attached();
257                self.cpu_io.read(address & 0x1FFF, mclk, cd_attached)
258            }
259            Handler::Card => {
260                let Board {
261                    slot,
262                    irq2,
263                    held,
264                    vdcs,
265                    opcode,
266                    ..
267                } = self;
268                let mut pins = BoardPins {
269                    irq2,
270                    held,
271                    vdcs,
272                    opcode: *opcode,
273                    card: None,
274                };
275                match slot.card.as_mut() {
276                    Some(card) => card.read(address, mclk, &mut pins),
277                    None => 0xFF,
278                }
279            }
280            Handler::Port => {
281                let Board {
282                    slot,
283                    port,
284                    irq2,
285                    held,
286                    vdcs,
287                    opcode,
288                    ..
289                } = self;
290                let mut pins = BoardPins {
291                    irq2,
292                    held,
293                    vdcs,
294                    opcode: *opcode,
295                    card: slot.card.as_deref_mut(),
296                };
297                match port.as_mut() {
298                    Some(port) => port.read(address, mclk, &mut pins),
299                    None => 0xFF,
300                }
301            }
302            Handler::PixelPath => {
303                let Board {
304                    slot,
305                    pixel_path,
306                    irq2,
307                    held,
308                    vdcs,
309                    opcode,
310                    ..
311                } = self;
312                let mut pins = BoardPins {
313                    irq2,
314                    held,
315                    vdcs,
316                    opcode: *opcode,
317                    card: slot.card.as_deref_mut(),
318                };
319                pixel_path.read(address, mclk, &mut pins)
320            }
321        }
322    }
323
324    /// The reference's `pages.write`.
325    pub fn page_write(&mut self, address: u32, value: u8, mclk: i64) {
326        let address = address & ADDRESS_MASK;
327        match self.pages.handler(address) {
328            Handler::Unmapped => {}
329            Handler::Ram => self.ram.write(address, value),
330            Handler::Vdc => self.vdcs[0].write(address & 3, value, mclk),
331            Handler::Vce => self.vce.write(address & 7, value, mclk),
332            Handler::CpuIo => self
333                .cpu_io
334                .write(address & 0x1FFF, value, mclk, &mut self.psg),
335            Handler::Card => {
336                let Board {
337                    slot,
338                    irq2,
339                    held,
340                    vdcs,
341                    opcode,
342                    ..
343                } = self;
344                let mut pins = BoardPins {
345                    irq2,
346                    held,
347                    vdcs,
348                    opcode: *opcode,
349                    card: None,
350                };
351                if let Some(card) = slot.card.as_mut() {
352                    card.write(address, value, mclk, &mut pins);
353                }
354            }
355            Handler::Port => {
356                let Board {
357                    slot,
358                    port,
359                    irq2,
360                    held,
361                    vdcs,
362                    opcode,
363                    ..
364                } = self;
365                let mut pins = BoardPins {
366                    irq2,
367                    held,
368                    vdcs,
369                    opcode: *opcode,
370                    card: slot.card.as_deref_mut(),
371                };
372                if let Some(port) = port.as_mut() {
373                    port.write(address, value, mclk, &mut pins);
374                }
375            }
376            Handler::PixelPath => {
377                let Board {
378                    slot,
379                    pixel_path,
380                    irq2,
381                    held,
382                    vdcs,
383                    opcode,
384                    ..
385                } = self;
386                let mut pins = BoardPins {
387                    irq2,
388                    held,
389                    vdcs,
390                    opcode: *opcode,
391                    card: slot.card.as_deref_mut(),
392                };
393                pixel_path.write(address, value, mclk, &mut pins);
394            }
395        }
396    }
397
398    // -- the CPU ----------------------------------------------------------------------------------
399
400    #[inline]
401    fn cycle_clocks(pins: &Pins) -> i64 {
402        if pins.high_speed {
403            CPU_CLOCKS_HIGH
404        } else {
405            CPU_CLOCKS_LOW
406        }
407    }
408
409    fn finish_access(&mut self, address: u32, cycle: i64, pins: &mut Pins) {
410        // The disable mask a write to $1402 left (the reference's `_irq_disable_changed`,
411        // called from inside the write: nothing has touched the CPU since).
412        if self.cpu_io.irq.mask_changed {
413            self.cpu_io.irq.mask_changed = false;
414            pins.set_irq_disable(self.cpu_io.irq.disable);
415        }
416        // [hw: pcetech 3 note 3] a VDC or VCE access takes one more cycle, reads and writes.
417        // C4: ares charges it only outside burst mode and only for the VDC; Mednafen charges
418        // a statistical VRAM penalty. MacDonald's rule, tier 2, is this model's.
419        let page = (address >> PAGE_BITS) as usize;
420        if (HARDWARE_FIRST_PAGE..HARDWARE_FIRST_PAGE + 8).contains(&page) {
421            self.held += cycle;
422        }
423        for vdc in self.vdcs.iter_mut() {
424            self.held += vdc.take_hold();
425        }
426        if self.held != 0 {
427            let held = std::mem::take(&mut self.held);
428            self.advance_with(held, Some(&mut *pins));
429        }
430        // the access itself (a status read) may have changed a line
431        self.deliver_lines(Some(pins), false);
432    }
433
434    /// A device stretches the current cycle (RDY low); applied when the access returns.
435    pub fn hold(&mut self, clocks: i64) {
436        self.held += clocks;
437    }
438
439    // -- time -------------------------------------------------------------------------------------
440
441    /// Let `clocks` master clocks pass and run every device up to the new time, with no CPU
442    /// to hand the interrupt lines to (the reference's `advance` on a board without one).
443    pub fn advance(&mut self, clocks: i64) {
444        self.advance_with(clocks, None);
445    }
446
447    fn advance_with(&mut self, clocks: i64, pins: Option<&mut Pins>) {
448        self.mclk += clocks;
449        self.run_to(self.mclk);
450        self.deliver_lines(pins, false);
451    }
452
453    fn run_to(&mut self, target: i64) {
454        loop {
455            let line_at = self.timeline.next_line_start();
456            let row_at = self.row_end;
457            let mut vdc_at = self.vdcs[0].next_event();
458            for other in &self.vdcs[1..] {
459                if let Some(at) = other.next_event() {
460                    if vdc_at.is_none_or(|first| at < first) {
461                        vdc_at = Some(at);
462                    }
463                }
464            }
465            let timer_at = self.cpu_io.next_event();
466            if let Some(row_at) = row_at.filter(|&at| at <= target && at <= line_at) {
467                self.end_row(row_at);
468            } else if line_at <= target && vdc_at.is_none_or(|at| line_at <= at) {
469                self.new_line(line_at);
470            } else if let Some(vdc_at) = vdc_at.filter(|&at| at <= target) {
471                for chip in self.vdcs.iter_mut() {
472                    chip.catch_up(vdc_at);
473                }
474            } else if let Some(timer_at) = timer_at.filter(|&at| at <= target) {
475                self.cpu_io.catch_up(timer_at);
476            } else {
477                break;
478            }
479        }
480        for chip in self.vdcs.iter_mut() {
481            chip.catch_up(target);
482        }
483        self.cpu_io.catch_up(target);
484        // socket 5, issue 0002: a port device acts by itself
485        let Board {
486            slot,
487            port,
488            irq2,
489            held,
490            vdcs,
491            opcode,
492            ..
493        } = self;
494        if let Some(port) = port.as_mut() {
495            let mut pins = BoardPins {
496                irq2,
497                held,
498                vdcs,
499                opcode: *opcode,
500                card: slot.card.as_deref_mut(),
501            };
502            port.catch_up(target, &mut pins);
503        }
504    }
505
506    fn new_line(&mut self, at: i64) {
507        for vdc in self.vdcs.iter_mut() {
508            vdc.catch_up(at);
509        }
510        // the line that is ending; its row ends 237 clocks later
511        self.row_timing = Some(self.timeline.timing(&self.vce));
512        self.row_end = Some(at + HSYNC_CLOCKS);
513        self.timeline.advance(&self.vce);
514        let divider = self.vce.dot_divider();
515        let vsync = self.timeline.line == self.timeline.frame_lines - 3;
516        for vdc in self.vdcs.iter_mut() {
517            vdc.hsync(at, divider);
518            if vsync {
519                vdc.vsync(); // [emu: Mednafen] after the hsync of the same line
520            }
521        }
522    }
523
524    /// The previous line's picture row ends as this line's sync does: hand it to the capture
525    /// before the VDC starts the new line's geometry (events at `at` itself wait).
526    fn end_row(&mut self, at: i64) {
527        for vdc in self.vdcs.iter_mut() {
528            vdc.catch_up(at - 1);
529        }
530        let timing = self.row_timing.expect("a row ends after a line began");
531        let dots = (LINE_CLOCKS / timing.dot_divider) as usize;
532        let rows: Vec<Vec<u16>> = self.vdcs.iter().map(|vdc| vdc.pixel_row(dots)).collect();
533        let row = self.pixel_path.mix(&timing, rows);
534        self.capture.finish_line(&timing, &row, &mut self.vce);
535        self.row_end = None;
536    }
537
538    // -- interrupts -------------------------------------------------------------------------------
539
540    /// (IRQ1, IRQ2, TIQ) as the interrupt controller sees them, before the mask.
541    pub fn lines(&self) -> (bool, bool, bool) {
542        // IRQ1 is shared by every VDC (wired-OR; each is acknowledged by reading its status).
543        (
544            self.vdcs.iter().any(|vdc| vdc.irq1()),
545            self.irq2.level(),
546            self.cpu_io.tiq(),
547        )
548    }
549
550    pub(crate) fn deliver_lines(&mut self, pins: Option<&mut Pins>, force: bool) {
551        let lines = self.lines();
552        self.cpu_io.irq.irq1 = lines.0;
553        self.cpu_io.irq.irq2 = lines.1;
554        if lines != self.lines || force {
555            if let Some(pins) = pins {
556                pins.set_irq_lines(lines.0, lines.1, lines.2);
557            }
558        }
559        self.lines = lines;
560    }
561
562    // -- reset ------------------------------------------------------------------------------------
563
564    pub fn reset(&mut self, kind: ResetKind) {
565        let Board {
566            slot,
567            port,
568            pixel_path,
569            irq2,
570            held,
571            vdcs,
572            opcode,
573            ..
574        } = self;
575        if let Some(card) = slot.card.as_mut() {
576            let mut pins = BoardPins {
577                irq2,
578                held,
579                vdcs,
580                opcode: *opcode,
581                card: None,
582            };
583            card.reset(kind, &mut pins);
584        }
585        if let Some(port) = port.as_mut() {
586            let mut pins = BoardPins {
587                irq2,
588                held,
589                vdcs,
590                opcode: *opcode,
591                card: slot.card.as_deref_mut(),
592            };
593            port.reset(kind, &mut pins);
594        }
595        let mut pins = BoardPins {
596            irq2,
597            held,
598            vdcs,
599            opcode: *opcode,
600            card: slot.card.as_deref_mut(),
601        };
602        pixel_path.reset(kind, &mut pins);
603        if kind == ResetKind::PowerOn {
604            self.cpu_io.reset();
605        }
606    }
607}
608
609impl Bus for Board {
610    fn read(&mut self, address: u32, pins: &mut Pins) -> u8 {
611        self.opcode = pins.opcode();
612        let cycle = Board::cycle_clocks(pins);
613        self.advance_with(cycle, Some(pins));
614        let value = self.page_read(address, self.mclk);
615        self.finish_access(address, cycle, pins);
616        if let Some(log) = self.bus_log.as_mut() {
617            log.push((address as u64) << 8 | value as u64);
618            log.push((self.mclk as u64) << 2);
619        }
620        if let Some(detail) = self.bus_detail.as_mut() {
621            detail.push((0, address, value, self.mclk));
622        }
623        value
624    }
625
626    fn write(&mut self, address: u32, value: u8, pins: &mut Pins) {
627        self.opcode = pins.opcode();
628        let cycle = Board::cycle_clocks(pins);
629        self.advance_with(cycle, Some(pins));
630        self.page_write(address, value, self.mclk);
631        self.finish_access(address, cycle, pins);
632        if let Some(log) = self.bus_log.as_mut() {
633            log.push((address as u64) << 8 | value as u64);
634            log.push((self.mclk as u64) << 2 | 1);
635        }
636        if let Some(detail) = self.bus_detail.as_mut() {
637            detail.push((1, address, value, self.mclk));
638        }
639    }
640
641    /// A cycle with no bus transfer (internal cycle or dummy read: nothing reacts).
642    fn idle(&mut self, _address: Option<u32>, pins: &mut Pins) {
643        self.opcode = pins.opcode();
644        let cycle = Board::cycle_clocks(pins);
645        self.advance_with(cycle, Some(pins));
646        if let Some(log) = self.bus_log.as_mut() {
647            log.push((self.mclk as u64) << 2 | 2);
648        }
649        if let Some(detail) = self.bus_detail.as_mut() {
650            detail.push((2, 0, 0, self.mclk));
651        }
652    }
653}