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