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