supergrafx_rust/
vpc.rs

1//! The HuC6202 video priority controller (VPC): the SuperGrafx's pixel path and its register
2//! block (`vpc.py`).
3//!
4//! [hw: sgxtech, "Video Priority Controller"] The VPC
5//!
6//! - mixes the 9-bit pixel buses of VDC 1 and VDC 2 and hands the result to the VCE
7//!   (`Vpc::mix`, the board's `PixelPath` socket 7: one row per VDC, one row back);
8//! - keeps two window widths and four 4-bit (enable, enable, priority) groups, one per window area;
9//! - steers `ST0`-`ST2` to VDC 2 when `$0E` bit 0 is set (`Vpc::st_to_vdc2`, used by `VideoPage`);
10//! - decodes the video chip area `$FF:0000-03FF` (`VideoPage`, with the compat switch).
11//!
12//! A VDC row value is 9 bits: bit 8 sprite, bits 7-4 palette, bits 3-0 colour; a colour of 0 is
13//! transparent. "Priority between backgrounds and sprites is managed internally to the VDC": the VPC
14//! sees only the bit-8 sprite flag and the transparency, so it cannot tell a high-priority sprite from
15//! a low one.
16//!
17//! Everything the sources do not settle is a **named switch** with a provisional default and its
18//! tier, so a later judge changes one line (the reference's docs/m6-record.md lists them as U/C
19//! entries).
20//!
21//! Differences forced by Rust:
22//!
23//! - **`VideoPage` is the board's `PixelPath` and owns the `Vpc`.** The reference has two objects
24//!   that share state by reference: `Vpc` is the pixel path, `VideoPage` claims the pages and
25//!   holds the VPC and both VDCs. Here one trait object is both (the base board's
26//!   `sockets::PixelPath` may claim pages), `VideoPage::vpc` is the VPC, and the VDCs are
27//!   `pins.vdcs`, handed in with every access. Each access steered to a VDC is made with
28//!   `pins.vdc_read` / `vdc_write`, so that the base board's wait reaches it (pcengine-python
29//!   issue 0004: where the reference's VDC calls the board's `_serve_vram` from inside the
30//!   access, the base board serves the chip after the access stops and makes it again).
31//! - **`store_immediate`** is `pins.opcode`: the reference's page calls back into the
32//!   `SuperGrafx` object, which reads the core's `opcode`; here the board hands the opcode to
33//!   the device with each access (and 0 with no CPU, where the reference answers `False`).
34//! - **The named switches** are fields (`priority_labels`, `window_origin`,
35//!   `window_off_at_or_below`, `VideoPage::st_steers_in_compat`) where the reference has class
36//!   attributes; `PRIORITY_LABELS`' two strings are the enum `PriorityLabels`, and
37//!   `WINDOW_ORIGIN`'s dict by dot divider is `WindowOrigin`.
38//! - **Save states**: `DeviceState` (bytes out, bytes in), where the reference's state walks the
39//!   object graph. As there, the registers, the shadows, the write log and the position of the
40//!   compatibility switch are in a state; the named switches are the system's own.
41//! - **Reset**: `PixelPath::reset` (called by `Board::reset`) is what the reference's
42//!   `SuperGrafx.reset` does after the board's: a power-on reset resets the VPC.
43
44use std::any::Any;
45
46use pcengine_rust::machine::{py_floordiv, HARDWARE_FIRST_PAGE, HSYNC_CLOCKS, LINE_CLOCKS};
47use pcengine_rust::sockets::{BoardPins, DeviceState, PixelPath, ResetKind, VideoTiming};
48use serde::{Deserialize, Serialize};
49
50/// bit 8 of a VDC row value: the pixel came from a sprite
51pub const SPRITE: u16 = 0x100;
52/// bits 3-0: 0 is transparent
53pub const COLOUR: u16 = 0x0F;
54
55// Register offsets inside the VPC block ($FF:0008-000F, native mode).
56/// bits 7-4 window 2 only, bits 3-0 windows 1 and 2 overlapping
57pub const PRIORITY_A: u8 = 0x08;
58/// bits 7-4 no window, bits 3-0 window 1 only
59pub const PRIORITY_B: u8 = 0x09;
60pub const WINDOW1_LSB: u8 = 0x0A;
61pub const WINDOW1_MSB: u8 = 0x0B;
62pub const WINDOW2_LSB: u8 = 0x0C;
63pub const WINDOW2_MSB: u8 = 0x0D;
64/// bit 0: ST0-ST2 go to VDC 2
65pub const ST_STEER: u8 = 0x0E;
66
67/// [hw: HuC6280 hardware manual] ST0, ST1, ST2 are opcodes $03, $13, $23.
68pub const ST_OPCODES: [u8; 3] = [0x03, 0x13, 0x23];
69
70/// C-SGX1: which reading of the 2-bit priority codes (`Vpc::priority_labels`).
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum PriorityLabels {
73    /// Mednafen's and Mesen2's reading, and Dai Makai Mura's behaviour (the default).
74    Detectors,
75    /// sgxtech's labels: the two codes swapped.
76    Sgxtech,
77}
78
79/// U-SGX1: the window origin per dot clock (`Vpc::window_origin`), by the dot divider.
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub struct WindowOrigin {
82    /// 4 master clocks a dot: 5.37 MHz
83    pub divider4: i64,
84    /// 3: 7.16 MHz
85    pub divider3: i64,
86    /// 2: 10.7 MHz
87    pub divider2: i64,
88}
89
90impl WindowOrigin {
91    /// The reference's `WINDOW_ORIGIN[div]` (a `KeyError` there for another divider).
92    pub fn of(&self, div: i64) -> i64 {
93        match div {
94            4 => self.divider4,
95            3 => self.divider3,
96            2 => self.divider2,
97            _ => panic!("no window origin for a dot divider of {div}"),
98        }
99    }
100}
101
102/// Registers, ST steering and the mix. `mix(timing, rows)` is the PixelPath's.
103#[derive(Clone, Debug, PartialEq, Eq)]
104pub struct Vpc {
105    /// C-SGX1 (undecidable without hardware): which 2-bit priority code means what. sgxtech says
106    /// 01b = "VDC #1 sprites behind the VDC #2 background" and 10b = "VDC #2 sprites in front of
107    /// the VDC #1 background"; Mednafen and Mesen2 (tier 5) read the same register the other way
108    /// round, and Mednafen's source says Dai Makai Mura (Ghouls 'n Ghosts) *uses setting 1 and
109    /// expects VDC #2 sprites in front of the VDC #1 background*. A shipped game that works on
110    /// hardware outranks the document's labels, so the default follows the detectors. `Sgxtech`
111    /// swaps the two codes. Tier: detectors + a game's behaviour (5), against tier 2 text.
112    /// Decided 2026-11-12 (Aubrey): this default stays. Past the title Dai Makai Mura's cutscene
113    /// and stage 1 lose their statues and score display under `Sgxtech` and are row-identical to
114    /// both detectors under `Detectors` (the reference's docs/m6-record.md); still no console run.
115    pub priority_labels: PriorityLabels,
116
117    /// U-SGX1: where the window edges fall. A window of width W covers the row's dots
118    /// [0, W - 0x40 + ORIGIN\[dot_divider\]) and is off for W <= 0x40 (sgxtech: "values smaller
119    /// than $0040 disable the window"; "windows start from the leftmost pixel of the physical
120    /// screen"). The origin per dot clock (4 = 5.37 MHz, 3 = 7.16, 2 = 10.7) is Mednafen's
121    /// calibrated `8 + 24`/`8 + 38`; Mesen2 uses 48 at every clock. Tier 5; the pictures decide
122    /// (the reference's docs/m6-record.md).
123    pub window_origin: WindowOrigin,
124
125    /// U-SGX2: a window width at or below this disables the window (sgxtech, tier 2).
126    pub window_off_at_or_below: i64,
127
128    // U-SGX3: the dot, counted from the end of the line's horizontal sync, at which a register
129    // write takes effect is the first dot whose time is at or after the write (the same rule as
130    // the VCE's palette); Mesen2 and Mednafen both draw the line up to the write first.
131    // (Documented behaviour of this model, tier 5; not a switch.)
132    pub priority: [u8; 2],
133    pub window: [u16; 2],
134    pub st_to_vdc2: bool,
135    shadow_priority: [u8; 2],
136    shadow_window: [u16; 2],
137    /// (mclk, register, value) of every write that changes the picture, drained by `mix`
138    log: Vec<(i64, u8, u8)>,
139}
140
141impl Default for Vpc {
142    fn default() -> Self {
143        Vpc::new()
144    }
145}
146
147impl Vpc {
148    pub fn new() -> Vpc {
149        Vpc {
150            priority_labels: PriorityLabels::Detectors,
151            window_origin: WindowOrigin {
152                divider4: 32,
153                divider3: 46,
154                divider2: 32,
155            },
156            window_off_at_or_below: 0x40,
157            priority: [0x11, 0x11],
158            window: [0, 0],
159            st_to_vdc2: false,
160            shadow_priority: [0x11, 0x11],
161            shadow_window: [0, 0],
162            log: Vec::new(),
163        }
164    }
165
166    /// [hw: sgxtech] power-up: `$11 $11 $00 $00 $00 $00 $00 $00` in `$08-$0F`: windows off,
167    /// store-immediate to VDC 1, and only VDC 1 enabled with the default priority everywhere.
168    pub fn reset(&mut self) {
169        self.priority = [0x11, 0x11];
170        self.window = [0, 0];
171        self.st_to_vdc2 = false;
172        self.shadow_priority = [0x11, 0x11];
173        self.shadow_window = [0, 0];
174        self.log.clear();
175    }
176
177    // -- the CPU's port -----------------------------------------------------------------------
178
179    /// `$08-$0F`. Both priority registers and the window LSBs return what was written; the
180    /// window MSBs keep only bits 1-0; `$0E` and `$0F` read $00 [hw: sgxtech].
181    pub fn read(&self, offset: u32) -> u8 {
182        match (offset & 0x0F) as u8 {
183            PRIORITY_A => self.priority[0],
184            PRIORITY_B => self.priority[1],
185            WINDOW1_LSB => (self.window[0] & 0xFF) as u8,
186            WINDOW1_MSB => (self.window[0] >> 8) as u8,
187            WINDOW2_LSB => (self.window[1] & 0xFF) as u8,
188            WINDOW2_MSB => (self.window[1] >> 8) as u8,
189            _ => 0x00,
190        }
191    }
192
193    pub fn write(&mut self, offset: u32, value: u8, mclk: i64) {
194        let reg = (offset & 0x0F) as u8;
195        match reg {
196            PRIORITY_A => self.priority[0] = value,
197            PRIORITY_B => self.priority[1] = value,
198            WINDOW1_LSB => self.window[0] = (self.window[0] & 0x300) | value as u16,
199            WINDOW1_MSB => self.window[0] = (self.window[0] & 0x0FF) | ((value as u16 & 3) << 8),
200            WINDOW2_LSB => self.window[1] = (self.window[1] & 0x300) | value as u16,
201            WINDOW2_MSB => self.window[1] = (self.window[1] & 0x0FF) | ((value as u16 & 3) << 8),
202            ST_STEER => {
203                self.st_to_vdc2 = value & 1 != 0;
204                return;
205            }
206            _ => return, // $0F is unused
207        }
208        self.log.push((mclk, reg, value));
209    }
210
211    // -- the mix ------------------------------------------------------------------------------
212
213    /// The PixelPath: VDC 1's and VDC 2's rows for one line in, the row for the VCE out.
214    ///
215    /// A register written during the line takes effect at the first dot whose time is at or
216    /// after the write, as the VCE's palette does (`Capture`): the line is mixed in pieces.
217    pub fn mix(&mut self, timing: &VideoTiming, rows: &[Vec<u16>]) -> Vec<u16> {
218        let (vdc1, vdc2) = (&rows[0][..], &rows[1][..]);
219        let dots = vdc1.len() as i64;
220        let div = timing.dot_divider;
221        let first = timing.start_mclk + HSYNC_CLOCKS;
222        let end = first + LINE_CLOCKS;
223        let mut used = 0;
224        while used < self.log.len() && self.log[used].0 < end {
225            used += 1;
226        }
227        let mut out = Vec::with_capacity(vdc1.len());
228        if used == 0 {
229            self.span(&mut out, vdc1, vdc2, 0, dots, div);
230            return out;
231        }
232        let mut x = 0;
233        for index in 0..used {
234            let (when, reg, value) = self.log[index];
235            // ceil((when - first) / div)
236            let stop = dots.min(x.max(-py_floordiv(first - when, div)));
237            if stop > x {
238                self.span(&mut out, vdc1, vdc2, x, stop, div);
239                x = stop;
240            }
241            self.replay(reg, value);
242        }
243        self.span(&mut out, vdc1, vdc2, x, dots, div);
244        self.log.drain(..used);
245        out
246    }
247
248    fn replay(&mut self, reg: u8, value: u8) {
249        match reg {
250            PRIORITY_A => self.shadow_priority[0] = value,
251            PRIORITY_B => self.shadow_priority[1] = value,
252            WINDOW1_LSB => self.shadow_window[0] = (self.shadow_window[0] & 0x300) | value as u16,
253            WINDOW1_MSB => {
254                self.shadow_window[0] = (self.shadow_window[0] & 0x0FF) | ((value as u16 & 3) << 8)
255            }
256            WINDOW2_LSB => self.shadow_window[1] = (self.shadow_window[1] & 0x300) | value as u16,
257            _ => {
258                self.shadow_window[1] = (self.shadow_window[1] & 0x0FF) | ((value as u16 & 3) << 8)
259            }
260        }
261    }
262
263    /// The first row dot outside a window of register value `width` (0 = no window).
264    pub fn window_edge(&self, width: u16, div: i64, dots: i64) -> i64 {
265        let width = width as i64;
266        if width <= self.window_off_at_or_below {
267            return 0;
268        }
269        dots.min(width - 0x40 + self.window_origin.of(div))
270    }
271
272    /// The 4-bit group for a window area, from the registers as the line has replayed them.
273    pub fn region_config(&self, in_window1: bool, in_window2: bool) -> u8 {
274        let [a, b] = self.shadow_priority;
275        match (in_window1, in_window2) {
276            (true, true) => a & 0x0F,
277            (false, true) => a >> 4,
278            (true, false) => b & 0x0F,
279            (false, false) => b >> 4,
280        }
281    }
282
283    fn span(&self, out: &mut Vec<u16>, vdc1: &[u16], vdc2: &[u16], x0: i64, x1: i64, div: i64) {
284        let dots = vdc1.len() as i64;
285        let edge1 = self.window_edge(self.shadow_window[0], div, dots);
286        let edge2 = self.window_edge(self.shadow_window[1], div, dots);
287        // sorted({x0, x1, the edges strictly between them})
288        let mut cuts = vec![x0, x1];
289        for edge in [edge1, edge2] {
290            if x0 < edge && edge < x1 {
291                cuts.push(edge);
292            }
293        }
294        cuts.sort_unstable();
295        cuts.dedup();
296        for pair in cuts.windows(2) {
297            let (lo, hi) = (pair[0], pair[1]);
298            let cfg = self.region_config(lo < edge1, lo < edge2);
299            let (lo, hi) = (lo as usize, hi as usize);
300            self.mix_run(out, &vdc1[lo..hi], &vdc2[lo..hi], cfg);
301        }
302    }
303
304    /// One window area: `cfg` bit 0 enables VDC 1, bit 1 VDC 2, bits 3-2 the priority code.
305    fn mix_run(&self, out: &mut Vec<u16>, a: &[u16], b: &[u16], cfg: u8) {
306        let (enable1, enable2, mut code) = (cfg & 1 != 0, cfg & 2 != 0, (cfg >> 2) & 3);
307        if !enable1 && !enable2 {
308            // [hw: sgxtech] both layers off: colour 0 of the VCE table for every pixel, overscan too
309            out.extend(std::iter::repeat_n(0, a.len()));
310            return;
311        }
312        if !enable2 {
313            out.extend_from_slice(a);
314            return;
315        }
316        if !enable1 {
317            out.extend_from_slice(b);
318            return;
319        }
320        if (code == 1 || code == 2) && self.priority_labels == PriorityLabels::Sgxtech {
321            code = 3 - code;
322        }
323        let pairs = a.iter().zip(b.iter());
324        if code == 1 {
325            // VDC 2 sprites in front of the VDC 1 background, behind VDC 1 sprites
326            out.extend(pairs.map(|(&p, &q)| {
327                if q & SPRITE != 0 && p & SPRITE == 0 && q & COLOUR != 0 {
328                    q
329                } else if p & COLOUR != 0 {
330                    p
331                } else {
332                    q
333                }
334            }));
335        } else if code == 2 {
336            // VDC 1 sprites behind the VDC 2 background (they stay in front of VDC 2 sprites)
337            out.extend(pairs.map(|(&p, &q)| {
338                if p & SPRITE != 0 && q & SPRITE == 0 && q & COLOUR != 0 {
339                    q
340                } else if p & COLOUR != 0 {
341                    p
342                } else {
343                    q
344                }
345            }));
346        } else {
347            // 00b and 11b: VDC 1 over VDC 2 wherever VDC 1 is opaque
348            out.extend(pairs.map(|(&p, &q)| if p & COLOUR != 0 { p } else { q }));
349        }
350    }
351}
352
353/// What of the VPC and the page is in a save state (the reference's walk of both objects).
354#[derive(Serialize, Deserialize)]
355struct State {
356    priority: [u8; 2],
357    window: [u16; 2],
358    st_to_vdc2: bool,
359    shadow_priority: [u8; 2],
360    shadow_window: [u16; 2],
361    log: Vec<(i64, u8, u8)>,
362    compat: bool,
363}
364
365/// The video chip area, `$FF:0000-03FF` (four 256-byte pages): what the VPC decodes.
366///
367/// Native mode [hw: sgxtech, "HuC6280 memory map"], a 32-byte block repeated through the 1 KiB:
368///
369/// ```text
370///     $00-$03 VDC 1   $04-$07 VDC 1 (mirror)   $08-$0F VPC   $10-$13 VDC 2
371///     $14-$17 VDC 2 (mirror)   $18-$1F unused, reads $FF
372/// ```
373///
374/// PC Engine compatibility mode (the switch on the back): VDC 1 alone, mirrored every 4 bytes, as
375/// on a PC Engine, for games that use those mirrors. Whether the CPU's current write is an
376/// `ST0`/`ST1`/`ST2` is `pins.opcode` (the VPC sees the instruction, not the address).
377///
378/// This is the board's `PixelPath`: the mix is `vpc`'s.
379#[derive(Clone, Debug, PartialEq, Eq)]
380pub struct VideoPage {
381    pub vpc: Vpc,
382    /// The back-panel switch: `true` is the PC Engine position.
383    pub compat: bool,
384    /// U-SGX4: whether `ST0`-`ST2` still follow `$0E` bit 0 with the switch in compatibility mode.
385    /// `$0E` cannot be written in that mode (it is a VDC 1 mirror), so the bit is only ever left
386    /// over from native mode; nothing documents it. Default: no steering in compatibility mode.
387    pub st_steers_in_compat: bool,
388}
389
390impl VideoPage {
391    pub fn new(vpc: Vpc, compat: bool) -> VideoPage {
392        VideoPage {
393            vpc,
394            compat,
395            st_steers_in_compat: false,
396        }
397    }
398}
399
400impl DeviceState for VideoPage {
401    fn save_state(&self) -> Vec<u8> {
402        let vpc = &self.vpc;
403        bincode::serialize(&State {
404            priority: vpc.priority,
405            window: vpc.window,
406            st_to_vdc2: vpc.st_to_vdc2,
407            shadow_priority: vpc.shadow_priority,
408            shadow_window: vpc.shadow_window,
409            log: vpc.log.clone(),
410            compat: self.compat,
411        })
412        .expect("the VPC's state serialises")
413    }
414
415    fn load_state(&mut self, data: &[u8]) -> Result<(), String> {
416        let state: State =
417            bincode::deserialize(data).map_err(|error| format!("the VPC's state: {error}"))?;
418        let vpc = &mut self.vpc;
419        vpc.priority = state.priority;
420        vpc.window = state.window;
421        vpc.st_to_vdc2 = state.st_to_vdc2;
422        vpc.shadow_priority = state.shadow_priority;
423        vpc.shadow_window = state.shadow_window;
424        vpc.log = state.log;
425        self.compat = state.compat;
426        Ok(())
427    }
428
429    fn state_identity(&self) -> String {
430        "supergrafx_rust VideoPage (HuC6202 VPC)".to_string()
431    }
432}
433
434impl PixelPath for VideoPage {
435    fn mix(&mut self, timing: &VideoTiming, rows: Vec<Vec<u16>>) -> Vec<u16> {
436        self.vpc.mix(timing, &rows)
437    }
438
439    /// The VPC decodes the whole 1 KiB video chip area: four pages of the hardware page.
440    fn claims(&self) -> Vec<(usize, usize)> {
441        vec![(HARDWARE_FIRST_PAGE, HARDWARE_FIRST_PAGE + 3)]
442    }
443
444    fn read(&mut self, address: u32, mclk: i64, pins: &mut BoardPins) -> u8 {
445        if self.compat {
446            return pins.vdc_read(0, address & 3, mclk);
447        }
448        let offset = address & 0x1F;
449        if offset < 0x08 {
450            pins.vdc_read(0, offset & 3, mclk)
451        } else if offset < 0x10 {
452            self.vpc.read(offset)
453        } else if offset < 0x18 {
454            pins.vdc_read(1, offset & 3, mclk)
455        } else {
456            0xFF
457        }
458    }
459
460    fn write(&mut self, address: u32, value: u8, mclk: i64, pins: &mut BoardPins) {
461        let steered = self.vpc.st_to_vdc2 && (self.st_steers_in_compat || !self.compat);
462        if steered && ST_OPCODES.contains(&pins.opcode) {
463            pins.vdc_write(1, address & 3, value, mclk);
464            return;
465        }
466        if self.compat {
467            pins.vdc_write(0, address & 3, value, mclk);
468            return;
469        }
470        let offset = address & 0x1F;
471        if offset < 0x08 {
472            pins.vdc_write(0, offset & 3, value, mclk);
473        } else if offset < 0x10 {
474            self.vpc.write(offset, value, mclk);
475        } else if offset < 0x18 {
476            pins.vdc_write(1, offset & 3, value, mclk);
477        }
478    }
479
480    /// The reference's `SuperGrafx.reset`, after the board's own: a power-on resets the VPC.
481    fn reset(&mut self, kind: ResetKind, _pins: &mut BoardPins) {
482        if kind == ResetKind::PowerOn {
483            self.vpc.reset();
484        }
485    }
486
487    fn as_any_mut(&mut self) -> &mut dyn Any {
488        self
489    }
490}