pcengine_rust/vdc/
background.rs

1//! The background layer: one line of 9-bit pixels from the BAT and the character generator
2//! (`vdc/background.py`).
3//!
4//! [hw: pcetech 5.2; mfr: Hudson HuC6270 manual] Tiles are 8x8, 4 bits per pixel, planar: 16 words
5//! per tile, word `y` holds bitplanes 0 (low byte) and 1 (high byte) of line `y`, word `y + 8`
6//! bitplanes 2 and 3. The BAT starts at VRAM word 0, one word per tile `ppppnnnnnnnnnnnn`: palette
7//! and name, no flips and no priority. Only names 0-2047 exist in 64 KiB of VRAM; the rest read as
8//! 0 here (U23).
9//!
10//! The line is drawn in one go when the display width begins, from the scroll registers latched a few
11//! dots earlier, as Mednafen does (tier 5, U3); a VRAM change during the line shows on the next one.
12//!
13//! Differences forced by Rust: none in behaviour. The reference's per-instance decode cache (a
14//! dict that only saves PyPy time) is not carried over; the eight pixels are decoded each time.
15
16pub const BAT_WIDTHS: [usize; 4] = [32, 64, 128, 128]; // MWR D5-D4 [hw: pcetech 5.1 $09]
17pub const BAT_SHIFTS: [u32; 4] = [5, 6, 7, 7];
18pub const BAT_HEIGHTS: [i64; 2] = [32, 64]; // MWR D6
19
20#[inline]
21fn decode(w0: u16, w1: u16, mask: u16, x: u32) -> u16 {
22    let bit = 7 - x;
23    (((w0 >> bit) & 1)
24        | (((w0 >> (8 + bit)) & 1) << 1)
25        | (((w1 >> bit) & 1) << 2)
26        | (((w1 >> (8 + bit)) & 1) << 3))
27        & mask
28}
29
30/// `width` pixels, each `palette << 4 | colour`; colour 0 is transparent.
31pub fn row(
32    vram: &[u16],
33    size: usize,
34    mwr: u16,
35    x_offset: i64,
36    y_offset: i64,
37    width: i64,
38) -> Vec<u16> {
39    let shape = ((mwr >> 4) & 3) as usize;
40    let bat_mask = BAT_WIDTHS[shape] - 1;
41    let bat_row = (((y_offset >> 3) & (BAT_HEIGHTS[((mwr >> 6) & 1) as usize] - 1)) as usize)
42        << BAT_SHIFTS[shape];
43    let line = (y_offset & 7) as usize;
44    // [hw: pcetech 5.2] MWR D1-D0 = 3 is the one-bitplane-pair mode: D7 picks planes 0/1 or
45    // 2/3 and the other pair reads as zero.
46    let mut mask = 0x0F;
47    if mwr & 3 == 3 {
48        mask = if mwr & 0x80 != 0 { 0x0C } else { 0x03 };
49    }
50    let width = width.max(0) as usize;
51    let mut out: Vec<u16> = Vec::with_capacity(width + 8);
52    let mut skip = (x_offset & 7) as u32;
53    let mut column = ((x_offset >> 3) as usize) & bat_mask;
54    while out.len() < width {
55        let bat = vram[bat_row | column];
56        let base = (bat & 0xFFF) as usize * 16 + line;
57        let w0 = if base < size { vram[base] } else { 0 };
58        let w1 = if base + 8 < size { vram[base + 8] } else { 0 };
59        let palette = (bat >> 8) & 0xF0;
60        for x in skip..8 {
61            out.push(palette | decode(w0, w1, mask, x));
62        }
63        skip = 0;
64        column = (column + 1) & bat_mask;
65    }
66    out.truncate(width);
67    out
68}