pcengine_rust/vdc/
sprites.rs

1//! Sprites: the line scan of the sprite attribute table, and the drawing of the line's sprites
2//! (`vdc/sprites.py`).
3//!
4//! [hw: pcetech 5.3; mfr: Hudson HuC6270 manual] The 64-entry table (SAT, filled only by the VRAM ->
5//! SAT DMA) holds, per sprite: Y (10 bits, the first visible line is 64), X (10 bits, 32 is the
6//! display's left edge), pattern (bits 10-1; bit 0 is the CG bit), and flags: palette (3-0), priority
7//! (7), width 16/32 (8), flip X (11), height 16/32/64 (13-12), flip Y (15). A pattern is 16 x 16
8//! pixels = 64 words, four planes of 16 words. Larger sprites use neighbouring patterns: width 32
9//! clears pattern bit 0, height 32 clears bit 1, height 64 clears bits 2 and 1; flips act on the whole
10//! sprite.
11//!
12//! Per line the scan finds the sprites that cover the *next* line, in table order, up to 16 pattern
13//! entries (a 32-wide sprite is two entries); a 17th needed entry sets the overflow flag and ends the
14//! scan. The first opaque pixel in buffer order wins; a pixel is in front of the background if its
15//! priority bit is set or the background pixel is transparent; sprite 0 colliding with another
16//! sprite's opaque pixel sets the collision flag. When MWR's sprite access width is 1 the pattern
17//! is two bitplanes, picked by the CG bit (SP0/SP1 or SP2/SP3).
18//!
19//! Provisional (U3, tier 5): that the scan reads the pattern words when it finds the sprite (the
20//! line before it is drawn), as Mednafen does; the narrow-display budget below is Mesen2's.
21
22use serde::{Deserialize, Serialize};
23
24pub const HEIGHTS: [i64; 4] = [16, 32, 64, 64];
25pub const HEIGHT_MASKS: [u32; 4] = [!0, !2, !6, !6];
26/// [mfr: SM table; emu: Mesen2] dots of fetch time per entry
27pub const CLOCKS_PER_SPRITE: [i64; 4] = [4, 4, 8, 16];
28
29pub const SPRITE_LIMIT: usize = 16;
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
32pub struct Entry {
33    /// left pixel, in display columns (may be negative or past the width)
34    pub x: i64,
35    /// palette << 4
36    pub palette: u16,
37    pub priority: bool,
38    pub hflip: bool,
39    pub sprite0: bool,
40    pub planes: [u16; 4],
41}
42
43/// The entries of sprites covering `line` (counted from the first display line), and whether
44/// a 17th entry was needed (overflow).
45pub fn scan(
46    vram: &[u16],
47    size: usize,
48    sat: &[u16],
49    line: i64,
50    mwr: u16,
51    limit: usize,
52) -> (Vec<Entry>, bool) {
53    let mut entries: Vec<Entry> = Vec::new();
54    let overflow = scan_into(&mut entries, vram, size, sat, line, mwr, limit);
55    (entries, overflow)
56}
57
58/// `scan` into a list the caller keeps (emptied first); returns the overflow.
59pub fn scan_into(
60    entries: &mut Vec<Entry>,
61    vram: &[u16],
62    size: usize,
63    sat: &[u16],
64    line: i64,
65    mwr: u16,
66    limit: usize,
67) -> bool {
68    entries.clear();
69    let cg_two_planes = ((mwr >> 2) & 3) == 1;
70    for i in 0..64 {
71        let (w0, w1, w2, w3) = (sat[4 * i], sat[4 * i + 1], sat[4 * i + 2], sat[4 * i + 3]);
72        let y = (w0 & 0x3FF) as i64 - 64;
73        let shape = ((w3 >> 12) & 3) as usize;
74        let height = HEIGHTS[shape];
75        if !(y..y + height).contains(&line) {
76            continue;
77        }
78        let wide = w3 & 0x100 != 0;
79        let hflip = w3 & 0x800 != 0;
80        let mut row = line - y;
81        if w3 & 0x8000 != 0 {
82            row = height - 1 - row;
83        }
84        let row = row as u32;
85        let mut pattern = ((w2 as u32 >> 1) & 0x3FF) & HEIGHT_MASKS[shape];
86        pattern |= (row & 0x30) >> 3;
87        if wide {
88            pattern &= !1;
89        }
90        let base_x = (w1 & 0x3FF) as i64 - 32;
91        for half in 0..(if wide { 2u32 } else { 1 }) {
92            if entries.len() == SPRITE_LIMIT {
93                // [mfr] "17 or more": the rest of the scan is dropped
94                entries.truncate(limit);
95                return true;
96            }
97            let cell = pattern | if wide { half ^ hflip as u32 } else { 0 };
98            let address = (cell * 64 + (row & 15)) as usize;
99            let planes = if address + 48 >= size {
100                // [emu: Mesen2] an empty sprite past the VRAM; U23
101                [0, 0, 0, 0]
102            } else if cg_two_planes {
103                let shift = if w2 & 1 != 0 { 32 } else { 0 };
104                [vram[address + shift], vram[address + shift + 16], 0, 0]
105            } else {
106                [
107                    vram[address],
108                    vram[address + 16],
109                    vram[address + 32],
110                    vram[address + 48],
111                ]
112            };
113            entries.push(Entry {
114                x: base_x + 16 * half as i64,
115                palette: (w3 & 0xF) << 4,
116                priority: w3 & 0x80 != 0,
117                hflip,
118                sprite0: i == 0,
119                planes,
120            });
121        }
122    }
123    entries.truncate(limit);
124    false
125}
126
127/// Draw the entries over `row` (the line's 9-bit pixels; the display starts at index `first`).
128///
129/// Returns the display column of the first pixel where sprite 0 hit another sprite, or None.
130pub fn draw(entries: &[Entry], width: i64, row: &mut [u16], first: usize) -> Option<i64> {
131    let mut buffer = vec![0u16; width.max(0) as usize];
132    let mut hit: Option<i64> = None;
133    for entry in entries.iter().rev() {
134        let [p0, p1, p2, p3] = entry.planes;
135        for x in 0..16i64 {
136            let column = entry.x + x;
137            if !(0..width).contains(&column) {
138                continue;
139            }
140            let bit = if entry.hflip { x } else { 15 - x };
141            let raw = ((p0 >> bit) & 1)
142                | (((p1 >> bit) & 1) << 1)
143                | (((p2 >> bit) & 1) << 2)
144                | (((p3 >> bit) & 1) << 3);
145            if raw == 0 {
146                continue;
147            }
148            let slot = &mut buffer[column as usize];
149            if entry.sprite0 && *slot & 0x0F != 0 && hit.is_none_or(|h| column < h) {
150                hit = Some(column);
151            }
152            *slot = 0x100 | entry.palette | raw | if entry.priority { 0x200 } else { 0 };
153        }
154    }
155    for (column, &value) in buffer.iter().enumerate() {
156        if value & 0x0F != 0 {
157            let target = first + column;
158            if row[target] & 0x0F == 0 || value & 0x200 != 0 {
159                row[target] = value & 0x1FF;
160            }
161        }
162    }
163    hit
164}