pcengine_rust/vdc/
chip.rs

1//! The HuC6270 VDC as the CPU sees it: the bus port, VRAM access, status, IRQ1 (`vdc/chip.py`).
2//!
3//! Instances, not module state: a SuperGrafx has two, a PC-FX may one day pin this module.
4//!
5//! Bus ($FF:0000-03FF, 4-byte mirror) [hw: pcetech 5]:
6//!
7//! ```text
8//! $0  write: register select (low 5 bits); read: status
9//! $1  unused, reads 0
10//! $2  data LSB     $3  data MSB
11//! ```
12//!
13//! Provisional (U1, tier 5): the VDC's CPU access schedule in active display. Hudson's table and
14//! MacDonald's give the mode-0 slot order (CPU, BAT, CPU, ?, CPU, CG0, CPU, CG1) but not the
15//! phase against the line. A VRAM data access made during the display width is *accepted* at once
16//! and *committed* at the next CPU slot of an 8-dot cycle counted from the display start; BSY
17//! (status bit 6) is set until then; a second data access while one is pending holds the CPU
18//! (RDY) until the first commits. Mednafen instead charges a statistical 1-cycle penalty (C4).
19//!
20//! Differences forced by Rust: the reference's `hold` callable (the board's) is an accumulator
21//! here, `held`, which the board takes when the access returns (`take_hold`): the reference's
22//! board applies its own sum at the same point.
23
24use serde::{Deserialize, Serialize};
25
26use crate::machine::{py_floordiv, HSYNC_CLOCKS};
27use crate::mt::PythonRandom;
28use crate::vdc::dma::DmaEngine;
29use crate::vdc::regs as r;
30use crate::vdc::sequencer::{Event, Sequencer, VPhase};
31use crate::vdc::{background, sprites};
32
33/// [hw: pcetech 5] 64 KiB; the upper half of the 128 KiB space mirrors it
34pub const VRAM_WORDS: usize = 0x8000;
35
36/// [hw: pcetech 5.1 register $09] CPU slots within the 8-dot cycle, by VRAM access mode
37/// (MWR D1-D0): mode 0 "CPU BAT CPU ??? CPU CG0 CPU CG1", modes 1 and 2 "BAT CPU CG0 CG1" over
38/// two dots each, mode 3 none for the CPU (four-dot accesses, BAT then CG).
39pub const CPU_SLOTS: [&[i64]; 4] = [&[0, 2, 4, 6], &[2], &[2], &[]];
40
41#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
42pub struct Vdc {
43    pub regs: r::VdcRegisters,
44    held: i64,
45    pub vram: Vec<u16>,
46    pub sat: Vec<u16>,
47    pub status: u8,
48    /// master-clock time of the sequencer event being handled
49    pub now: i64,
50    pub seq: Sequencer,
51    pub dma: DmaEngine,
52    // [emu: Mednafen BG_YMoo, BG_YOffset, BG_XOffset] the scroll as the line latched it
53    pub(crate) bg_y: i64,
54    pub(crate) need_bg_y_step: bool,
55    pub(crate) bg_y_offset: i64,
56    pub(crate) bg_x_offset: i64,
57    /// MWR as the vertical sync latched it
58    pub(crate) mwr_cache: u16,
59    pub(crate) row: Option<Vec<u16>>,
60    pub(crate) sprite_entries: Vec<sprites::Entry>,
61    /// A pending CPU VRAM write: (address, word)
62    pub(crate) pending_write: Option<(u16, u16)>,
63    pub(crate) pending_read: Option<u16>,
64    pub(crate) commit_at: i64,
65}
66
67impl Vdc {
68    /// The reference's defaults: `vblank_dots = Some(-8)`, `vertical_at_line_start = false`,
69    /// `dma_resumes = true`.
70    pub fn new(
71        power_on: Option<&mut PythonRandom>,
72        vblank_dots: Option<i64>,
73        vertical_at_line_start: bool,
74        dma_resumes: bool,
75    ) -> Vdc {
76        // U7: zeros by default, random on request.
77        let (vram, sat) = match power_on {
78            None => (vec![0; VRAM_WORDS], vec![0; 256]),
79            Some(rng) => {
80                let vram = (0..VRAM_WORDS)
81                    .map(|_| rng.getrandbits(16) as u16)
82                    .collect();
83                let sat = (0..256).map(|_| rng.getrandbits(16) as u16).collect();
84                (vram, sat)
85            }
86        };
87        Vdc {
88            regs: r::VdcRegisters::new(),
89            held: 0,
90            vram,
91            sat,
92            status: 0,
93            now: 0,
94            seq: Sequencer::new(vblank_dots, vertical_at_line_start),
95            dma: DmaEngine::new(dma_resumes),
96            bg_y: 0,
97            need_bg_y_step: false,
98            bg_y_offset: 0,
99            bg_x_offset: 0,
100            mwr_cache: 0,
101            row: None,
102            sprite_entries: Vec::new(),
103            pending_write: None,
104            pending_read: None,
105            commit_at: 0,
106        }
107    }
108
109    /// The master clocks the accesses since the last call asked the CPU to wait (the
110    /// reference's `hold` callable, summed).
111    pub fn take_hold(&mut self) -> i64 {
112        std::mem::take(&mut self.held)
113    }
114
115    fn hold(&mut self, clocks: i64) {
116        self.held += clocks;
117    }
118
119    // -- outputs --------------------------------------------------------------------------------
120
121    /// The /IRQ pin: held until the status port is read.
122    #[inline]
123    pub fn irq1(&self) -> bool {
124        self.status & r::IRQ_BITS != 0
125    }
126
127    #[inline]
128    pub fn bsy(&self) -> bool {
129        self.pending_write.is_some() || self.pending_read.is_some()
130    }
131
132    pub fn next_event(&self) -> Option<i64> {
133        [
134            self.seq_next_event(),
135            self.commit_event(),
136            self.dma_next_event(),
137        ]
138        .into_iter()
139        .flatten()
140        .min()
141    }
142
143    fn commit_event(&self) -> Option<i64> {
144        if self.bsy() {
145            Some(self.commit_at)
146        } else {
147            None
148        }
149    }
150
151    pub fn catch_up(&mut self, mclk: i64) {
152        loop {
153            let seq_t = self.seq_next_event();
154            let dma_t = self.dma_next_event();
155            let commit_t = self.commit_event();
156            let due = [seq_t, dma_t, commit_t]
157                .into_iter()
158                .flatten()
159                .filter(|&t| t <= mclk)
160                .min();
161            let Some(t) = due else {
162                self.dma_advance(mclk);
163                return;
164            };
165            if dma_t == Some(t) {
166                self.dma_advance(t);
167            } else if commit_t == Some(t) && seq_t.is_none_or(|seq_t| t <= seq_t) {
168                self.commit_pending();
169            } else {
170                self.dma_advance(t);
171                self.seq_run_to(t);
172            }
173        }
174    }
175
176    // -- the sync generator's calls (the VCE's line clock) ----------------------------------------
177
178    pub fn hsync(&mut self, mclk: i64, divider: i64) {
179        self.seq_hsync(mclk, divider);
180    }
181
182    pub fn vsync(&mut self) {
183        self.seq_vsync();
184        self.need_bg_y_step = false;
185        self.mwr_cache = self.regs.mwr();
186    }
187
188    // -- events from the sequencer ----------------------------------------------------------------
189
190    pub(crate) fn vblank_test(&mut self) {
191        if self.regs.cr() & r::CR_VBLANK_IRQ != 0 {
192            self.status |= r::VD;
193        }
194    }
195
196    pub(crate) fn raster_test(&mut self, count: i64) {
197        // [hw: pcetech 5.1] RCR is compared with the line counted from $40 at the first active
198        // line; values outside $40-$146 never match.
199        if count == self.regs.rcr() - 0x40 && self.regs.cr() & r::CR_RASTER_IRQ != 0 {
200            self.status |= r::RR;
201        }
202    }
203
204    pub(crate) fn latch_byr(&mut self) {
205        self.step_bg_y();
206        self.bg_y_offset = self.bg_y;
207    }
208
209    pub(crate) fn latch_bxr(&mut self) {
210        self.bg_x_offset = (self.regs.value[r::BXR] & 0x3FF) as i64;
211    }
212
213    fn step_bg_y(&mut self) {
214        if self.need_bg_y_step {
215            self.need_bg_y_step = false;
216            self.bg_y = if self.seq.rcr_count == 0 {
217                (self.regs.value[r::BYR] & 0x1FF) as i64
218            } else {
219                self.bg_y + 1
220            };
221        }
222    }
223
224    pub(crate) fn line_counter_step(&mut self, _count: i64) {
225        self.step_bg_y();
226        self.need_bg_y_step = true;
227    }
228
229    /// The scan for the next line's sprites, with the overflow flag and the narrow-display
230    /// budget (U3: Mesen2's: the VDC fetches 4, 4, 8 or 16 dots per entry between the end of
231    /// one line's display width and 16 dots before the next line's).
232    pub(crate) fn fetch_sprites(&mut self, line: i64) {
233        let seq = &self.seq;
234        let dots = 1365 / seq.divider;
235        let previous_end = py_floordiv(seq.active_end - seq.origin - HSYNC_CLOCKS, seq.divider);
236        let next_start = dots + 8 + (self.regs.hds() + 1) * 8 - 16;
237        let budget = 0.max(next_start - previous_end)
238            / sprites::CLOCKS_PER_SPRITE[((self.mwr_cache >> 2) & 3) as usize];
239        let (entries, overflow) = sprites::scan(
240            &self.vram,
241            VRAM_WORDS,
242            &self.sat,
243            line,
244            self.mwr_cache,
245            budget as usize,
246        );
247        self.sprite_entries = entries;
248        if overflow && self.regs.cr() & r::CR_OVERFLOW_IRQ != 0 {
249            self.status |= r::OR;
250        }
251    }
252
253    pub(crate) fn collision_hit(&mut self) {
254        if self.regs.cr() & r::CR_COLLISION_IRQ != 0 {
255            self.status |= r::CR_FLAG;
256        }
257    }
258
259    pub(crate) fn display_started(&mut self) {
260        self.dma_display_started(self.now);
261    }
262
263    pub(crate) fn display_ended(&mut self) {
264        self.dma_display_ended(self.now);
265    }
266
267    pub(crate) fn burst_began(&mut self) {
268        self.dma_advance(self.now);
269    }
270
271    /// The 9-bit pixels of this line, drawn as the display width begins. [hw: pcetech 5.2, 6]
272    /// Backdrop (background colour 0, $000) inside the width if either layer is on, overscan
273    /// (sprite colour 0, $100) otherwise and outside.
274    pub(crate) fn render_line(&mut self) {
275        let seq = &self.seq;
276        let dots = (1365 / seq.divider) as usize;
277        let mut row = vec![0x100u16; dots];
278        if !seq.display_line {
279            self.row = Some(row);
280            return;
281        }
282        let row_start = seq.origin + HSYNC_CLOCKS;
283        let first = py_floordiv(seq.active_start - row_start, seq.divider);
284        let width = py_floordiv(seq.active_end - seq.active_start, seq.divider);
285        let cr = seq.cr_cache;
286        let divider = seq.divider;
287        let end = (first + width).min(dots as i64);
288        if first >= end {
289            // Not reachable: a display start at or past the row's end is later than the next
290            // line's sync, which drops this line's events before `render_line` runs
291            // (sequencer.rs, `seq_leave_hsync`). Kept so the slices below cannot panic.
292            self.row = Some(row);
293            return;
294        }
295        let pixels = if cr & 0x80 != 0 {
296            background::row(
297                &self.vram,
298                VRAM_WORDS,
299                self.mwr_cache,
300                self.bg_x_offset,
301                self.bg_y_offset,
302                width,
303            )
304        } else {
305            // sprites only, or neither layer inside a non-burst display period: the backdrop.
306            // [emu: Mednafen, Mesen2 and Beetle all show colour 0 of the background palette when
307            // both layers are off (Space Harrier's last 12 lines); pcetech 5.2 says overscan: C30]
308            vec![0x000; width as usize]
309        };
310        let (first_index, end_index) = (first as usize, end as usize);
311        row[first_index..end_index].copy_from_slice(&pixels[..end_index - first_index]);
312        let mut collision = None;
313        if cr & 0x40 != 0 && !self.sprite_entries.is_empty() {
314            let hit = sprites::draw(&self.sprite_entries, end - first, &mut row, first_index);
315            if let Some(hit) = hit {
316                if self.regs.cr() & r::CR_COLLISION_IRQ != 0 {
317                    // the flag rises when the beam reaches the pixel (Mesen2 runs the VDC per CPU cycle
318                    // for this; Mednafen raises it as the line is drawn): U3
319                    collision = Some(row_start + (first + hit) * divider);
320                }
321            }
322        }
323        self.row = Some(row);
324        if let Some(when) = collision {
325            self.seq_schedule(when.max(self.now), Event::Collision);
326        }
327    }
328
329    /// Commit a waiting CPU access unless a transfer holds the VRAM (Mednafen's
330    /// `CheckAndCommitPending`: nothing is committed while the SAT or VRAM DMA runs).
331    pub(crate) fn commit_unless_dma(&mut self) {
332        if !self.dma.busy() {
333            self.commit_pending();
334        }
335    }
336
337    pub(crate) fn commit_pending(&mut self) {
338        if let Some((address, word)) = self.pending_write.take() {
339            if (address as usize) < VRAM_WORDS {
340                // [hw] writes to the mirrored half are ignored
341                self.vram[address as usize] = word;
342            }
343        }
344        if let Some(address) = self.pending_read.take() {
345            // Mirrored reads "sometimes return corrupted data" [hw]; U23: this model reads 0.
346            self.regs.read_buffer = if (address as usize) < VRAM_WORDS {
347                self.vram[address as usize]
348            } else {
349                0
350            };
351        }
352    }
353
354    // -- the CPU's port ---------------------------------------------------------------------------
355
356    pub fn read(&mut self, offset: u32, mclk: i64) -> u8 {
357        self.catch_up(mclk);
358        let port = offset & 3;
359        if port == 0 {
360            let value = self.status | if self.bsy() { r::BSY } else { 0 };
361            self.status &= !r::IRQ_BITS;
362            return value;
363        }
364        if port == 1 {
365            return 0;
366        }
367        let msb = port == 3;
368        if self.pending_read.is_some() {
369            // The word the last MARR write or VRR read asked for is not in the buffer yet (it
370            // waits for a CPU slot or a DMA): the CPU waits for it rather than reading the old
371            // word. The manual's read sequence and both Mednafen and Mesen2 ("D&D Order of the
372            // Griffon breaks without this") agree; the model's slot wait made the case possible.
373            self.data_access(mclk);
374        }
375        let value = if msb {
376            (self.regs.read_buffer >> 8) as u8
377        } else {
378            (self.regs.read_buffer & 0xFF) as u8
379        };
380        if msb && self.regs.select as usize == r::VRW {
381            // [hw: pcetech 5.1 $02] after the MSB read MARR advances and the next word is read
382            self.data_access(mclk);
383            self.regs.value[r::MARR] = self.regs.value[r::MARR].wrapping_add(self.regs.increment());
384            self.pending_read = Some(self.regs.value[r::MARR]);
385            self.schedule_commit(mclk);
386        }
387        value
388    }
389
390    pub fn write(&mut self, offset: u32, value: u8, mclk: i64) {
391        self.catch_up(mclk);
392        let port = offset & 3;
393        if port == 0 {
394            self.regs.select = value & 0x1F;
395            return;
396        }
397        if port == 1 {
398            return;
399        }
400        let register = self.regs.select;
401        if !r::valid_register(register) {
402            return;
403        }
404        let register = register as usize;
405        let msb = port == 3;
406        if register == r::VRW {
407            if !msb {
408                self.regs.write_latch = value;
409            } else {
410                self.data_access(mclk);
411                let word = self.regs.write_latch as u16 | ((value as u16) << 8);
412                self.pending_write = Some((self.regs.value[r::MAWR], word));
413                self.regs.value[r::MAWR] =
414                    self.regs.value[r::MAWR].wrapping_add(self.regs.increment());
415                self.schedule_commit(mclk);
416            }
417            return;
418        }
419        self.regs.set_byte(register, value, msb);
420        if register == r::MARR && msb {
421            // [hw: pcetech 5.1 $01] writing the MSB loads the read buffer from VRAM[MARR]
422            self.data_access(mclk);
423            self.pending_read = Some(self.regs.value[r::MARR]);
424            self.schedule_commit(mclk);
425        } else if register == r::BYR {
426            // [emu: Mednafen] set on both bytes: only changing on the MSB breaks a game
427            self.bg_y = (self.regs.value[r::BYR] & 0x1FF) as i64;
428        } else if register == r::SATB {
429            self.dma_arm_satb(); // [mfr] armed by a write; starts when the display period ends
430        } else if register == r::LENR && msb {
431            self.dma_start(mclk);
432        }
433    }
434
435    // -- VRAM access timing -----------------------------------------------------------------------
436
437    /// A second data-port access while one is pending holds the CPU until it commits.
438    fn data_access(&mut self, mclk: i64) {
439        let mut now = mclk;
440        while self.bsy() && self.dma.busy() {
441            // the pending access is stuck behind a transfer
442            let Some(due) = self.dma_next_event() else {
443                // paused behind the display: nothing to wait for but the end of it
444                self.dma_force_complete(now);
445                break;
446            };
447            if due > now {
448                self.hold(due - now);
449            }
450            self.catch_up(due);
451            now = now.max(due);
452        }
453        if self.bsy() {
454            let wait = self.commit_at - now;
455            if wait > 0 {
456                self.hold(wait);
457            }
458            self.commit_pending();
459        }
460    }
461
462    fn schedule_commit(&mut self, mclk: i64) {
463        if self.dma.busy() {
464            // waits for the transfer; its end commits (BSY meanwhile)
465            self.commit_at = 1 << 62;
466            return;
467        }
468        self.commit_at = self.slot_time(mclk);
469        if self.commit_at <= mclk {
470            self.commit_pending();
471        }
472    }
473
474    /// Earliest time at or after `mclk` that the CPU owns a VRAM slot (U1, provisional).
475    pub fn slot_time(&self, mclk: i64) -> i64 {
476        let seq = &self.seq;
477        if !(seq.active_display() && (seq.active_start..seq.active_end).contains(&mclk)) {
478            return mclk;
479        }
480        let div = seq.divider;
481        // first dot boundary at or after mclk
482        let mut dot = -py_floordiv(-(mclk - seq.active_start), div);
483        let slots = CPU_SLOTS[(self.regs.mwr() & 3) as usize];
484        if slots.is_empty() {
485            return seq.active_end;
486        }
487        loop {
488            let when = seq.active_start + dot * div;
489            if when >= seq.active_end {
490                return seq.active_end;
491            }
492            if slots.contains(&dot.rem_euclid(8)) {
493                return when;
494            }
495            dot += 1;
496        }
497    }
498
499    // -- display ----------------------------------------------------------------------------------
500
501    pub fn vphase(&self) -> VPhase {
502        self.seq.vphase
503    }
504
505    /// The 9-bit VDC output for the line that just ran (drawn by `render_line`).
506    pub fn pixel_row(&self, dots: usize) -> Vec<u16> {
507        match &self.row {
508            Some(row) if row.len() == dots => row.clone(),
509            _ => vec![0x100; dots],
510        }
511    }
512}