Skip to main content

rustyn64_rdp/
lib.rs

1//! `rustyn64-rdp` — RDP (Reality Display Processor), the RCP rasterizer.
2//!
3//! The RDP consumes a command stream (from the RSP or the CPU via the DP FIFO)
4//! and rasterizes triangles/rectangles into a framebuffer in RDRAM, running the
5//! color-combiner + blender + Z/coverage pipeline. The Video Interface (VI)
6//! then scans that framebuffer out. The accuracy bar is **LLE** — a faithful
7//! per-pixel pipeline (the ParaLLEl-RDP / angrylion reference), not a
8//! triangle-list HLE.
9//!
10//! [`Rdp::tick`] decodes the DP FIFO — recognizing every command `0x00`–`0x3F`
11//! and consuming each one's full length (via [`command`]) so the stream stays
12//! aligned — and dispatches the sync commands and the **FILL pipeline** (Set
13//! Color Image, Set Fill Color, Set Scissor, Fill Rectangle), which writes solid
14//! rectangles into the framebuffer. The rest of the rasterizer (edge-walked
15//! triangles, the texture engine with TMEM, the combiner/blender, dithering,
16//! coverage AA) is the remainder of this roadmap phase.
17//!
18//! Part of the one-directional chip-crate graph (see `docs/architecture.md`):
19//! this crate depends on **exactly one** chip crate, `rustyn64-cart`, purely for
20//! its [`RdramBus`] memory-bus trait — the RDP reads texture and framebuffer
21//! reaches its tile storage through `rustynes-mappers`. `#![no_std]` + `alloc`.
22
23#![no_std]
24#![forbid(unsafe_code)]
25#![warn(missing_docs)]
26#![allow(clippy::cast_possible_truncation, clippy::cast_lossless)]
27// Skeleton `tick` is deliberately non-`const` (it will drain the DP FIFO).
28#![allow(clippy::missing_const_for_fn)]
29
30extern crate alloc;
31
32pub mod command;
33
34pub use rustyn64_cart::RdramBus;
35
36use serde::{Deserialize, Serialize};
37
38/// The narrow bus the RDP sees.
39///
40/// RDRAM access (for the framebuffer + texture fetches) plus the
41/// DP-interrupt-raise hook. Extends [`RdramBus`] (`RustyNES`'s `PpuBus` analog)
42/// with the IRQ notify the rasterizer needs on `SYNC_FULL` / DP-done.
43pub trait VideoBus: RdramBus {
44    /// Raise the DP (RDP-done) interrupt on the MI. Default no-op for ad-hoc
45    /// test buses; `rustyn64-core` sets the live `MI_INTR.dp` line.
46    fn raise_dp_interrupt(&mut self) {}
47}
48
49/// One RGBA8888 output pixel (post-VI-filter); the framebuffer the frontend
50/// presents is a slice of these.
51pub type Pixel = u32;
52
53/// `DPC_STATUS.XBUS` — the DP reads commands from DMEM rather than RDRAM.
54pub const DP_STATUS_XBUS: u32 = 0x1;
55/// `DPC_STATUS.FREEZE` — the DP is halted; registers can be read/written freely
56/// without the command FIFO advancing.
57pub const DP_STATUS_FREEZE: u32 = 0x2;
58/// `DPC_STATUS.END_VALID` (the wiki's `END_PENDING`, read bit 9) — an end
59/// address is latched behind an in-flight transfer.
60///
61/// Defined for the read-back layout but **not yet driven**: setting it requires
62/// tracking a transfer *in progress*, which only exists once the rasterizer
63/// runs (`tick` is a stub). It therefore always reads 0 today, which is exactly
64/// what n64-systemtest's frozen `start-valid` case expects; the set/clear
65/// transition lands with the FIFO drain.
66pub const DP_STATUS_END_VALID: u32 = 0x200;
67/// `DPC_STATUS.START_VALID` — a start address is latched and pending; further
68/// writes to `DPC_START` are ignored until it is consumed by a `DPC_END` write.
69pub const DP_STATUS_START_VALID: u32 = 0x400;
70
71/// The `DPC_START`/`DPC_END` register mask: a 24-bit, 8-byte-aligned RDRAM
72/// address (n64-systemtest's `RDP START & END REG (masking)`).
73pub const DPC_ADDR_MASK: u32 = 0x00FF_FFF8;
74
75/// `Sync Load` (0x26) pipeline stall, in GCLK cycles.
76///
77/// Fixed and unconditional — the RDP always stalls this long, whether or not a
78/// load is in flight (N64brew *Reality Display Processor/Commands* §0x26). One
79/// `tick` is one GCLK.
80pub const SYNC_LOAD_GCLK: u32 = 25;
81
82// `Set Other Modes.cycle_type` (command bits 53:52 = word-0 bits 21:20).
83// Provenance: N64brew *Reality Display Processor/Commands* §0x2F – Set Other
84// Modes, the `bit 53:52` row — *"cycle_type[1:0]: Determines pipeline mode.
85// Either 1-Cycle (0), 2-Cycle (1), COPY (2), FILL (3)"*. Which of these read the
86// fill register rather than the combiner is ledger **R-21**.
87
88/// `Set Other Modes.cycle_type` value for **1-cycle** mode — the default
89/// pipeline: one combiner pass per pixel.
90pub const CYCLE_TYPE_1CYCLE: u8 = 0;
91
92/// `Set Other Modes.cycle_type` value for **2-cycle** mode — two combiner passes
93/// per pixel, so a second texel and the LOD fraction become available.
94pub const CYCLE_TYPE_2CYCLE: u8 = 1;
95
96/// `Set Other Modes.cycle_type` value for **copy** mode — a raw texel blit that
97/// bypasses the combiner and blender entirely.
98pub const CYCLE_TYPE_COPY: u8 = 2;
99
100/// `Set Other Modes.cycle_type` value for **fill** mode — the `Set Fill Color`
101/// register is repeated verbatim to memory, bypassing the combiner and blender.
102pub const CYCLE_TYPE_FILL: u8 = 3;
103
104/// `Sync Pipe` (0x27) pipeline stall, in GCLK cycles.
105///
106/// Fixed and unconditional (N64brew *…/Commands* §0x27).
107pub const SYNC_PIPE_GCLK: u32 = 50;
108/// `Sync Tile` (0x28) pipeline stall, in GCLK cycles.
109///
110/// Fixed and unconditional (N64brew *…/Commands* §0x28).
111pub const SYNC_TILE_GCLK: u32 = 33;
112
113// RDP command opcodes handled by the dispatcher (bits 61:56 of a command word).
114const OP_SYNC_LOAD: u8 = 0x26;
115const OP_SYNC_PIPE: u8 = 0x27;
116const OP_SYNC_TILE: u8 = 0x28;
117const OP_SYNC_FULL: u8 = 0x29;
118const OP_TEXTURE_RECTANGLE: u8 = 0x24;
119const OP_TEXTURE_RECTANGLE_FLIP: u8 = 0x25;
120const OP_SET_SCISSOR: u8 = 0x2D;
121const OP_LOAD_TLUT: u8 = 0x30;
122const OP_SET_TILE_SIZE: u8 = 0x32;
123const OP_LOAD_BLOCK: u8 = 0x33;
124const OP_LOAD_TILE: u8 = 0x34;
125const OP_SET_TILE: u8 = 0x35;
126
127/// TMEM byte offset of the high (palette / split-high) half.
128const TMEM_HIGH: u32 = 0x800;
129
130/// Sign-extend the low 16 bits of `v` to `i32` (for the `s10.5` `S`/`T` and the
131/// `s5.10` `DsDx`/`DtDy`). `v as i16` already keeps only the low 16 bits.
132const fn sext16(v: u32) -> i32 {
133    v as i16 as i32
134}
135
136/// Sign-extend the low `bits` bits of `v` to `i32` (for the triangle edge fields:
137/// `yh/ym/yl` are 14-bit `s11.2`, `xh/xm/xl` 28-bit `s11.16`, the slopes 30-bit).
138#[allow(clippy::cast_possible_wrap)] // the reinterpret-as-signed IS the sign extension
139const fn sext(v: u32, bits: u32) -> i32 {
140    debug_assert!(bits >= 1 && bits <= 32, "sext width out of range");
141    let shift = 32 - bits;
142    ((v << shift) as i32) >> shift
143}
144
145/// Sign-extend the low 9 bits of `x` (the combiner's `bitfieldExtract(x, 0, 9)`).
146///
147/// Only bits 0–8 are used: the `<< 23` shifts bit 8 to the sign position and the
148/// arithmetic `>> 23` fills from it, so any higher bits of `x` are discarded.
149const fn sext9(x: i32) -> i32 {
150    (x << 23) >> 23
151}
152
153/// Position of the most significant set bit of `x`, or `-1` for `x <= 0` — GLSL
154/// `findMSB` semantics for the non-negative inputs this codec uses (`z_encode.h`).
155/// All callers here pass non-negative magnitudes; the `-1` result flows through
156/// `max(findMSB(dz), 0)` in [`dz_compress`], and [`combine_dz`] guards on it so a
157/// non-positive input can never reach the negative shift (GLSL's signed `findMSB`
158/// differs for genuinely-negative inputs, which do not occur in this domain).
159#[allow(
160    clippy::cast_possible_wrap,
161    reason = "leading_zeros() is 0..=31, always in range for i32"
162)]
163const fn find_msb(x: i32) -> i32 {
164    if x <= 0 {
165        -1
166    } else {
167        31 - (x.leading_zeros() as i32)
168    }
169}
170
171/// Decompress a 14-bit stored depth to an 18-bit UNORM (`0..=0x3_FFFF`). The N64
172/// Z buffer uses an inverted floating-point encoding with more precision near 1
173/// (ParaLLEl-RDP `z_encode.h`): `exponent` in bits 13:11, `mantissa` in 10:0.
174fn z_decompress(z: u16) -> i32 {
175    let z = i32::from(z);
176    let exponent = z >> 11;
177    let mantissa = z & 0x7ff;
178    let shift = (6 - exponent).max(0);
179    let base = 0x4_0000 - (0x4_0000 >> exponent);
180    (mantissa << shift) + base
181}
182
183/// Compress an 18-bit UNORM depth back to the 14-bit stored form (`z_encode.h`).
184/// Inverse of [`z_decompress`]; `exponent` is derived from the leading zeros of
185/// the inverted depth so precision concentrates near the far plane.
186///
187/// Verified by the [`z_decompress`] round-trip test and exercised by
188/// [`Rdp::zbuffer_write`], which compresses the computed 18-bit depth before it is
189/// packed into the Z buffer.
190#[allow(
191    clippy::cast_sign_loss,
192    clippy::cast_possible_truncation,
193    reason = "the packed result is 0..=0x3FFF, always a valid non-negative u16"
194)]
195fn z_compress(z: i32) -> u16 {
196    // Clamp to the 18-bit UNORM domain so the `0x3FFFF - z` subtraction and the
197    // `z >> shift` mantissa are well-defined for any computed depth (parallel-rdp
198    // clamps `z` this way before writeback, `clamping.h`).
199    let z = z.clamp(0, 0x3_FFFF);
200    let inv_z = (0x3_FFFF - z).max(1);
201    let exponent = (17 - find_msb(inv_z)).clamp(0, 7);
202    let shift = (6 - exponent).max(0);
203    let mantissa = (z >> shift) & 0x7ff;
204    ((exponent << 11) + mantissa) as u16
205}
206
207/// Decompress a 4-bit stored `dz` to its linear delta `1 << dz` (`z_encode.h`).
208const fn dz_decompress(dz: i32) -> i32 {
209    1 << dz
210}
211
212/// Compress a linear `dz` delta to its 4-bit `log2` form (`z_encode.h`). The RDP
213/// uses this cheap integer `log2`, correct only for powers of two (hence the
214/// "dz should be a power of 2" hazard); `dz == 0` yields 0 via `find_msb`'s `-1`.
215const fn dz_compress(dz: i32) -> i32 {
216    let m = find_msb(dz);
217    if m < 0 { 0 } else { m }
218}
219
220/// The largest power of two `<= dz` (ParaLLEl-RDP `depth_test.h` `combine_dz`).
221/// Guards on `find_msb(dz) >= 0` rather than `dz != 0` so a non-positive `dz`
222/// returns 0 instead of shifting `1 << -1` (the codec only feeds it non-negative
223/// magnitudes; the guard makes it panic-free for any `i32` regardless).
224const fn combine_dz(dz: i32) -> i32 {
225    let m = find_msb(dz);
226    if m >= 0 { 1 << m } else { 0 }
227}
228
229/// Interpolate the per-pixel depth (18-bit UNORM, `0..=0x3_FFFF`) for pixel
230/// `(x, y)` from the triangle's z-coefficients — a faithful port of ParaLLEl-RDP's
231/// `interpolate_z` (`interpolation.h`) for the full-coverage, `do_offset == false`
232/// case (sub-pixel coverage snapping is the deferred R-9 residual).
233///
234/// `z_base`/`dzdx`/`dzde` are the `s15.16` z-coefficient and its per-x / per-major-
235/// edge deltas; `major_x` is the `s15.16` major-edge x at this scanline (its
236/// integer part is the interpolation origin, its `xfrac` aligns to the edge);
237/// `y_base` is the top scanline. 32-bit wrapping matches the reference's `int`
238/// arithmetic; the final `clamp_z` bounds the result to the depth range.
239#[allow(
240    clippy::cast_possible_truncation,
241    reason = "major_x fields and the clamped result are within range for the casts"
242)]
243#[allow(
244    clippy::similar_names,
245    reason = "dzdx / dzde are the N64 RDP's own z-coefficient names"
246)]
247fn interpolate_z(
248    z_base: i32,
249    dzdx: i32,
250    dzde: i32,
251    major_x: i64,
252    y: i32,
253    y_base: i32,
254    x: i32,
255) -> i32 {
256    let base_x = (major_x >> 16) as i32;
257    let xfrac = ((major_x >> 8) & 0xff) as i32;
258    let mut z = z_base.wrapping_add(dzde.wrapping_mul(y.wrapping_sub(y_base)));
259    z = ((z & !0x1ff).wrapping_sub(xfrac.wrapping_mul((dzdx >> 8) & !1))) & !0x3ff;
260    z = z.wrapping_add(dzdx.wrapping_mul(x.wrapping_sub(base_x)));
261    // Snap (full coverage: the first-subpixel xoff/yoff terms are 0).
262    let snapped = ((z >> 10) << 2) >> 5;
263    snapped.clamp(0, 0x3_FFFF)
264}
265
266/// Interpolate the per-pixel shade color for pixel `(x, y)` from a triangle's
267/// shade coefficients — a port of ParaLLEl-RDP's `interpolate_rgba`
268/// (`interpolation.h`) for the full-coverage case. `base`/`dx`/`de` are the `s15.16`
269/// RGBA base and its per-x / per-major-edge deltas; `base_x` is the major-edge x
270/// integer at this scanline. Each channel: walk the scanline base by `de`, add the
271/// per-x `dx` term (masked `& ~0x1f`), snap `>> 14 << 2 >> 4`, and clamp to a byte.
272#[allow(
273    clippy::cast_possible_truncation,
274    reason = "base_x derives from the s15.16 major-edge x, in range for the cast"
275)]
276fn interpolate_shade(
277    base: &[i32; 4],
278    dx: &[i32; 4],
279    de: &[i32; 4],
280    major_x: i64,
281    y: i32,
282    y_base: i32,
283    x: i32,
284) -> [u8; 4] {
285    let base_x = (major_x >> 16) as i32;
286    let mut out = [0u8; 4];
287    for (c, o) in out.iter_mut().enumerate() {
288        let scan = base[c].wrapping_add(de[c].wrapping_mul(y.wrapping_sub(y_base)));
289        let v = scan.wrapping_add((dx[c] & !0x1f).wrapping_mul(x.wrapping_sub(base_x)));
290        // The snap is done in i16, matching the oracle's `i16x4(rgba >> 14)` cast
291        // (`interpolation.h`) — the truncation to 16 bits is part of the hardware
292        // result, and it keeps the `<< 2` off the i32 sign bit.
293        let snapped = (((v >> 14) as i16).wrapping_shl(2) >> 4).into();
294        *o = clamp_9bit(snapped);
295    }
296    out
297}
298
299/// The raw `S`/`T`/`W` accumulators for pixel `(x, y)`, **before** the `>> 16` and
300/// the (non-)perspective divide: walk the `s16.16` `S`/`T`/`W` by `de` down the
301/// scanline and `dx` across (`interpolation.h`).
302///
303/// Kept separate from [`divide_stw`] so the LOD (R-13) can tap this same
304/// accumulator and step it by `dx`/`dy` without re-deriving the scanline walk;
305/// `divide_stw(interpolate_stw_raw(..), persp)` is the plain per-pixel coordinate.
306#[allow(
307    clippy::cast_possible_truncation,
308    reason = "base_x is in range for the cast"
309)]
310fn interpolate_stw_raw(tex: &TexSetup, major_x: i64, y: i32, y_base: i32, x: i32) -> [i32; 3] {
311    let base_x = (major_x >> 16) as i32;
312    let mut stw = [0i32; 3];
313    for (c, o) in stw.iter_mut().enumerate() {
314        let scan = tex.base[c].wrapping_add(tex.de[c].wrapping_mul(y.wrapping_sub(y_base)));
315        *o = scan.wrapping_add((tex.dx[c] & !0x1f).wrapping_mul(x.wrapping_sub(base_x)));
316    }
317    stw
318}
319
320/// Take the integer part of the raw accumulators and run the (non-)perspective
321/// divide: `no_perspective_divide` is just `(s, t)`; the perspective path divides
322/// by `W`.
323///
324/// Returns the raw **`s10.5`** coordinate (the 5 low bits are the sub-texel
325/// fraction), *before* the tile transform: the caller runs [`sample_coord`]
326/// (shift / tile-origin subtraction / clamp / mask) to turn it into the
327/// tile-relative integer texel. Keeping the fraction here is what lets the shift
328/// and the tile-size clamp operate on the true coordinate (ledger R-13).
329#[allow(
330    clippy::tuple_array_conversions,
331    reason = "the perspective divide's (s, t) is packed into the coord array"
332)]
333fn divide_stw(stw: [i32; 3], persp: bool) -> [i32; 2] {
334    let (s, t, w) = (stw[0] >> 16, stw[1] >> 16, stw[2] >> 16);
335    if persp {
336        let (s, t) = perspective_divide(s, t, w);
337        [s, t]
338    } else {
339        [s, t]
340    }
341}
342
343/// Map a raw `s10.5` texture coordinate to a tile-relative **integer texel** for
344/// the point-sampled 1-cycle path: shift, tile-origin subtraction, **clamp**, then
345/// mask/mirror — the sampler order (ParaLLEl-RDP `tcshift_cycle` → `TRELATIVE` →
346/// `tcclamp_cycle_light` → `tcmask`; ledger R-13). Differs from the COPY-mode
347/// [`wrap_coord`] only by the clamp, which sits *between* the subtraction and the
348/// mask — masking first would corrupt the clamp's over-max / negative detection.
349///
350/// `lo`/`hi` are the tile's `SL`/`SH` (or `TL`/`TH`) `Set Tile Size` fields
351/// (`u10.2`). The over-max test compares against the **raw absolute** `hi`; the
352/// substituted clamp value is the **relative** tile width `(hi>>2) − (lo>>2)`.
353#[allow(
354    clippy::cast_sign_loss,
355    reason = "the texel index is non-negative after the clamp-to-0 and the mask"
356)]
357fn sample_coord(
358    coord: i32,
359    shift: u8,
360    mask: u8,
361    mirror: bool,
362    clamp_en: bool,
363    lo: u16,
364    hi: u16,
365) -> u32 {
366    // Point sampling discards the sub-texel fraction and the neighbor diff, so the
367    // `is_t` argument (which only affects the T-axis neighbor diff) is irrelevant
368    // here — `false` is safe for both axes. The base texel is exactly the bilinear
369    // base (`sample_axis`), so the point and bilinear paths never disagree.
370    sample_axis(coord, shift, mask, mirror, clamp_en, lo, hi, false).0 as u32
371}
372
373/// Shift step of the tile transform (`tcshift_cycle`): codes 0–10 shift right,
374/// 11–15 shift left by `16 − code`, both on the sign-extended `i16`.
375///
376/// The left shift wraps in 16-bit space — a result that overflows `i16` stays
377/// truncated + sign-extended (`SIGN16`), matching `coord <<= (16-shifter);
378/// coord = SIGN16(coord)` (equivalent because the low 16 bits of `coord << n`
379/// depend only on `coord`'s low 16 bits). This is the hardware behavior, NOT a
380/// bug: widening to `i32` before the shift would give a different result.
381fn tile_shift(coord: i32, shift: u8) -> i32 {
382    let shift = shift.min(15); // the hardware shift field is 4 bits
383    if shift < 11 {
384        i32::from(coord as i16) >> shift
385    } else {
386        i32::from((coord as i16).wrapping_shl(u32::from(16 - shift)))
387    }
388}
389
390/// Mask/mirror + neighbor-diff step (`tcmask_coupled`): returns the masked base
391/// texel and the increment (`sdiff`/`tdiff`) to reach the bilinear neighbor. The
392/// neighbor is `base + diff` and is **NOT** re-masked — `diff` is chosen so a plain
393/// add lands on the correct wrapped/mirrored texel: `+1` normally, `0` at a wrap
394/// **seam** (the "duplicate the last texel" quirk), `-base` at a mirror-off period
395/// end (wrap to 0), `-1` on a mirrored half. `mask == 0` ⇒ identity base, `diff = 1`.
396/// `is_t` uses the T max-wrap `-(base & 0xff)` (the fetch masks the T base `& 0xff`).
397fn mask_coupled(mut s: i32, mask: u8, mirror: bool, is_t: bool) -> (i32, i32) {
398    let mask = mask.min(10); // hardware caps the mask width at 10
399    if mask == 0 {
400        return (s, 1);
401    }
402    let maskbits = (1i32 << mask) - 1;
403    if mirror {
404        let wrap = (s >> mask) & 1; // wrapthreshold = mask (mask <= 10)
405        s = (s ^ -wrap) & maskbits; // -wrap = all-ones in the mirrored half → invert
406        let diff = if (s - wrap) & maskbits == maskbits {
407            0 // seam: the neighbor duplicates the last texel
408        } else {
409            1 - (wrap << 1) // +1 in the forward half, -1 in the mirrored half
410        };
411        (s, diff)
412    } else {
413        s &= maskbits;
414        let diff = if s == maskbits {
415            if is_t { -(s & 0xFF) } else { -s } // period end: wrap the neighbor to 0
416        } else {
417            1
418        };
419        (s, diff)
420    }
421}
422
423/// The per-axis tile sampler: map a raw `s10.5` coordinate to `(base_texel, frac,
424/// diff)` via shift → tile-origin subtraction → **clamp** → mask/mirror (the
425/// ParaLLEl-RDP sampler order; ledger R-13). `frac` is the 5-bit sub-texel weight
426/// the bilinear filter uses; per `tcclamp_cycle` it is **zeroed when the coordinate
427/// clamps** (high, or negative), so the filter degenerates to the edge texel there.
428/// `diff` (from [`mask_coupled`]) is the increment to the bilinear neighbor texel.
429/// The point sampler ([`sample_coord`]) drops both `frac` and `diff`.
430///
431/// `lo`/`hi` are the tile's `SL`/`SH` (or `TL`/`TH`) `Set Tile Size` fields
432/// (`u10.2`). The over-max test compares against the **raw absolute** `hi`; the
433/// substituted clamp value is the **relative** tile width `(hi>>2) − (lo>>2)`.
434#[allow(
435    clippy::cast_sign_loss,
436    reason = "the fraction is masked to 5 bits (0..=0x1f), always non-negative"
437)]
438#[allow(
439    clippy::too_many_arguments,
440    reason = "the per-axis tile fields (shift/mask/mirror/clamp/lo/hi) plus coord and is_t"
441)]
442fn sample_axis(
443    coord: i32,
444    shift: u8,
445    mask: u8,
446    mirror: bool,
447    clamp_en: bool,
448    lo: u16,
449    hi: u16,
450    is_t: bool,
451) -> (i32, u32, i32) {
452    let shifted = tile_shift(coord, shift);
453    // Over-max flag against the RAW absolute `hi`, BEFORE the tile-origin subtraction
454    // (`tcshift_cycle` computes it here) — also removes every large positive, so the
455    // `0x10000` sign test below only ever sees the reachable small range.
456    let over_max = (shifted >> 3) >= i32::from(hi);
457    // Tile-origin subtraction (`TRELATIVE`): `SL` (`u10.2`) `<< 3` = the `s.5` scale.
458    let rel = shifted - (i32::from(lo) << 3);
459    let mut frac = (rel & 0x1F) as u32; // 5-bit sub-texel fraction, captured pre-clamp
460    // Clamp — active when the tile clamp bit is set OR `mask == 0`; zeroes `frac`.
461    let base = if clamp_en || mask == 0 {
462        if over_max {
463            frac = 0;
464            // `clampdiffs`: the tile WIDTH in texels, `(SH>>2) − (SL>>2)`.
465            ((i32::from(hi) >> 2) - (i32::from(lo) >> 2)) & 0x3FF
466        } else if rel & 0x1_0000 == 0 {
467            // Non-negative (bit 16 = the RDP's sign marker, `!(locs & 0x10000)`).
468            rel >> 5
469        } else {
470            frac = 0;
471            0 // went below the tile origin: clamp low
472        }
473    } else {
474        rel >> 5
475    };
476    let (masked, diff) = mask_coupled(base, mask, mirror, is_t);
477    (masked, frac, diff)
478}
479
480/// The N64's **3-point (triangular) bilinear** filter: blend the four texels
481/// `t0=(s,t)`, `t1=(s+1,t)`, `t2=(s,t+1)`, `t3=(s+1,t+1)` by the 5-bit `sfrac`,
482/// `tfrac` — a faithful port of ParaLLEl-RDP `texture_pipeline_cycle` (`tex.c`).
483/// `upper = (sfrac + tfrac) & 0x20` selects the triangle: the lower-left uses
484/// `t0,t1,t2`, the upper-right uses `t3,t2,t1` with inverted fractions. Each
485/// channel is a `+0x10 >> 5` round of a convex combination, so it stays in `0..=255`.
486///
487/// When `mid_texel` (Set Other Modes bit 44) is set **and** the sample lands
488/// exactly on the texel center (`sfrac == tfrac == 0x10`), the RDP replaces the
489/// triangle pick with a **four-texel average** (Angrylion `tex.c` `center` case:
490/// `t3 + ((((t1+t2)<<6) − (t3<<7) + ((!t3+t0)<<6) + 0xc0) >> 8)`).
491#[allow(
492    clippy::cast_possible_wrap,
493    clippy::cast_sign_loss,
494    reason = "sfrac/tfrac are 5-bit (0..=0x1f); the convex-combination output is 0..=255"
495)]
496fn bilinear_3point(
497    t0: [u8; 4],
498    t1: [u8; 4],
499    t2: [u8; 4],
500    t3: [u8; 4],
501    sfrac: u32,
502    tfrac: u32,
503    mid_texel: bool,
504) -> [u8; 4] {
505    let (sf, tf) = (sfrac as i32, tfrac as i32);
506    let upper = (sfrac + tfrac) & 0x20 != 0;
507    // The exact-center four-texel average, active only under `mid_texel`.
508    let center = mid_texel && sfrac == 0x10 && tfrac == 0x10;
509    let mut out = [0u8; 4];
510    for x in 0..4 {
511        let (c0, c1, c2, c3) = (
512            i32::from(t0[x]),
513            i32::from(t1[x]),
514            i32::from(t2[x]),
515            i32::from(t3[x]),
516        );
517        let v = if center {
518            // Four-neighbor average (`!c3` = C `~t3`, i.e. `-c3 - 1`).
519            c3 + ((((c1 + c2) << 6) - (c3 << 7) + ((!c3 + c0) << 6) + 0xc0) >> 8)
520        } else if upper {
521            c3 + (((0x20 - sf) * (c2 - c3) + (0x20 - tf) * (c1 - c3) + 0x10) >> 5)
522        } else {
523            c0 + ((sf * (c1 - c0) + tf * (c2 - c0) + 0x10) >> 5)
524        };
525        out[x] = v as u8; // convex combination + round: always 0..=255
526    }
527    out
528}
529
530/// Accumulate one LOD delta pair — a port of Angrylion `tclod_4x17_to_15`
531/// (`tcoord.c`). Each axis' delta is a 17-bit signed difference folded to its
532/// magnitude (`~d & 0x1ffff` when negative); the LOD is the running maximum of
533/// the S delta, the T delta, and `previous`. Bit 14 is the "too large" marker
534/// set when any of bits 16:14 survive.
535fn lod_delta(scurr: i32, snext: i32, tcurr: i32, tnext: i32, previous: i32) -> i32 {
536    let fold = |next: i32, curr: i32| {
537        // Mask to 17 bits first: the masked value is provably non-negative, so
538        // widening it to `sext`'s `u32` cannot lose a sign.
539        let d = sext((next & 0x1_FFFF).cast_unsigned(), 17)
540            - sext((curr & 0x1_FFFF).cast_unsigned(), 17);
541        if d & 0x2_0000 != 0 { !d & 0x1_FFFF } else { d }
542    };
543    let d = fold(snext, scurr).max(fold(tnext, tcurr)).max(previous);
544    let mut lod = d & 0x7FFF;
545    if d & 0x1_C000 != 0 {
546        lod |= 0x4000;
547    }
548    lod
549}
550
551/// `log2table` (Angrylion `tcoord.c`): the index of the highest set bit, with
552/// `0` and `1` both mapping to `0` — i.e. `i.ilog2()` for `i >= 1`.
553const fn lod_log2(i: u32) -> u32 {
554    if i < 2 { 0 } else { i.ilog2() }
555}
556
557/// The four outputs of Angrylion `lodfrac_lodtile_signals` (`tcoord.c`).
558#[derive(Debug, Clone, Copy, PartialEq, Eq)]
559struct LodSignals {
560    /// The LOD fraction, **raw** (`0..=0x1ff`, the `0x100` bit set by
561    /// `sharpen_tex_en`) exactly as the hardware holds it; the combiner
562    /// sign-extends it downstream via `sext9`, matching how `K4`/`K5` are stored
563    /// (ledger R-10).
564    frac: i16,
565    /// The mip level the LOD lands on (`log2` of the LOD's high bits).
566    l_tile: u32,
567    /// The LOD is below the finest level — magnifying rather than minifying.
568    magnify: bool,
569    /// The LOD is past the coarsest available level (or there is no mip chain).
570    distant: bool,
571}
572
573/// Decode an LOD magnitude into its fraction and mip signals — a port of
574/// Angrylion `lodfrac_lodtile_signals` (`tcoord.c`).
575fn lod_signals(
576    lodclamp: bool,
577    lod: i32,
578    min_level: u8,
579    max_level: u8,
580    sharpen: bool,
581    detail: bool,
582) -> LodSignals {
583    // `lod` is a 15-bit magnitude, never negative: its only producer, `lod_delta`,
584    // returns `d & 0x7fff` (optionally `| 0x4000`). That is what makes the bit-14
585    // test below safe on a signed type — the same `int32_t` the oracle uses.
586    debug_assert!((0..=0x7FFF).contains(&lod), "lod is a 15-bit magnitude");
587    let min_level = i32::from(min_level);
588    let plain = !sharpen && !detail; // neither sharpen nor detail texturing
589    if lod & 0x4000 != 0 || lodclamp {
590        // Clamped / too far: pinned to the coarsest level, fully on it.
591        return LodSignals {
592            frac: 0xFF,
593            l_tile: 0,
594            magnify: false,
595            distant: true,
596        };
597    }
598    if lod < min_level || lod < 32 {
599        // Magnifying: `lod` is below the finest level, so there is nothing to
600        // interpolate toward unless sharpen/detail texturing asks for it.
601        let distant = max_level == 0;
602        let frac = if plain {
603            if distant { 0xFF } else { 0 }
604        } else {
605            let base = if lod < min_level { min_level } else { lod };
606            let lf = base << 3;
607            (if sharpen { lf | 0x100 } else { lf }) as i16
608        };
609        return LodSignals {
610            frac,
611            l_tile: 0,
612            magnify: true,
613            distant,
614        };
615    }
616    let l_tile = lod_log2((lod >> 5).cast_unsigned() & 0xFF);
617    let distant = if max_level == 0 {
618        true
619    } else {
620        lod & 0x6000 != 0 || l_tile >= u32::from(max_level)
621    };
622    let frac = if plain && distant {
623        0xFF
624    } else {
625        (((lod << 3) >> l_tile) & 0xFF) as i16
626    };
627    LodSignals {
628        frac,
629        l_tile,
630        magnify: false,
631        distant,
632    }
633}
634
635/// The mip tile pair the LOD selects, when `tex_lod_en` is set — a port of the
636/// tile-selection tail of Angrylion `tclod_2cycle` (`tcoord.c`).
637///
638/// A "distant" LOD pins the level to `max_level`; otherwise it is `l_tile`. The
639/// pair is `(base + level, base + level + 1)` so the two cycles straddle the mip
640/// boundary, collapsing to the same tile where there is nothing to blend toward
641/// (distant, or magnifying without sharpen). Detail texturing shifts both by one.
642/// Every index wraps into the 8 tile descriptors.
643fn lod_mip_tiles(
644    base_tile: usize,
645    sig: LodSignals,
646    max_level: u8,
647    sharpen: bool,
648    detail: bool,
649) -> (usize, usize) {
650    let level = if sig.distant {
651        usize::from(max_level)
652    } else {
653        sig.l_tile as usize
654    };
655    if detail {
656        // Detail texturing samples one level finer than the plain path.
657        // One level finer unless magnifying (`usize::from(bool)` is 1 for true, 0
658        // for false; clippy's `bool_to_int_with_if` requires this form over an `if`).
659        let finer = usize::from(!sig.magnify);
660        let t1 = (base_tile + level + finer) & 7;
661        let t2 = if !sig.distant && !sig.magnify {
662            (base_tile + level + 2) & 7
663        } else {
664            (base_tile + level + 1) & 7
665        };
666        return (t1, t2);
667    }
668    let t1 = (base_tile + level) & 7;
669    // The second tile advances only when there is a coarser level to blend
670    // toward: not when distant, and not when plainly magnifying.
671    let t2 = if sig.distant || (!sharpen && sig.magnify) {
672        t1
673    } else {
674        (t1 + 1) & 7
675    };
676    (t1, t2)
677}
678
679/// The RDP's perspective-divide reciprocal LUT (ParaLLEl-RDP `perspective.h`,
680/// transcribed in its `(base, slope · 4)` source form). Indexed by the top 6 bits
681/// of the normalized `W`; `(base, slope)` give `rcp = ((slope · wnorm) >> 10) + base`.
682#[rustfmt::skip]
683const PERSPECTIVE_TABLE: [(i16, i16); 64] = [
684    (0x4000, -252 * 4), (0x3f04, -244 * 4), (0x3e10, -238 * 4), (0x3d22, -230 * 4),
685    (0x3c3c, -223 * 4), (0x3b5d, -218 * 4), (0x3a83, -210 * 4), (0x39b1, -205 * 4),
686    (0x38e4, -200 * 4), (0x381c, -194 * 4), (0x375a, -189 * 4), (0x369d, -184 * 4),
687    (0x35e5, -179 * 4), (0x3532, -175 * 4), (0x3483, -170 * 4), (0x33d9, -166 * 4),
688    (0x3333, -162 * 4), (0x3291, -157 * 4), (0x31f4, -155 * 4), (0x3159, -150 * 4),
689    (0x30c3, -147 * 4), (0x3030, -143 * 4), (0x2fa1, -140 * 4), (0x2f15, -137 * 4),
690    (0x2e8c, -134 * 4), (0x2e06, -131 * 4), (0x2d83, -128 * 4), (0x2d03, -125 * 4),
691    (0x2c86, -123 * 4), (0x2c0b, -120 * 4), (0x2b93, -117 * 4), (0x2b1e, -115 * 4),
692    (0x2aab, -113 * 4), (0x2a3a, -110 * 4), (0x29cc, -108 * 4), (0x2960, -106 * 4),
693    (0x28f6, -104 * 4), (0x288e, -102 * 4), (0x2828, -100 * 4), (0x27c4,  -98 * 4),
694    (0x2762,  -96 * 4), (0x2702,  -94 * 4), (0x26a4,  -92 * 4), (0x2648,  -91 * 4),
695    (0x25ed,  -89 * 4), (0x2594,  -87 * 4), (0x253d,  -86 * 4), (0x24e7,  -85 * 4),
696    (0x2492,  -83 * 4), (0x243f,  -81 * 4), (0x23ee,  -80 * 4), (0x239e,  -79 * 4),
697    (0x234f,  -77 * 4), (0x2302,  -76 * 4), (0x22b6,  -74 * 4), (0x226c,  -74 * 4),
698    (0x2222,  -72 * 4), (0x21da,  -71 * 4), (0x2193,  -70 * 4), (0x214d,  -69 * 4),
699    (0x2108,  -67 * 4), (0x20c5,  -67 * 4), (0x2082,  -65 * 4), (0x2041,  -65 * 4),
700];
701
702/// The reciprocal and shift for a normalized `W` (ParaLLEl-RDP `perspective_get_lut`).
703#[allow(
704    clippy::cast_sign_loss,
705    reason = "normout & 0x3fff >> 8 is 0..=63, a valid table index"
706)]
707fn perspective_get_lut(w: i32) -> (i32, i32) {
708    let shift = (14 - find_msb(w)).min(14);
709    let normout = (w << shift) & 0x3fff;
710    let wnorm = normout & 0xff;
711    let (base, slope) = PERSPECTIVE_TABLE[(normout >> 8) as usize];
712    let rcp = ((i32::from(slope) * wnorm) >> 10) + i32::from(base);
713    (rcp, shift)
714}
715
716/// Perspective-divide a texture coordinate `(s, t)` by `w` — a faithful port of
717/// ParaLLEl-RDP's `perspective_divide` (`perspective.h`): the LUT reciprocal, the
718/// shift, the `temp_mask` out-of-bounds saturation, the `w <= 0` carry, and the
719/// final 17-bit clamp. Returns the divided `(s, t)`.
720#[allow(
721    clippy::similar_names,
722    reason = "s / t / w are the RDP's own texture-coordinate names"
723)]
724fn perspective_divide(s: i32, t: i32, w: i32) -> (i32, i32) {
725    let w_carry = w <= 0;
726    let w = w & 0x7fff;
727    let (rcp, shift) = perspective_get_lut(w);
728    let prod0 = [s.wrapping_mul(rcp), t.wrapping_mul(rcp)];
729    let temp_mask = ((1 << 30) - 1) & -((1 << 29) >> shift);
730    let out_of_bounds = [prod0[0] & temp_mask, prod0[1] & temp_mask];
731    let (mut temp, prod) = if shift == 14 {
732        ([prod0[0] << 1, prod0[1] << 1], prod0)
733    } else {
734        let p = [prod0[0] >> (13 - shift), prod0[1] >> (13 - shift)];
735        (p, p)
736    };
737    if out_of_bounds != [0, 0] {
738        for c in 0..2 {
739            if out_of_bounds[c] != temp_mask && out_of_bounds[c] != 0 {
740                temp[c] = if prod[c] & (1 << 29) == 0 {
741                    0x7fff
742                } else {
743                    -0x8000
744                };
745            }
746        }
747    }
748    if w_carry {
749        temp = [0x7fff, 0x7fff];
750    }
751    (
752        temp[0].clamp(-0x10000, 0xffff),
753        temp[1].clamp(-0x10000, 0xffff),
754    )
755}
756
757/// The RDP's asymmetric 9-bit expand for the combiner's A/B/D inputs: subtract
758/// the 0x80 bias, sign-extend to 9 bits, add the bias back (ParaLLEl-RDP
759/// `special_expand`, `combiner.h`). The multiplier C uses a plain [`sext9`].
760const fn special_expand(v: i32) -> i32 {
761    sext9(v - 0x80) + 0x80
762}
763
764/// Evaluate one combiner channel `(A − B) * C + D` with the RDP's fixed-point
765/// rules: A/B/D through [`special_expand`], C a plain 9-bit value, a `+0x80`
766/// rounding bias applied before the `>> 8`, and D added afterwards, unscaled
767/// (ParaLLEl-RDP `combiner_equation`). No clamp here — that is per cycle.
768const fn combine_channel(a: i32, b: i32, c: i32, d: i32) -> i32 {
769    let color = (special_expand(a) - special_expand(b)) * sext9(c) + 0x80;
770    (color >> 8) + special_expand(d)
771}
772
773/// Clamp a combiner result to `[0, 255]` with the RDP's 9-bit fold — the
774/// `-0x80 / sext9 / +0x80` before the clamp is what makes 256–383 saturate and
775/// 384–511 wrap toward 0 (ParaLLEl-RDP `clamp_9bit_notrunc`, `clamping.h`).
776#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
777fn clamp_9bit(color: i32) -> u8 {
778    special_expand(color).clamp(0, 0xFF) as u8
779}
780
781/// The combiner equation's **pre-`>>8` 17-bit** result — what the chroma-key alpha
782/// compare consumes (Angrylion `color_combiner_equation`). Same terms as
783/// [`combine_channel`] but returning `((A − B) * C + (D << 8) + 0x80) & 0x1ffff`
784/// rather than the `>> 8`'d color.
785const fn combine_channel_17bit(a: i32, b: i32, c: i32, d: i32) -> i32 {
786    (((special_expand(a) - special_expand(b)) * sext9(c)) + (special_expand(d) << 8) + 0x80)
787        & 0x1_FFFF
788}
789
790/// The chroma-key alpha (Angrylion `chroma_key_min`): per channel, fold the sign of
791/// the 17-bit combined value into a distance, offset by the programmed half-width,
792/// take the minimum across R/G/B, and clamp to `[0, 0xff]`. `col17` is the pre-`>>8`
793/// combined color ([`combine_channel_17bit`]); `width` is the 12-bit `Set Key` width
794/// per channel.
795#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
796fn chroma_key_min(col17: [i32; 3], width: [u16; 3]) -> u8 {
797    let mut keyalpha = i32::MAX;
798    for ch in 0..3 {
799        // Sign-extend the 17-bit value (mask first so an unmasked caller is safe).
800        let mut k = ((col17[ch] & 0x1_FFFF) << 15) >> 15; // SIGN(col, 17)
801        if k > 0 {
802            k = if (k & 0xf) == 8 { -k + 0x10 } else { -k };
803        }
804        k += i32::from(width[ch]) << 4;
805        keyalpha = keyalpha.min(k);
806    }
807    keyalpha.clamp(0, 0xff) as u8
808}
809
810/// The combiner's "1" input — `0x100` in the internal `.8` representation, not
811/// `0xFF` (N64brew *…/Commands* §0x3C).
812const COMBINER_ONE: i16 = 0x100;
813
814/// The RGB `A` (muladd) input for channel `ch`. Table: 0 Combined, 1 Texel0,
815/// 2 Texel1, 3 Prim, 4 Shade, 5 Env, 6 One, 7 Noise (R-10 → 0), 8+ Zero.
816fn rgb_input_a(sel: u8, inp: &CombinerInputs, ch: usize) -> i16 {
817    match sel {
818        0 => i16::from(inp.combined[ch]),
819        1 => i16::from(inp.texel0[ch]),
820        2 => i16::from(inp.texel1[ch]),
821        3 => i16::from(inp.prim[ch]),
822        4 => i16::from(inp.shade[ch]),
823        5 => i16::from(inp.env[ch]),
824        6 => COMBINER_ONE,
825        _ => 0, // 7 Noise + 8+ Zero — R-10
826    }
827}
828
829/// The RGB `B` (mulsub) input. Same as `A` except 6/7 are `KeyCenter` (`Set Key`)
830/// and `ConvertK4` (`Set Convert`); 8+ read as zero.
831fn rgb_input_b(sel: u8, inp: &CombinerInputs, ch: usize) -> i16 {
832    match sel {
833        0 => i16::from(inp.combined[ch]),
834        1 => i16::from(inp.texel0[ch]),
835        2 => i16::from(inp.texel1[ch]),
836        3 => i16::from(inp.prim[ch]),
837        4 => i16::from(inp.shade[ch]),
838        5 => i16::from(inp.env[ch]),
839        6 => i16::from(inp.key_center[ch]), // Chroma-key center (Set Key R/GB)
840        7 => inp.k4, // Convert K4 (raw 0..511; combine_channel's special_expand sign-extends)
841        _ => 0,      // 8+ Zero (no R-10-deferred select remains for B; both 6 and 7 wired)
842    }
843}
844
845/// The RGB `C` (mul) input (5-bit table). Alpha-channel inputs (7–12) tap the
846/// alpha of the corresponding signal; `KeyScale` (6, `Set Key`) and Convert `K5` (15)
847/// are wired, `LODFrac` (13) is R-10 → 0.
848fn rgb_input_c(sel: u8, inp: &CombinerInputs, ch: usize) -> i16 {
849    match sel {
850        0 => i16::from(inp.combined[ch]),
851        1 => i16::from(inp.texel0[ch]),
852        2 => i16::from(inp.texel1[ch]),
853        3 => i16::from(inp.prim[ch]),
854        4 => i16::from(inp.shade[ch]),
855        5 => i16::from(inp.env[ch]),
856        7 => i16::from(inp.combined[3]),
857        8 => i16::from(inp.texel0[3]),
858        9 => i16::from(inp.texel1[3]),
859        10 => i16::from(inp.prim[3]),
860        11 => i16::from(inp.shade[3]),
861        12 => i16::from(inp.env[3]),
862        6 => i16::from(inp.key_scale[ch]), // Chroma-key scale (Set Key R/GB)
863        13 => inp.lod_frac,                // LOD fraction (raw 0..511; sext9 sign-extends)
864        14 => inp.prim_lod_frac,           // Prim LOD fraction
865        15 => inp.k5, // Convert K5 (raw 0..511; combine_channel's sext9 sign-extends)
866        _ => 0,       // 16+ Zero
867    }
868}
869
870/// The RGB `D` (add) input (3-bit table): 0 Combined … 5 Env, 6 One, 7 Zero.
871fn rgb_input_d(sel: u8, inp: &CombinerInputs, ch: usize) -> i16 {
872    match sel {
873        0 => i16::from(inp.combined[ch]),
874        1 => i16::from(inp.texel0[ch]),
875        2 => i16::from(inp.texel1[ch]),
876        3 => i16::from(inp.prim[ch]),
877        4 => i16::from(inp.shade[ch]),
878        5 => i16::from(inp.env[ch]),
879        6 => COMBINER_ONE,
880        _ => 0, // 7 Zero
881    }
882}
883
884/// The alpha `A`/`B`/`D` input (3-bit table): 0 combined-alpha … 5 env-alpha,
885/// 6 one, 7 zero.
886fn alpha_input_abd(sel: u8, inp: &CombinerInputs) -> i16 {
887    match sel {
888        0 => i16::from(inp.combined[3]),
889        1 => i16::from(inp.texel0[3]),
890        2 => i16::from(inp.texel1[3]),
891        3 => i16::from(inp.prim[3]),
892        4 => i16::from(inp.shade[3]),
893        5 => i16::from(inp.env[3]),
894        6 => COMBINER_ONE,
895        _ => 0, // 7 Zero
896    }
897}
898
899/// The alpha `C` (mul) input (3-bit table): 0 lod-frac (R-10 → 0), 1 texel0-alpha,
900/// … 5 env-alpha, 6 prim-lod-frac (R-10 → 0), 7 zero.
901fn alpha_input_c(sel: u8, inp: &CombinerInputs) -> i16 {
902    match sel {
903        1 => i16::from(inp.texel0[3]),
904        2 => i16::from(inp.texel1[3]),
905        3 => i16::from(inp.prim[3]),
906        4 => i16::from(inp.shade[3]),
907        5 => i16::from(inp.env[3]),
908        0 => inp.lod_frac,      // LOD fraction (raw 0..511; sext9 sign-extends)
909        6 => inp.prim_lod_frac, // Prim LOD fraction
910        _ => 0,                 // 7 Zero
911    }
912}
913
914/// The blender's `P`/`M` color select: which RGB triple feeds one blend term
915/// (N64brew *…/Blender*). 0 = pixel (combiner output), 1 = memory (framebuffer),
916/// 2 = blend-color register, 3 = fog-color register.
917fn blend_rgb_input(sel: u8, inp: &BlendInputs) -> [u8; 3] {
918    let [r, g, b, _] = match sel & 0x3 {
919        1 => inp.memory,
920        2 => inp.blend_color,
921        3 => inp.fog,
922        _ => inp.pixel,
923    };
924    [r, g, b]
925}
926
927/// The blender's `A` (1b) alpha weight: 0 = pixel alpha, 1 = fog alpha,
928/// 2 = shade alpha, 3 = zero (N64brew *…/Blender*).
929fn blend_a_input(sel: u8, inp: &BlendInputs) -> u8 {
930    match sel & 0x3 {
931        1 => inp.fog[3],
932        2 => inp.shade_alpha,
933        3 => 0,
934        _ => inp.pixel[3],
935    }
936}
937
938/// The blender's `B` (2b) alpha weight: 0 = `1 − A`, 1 = memory alpha (framebuffer
939/// coverage), 2 = one (0xFF), 3 = zero (N64brew *…/Blender*).
940///
941/// The `1 − A` case is the one's complement of the **already-selected `A` weight**,
942/// not of pixel alpha specifically — the ParaLLEl-RDP constant is named
943/// `INV_PIXEL_ALPHA` but computes `~a0` (`blender.h:106`), so `A` selecting fog or
944/// shade alpha makes `B` their complement too. `a0_full` is that resolved `A` weight
945/// **before** the `>> 3` (the complement is taken on the full 8-bit value, then both
946/// weights are shifted — `blender.h:106` vs `:112`).
947fn blend_b_input(sel: u8, inp: &BlendInputs, a0_full: u8) -> u8 {
948    match sel & 0x3 {
949        1 => inp.memory[3],
950        2 => 0xFF,
951        3 => 0,
952        _ => !a0_full,
953    }
954}
955
956/// Wrap one raw texture coordinate (`s10.5` fixed point) into a tile-relative
957/// integer texel, applying the tile's shift, tile-origin subtraction, mirror, and
958/// mask — the COPY-mode order (no clamp). Matches the ParaLLEl-RDP reference
959/// (`texture.h`): clamp to `i16`, then shift (codes 1–10 shift right, 11–15 shift
960/// left by `16−code`), subtract `SL<<3`, take the integer part (`>>5`), then
961/// mirror-on-alternate-spans and mask to `mask` bits (`mask == 0` = no wrap).
962fn wrap_coord(coord: i32, shift: u8, mask: u8, mirror: bool, lo: u16) -> i32 {
963    let shift = shift.min(15); // the hardware shift field is 4 bits (0..15)
964    let c = coord.clamp(-0x8000, 0x7FFF);
965    let shifted = if shift <= 10 {
966        c >> shift
967    } else {
968        // Left shift by (16 − shift), truncated to 16 bits (sign-preserving).
969        i32::from((c as i16).wrapping_shl(u32::from(16 - shift)))
970    };
971    let mut s = (shifted - (i32::from(lo) << 3)) >> 5;
972    let mask = mask.min(10); // hardware caps the mask width at 10
973    if mask != 0 {
974        let m = 1i32 << mask;
975        if mirror && s & m != 0 {
976            s ^= m - 1; // reflect on odd mask-sized spans
977        }
978        s &= m - 1;
979    }
980    s
981}
982
983/// Widen a 5-bit channel to 8 bits by bit-replication (`v<<3 | v>>2`).
984const fn widen5(v: u32) -> u8 {
985    ((v << 3) | (v >> 2)) as u8
986}
987
988/// Widen a 4-bit channel to 8 bits by bit-replication (`v<<4 | v`).
989const fn widen4(v: u32) -> u8 {
990    ((v << 4) | v) as u8
991}
992
993/// Widen a 3-bit channel to 8 bits by bit-replication.
994const fn widen3(v: u32) -> u8 {
995    ((v << 5) | (v << 2) | (v >> 1)) as u8
996}
997
998/// Decode a 16-bit RGBA5551 word to `[R, G, B, A]` (5→8 replication; 1-bit alpha).
999const fn decode_rgba16(w: u32) -> [u8; 4] {
1000    [
1001        widen5((w >> 11) & 0x1F),
1002        widen5((w >> 6) & 0x1F),
1003        widen5((w >> 1) & 0x1F),
1004        if w & 1 != 0 { 0xFF } else { 0 },
1005    ]
1006}
1007
1008/// Maximum texels a single `Load Block` may transfer (N64brew *…/Commands*
1009/// §Load Block); a load over this writes nothing into TMEM.
1010pub const LOAD_BLOCK_MAX_TEXELS: u32 = 2048;
1011
1012/// Bytes per texel for a texel-size code, or `None` for 4-bit (`size` 0), which
1013/// is sub-byte and needs nibble addressing: 8bpp=1, 16bpp=2, 32bpp=4.
1014const fn bytes_per_texel(size: u8) -> Option<u32> {
1015    match size {
1016        1 => Some(1),
1017        2 => Some(2),
1018        3 => Some(4),
1019        _ => None,
1020    }
1021}
1022const OP_SET_PRIM_DEPTH: u8 = 0x2E;
1023const OP_SET_OTHER_MODES: u8 = 0x2F;
1024const OP_FILL_RECTANGLE: u8 = 0x36;
1025const OP_SET_FILL_COLOR: u8 = 0x37;
1026const OP_SET_FOG_COLOR: u8 = 0x38;
1027const OP_SET_BLEND_COLOR: u8 = 0x39;
1028const OP_SET_CONVERT: u8 = 0x2C;
1029const OP_SET_KEY_GB: u8 = 0x2A;
1030const OP_SET_KEY_R: u8 = 0x2B;
1031const OP_SET_PRIM_COLOR: u8 = 0x3A;
1032const OP_SET_ENV_COLOR: u8 = 0x3B;
1033const OP_SET_COMBINE_MODE: u8 = 0x3C;
1034
1035/// The alpha mul-select that reads the LOD fraction. It is **zero**, which is also
1036/// the reset/default select — so a `Set Combine` that leaves the alpha mul field
1037/// clear really does ask for `LODFrac`, exactly as on hardware (R-13).
1038const LOD_FRAC_ALPHA_MUL_SELECT: u8 = 0;
1039const OP_SET_TEXTURE_IMAGE: u8 = 0x3D;
1040const OP_SET_DEPTH_IMAGE: u8 = 0x3E;
1041const OP_SET_COLOR_IMAGE: u8 = 0x3F;
1042
1043/// One cycle of the blender: the `P`/`M` color selects and the `A`/`B` alpha
1044/// selects for `P * A + M * (B + 1)` (`Set Other Modes`, 0x2F). Each is 2-bit.
1045#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1046pub struct BlendCycle {
1047    /// `P` (1a) color select: 0 pixel, 1 memory, 2 blend, 3 fog.
1048    pub p: u8,
1049    /// `A` (1b) alpha select: 0 pixel-alpha, 1 fog-alpha, 2 shade-alpha, 3 zero.
1050    pub a: u8,
1051    /// `M` (2a) color select (same table as `P`).
1052    pub m: u8,
1053    /// `B` (2b) alpha select: 0 `1−A`, 1 memory-alpha, 2 one, 3 zero.
1054    pub b: u8,
1055}
1056
1057/// The `Set Other Modes` (0x2F) render-mode state the blender and cycle control
1058/// need.
1059///
1060/// Coverage, RGB dither, and alpha-compare are decoded here and now applied
1061/// (dither on both pixel paths; alpha-compare gates the write on both). The
1062/// remaining decoded-but-unused fields — the AA-edge divider LUT, the
1063/// interpenetrating-Z blend-shift, `color_on_cvg`, and coverage write-back — are
1064/// the **open residual R-11**.
1065#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1066#[allow(
1067    clippy::struct_excessive_bools,
1068    reason = "these are independent hardware mode bits from Set Other Modes, not a state machine"
1069)]
1070// This render state grows a field nearly every sprint (mid_texel, key_en, … most
1071// recently); `#[non_exhaustive]` keeps that additive for external consumers, who
1072// build it from `Default` rather than an exhaustive literal (the in-crate decoder
1073// still uses a full literal, which same-crate construction permits).
1074#[non_exhaustive]
1075pub struct OtherModes {
1076    /// Cycle type: 0 = 1-cycle, 1 = 2-cycle, 2 = copy, 3 = fill.
1077    pub cycle_type: u8,
1078    /// The two blender cycles (cycle 0 chains into cycle 1 in 2-cycle mode).
1079    pub blend: [BlendCycle; 2],
1080    /// Force the no-divide blend form even on the final cycle.
1081    pub force_blend: bool,
1082    /// Read the framebuffer (memory) color into the blend.
1083    pub image_read_en: bool,
1084    /// Coverage write-back mode: 0 clamp, 1 wrap, 2 full, 3 save.
1085    pub cvg_dest: u8,
1086    /// Z test / update enables and the Z mode (T-33-004 consumes these).
1087    pub z_compare_en: bool,
1088    /// Z-buffer update enable.
1089    pub z_update_en: bool,
1090    /// Z mode: 0 opaque, 1 interpenetrating, 2 transparent, 3 decal.
1091    pub z_mode: u8,
1092    /// Alpha-compare enable (gates the pixel write; R-11).
1093    pub alpha_compare_en: bool,
1094    /// Chroma-key enable (bit 40): the combiner outputs the sub-A color and derives
1095    /// the pixel alpha from the key window (`chroma_key_min`). R-10.
1096    pub key_en: bool,
1097    /// Perspective-correct texturing (bit 51): divide the interpolated `S`/`T` by `W`.
1098    pub persp_tex_en: bool,
1099    /// Anti-aliasing enable (bit 3): sub-pixel edge coverage governs which edge
1100    /// pixels draw and enables the edge blend (N64brew *…/Commands* §0x2F bit 3).
1101    pub aa_enable: bool,
1102    /// RGB dither mode (bits 39:38): 0 magic, 1 bayer, 2 noise, 3 off. Applied
1103    /// to the combined RGB per pixel before write-back (N64brew *…/Commands*
1104    /// §0x2F; parallel-rdp `dither.c`). Modes 0/1 dither; 2 (noise, **R-10**)
1105    /// currently reads the magic cell; 3 never rounds up (dither off).
1106    pub rgb_dither_mode: u8,
1107    /// Texture sample type (bit 45): `false` = point-sample one texel, `true` =
1108    /// the N64's 3-point bilinear filter (R-13). Applied in the triangle sampler.
1109    pub sample_type: bool,
1110    /// LOD enable (bit 48): the derivative-based mip level drives tile selection.
1111    /// Decoded and fed to the LOD fraction; LOD-driven **tile** selection is the
1112    /// remaining R-13 residual, so this does not yet re-tile.
1113    pub tex_lod_en: bool,
1114    /// Sharpen-texture enable (bit 49): keeps the LOD fraction live when
1115    /// magnifying and sets its `0x100` bit (R-13).
1116    pub sharpen_tex_en: bool,
1117    /// Detail-texture enable (bit 50): keeps the LOD fraction live when
1118    /// magnifying (R-13).
1119    pub detail_tex_en: bool,
1120    /// **TLUT enable** (bit 47). N64brew *…/Commands* §0x2F: *"`tlut_en`: Enables
1121    /// Texture Look-Up Table (TLUT) sampling. Texels are first fetched from low
1122    /// TMEM that are then used to index a palette in high TMEM to find the final
1123    /// color values."*
1124    ///
1125    /// This is the flag that decides whether a palette lookup happens — **not**
1126    /// the tile's format field. Keying off the format alone is wrong in two
1127    /// directions, and **only one of them is fixed**:
1128    ///
1129    /// - **Implemented:** a CI tile with `tlut_en` clear is no longer
1130    ///   palette-mapped. Pinned by `ci4_tlut_disabled_16`, whose golden is all
1131    ///   black where the `tlut_en`-set twin renders the full palette.
1132    /// - **Deferred:** a **non-CI** tile with `tlut_en` set is still not
1133    ///   palette-mapped, though hardware would sample it through the TLUT. No
1134    ///   vector covers that case, and the RGBA/IA/I formats index the palette
1135    ///   differently enough that implementing it from the prose alone would be
1136    ///   inventing behavior. It stays wrong-but-honest until a vector defines it,
1137    ///   the same posture as `tlut_type`'s IA16 palettes below.
1138    pub tlut_en: bool,
1139    /// TLUT texel format (bit 46): `false` = RGBA16, `true` = IA16
1140    /// (N64brew *…/Commands* §0x2F). Decoded so it is available and so the flag
1141    /// is not silently ignored; **IA16 palettes are still deferred** — the lookup
1142    /// assumes RGBA16, and implementing IA16 without a vector would be inventing
1143    /// behavior rather than emulating it.
1144    pub tlut_type: bool,
1145    /// Mid-texel filter (bit 44, R-13): when set and the bilinear sample lands
1146    /// exactly on the texel center (`sfrac == tfrac == 0x10`), the four neighbors
1147    /// are averaged instead of the 3-point triangle pick (Angrylion `tex.c`, the
1148    /// `center`/`centerrg` case). Only meaningful with `sample_type`.
1149    pub mid_texel: bool,
1150}
1151
1152/// The resolved per-pixel blender input colors (each RGBA8888).
1153#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)]
1154pub struct BlendInputs {
1155    /// The combiner's output ("pixel color").
1156    pub pixel: [u8; 4],
1157    /// The framebuffer's current color (memory), with coverage in its alpha.
1158    pub memory: [u8; 4],
1159    /// The blend-color register (`Set Blend Color`, 0x39).
1160    pub blend_color: [u8; 4],
1161    /// The fog-color register (`Set Fog Color`, 0x38).
1162    pub fog: [u8; 4],
1163    /// The interpolated shade alpha.
1164    pub shade_alpha: u8,
1165}
1166
1167/// The Z-buffer read and render-mode flags [`Rdp::depth_test`] needs beyond the
1168/// incoming pixel's own `z`/`dz` (grouped so the signature stays legible).
1169#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)]
1170pub struct DepthInputs {
1171    /// The 14-bit compressed depth already stored for this pixel.
1172    pub current_depth: u16,
1173    /// The 4-bit `dz` already stored for this pixel.
1174    pub current_dz: u8,
1175    /// The coverage already accumulated in the framebuffer pixel.
1176    pub current_coverage: i32,
1177    /// `Set Other Modes` `z_compare_en`: run the depth comparison at all.
1178    pub z_compare: bool,
1179    /// `Set Other Modes` `z_mode`: 0 opaque, 1 interpenetrating, 2 transparent, 3 decal.
1180    pub z_mode: u8,
1181    /// `Set Other Modes` `force_blend`.
1182    pub force_blend: bool,
1183    /// Anti-aliasing enable (`Set Other Modes` `antialias_en`).
1184    pub aa_enable: bool,
1185}
1186
1187/// The outcome of a per-pixel depth test: whether the pixel is written, and the
1188/// blend/coverage state the blender consumes.
1189#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1190pub struct DepthResult {
1191    /// The pixel passes the depth test and is written.
1192    pub depth_pass: bool,
1193    /// Enable the blender for this pixel (vs. an opaque overwrite).
1194    pub blend_en: bool,
1195    /// Coverage overflowed (`>= 8`): the surface differs, wrap the coverage.
1196    pub coverage_wrap: bool,
1197    /// The two blender coverage shifts (`[dz→mem, mem→dz]`, each clamped `0..=4`).
1198    pub blend_shift: [u8; 2],
1199    /// The (possibly interpenetrating-reduced) coverage count carried forward.
1200    pub coverage_count: i32,
1201}
1202
1203/// The decoded per-triangle depth setup for the per-pixel path: the `s15.16`
1204/// z-coefficient and its per-x / per-major-edge deltas, plus the primitive `dz`
1205/// (linear) and `dz_compressed` (4-bit stored form) for the test and writeback.
1206#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)]
1207#[allow(
1208    clippy::similar_names,
1209    reason = "dzdx / dzde / dz are the N64 RDP's own z-coefficient names"
1210)]
1211struct ZTriSetup {
1212    z_base: i32,
1213    dzdx: i32,
1214    dzde: i32,
1215    dz: i32,
1216    dz_compressed: i32,
1217}
1218
1219/// The decoded per-triangle shade setup for the per-pixel path: the `s15.16` RGBA
1220/// base color (at the top vertex) and its per-x (`dx`) and per-major-edge (`de`)
1221/// deltas. The per-scanline `dy` term (sub-pixel snap) is part 2c.
1222#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)]
1223struct ShadeSetup {
1224    base: [i32; 4],
1225    dx: [i32; 4],
1226    de: [i32; 4],
1227}
1228
1229/// The decoded per-triangle texture setup: `S`/`T`/`W` (`W` for the perspective
1230/// divide). `base`/`dx`/`de` are the `s16.16` base at the top vertex and its per-x
1231/// and per-major-edge deltas.
1232#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)]
1233struct TexSetup {
1234    base: [i32; 3],
1235    dx: [i32; 3],
1236    de: [i32; 3],
1237    /// Per-**Y** derivative (`DsDy`/`DtDy`/`DwDy`, words 5/7). Unlike `de` (the
1238    /// major-edge step the scanline walk uses), this is the true vertical
1239    /// gradient the **LOD** needs for its second delta pair (R-13).
1240    dy: [i32; 3],
1241}
1242
1243/// Unpack an RGBA8888 register word into `[r, g, b, a]` bytes.
1244const fn unpack_rgba(w: u32) -> [u8; 4] {
1245    w.to_be_bytes()
1246}
1247
1248/// Pack an RGBA8888 color into a 16-bit RGBA5551 framebuffer pixel
1249/// (`R[15:11] G[10:6] B[5:1] A[0]`).
1250const fn pack_rgba5551(rgba: [u8; 4]) -> u16 {
1251    ((rgba[0] as u16 >> 3) << 11)
1252        | ((rgba[1] as u16 >> 3) << 6)
1253        | ((rgba[2] as u16 >> 3) << 1)
1254        | (rgba[3] as u16 >> 7)
1255}
1256
1257/// Unpack a 16-bit RGBA5551 framebuffer pixel to RGBA8888, widening each 5-bit
1258/// channel by high-bit replication (`v << 3 | v >> 2`) and the 1-bit alpha to
1259/// `0x00`/`0xFF`.
1260const fn unpack_rgba5551(p: u16) -> [u8; 4] {
1261    let r = (p >> 11) & 0x1F;
1262    let g = (p >> 6) & 0x1F;
1263    let b = (p >> 1) & 0x1F;
1264    [
1265        ((r << 3) | (r >> 2)) as u8,
1266        ((g << 3) | (g >> 2)) as u8,
1267        ((b << 3) | (b >> 2)) as u8,
1268        if p & 1 != 0 { 0xFF } else { 0 },
1269    ]
1270}
1271
1272/// The number of Y-subpixels the RDP samples per scanline for coverage
1273/// (parallel-rdp `coverage.h` `SUBPIXELS`).
1274pub const COVERAGE_SUBPIXELS: usize = 4;
1275
1276/// `log2` of the 4 sub-scanlines per pixel row: the triangle edge slopes are dx
1277/// per **pixel** row but the edge-walk steps per **quarter**-pixel, so each slope
1278/// is pre-shifted `>> SUB_SCANLINE_SHIFT` at decode (ledger R-14).
1279const SUB_SCANLINE_SHIFT: i32 = 2;
1280
1281/// Left-edge poison for a sub-scanline outside the triangle: larger than any real
1282/// `s.3` edge, so every X-sample tests as clipped and `min4` ignores it.
1283const SPAN_X_POISON_LEFT: i32 = i32::MAX;
1284/// Right-edge poison (mirror of [`SPAN_X_POISON_LEFT`]).
1285const SPAN_X_POISON_RIGHT: i32 = i32::MIN;
1286
1287/// The minimum of the four per-Y-subpixel left edges (parallel-rdp `span_setup.comp` `min4`).
1288fn min4(v: &[i32; COVERAGE_SUBPIXELS]) -> i32 {
1289    v[0].min(v[1]).min(v[2]).min(v[3])
1290}
1291/// The maximum of the four per-Y-subpixel right edges (`span_setup.comp` `max4`).
1292fn max4(v: &[i32; COVERAGE_SUBPIXELS]) -> i32 {
1293    v[0].max(v[1]).max(v[2]).max(v[3])
1294}
1295
1296/// Quantize a signed edge X to the 3-fraction-bit sub-pixel domain used by
1297/// [`compute_coverage`], with the RDP sticky bit.
1298///
1299/// Any discarded fraction bit forces the low output bit set, so a
1300/// truncated-but-nonzero coordinate never snaps exactly onto a sub-pixel
1301/// boundary — this is what makes the half-open `<` / `>=` edge tests in
1302/// [`compute_coverage`] bit-exact (parallel-rdp `span_setup.comp:60-66`).
1303///
1304/// **Fixed-point domain.** parallel-rdp's `setup.xh` is `s.15` (its `base_x =
1305/// xh >> 15`), so it quantizes with `>> 12` to reach the `s.3` coverage domain.
1306/// Our edge values are the raw command `s.16` (`major >> 16` is the pixel), one
1307/// fraction bit wider, so we shift `>> 13` and take the sticky bit over the low
1308/// 13 discarded bits — the same 3-fraction-bit result.
1309///
1310/// This and [`compute_coverage`] are the sub-pixel coverage primitives (T-33-004
1311/// slice 2c); the rasterizer's edge-walk still unions the four sub-scanlines into
1312/// a whole-pixel bounding span (**open residual R-9**) until the coverage
1313/// integration lands, so these have no runtime caller yet.
1314#[must_use]
1315pub const fn quantize_x(x: i32) -> i32 {
1316    let sticky = (x & 0x1FFF != 0) as i32;
1317    (x >> 13) | sticky
1318}
1319
1320/// The 8-bit sub-pixel coverage mask for integer pixel column `x`, given the
1321/// per-Y-subpixel left/right span edges (each `s.3`, from [`quantize_x`]).
1322///
1323/// The RDP samples 4 Y-subpixels × 2 X-samples = 8 sub-positions. The two
1324/// X-samples sit at sub-pixel fractions that alternate by Y-subpixel — `{0, 4}`
1325/// for Y-subpixels 0/2 and `{2, 6}` for 1/3 — the RDP's diamond sample pattern
1326/// (`coverage.h:31-44` `u16x4(0, 4, 2, 6)`). A sample is covered when it lies in
1327/// the half-open span `[xleft, xright)` of its Y-subpixel.
1328///
1329/// **Bit layout.** The oracle's `clip_x0 * (1,2,4,8) + clip_x1 * (16,32,64,128)`
1330/// packs the two X-samples of each Y-subpixel into adjacent bits — bit
1331/// `2·Ysub + Xsample` — so the mask reads (LSB→MSB) `Y0X0 Y0X1 Y1X0 Y1X1 Y2X0
1332/// Y2X1 Y3X0 Y3X1`, *not* all-X0 then all-X1. Bit 0 is therefore the top-left
1333/// sample (Y-subpixel 0, X-sample 0), which is the one the AA-off path tests.
1334/// The popcount ([`u8::count_ones`]) is the coverage count (0–8) regardless of order.
1335///
1336/// See [`quantize_x`] for the domain of `xleft`/`xright` and why this has no
1337/// runtime caller yet.
1338#[must_use]
1339pub fn compute_coverage(
1340    xleft: [i32; COVERAGE_SUBPIXELS],
1341    xright: [i32; COVERAGE_SUBPIXELS],
1342    x: i32,
1343) -> u8 {
1344    // The four lanes carry X-sample offsets {0, 4, 2, 6}; `xshift = (x << 3) + offset`.
1345    let base = x << 3;
1346    let xshift = [base, base + 4, base + 2, base + 6];
1347    // `.xxyy` / `.zzww`: lanes 0-3 test Y-subpixels {0,0,1,1} then {2,2,3,3}.
1348    let ysub_lo = [0usize, 0, 1, 1];
1349    let ysub_hi = [2usize, 2, 3, 3];
1350    let mut clip = 0u8;
1351    let mut lane = 0;
1352    while lane < COVERAGE_SUBPIXELS {
1353        let lo = ysub_lo[lane];
1354        if xshift[lane] < xleft[lo] || xshift[lane] >= xright[lo] {
1355            clip |= 1 << lane;
1356        }
1357        let hi = ysub_hi[lane];
1358        if xshift[lane] < xleft[hi] || xshift[lane] >= xright[hi] {
1359            clip |= 1 << (lane + 4);
1360        }
1361        lane += 1;
1362    }
1363    !clip
1364}
1365
1366/// The RDP's 4×4 "magic" ordered-dither matrix (parallel-rdp/angrylion `dither.c`).
1367#[rustfmt::skip]
1368const DITHER_MAGIC: [u8; 16] = [
1369    0, 6, 1, 7,
1370    4, 2, 5, 3,
1371    3, 5, 2, 4,
1372    7, 1, 6, 0,
1373];
1374/// The RDP's 4×4 "bayer" ordered-dither matrix (`dither.c`).
1375#[rustfmt::skip]
1376const DITHER_BAYER: [u8; 16] = [
1377    0, 4, 1, 5,
1378    4, 0, 5, 1,
1379    3, 7, 2, 6,
1380    7, 3, 6, 2,
1381];
1382
1383/// The 3-bit RGB dither value for pixel `(x, y)` under the RGB dither mode
1384/// (`Set Other Modes` bits 39:38): 0 magic, 1 bayer, 2 noise (**R-10**, read as
1385/// the magic cell for now), 3 "constant 7" — which never rounds up, i.e. dither
1386/// off. (parallel-rdp `dither.c` `get_dither_noise`.)
1387fn rgb_dither_value(mode: u8, x: u32, y: u32) -> i32 {
1388    let idx = ((y & 3) * 4 + (x & 3)) as usize;
1389    match mode {
1390        // Mode 2 (noise) intentionally reuses the magic matrix pending a real
1391        // noise source (**R-10**); a per-pixel noise value replaces this then.
1392        0 | 2 => i32::from(DITHER_MAGIC[idx]),
1393        1 => i32::from(DITHER_BAYER[idx]),
1394        _ => 7, // 3: constant 7 -> no dithering
1395    }
1396}
1397
1398/// Apply the RDP's ordered RGB dither to a color (`dither.c` `rgb_dither`): each
1399/// channel rounds up to the next 5-bit level `(c & 0xf8) + 8` (saturating at 255)
1400/// **iff** the dither value is less than the channel's low 3 bits, else it is left
1401/// unchanged. Alpha is untouched. `dith` is the shared 3-bit value (matrix cell).
1402fn apply_rgb_dither(rgb: [u8; 4], dith: i32) -> [u8; 4] {
1403    let channel = |c: u8| -> u8 {
1404        let c = i32::from(c);
1405        let rounded = if c > 247 { 255 } else { (c & 0xF8) + 8 };
1406        // `replacesign` is all-ones when `dith < (c & 7)`, selecting the rounded value.
1407        let replacesign = (dith - (c & 7)) >> 31;
1408        #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
1409        {
1410            (c + ((rounded - c) & replacesign)) as u8
1411        }
1412    };
1413    [channel(rgb[0]), channel(rgb[1]), channel(rgb[2]), rgb[3]]
1414}
1415
1416/// One cycle of the color combiner.
1417///
1418/// The four RGB input selects and the four alpha input selects for
1419/// `(A − B) * C + D` (`Set Combine Mode`, 0x3C). A/B/D RGB are 4-bit (D 3-bit),
1420/// C RGB is 5-bit; the alpha selects are all 3-bit.
1421#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1422pub struct CombineCycle {
1423    /// RGB `A` (muladd) select.
1424    pub rgb_a: u8,
1425    /// RGB `B` (mulsub) select.
1426    pub rgb_b: u8,
1427    /// RGB `C` (mul) select.
1428    pub rgb_c: u8,
1429    /// RGB `D` (add) select.
1430    pub rgb_d: u8,
1431    /// Alpha `A` select.
1432    pub a_a: u8,
1433    /// Alpha `B` select.
1434    pub a_b: u8,
1435    /// Alpha `C` select.
1436    pub a_c: u8,
1437    /// Alpha `D` select.
1438    pub a_d: u8,
1439}
1440
1441/// The two-cycle color-combiner configuration (`Set Combine Mode`, 0x3C).
1442#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1443pub struct CombineMode {
1444    /// Cycle-0 selects (the first stage in 2-cycle mode).
1445    pub cyc0: CombineCycle,
1446    /// Cycle-1 selects (the only stage used in 1-cycle mode).
1447    pub cyc1: CombineCycle,
1448}
1449
1450/// The resolved per-pixel combiner input signals (each RGBA8888).
1451///
1452/// The combiner muxes these by the [`CombineCycle`] selects. The register-sourced
1453/// exotic inputs (prim-LOD-frac, the convert `K4`/`K5`, the chroma-key center/scale)
1454/// are wired; the rest (noise, the derivative `lod_frac`, the YUV `K0`–`K3` convert)
1455/// are not modeled yet (**open residual R-10**) and read as zero.
1456///
1457/// This is **transient** per-pixel state — built in `combined_color`, consumed by
1458/// `combine`, and discarded — never stored in `System`. It is therefore `pub(crate)`
1459/// (not part of this crate's public API), does not derive `Serialize`/`Deserialize`
1460/// (never in a save-state), and needs no `#[non_exhaustive]` (a new field is always a
1461/// compatible change within the crate). Construct it with `..Default::default()`.
1462#[derive(Debug, Default, Clone, Copy)]
1463pub(crate) struct CombinerInputs {
1464    /// The previous cycle's output (cycle 0's result feeds cycle 1's `Combined`).
1465    pub combined: [u8; 4],
1466    /// Texel from tile 0.
1467    pub texel0: [u8; 4],
1468    /// Texel from tile 1.
1469    pub texel1: [u8; 4],
1470    /// The primitive color (`Set Prim Color`, 0x3A).
1471    pub prim: [u8; 4],
1472    /// The interpolated shade color.
1473    pub shade: [u8; 4],
1474    /// The environment color (`Set Env Color`, 0x3B).
1475    pub env: [u8; 4],
1476    /// Primitive LOD fraction (`Set Prim Color` word-0 low byte) — combiner mul
1477    /// input (RGB select 14, alpha select 6). `0..=255` (R-10).
1478    pub prim_lod_frac: i16,
1479    /// The derivative-computed **LOD fraction** — combiner mul input (RGB select
1480    /// 13, alpha select 0). Held **raw** (`0..=0x1ff`; the `0x100` bit is set by
1481    /// `sharpen_tex_en`), sign-extended downstream by `sext9` exactly like
1482    /// `K4`/`K5`. R-13.
1483    pub lod_frac: i16,
1484    /// `Set Convert` (0x2C) `K4` — combiner RGB sub-B input (select 7). Held as the
1485    /// **raw 0..511** value the hardware stores; `combine_channel` sign-extends it via
1486    /// `special_expand` (bit-identical to Angrylion's `special_9bit_exttable`), so a
1487    /// bit-8-set value reads as negative. Storing raw matches Angrylion `rdp_set_convert`
1488    /// — sign-extending at decode would double-apply. R-10.
1489    pub k4: i16,
1490    /// `Set Convert` (0x2C) `K5` — combiner RGB mul input (select 15). Held as the
1491    /// **raw 0..511** value; `combine_channel` sign-extends it via `sext9`
1492    /// (Angrylion `SIGNF(c, 9)`). Stored raw, like `k4`. R-10.
1493    pub k5: i16,
1494    /// Chroma-key center `[r, g, b]` (`Set Key R`/`GB`) — the combiner RGB sub-B
1495    /// input (select 6), fed as an 8-bit value like `prim`/`env`. R-10.
1496    pub key_center: [u8; 3],
1497    /// Chroma-key scale `[r, g, b]` (`Set Key R`/`GB`) — the combiner RGB mul input
1498    /// (select 6), 8-bit. R-10.
1499    pub key_scale: [u8; 3],
1500}
1501
1502/// TMEM size in bytes — 4 KiB of on-chip texture memory.
1503///
1504/// Addressed as 512 64-bit words. The upper half (byte >= 0x800 / word >= 0x100)
1505/// holds TLUTs and the high halves of 32-bit / YUV textures (N64brew
1506/// *…/Commands* §Set Tile).
1507pub const TMEM_SIZE: usize = 4096;
1508
1509/// One of the RDP's eight tile descriptors.
1510///
1511/// The format/size/addressing state that binds a region of TMEM to a texture,
1512/// set by `Set Tile` (0x35) and sized by `Set Tile Size` (0x32) / the load
1513/// commands. All fields are decoded straight from the command word (N64brew
1514/// *…/Commands* §0x35/§0x32).
1515// The four bools are the hardware's four independent clamp/mirror bit-flags (one
1516// clamp + one mirror per S/T axis); they are decoded straight from command bits
1517// 8/9/18/19, so an enum would misrepresent the register rather than clarify it.
1518#[allow(clippy::struct_excessive_bools)]
1519#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1520pub struct TileDescriptor {
1521    /// Texel format: RGBA=0, YUV=1, CI=2, IA=3, I=4 (`Set Tile` bits 55:53).
1522    pub format: u8,
1523    /// Texel size code: 4bpp=0, 8bpp=1, 16bpp=2, 32bpp=3 (bits 52:51).
1524    pub size: u8,
1525    /// Row stride in 64-bit TMEM words (bits 49:41).
1526    pub line: u16,
1527    /// Base TMEM address in 64-bit words (bits 40:32); word 0x100 = byte 0x800.
1528    pub tmem_addr: u16,
1529    /// Palette index, the high half of the TLUT address for CI4 tiles only
1530    /// (bits 23:20).
1531    pub palette: u8,
1532    // T-axis fields precede S-axis, matching the command word's MSB→LSB order
1533    // (T in bits 19:10, S in bits 9:0) and the `set_tile` decoder.
1534    /// Clamp T when sampling outside the tile (bit 19).
1535    pub clamp_t: bool,
1536    /// Mirror T on every other wrap (bit 18).
1537    pub mirror_t: bool,
1538    /// Number of T integer-coordinate bits used for wrap; 0 = all (bits 17:14).
1539    pub mask_t: u8,
1540    /// T coordinate shift code, per the shift table (bits 13:10).
1541    pub shift_t: u8,
1542    /// Clamp S when sampling outside the tile (bit 9).
1543    pub clamp_s: bool,
1544    /// Mirror S on every other wrap (bit 8).
1545    pub mirror_s: bool,
1546    /// Number of S integer-coordinate bits used for wrap; 0 = all (bits 7:4).
1547    pub mask_s: u8,
1548    /// S coordinate shift code, per the shift table (bits 3:0).
1549    pub shift_s: u8,
1550    /// Tile-size upper-left S (`u10.2`), from `Set Tile Size` / the loaders.
1551    pub sl: u16,
1552    /// Tile-size upper-left T (`u10.2`).
1553    pub tl: u16,
1554    /// Tile-size lower-right S (`u10.2`).
1555    pub sh: u16,
1556    /// Tile-size lower-right T (`u10.2`).
1557    pub th: u16,
1558}
1559
1560/// Proof that a step needs the bus, produced only by [`Rdp::tick_without_bus`] and
1561/// consumed only by [`Rdp::tick_with_bus`].
1562///
1563/// The two halves exist for a caller that cannot hand out a borrow of this struct
1564/// without first moving the struct itself — it needs to know whether the step will use
1565/// the bus *before* paying the 344-byte `core::mem::take` that arranging one costs.
1566/// (In this workspace that caller is the Bus, which owns every chip.) The bus half
1567/// then has real preconditions:
1568/// the pipeline is unfrozen, `stall` is zero, and the command FIFO is non-empty.
1569///
1570/// Those preconditions are carried by this token rather than by a comment, an
1571/// `assert!`, or a `debug_assert!` alone. A comment is not checked; a `debug_assert`
1572/// compiles out, so a release build would decode a command from an empty FIFO in
1573/// silence; and a release guard that returns early would make a caller who never calls
1574/// `tick_without_bus` hang, because `stall` would never count down. Requiring the token
1575/// removes all three: calling the bus half out of order does not compile.
1576///
1577/// The field is private and the type has no constructor, so it cannot be forged.
1578///
1579/// **Dropping a token loses a cycle, not the work.** The `Some` path mutates
1580/// nothing — it is reached only once `stall` is zero, so no decrement has happened, and
1581/// no FIFO pointer moves until the bus half runs. The command is therefore still
1582/// pending and the next `rdp_tick` retries the identical step. What is lost is the
1583/// *step*: the RDP made no progress during that GCLK and is one cycle late from then
1584/// on. That is the failure mode worth naming here, because it is a timing divergence
1585/// with **no wrong state anywhere** — correct-but-late, which no state comparison can
1586/// see. Hence `#[must_use]`, below, rather than a `debug_assert` on the token count.
1587///
1588/// What makes ignoring one loud is the `#[must_use]` on
1589/// [`Rdp::tick_without_bus`] **itself**, not the one on this type: an attribute on `T`
1590/// does not propagate through `Option<T>`, and `Option` — unlike `Result` — is not
1591/// `#[must_use]` either. Verified by discarding the call and watching the lint appear
1592/// only once the attribute moved to the function.
1593///
1594/// **`Copy` and `Clone` are deliberately not derived.** Either would let a caller keep
1595/// a token past the step it authorized and present it again after the state it attested
1596/// to had changed — the same hole as taking it by reference. `Debug` is derived because
1597/// it cannot duplicate the value.
1598#[derive(Debug)]
1599#[must_use = "a step that needs the bus is not finished until `tick_with_bus` runs it"]
1600pub struct NeedsBus(());
1601
1602/// RDP state (skeleton).
1603///
1604/// Holds the command-FIFO pointers, the current render mode (other-modes),
1605/// scissor rectangle, the color-image / Z-image RDRAM addresses, the
1606/// texture-image source registers, the eight tile descriptors, and TMEM. The
1607/// texel loads and the sampler/combiner that consume this state land in the rest
1608/// of the sprint. `#[non_exhaustive]`: this render state grows every sprint
1609/// (other-modes and the combiner latches are still to come), so adding a field
1610/// must not be a breaking change. Construct via [`Rdp::new`]; the workspace
1611/// never uses a struct literal.
1612#[derive(Debug, Default, Clone, Serialize, Deserialize)]
1613#[non_exhaustive]
1614pub struct Rdp {
1615    /// DP command FIFO start (`DPC_START`).
1616    pub cmd_start: u32,
1617    /// DP command FIFO end (`DPC_END`).
1618    pub cmd_end: u32,
1619    /// DP command FIFO current (`DPC_CURRENT`).
1620    pub cmd_current: u32,
1621    /// DP command FIFO status (`DPC_STATUS`): FREEZE, START/END-valid, XBUS,
1622    /// and (later) the busy/counter bits.
1623    pub status: u32,
1624    /// Color-image (framebuffer) base in RDRAM (`Set Color Image`, 0x3F).
1625    pub color_image: u32,
1626    /// Color-image pixel size code (`Set Color Image` size\[1:0\]): 0 = 4-bit,
1627    /// 1 = 8-bit, 2 = 16-bit, 3 = 32-bit. Bytes-per-pixel derive from it.
1628    pub color_image_size: u8,
1629    /// Color-image pixel format code (`Set Color Image` format\[2:0\]); the same
1630    /// format enumeration as textures. Stored for later pipeline stages — the
1631    /// FILL path writes the raw fill value and does not consult it.
1632    pub color_image_format: u8,
1633    /// Color-image width in pixels (`Set Color Image` width\[9:0\] + 1). The row
1634    /// stride is `width * bytes_per_pixel`.
1635    pub color_image_width: u16,
1636    /// Z-image base in RDRAM (`Set Depth Image`, 0x3E).
1637    pub z_image: u32,
1638    /// Primitive depth `z` (`Set Primitive Depth`, 0x2E): the s15.3 depth used when
1639    /// `Set Other Modes` `z_source_sel` selects it (and the only depth source for
1640    /// rectangle commands). Stored as the raw 16-bit field.
1641    pub prim_z: u16,
1642    /// Primitive `dz` (`Set Primitive Depth`, 0x2E), the raw 16-bit field.
1643    pub prim_dz: u16,
1644    /// FILL-mode color register (`Set Fill Color`, 0x37): a 32-bit value written
1645    /// verbatim to the color image. Its interpretation depends on the pixel size
1646    /// — one RGBA32, two RGBA16 (even pixel = upper half, odd = lower), or four
1647    /// 8-bit values repeating every four pixels.
1648    pub fill_color: u32,
1649    /// Scissor rectangle (`Set Scissor`, 0x2D), the four `u10.2` screen
1650    /// coordinates that bound every primitive: upper-left (x, y) and lower-right
1651    /// (x, y). Pixels outside it are neither processed nor written.
1652    pub scissor_ulx: u16,
1653    /// Scissor upper-left y (`u10.2`). See [`Rdp::scissor_ulx`].
1654    pub scissor_uly: u16,
1655    /// Scissor lower-right x (`u10.2`). See [`Rdp::scissor_ulx`].
1656    pub scissor_lrx: u16,
1657    /// Scissor lower-right y (`u10.2`). See [`Rdp::scissor_ulx`].
1658    pub scissor_lry: u16,
1659    /// Count of commands the FIFO decoder has retired. A **retired-work tally**,
1660    /// not a cycle position: nothing schedules against it (the residue
1661    /// invariant governs only `master_ticks`), it is derived from the command
1662    /// stream, and it exists so tests can witness that the decoder consumed the
1663    /// number of commands it should. Wraps rather than panicking.
1664    pub commands_processed: u64,
1665    /// GCLK cycles the pipeline is currently stalled, counted **down** one per
1666    /// `tick`; while non-zero the FIFO does not advance. Set by the sync
1667    /// commands to their documented fixed stalls ([`SYNC_LOAD_GCLK`] etc.). This
1668    /// is a stall countdown, not a cycle position — it is decremented, nothing
1669    /// derives a clock from it, and it does not touch the derive-don't-increment
1670    /// rule (only `master_ticks` is ever incremented; ADR 0006).
1671    pub stall: u32,
1672    /// Texture-image (`Set Texture Image`, 0x3D) format code — the RDRAM source
1673    /// for texture loads. The wiki notes this format has no effect on any
1674    /// operation (only the tile format matters); stored for completeness.
1675    pub tex_image_format: u8,
1676    /// Texture-image texel size code (0x3D size\[1:0\]): 4/8/16/32bpp = 0/1/2/3.
1677    /// Drives the per-texel address stride during a load.
1678    pub tex_image_size: u8,
1679    /// Texture-image width in pixels (0x3D width\[9:0\] + 1); the row stride of
1680    /// the RDRAM source during a load.
1681    pub tex_image_width: u16,
1682    /// Texture-image base address in RDRAM (0x3D dramAddress\[23:0\]).
1683    pub tex_image_addr: u32,
1684    /// The eight tile descriptors (`Set Tile` / `Set Tile Size` / the loaders).
1685    pub tiles: [TileDescriptor; 8],
1686    /// The color-combiner configuration (`Set Combine Mode`, 0x3C).
1687    pub combine: CombineMode,
1688    /// The render-mode / blender configuration (`Set Other Modes`, 0x2F).
1689    pub other_modes: OtherModes,
1690    /// The primitive color, RGBA8888 (`Set Prim Color`, 0x3A).
1691    pub prim_color: u32,
1692    /// Primitive LOD fraction (`Set Prim Color` word-0 low byte) — a combiner mul
1693    /// input (R-10).
1694    pub prim_lod_frac: u8,
1695    /// `Set Prim Color` `min_level` (word-0 bits 12:8): the floor the LOD is held
1696    /// at while magnifying (Angrylion `lodfrac_lodtile_signals`). R-13.
1697    pub min_level: u8,
1698    /// The current primitive's `level[2:0]` (triangle command bits 53:51) — the
1699    /// number of mip levels past the base tile. Per-primitive render state, set
1700    /// by the triangle decode, exactly as Angrylion holds it (`rasterizer.c`
1701    /// `state[wid].max_level = (ewdata[0] >> 19) & 7`). R-13.
1702    pub max_level: u8,
1703    /// `Set Convert` (0x2C) `K4`/`K5` — combiner sub-B / mul inputs, raw 9-bit
1704    /// (`K0..K3`, the YUV-convert coefficients, are deferred). R-10.
1705    pub k4: i16,
1706    /// `Set Convert` `K5` (see `k4`).
1707    pub k5: i16,
1708    /// Chroma-key **center** per channel `[r, g, b]` (`Set Key R` 0x2B / `Set Key GB`
1709    /// 0x2A) — the combiner RGB sub-B input (select 6). `0..=255`. R-10.
1710    pub key_center: [u8; 3],
1711    /// Chroma-key **scale** per channel `[r, g, b]` (`Set Key R`/`GB`) — the combiner
1712    /// RGB mul input (select 6). `0..=255`. R-10.
1713    pub key_scale: [u8; 3],
1714    /// Chroma-key **width** per channel `[r, g, b]` (`Set Key R`/`GB`, 12-bit) — the
1715    /// half-width of the key window, consumed by the `key_en` chroma-key alpha compare
1716    /// (`chroma_key_min`), not the combiner mux. R-10.
1717    pub key_width: [u16; 3],
1718    /// The environment color, RGBA8888 (`Set Env Color`, 0x3B).
1719    pub env_color: u32,
1720    /// The blend color, RGBA8888 (`Set Blend Color`, 0x39).
1721    pub blend_color: u32,
1722    /// The fog color, RGBA8888 (`Set Fog Color`, 0x38).
1723    pub fog_color: u32,
1724    /// On-chip texture memory (4 KiB). **Lazily allocated**: `None` until the
1725    /// first byte is written, and read as all-zero while `None`. This keeps
1726    /// [`Rdp`]'s `Default` cheap, which matters because `Bus::rdp_tick` does a
1727    /// `core::mem::take` every RCP step — a `None` placeholder is swapped in with
1728    /// no 4 KiB allocation or copy, while the real TMEM box moves by pointer.
1729    #[serde(with = "rustyn64_snapshot::opt_boxed_bytes")]
1730    tmem: Option<alloc::boxed::Box<[u8; TMEM_SIZE]>>,
1731}
1732
1733impl Rdp {
1734    /// Construct at power-on.
1735    #[must_use]
1736    pub fn new() -> Self {
1737        Self::default()
1738    }
1739
1740    /// Read a DP command register by word offset within the `0x0410_0000`
1741    /// block: 0 `DPC_START`, 1 `DPC_END`, 2 `DPC_CURRENT`, 3 `DPC_STATUS`. The
1742    /// clock/busy/counter registers (4..=7) are not modeled and read zero.
1743    #[must_use]
1744    pub const fn dpc_read(&self, offset: u32) -> u32 {
1745        match offset & 7 {
1746            0 => self.cmd_start,
1747            1 => self.cmd_end,
1748            2 => self.cmd_current,
1749            3 => self.status,
1750            _ => 0,
1751        }
1752    }
1753
1754    /// Write a DP command register (word offsets as in [`Rdp::dpc_read`]).
1755    ///
1756    /// The FIFO uses a double-latch pinned by n64-systemtest's `RSP STATUS:
1757    /// start-valid` and documented in the N64brew wiki (*Reality Display
1758    /// Processor Interface*, the `DPC_END` section):
1759    ///
1760    /// - Writing `DPC_START` latches the (masked) address and sets `START_VALID`
1761    ///   **only if it was clear** — a second write while valid is ignored.
1762    /// - Writing `DPC_END` latches the end address, then branches on
1763    ///   `START_VALID` (the wiki's `START_PENDING`): if **set**, this is a fresh
1764    ///   transfer — copy the pending start into `DPC_CURRENT` and clear
1765    ///   `START_VALID`. If **clear**, it is an *incremental* transfer that
1766    ///   continues from the current position, so `DPC_CURRENT` is left alone
1767    ///   (rewinding it would reprocess already-consumed commands). On unfrozen
1768    ///   hardware the transfer also runs; while frozen only the latch happens.
1769    pub const fn dpc_write(&mut self, offset: u32, value: u32) {
1770        match offset & 7 {
1771            0 => {
1772                if self.status & DP_STATUS_START_VALID == 0 {
1773                    self.cmd_start = value & DPC_ADDR_MASK;
1774                    self.status |= DP_STATUS_START_VALID;
1775                }
1776            }
1777            1 => {
1778                self.cmd_end = value & DPC_ADDR_MASK;
1779                if self.status & DP_STATUS_START_VALID != 0 {
1780                    self.cmd_current = self.cmd_start;
1781                    self.status &= !DP_STATUS_START_VALID;
1782                }
1783            }
1784            3 => self.dpc_write_status(value),
1785            _ => {}
1786        }
1787    }
1788
1789    /// Apply a `DPC_STATUS` write, whose bits are set/clear *commands* rather
1790    /// than the status layout read back. Only XBUS and FREEZE are modeled; the
1791    /// FLUSH/TMEM/PIPE/CMD/CLOCK-counter commands come with the FIFO drain.
1792    // TODO(T-RDP-01): when `SET_FLUSH` (pipeline flush) lands here, it must also
1793    // clear `self.stall` — a flush discards in-flight pipeline work, so a
1794    // leftover sync-stall countdown must not persist across it. Subsystem-scoped
1795    // (pre-ticket) rather than T-31-003, which is the fill pipeline, not flush.
1796    const fn dpc_write_status(&mut self, value: u32) {
1797        const CLEAR_XBUS: u32 = 0x1;
1798        const SET_XBUS: u32 = 0x2;
1799        const CLEAR_FREEZE: u32 = 0x4;
1800        const SET_FREEZE: u32 = 0x8;
1801        if value & CLEAR_XBUS != 0 {
1802            self.status &= !DP_STATUS_XBUS;
1803        }
1804        if value & SET_XBUS != 0 {
1805            self.status |= DP_STATUS_XBUS;
1806        }
1807        if value & CLEAR_FREEZE != 0 {
1808            self.status &= !DP_STATUS_FREEZE;
1809        }
1810        if value & SET_FREEZE != 0 {
1811            self.status |= DP_STATUS_FREEZE;
1812        }
1813    }
1814
1815    /// Advance the RDP by one rasterization step: decode the command at
1816    /// `DPC_CURRENT` and consume its whole length, so the FIFO drains one
1817    /// command per scheduler tick rather than in a burst.
1818    ///
1819    /// Hot path: keep allocation-free. No-op while the FIFO is empty
1820    /// (`DPC_CURRENT >= DPC_END`) or the DP is frozen (`DPC_STATUS.FREEZE`).
1821    ///
1822    /// The command length comes from [`command::command_len_words`], which
1823    /// recognizes every opcode `0x00`–`0x3F`; consuming the exact length is what
1824    /// keeps a multi-word primitive from desyncing the pointer. Today the
1825    /// decoder only advances and counts — no primitive is rasterized yet.
1826    ///
1827    /// Commands are read from RDRAM (the `XBUS` bit clear). The `XBUS`/DMEM
1828    /// command source is not yet wired: the `rdpq` microcode that drives us DMAs
1829    /// its list to RDRAM, so the RDRAM path is the one exercised. With `XBUS`
1830    /// set the decoder **stalls** rather than mis-reading RDRAM as the command
1831    /// stream — decoding DMEM commands out of RDRAM would treat parameter data
1832    /// as opcodes and desync.
1833    ///
1834    /// Dispatch so far (`dispatch`) covers the four sync commands and the FILL
1835    /// pipeline (Set Color Image, Set Fill Color, Set Scissor, Fill Rectangle).
1836    /// Everything else is still recognized-and-consumed only.
1837    ///
1838    /// **This is the whole-step entry point and is not deprecated.** It is what a
1839    /// caller uses when it already holds the bus and has nothing to decide — tests,
1840    /// and any future embedder. `Bus::rdp_tick` in `rustyn64-core` instead calls the two
1841    /// halves directly, because it must know whether the step needs the bus *before*
1842    /// arranging one: the arranging is a `core::mem::take` of this whole struct.
1843    /// Splitting is worth it only for that caller, which is why the convenient form
1844    /// stays.
1845    pub fn tick<B: VideoBus>(&mut self, bus: &mut B) {
1846        if let Some(proof) = self.tick_without_bus() {
1847            self.tick_with_bus(proof, bus);
1848        }
1849    }
1850
1851    /// Whether this step would answer entirely from the RDP's own state — frozen,
1852    /// XBUS-sourced, stalling on a sync, or looking at an empty command FIFO.
1853    ///
1854    /// A **census predicate**, deliberately read-only: it must not consume the
1855    /// stall the real step consumes, or measuring would change what is measured.
1856    /// It duplicates [`Rdp::tick_without_bus`]'s early-outs for that reason, and
1857    /// the two are pinned together by `census_predicate_agrees_with_the_real_early_outs`.
1858    #[cfg(feature = "work-counters")]
1859    #[must_use]
1860    pub fn is_idle_for_census(&self) -> bool {
1861        self.status & (DP_STATUS_FREEZE | DP_STATUS_XBUS) != 0
1862            || self.stall > 0
1863            || self.cmd_current >= self.cmd_end
1864    }
1865
1866    /// The part of a step that needs **no bus access**, returning `None` when it
1867    /// finished the step on its own and `Some(NeedsBus)` when work remains.
1868    ///
1869    /// **This advances state**, despite the `Option` return: on the stalling path it
1870    /// burns one GCLK. It is named `tick_*` rather than `is_*` for that reason — in
1871    /// this codebase `tick` means *advance by one step*, as in `Bus::rsp_tick` and
1872    /// `Cpu::tick_at`.
1873    ///
1874    /// Split out so a caller can decide whether to pay for bus access *before*
1875    /// arranging it. `Bus::rdp_tick` moves this whole struct out of the Bus with
1876    /// `core::mem::take` to satisfy the borrow checker — 344 bytes read and written,
1877    /// plus a default written back, on **every RCP step** — and on most steps the
1878    /// answer here is `None`, so that shuffle bought nothing
1879    /// (`docs/performance.md` §"The Bus split-borrow moves 1.35 GB a frame").
1880    ///
1881    /// It lives here rather than in the Bus because it is a statement about *this*
1882    /// chip's early-outs: if they change, this changes with them, in the same file.
1883    /// [`Rdp::tick`] calls it too, so there is one implementation and no way for the
1884    /// two to disagree.
1885    ///
1886    /// Returns [`NeedsBus`] when the step still has work that requires RDRAM. That
1887    /// token is the only way to reach [`Rdp::tick_with_bus`], so the two halves cannot
1888    /// be called out of order — the preconditions are carried by the type rather than
1889    /// by a comment or an assertion.
1890    #[must_use = "a `Some` means the step is unfinished and needs `tick_with_bus`"]
1891    pub fn tick_without_bus(&mut self) -> Option<NeedsBus> {
1892        // Frozen or DMEM-sourced (XBUS, not yet wired): the pipeline counter is
1893        // halted, so do not even burn a stall cycle.
1894        if self.status & (DP_STATUS_FREEZE | DP_STATUS_XBUS) != 0 {
1895            return None;
1896        }
1897        // A prior sync is still stalling the pipeline — burn one GCLK and hold
1898        // the FIFO until the stall expires.
1899        if self.stall > 0 {
1900            self.stall -= 1;
1901            return None;
1902        }
1903        // An empty command FIFO. A plain `>=` is right because these are RDRAM
1904        // addresses, not ring indices: `DPC_START`/`DPC_END` are latched through
1905        // `DPC_ADDR_MASK` in [`Rdp::dpc_write`], `cmd_current` only ever advances by a
1906        // decoded command's length, and the hardware has no wrap — a driver that wants
1907        // to restart writes `DPC_START` again. So there is no wrapped case for this
1908        // comparison to get wrong.
1909        //
1910        // The *partially written* case cannot be decided here: its length comes from an
1911        // opcode that lives in RDRAM, which is exactly why the check below is on the far
1912        // side of the split.
1913        if self.cmd_current >= self.cmd_end {
1914            return None;
1915        }
1916        Some(NeedsBus(()))
1917    }
1918
1919    /// The remainder of a step, once [`Rdp::tick_without_bus`] has handed back a
1920    /// [`NeedsBus`].
1921    ///
1922    /// Reachable only with a [`NeedsBus`], which [`Rdp::tick_without_bus`] hands out
1923    /// exactly when the FIFO is non-empty and the pipeline is neither frozen nor
1924    /// stalled. Those preconditions are therefore not asserted here: an assertion that
1925    /// cannot fire is dead code that reads like a safeguard.
1926    ///
1927    /// The token is taken **by value**, not by reference, so it is consumed: one
1928    /// `tick_without_bus` authorizes exactly one bus half. Relaxing this to
1929    /// `&NeedsBus` would let a caller hold one and re-enter after the state it
1930    /// attested to had changed, which is the whole property being bought here.
1931    pub fn tick_with_bus<B: VideoBus>(&mut self, _proof: NeedsBus, bus: &mut B) {
1932        let word0_hi = bus.rdram_read_u32(self.cmd_current);
1933        let opcode = command::opcode_of(word0_hi);
1934        let len_bytes = command::command_len_words(opcode) * 8;
1935        // Consume a command only once it is present in full. The `rdpq`
1936        // microcode advances `DPC_END` incrementally as it fills the buffer, so
1937        // `DPC_END` can land mid-command; consuming a partially-written
1938        // multi-word primitive would decode against unwritten RDRAM. The guard
1939        // above guarantees `cmd_current < cmd_end`, so the subtraction cannot
1940        // underflow.
1941        if self.cmd_end - self.cmd_current < len_bytes {
1942            return;
1943        }
1944        // The low half of the first command word. Multi-word commands (e.g.
1945        // Texture Rectangle, 2 words) read their later words through `cmd_base`,
1946        // the command's RDRAM address captured *before* the pointer advances.
1947        let word0_lo = bus.rdram_read_u32(self.cmd_current.wrapping_add(4));
1948        let cmd_base = self.cmd_current;
1949        self.cmd_current = self.cmd_current.wrapping_add(len_bytes);
1950        self.commands_processed = self.commands_processed.wrapping_add(1);
1951        self.dispatch(opcode, word0_hi, word0_lo, cmd_base, bus);
1952    }
1953
1954    /// Act on a just-consumed command. Only the sync commands are handled so
1955    /// far; every other opcode is a recognized no-op until its handler lands.
1956    ///
1957    /// - `Sync Load`/`Pipe`/`Tile` (0x26/0x27/0x28) each stall the pipeline for
1958    ///   a fixed, unconditional number of GCLK cycles (25/50/33) — the RDP waits
1959    ///   the full time whether or not the sync was needed, which is why the
1960    ///   stall is a constant and not a wait on an internal signal.
1961    /// - `Sync Full` (0x29) **raises the DP interrupt** (`raise_dp_interrupt`) —
1962    ///   the only part of the command implemented. On hardware it first waits for
1963    ///   all staged pipeline/memory work and halts the pipeline counter; neither
1964    ///   is modeled (there is no asynchronous pipeline work yet, and no pipeline
1965    ///   counter), so the interrupt is raised as soon as the command is
1966    ///   dispatched. A *preceding* sync stall still delays this dispatch via the
1967    ///   `stall` gate above (checked before a command is dispatched), so a queued
1968    ///   stall drains before the interrupt fires.
1969    ///
1970    /// On stall resolution: per-command *execution* cost is not modeled yet —
1971    /// every command is consumed in a single placeholder `tick` — so the `stall`
1972    /// set here is the documented pipeline stall *layered on top of* that one
1973    /// consume tick, not a claim about total command latency (the next command
1974    /// resumes after `1 + N` ticks). The stall itself is exactly the documented
1975    /// N GCLK; exact per-command base timing is deferred to the command-timing
1976    /// model.
1977    ///
1978    /// The rectangle arms take the command's two 32-bit halves (`hi` = RDRAM bits
1979    /// 63:32, `lo` = 31:0). `Fill Rectangle` covers the rectangle ∩ scissor; what
1980    /// it writes depends on `Set Other Modes.cycle_type` — the fill register in
1981    /// FILL/COPY, the combiner output in 1-/2-cycle (ledger R-21).
1982    fn dispatch<B: VideoBus>(&mut self, opcode: u8, hi: u32, lo: u32, cmd_base: u32, bus: &mut B) {
1983        match opcode {
1984            OP_SYNC_LOAD => self.stall = SYNC_LOAD_GCLK,
1985            OP_SYNC_PIPE => self.stall = SYNC_PIPE_GCLK,
1986            OP_SYNC_TILE => self.stall = SYNC_TILE_GCLK,
1987            OP_SYNC_FULL => bus.raise_dp_interrupt(),
1988            OP_SET_COLOR_IMAGE => {
1989                // format[2:0] = hi 23:21, size[1:0] = hi 20:19, width[9:0] = hi
1990                // 9:0 (minus one), dramAddress[23:0] = lo 23:0.
1991                self.color_image_format = ((hi >> 21) & 0x7) as u8;
1992                self.color_image_size = ((hi >> 19) & 0x3) as u8;
1993                self.color_image_width = ((hi & 0x3FF) as u16).wrapping_add(1);
1994                self.color_image = lo & 0x00FF_FFFF;
1995            }
1996            OP_SET_FILL_COLOR => self.fill_color = lo,
1997            OP_SET_PRIM_COLOR => {
1998                // word 0 (hi): min_level[12:8] (the LOD magnify floor, R-13),
1999                // prim_lod_frac[7:0]; word 1 (lo): RGBA.
2000                self.prim_color = lo;
2001                self.prim_lod_frac = (hi & 0xFF) as u8;
2002                self.min_level = ((hi >> 8) & 0x1F) as u8;
2003            }
2004            OP_SET_CONVERT => {
2005                // K4 = lo[17:9], K5 = lo[8:0], stored as the raw 0..511 value the
2006                // hardware holds (matching Angrylion `rdp_set_convert`); the combiner
2007                // sign-extends them downstream (`special_expand`/`sext9`), so signing
2008                // here would double-apply. K0..K3 (the YUV-convert coefficients, in the
2009                // hi word and lo[31:18]) are deliberately ignored — deferred, R-10.
2010                self.k4 = ((lo >> 9) & 0x1FF) as i16;
2011                self.k5 = (lo & 0x1FF) as i16;
2012            }
2013            OP_SET_KEY_GB => {
2014                // word 0 (hi): width_g[23:12], width_b[11:0]; word 1 (lo):
2015                // center_g[31:24], scale_g[23:16], center_b[15:8], scale_b[7:0]
2016                // (Angrylion `rdp_set_key_gb`). Widths feed the `key_en` alpha compare.
2017                self.key_width[1] = ((hi >> 12) & 0xFFF) as u16;
2018                self.key_width[2] = (hi & 0xFFF) as u16;
2019                self.key_center[1] = (lo >> 24) as u8;
2020                self.key_scale[1] = (lo >> 16) as u8;
2021                self.key_center[2] = (lo >> 8) as u8;
2022                self.key_scale[2] = lo as u8;
2023            }
2024            OP_SET_KEY_R => {
2025                // word 1 (lo): width_r[27:16] (12-bit), center_r[15:8], scale_r[7:0]
2026                // (Angrylion `rdp_set_key_r`, `(args[1] >> 16) & 0xfff`).
2027                self.key_width[0] = ((lo >> 16) & 0xFFF) as u16;
2028                self.key_center[0] = (lo >> 8) as u8;
2029                self.key_scale[0] = lo as u8;
2030            }
2031            OP_SET_ENV_COLOR => self.env_color = lo,
2032            OP_SET_BLEND_COLOR => self.blend_color = lo,
2033            OP_SET_FOG_COLOR => self.fog_color = lo,
2034            OP_SET_DEPTH_IMAGE => self.z_image = lo & 0x00FF_FFFF,
2035            OP_SET_PRIM_DEPTH => {
2036                // z[15:0] = lo 31:16 (s15.3, integer part), dz[15:0] = lo 15:0.
2037                self.prim_z = (lo >> 16) as u16;
2038                self.prim_dz = lo as u16;
2039            }
2040            OP_SET_OTHER_MODES => self.set_other_modes(hi, lo),
2041            OP_SET_COMBINE_MODE => self.set_combine_mode(hi, lo),
2042            OP_SET_SCISSOR => {
2043                // upper-left x/y = hi 23:12 / 11:0, lower-right x/y = lo 23:12 /
2044                // 11:0 (all u10.2). The field/odd interlace bits (lo 25/24) are
2045                // not modeled yet.
2046                self.scissor_ulx = ((hi >> 12) & 0xFFF) as u16;
2047                self.scissor_uly = (hi & 0xFFF) as u16;
2048                self.scissor_lrx = ((lo >> 12) & 0xFFF) as u16;
2049                self.scissor_lry = (lo & 0xFFF) as u16;
2050            }
2051            OP_FILL_RECTANGLE => self.fill_rectangle(hi, lo, bus),
2052            OP_SET_TEXTURE_IMAGE => {
2053                // Same field layout as Set Color Image: format[55:53] = hi
2054                // 23:21, size[52:51] = hi 20:19, width[41:32] = hi 9:0 (minus
2055                // one), dramAddress[23:0] = lo 23:0.
2056                self.tex_image_format = ((hi >> 21) & 0x7) as u8;
2057                self.tex_image_size = ((hi >> 19) & 0x3) as u8;
2058                self.tex_image_width = ((hi & 0x3FF) as u16).wrapping_add(1);
2059                self.tex_image_addr = lo & 0x00FF_FFFF;
2060            }
2061            OP_SET_TILE => self.set_tile(hi, lo),
2062            OP_SET_TILE_SIZE => self.set_tile_size(hi, lo),
2063            OP_LOAD_TILE => self.load_tile(hi, lo, bus),
2064            OP_LOAD_BLOCK => self.load_block(hi, lo, bus),
2065            OP_LOAD_TLUT => self.load_tlut(hi, lo, bus),
2066            OP_TEXTURE_RECTANGLE => self.texture_rectangle(hi, lo, cmd_base, bus, false),
2067            OP_TEXTURE_RECTANGLE_FLIP => self.texture_rectangle(hi, lo, cmd_base, bus, true),
2068            // Fill Triangle and its shade/texture/Z variants (0x08–0x0F): flat-fill
2069            // the triangle for now (the shade/texture/Z coefficient blocks and the
2070            // combiner/blender come later in Sprint 3).
2071            0x08..=0x0F => self.triangle_fill(hi, lo, cmd_base, bus),
2072            // TODO(T-31-004): remaining opcodes are recognized and
2073            // length-consumed by `tick`, but not yet dispatched — an
2074            // intentional, documented no-op at this stage, not a silent discard.
2075            // Handlers arrive per ticket (VI scan-out, then texture / combiner /
2076            // blender), and `docs/rdp.md` is the authoritative list of what is
2077            // dispatched versus recognized-only, so a later missing arm is caught
2078            // against that spec rather than passing silently here.
2079            _ => {}
2080        }
2081    }
2082
2083    /// Bytes per pixel for the current color-image size, or `None` for the
2084    /// 4-bit mode, which cannot be a FILL-mode render target (it would crash the
2085    /// real RDP — N64brew *…/Commands* §Set Color Image hazards).
2086    const fn color_image_bpp(&self) -> Option<u32> {
2087        match self.color_image_size {
2088            1 => Some(1), // 8-bit
2089            2 => Some(2), // 16-bit
2090            3 => Some(4), // 32-bit
2091            _ => None,    // 4-bit: crash on the real RDP
2092        }
2093    }
2094
2095    /// Render a `Fill Rectangle` (0x36) over the rectangle ∩ scissor.
2096    ///
2097    /// **What is written depends on `Set Other Modes.cycle_type`** (ledger R-21).
2098    /// FILL and COPY repeat the `Set Fill Color` register verbatim; 1-/2-cycle
2099    /// treat the rectangle as an ordinary primitive and take the **combiner**
2100    /// output, then alpha-compare and dither, exactly as the triangle path does.
2101    /// A rectangle carries no shade or texture block, so the combiner sees only
2102    /// its register inputs and the result is constant across the whole rectangle.
2103    ///
2104    /// FILL mode "repeats the 32-bit value verbatim out to memory", which
2105    /// resolves per pixel by size (N64brew *…/Commands* §Set Fill Color):
2106    /// 32-bit writes the whole color; 16-bit takes the upper half for even
2107    /// pixels and the lower half for odd; 8-bit takes byte `x & 3`. Coordinates
2108    /// are `u10.2`; FILL mode floors the upper-left and draws through the pixel
2109    /// **containing** the lower-right coordinate (inclusive), with `yl | 3` forcing
2110    /// the last scanline whole (Angrylion `rasterizer.c`). The **scissor** clips
2111    /// with an **exclusive** lower-right. This integer-coordinate rule is
2112    /// oracle-validated against Angrylion (`docs/accuracy-ledger.md` R-3, the
2113    /// seeded-fuzz corpus); the remaining residual is **sub-pixel** (fractional)
2114    /// rectangle edges, which the whole-pixel corpus does not exercise.
2115    fn fill_rectangle<B: VideoBus>(&self, hi: u32, lo: u32, bus: &mut B) {
2116        let Some(bpp) = self.color_image_bpp() else {
2117            return; // 4-bit target: the real RDP crashes; we skip.
2118        };
2119        // No color image configured yet (width is field+1, so a real Set Color
2120        // Image never yields 0). Rendering before it is a documented hazard —
2121        // the real RDP writes to an unspecified location — so we write nothing
2122        // rather than smear every row onto offset 0 with a zero stride.
2123        if self.color_image_width == 0 {
2124            return;
2125        }
2126        // Rectangle: lower-right x/y = hi 23:12 / 11:0, upper-left x/y = lo 23:12
2127        // / 11:0 (all u10.2). Floor the upper-left. The lower-right is **inclusive**
2128        // of the pixel that contains the coordinate, and in FILL/COPY mode the RDP
2129        // forces the low two bits of `yl` set before the shift (Angrylion
2130        // `rasterizer.c` `rdp_fill_rect`: `yl |= 3`, so the final scanline is filled
2131        // whole). Both confirmed against the Angrylion conformance oracle (ledger
2132        // R-3): a rect whose lower-right lands on an integer pixel boundary still
2133        // draws that pixel row/column. Convert the inclusive pixel index to a
2134        // half-open bound with `+ 1`.
2135        let rect_xh = (lo >> 12) & 0xFFF; // rect upper-left x, u10.2
2136        let rx0 = rect_xh >> 2;
2137        let ry0 = (lo & 0xFFF) >> 2;
2138        let rx1 = (((hi >> 12) & 0xFFF) >> 2) + 1;
2139        let ry1 = (((hi & 0xFFF) | 3) >> 2) + 1;
2140        // Scissor clip is **asymmetric** (ledger R-15, oracle-confirmed against
2141        // Angrylion `rasterizer.c` `edgewalker_for_prims`). The **Y** lower-right is
2142        // **exclusive** (scanlines at or past `scissor.yl` are dropped:
2143        // `invaly = k >= yllimit`) — the RDP shows this because FILL/COPY forces the
2144        // *rectangle's* `yl | 3` while the scissor's `yl` stays raw. The **X**
2145        // lower-right is **inclusive** of the pixel containing `scissor.xl`, EXCEPT
2146        // that the horizontal clip drops the whole scanline when the rectangle lies
2147        // entirely at or past the scissor's right edge (`allover`: the rect's left
2148        // edge is `>= scissor.xl`) — without that guard the inclusive bound would
2149        // spuriously draw the single boundary column when a rect starts exactly on
2150        // the scissor's right edge.
2151        let scissor_xl = u32::from(self.scissor_lrx);
2152        if rect_xh >= scissor_xl {
2153            return; // rectangle entirely right of the scissor: nothing drawn
2154        }
2155        let sx0 = u32::from(self.scissor_ulx) >> 2;
2156        let sy0 = u32::from(self.scissor_uly) >> 2;
2157        let sx1 = (scissor_xl >> 2) + 1; // inclusive right pixel -> half-open
2158        // Exclusive Y: `(lry + 3) >> 2` keeps a row iff any of its four sub-scanlines
2159        // is `< lry` (Angrylion drops `k >= yllimit`), so a fractional `lry` still
2160        // draws the partially-covered row while an integer `lry` drops it whole.
2161        let sy1 = (u32::from(self.scissor_lry) + 3) >> 2;
2162        // Intersection of rectangle and scissor (half-open), then a hard clip to the
2163        // color-image width: a pixel at or past the stride would spill into the next
2164        // row, so the inclusive X bounds never write beyond the framebuffer.
2165        let x0 = rx0.max(sx0);
2166        let y0 = ry0.max(sy0);
2167        let x1 = rx1.min(sx1).min(u32::from(self.color_image_width));
2168        let y1 = ry1.min(sy1);
2169        if x0 >= x1 || y0 >= y1 {
2170            return;
2171        }
2172        let stride = u32::from(self.color_image_width) * bpp;
2173        // **Only FILL and COPY take the fill register.** In 1-/2-cycle mode a
2174        // rectangle is an ordinary primitive and goes through the combiner; it
2175        // carries no shade or texture, so the combiner sees only its register
2176        // inputs (prim/env/…) and the fill register is never consulted. Confirmed
2177        // against the Angrylion oracle (ledger R-21, vector `fill_rect_1cycle_16`):
2178        // a 1-cycle rectangle with a green fill register and a *distinct* prim
2179        // color renders the **prim** color in all 64 pixels.
2180        if matches!(
2181            self.other_modes.cycle_type,
2182            CYCLE_TYPE_COPY | CYCLE_TYPE_FILL
2183        ) {
2184            for y in y0..y1 {
2185                let row = self.color_image.wrapping_add(y * stride);
2186                for x in x0..x1 {
2187                    self.fill_pixel(row, x, bpp, bus);
2188                }
2189            }
2190            return;
2191        }
2192
2193        // 1-/2-cycle: the combiner output is **loop-invariant**. A rectangle has
2194        // no shade or texture block, so `combined_color` reads only the prim/env/
2195        // key/convert registers and the interpolation origin
2196        // (`major_x`/`line`/`y_base`/`x`) is unused — hence the zeros. Evaluating
2197        // it once per rectangle rather than once per pixel is not a speculative
2198        // optimization but a statement of that invariance: if this ever needs to
2199        // move back inside the loop, something has started varying per pixel and
2200        // the change deserves the scrutiny.
2201        let (base, _shade_alpha) = self.combined_color(None, None, 0, 0, 0, 0, 0);
2202        // Alpha-compare gates the write exactly as on the triangle path — and on
2203        // an invariant alpha it either passes for every pixel or for none, so the
2204        // whole rectangle is rejected here rather than per pixel.
2205        if !self.alpha_compare_passes(base[3]) {
2206            return;
2207        }
2208        for y in y0..y1 {
2209            let row = self.color_image.wrapping_add(y * stride);
2210            for x in x0..x1 {
2211                // Dither is the one genuinely per-pixel step, so it works on a
2212                // copy and must not mutate the shared `base`.
2213                let mut color = base;
2214                self.dither_pixel(&mut color, x, y);
2215                Self::write_pixel(row, x, bpp, color, bus);
2216            }
2217        }
2218    }
2219
2220    /// Apply a `Texture Rectangle` (0x24) / `Flip` (0x25) in **COPY mode**: blit a
2221    /// tile into the color image. Word 0 carries the screen rectangle (`u10.2`)
2222    /// and the tile; word 1 (read from `cmd_base`) carries the texture start
2223    /// (`S`/`T`, `s10.5`) and the per-pixel increments (`DsDx`/`DtDy`, `s5.10`).
2224    ///
2225    /// COPY mode is a raw texel blit — no combiner or blender. The lower-right
2226    /// screen bound is inclusive. For a 16-bit color image the texel bits are
2227    /// copied verbatim (a direct 16-bit copy). `S` steps across X and `T` down Y
2228    /// (`Flip` swaps them); the horizontal step is scaled by the 4-pixels-per-cycle
2229    /// factor (`>> (5 + dx_shift)`) so a 1:1 blit's `DsDx = 4.0` advances one texel
2230    /// per pixel.
2231    ///
2232    /// Scope (**open residual R-8**): wired for a **16-bit tile → 16-bit color
2233    /// image** (the first-picture path). `Flip`, the 8/32-bit and TLUT copy paths,
2234    /// non-1:1 sub-texel selection, and the copy alpha-compare are deferred to the
2235    /// ParaLLEl-RDP fuzz validation (Sprint 3); an unsupported configuration draws
2236    /// nothing.
2237    // The coordinate/address arithmetic casts here (screen/texel coords to `i32`
2238    // and back to `u32` offsets) wrap deliberately: a degenerate coordinate wraps
2239    // into the framebuffer/TMEM space rather than trapping. `bus` IS used mutably
2240    // (`rdram_write` in the inner loop); `needless_pass_by_ref_mut` mis-analyzes the
2241    // mutable trait call nested past the early-return guard (a known false positive).
2242    #[allow(
2243        clippy::cast_sign_loss,
2244        clippy::cast_possible_wrap,
2245        clippy::needless_pass_by_ref_mut
2246    )]
2247    fn texture_rectangle<B: VideoBus>(
2248        &mut self,
2249        hi: u32,
2250        lo: u32,
2251        cmd_base: u32,
2252        bus: &mut B,
2253        flip: bool,
2254    ) {
2255        // Word 0: screen rectangle (u10.2) + tile index.
2256        let xl = (hi >> 12) & 0xFFF;
2257        let yl = hi & 0xFFF;
2258        let tile_idx = ((lo >> 24) & 0x7) as usize;
2259        let xh = (lo >> 12) & 0xFFF;
2260        let yh = lo & 0xFFF;
2261        // Word 1: texture start (s10.5) + increments (s5.10).
2262        let w1_hi = bus.rdram_read_u32(cmd_base.wrapping_add(8));
2263        let w1_lo = bus.rdram_read_u32(cmd_base.wrapping_add(12));
2264        // S/T are signed s10.5 (a scrolled/wrapped tile can start negative), so
2265        // sign-extend like DsDx/DtDy — a plain mask would read bit 15 as +32768.
2266        let s_start = sext16(w1_hi >> 16);
2267        let t_start = sext16(w1_hi);
2268        let dsdx = sext16(w1_lo >> 16);
2269        let dtdy = sext16(w1_lo);
2270
2271        let tile = self.tiles[tile_idx];
2272        // Only the 16-bit -> 16-bit copy is wired (R-8): both the 1:1 and the non-1:1
2273        // 4-pixels-per-cycle cases now model correctly, but `Flip` (0x25), 8/32-bit,
2274        // and TLUT copy are still unsupported and draw nothing.
2275        if flip || tile.size != 2 || self.color_image_size != 2 || self.color_image_width == 0 {
2276            return;
2277        }
2278        let dx_shift = 2u32; // 4 pixels per 64-bit cycle for a 16-bit image.
2279        // Integer pixel bounds; COPY mode's lower-right is inclusive.
2280        let px0 = xh >> 2;
2281        let py0 = yh >> 2;
2282        // Clip to the scissor (floor upper-left, and the rect's inclusive lower-right).
2283        let x_lo = px0.max(u32::from(self.scissor_ulx) >> 2);
2284        let y_lo = py0.max(u32::from(self.scissor_uly) >> 2);
2285        let x_hi =
2286            (xl >> 2).min((u32::from(self.scissor_lrx).wrapping_add(3) >> 2).saturating_sub(1));
2287        let y_hi =
2288            (yl >> 2).min((u32::from(self.scissor_lry).wrapping_add(3) >> 2).saturating_sub(1));
2289        let stride = u32::from(self.color_image_width) * 2;
2290        for py in y_lo..=y_hi {
2291            let row = (py - py0) as i32;
2292            let t105 = t_start + ((dtdy * row) >> 5);
2293            let t_tex = wrap_coord(t105, tile.shift_t, tile.mask_t, tile.mirror_t, tile.tl);
2294            let swap = ((t_tex & 1) << 2) as u32;
2295            let t_row = u32::from(tile.line)
2296                .wrapping_mul(8)
2297                .wrapping_mul(t_tex as u32);
2298            let row_addr = self.color_image.wrapping_add(py.wrapping_mul(stride));
2299            for px in x_lo..=x_hi {
2300                let col = (px - px0) as i32;
2301                // COPY mode processes **4 pixels per cycle**: each cycle reads a
2302                // 64-bit TMEM word (4 consecutive 16-bit texels) and writes them to
2303                // 4 output pixels. So the base texel is evaluated at the cycle's
2304                // first column (advancing by `DsDx * 4` texels per cycle), and the
2305                // within-cycle offset is a direct `+0..3` TMEM increment — NOT a
2306                // per-pixel coordinate step (N64brew *…/Commands* §Texture Rectangle
2307                // copy; ledger R-8). For `DsDx = 4.0` (1:1) this reduces to `s = col`.
2308                let cycle_start = col & !3;
2309                let within = col & 3;
2310                let base_s105 = s_start + ((dsdx * cycle_start) >> (5 + dx_shift));
2311                let base_tex =
2312                    wrap_coord(base_s105, tile.shift_s, tile.mask_s, tile.mirror_s, tile.sl);
2313                let s_tex = base_tex + within;
2314                // Raw 16-bit texel fetch (RGBA16 addressing, no decode).
2315                let boff = (u32::from(tile.tmem_addr).wrapping_mul(8))
2316                    .wrapping_add(t_row)
2317                    .wrapping_add((s_tex as u32).wrapping_mul(2))
2318                    ^ swap;
2319                let texel = self.tmem_u16(boff);
2320                let addr = row_addr.wrapping_add(px.wrapping_mul(2));
2321                bus.rdram_write(addr, (texel >> 8) as u8);
2322                bus.rdram_write(addr.wrapping_add(1), (texel & 0xFF) as u8);
2323            }
2324        }
2325    }
2326
2327    /// Write the FILL-mode color to one pixel of the color image (shared by the
2328    /// fill rectangle and the flat-fill triangle). `bpp` is 1/2/4; the 16-bit case
2329    /// takes the upper half of the fill register for even `x` and the lower for
2330    /// odd, and the 8-bit case cycles the four bytes — as `Set Fill Color` defines.
2331    fn fill_pixel<B: VideoBus>(&self, row_addr: u32, x: u32, bpp: u32, bus: &mut B) {
2332        let addr = row_addr.wrapping_add(x.wrapping_mul(bpp));
2333        let color = self.fill_color.to_be_bytes();
2334        match bpp {
2335            4 => {
2336                for (i, b) in color.iter().enumerate() {
2337                    bus.rdram_write(addr.wrapping_add(i as u32), *b);
2338                }
2339            }
2340            2 => {
2341                let half = if x & 1 == 0 { 0 } else { 2 };
2342                bus.rdram_write(addr, color[half]);
2343                bus.rdram_write(addr.wrapping_add(1), color[half + 1]);
2344            }
2345            1 => bus.rdram_write(addr, color[(x & 3) as usize]),
2346            _ => {}
2347        }
2348    }
2349
2350    /// Flat-fill a `Fill Triangle` (0x08) or one of its shade/texture/Z variants
2351    /// (0x09–0x0F). Decode the three edges (major `H` yh→yl, minor `M` yh→ym, minor
2352    /// `L` ym→yl), walk each scanline's span between the major edge and the active
2353    /// minor edge, and write the FILL-mode color into the span — the FILL-cycle
2354    /// path (a 1-/2-cycle triangle is colored by the combiner/blender, which is
2355    /// later in Sprint 3, so the shade/texture/Z coefficient words are ignored
2356    /// here, only length-consumed).
2357    ///
2358    /// Y is `s11.2` (four sub-scanlines per pixel); X and the slopes are `s11.16` /
2359    /// `s13.16`. Per sub-scanline the edge X is `x0 + (y − yh_base) * slope`,
2360    /// reduced to a whole pixel (`>> 16`); `lmajor`/`flip` (bit 55) selects which
2361    /// edge is the left bound. Matched to the ParaLLEl-RDP `interpolate_x` walk
2362    /// (native scaling — no upscale sub-pixel bit); the bit-exact sub-pixel
2363    /// coverage (`quantize_x` sticky bit) and attribute interpolation are deferred
2364    /// to the fuzz-validated pipeline (**open residual R-9**).
2365    // `bus` IS used mutably (`fill_pixel` → `rdram_write`); the lint mis-analyzes the
2366    // call nested past the early returns. `xl`/`xh`/`xm` etc. are the hardware edge names.
2367    #[allow(
2368        clippy::cast_sign_loss,
2369        clippy::cast_possible_truncation,
2370        clippy::needless_pass_by_ref_mut,
2371        clippy::similar_names
2372    )]
2373    #[allow(
2374        clippy::too_many_lines,
2375        reason = "the rasterizer's edge decode, span walk, and the flat/shaded/depth render paths are one tightly-coupled unit; splitting further would fragment the shared setup"
2376    )]
2377    fn triangle_fill<B: VideoBus>(&mut self, hi: u32, lo: u32, cmd_base: u32, bus: &mut B) {
2378        let Some(bpp) = self.color_image_bpp() else {
2379            return;
2380        };
2381        if self.color_image_width == 0 {
2382            return;
2383        }
2384        let flip = hi >> 23 & 1 != 0;
2385        // The primitive's base tile (bits 50:48 of the command = `hi` bits 18:16;
2386        // `(ewdata[0] >> 16) & 7` in Angrylion `rasterizer.c`). Selects the tile
2387        // descriptor the texture sampler reads (and `base+1` in 2-cycle mode).
2388        let base_tile = ((hi >> 16) & 7) as usize;
2389        // `level[2:0]` (bits 53:51): the mip-level count, which the LOD fraction
2390        // reads (`max_level == 0` means "no mip chain", so the LOD is fully
2391        // distant). Per-primitive state, as in Angrylion `rasterizer.c`. R-13.
2392        self.max_level = ((hi >> 19) & 7) as u8;
2393        let yl = sext(hi & 0x3FFF, 14);
2394        let mut ym = sext(lo >> 16 & 0x3FFF, 14);
2395        let yh = sext(lo & 0x3FFF, 14);
2396        if yl <= yh {
2397            return; // degenerate
2398        }
2399        // The triangle setup guarantees yh <= ym <= yl (sorted vertices); clamp
2400        // malformed input into range so the M/L edge split stays well-defined.
2401        ym = ym.clamp(yh, yl);
2402        // Edge coefficients: words 1 (L), 2 (H major), 3 (M).
2403        //
2404        // The slopes `dx?dy` are `s13.16` **dx per pixel-row** (N64brew *…/Commands*
2405        // §Edge Coefficients: "change in x per change in y", with `yh/ym/yl` in
2406        // `s11.2` *screen* pixels). The edge-walk below advances the edge per
2407        // Y-subpixel — `y = line*4 + sub` is in **quarter-pixel** units — so each
2408        // slope is pre-shifted `>> SUB_SCANLINE_SHIFT` to a per-quarter-pixel step
2409        // (parallel-rdp `span_setup.comp:167`, where `setup.dxhdy = raw >> 2`).
2410        // Omitting this advanced every edge 4× too fast (ledger R-14, caught by the
2411        // T-33-005 conformance gate against Angrylion). The arithmetic shift rounds
2412        // a negative slope toward −∞, matching the hardware (`fill_tri_neg_16`).
2413        let xl = sext(
2414            bus.rdram_read_u32(cmd_base.wrapping_add(8)) & 0x0FFF_FFFF,
2415            28,
2416        );
2417        let dxldy = sext(
2418            bus.rdram_read_u32(cmd_base.wrapping_add(12)) & 0x3FFF_FFFF,
2419            30,
2420        ) >> SUB_SCANLINE_SHIFT;
2421        let xh = sext(
2422            bus.rdram_read_u32(cmd_base.wrapping_add(16)) & 0x0FFF_FFFF,
2423            28,
2424        );
2425        let dxhdy = sext(
2426            bus.rdram_read_u32(cmd_base.wrapping_add(20)) & 0x3FFF_FFFF,
2427            30,
2428        ) >> SUB_SCANLINE_SHIFT;
2429        let xm = sext(
2430            bus.rdram_read_u32(cmd_base.wrapping_add(24)) & 0x0FFF_FFFF,
2431            28,
2432        );
2433        let dxmdy = sext(
2434            bus.rdram_read_u32(cmd_base.wrapping_add(28)) & 0x3FFF_FFFF,
2435            30,
2436        ) >> SUB_SCANLINE_SHIFT;
2437
2438        // Scissor in integer pixels (u10.2 -> pixel).
2439        let sx0 = i32::from(self.scissor_ulx) >> 2;
2440        let sx1 = i32::from(self.scissor_lrx) >> 2;
2441        let sy0 = i32::from(self.scissor_uly) >> 2;
2442        let sy1 = i32::from(self.scissor_lry) >> 2;
2443        let start_line = (yh >> 2).max(sy0);
2444        let end_line = ((yl - 1) >> 2).min(sy1 - 1);
2445        let yh_base = yh & !3;
2446        let width = i32::from(self.color_image_width);
2447        let stride = (width as u32).wrapping_mul(bpp);
2448
2449        // Per-pixel depth path (T-33-004 PR-B part 2a): active when the command
2450        // carries z-coefficients (bit 56, the opcode's low bit) and `Set Other
2451        // Modes` enables the depth test or update. The z-suffix follows the 4-word
2452        // base plus the shade (bit 58) and texture (bit 57) blocks, in that order.
2453        let z_setup = if self.other_modes.z_compare_en || self.other_modes.z_update_en {
2454            Self::decode_triangle_z(hi, cmd_base, bus)
2455        } else {
2456            None
2457        };
2458        // Shade block (bit 58): when present, the pixel color comes from the
2459        // combiner fed the interpolated shade, not the FILL register (T-33-004
2460        // PR-B 2b — the first shaded triangle).
2461        let shade_setup = Self::decode_shade(hi, cmd_base, bus);
2462        // Texture block (bit 57): the combiner samples tile 0 at the interpolated
2463        // (non-perspective) coordinate. The perspective divide is a later slice.
2464        let tex_setup = Self::decode_texture(hi, cmd_base, bus);
2465        // **The CYCLE TYPE decides the path, not the presence of a shade block**
2466        // (ledger R-21's still-open half, now closed). A *flat* triangle — one
2467        // with no shade and no texture coefficients — used to fall through to
2468        // `fill_pixel` whatever the cycle type, so a 1-cycle flat triangle
2469        // rasterized the `SET_FILL_COLOR` register instead of running the
2470        // combiner. That is the identical defect `fill_rectangle` had, resolved
2471        // there against the oracle (vector `fill_rect_1cycle_16`): a 1-cycle
2472        // rectangle renders the *prim* color, never the fill register.
2473        //
2474        // The rule is the same for both primitives because it is a property of
2475        // the cycle type rather than of the primitive: FILL and COPY write the
2476        // fill register, 1-/2-cycle run the combiner — which for a flat triangle
2477        // sees only its register inputs (prim/env/…), exactly as for a flat
2478        // rectangle.
2479        //
2480        // Found by `aa_tri_coverage_16`, the first committed vector to render a
2481        // triangle in 1-cycle mode; every earlier one is FILL, which is why R-21
2482        // recorded this half as unexercised.
2483        let has_color = shade_setup.is_some()
2484            || tex_setup.is_some()
2485            || !matches!(
2486                self.other_modes.cycle_type,
2487                CYCLE_TYPE_COPY | CYCLE_TYPE_FILL
2488            );
2489        let y_base = yh >> 2;
2490
2491        // 1-/2-cycle mode rasterizes with sub-pixel coverage; FILL/COPY mode
2492        // (`cycle_type >= 2`) rounds to whole pixels (N64brew *…/Commands*: FILL is
2493        // "without subpixel accuracy"), which the union span already models exactly.
2494        let subpixel = self.other_modes.cycle_type < 2;
2495        // Sub-pixel scissor bounds (`s.3`): the raw `s10.2` scissor is one fraction
2496        // bit narrower, so `<< 1` lifts it (parallel-rdp `span_setup.comp:196`).
2497        let sc_lo = i32::from(self.scissor_ulx) << 1;
2498        let sc_hi = i32::from(self.scissor_lrx) << 1;
2499        for line in start_line..=end_line {
2500            let mut span_l = i32::MAX;
2501            let mut span_r = i32::MIN;
2502            // Per-Y-subpixel `s.3` edges for the sub-pixel coverage path.
2503            let mut xleft = [SPAN_X_POISON_LEFT; COVERAGE_SUBPIXELS];
2504            let mut xright = [SPAN_X_POISON_RIGHT; COVERAGE_SUBPIXELS];
2505            for sub in 0..4 {
2506                let y = line * 4 + sub;
2507                if y < yh || y >= yl {
2508                    continue;
2509                }
2510                let major = i64::from(xh) + i64::from(y - yh_base) * i64::from(dxhdy);
2511                let minor = if y < ym {
2512                    i64::from(xm) + i64::from(y - yh_base) * i64::from(dxmdy)
2513                } else {
2514                    i64::from(xl) + i64::from(y - ym) * i64::from(dxldy)
2515                };
2516                // Whole-pixel edges for the union span (distinct from the scanline
2517                // interpolation origin `major_x` computed after the sub-loop).
2518                let major_px = (major >> 16) as i32;
2519                let minor_px = (minor >> 16) as i32;
2520                let (xl_i, xr_i) = if flip {
2521                    (major_px, minor_px)
2522                } else {
2523                    (minor_px, major_px)
2524                };
2525                if xl_i > xr_i {
2526                    continue;
2527                }
2528                // The union bounding span (FILL / COPY / depth paths).
2529                span_l = span_l.min(xl_i);
2530                span_r = span_r.max(xr_i);
2531                // Sub-pixel edges (`s.3`, sticky-bit snapped) for the coverage path:
2532                // quantize the `s.16` major/minor and clamp to the scissor.
2533                let (raw_l, raw_r) = if flip { (major, minor) } else { (minor, major) };
2534                #[allow(clippy::cast_possible_truncation)]
2535                let el = quantize_x(sext(raw_l as u32, 27)).clamp(sc_lo, sc_hi);
2536                #[allow(clippy::cast_possible_truncation)]
2537                let er = quantize_x(sext(raw_r as u32, 27)).clamp(sc_lo, sc_hi);
2538                if (el >> 1) <= (er >> 1) {
2539                    xleft[sub as usize] = el;
2540                    xright[sub as usize] = er;
2541                }
2542            }
2543            let (x0, x1) = if subpixel {
2544                (
2545                    (min4(&xleft) >> 3).max(0),
2546                    (max4(&xright) >> 3).min(width - 1),
2547                )
2548            } else {
2549                (span_l.max(sx0).max(0), span_r.min(sx1).min(width - 1))
2550            };
2551            if x0 > x1 {
2552                continue;
2553            }
2554            let row_addr = self
2555                .color_image
2556                .wrapping_add((line as u32).wrapping_mul(stride));
2557            // The major-edge x at this scanline (s15.16), the interpolation origin
2558            // shared by the depth and shade interpolators.
2559            let major_x = i64::from(xh) + i64::from(line * 4 - yh_base) * i64::from(dxhdy);
2560            if let Some(z) = z_setup {
2561                let cov = if subpixel {
2562                    Some((&xleft, &xright))
2563                } else {
2564                    None
2565                };
2566                self.depth_span(
2567                    row_addr,
2568                    x0,
2569                    x1,
2570                    line,
2571                    bpp,
2572                    major_x,
2573                    y_base,
2574                    &z,
2575                    cov,
2576                    shade_setup.as_ref(),
2577                    tex_setup.as_ref(),
2578                    base_tile,
2579                    bus,
2580                );
2581            } else if has_color {
2582                // The no-Z path (a triangle with no z-suffix): the combiner color.
2583                // In 1-/2-cycle mode each pixel's sub-pixel coverage gates the write
2584                // and is stored in the pixel alpha (the AA/`cvg_dest` write-back); the
2585                // memory-read blender still lives only on the depth path (R-9/R-11).
2586                #[allow(clippy::cast_sign_loss, reason = "x >= 0 within a clipped span")]
2587                for x in x0..=x1 {
2588                    let (mut color, _shade_alpha) = self.combined_color(
2589                        shade_setup.as_ref(),
2590                        tex_setup.as_ref(),
2591                        base_tile,
2592                        major_x,
2593                        line,
2594                        y_base,
2595                        x,
2596                    );
2597                    // Alpha-compare (Set Other Modes bit 0) gates the write on the
2598                    // combiner output alpha, evaluated BEFORE coverage overwrites the
2599                    // alpha byte.
2600                    if !self.alpha_compare_passes(color[3]) {
2601                        continue;
2602                    }
2603                    // `stored_cvg` is `Some` only on the sub-pixel path, because
2604                    // only there is `color[3]` a coverage value rather than the
2605                    // combiner's alpha. Writing the hidden plane from a combiner
2606                    // alpha would fabricate coverage out of a color channel.
2607                    let mut stored_cvg = None;
2608                    if subpixel {
2609                        match self.pixel_coverage(xleft, xright, x) {
2610                            Some(cov) => {
2611                                color[3] = cov << 5;
2612                                stored_cvg = Some(cov);
2613                            }
2614                            None => continue,
2615                        }
2616                    }
2617                    self.dither_pixel(&mut color, x as u32, line as u32);
2618                    Self::write_pixel(row_addr, x as u32, bpp, color, bus);
2619                    if let Some(cov) = stored_cvg {
2620                        // Ledger R-24: the low two bits of coverage go to the
2621                        // hidden plane, which is where the VI looks for them.
2622                        Self::write_coverage(row_addr, x as u32, bpp, cov, bus);
2623                    }
2624                }
2625            } else {
2626                #[allow(clippy::cast_sign_loss, reason = "x >= 0 within a clipped span")]
2627                for x in x0..=x1 {
2628                    self.fill_pixel(row_addr, x as u32, bpp, bus);
2629                }
2630            }
2631        }
2632    }
2633
2634    /// Decode the z-coefficient suffix of a `Fill Triangle` — present when bit 56
2635    /// (the opcode's low bit) is set. The suffix follows the 4-word base plus the
2636    /// shade (bit 58, +8 words) and texture (bit 57, +8 words) blocks, in that
2637    /// order; each field is `s15.16`. Returns `None` when there is no z-suffix.
2638    #[allow(
2639        clippy::cast_possible_wrap,
2640        reason = "the s15.16 z-coefficients are the raw command bits reinterpreted as signed"
2641    )]
2642    #[allow(
2643        clippy::similar_names,
2644        reason = "dzdx / dzde are the N64 RDP's own z-coefficient names"
2645    )]
2646    fn decode_triangle_z<B: VideoBus>(hi: u32, cmd_base: u32, bus: &B) -> Option<ZTriSetup> {
2647        if (hi >> 24) & 1 == 0 {
2648            return None;
2649        }
2650        let has_shade = (hi >> 26) & 1 != 0;
2651        let has_tex = (hi >> 25) & 1 != 0;
2652        let zoff = (4 + 8 * u32::from(has_shade) + 8 * u32::from(has_tex)) * 8;
2653        let za = cmd_base.wrapping_add(zoff);
2654        let z_base = bus.rdram_read_u32(za) as i32;
2655        let dzdx = bus.rdram_read_u32(za.wrapping_add(4)) as i32;
2656        let dzde = bus.rdram_read_u32(za.wrapping_add(8)) as i32;
2657        // `dzdy` (za + 12) is the 4th z-suffix word; it feeds only the sub-pixel
2658        // snap (part 2c), so the per-scanline path here uses `dzde` and leaves it.
2659        //
2660        // Primitive dz for the stored value and the test tolerance: the integer
2661        // depth gradient (first cut — the exact setup derivation is R-9/R-12).
2662        // `saturating_abs` avoids the `i32::MIN.abs()` overflow panic on the
2663        // unvalidated RDRAM coefficients.
2664        let dz = dzdx.saturating_abs().max(dzde.saturating_abs()) >> 16;
2665        Some(ZTriSetup {
2666            z_base,
2667            dzdx,
2668            dzde,
2669            dz,
2670            dz_compressed: dz_compress(dz).min(0xf),
2671        })
2672    }
2673
2674    /// Decode the 8-word shade coefficient block of a `Fill Triangle` (present when
2675    /// bit 58 is set) into [`ShadeSetup`]. It follows the 4-word base immediately
2676    /// (before the texture/z blocks). Per channel the value is `s15.16`: the base's
2677    /// int part is 9-bit signed, the deltas' int parts 16-bit (N64brew *…/Commands*
2678    /// §Fill Shaded Triangle). Returns `None` when there is no shade block.
2679    #[allow(
2680        clippy::cast_possible_wrap,
2681        reason = "the s15.16 delta is the raw (int << 16 | frac) bits reinterpreted as signed"
2682    )]
2683    fn decode_shade<B: VideoBus>(hi: u32, cmd_base: u32, bus: &B) -> Option<ShadeSetup> {
2684        if (hi >> 26) & 1 == 0 {
2685            return None;
2686        }
2687        let sa = cmd_base.wrapping_add(4 * 8);
2688        let w = |word: u32| bus.rdram_read_u32(sa.wrapping_add(word * 4));
2689        // Words: 0 int-base, 1 dx-int, 2 frac-base, 3 dx-frac, 4 de-int, 5 dy-int,
2690        // 6 de-frac, 7 dy-frac. Each 64-bit word packs R/G/B/A; read as two u32
2691        // halves — channels 0/1 (R/G) in the hi u32, 2/3 (B/A) in the lo. Within a
2692        // u32, the even channel (R/B) is the high 16 bits, the odd (G/A) the low.
2693        let u32_index = |base_word: u32, ch: usize| base_word * 2 + (ch >> 1) as u32;
2694        let field = |base_word: u32, ch: usize, mask: u32| {
2695            let shift = 16 * (1 - (ch & 1) as u32);
2696            (w(u32_index(base_word, ch)) >> shift) & mask
2697        };
2698        let mut shade = ShadeSetup::default();
2699        for ch in 0..4 {
2700            // Base: 9-bit int (word 0) + 16-bit frac (word 2) -> a 25-bit s(9).16.
2701            let i9 = field(0, ch, 0x1FF);
2702            let bf = field(2, ch, 0xFFFF);
2703            shade.base[ch] = sext((i9 << 16) | bf, 25);
2704            // Deltas: 16-bit int + 16-bit frac -> a full s15.16, reinterpreted.
2705            let assemble =
2706                |iw: u32, fw: u32| ((field(iw, ch, 0xFFFF) << 16) | field(fw, ch, 0xFFFF)) as i32;
2707            shade.dx[ch] = assemble(1, 3);
2708            shade.de[ch] = assemble(4, 6);
2709        }
2710        Some(shade)
2711    }
2712
2713    /// Write one RGBA8888 pixel to the color image at `(row_addr, x)`: direct for a
2714    /// 32-bit image, packed to RGBA5551 for a 16-bit one (matching `fill_pixel`'s
2715    /// addressing). Other sizes are unsupported and write nothing.
2716    fn write_pixel<B: VideoBus>(row_addr: u32, x: u32, bpp: u32, rgba: [u8; 4], bus: &mut B) {
2717        let addr = row_addr.wrapping_add(x.wrapping_mul(bpp));
2718        match bpp {
2719            4 => {
2720                for (i, b) in rgba.iter().enumerate() {
2721                    bus.rdram_write(addr.wrapping_add(i as u32), *b);
2722                }
2723            }
2724            2 => {
2725                let p = pack_rgba5551(rgba).to_be_bytes();
2726                bus.rdram_write(addr, p[0]);
2727                bus.rdram_write(addr.wrapping_add(1), p[1]);
2728            }
2729            _ => {}
2730        }
2731    }
2732
2733    /// Store a pixel's **coverage** where the VI reads it back from (ledger R-24).
2734    ///
2735    /// The N64 keeps anti-aliasing coverage for a 16-bit color image split across
2736    /// two places: the top bit is the RGBA5551 alpha bit, written by
2737    /// [`Self::write_pixel`] out of `rgba[3]`, and **the low two bits live in the
2738    /// RDRAM hidden 9th-bit plane** — "This 9th bit is used to store things like
2739    /// anti-aliasing coverage in the color buffer" (N64brew Wiki, *RDRAM*). The VI
2740    /// reassembles them as `((px & 1) << 2) | rdram_read_hidden(byte)`
2741    /// (`Bus::vi_read_cov`).
2742    ///
2743    /// **Only 16-bit images need this.** A 32-bit color image carries all three
2744    /// coverage bits inside the alpha byte, and the VI reads them straight back as
2745    /// `(px >> 5) & 7` — so writing the hidden plane there would be storing a
2746    /// second, redundant copy the hardware does not keep.
2747    ///
2748    /// Without this the low two bits were dropped on every write, so the VI could
2749    /// only ever read coverage 0 or 4, `cvg == 7` never held, and every
2750    /// coverage-gated VI filter silently degenerated. Measured before the fix on
2751    /// Super Mario 64: 27,150,246 filtered pixels, **`cvg0` 22.45% / `cvg4`
2752    /// 77.55% / everything else 0.00%**.
2753    fn write_coverage<B: VideoBus>(row_addr: u32, x: u32, bpp: u32, cov: u8, bus: &mut B) {
2754        if bpp != 2 {
2755            return;
2756        }
2757        let addr = row_addr.wrapping_add(x.wrapping_mul(bpp));
2758        bus.rdram_write_hidden(addr, cov & 0x3);
2759    }
2760
2761    /// Read the current color-image pixel at `(row_addr, x)` as RGBA8888 — the
2762    /// blender's `memory_color`. The inverse of [`Self::write_pixel`]: direct for a
2763    /// 32-bit image, RGBA5551 widened (5→8 bits) for a 16-bit one.
2764    ///
2765    /// An 8-bit color image (`bpp == 1`, a legal but unsupported render target —
2766    /// [`Self::color_image_bpp`] returns `Some(1)` for it) reads as transparent
2767    /// black, mirroring [`Self::write_pixel`]'s silent no-op for the same size (the
2768    /// blended result is discarded there anyway, so no draw happens either way). It
2769    /// stays a graceful default rather than a panic because `bpp` derives from a
2770    /// `Set Color Image` field under ROM control (module 60: never panic on external
2771    /// input, and a `debug_assert` would fire on that legal configuration).
2772    fn read_pixel<B: VideoBus>(row_addr: u32, x: u32, bpp: u32, bus: &B) -> [u8; 4] {
2773        let addr = row_addr.wrapping_add(x.wrapping_mul(bpp));
2774        match bpp {
2775            4 => [
2776                bus.rdram_read(addr),
2777                bus.rdram_read(addr.wrapping_add(1)),
2778                bus.rdram_read(addr.wrapping_add(2)),
2779                bus.rdram_read(addr.wrapping_add(3)),
2780            ],
2781            2 => {
2782                let p = u16::from_be_bytes([
2783                    bus.rdram_read(addr),
2784                    bus.rdram_read(addr.wrapping_add(1)),
2785                ]);
2786                unpack_rgba5551(p)
2787            }
2788            // 8-bit (bpp 1) and any other size: transparent black, as documented above.
2789            _ => [0; 4],
2790        }
2791    }
2792
2793    /// Decode the 8-word texture coefficient block of a `Fill Triangle` (present
2794    /// when bit 57 is set) into [`TexSetup`]. It follows the 4-word base plus the
2795    /// shade block (if bit 58 set), before the z block. Each word packs `S`/`T`/`W`
2796    /// into bits 63:48/47:32/31:16 (`s16.16`); this slice keeps only `S`/`T` (both
2797    /// in the hi u32) — the `W` perspective term is the deferred perspective slice.
2798    #[allow(
2799        clippy::cast_possible_wrap,
2800        reason = "the s16.16 coordinate is the raw (int << 16 | frac) bits reinterpreted"
2801    )]
2802    fn decode_texture<B: VideoBus>(hi: u32, cmd_base: u32, bus: &B) -> Option<TexSetup> {
2803        if (hi >> 25) & 1 == 0 {
2804            return None;
2805        }
2806        let has_shade = (hi >> 26) & 1;
2807        let ta = cmd_base.wrapping_add((4 + 8 * has_shade) * 8);
2808        let w = |word: u32| bus.rdram_read_u32(ta.wrapping_add(word * 4));
2809        // Each 64-bit word packs S (bits 63:48), T (47:32), W (31:16): S and T are in
2810        // the hi u32 (shift 16 / 0), W in the lo u32 (shift 16). `c` = 0 S, 1 T, 2 W.
2811        let field = |base_word: u32, c: usize| {
2812            let u32_off = u32::from(c == 2);
2813            let shift = if c == 1 { 0 } else { 16 };
2814            (w(base_word * 2 + u32_off) >> shift) & 0xFFFF
2815        };
2816        let assemble = |iw: u32, fw: u32, c: usize| ((field(iw, c) << 16) | field(fw, c)) as i32;
2817        let mut tex = TexSetup::default();
2818        for c in 0..3 {
2819            tex.base[c] = assemble(0, 2, c); // int word 0, frac word 2
2820            tex.dx[c] = assemble(1, 3, c); // per-x
2821            tex.de[c] = assemble(4, 6, c); // per-major-edge
2822            tex.dy[c] = assemble(5, 7, c); // per-y (LOD only)
2823        }
2824        Some(tex)
2825    }
2826
2827    /// Sample `tile` at the raw `s10.5` coordinate `(s105, t105)` — point or the
2828    /// 3-point bilinear filter per `Set Other Modes.sample_type` (R-13). Point
2829    /// applies the tile transform ([`sample_coord`]) and fetches one texel;
2830    /// bilinear runs [`sample_axis`] per axis for `(base, frac)`, fetches the four
2831    /// texels at `(s,t)/(s+1,t)/(s,t+1)/(s+1,t+1)`, and blends with
2832    /// [`bilinear_3point`]. The four texels share the one base clamp/mask; the exact
2833    /// mask-wrap-seam `sdiff`/`tdiff` (`0`/`-1` at the wrap edge) is deferred — the
2834    /// neighbor is the base plus one, correct except across a mask seam.
2835    #[allow(
2836        clippy::cast_sign_loss,
2837        clippy::cast_possible_wrap,
2838        reason = "fetch_texel masks the coordinate into the 4 KiB TMEM space, as the point path does"
2839    )]
2840    fn sample_texel(&self, tile: &TileDescriptor, s105: i32, t105: i32) -> [u8; 4] {
2841        if !self.other_modes.sample_type {
2842            let s = sample_coord(
2843                s105,
2844                tile.shift_s,
2845                tile.mask_s,
2846                tile.mirror_s,
2847                tile.clamp_s,
2848                tile.sl,
2849                tile.sh,
2850            );
2851            let t = sample_coord(
2852                t105,
2853                tile.shift_t,
2854                tile.mask_t,
2855                tile.mirror_t,
2856                tile.clamp_t,
2857                tile.tl,
2858                tile.th,
2859            );
2860            return self.fetch_texel(tile, s, t);
2861        }
2862        let (sb, sfrac, sdiff) = sample_axis(
2863            s105,
2864            tile.shift_s,
2865            tile.mask_s,
2866            tile.mirror_s,
2867            tile.clamp_s,
2868            tile.sl,
2869            tile.sh,
2870            false,
2871        );
2872        let (tb, tfrac, tdiff) = sample_axis(
2873            t105,
2874            tile.shift_t,
2875            tile.mask_t,
2876            tile.mirror_t,
2877            tile.clamp_t,
2878            tile.tl,
2879            tile.th,
2880            true,
2881        );
2882        // The neighbor is the masked base plus the mask-coupled diff (+1 / 0 / -1 /
2883        // wrap), NOT re-masked — `mask_coupled` chose `diff` for exactly this. The
2884        // diff keeps the neighbor non-negative (the -1 case only fires when base>=1,
2885        // the wrap case lands on 0), so the `as u32` never wraps to a huge value.
2886        debug_assert!(
2887            sb + sdiff >= 0 && tb + tdiff >= 0,
2888            "neighbor texel is non-negative"
2889        );
2890        let (s0, t0) = (sb as u32, tb as u32);
2891        let (s1, t1) = ((sb + sdiff) as u32, (tb + tdiff) as u32);
2892        bilinear_3point(
2893            self.fetch_texel(tile, s0, t0),
2894            self.fetch_texel(tile, s1, t0),
2895            self.fetch_texel(tile, s0, t1),
2896            self.fetch_texel(tile, s1, t1),
2897            sfrac,
2898            tfrac,
2899            self.other_modes.mid_texel,
2900        )
2901    }
2902
2903    /// Compute a pixel's color through the combiner from the interpolated shade
2904    /// and/or sampled texel (plus the prim/env registers). `shade`/`tex` are the
2905    /// decoded setups, `None` when that attribute is absent. The two-cycle mode
2906    /// comes from `Set Other Modes`. Texture uses the interpolated coordinate
2907    /// (`interpolate_st`, perspective-correct when `persp_tex_en` is set) sampled
2908    /// from `base_tile` (and `base_tile + 1` in 2-cycle).
2909    ///
2910    /// Returns the combiner output **and** the interpolated shade alpha, which the
2911    /// blender selects separately (`A`-select 2) from the combiner output alpha
2912    /// (`A`-select 0) — the two differ whenever the alpha combiner transforms the
2913    /// shade alpha. Shade alpha is `0` when the triangle carries no shade block.
2914    #[allow(
2915        clippy::too_many_arguments,
2916        reason = "per-pixel combiner inputs: setups, base tile, and interpolation origin"
2917    )]
2918    fn combined_color(
2919        &self,
2920        shade: Option<&ShadeSetup>,
2921        tex: Option<&TexSetup>,
2922        base_tile: usize,
2923        major_x: i64,
2924        line: i32,
2925        y_base: i32,
2926        x: i32,
2927    ) -> ([u8; 4], u8) {
2928        let mut inp = CombinerInputs {
2929            prim: unpack_rgba(self.prim_color),
2930            env: unpack_rgba(self.env_color),
2931            // R-10 register-sourced exotic combiner inputs: prim-LOD-frac, the Set
2932            // Convert K4/K5, and the chroma-key center/scale. Still deferred (read as
2933            // zero): noise, the derivative-computed lod_frac, and the YUV K0..K3 convert.
2934            prim_lod_frac: i16::from(self.prim_lod_frac),
2935            k4: self.k4,
2936            k5: self.k5,
2937            key_center: self.key_center,
2938            key_scale: self.key_scale,
2939            ..CombinerInputs::default()
2940        };
2941        if let Some(shade) = shade {
2942            inp.shade =
2943                interpolate_shade(&shade.base, &shade.dx, &shade.de, major_x, line, y_base, x);
2944        }
2945        if let Some(tex) = tex {
2946            let persp = self.other_modes.persp_tex_en;
2947            let stw = interpolate_stw_raw(tex, major_x, line, y_base, x);
2948            let [s105, t105] = divide_stw(stw, persp);
2949            // The derivative-computed LOD fraction (R-13). Gated two ways: on
2950            // Angrylion's `dolod` (something actually consumes the fraction), so
2951            // the common path pays neither the two extra perspective divides nor
2952            // any behavior change; and on **2-cycle** mode, because only the
2953            // 2-cycle LOD form is modeled — the 1-cycle form needs span-edge
2954            // signals the rasterizer does not have, so it stays deferred and
2955            // reads zero rather than being approximated with the wrong formula.
2956            // The primitive's base tile comes from the triangle command (bits 50:48,
2957            // `(ewdata[0] >> 16) & 7` — Angrylion `rasterizer.c`); the sampler reads
2958            // that descriptor, not a hardwired tile 0. In 2-cycle mode the second
2959            // texel comes from the next tile (the `RENDERTILE`/`RENDERTILE+1` case),
2960            // and `combine` swaps texel0/texel1 for the second cycle so cycle 1's
2961            // TEXEL0 reads it.
2962            let (mut tile0, mut tile1) = (base_tile, (base_tile + 1) & 7);
2963            if self.other_modes.cycle_type == CYCLE_TYPE_2CYCLE && self.lod_active() {
2964                // The 2-cycle LOD (R-13). Gated on Angrylion's `dolod` — something
2965                // consumes it — so the common path pays neither the two extra
2966                // perspective divides nor any behavior change; and on 2-cycle mode,
2967                // because only the 2-cycle LOD form is modeled (the 1-cycle form
2968                // needs span-edge signals the rasterizer does not have, so it stays
2969                // deferred rather than being approximated with the wrong formula).
2970                let sig = self.lod_2cycle(tex, stw, persp, [s105, t105]);
2971                inp.lod_frac = sig.frac;
2972                // With `tex_lod_en` the LOD also picks the mip pair to sample.
2973                if self.other_modes.tex_lod_en {
2974                    (tile0, tile1) = lod_mip_tiles(
2975                        base_tile,
2976                        sig,
2977                        self.max_level,
2978                        self.other_modes.sharpen_tex_en,
2979                        self.other_modes.detail_tex_en,
2980                    );
2981                }
2982            }
2983            inp.texel0 = self.sample_texel(&self.tiles[tile0], s105, t105);
2984            if self.other_modes.cycle_type == CYCLE_TYPE_2CYCLE {
2985                inp.texel1 = self.sample_texel(&self.tiles[tile1], s105, t105);
2986            }
2987        }
2988        let shade_alpha = inp.shade[3];
2989        (
2990            self.combine(inp, self.other_modes.cycle_type == CYCLE_TYPE_2CYCLE),
2991            shade_alpha,
2992        )
2993    }
2994
2995    /// Whether the LOD fraction has to be computed for this primitive — the
2996    /// Angrylion `other_modes.f.dolod` gate (`rdp.c`): either `tex_lod_en` is on,
2997    /// or the combiner actually selects `LODFrac` as a mul input (RGB select 13 /
2998    /// alpha select 0) in either cycle. When false the fraction is unread, so
2999    /// skipping it is behavior-preserving as well as cheaper.
3000    fn lod_active(&self) -> bool {
3001        let uses = |c: &CombineCycle| c.rgb_c == 13 || c.a_c == LOD_FRAC_ALPHA_MUL_SELECT;
3002        self.other_modes.tex_lod_en || uses(&self.combine.cyc0) || uses(&self.combine.cyc1)
3003    }
3004
3005    /// The 2-cycle LOD fraction — a port of Angrylion `tclod_2cycle` (`tcoord.c`)
3006    /// down to its `lf` output.
3007    ///
3008    /// The LOD is the larger of the texture-coordinate deltas to the next pixel in
3009    /// **x** (`stw + dsdx`) and the next scanline in **y** (`stw + dsdy`, the true
3010    /// vertical gradient — *not* the major-edge `de` the scanline walk uses), each
3011    /// taken through the same perspective divide as the pixel's own coordinate.
3012    /// A coordinate with bits 18:17 set clamps the LOD to its maximum.
3013    ///
3014    /// Scope: this is the **2-cycle** form. The 1-cycle form
3015    /// (`tclod_1cycle_current_simple`) differs — it compares the `x+1` and `x+2`
3016    /// taps and needs the span-edge signals (`endspan`/`longspan`/`midspan`,
3017    /// `validline`) that the rasterizer does not model — so it stays deferred
3018    /// under R-13 rather than being approximated with the 2-cycle formula.
3019    #[allow(
3020        clippy::similar_names,
3021        reason = "nexts/nextt and nextys/nextyt are Angrylion's own names for the two LOD taps"
3022    )]
3023    fn lod_2cycle(&self, tex: &TexSetup, stw: [i32; 3], persp: bool, init: [i32; 2]) -> LodSignals {
3024        // Step the raw accumulator by a derivative, then divide exactly as the
3025        // pixel's own coordinate was divided.
3026        let step = |d: [i32; 3]| {
3027            let mut n = stw;
3028            for (o, dv) in n.iter_mut().zip(d) {
3029                *o = o.wrapping_add(dv);
3030            }
3031            divide_stw(n, persp)
3032        };
3033        // The hardware truncates each derivative before use: `dsdx & ~0x1f`,
3034        // `dsdy & ~0x7fff` (Angrylion `spans_ds` / `spans_dsdy`).
3035        let dx = [tex.dx[0] & !0x1F, tex.dx[1] & !0x1F, tex.dx[2] & !0x1F];
3036        let dy = [
3037            tex.dy[0] & !0x7FFF,
3038            tex.dy[1] & !0x7FFF,
3039            tex.dy[2] & !0x7FFF,
3040        ];
3041        let [nexts, nextt] = step(dx);
3042        let [nextys, nextyt] = step(dy);
3043        let lodclamp = (init[0] | init[1] | nexts | nextt | nextys | nextyt) & 0x6_0000 != 0;
3044        let mut lod = 0;
3045        if !lodclamp {
3046            lod = lod_delta(init[0], nexts, init[1], nextt, 0);
3047            lod = lod_delta(init[0], nextys, init[1], nextyt, lod);
3048        }
3049        lod_signals(
3050            lodclamp,
3051            lod,
3052            self.min_level,
3053            self.max_level,
3054            self.other_modes.sharpen_tex_en,
3055            self.other_modes.detail_tex_en,
3056        )
3057    }
3058
3059    /// The stored coverage value (`0..=7`) for pixel column `x` under sub-pixel
3060    /// coverage, or `None` when the pixel is not drawn.
3061    ///
3062    /// A zero mask kills the pixel. With anti-aliasing off, only the first
3063    /// sub-sample (mask bit 0 — the top-left) matters, so a pixel whose top-left
3064    /// sample is outside the span is dropped (parallel-rdp `shading.h:171-178`). The
3065    /// stored coverage is the `cvg_dest` write-back: **clamp** (mode 0) stores the
3066    /// no-blend `(count - 1) & 7` (`coverage.h`) and **full** (mode 2) stores `7`
3067    /// (so a partially-covered edge pixel gets the full RGBA5551 alpha bit). Both
3068    /// pack into the pixel's alpha/coverage bits — full coverage (count 8) stores 7,
3069    /// so the alpha bit (`cov >> 2`) is set. The **wrap** (1) and **save** (3) modes
3070    /// need the memory-read coverage accumulator (R-9 slice 2c-2) and are deferred.
3071    fn pixel_coverage(
3072        &self,
3073        xleft: [i32; COVERAGE_SUBPIXELS],
3074        xright: [i32; COVERAGE_SUBPIXELS],
3075        x: i32,
3076    ) -> Option<u8> {
3077        let mask = compute_coverage(xleft, xright, x);
3078        if mask == 0 || (!self.other_modes.aa_enable && (mask & 1) == 0) {
3079            return None;
3080        }
3081        #[allow(clippy::cast_possible_truncation)] // count_ones() is 1..=8 here
3082        let count = mask.count_ones() as u8;
3083        // `cvg_dest = 2` (full) forces full coverage regardless of the sample count.
3084        Some(if self.other_modes.cvg_dest == 2 {
3085            7
3086        } else {
3087            (count - 1) & 7
3088        })
3089    }
3090
3091    /// Apply the ordered RGB dither to a combined pixel color in place, mirroring
3092    /// Angrylion's `rgb_dither`. Dither is part of the 1-/2-cycle pixel pipeline
3093    /// only (FILL/COPY bypass the combiner), and RGB dither mode 3 is "off" — both
3094    /// return early. Alpha is untouched. `(x, y)` index the 4×4 dither matrix
3095    /// (**R-10**: noise mode 2 reads the magic cell for now).
3096    /// Whether a pixel survives **alpha-compare** (`Set Other Modes` bit 0). With
3097    /// the gate off, every pixel passes. With it on, the combiner output alpha must
3098    /// be `>=` the threshold — the `Set Blend Color` alpha (the dithered-threshold
3099    /// variant, `dither_alpha_en`, is a deferred residual). Below-threshold pixels
3100    /// are not written (N64brew *…/Blender* §Alpha compare).
3101    fn alpha_compare_passes(&self, alpha: u8) -> bool {
3102        if !self.other_modes.alpha_compare_en {
3103            return true;
3104        }
3105        #[allow(clippy::cast_possible_truncation)] // low byte of the RGBA8888 register
3106        let threshold = (self.blend_color & 0xFF) as u8;
3107        alpha >= threshold
3108    }
3109
3110    fn dither_pixel(&self, color: &mut [u8; 4], x: u32, y: u32) {
3111        // FILL/COPY bypass the combiner, and mode 3 ("off") never rounds up — both
3112        // are the common case, so skip the per-pixel work outright rather than run
3113        // it to a no-op result.
3114        if self.other_modes.cycle_type >= 2 || self.other_modes.rgb_dither_mode == 3 {
3115            return;
3116        }
3117        let dith = rgb_dither_value(self.other_modes.rgb_dither_mode, x, y);
3118        *color = apply_rgb_dither(*color, dith);
3119    }
3120
3121    /// Render one scanline's span with the per-pixel depth test (T-33-004 PR-B 2a):
3122    /// for each pixel, interpolate the depth, test it against the Z buffer, and —
3123    /// only if it passes — write the color and (when `z_update`) the depth.
3124    ///
3125    /// In 1-/2-cycle mode `cov` carries the per-Y-subpixel edges: each pixel is gated
3126    /// by [`Self::pixel_coverage`] (an uncovered pixel is skipped before the depth
3127    /// test) and the coverage count is stored in the pixel alpha, identical to the
3128    /// no-Z shaded path (validated against Angrylion by `shade_depth_tri_frac_16`).
3129    /// FILL/COPY mode passes `None` and keeps whole-pixel coverage. The depth test
3130    /// itself still uses a full count (`8`); the coverage-weighted interpenetration
3131    /// path is the deferred R-9/R-12 residual.
3132    #[allow(
3133        clippy::too_many_arguments,
3134        reason = "an internal rasterizer span helper; a struct would only relocate the parameters"
3135    )]
3136    #[allow(
3137        clippy::cast_sign_loss,
3138        reason = "x and line are >= 0 within a clipped span"
3139    )]
3140    #[allow(
3141        clippy::similar_names,
3142        reason = "mem_z / mem_dz mirror the memory depth/dz pair they hold"
3143    )]
3144    fn depth_span<B: VideoBus>(
3145        &self,
3146        row_addr: u32,
3147        x0: i32,
3148        x1: i32,
3149        line: i32,
3150        bpp: u32,
3151        major_x: i64,
3152        y_base: i32,
3153        z: &ZTriSetup,
3154        cov: Option<(&[i32; COVERAGE_SUBPIXELS], &[i32; COVERAGE_SUBPIXELS])>,
3155        shade: Option<&ShadeSetup>,
3156        tex: Option<&TexSetup>,
3157        base_tile: usize,
3158        bus: &mut B,
3159    ) {
3160        let yu = line as u32;
3161        for x in x0..=x1 {
3162            // In 1-/2-cycle mode, sub-pixel coverage gates the pixel and drives the
3163            // stored alpha; an uncovered pixel is skipped before the depth test (no
3164            // Z read/write). FILL/COPY mode (`cov == None`) keeps whole-pixel span.
3165            let pixel_cov = match cov {
3166                Some((xleft, xright)) => match self.pixel_coverage(*xleft, *xright, x) {
3167                    Some(c) => Some(c),
3168                    None => continue,
3169                },
3170                None => None,
3171            };
3172            let z_px = interpolate_z(z.z_base, z.dzdx, z.dzde, major_x, line, y_base, x);
3173            let xu = x as u32;
3174            let (mem_z, mem_dz) = self.zbuffer_read(xu, yu, bus);
3175            let dinp = DepthInputs {
3176                current_depth: mem_z,
3177                current_dz: mem_dz,
3178                current_coverage: 0,
3179                z_compare: self.other_modes.z_compare_en,
3180                z_mode: self.other_modes.z_mode,
3181                force_blend: self.other_modes.force_blend,
3182                // AA-edge coverage (the `aa_enable && farther` blend path) is slice 2c;
3183                // until per-pixel coverage exists, only `force_blend` drives the blender.
3184                aa_enable: false,
3185            };
3186            let dr = Self::depth_test(z_px, z.dz, z.dz_compressed, 8, &dinp);
3187            if dr.depth_pass {
3188                // Shaded/textured triangles take the combiner color; else the FILL register.
3189                if shade.is_some() || tex.is_some() {
3190                    let (mut color, shade_alpha) =
3191                        self.combined_color(shade, tex, base_tile, major_x, line, y_base, x);
3192                    // Alpha-compare gates the write AND the z-write on the combiner
3193                    // alpha (before blend/coverage touch the alpha byte). This is
3194                    // observably equivalent to the RDP's pre-depth-test ordering
3195                    // because the compare is depth-independent: a pixel is written
3196                    // (and its depth stored) only when both depth and alpha pass.
3197                    if !self.alpha_compare_passes(color[3]) {
3198                        continue;
3199                    }
3200                    // The blender runs only when the depth test enabled it (translucent /
3201                    // AA-edge pixels); an opaque pixel keeps the combiner color, matching
3202                    // the reference's `!blend_en` fast-path. The full opaque-alpha fast path
3203                    // and coverage-driven alpha are R-11.
3204                    if dr.blend_en {
3205                        let memory = Self::read_pixel(row_addr, xu, bpp, bus);
3206                        let rgb = self.blend(BlendInputs {
3207                            pixel: color,
3208                            memory,
3209                            blend_color: unpack_rgba(self.blend_color),
3210                            fog: unpack_rgba(self.fog_color),
3211                            // The blender's shade-alpha mux input (`A`-select 2) is the
3212                            // interpolated shade alpha, independent of the combiner output
3213                            // alpha (`A`-select 0, carried in `pixel[3]`).
3214                            shade_alpha,
3215                        });
3216                        // The blender produces RGB only; the alpha byte keeps the combiner
3217                        // output alpha unless sub-pixel coverage overrides it below.
3218                        color = [rgb[0], rgb[1], rgb[2], color[3]];
3219                    }
3220                    // Store the sub-pixel coverage in the pixel alpha (1-/2-cycle mode).
3221                    if let Some(c) = pixel_cov {
3222                        color[3] = c << 5;
3223                    }
3224                    self.dither_pixel(&mut color, xu, yu);
3225                    Self::write_pixel(row_addr, xu, bpp, color, bus);
3226                    if let Some(c) = pixel_cov {
3227                        // Ledger R-24, the depth path's half. The no-Z span had
3228                        // the identical gap; both must store it or the VI sees
3229                        // coverage only from whichever path a scene happens to
3230                        // use — which is how 74.91% of pixels sat at exactly
3231                        // `cvg4` after the first half of this fix.
3232                        Self::write_coverage(row_addr, xu, bpp, c, bus);
3233                    }
3234                } else {
3235                    self.fill_pixel(row_addr, xu, bpp, bus);
3236                }
3237                if self.other_modes.z_update_en {
3238                    #[allow(
3239                        clippy::cast_sign_loss,
3240                        clippy::cast_possible_truncation,
3241                        reason = "dz_compressed is clamped to 0..=0xf in decode_triangle_z"
3242                    )]
3243                    self.zbuffer_write(xu, yu, z_px, z.dz_compressed as u8, bus);
3244                }
3245            }
3246        }
3247    }
3248
3249    /// Apply a `Set Combine Mode` (0x3C): decode the 16 mux input selects for both
3250    /// cycles into [`CombineMode`] (N64brew *…/Commands* §0x3C, matched to the
3251    /// ParaLLEl-RDP field layout).
3252    fn set_combine_mode(&mut self, hi: u32, lo: u32) {
3253        self.combine.cyc0 = CombineCycle {
3254            rgb_a: ((hi >> 20) & 0xF) as u8,
3255            rgb_c: ((hi >> 15) & 0x1F) as u8,
3256            rgb_b: ((lo >> 28) & 0xF) as u8,
3257            rgb_d: ((lo >> 15) & 0x7) as u8,
3258            a_a: ((hi >> 12) & 0x7) as u8,
3259            a_c: ((hi >> 9) & 0x7) as u8,
3260            a_b: ((lo >> 12) & 0x7) as u8,
3261            a_d: ((lo >> 9) & 0x7) as u8,
3262        };
3263        self.combine.cyc1 = CombineCycle {
3264            rgb_a: ((hi >> 5) & 0xF) as u8,
3265            rgb_c: (hi & 0x1F) as u8,
3266            rgb_b: ((lo >> 24) & 0xF) as u8,
3267            rgb_d: ((lo >> 6) & 0x7) as u8,
3268            a_a: ((lo >> 21) & 0x7) as u8,
3269            a_c: ((lo >> 18) & 0x7) as u8,
3270            a_b: ((lo >> 3) & 0x7) as u8,
3271            a_d: (lo & 0x7) as u8,
3272        };
3273    }
3274
3275    /// Evaluate the color combiner for one cycle, returning the RGBA8888 output.
3276    ///
3277    /// Muxes the [`CombinerInputs`] by the cycle's selects into `(A − B) * C + D`
3278    /// per channel (`combine_channel`), clamps to `[0, 255]` (`clamp_9bit`), and
3279    /// does the same for alpha. The RGB and alpha combiners use different
3280    /// input tables (N64brew *…/Commands* §0x3C). The register-sourced exotic inputs
3281    /// (prim-LOD-frac, the convert `K4`/`K5`, and the chroma-key center/scale) are
3282    /// wired; the remaining exotic inputs (noise, the derivative `lod_frac`, and the
3283    /// YUV `K0`–`K3` convert) are **open residual R-10** and read as zero.
3284    #[must_use]
3285    pub(crate) fn combine_cycle(cfg: CombineCycle, inp: &CombinerInputs) -> [u8; 4] {
3286        // RGB: A/B share the muladd/mulsub table, C the wide mul table, D the add.
3287        let mut out = [0u8; 4];
3288        for (ch, o) in out.iter_mut().enumerate().take(3) {
3289            let a = i32::from(rgb_input_a(cfg.rgb_a, inp, ch));
3290            let b = i32::from(rgb_input_b(cfg.rgb_b, inp, ch));
3291            let c = i32::from(rgb_input_c(cfg.rgb_c, inp, ch));
3292            let d = i32::from(rgb_input_d(cfg.rgb_d, inp, ch));
3293            *o = clamp_9bit(combine_channel(a, b, c, d));
3294        }
3295        // Alpha: A/B/D share one 3-bit table; C its own.
3296        let a = i32::from(alpha_input_abd(cfg.a_a, inp));
3297        let b = i32::from(alpha_input_abd(cfg.a_b, inp));
3298        let c = i32::from(alpha_input_c(cfg.a_c, inp));
3299        let d = i32::from(alpha_input_abd(cfg.a_d, inp));
3300        out[3] = clamp_9bit(combine_channel(a, b, c, d));
3301        out
3302    }
3303
3304    /// Evaluate the whole combiner for a pixel: cycle 1 alone in 1-cycle mode, or
3305    /// cycle 0 feeding cycle 1's `Combined` input in 2-cycle mode. `two_cycle`
3306    /// comes from `Set Other Modes` (T-33-003).
3307    #[must_use]
3308    /// Run the combiner. In `two_cycle` mode the caller must have populated
3309    /// `inp.texel1` (the `tile+1` sample) — the render path (`combined_color`)
3310    /// samples it whenever `cycle_type` is 2-cycle. The swap below then matches the
3311    /// hardware unconditionally; a `two_cycle` call that left `texel1` at its default
3312    /// would feed cycle 1 a zeroed `texel0`, which is a caller contract violation,
3313    /// not a mode this function guards against.
3314    pub(crate) fn combine(&self, mut inp: CombinerInputs, two_cycle: bool) -> [u8; 4] {
3315        if two_cycle {
3316            inp.combined = Self::combine_cycle(self.combine.cyc0, &inp);
3317            // The hardware pipelines the two texels: cycle 1's TEXEL0 reads the
3318            // second tile's sample and TEXEL1 the first, so the combiner swaps them
3319            // before cycle 1 (`combiner_2cycle_cycle1`, R-13).
3320            core::mem::swap(&mut inp.texel0, &mut inp.texel1);
3321        }
3322        let cyc = self.combine.cyc1;
3323        if self.other_modes.key_en {
3324            // Chroma-key alpha compare (Angrylion `combiner_1cycle` key_en path, R-10):
3325            // the RGB output is the sub-A "chromabypass" color (clamped), and the pixel
3326            // alpha is derived from the key window over the pre-`>>8` 17-bit combined
3327            // color. Gated on `key_en` so the common path (below) is byte-identical.
3328            let mut col17 = [0i32; 3];
3329            let mut rgb = [0u8; 3];
3330            for (ch, (c17, out)) in col17.iter_mut().zip(rgb.iter_mut()).enumerate() {
3331                let a = i32::from(rgb_input_a(cyc.rgb_a, &inp, ch));
3332                let b = i32::from(rgb_input_b(cyc.rgb_b, &inp, ch));
3333                let c = i32::from(rgb_input_c(cyc.rgb_c, &inp, ch));
3334                let d = i32::from(rgb_input_d(cyc.rgb_d, &inp, ch));
3335                *c17 = combine_channel_17bit(a, b, c, d);
3336                *out = clamp_9bit(a); // chromabypass = sub-A input, clamped
3337            }
3338            let keyalpha = chroma_key_min(col17, self.key_width);
3339            return [rgb[0], rgb[1], rgb[2], keyalpha];
3340        }
3341        Self::combine_cycle(cyc, &inp)
3342    }
3343
3344    /// Decode `Set Other Modes` (0x2F) into [`OtherModes`]. The blend selects and
3345    /// the cycle-control / Z / coverage flags all live in this one word; only the
3346    /// subset the blender and cycle control consume today is used, but the full
3347    /// layout is decoded so nothing silently reads as its `Default` (N64brew
3348    /// *…/Commands* §0x2F, cross-checked against parallel-rdp `rdp_common.hpp`).
3349    ///
3350    /// `hi` is command bits 63:32 and `lo` bits 31:0. The blend selects pack two
3351    /// cycles into `lo` bits 31:16 (`P0 P1 A0 A1 M0 M1 B0 B1`, MSB-first, 2 bits
3352    /// each); the cycle type is `hi` bits 53:52.
3353    fn set_other_modes(&mut self, hi: u32, lo: u32) {
3354        self.other_modes = OtherModes {
3355            cycle_type: ((hi >> 20) & 0x3) as u8,
3356            blend: [
3357                BlendCycle {
3358                    p: ((lo >> 30) & 0x3) as u8,
3359                    a: ((lo >> 26) & 0x3) as u8,
3360                    m: ((lo >> 22) & 0x3) as u8,
3361                    b: ((lo >> 18) & 0x3) as u8,
3362                },
3363                BlendCycle {
3364                    p: ((lo >> 28) & 0x3) as u8,
3365                    a: ((lo >> 24) & 0x3) as u8,
3366                    m: ((lo >> 20) & 0x3) as u8,
3367                    b: ((lo >> 16) & 0x3) as u8,
3368                },
3369            ],
3370            force_blend: (lo >> 14) & 1 != 0,
3371            image_read_en: (lo >> 6) & 1 != 0,
3372            cvg_dest: ((lo >> 8) & 0x3) as u8,
3373            z_compare_en: (lo >> 4) & 1 != 0,
3374            z_update_en: (lo >> 5) & 1 != 0,
3375            z_mode: ((lo >> 10) & 0x3) as u8,
3376            alpha_compare_en: lo & 1 != 0,
3377            key_en: (hi >> 8) & 1 != 0,               // command bit 40
3378            persp_tex_en: (hi >> 19) & 1 != 0,        // command bit 51
3379            aa_enable: (lo >> 3) & 1 != 0,            // command bit 3
3380            rgb_dither_mode: ((hi >> 6) & 0x3) as u8, // command bits 39:38
3381            tlut_en: (hi >> 15) & 1 != 0,             // command bit 47
3382            tlut_type: (hi >> 14) & 1 != 0,           // command bit 46
3383            sample_type: (hi >> 13) & 1 != 0,         // command bit 45
3384            mid_texel: (hi >> 12) & 1 != 0,           // command bit 44
3385            detail_tex_en: (hi >> 18) & 1 != 0,       // command bit 50
3386            sharpen_tex_en: (hi >> 17) & 1 != 0,      // command bit 49
3387            tex_lod_en: (hi >> 16) & 1 != 0,          // command bit 48
3388        };
3389    }
3390
3391    /// Evaluate one blender cycle: `(P * a0 + M * (a1 + 1)) >> 5`, the divide-free
3392    /// form the hardware uses whenever the result is not an anti-aliased edge
3393    /// (N64brew *…/Blender*; parallel-rdp `shaders/blender.h`). `a0 = A >> 3` and
3394    /// `a1 = B >> 3` map the 8-bit alpha selects to the 5-bit blend weights, and
3395    /// the `+ 1` on the `M` term is real hardware, not a rounding fudge.
3396    ///
3397    /// The color selects (`P`, `M`) pick an RGB triple; the alpha selects (`A`,
3398    /// `B`) pick a scalar weight — `B`'s `1 − A` case complements the resolved `A`
3399    /// weight, so `A` is computed first and handed to `blend_b_input`. The result
3400    /// is masked to 8 bits, **not** clamped: the reference casts through `u8` and
3401    /// re-masks (`blender.h:142`), so an over-range blend wraps exactly as hardware
3402    /// does — software is expected to keep `a0 + a1 + 1 ≈ 32`.
3403    ///
3404    /// The final-cycle early-return fast paths (opaque passthrough, `color_on_cvg`),
3405    /// the anti-aliased divider path, alpha-compare, dither, and Z are **open
3406    /// residual R-11**; `blend_cycle` always takes the no-divide branch for now.
3407    #[must_use]
3408    pub fn blend_cycle(cycle: BlendCycle, inp: &BlendInputs) -> [u8; 3] {
3409        let p = blend_rgb_input(cycle.p, inp);
3410        let m = blend_rgb_input(cycle.m, inp);
3411        let a0_full = blend_a_input(cycle.a, inp);
3412        let a0 = u32::from(a0_full >> 3);
3413        let a1 = u32::from(blend_b_input(cycle.b, inp, a0_full) >> 3);
3414        let mut out = [0u8; 3];
3415        for (ch, o) in out.iter_mut().enumerate() {
3416            let blended = u32::from(p[ch]) * a0 + u32::from(m[ch]) * (a1 + 1);
3417            *o = ((blended >> 5) & 0xFF) as u8;
3418        }
3419        out
3420    }
3421
3422    /// Evaluate the whole blender for a pixel: blend cycle 0 alone in 1-cycle
3423    /// mode, or cycle 0's RGB fed back as the pixel color into cycle 1 in
3424    /// 2-cycle mode (N64brew *…/Blender*).
3425    ///
3426    /// Only `pixel.rgb` chains between cycles — **`pixel.a` is deliberately left
3427    /// unchanged**, so both cycles' `A`/`B` alpha selects see the original combiner
3428    /// alpha. This matches the reference, which reassigns `pixel_color.rgb` only
3429    /// before the second `blender()` call (parallel-rdp `memory_interfacing.h:536`);
3430    /// the blender produces no alpha of its own (`blender.h` returns `u8x3`).
3431    ///
3432    /// **Precondition: only valid for cycle types 0 (1-cycle) and 1 (2-cycle).** Copy
3433    /// (2) and Fill (3) bypass the blender on hardware — the pixel comes straight from
3434    /// the texel copy / fill register — so the pixel pipeline (T-33-004) must gate on
3435    /// `cycle_type` and not route those modes through here. This method is not given a
3436    /// fabricated Copy/Fill result, because the honest contract is "not called", not
3437    /// "called and returns something"; for cycle type 0 it correctly runs cycle 0 once.
3438    #[must_use]
3439    pub fn blend(&self, mut inp: BlendInputs) -> [u8; 3] {
3440        if self.other_modes.cycle_type == 1 {
3441            let rgb0 = Self::blend_cycle(self.other_modes.blend[0], &inp);
3442            inp.pixel[0] = rgb0[0];
3443            inp.pixel[1] = rgb0[1];
3444            inp.pixel[2] = rgb0[2];
3445            return Self::blend_cycle(self.other_modes.blend[1], &inp);
3446        }
3447        Self::blend_cycle(self.other_modes.blend[0], &inp)
3448    }
3449
3450    /// The per-pixel depth test and coverage/blend derivation — a faithful port of
3451    /// ParaLLEl-RDP's `depth_test.h` (the Angrylion-parity reference).
3452    ///
3453    /// `z`/`dz` are this pixel's decompressed 18-bit depth and its raw delta;
3454    /// `dz_compressed` is `dz`'s 4-bit `log2`; `coverage_count` is this pixel's
3455    /// span coverage. [`DepthInputs`] carries the Z-buffer read and the render-mode
3456    /// flags. When `z_compare` is off the pixel always passes; otherwise the four Z
3457    /// modes (opaque/interpenetrating/transparent/decal) apply, with the
3458    /// coplanar/precision-factor handling of the stored `dz`. Interpenetrating mode
3459    /// can *reduce* the returned `coverage_count`. No buffer is touched here — the
3460    /// caller (the pixel pipeline, PR-B) reads/writes the Z buffer and applies the
3461    /// result; today this has no runtime caller, so the oracle is unchanged.
3462    #[must_use]
3463    #[allow(
3464        clippy::cast_possible_truncation,
3465        clippy::cast_sign_loss,
3466        reason = "dz_compressed is clamped to 0..=0xf up front, so both blend_shift \
3467                  branches (clamp(0,4) and min(0xf - dz_compressed, 4)) yield 0..=4 \
3468                  before the u8 cast — the DepthResult invariant holds"
3469    )]
3470    #[allow(
3471        clippy::similar_names,
3472        reason = "memory_z / memory_dz / dz are the oracle's own names (depth_test.h)"
3473    )]
3474    pub fn depth_test(
3475        z: i32,
3476        dz: i32,
3477        dz_compressed: i32,
3478        mut coverage_count: i32,
3479        inp: &DepthInputs,
3480    ) -> DepthResult {
3481        let depth_pass;
3482        let blend_en;
3483        let coverage_wrap;
3484        let mut blend_shift = [0u8; 2];
3485        // Sanitize every input to its hardware domain up front, so the shifts and
3486        // sums below are bounded for any `i32`/`u8` a caller passes (`depth_test` is
3487        // public and the pipeline that will call it clamps identically — the oracle
3488        // clamps `z` to the 18-bit range in `clamping.h`, and `current_dz`/
3489        // `current_depth`/`dz_compressed` are 4-/14-/4-bit storage fields).
3490        let z = z.clamp(0, 0x3_FFFF); // 18-bit UNORM depth
3491        let dz = dz.clamp(0, 0x3_FFFF); // depth-range delta (non-negative)
3492        let dz_compressed = dz_compressed.clamp(0, 0xf); // 4-bit log2, as `0xf - …` assumes
3493        let current_depth = inp.current_depth & 0x3FFF; // 14-bit stored z
3494        let current_dz = i32::from(inp.current_dz & 0xf); // 4-bit stored dz
3495
3496        if inp.z_compare {
3497            let memory_z = z_decompress(current_depth);
3498            let mut memory_dz = dz_decompress(current_dz);
3499            let precision_factor = (i32::from(current_depth) >> 11) & 0xf;
3500            let mut coplanar = false;
3501
3502            blend_shift[0] = (dz_compressed - current_dz).clamp(0, 4) as u8;
3503            blend_shift[1] = (current_dz - dz_compressed).clamp(0, 4) as u8;
3504
3505            if precision_factor < 3 {
3506                if memory_dz == 0x8000 {
3507                    coplanar = true;
3508                    memory_dz = 0xffff;
3509                } else {
3510                    memory_dz = (memory_dz << 1).max(16 >> precision_factor);
3511                }
3512            }
3513
3514            let mut combined_dz = combine_dz(dz | memory_dz);
3515            let combined_dz_interpenetrate = combined_dz;
3516            combined_dz <<= 3;
3517
3518            let farther = coplanar || (z + combined_dz) >= memory_z;
3519            let overflow = (coverage_count + inp.current_coverage) >= 8;
3520
3521            blend_en = inp.force_blend || (!overflow && inp.aa_enable && farther);
3522            coverage_wrap = overflow;
3523
3524            let max_z = memory_z == 0x3_FFFF;
3525            let front = z < memory_z;
3526            let nearer = coplanar || (z - combined_dz) <= memory_z;
3527            let opaque_pass = max_z || if overflow { front } else { nearer };
3528
3529            depth_pass = match inp.z_mode {
3530                // Interpenetrating: a decal-like intersect modifies coverage; else
3531                // it falls back to the opaque less-than test.
3532                1 if front && farther && overflow => {
3533                    let ip = dz_compress(combined_dz_interpenetrate & 0xffff);
3534                    let cvg_coeff = ((memory_z >> ip) - (z >> ip)) & 0xf;
3535                    coverage_count = ((cvg_coeff * coverage_count) >> 3).min(8);
3536                    true
3537                }
3538                0 | 1 => opaque_pass,
3539                2 => front || max_z,              // transparent
3540                _ => farther && nearer && !max_z, // decal (3)
3541            };
3542        } else {
3543            blend_shift[1] = (0xf - dz_compressed).min(4) as u8;
3544            let overflow = (coverage_count + inp.current_coverage) >= 8;
3545            blend_en = inp.force_blend || (!overflow && inp.aa_enable);
3546            coverage_wrap = overflow;
3547            depth_pass = true;
3548        }
3549
3550        DepthResult {
3551            depth_pass,
3552            blend_en,
3553            coverage_wrap,
3554            blend_shift,
3555            coverage_count,
3556        }
3557    }
3558
3559    /// Byte address of the 16-bit Z-buffer entry for pixel `(x, y)`: entries are
3560    /// 16-bit, based at `z_image`. The row stride reuses `color_image_width` — the
3561    /// N64 RDP addresses the depth buffer with the *color* buffer's width (there is
3562    /// no separate depth-image width register), so the two buffers share a geometry.
3563    fn zbuffer_addr(&self, x: u32, y: u32) -> u32 {
3564        let index = y
3565            .wrapping_mul(u32::from(self.color_image_width))
3566            .wrapping_add(x);
3567        self.z_image.wrapping_add(index.wrapping_mul(2))
3568    }
3569
3570    /// Read the Z-buffer entry at `(x, y)` as `(compressed_z, dz)`.
3571    ///
3572    /// The 16-bit halfword holds the 14-bit compressed `z` in bits 15:2 and the
3573    /// **high** two bits of the 4-bit `dz` in bits 1:0; the **low** two bits of
3574    /// `dz` come from the RDRAM hidden bits — matching ParaLLEl-RDP's
3575    /// `load_vram_depth`. `dz` is returned as the 4-bit value `0..=15`.
3576    #[must_use]
3577    pub fn zbuffer_read<B: VideoBus>(&self, x: u32, y: u32, bus: &B) -> (u16, u8) {
3578        let addr = self.zbuffer_addr(x, y);
3579        let word = (u16::from(bus.rdram_read(addr)) << 8)
3580            | u16::from(bus.rdram_read(addr.wrapping_add(1)));
3581        let hidden = bus.rdram_read_hidden(addr) & 0x3;
3582        let compressed_z = word >> 2;
3583        let dz = (((word & 0x3) as u8) << 2) | hidden;
3584        (compressed_z, dz)
3585    }
3586
3587    /// Write the Z-buffer entry at `(x, y)`: compress the 18-bit `z`, pack it with
3588    /// `dz`'s high two bits into the halfword, and store `dz`'s low two bits in the
3589    /// RDRAM hidden bits — matching ParaLLEl-RDP's `store_vram_depth`. `dz` is the
3590    /// 4-bit compressed delta (`0..=15`); `z` is the 18-bit UNORM depth.
3591    pub fn zbuffer_write<B: VideoBus>(&self, x: u32, y: u32, z: i32, dz: u8, bus: &mut B) {
3592        let addr = self.zbuffer_addr(x, y);
3593        let dz = dz & 0xf;
3594        let word = (z_compress(z) << 2) | u16::from(dz >> 2);
3595        let bytes = word.to_be_bytes();
3596        bus.rdram_write(addr, bytes[0]);
3597        bus.rdram_write(addr.wrapping_add(1), bytes[1]);
3598        bus.rdram_write_hidden(addr, dz & 0x3);
3599    }
3600
3601    /// Apply a `Set Tile` (0x35): decode the descriptor at `index` (bits 26:24)
3602    /// from the command word. Pure state — no texel is moved (that is the load
3603    /// commands). Field layout: format 55:53, size 52:51, line 49:41, TMEM
3604    /// address 40:32; then per-axis clamp/mirror/mask/shift with T in bits 19:10
3605    /// and S in bits 9:0 (N64brew *…/Commands* §0x35).
3606    fn set_tile(&mut self, hi: u32, lo: u32) {
3607        let index = ((lo >> 24) & 0x7) as usize;
3608        self.tiles[index] = TileDescriptor {
3609            format: ((hi >> 21) & 0x7) as u8,
3610            size: ((hi >> 19) & 0x3) as u8,
3611            line: ((hi >> 9) & 0x1FF) as u16,
3612            tmem_addr: (hi & 0x1FF) as u16,
3613            palette: ((lo >> 20) & 0xF) as u8,
3614            clamp_t: (lo >> 19) & 1 != 0,
3615            mirror_t: (lo >> 18) & 1 != 0,
3616            mask_t: ((lo >> 14) & 0xF) as u8,
3617            shift_t: ((lo >> 10) & 0xF) as u8,
3618            clamp_s: (lo >> 9) & 1 != 0,
3619            mirror_s: (lo >> 8) & 1 != 0,
3620            mask_s: ((lo >> 4) & 0xF) as u8,
3621            shift_s: (lo & 0xF) as u8,
3622            // Set Tile does not touch the tile-size coords; preserve them.
3623            ..self.tiles[index]
3624        };
3625    }
3626
3627    /// Apply a `Set Tile Size` (0x32): the clamp/mask/mirror extents for the
3628    /// descriptor at `index` (bits 26:24). Upper-left `SL`/`TL` in bits 55:44 /
3629    /// 43:32, lower-right `SH`/`TH` in bits 23:12 / 11:0, all `u10.2` (N64brew
3630    /// *…/Commands* §0x32).
3631    fn set_tile_size(&mut self, hi: u32, lo: u32) {
3632        let index = ((lo >> 24) & 0x7) as usize;
3633        let tile = &mut self.tiles[index];
3634        tile.sl = ((hi >> 12) & 0xFFF) as u16;
3635        tile.tl = (hi & 0xFFF) as u16;
3636        tile.sh = ((lo >> 12) & 0xFFF) as u16;
3637        tile.th = (lo & 0xFFF) as u16;
3638    }
3639
3640    /// Write one byte into TMEM, allocating the 4 KiB backing box on first use.
3641    ///
3642    /// `offset` is a byte address, masked into the 4 KiB space (loads past the end
3643    /// wrap to the start — N64brew *…/Commands* §Load Tile). This is the single
3644    /// allocation seam the load commands share, so `get_or_insert_with` is not
3645    /// repeated per command.
3646    fn tmem_write(&mut self, offset: usize, byte: u8) {
3647        let tmem = self
3648            .tmem
3649            .get_or_insert_with(|| alloc::boxed::Box::new([0u8; TMEM_SIZE]));
3650        tmem[offset & (TMEM_SIZE - 1)] = byte;
3651    }
3652
3653    /// Apply a `Load Tile` (0x34): copy a rectangle of texels from the current
3654    /// texture image in RDRAM into the tile's TMEM region, then update the tile
3655    /// size for rendering. `SL`/`TL`/`SH`/`TH` (bits 55:44 / 43:32 / 23:12 / 11:0)
3656    /// are `u10.2`; the `.2` fraction is floored and the span is **inclusive**
3657    /// (`SH − SL + 1` texels per row). Rows advance by the tile's `line` stride.
3658    ///
3659    /// The TMEM byte placement mirrors the sampler exactly: an **odd-row 32-bit
3660    /// word swap** (`dst ^= (t & 1) << 2`) applies to every size, and **32-bit
3661    /// RGBA is split** — R,G into the low half of TMEM, B,A into the high half,
3662    /// stepping two bytes per texel and masking to `0x7FF`. Both are the read-side
3663    /// layout in the ParaLLEl-RDP reference (MIT); see `docs/rdp.md` §TMEM loads.
3664    ///
3665    /// Scope: 8/16/32-bit texels (`size` 1/2/3). 4-bit (`size` 0) loading needs
3666    /// nibble addressing and lands with the CI4/I4 decoders (T-32-003); an
3667    /// unsupported size writes nothing (**open residual R-7**).
3668    fn load_tile<B: VideoBus>(&mut self, hi: u32, lo: u32, bus: &B) {
3669        let index = ((lo >> 24) & 0x7) as usize;
3670        let sl = ((hi >> 12) & 0xFFF) >> 2;
3671        let tl = (hi & 0xFFF) >> 2;
3672        let sh = ((lo >> 12) & 0xFFF) >> 2;
3673        let th = (lo & 0xFFF) >> 2;
3674        // Reject a degenerate/inverted range the same way as every other unsupported
3675        // path (write nothing) rather than letting the `& 0xFFF` wrap produce a large
3676        // bogus width/height: `sh < sl` would otherwise iterate ~4095 texels of
3677        // garbage. A well-formed load has SL <= SH and TL <= TH.
3678        if th < tl || sh < sl {
3679            return;
3680        }
3681        let width = (sh - sl + 1) & 0xFFF;
3682        let height = th - tl + 1;
3683        if width == 0 {
3684            return;
3685        }
3686        let tile = self.tiles[index];
3687        let Some(dst_bpt) = bytes_per_texel(tile.size) else {
3688            return; // 4-bit (or unmapped) not loaded here — R-7.
3689        };
3690        // The texture image should match the tile size (documented hazard). A 4-bit
3691        // (or unmapped) source size has no byte stride, so bail rather than fall back
3692        // to the tile stride and read out of bounds — R-7.
3693        let Some(src_bpt) = bytes_per_texel(self.tex_image_size) else {
3694            return;
3695        };
3696        let split = tile.size == 3; // 32-bit RGBA uses the split TMEM layout.
3697        let tmem_base = u32::from(tile.tmem_addr) * 8;
3698        let stride = u32::from(tile.line) * 8;
3699        let tex_w = u32::from(self.tex_image_width);
3700        for t in 0..height {
3701            let swap = (t & 1) << 2;
3702            for s in 0..width {
3703                let src_pixel = (tl + t) * tex_w + (sl + s);
3704                let src = self.tex_image_addr.wrapping_add(src_pixel * src_bpt);
3705                if split {
3706                    // R,G -> low half; B,A -> high half (offset by 0x800). The swap is
3707                    // applied per final byte so it stays correct regardless of alignment.
3708                    let bo = (tmem_base + stride * t + s * 2) & 0x7FF;
3709                    self.tmem_write((bo ^ swap) as usize, bus.rdram_read(src));
3710                    self.tmem_write(
3711                        ((bo + 1) ^ swap) as usize,
3712                        bus.rdram_read(src.wrapping_add(1)),
3713                    );
3714                    self.tmem_write(
3715                        ((bo + 0x800) ^ swap) as usize,
3716                        bus.rdram_read(src.wrapping_add(2)),
3717                    );
3718                    self.tmem_write(
3719                        ((bo + 0x801) ^ swap) as usize,
3720                        bus.rdram_read(src.wrapping_add(3)),
3721                    );
3722                } else {
3723                    let base = tmem_base + stride * t + s * dst_bpt;
3724                    for i in 0..dst_bpt {
3725                        // XOR the swap into each final byte address, not the base.
3726                        self.tmem_write(
3727                            ((base + i) ^ swap) as usize,
3728                            bus.rdram_read(src.wrapping_add(i)),
3729                        );
3730                    }
3731                }
3732            }
3733        }
3734        // Load Tile updates the descriptor's tile size for rendering.
3735        let tile = &mut self.tiles[index];
3736        tile.sl = ((hi >> 12) & 0xFFF) as u16;
3737        tile.tl = (hi & 0xFFF) as u16;
3738        tile.sh = ((lo >> 12) & 0xFFF) as u16;
3739        tile.th = (lo & 0xFFF) as u16;
3740    }
3741
3742    /// Apply a `Load Block` (0x33): stream a linear run of texels from the current
3743    /// texture image into the tile's TMEM region. `SL`/`SH` (bits 55:44 / 23:12)
3744    /// are `u12.0` integer texels; `SH − SL + 1` is the count (**inclusive**), and
3745    /// a count over [`LOAD_BLOCK_MAX_TEXELS`] writes nothing. The low field
3746    /// (bits 11:0) is **`dxt`** (`u1.11`): a running counter `T = (word * dxt) >>
3747    /// 11` over each 64-bit TMEM word decides line parity, and an odd line swaps
3748    /// that word's two 32-bit halves (`dst ^= 4`).
3749    ///
3750    /// Scope: 8/16-bit texels (`size` 1/2). The 32-bit split path and 4-bit are
3751    /// deferred (**open residual R-7**); an unsupported size writes nothing.
3752    fn load_block<B: VideoBus>(&mut self, hi: u32, lo: u32, bus: &B) {
3753        let index = ((lo >> 24) & 0x7) as usize;
3754        let slo = (hi >> 12) & 0xFFF;
3755        let tlo = hi & 0xFFF;
3756        let shi = (lo >> 12) & 0xFFF;
3757        let dxt = lo & 0xFFF;
3758        // An inverted range writes nothing (as in `load_tile`); without this an
3759        // extreme `shi < slo` (slo >= 2049) wraps into a valid-looking count.
3760        if shi < slo {
3761            return;
3762        }
3763        let count = (shi - slo + 1) & 0xFFF;
3764        if count == 0 || count > LOAD_BLOCK_MAX_TEXELS {
3765            return; // over the limit: nothing written (§Load Block).
3766        }
3767        let tile = self.tiles[index];
3768        let Some(bpt) = bytes_per_texel(tile.size) else {
3769            return;
3770        };
3771        if tile.size == 3 {
3772            return; // 32-bit block load (split) deferred — R-7.
3773        }
3774        // A 4-bit (or unmapped) source size has no byte stride — bail rather than
3775        // fall back to the tile stride and read out of bounds (R-7).
3776        let Some(src_bpt) = bytes_per_texel(self.tex_image_size) else {
3777            return;
3778        };
3779        let tex_w = u32::from(self.tex_image_width);
3780        let src_base = self
3781            .tex_image_addr
3782            .wrapping_add((tex_w * tlo + slo) * src_bpt);
3783        let tmem_base = u32::from(tile.tmem_addr) * 8;
3784        for s in 0..count {
3785            let src = src_base.wrapping_add(s * src_bpt);
3786            let byte_off = s * bpt;
3787            // Line parity from the dxt counter over 64-bit TMEM words.
3788            let word = byte_off / 8;
3789            let line = (word * dxt) >> 11;
3790            let swap = (line & 1) << 2;
3791            let base = tmem_base + byte_off;
3792            for i in 0..bpt {
3793                // XOR the swap into each final byte address, not the base.
3794                self.tmem_write(
3795                    ((base + i) ^ swap) as usize,
3796                    bus.rdram_read(src.wrapping_add(i)),
3797                );
3798            }
3799        }
3800    }
3801
3802    /// Apply a `Load TLUT` (0x30): load a palette into TMEM. Each 16-bit entry
3803    /// from the (16-bit) texture image is **quadrupled** — written to four
3804    /// adjacent `u16` slots — so entry `i` occupies 8 bytes at TMEM byte
3805    /// `tmem_addr*8 + i*8`. The count is inclusive (`(SH>>2) − (SL>>2) + 1`).
3806    ///
3807    /// The destination is wherever the tile's `tmem_addr` points; a correct
3808    /// program sets it into the upper 2 KiB (byte >= 0x800), aligned to 128 bytes
3809    /// (N64brew *…/Commands* §Load TLUT). That is a **programmer requirement, not
3810    /// a hardware rejection** — the ParaLLEl-RDP reference writes to the addressed
3811    /// location and the sampler reads the palette from the upper half, so a
3812    /// misplaced TLUT is simply not found rather than refused. Enforcing a
3813    /// rejection here would invent behavior the hardware does not have.
3814    fn load_tlut<B: VideoBus>(&mut self, hi: u32, lo: u32, bus: &B) {
3815        let sl = ((hi >> 12) & 0xFFF) >> 2;
3816        let sh = ((lo >> 12) & 0xFFF) >> 2;
3817        let index = ((lo >> 24) & 0x7) as usize;
3818        if sh < sl {
3819            return;
3820        }
3821        let count = sh - sl + 1;
3822        let tmem_base = u32::from(self.tiles[index].tmem_addr) * 8;
3823        let src_base = self.tex_image_addr.wrapping_add(sl * 2); // 16-bit source
3824        for i in 0..count {
3825            let src = src_base.wrapping_add(i * 2);
3826            let hi_b = bus.rdram_read(src);
3827            let lo_b = bus.rdram_read(src.wrapping_add(1));
3828            let dst = tmem_base + i * 8;
3829            for k in 0..4u32 {
3830                let slot = (dst + k * 2) as usize;
3831                self.tmem_write(slot, hi_b);
3832                self.tmem_write(slot + 1, lo_b);
3833            }
3834        }
3835        // Load TLUT also updates the tile size (like the other loads).
3836        let tile = &mut self.tiles[index];
3837        tile.sl = ((hi >> 12) & 0xFFF) as u16;
3838        tile.tl = (hi & 0xFFF) as u16;
3839        tile.sh = ((lo >> 12) & 0xFFF) as u16;
3840        tile.th = (lo & 0xFFF) as u16;
3841    }
3842
3843    /// Sample one texel from `tile` at tile-relative integer coords `(s, t)`,
3844    /// returning RGBA8888. The fetch half of the texture pipeline; the
3845    /// clamp/mirror/mask/shift wrapper and the filter/combiner are T-32-004 /
3846    /// Sprint 3. Decodes every listed texel format (RGBA16/32, IA16/8/4, I8/4,
3847    /// CI8/4 via the TLUT), matched to the ParaLLEl-RDP read layout.
3848    ///
3849    /// TMEM is read as a natural big-endian byte array with the odd-row
3850    /// 32-bit-word swap `^= (t & 1) << 2` — the same convention the loads use, so
3851    /// the endian twiddles ParaLLEl-RDP applies to its host-word storage are
3852    /// intentionally absent here too. An unsupported format/size is transparent
3853    /// black.
3854    #[must_use]
3855    pub fn fetch_texel(&self, tile: &TileDescriptor, s: u32, t: u32) -> [u8; 4] {
3856        let swap = (t & 1) << 2;
3857        // Wrapping arithmetic end to end: an oversized/unclipped `s` or `t` must
3858        // not debug-panic on overflow before the TMEM mask applies — a panic would
3859        // break the determinism contract (ADR 0004). Every offset below is masked
3860        // into the 4 KiB space by `tmem_byte`. The per-column byte offsets for the
3861        // three texel widths (16/32-bit, 8-bit, 4-bit-nibble):
3862        let base = u32::from(tile.tmem_addr)
3863            .wrapping_mul(8)
3864            .wrapping_add(u32::from(tile.line).wrapping_mul(8).wrapping_mul(t));
3865        let off16 = base.wrapping_add(s.wrapping_mul(2));
3866        let off8 = base.wrapping_add(s);
3867        let off4 = base.wrapping_add(s >> 1);
3868        match (tile.format, tile.size) {
3869            (0, 2) => decode_rgba16(self.tmem_u16(off16 ^ swap)), // RGBA16
3870            (0, 3) => {
3871                // RGBA32 split: R,G low half; B,A high half.
3872                let bo = (off16 & 0x7FF) ^ swap;
3873                [
3874                    self.tmem_byte(bo as usize),
3875                    self.tmem_byte(bo.wrapping_add(1) as usize),
3876                    self.tmem_byte(bo.wrapping_add(TMEM_HIGH) as usize),
3877                    self.tmem_byte(bo.wrapping_add(TMEM_HIGH + 1) as usize),
3878                ]
3879            }
3880            (3, 2) => {
3881                // IA16: I high byte, A low byte.
3882                let w = self.tmem_u16(off16 ^ swap);
3883                let i = (w >> 8) as u8;
3884                [i, i, i, (w & 0xFF) as u8]
3885            }
3886            (3, 1) => {
3887                // IA8: I high nibble, A low nibble (each 4->8).
3888                let byte = self.tmem_byte((off8 ^ swap) as usize);
3889                let i = widen4(u32::from(byte) >> 4);
3890                [i, i, i, widen4(u32::from(byte) & 0xF)]
3891            }
3892            (3, 0) => {
3893                // IA4: I top 3 bits (3->8), A bottom bit.
3894                let nib = self.nibble_at((off4 ^ swap) as usize, s);
3895                let i = widen3(u32::from(nib) >> 1);
3896                [i, i, i, if nib & 1 != 0 { 0xFF } else { 0 }]
3897            }
3898            (4, 1) => {
3899                // I8: intensity in all channels, alpha = intensity.
3900                let v = self.tmem_byte((off8 ^ swap) as usize);
3901                [v, v, v, v]
3902            }
3903            (4, 0) => {
3904                // I4: 4-bit intensity (4->8), alpha = intensity.
3905                let v = widen4(u32::from(self.nibble_at((off4 ^ swap) as usize, s)));
3906                [v, v, v, v]
3907            }
3908            // The color-index formats resolve through the palette **only when
3909            // `Set Other Modes.tlut_en` is set** (bit 47) — the format field alone
3910            // does not enable it (N64brew *…/Commands* §0x2F). With the flag clear
3911            // the oracle renders a CI tile entirely black, which
3912            // `ci4_tlut_disabled_16` pins: it is byte-identical to
3913            // `tex_tri_ci4_tlut_16` apart from that one bit, and the two goldens are
3914            // the full palette versus all black.
3915            //
3916            // Zero is what the oracle produces, not a mechanism claim: what the
3917            // hardware *does* with un-TLUT'd index data is not documented in §0x2F,
3918            // so this reproduces the observed result rather than inventing a
3919            // reinterpretation of the index bits.
3920            (2, _) if !self.other_modes.tlut_en => [0, 0, 0, 0],
3921            (2, 1) => {
3922                // CI8: 8-bit index into the TLUT.
3923                let ci = self.tmem_byte(((off8 & 0x7FF) ^ swap) as usize);
3924                self.tlut_lookup(u32::from(ci))
3925            }
3926            (2, 0) => {
3927                // CI4: 4-bit index + tile.palette as the high nibble.
3928                let nib = self.nibble_at(((off4 & 0x7FF) ^ swap) as usize, s);
3929                // `palette` is already 4-bit from `set_tile` decode; mask defensively
3930                // so a directly-constructed descriptor cannot push `ci` out of range.
3931                let ci = u32::from(nib) | (u32::from(tile.palette & 0xF) << 4);
3932                self.tlut_lookup(ci)
3933            }
3934            _ => [0, 0, 0, 0],
3935        }
3936    }
3937
3938    /// Read a big-endian `u16` from TMEM at byte offset `b` (both bytes masked
3939    /// into the 4 KiB space; `b + 1` wraps rather than overflowing).
3940    fn tmem_u16(&self, b: u32) -> u32 {
3941        (u32::from(self.tmem_byte(b as usize)) << 8)
3942            | u32::from(self.tmem_byte(b.wrapping_add(1) as usize))
3943    }
3944
3945    /// Select the 4-bit nibble of the TMEM byte at `byte_off` for texel column
3946    /// `s`: the high nibble for even `s`, the low nibble for odd `s`.
3947    fn nibble_at(&self, byte_off: usize, s: u32) -> u8 {
3948        let byte = self.tmem_byte(byte_off);
3949        (byte >> ((!s & 1) * 4)) & 0xF
3950    }
3951
3952    /// Look up a TLUT entry by 8-bit index `ci` and decode it as RGBA5551.
3953    ///
3954    /// Entry `ci` is the quadrupled 16-bit word at TMEM byte `0x800 + ci*8` (the
3955    /// four copies are identical after `Load TLUT`, so the first is read). The
3956    /// `IA16` TLUT type (Other Modes `tlut_type = 1`) is deferred; RGBA16 is
3957    /// assumed.
3958    fn tlut_lookup(&self, ci: u32) -> [u8; 4] {
3959        decode_rgba16(self.tmem_u16(TMEM_HIGH.wrapping_add(ci.wrapping_mul(8))))
3960    }
3961
3962    /// Read one byte of TMEM.
3963    ///
3964    /// `offset` is a **byte** address (0..[`TMEM_SIZE`]), masked into the 4 KiB
3965    /// space — *not* the 64-bit-word address that `Set Tile`'s `tmem_addr` /
3966    /// `line` use; a word address must be multiplied by 8 first (word 0x100 =
3967    /// byte 0x800). An unwritten (lazily-unallocated) TMEM reads as zero.
3968    #[must_use]
3969    pub fn tmem_byte(&self, offset: usize) -> u8 {
3970        self.tmem
3971            .as_ref()
3972            .map_or(0, |t| t[offset & (TMEM_SIZE - 1)])
3973    }
3974}
3975
3976/// Returns the crate version string.
3977#[must_use]
3978pub const fn version() -> &'static str {
3979    env!("CARGO_PKG_VERSION")
3980}
3981
3982#[cfg(test)]
3983mod tests {
3984    use super::*;
3985    use alloc::vec::Vec;
3986
3987    /// Every early-out of [`Rdp::tick_without_bus`], exercised here rather than only
3988    /// through `Bus::rdp_tick` in another crate.
3989    ///
3990    /// Each branch is the reason a step can skip the 344-byte `core::mem::take`, so a
3991    /// branch that stopped firing would be a silent performance regression, and one
3992    /// that fired when it should not would be a **correctness** regression — a skipped
3993    /// command. Neither shows up in the conformance vectors as long as the totals
3994    /// happen to work out, which is why they are pinned individually.
3995    #[test]
3996    fn every_bus_free_early_out_fires_on_its_own_condition() {
3997        // Frozen: no bus needed, and the stall is *not* touched — a frozen pipeline
3998        // does not burn a GCLK.
3999        let mut rdp = Rdp::new();
4000        rdp.status |= DP_STATUS_FREEZE;
4001        rdp.stall = 5;
4002        rdp.cmd_current = 0;
4003        rdp.cmd_end = 0x100;
4004        assert!(rdp.tick_without_bus().is_none(), "frozen: no bus");
4005        assert_eq!(rdp.stall, 5, "a frozen pipeline does not count down");
4006
4007        // XBUS (DMEM-sourced, not yet wired) takes the same exit.
4008        let mut rdp = Rdp::new();
4009        rdp.status |= DP_STATUS_XBUS;
4010        rdp.cmd_end = 0x100;
4011        assert!(rdp.tick_without_bus().is_none(), "xbus: no bus");
4012
4013        // Stalling: no bus, and exactly one GCLK burned.
4014        let mut rdp = Rdp::new();
4015        rdp.stall = 2;
4016        rdp.cmd_end = 0x100;
4017        assert!(rdp.tick_without_bus().is_none(), "stalled: no bus");
4018        assert_eq!(rdp.stall, 1, "one GCLK per step");
4019        assert!(rdp.tick_without_bus().is_none(), "still stalled");
4020        assert_eq!(rdp.stall, 0, "and again");
4021
4022        // Empty FIFO: no bus, nothing mutated.
4023        let mut rdp = Rdp::new();
4024        rdp.cmd_current = 0x40;
4025        rdp.cmd_end = 0x40;
4026        assert!(rdp.tick_without_bus().is_none(), "empty FIFO: no bus");
4027
4028        // And the one case that DOES need the bus: unfrozen, unstalled, non-empty.
4029        let mut rdp = Rdp::new();
4030        rdp.cmd_current = 0;
4031        rdp.cmd_end = 0x100;
4032        assert!(
4033            rdp.tick_without_bus().is_some(),
4034            "a queued command needs RDRAM to decode its opcode"
4035        );
4036    }
4037
4038    struct NullBus;
4039    impl RdramBus for NullBus {
4040        fn rdram_read(&self, _addr: u32) -> u8 {
4041            0
4042        }
4043        fn rdram_write(&mut self, _addr: u32, _val: u8) {}
4044    }
4045    impl VideoBus for NullBus {}
4046
4047    #[test]
4048    fn empty_fifo_tick_is_noop() {
4049        let mut rdp = Rdp::new();
4050        let mut bus = NullBus;
4051        rdp.tick(&mut bus);
4052        assert_eq!(rdp.cmd_current, 0);
4053    }
4054
4055    #[test]
4056    fn version_is_non_empty() {
4057        assert!(!version().is_empty());
4058    }
4059
4060    /// **`DPC_STATUS` writes are set/clear commands.** `SET_FREEZE` (0x8) raises
4061    /// FREEZE; `CLEAR_FREEZE` (0x4) drops it. n64-systemtest's `RDP START & END
4062    /// REG` freezes the DP precisely so it can poke the registers.
4063    #[test]
4064    fn status_write_sets_and_clears_freeze() {
4065        let mut rdp = Rdp::new();
4066        rdp.dpc_write(3, 0x8); // SET_FREEZE
4067        assert_ne!(rdp.dpc_read(3) & DP_STATUS_FREEZE, 0, "freeze set");
4068        rdp.dpc_write(3, 0x4); // CLEAR_FREEZE
4069        assert_eq!(rdp.dpc_read(3) & DP_STATUS_FREEZE, 0, "freeze cleared");
4070    }
4071
4072    /// **`DPC_START`/`END` mask to a 24-bit, 8-aligned address**, and writing
4073    /// `END` copies the latched start into `CURRENT`.
4074    #[test]
4075    fn start_end_mask_and_current_follows_start() {
4076        let mut rdp = Rdp::new();
4077        rdp.dpc_write(3, 0x8); // freeze
4078        rdp.dpc_write(0, 0x12FF_FFFF); // START
4079        rdp.dpc_write(1, 0x12FF_FFFF); // END
4080        assert_eq!(rdp.dpc_read(0), 0x00FF_FFF8, "START masked");
4081        assert_eq!(rdp.dpc_read(1), 0x00FF_FFF8, "END masked");
4082        assert_eq!(rdp.dpc_read(2), 0x00FF_FFF8, "CURRENT = START after END");
4083    }
4084
4085    /// **The `START_VALID` double-latch.** Writing START sets `START_VALID`; a
4086    /// second write while valid is *ignored*; writing END consumes it (clears
4087    /// `START_VALID`, leaves `END_VALID` clear while frozen). This is the exact
4088    /// sequence `RSP STATUS: start-valid` walks.
4089    #[test]
4090    fn start_valid_latch_ignores_a_second_start_write() {
4091        let mut rdp = Rdp::new();
4092        rdp.dpc_write(3, 0x8); // freeze
4093        assert_eq!(rdp.dpc_read(3) & DP_STATUS_START_VALID, 0, "clear at entry");
4094
4095        rdp.dpc_write(0, 0x1238); // START
4096        assert_ne!(
4097            rdp.dpc_read(3) & DP_STATUS_START_VALID,
4098            0,
4099            "set after write"
4100        );
4101        assert_eq!(rdp.dpc_read(0), 0x1238);
4102
4103        rdp.dpc_write(0, 0x12_3450); // ignored while valid
4104        assert_eq!(rdp.dpc_read(0), 0x1238, "second START write ignored");
4105
4106        rdp.dpc_write(1, 0x1238); // END consumes the latch
4107        assert_eq!(rdp.dpc_read(3) & DP_STATUS_START_VALID, 0, "cleared by END");
4108        assert_eq!(
4109            rdp.dpc_read(3) & DP_STATUS_END_VALID,
4110            0,
4111            "END_VALID clear while frozen"
4112        );
4113        assert_eq!(rdp.dpc_read(2), 0x1238, "CURRENT = START");
4114    }
4115
4116    /// **An END-only write is an incremental transfer: `CURRENT` is not
4117    /// rewound.** With `START_VALID` clear (the first transfer already
4118    /// consumed), writing a new END extends the buffer from where the DMA
4119    /// stopped — reloading `CURRENT` from `START` would reprocess commands
4120    /// already transferred (N64brew *Interface*, `DPC_END`: "If `START_PENDING`
4121    /// is 0, the write is considered an incremental transfer").
4122    #[test]
4123    fn an_end_only_write_extends_without_rewinding_current() {
4124        let mut rdp = Rdp::new();
4125        rdp.dpc_write(3, 0x8); // freeze
4126        rdp.dpc_write(0, 0x1000); // START
4127        rdp.dpc_write(1, 0x1000); // END consumes START -> START_VALID clear
4128        rdp.cmd_current = 0x1000; // pretend the transfer reached the end
4129
4130        rdp.dpc_write(1, 0x1040); // incremental END, no new START
4131        assert_eq!(rdp.dpc_read(1), 0x1040, "END extended");
4132        assert_eq!(rdp.dpc_read(2), 0x1000, "CURRENT not rewound to START");
4133    }
4134
4135    /// **A frozen DP does not advance the FIFO**, so registers stay put even
4136    /// with `cmd_current < cmd_end`.
4137    #[test]
4138    fn a_frozen_dp_does_not_tick() {
4139        let mut rdp = Rdp::new();
4140        rdp.status = DP_STATUS_FREEZE;
4141        rdp.cmd_current = 0x10;
4142        rdp.cmd_end = 0x40;
4143        let mut bus = NullBus;
4144        rdp.tick(&mut bus);
4145        assert_eq!(rdp.cmd_current, 0x10, "frozen: CURRENT unchanged");
4146    }
4147
4148    /// A bus backed by a byte buffer, so the decoder can walk a real command
4149    /// list out of "RDRAM" and we can assert the pointer lands exactly on
4150    /// `DPC_END`.
4151    struct SliceBus {
4152        mem: Vec<u8>,
4153        dp_raised: bool,
4154    }
4155    impl RdramBus for SliceBus {
4156        fn rdram_read(&self, addr: u32) -> u8 {
4157            self.mem.get(addr as usize).copied().unwrap_or(0)
4158        }
4159        fn rdram_write(&mut self, addr: u32, val: u8) {
4160            if let Some(b) = self.mem.get_mut(addr as usize) {
4161                *b = val;
4162            }
4163        }
4164    }
4165    impl VideoBus for SliceBus {
4166        fn raise_dp_interrupt(&mut self) {
4167            self.dp_raised = true;
4168        }
4169    }
4170
4171    /// Append a command: its opcode in bits 61:56 of the first word, then
4172    /// `words` total 64-bit words with the remainder zero-filled. The word count
4173    /// is supplied **explicitly by the caller**, independent of the production
4174    /// decoder, so a walk over the buffer is a genuine check of
4175    /// `command_len_words` rather than a tautology built from it.
4176    fn push_cmd(buf: &mut Vec<u8>, opcode: u8, words: u32) {
4177        buf.extend_from_slice(&(u32::from(opcode) << 24).to_be_bytes());
4178        for _ in 4..words * 8 {
4179            buf.push(0);
4180        }
4181    }
4182
4183    /// **The decoder consumes every command whole and never desyncs.** A mixed
4184    /// list exercising all three length classes — a 1-word set-state, a 22-word
4185    /// shade+texture+z triangle, a no-op, a 2-word texture rectangle, and
4186    /// `Sync Full` — drains one command per tick and lands `DPC_CURRENT` exactly
4187    /// on `DPC_END`. The expected lengths are stated here from the N64brew
4188    /// command map, so a wrong decoder length overshoots or stops short.
4189    #[test]
4190    fn decoder_consumes_each_command_whole_without_desync() {
4191        // (opcode, documented 64-bit-word length) — independent of the decoder.
4192        let fixtures = [
4193            (0x3F_u8, 1), // Set Color Image
4194            (0x0F, 22),   // Fill Triangle (STZ) = shade + texture + z
4195            (0x00, 1),    // No Operation
4196            (0x24, 2),    // Texture Rectangle
4197            (0x29, 1),    // Sync Full
4198        ];
4199        let mut mem = Vec::new();
4200        for &(op, words) in &fixtures {
4201            push_cmd(&mut mem, op, words);
4202        }
4203        let total = u32::try_from(mem.len()).unwrap();
4204        let mut bus = SliceBus {
4205            mem,
4206            dp_raised: false,
4207        };
4208        let mut rdp = Rdp::new();
4209        rdp.cmd_end = total;
4210
4211        let mut ticks = 0u32;
4212        while rdp.cmd_current < rdp.cmd_end && ticks < 1000 {
4213            rdp.tick(&mut bus);
4214            ticks += 1;
4215        }
4216        assert_eq!(rdp.cmd_current, total, "consumed exactly to DPC_END");
4217        assert_eq!(ticks, 5, "one command retired per scheduler tick");
4218        assert_eq!(rdp.commands_processed, 5, "every command counted");
4219    }
4220
4221    /// **A multi-word primitive is consumed in a single tick**, by its full
4222    /// decoded length — an unimplemented command advances the FIFO past all its
4223    /// words rather than treating each word as a fresh command.
4224    #[test]
4225    fn a_multiword_command_is_consumed_in_one_tick() {
4226        let mut mem = Vec::new();
4227        push_cmd(&mut mem, 0x0E, 20); // Fill Triangle (ST) = shade + texture: 20 words
4228        let mut bus = SliceBus {
4229            mem,
4230            dp_raised: false,
4231        };
4232        let mut rdp = Rdp::new();
4233        rdp.cmd_end = 20 * 8;
4234        rdp.tick(&mut bus);
4235        assert_eq!(rdp.cmd_current, 20 * 8, "whole 20-word triangle at once");
4236        assert_eq!(rdp.commands_processed, 1);
4237    }
4238
4239    /// **A partially-written command is not consumed until it is complete.** If
4240    /// `DPC_END` lands mid-command — as it does while the `rdpq` microcode fills
4241    /// the buffer and advances `DPC_END` incrementally — the decoder stalls
4242    /// rather than executing against unwritten RDRAM, then consumes the command
4243    /// whole once the rest of its words arrive.
4244    #[test]
4245    fn a_partial_command_is_not_consumed_until_complete() {
4246        let mut mem = Vec::new();
4247        push_cmd(&mut mem, 0x0F, 22); // 22-word triangle
4248        let mut bus = SliceBus {
4249            mem,
4250            dp_raised: false,
4251        };
4252        let mut rdp = Rdp::new();
4253        rdp.cmd_end = 10 * 8; // DPC_END only reached word 10 of 22
4254        rdp.tick(&mut bus);
4255        assert_eq!(rdp.cmd_current, 0, "stalled: partial command not consumed");
4256        assert_eq!(rdp.commands_processed, 0);
4257
4258        rdp.cmd_end = 22 * 8; // the rest of the command arrives
4259        rdp.tick(&mut bus);
4260        assert_eq!(rdp.cmd_current, 22 * 8, "consumed whole once complete");
4261        assert_eq!(rdp.commands_processed, 1);
4262    }
4263
4264    /// **XBUS mode reads commands from DMEM, which is not yet wired**, so the
4265    /// decoder must not mis-read RDRAM as the command stream. With `XBUS` set it
4266    /// stalls, leaving `DPC_CURRENT` and the counter untouched.
4267    #[test]
4268    fn xbus_mode_does_not_decode_rdram() {
4269        let mut mem = Vec::new();
4270        push_cmd(&mut mem, 0x3F, 1);
4271        let mut bus = SliceBus {
4272            mem,
4273            dp_raised: false,
4274        };
4275        let mut rdp = Rdp::new();
4276        rdp.status = DP_STATUS_XBUS;
4277        rdp.cmd_end = 8;
4278        rdp.tick(&mut bus);
4279        assert_eq!(rdp.cmd_current, 0, "XBUS: RDRAM not decoded");
4280        assert_eq!(rdp.commands_processed, 0);
4281    }
4282
4283    /// Drive a single command through `tick` and return the resulting state.
4284    fn run_one(opcode: u8) -> (Rdp, SliceBus) {
4285        let mut mem = Vec::new();
4286        push_cmd(&mut mem, opcode, 1);
4287        let mut bus = SliceBus {
4288            mem,
4289            dp_raised: false,
4290        };
4291        let mut rdp = Rdp::new();
4292        rdp.cmd_end = 8;
4293        rdp.tick(&mut bus);
4294        (rdp, bus)
4295    }
4296
4297    /// **`Sync Full` (0x29) raises the DP interrupt.** The dispatcher calls
4298    /// `raise_dp_interrupt` on the bus, which the live `Bus` turns into
4299    /// `MI_INTR.dp`; here the test bus records the raise.
4300    #[test]
4301    fn sync_full_raises_the_dp_interrupt() {
4302        let (rdp, bus) = run_one(OP_SYNC_FULL);
4303        assert!(bus.dp_raised, "Sync Full raised the DP interrupt");
4304        assert_eq!(rdp.commands_processed, 1);
4305        assert_eq!(rdp.stall, 0, "Sync Full does not stall the pipeline itself");
4306    }
4307
4308    /// **The other sync commands do not raise an interrupt** — only `Sync Full`
4309    /// does. They each set the documented fixed pipeline stall instead.
4310    #[test]
4311    fn sync_load_pipe_tile_set_the_documented_stall() {
4312        for (opcode, expected) in [
4313            (OP_SYNC_LOAD, SYNC_LOAD_GCLK),
4314            (OP_SYNC_PIPE, SYNC_PIPE_GCLK),
4315            (OP_SYNC_TILE, SYNC_TILE_GCLK),
4316        ] {
4317            let (rdp, bus) = run_one(opcode);
4318            assert!(!bus.dp_raised, "opcode {opcode:#04x} raised no interrupt");
4319            assert_eq!(rdp.stall, expected, "opcode {opcode:#04x} stall cycles");
4320        }
4321    }
4322
4323    /// **A sync stall holds the FIFO for exactly its GCLK count.** After a
4324    /// `Sync Pipe` (50 GCLK) the next command is not consumed until 50 further
4325    /// ticks have elapsed — the pipeline is unavailable for exactly that long,
4326    /// as the command is an unconditional fixed-length stall.
4327    #[test]
4328    fn a_sync_pipe_stall_holds_the_fifo_for_50_gclk() {
4329        let mut mem = Vec::new();
4330        push_cmd(&mut mem, OP_SYNC_PIPE, 1); // sets stall = 50
4331        push_cmd(&mut mem, 0x00, 1); // a following no-op
4332        let mut bus = SliceBus {
4333            mem,
4334            dp_raised: false,
4335        };
4336        let mut rdp = Rdp::new();
4337        rdp.cmd_end = 16;
4338
4339        rdp.tick(&mut bus); // consumes Sync Pipe, sets stall = 50
4340        assert_eq!(rdp.commands_processed, 1);
4341        assert_eq!(rdp.stall, SYNC_PIPE_GCLK);
4342
4343        // The next 50 ticks burn the stall and do not advance the FIFO.
4344        for i in 0..SYNC_PIPE_GCLK {
4345            rdp.tick(&mut bus);
4346            assert_eq!(rdp.commands_processed, 1, "still stalled at tick {i}");
4347            assert_eq!(rdp.stall, SYNC_PIPE_GCLK - 1 - i);
4348        }
4349        // Stall expired: the following command is consumed on the next tick.
4350        rdp.tick(&mut bus);
4351        assert_eq!(rdp.commands_processed, 2, "FIFO resumes after the stall");
4352    }
4353
4354    /// **A frozen DP does not burn stall cycles.** The freeze guard is checked
4355    /// before the stall countdown, so a non-zero `stall` is held — not
4356    /// decremented — while frozen, and resumes counting down only once the DP is
4357    /// unfrozen. The plain `a_frozen_dp_does_not_tick` test leaves `stall` at
4358    /// zero and so cannot catch a regression that decremented it under freeze.
4359    #[test]
4360    fn a_frozen_dp_holds_its_stall_countdown() {
4361        let mut rdp = Rdp::new();
4362        let mut bus = NullBus;
4363        rdp.stall = 10;
4364        rdp.status = DP_STATUS_FREEZE;
4365        rdp.tick(&mut bus);
4366        assert_eq!(rdp.stall, 10, "frozen: stall countdown held, not burned");
4367
4368        rdp.status = 0; // unfreeze
4369        rdp.tick(&mut bus);
4370        assert_eq!(rdp.stall, 9, "unfrozen: countdown resumes");
4371    }
4372
4373    /// **A preceding stall delays the `Sync Full` interrupt.** With `Sync Pipe`
4374    /// (50 GCLK) queued before `Sync Full`, the DP interrupt stays low for all
4375    /// 50 stall ticks and rises only once the stall drains and `Sync Full` is
4376    /// dispatched — the stall-before-interrupt ordering the dispatch doc claims.
4377    /// (Were the stall gate absent, `Sync Full` would dispatch on the very next
4378    /// tick and the interrupt would rise during the loop.)
4379    #[test]
4380    fn a_preceding_stall_delays_the_sync_full_interrupt() {
4381        let mut mem = Vec::new();
4382        push_cmd(&mut mem, OP_SYNC_PIPE, 1);
4383        push_cmd(&mut mem, OP_SYNC_FULL, 1);
4384        let mut bus = SliceBus {
4385            mem,
4386            dp_raised: false,
4387        };
4388        let mut rdp = Rdp::new();
4389        rdp.cmd_end = 16;
4390
4391        rdp.tick(&mut bus); // consume Sync Pipe -> stall = 50
4392        assert_eq!(rdp.stall, SYNC_PIPE_GCLK);
4393        assert!(!bus.dp_raised, "no interrupt while the stall is set");
4394
4395        for i in 0..SYNC_PIPE_GCLK {
4396            rdp.tick(&mut bus);
4397            assert!(!bus.dp_raised, "interrupt still low during stall tick {i}");
4398        }
4399        // Stall drained: the next tick dispatches Sync Full and raises.
4400        rdp.tick(&mut bus);
4401        assert!(
4402            bus.dp_raised,
4403            "interrupt raised only after the stall drains"
4404        );
4405        assert_eq!(rdp.commands_processed, 2);
4406    }
4407
4408    // --- The FILL pipeline (T-31-003) ---
4409
4410    // The command list lives here; the color image is based at RDRAM 0, well
4411    // below it, so the two never overlap in the shared test buffer.
4412    const CMD_BASE: u32 = 0x4000;
4413
4414    fn push_word(buf: &mut Vec<u8>, hi: u32, lo: u32) {
4415        buf.extend_from_slice(&hi.to_be_bytes());
4416        buf.extend_from_slice(&lo.to_be_bytes());
4417    }
4418
4419    // Command builders. Screen coordinates are given in whole pixels; the wire
4420    // format is u10.2, so each is shifted left by two.
4421    fn set_color_image(format: u32, size: u32, width: u32, addr: u32) -> (u32, u32) {
4422        let hi =
4423            (u32::from(OP_SET_COLOR_IMAGE) << 24) | (format << 21) | (size << 19) | (width - 1);
4424        (hi, addr)
4425    }
4426    fn set_fill_color(color: u32) -> (u32, u32) {
4427        (u32::from(OP_SET_FILL_COLOR) << 24, color)
4428    }
4429    fn set_scissor(ulx: u32, uly: u32, lrx: u32, lry: u32) -> (u32, u32) {
4430        let hi = (u32::from(OP_SET_SCISSOR) << 24) | (ulx << 14) | (uly << 2);
4431        let lo = (lrx << 14) | (lry << 2);
4432        (hi, lo)
4433    }
4434    fn fill_rect(ulx: u32, uly: u32, lrx: u32, lry: u32) -> (u32, u32) {
4435        let hi = (u32::from(OP_FILL_RECTANGLE) << 24) | (lrx << 14) | (lry << 2);
4436        let lo = (ulx << 14) | (uly << 2);
4437        (hi, lo)
4438    }
4439    /// `Set Other Modes` selecting **FILL** cycle type (`cycle_type` is command
4440    /// bits 53:52 = word-0 bits 21:20). Required by every fill-register test: in
4441    /// 1-/2-cycle mode a rectangle goes through the combiner instead and never
4442    /// reads the fill register at all (ledger R-21).
4443    fn set_cycle_fill() -> (u32, u32) {
4444        (
4445            (u32::from(OP_SET_OTHER_MODES) << 24) | (u32::from(CYCLE_TYPE_FILL) << 20),
4446            0,
4447        )
4448    }
4449
4450    /// Run a command list through the FIFO (color image at RDRAM 0, commands at
4451    /// `CMD_BASE`) and return the RDP plus the memory the fill wrote into.
4452    fn run_commands(words: &[(u32, u32)]) -> (Rdp, SliceBus) {
4453        let mut mem = alloc::vec![0u8; CMD_BASE as usize + words.len() * 8];
4454        let mut list = Vec::new();
4455        for &(hi, lo) in words {
4456            push_word(&mut list, hi, lo);
4457        }
4458        mem[CMD_BASE as usize..CMD_BASE as usize + list.len()].copy_from_slice(&list);
4459        let mut bus = SliceBus {
4460            mem,
4461            dp_raised: false,
4462        };
4463        let mut rdp = Rdp::new();
4464        rdp.cmd_current = CMD_BASE;
4465        rdp.cmd_end = CMD_BASE + u32::try_from(list.len()).unwrap();
4466        let mut guard = 0;
4467        while rdp.cmd_current < rdp.cmd_end && guard < 10_000 {
4468            rdp.tick(&mut bus);
4469            guard += 1;
4470        }
4471        (rdp, bus)
4472    }
4473
4474    /// **`Set Color Image` parses format, size, width, and address.** Width is
4475    /// the encoded field plus one; the address is masked to 24 bits.
4476    #[test]
4477    fn set_color_image_parses_its_fields() {
4478        let (rdp, _) = run_commands(&[set_color_image(0, 3, 320, 0x0010_0000)]);
4479        assert_eq!(rdp.color_image_format, 0);
4480        assert_eq!(rdp.color_image_size, 3);
4481        assert_eq!(rdp.color_image_width, 320);
4482        assert_eq!(rdp.color_image, 0x0010_0000);
4483    }
4484
4485    /// **`Set Key GB`/`Set Key R` decode the chroma-key center/scale/width per channel
4486    /// (R-10).** Pins the bit-layout ported from Angrylion `rdp_set_key_gb`/`_r`: GB
4487    /// word-0 is `width_g[23:12] width_b[11:0]`, word-1 `center_g[31:24] scale_g[23:16]
4488    /// center_b[15:8] scale_b[7:0]`; R word-1 is `width_r[27:16] center_r[15:8]
4489    /// scale_r[7:0]`. Distinct per-channel values (incl. distinct 12-bit widths) so a
4490    /// field-swap or wrong extraction in the decode is caught.
4491    #[test]
4492    fn set_key_decodes_center_scale_and_width_per_channel() {
4493        let (rdp, _) = run_commands(&[
4494            // Set Key GB: wg=0x111 wb=0x222; cg=0x40 sg=0x80 cb=0x60 sb=0xC0.
4495            (0x2A11_1222, 0x4080_60C0),
4496            // Set Key R: wr=0x333; cr=0x20 sr=0x40.
4497            (0x2B00_0000, 0x0333_2040),
4498        ]);
4499        assert_eq!(rdp.key_center, [0x20, 0x40, 0x60], "center [r, g, b]");
4500        assert_eq!(rdp.key_scale, [0x40, 0x80, 0xC0], "scale [r, g, b]");
4501        assert_eq!(rdp.key_width, [0x333, 0x111, 0x222], "width [r, g, b]");
4502    }
4503
4504    /// **`Set Fill Color` and `Set Scissor` store their values.**
4505    #[test]
4506    fn set_fill_color_and_scissor_store_state() {
4507        let (rdp, _) = run_commands(&[set_fill_color(0xDEAD_BEEF), set_scissor(2, 3, 6, 7)]);
4508        assert_eq!(rdp.fill_color, 0xDEAD_BEEF);
4509        assert_eq!(rdp.scissor_ulx, 2 << 2);
4510        assert_eq!(rdp.scissor_uly, 3 << 2);
4511        assert_eq!(rdp.scissor_lrx, 6 << 2);
4512        assert_eq!(rdp.scissor_lry, 7 << 2);
4513    }
4514
4515    /// **A 32-bit FILL writes the whole color to every pixel**, four bytes
4516    /// each, big-endian — the memory is the fill value repeated verbatim.
4517    #[test]
4518    fn fill_rectangle_32bpp_writes_the_color_verbatim() {
4519        let (_, bus) = run_commands(&[
4520            set_cycle_fill(),
4521            set_color_image(0, 3, 4, 0), // 32-bit, width 4, base 0
4522            set_fill_color(0xAABB_CCDD),
4523            set_scissor(0, 0, 4, 2),
4524            fill_rect(0, 0, 4, 2),
4525        ]);
4526        // 4 px * 2 rows * 4 bytes = 32 bytes, all AA BB CC DD.
4527        for chunk in bus.mem[0..32].chunks_exact(4) {
4528            assert_eq!(chunk, [0xAA, 0xBB, 0xCC, 0xDD]);
4529        }
4530        assert_eq!(bus.mem[32], 0, "nothing written past the rectangle");
4531    }
4532
4533    /// **A 16-bit FILL alternates the color's halves per pixel** — even pixels
4534    /// take the upper 16 bits, odd pixels the lower — so memory is still the
4535    /// 32-bit value repeated.
4536    #[test]
4537    fn fill_rectangle_16bpp_alternates_halves() {
4538        let (_, bus) = run_commands(&[
4539            set_cycle_fill(),
4540            set_color_image(0, 2, 4, 0), // 16-bit, width 4
4541            set_fill_color(0xAABB_CCDD),
4542            set_scissor(0, 0, 4, 1),
4543            fill_rect(0, 0, 4, 1),
4544        ]);
4545        // px0 even -> AABB, px1 odd -> CCDD, px2 -> AABB, px3 -> CCDD.
4546        assert_eq!(
4547            bus.mem[0..8],
4548            [0xAA, 0xBB, 0xCC, 0xDD, 0xAA, 0xBB, 0xCC, 0xDD]
4549        );
4550    }
4551
4552    /// **An 8-bit FILL writes one of the four color bytes per pixel**, cycling
4553    /// every four pixels.
4554    #[test]
4555    fn fill_rectangle_8bpp_cycles_four_bytes() {
4556        let (_, bus) = run_commands(&[
4557            set_cycle_fill(),
4558            set_color_image(4, 1, 4, 0), // 8-bit (I8), width 4
4559            set_fill_color(0xAABB_CCDD),
4560            set_scissor(0, 0, 4, 1),
4561            fill_rect(0, 0, 4, 1),
4562        ]);
4563        assert_eq!(bus.mem[0..4], [0xAA, 0xBB, 0xCC, 0xDD]);
4564    }
4565
4566    /// **The scissor clips the fill, with an asymmetric lower-right** (ledger R-15,
4567    /// Angrylion-oracle-confirmed). A rectangle larger than the scissor writes only
4568    /// the scissored region: the **X** lower-right is **inclusive** of its boundary
4569    /// pixel (column 6 for `xl = 6.0`), while the **Y** lower-right is **exclusive**
4570    /// (row 3 for `yl = 3.0` stays clear). The pixel one column past the inclusive X
4571    /// edge (column 7) stays clear. (An earlier version of this test asserted an
4572    /// *exclusive* X edge — that was self-authored and never oracle-checked; the
4573    /// scissor-clip fuzz corpus corrected it.)
4574    #[test]
4575    fn fill_rectangle_is_clipped_to_the_scissor() {
4576        // 32-bit, width 8. Scissor keeps x in [2,6] (inclusive), y in [1,3) (excl).
4577        let (_, bus) = run_commands(&[
4578            set_cycle_fill(),
4579            set_color_image(0, 3, 8, 0),
4580            set_fill_color(0x1122_3344),
4581            set_scissor(2, 1, 6, 3),
4582            fill_rect(0, 0, 8, 4), // larger than the scissor on every side
4583        ]);
4584        let px = |x: u32, y: u32| {
4585            let a = (y * 8 + x) as usize * 4;
4586            &bus.mem[a..a + 4]
4587        };
4588        // Inside the scissor: written.
4589        assert_eq!(px(2, 1), [0x11, 0x22, 0x33, 0x44], "inside top-left");
4590        assert_eq!(px(5, 2), [0x11, 0x22, 0x33, 0x44], "inside");
4591        // The X lower-right boundary pixel (column 6) IS drawn (inclusive).
4592        assert_eq!(px(6, 1), [0x11, 0x22, 0x33, 0x44], "right edge inclusive");
4593        assert_eq!(px(6, 2), [0x11, 0x22, 0x33, 0x44], "right edge inclusive");
4594        // Outside each edge: clear.
4595        assert_eq!(px(1, 1), [0, 0, 0, 0], "left of scissor");
4596        assert_eq!(
4597            px(7, 1),
4598            [0, 0, 0, 0],
4599            "one column past the inclusive X edge"
4600        );
4601        assert_eq!(px(2, 0), [0, 0, 0, 0], "above scissor");
4602        assert_eq!(px(2, 3), [0, 0, 0, 0], "lower edge exclusive");
4603    }
4604
4605    /// **The rectangle's own lower-right edge is inclusive** (ledger R-3, oracle
4606    /// R). With a scissor larger than the rectangle so the scissor does not clip,
4607    /// a `Fill Rectangle` from `(1,1)` to `(3,4)` must draw the pixel *at* `(3,4)`
4608    /// — the pixel containing the lower-right coordinate — and leave the pixels one
4609    /// step past it (`(4,·)` on X, `(·,5)` on Y) clear. This is the Angrylion
4610    /// convention the fuzz corpus pinned: the pre-fix `(coord + 3) >> 2` half-open
4611    /// span dropped the boundary row and column, so reverting the fix makes the
4612    /// `(3,4)` assertion fail (mutation-checked).
4613    #[test]
4614    fn fill_rectangle_lower_right_edge_is_inclusive() {
4615        let (_, bus) = run_commands(&[
4616            set_cycle_fill(),
4617            set_color_image(0, 3, 8, 0), // 32-bit, width 8
4618            set_fill_color(0x1122_3344),
4619            set_scissor(0, 0, 8, 8), // larger than the rect: does not clip it
4620            fill_rect(1, 1, 3, 4),
4621        ]);
4622        let px = |x: u32, y: u32| {
4623            let a = (y * 8 + x) as usize * 4;
4624            &bus.mem[a..a + 4]
4625        };
4626        // The inclusive corners are drawn.
4627        assert_eq!(px(1, 1), [0x11, 0x22, 0x33, 0x44], "upper-left drawn");
4628        assert_eq!(
4629            px(3, 4),
4630            [0x11, 0x22, 0x33, 0x44],
4631            "lower-right pixel drawn"
4632        );
4633        // One step past the inclusive edge is clear.
4634        assert_eq!(px(4, 4), [0, 0, 0, 0], "one column past the right edge");
4635        assert_eq!(px(3, 5), [0, 0, 0, 0], "one row past the lower edge");
4636        // One step before the upper-left is clear.
4637        assert_eq!(px(0, 1), [0, 0, 0, 0], "one column before the left edge");
4638        assert_eq!(px(1, 0), [0, 0, 0, 0], "one row above the top edge");
4639    }
4640
4641    /// **A 4-bit color image is not a FILL target** — the real RDP crashes, so
4642    /// the fill is skipped and no memory is written.
4643    #[test]
4644    fn fill_rectangle_4bit_target_writes_nothing() {
4645        let (_, bus) = run_commands(&[
4646            set_color_image(0, 0, 4, 0), // 4-bit
4647            set_fill_color(0xFFFF_FFFF),
4648            set_scissor(0, 0, 4, 2),
4649            fill_rect(0, 0, 4, 2),
4650        ]);
4651        assert!(bus.mem[0..16].iter().all(|&b| b == 0), "no fill at 4-bit");
4652    }
4653
4654    /// **Degenerate and empty rectangles write nothing.** An inverted rectangle
4655    /// (`ulx > lrx`), an inverted scissor (`ul* > lr*`), and a rectangle disjoint
4656    /// from the scissor each yield an empty pixel span, so no pixel is written.
4657    /// The span emptiness — not the early-return, which is a redundant fast path
4658    /// over Rust's empty `for` ranges — is what these assert.
4659    #[test]
4660    fn fill_rectangle_degenerate_bounds_write_nothing() {
4661        // Inverted rectangle: upper-left past lower-right.
4662        let (_, bus) = run_commands(&[
4663            set_color_image(0, 3, 8, 0),
4664            set_fill_color(0xFFFF_FFFF),
4665            set_scissor(0, 0, 8, 4),
4666            fill_rect(6, 3, 2, 1), // ulx>lrx, uly>lry
4667        ]);
4668        assert!(bus.mem[0..128].iter().all(|&b| b == 0), "inverted rect");
4669
4670        // Inverted scissor: upper-left past lower-right.
4671        let (_, bus) = run_commands(&[
4672            set_color_image(0, 3, 8, 0),
4673            set_fill_color(0xFFFF_FFFF),
4674            set_scissor(6, 3, 2, 1), // sulx>slrx, suly>slry
4675            fill_rect(0, 0, 8, 4),
4676        ]);
4677        assert!(bus.mem[0..128].iter().all(|&b| b == 0), "inverted scissor");
4678
4679        // Rectangle entirely to the left of the scissor: empty intersection.
4680        let (_, bus) = run_commands(&[
4681            set_color_image(0, 3, 8, 0),
4682            set_fill_color(0xFFFF_FFFF),
4683            set_scissor(4, 0, 8, 4),
4684            fill_rect(0, 0, 3, 4), // rx1 = 3 <= scissor sx0 = 4
4685        ]);
4686        assert!(bus.mem[0..128].iter().all(|&b| b == 0), "disjoint rect");
4687    }
4688
4689    /// **A fill with no configured width writes nothing.** `color_image_width`
4690    /// is 0 only before `Set Color Image` (which always yields field + 1 ≥ 1);
4691    /// with a valid pixel size but zero width the guard skips the fill rather
4692    /// than smearing every row onto offset 0 with a zero stride. Reached here by
4693    /// setting the state directly, since the command stream cannot produce it.
4694    #[test]
4695    fn fill_rectangle_without_a_valid_width_writes_nothing() {
4696        let mut mem = alloc::vec![0u8; CMD_BASE as usize + 8];
4697        let (hi, lo) = fill_rect(0, 0, 4, 4);
4698        mem[CMD_BASE as usize..CMD_BASE as usize + 4].copy_from_slice(&hi.to_be_bytes());
4699        mem[CMD_BASE as usize + 4..CMD_BASE as usize + 8].copy_from_slice(&lo.to_be_bytes());
4700        let mut bus = SliceBus {
4701            mem,
4702            dp_raised: false,
4703        };
4704        let mut rdp = Rdp::new();
4705        rdp.color_image_size = 3; // valid 32-bit size, but width left at 0
4706        rdp.fill_color = 0xFFFF_FFFF;
4707        rdp.scissor_lrx = 4 << 2;
4708        rdp.scissor_lry = 4 << 2;
4709        rdp.cmd_current = CMD_BASE;
4710        rdp.cmd_end = CMD_BASE + 8;
4711        rdp.tick(&mut bus);
4712        assert!(bus.mem[0..64].iter().all(|&b| b == 0), "width 0: no write");
4713    }
4714
4715    // ---- T-32-001: texture state (TMEM, tile descriptors, state commands) ----
4716
4717    /// **TMEM is zero at power-on and unallocated.** The lazy `Option<Box<..>>`
4718    /// reads as all-zero while `None`, so a fresh RDP sees a blank TMEM without
4719    /// having paid a 4 KiB allocation.
4720    #[test]
4721    fn tmem_is_zero_and_unallocated_at_power_on() {
4722        let rdp = Rdp::new();
4723        assert!(rdp.tmem.is_none(), "no TMEM box allocated at power-on");
4724        assert_eq!(rdp.tmem_byte(0), 0);
4725        assert_eq!(rdp.tmem_byte(0x800), 0, "high half zero too");
4726        assert_eq!(rdp.tmem_byte(TMEM_SIZE - 1), 0, "last byte zero");
4727    }
4728
4729    /// **`Set Tile` (0x35) decodes every field into the addressed descriptor.**
4730    /// Each field is seeded with a distinct value so a swapped bit range shows
4731    /// up as a wrong field, not a coincidental match. Word built here from the
4732    /// N64brew field table, independent of the decoder.
4733    #[test]
4734    fn set_tile_decodes_all_fields() {
4735        // format=3 size=2 line=0x1F addr=0x100 | index=5 palette=0xA
4736        // clamp_t=1 mirror_t=0 mask_t=7 shift_t=3 | clamp_s=0 mirror_s=1
4737        // mask_s=5 shift_s=9
4738        let mut rdp = Rdp::new();
4739        rdp.set_tile(0x3570_3F00, 0x05A9_CD59);
4740        let expected = TileDescriptor {
4741            format: 3,
4742            size: 2,
4743            line: 0x1F,
4744            tmem_addr: 0x100,
4745            palette: 0xA,
4746            clamp_t: true,
4747            mirror_t: false,
4748            mask_t: 7,
4749            shift_t: 3,
4750            clamp_s: false,
4751            mirror_s: true,
4752            mask_s: 5,
4753            shift_s: 9,
4754            sl: 0,
4755            tl: 0,
4756            sh: 0,
4757            th: 0,
4758        };
4759        assert_eq!(rdp.tiles[5], expected, "descriptor 5 fully decoded");
4760        // Only the addressed descriptor is touched.
4761        for (i, t) in rdp.tiles.iter().enumerate() {
4762            if i != 5 {
4763                assert_eq!(*t, TileDescriptor::default(), "tile {i} untouched");
4764            }
4765        }
4766    }
4767
4768    /// **`Set Tile Size` (0x32) decodes SL/TL/SH/TH for the addressed
4769    /// descriptor** and leaves the format/addressing fields alone.
4770    #[test]
4771    fn set_tile_size_decodes_coords() {
4772        let mut rdp = Rdp::new();
4773        // Seed descriptor 2's addressing fields to non-zero first, so the
4774        // preservation check is real: if Set Tile Size wrongly cleared them this
4775        // catches it, whereas asserting `== 0` on a fresh descriptor could not.
4776        rdp.set_tile(0x3570_3F00, 0x02A9_CD59); // index 2: format=3 size=2 line=0x1F addr=0x100
4777        // SL=0x123 TL=0x045 | index=2 SH=0x678 TH=0x0AB
4778        rdp.set_tile_size(0x3212_3045, 0x0267_80AB);
4779        let t = rdp.tiles[2];
4780        assert_eq!(
4781            (t.sl, t.tl, t.sh, t.th),
4782            (0x123, 0x045, 0x678, 0x0AB),
4783            "coords updated"
4784        );
4785        assert_eq!(t.format, 3, "Set Tile Size preserves format");
4786        assert_eq!(t.size, 2, "preserves size");
4787        assert_eq!(t.line, 0x1F, "preserves line");
4788        assert_eq!(t.tmem_addr, 0x100, "preserves tmem_addr");
4789    }
4790
4791    /// **`Set Tile` preserves the tile-size coords** — the two commands write
4792    /// disjoint parts of the same descriptor, so a `Set Tile` after a `Set Tile
4793    /// Size` must not clear SL/TL/SH/TH (the `..self.tiles[index]` spread).
4794    #[test]
4795    fn set_tile_preserves_tile_size_coords() {
4796        let mut rdp = Rdp::new();
4797        rdp.set_tile_size(0x3212_3045, 0x0267_80AB); // seeds tiles[2] coords
4798        rdp.set_tile(0x3570_3F00, 0x02A9_CD59); // index bits -> descriptor 2
4799        let t = rdp.tiles[2];
4800        assert_eq!(t.format, 3, "Set Tile applied");
4801        assert_eq!(
4802            (t.sl, t.tl, t.sh, t.th),
4803            (0x123, 0x045, 0x678, 0x0AB),
4804            "tile-size coords survive a later Set Tile"
4805        );
4806    }
4807
4808    /// **`Set Texture Image` (0x3D) decodes format/size/width/addr.** Same field
4809    /// layout as Set Color Image; width is a field+1 pixel count.
4810    #[test]
4811    fn set_texture_image_decodes_fields() {
4812        // format=4 size=1 width_field=0x13F (-> 0x140) addr=0x654321
4813        let mut rdp = Rdp::new();
4814        let mut bus = NullBus;
4815        rdp.dispatch(OP_SET_TEXTURE_IMAGE, 0x3D88_013F, 0x0065_4321, 0, &mut bus);
4816        assert_eq!(rdp.tex_image_format, 4);
4817        assert_eq!(rdp.tex_image_size, 1);
4818        assert_eq!(rdp.tex_image_width, 0x140, "width is field + 1");
4819        assert_eq!(rdp.tex_image_addr, 0x0065_4321);
4820    }
4821
4822    /// **The dispatcher routes 0x35 and 0x32 to the right handlers.** The
4823    /// field-level tests call `set_tile` / `set_tile_size` directly; this drives
4824    /// the actual `dispatch` entry point, so a mis-wired opcode arm (0x35 sent to
4825    /// the size handler, or 0x32 to the tile handler) is caught, not only a
4826    /// decode bug. The inputs distinguish the two: `Set Tile` sets `format = 3`
4827    /// which `Set Tile Size` must leave alone, and `Set Tile Size` sets coords
4828    /// that `Set Tile` does not.
4829    #[test]
4830    fn dispatch_routes_set_tile_and_set_tile_size() {
4831        let mut rdp = Rdp::new();
4832        let mut bus = NullBus;
4833        rdp.dispatch(OP_SET_TILE, 0x3570_3F00, 0x02A9_CD59, 0, &mut bus); // index 2
4834        assert_eq!(rdp.tiles[2].format, 3, "0x35 routed to set_tile");
4835        assert_eq!(rdp.tiles[2].line, 0x1F, "and decoded its fields");
4836        rdp.dispatch(OP_SET_TILE_SIZE, 0x3212_3045, 0x0267_80AB, 0, &mut bus); // index 2
4837        assert_eq!(
4838            (rdp.tiles[2].sl, rdp.tiles[2].th),
4839            (0x123, 0x0AB),
4840            "0x32 routed to set_tile_size"
4841        );
4842        assert_eq!(
4843            rdp.tiles[2].format, 3,
4844            "set_tile_size did not clobber the tile format (distinct routing)"
4845        );
4846    }
4847
4848    // ---- T-32-002: TMEM loads (Load Tile 0x34, Load Block 0x33) ----
4849
4850    /// **`Load Tile` copies a 16-bit row and latches the tile size.** Row 0 is
4851    /// even, so no odd-row swap applies; the four texels land verbatim, and the
4852    /// descriptor's `SL/TL/SH/TH` are updated for rendering.
4853    #[test]
4854    fn load_tile_16bit_copies_a_row_and_sets_size() {
4855        let mut mem = alloc::vec![0u8; 0x200];
4856        let src = [0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88];
4857        mem[0x100..0x108].copy_from_slice(&src);
4858        let bus = SliceBus {
4859            mem,
4860            dp_raised: false,
4861        };
4862        let mut rdp = Rdp::new();
4863        rdp.tiles[0].size = 2; // 16-bit
4864        rdp.tiles[0].line = 1; // 8 bytes/row
4865        rdp.tex_image_size = 2;
4866        rdp.tex_image_width = 4;
4867        rdp.tex_image_addr = 0x100;
4868        // SL=0 TL=0 index=0 SH=3 (field 0xC) TH=0.
4869        rdp.load_tile(0x0000_0000, 0x0000_C000, &bus);
4870        for (i, &b) in src.iter().enumerate() {
4871            assert_eq!(rdp.tmem_byte(i), b, "tmem[{i}]");
4872        }
4873        assert_eq!(
4874            (rdp.tiles[0].sl, rdp.tiles[0].sh),
4875            (0, 0xC),
4876            "Load Tile latches the tile size"
4877        );
4878    }
4879
4880    /// **`Load Tile` applies the odd-row 32-bit-word swap.** Row 1 is odd, so each
4881    /// texel's TMEM byte address gains bit 2 (a `^ 4`), swapping the two 32-bit
4882    /// halves of the 64-bit word, while row 0 is unswapped.
4883    #[test]
4884    fn load_tile_swaps_odd_rows() {
4885        let mut mem = alloc::vec![0u8; 0x200];
4886        let row0 = [0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7];
4887        let row1 = [0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7];
4888        mem[0x100..0x108].copy_from_slice(&row0);
4889        mem[0x108..0x110].copy_from_slice(&row1);
4890        let bus = SliceBus {
4891            mem,
4892            dp_raised: false,
4893        };
4894        let mut rdp = Rdp::new();
4895        rdp.tiles[0].size = 2;
4896        rdp.tiles[0].line = 1;
4897        rdp.tex_image_size = 2;
4898        rdp.tex_image_width = 4;
4899        rdp.tex_image_addr = 0x100;
4900        // SL=0 TL=0 SH=3 TH=1 (field 4) -> 4x2.
4901        rdp.load_tile(0x0000_0000, 0x0000_C004, &bus);
4902        for (i, &b) in row0.iter().enumerate() {
4903            assert_eq!(rdp.tmem_byte(i), b, "row 0 verbatim [{i}]");
4904        }
4905        // Row 1 base = line*8 = 8; texel s at (8 + s*2) ^ 4.
4906        assert_eq!((rdp.tmem_byte(0xC), rdp.tmem_byte(0xD)), (0xB0, 0xB1));
4907        assert_eq!((rdp.tmem_byte(0xE), rdp.tmem_byte(0xF)), (0xB2, 0xB3));
4908        assert_eq!((rdp.tmem_byte(0x8), rdp.tmem_byte(0x9)), (0xB4, 0xB5));
4909        assert_eq!((rdp.tmem_byte(0xA), rdp.tmem_byte(0xB)), (0xB6, 0xB7));
4910    }
4911
4912    /// **`Load Tile` splits a 32-bit texel across TMEM.** R,G go to the low half
4913    /// and B,A to the high half (offset 0x800) — the documented 32-bit layout.
4914    #[test]
4915    fn load_tile_32bit_splits_rg_low_ba_high() {
4916        let mut mem = alloc::vec![0u8; 0x200];
4917        mem[0x100..0x104].copy_from_slice(&[0x11, 0x22, 0x33, 0x44]); // R G B A
4918        let bus = SliceBus {
4919            mem,
4920            dp_raised: false,
4921        };
4922        let mut rdp = Rdp::new();
4923        rdp.tiles[0].size = 3; // 32-bit RGBA
4924        rdp.tiles[0].line = 1;
4925        rdp.tex_image_size = 3;
4926        rdp.tex_image_width = 1;
4927        rdp.tex_image_addr = 0x100;
4928        rdp.load_tile(0x0000_0000, 0x0000_0000, &bus); // 1x1
4929        assert_eq!(rdp.tmem_byte(0), 0x11, "R low half");
4930        assert_eq!(rdp.tmem_byte(1), 0x22, "G low half");
4931        assert_eq!(rdp.tmem_byte(0x800), 0x33, "B high half");
4932        assert_eq!(rdp.tmem_byte(0x801), 0x44, "A high half");
4933    }
4934
4935    /// **`Load Block` streams texels and pins both sides of the 2048 limit.** A
4936    /// small 8-bit block copies verbatim (dxt 0 → one line, no swap); a 2049-texel
4937    /// load writes nothing, while exactly 2048 loads.
4938    #[test]
4939    fn load_block_streams_and_enforces_the_limit() {
4940        let mut mem = alloc::vec![0u8; 0x200];
4941        mem[0x100..0x104].copy_from_slice(&[0xDE, 0xAD, 0xBE, 0xEF]);
4942        let bus = SliceBus {
4943            mem,
4944            dp_raised: false,
4945        };
4946        let mut rdp = Rdp::new();
4947        rdp.tiles[0].size = 1; // 8-bit
4948        rdp.tex_image_size = 1;
4949        rdp.tex_image_width = 4;
4950        rdp.tex_image_addr = 0x100;
4951        // SL=0 index=0 SH=3 dxt=0.
4952        rdp.load_block(0x0000_0000, 0x0000_3000, &bus);
4953        for (i, &b) in [0xDE, 0xAD, 0xBE, 0xEF].iter().enumerate() {
4954            assert_eq!(rdp.tmem_byte(i), b, "block[{i}]");
4955        }
4956
4957        // Over the limit (count = 2049): nothing written / allocated.
4958        let mut over = Rdp::new();
4959        over.tiles[0].size = 1;
4960        over.tex_image_size = 1;
4961        over.tex_image_width = 4096;
4962        over.tex_image_addr = 0x100;
4963        over.load_block(0x0000_0000, 0x0080_0000, &bus); // SH field 2048
4964        assert!(
4965            over.tmem.is_none(),
4966            "a 2049-texel load writes nothing (over the 2048 limit)"
4967        );
4968
4969        // Exactly at the limit (count = 2048): loads.
4970        let mut edge = Rdp::new();
4971        edge.tiles[0].size = 1;
4972        edge.tex_image_size = 1;
4973        edge.tex_image_width = 4096;
4974        edge.tex_image_addr = 0x100;
4975        edge.load_block(0x0000_0000, 0x007F_F000, &bus); // SH field 2047 -> 2048 texels
4976        assert!(edge.tmem.is_some(), "exactly 2048 texels loads");
4977        assert_eq!(edge.tmem_byte(0), 0xDE, "and writes the first texel");
4978    }
4979
4980    /// **`Load Block` uses dxt to swap odd lines.** With `dxt = 0x800` the line
4981    /// index `(word * dxt) >> 11` is odd for odd 64-bit words, so the second group
4982    /// of four 16-bit texels (word 1) is swapped while the first (word 0) is not.
4983    #[test]
4984    fn load_block_dxt_swaps_odd_lines() {
4985        let mut mem = alloc::vec![0u8; 0x200];
4986        // 8 x 16-bit texels = 16 bytes: word 0 = texels 0..4, word 1 = texels 4..8.
4987        let data: [u8; 16] = [
4988            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45,
4989            0x46, 0x47,
4990        ];
4991        mem[0x100..0x110].copy_from_slice(&data);
4992        let bus = SliceBus {
4993            mem,
4994            dp_raised: false,
4995        };
4996        let mut rdp = Rdp::new();
4997        rdp.tiles[0].size = 2; // 16-bit
4998        rdp.tex_image_size = 2;
4999        rdp.tex_image_width = 8;
5000        rdp.tex_image_addr = 0x100;
5001        // SL=0 index=0 SH=7 (field 7<<... u12.0 so field=7) dxt=0x800.
5002        rdp.load_block(0x0000_0000, 0x0000_7800, &bus);
5003        // Word 0 (texels 0..4) unswapped at bytes 0..8.
5004        for (i, &b) in data[..8].iter().enumerate() {
5005            assert_eq!(rdp.tmem_byte(i), b, "word0[{i}] unswapped");
5006        }
5007        // Word 1 (texels 4..8) swapped: byte_off (8..16) ^ 4.
5008        for (i, &b) in data[8..].iter().enumerate() {
5009            assert_eq!(rdp.tmem_byte((8 + i) ^ 4), b, "word1 byte {i} swapped");
5010        }
5011    }
5012
5013    /// **An unsupported (4-bit) *tile* size writes nothing.** Isolates the
5014    /// destination-size guard: the source is a supported image, so only the
5015    /// tile-size (`dst_bpt`) guard stops the load. A silent no-op is invisible to a
5016    /// "does not panic" test, so this asserts the *effect*: TMEM is never allocated.
5017    #[test]
5018    fn load_with_unsupported_tile_size_writes_nothing() {
5019        let mut mem = alloc::vec![0u8; 0x200];
5020        mem[0x100..0x108].copy_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8]);
5021        let bus = SliceBus {
5022            mem,
5023            dp_raised: false,
5024        };
5025        // 4-bit tile (size 0), supported source: Load Tile writes nothing.
5026        let mut a = Rdp::new();
5027        a.tiles[0].size = 0;
5028        a.tex_image_size = 2;
5029        a.tex_image_width = 4;
5030        a.tex_image_addr = 0x100;
5031        a.load_tile(0x0000_0000, 0x0000_C000, &bus);
5032        assert!(a.tmem.is_none(), "4-bit tile: Load Tile writes nothing");
5033        // 4-bit tile: Load Block writes nothing.
5034        let mut b = Rdp::new();
5035        b.tiles[0].size = 0;
5036        b.tex_image_size = 1;
5037        b.tex_image_width = 4;
5038        b.tex_image_addr = 0x100;
5039        b.load_block(0x0000_0000, 0x0000_3000, &bus);
5040        assert!(b.tmem.is_none(), "4-bit tile: Load Block writes nothing");
5041    }
5042
5043    /// **An unsupported (4-bit) *source* size writes nothing — independently.** The
5044    /// tile size is supported, so only the source-size (`src_bpt`) guard stops the
5045    /// load; deleting that guard would read RDRAM at the wrong stride and allocate
5046    /// TMEM, failing this test.
5047    #[test]
5048    fn load_with_unsupported_source_size_writes_nothing() {
5049        let mut mem = alloc::vec![0u8; 0x200];
5050        mem[0x100..0x108].copy_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8]);
5051        let bus = SliceBus {
5052            mem,
5053            dp_raised: false,
5054        };
5055        let mut a = Rdp::new();
5056        a.tiles[0].size = 2; // supported destination
5057        a.tiles[0].line = 1;
5058        a.tex_image_size = 0; // 4-bit source (unsupported)
5059        a.tex_image_width = 4;
5060        a.tex_image_addr = 0x100;
5061        a.load_tile(0x0000_0000, 0x0000_C000, &bus);
5062        assert!(a.tmem.is_none(), "4-bit source: Load Tile writes nothing");
5063        let mut b = Rdp::new();
5064        b.tiles[0].size = 1; // supported destination
5065        b.tex_image_size = 0; // 4-bit source
5066        b.tex_image_width = 4;
5067        b.tex_image_addr = 0x100;
5068        b.load_block(0x0000_0000, 0x0000_3000, &bus);
5069        assert!(b.tmem.is_none(), "4-bit source: Load Block writes nothing");
5070    }
5071
5072    /// **`Load Block` rejects an inverted `SH < SL` range** (like `Load Tile`),
5073    /// with valid sizes so only the inverted-range guard prevents the load.
5074    #[test]
5075    fn load_block_rejects_inverted_range() {
5076        let mut mem = alloc::vec![0u8; 0x200];
5077        mem[0x100..0x110].copy_from_slice(&[0xFF; 16]);
5078        let bus = SliceBus {
5079            mem,
5080            dp_raised: false,
5081        };
5082        let mut rdp = Rdp::new();
5083        rdp.tiles[0].size = 1;
5084        rdp.tex_image_size = 1;
5085        rdp.tex_image_width = 8;
5086        rdp.tex_image_addr = 0x100;
5087        // SL=10 (field 0xA000) SH=2 (field 0x2000), u12.0: shi < slo.
5088        rdp.load_block(0x0000_A000, 0x0000_2000, &bus);
5089        assert!(rdp.tmem.is_none(), "shi < slo writes nothing");
5090    }
5091
5092    /// **The dispatcher routes 0x34 and 0x33 to the load handlers.** The other
5093    /// load tests call `load_tile` / `load_block` directly; this drives the actual
5094    /// `dispatch` entry so a removed or mis-wired opcode arm is caught by an
5095    /// observable TMEM write, not only a decode bug.
5096    #[test]
5097    fn dispatch_routes_load_tile_and_load_block() {
5098        let mut mem = alloc::vec![0u8; 0x200];
5099        mem[0x100..0x104].copy_from_slice(&[0x11, 0x22, 0x33, 0x44]);
5100        let mut bus = SliceBus {
5101            mem,
5102            dp_raised: false,
5103        };
5104        let mut a = Rdp::new();
5105        a.tiles[0].size = 2;
5106        a.tiles[0].line = 1;
5107        a.tex_image_size = 2;
5108        a.tex_image_width = 2;
5109        a.tex_image_addr = 0x100;
5110        a.dispatch(OP_LOAD_TILE, 0x0000_0000, 0x0000_4000, 0, &mut bus); // SH=1 -> 2 texels
5111        assert_eq!(
5112            (a.tmem_byte(0), a.tmem_byte(1)),
5113            (0x11, 0x22),
5114            "0x34 routed to load_tile"
5115        );
5116        let mut b = Rdp::new();
5117        b.tiles[0].size = 1;
5118        b.tex_image_size = 1;
5119        b.tex_image_width = 4;
5120        b.tex_image_addr = 0x100;
5121        b.dispatch(OP_LOAD_BLOCK, 0x0000_0000, 0x0000_3000, 0, &mut bus); // SH=3 -> 4 texels
5122        assert_eq!(b.tmem_byte(0), 0x11, "0x33 routed to load_block");
5123    }
5124
5125    /// **An inverted range writes nothing.** `SH < SL` (like `TH < TL`) is a
5126    /// degenerate command; without the guard the `& 0xFFF` wrap would iterate a
5127    /// large bogus width. Asserts the effect: TMEM stays unallocated.
5128    #[test]
5129    fn load_tile_rejects_inverted_range() {
5130        let mut mem = alloc::vec![0u8; 0x200];
5131        mem[0x100..0x110].copy_from_slice(&[0xFF; 16]);
5132        let bus = SliceBus {
5133            mem,
5134            dp_raised: false,
5135        };
5136        let mut rdp = Rdp::new();
5137        rdp.tiles[0].size = 2;
5138        rdp.tiles[0].line = 1;
5139        rdp.tex_image_size = 2;
5140        rdp.tex_image_width = 8;
5141        rdp.tex_image_addr = 0x100;
5142        // SL=10 (field 10<<2=0x28) SH=2 (field 2<<2=8): sh < sl.
5143        rdp.load_tile(0x0002_8000, 0x0000_8000, &bus);
5144        assert!(
5145            rdp.tmem.is_none(),
5146            "sh < sl writes nothing rather than a wrapped-width rectangle"
5147        );
5148    }
5149
5150    // ---- T-32-003: Load TLUT (0x30) and the texel-format decoders ----
5151
5152    /// Seed a tile descriptor's format/size (and optional palette) for a fetch test.
5153    fn tile_fmt(format: u8, size: u8) -> TileDescriptor {
5154        TileDescriptor {
5155            format,
5156            size,
5157            line: 1,
5158            ..TileDescriptor::default()
5159        }
5160    }
5161
5162    /// **`fetch_texel` decodes every supported format.** Each case seeds TMEM
5163    /// directly (the load path is tested separately) and asserts the RGBA8888.
5164    #[test]
5165    fn fetch_texel_decodes_each_format() {
5166        let mut rdp = Rdp::new();
5167        // RGBA16 (5551): 0xF801 = R=31, G=0, B=0, A=1 -> opaque red.
5168        rdp.tmem_write(0, 0xF8);
5169        rdp.tmem_write(1, 0x01);
5170        assert_eq!(
5171            rdp.fetch_texel(&tile_fmt(0, 2), 0, 0),
5172            [0xFF, 0, 0, 0xFF],
5173            "RGBA16"
5174        );
5175        // IA16: I=0x80 A=0xFF.
5176        assert_eq!(
5177            rdp.fetch_texel(&tile_fmt(3, 2), 0, 0),
5178            [0xF8, 0xF8, 0xF8, 0x01],
5179            "IA16 reads the same two bytes as I/A"
5180        );
5181
5182        // IA8: byte 0x5A -> I=widen4(5)=0x55, A=widen4(0xA)=0xAA.
5183        let mut r = Rdp::new();
5184        r.tmem_write(0, 0x5A);
5185        assert_eq!(
5186            r.fetch_texel(&tile_fmt(3, 1), 0, 0),
5187            [0x55, 0x55, 0x55, 0xAA],
5188            "IA8"
5189        );
5190        // I8: 0x5A in all channels.
5191        assert_eq!(
5192            r.fetch_texel(&tile_fmt(4, 1), 0, 0),
5193            [0x5A, 0x5A, 0x5A, 0x5A],
5194            "I8 alpha = intensity"
5195        );
5196
5197        // IA4: high nibble 0xE (i3=7 -> 0xFF, A = bit0 = 0).
5198        let mut n = Rdp::new();
5199        n.tmem_write(0, 0xE5);
5200        assert_eq!(
5201            n.fetch_texel(&tile_fmt(3, 0), 0, 0),
5202            [0xFF, 0xFF, 0xFF, 0],
5203            "IA4 (high nibble, even s)"
5204        );
5205        // I4: high nibble 0xE -> widen4(0xE)=0xEE in all channels.
5206        assert_eq!(
5207            n.fetch_texel(&tile_fmt(4, 0), 0, 0),
5208            [0xEE, 0xEE, 0xEE, 0xEE],
5209            "I4 alpha = intensity"
5210        );
5211        // Odd s selects the low nibble (0x5): I4 -> widen4(5)=0x55.
5212        assert_eq!(
5213            n.fetch_texel(&tile_fmt(4, 0), 1, 0),
5214            [0x55, 0x55, 0x55, 0x55],
5215            "I4 odd s -> low nibble"
5216        );
5217    }
5218
5219    /// **`fetch_texel` decodes RGBA32 from the split TMEM.** R,G come from the low
5220    /// half and B,A from the high half (0x800).
5221    #[test]
5222    fn fetch_texel_rgba32_reads_the_split() {
5223        let mut rdp = Rdp::new();
5224        rdp.tmem_write(0, 0x11); // R
5225        rdp.tmem_write(1, 0x22); // G
5226        rdp.tmem_write(0x800, 0x33); // B
5227        rdp.tmem_write(0x801, 0x44); // A
5228        assert_eq!(
5229            rdp.fetch_texel(&tile_fmt(0, 3), 0, 0),
5230            [0x11, 0x22, 0x33, 0x44]
5231        );
5232    }
5233
5234    /// **`fetch_texel` resolves CI8 and CI4 through the TLUT.** A CI index selects
5235    /// a quadrupled RGBA16 entry in the high TMEM half; CI4 folds in the tile
5236    /// palette as the high nibble.
5237    ///
5238    /// `tlut_en` must be set: the lookup is gated on `Set Other Modes` bit 47, not
5239    /// on the tile format (N64brew *…/Commands* §0x2F). This test previously left
5240    /// it clear and passed only because the gate did not exist — it was asserting
5241    /// the palette path while describing a machine that had not asked for it.
5242    #[test]
5243    fn fetch_texel_ci_through_the_tlut() {
5244        // CI8: index 5 -> TLUT entry at 0x800 + 5*8 = 0x828 = 0xF801 (red).
5245        let mut rdp = Rdp::new();
5246        rdp.other_modes.tlut_en = true;
5247        rdp.tmem_write(0, 5); // the index texel
5248        rdp.tmem_write(0x828, 0xF8);
5249        rdp.tmem_write(0x829, 0x01);
5250        assert_eq!(
5251            rdp.fetch_texel(&tile_fmt(2, 1), 0, 0),
5252            [0xFF, 0, 0, 0xFF],
5253            "CI8 -> TLUT red"
5254        );
5255
5256        // CI4: nibble 5 (high, even s) + palette 3 -> index 0x35 -> entry at
5257        // 0x800 + 0x35*8 = 0x9A8 = 0x07C1 (green).
5258        let mut c = Rdp::new();
5259        c.other_modes.tlut_en = true;
5260        c.tmem_write(0, 0x50); // high nibble 5
5261        c.tmem_write(0x9A8, 0x07);
5262        c.tmem_write(0x9A9, 0xC1);
5263        let mut tile = tile_fmt(2, 0);
5264        tile.palette = 3;
5265        assert_eq!(
5266            c.fetch_texel(&tile, 0, 0),
5267            [0, 0xFF, 0, 0xFF],
5268            "CI4 index = nibble | palette<<4"
5269        );
5270    }
5271
5272    /// **`fetch_texel` applies the odd-row swap.** Row 1 reads through the
5273    /// `^= (t & 1) << 2` twiddle, so the same TMEM contents sample differently on
5274    /// even vs odd rows — matching how the loads wrote them.
5275    #[test]
5276    fn fetch_texel_odd_row_swap() {
5277        let mut rdp = Rdp::new();
5278        // I8 tile, line 1 (8 bytes/row). Row 1 texel 0 reads byte (8) ^ 4 = 0xC.
5279        rdp.tmem_write(0xC, 0x99);
5280        assert_eq!(
5281            rdp.fetch_texel(&tile_fmt(4, 1), 0, 1),
5282            [0x99, 0x99, 0x99, 0x99],
5283            "odd row samples the swapped byte"
5284        );
5285    }
5286
5287    /// **`Load TLUT` quadruples each entry into the addressed TMEM region** and
5288    /// updates the tile size. Two 16-bit entries land as four adjacent copies each.
5289    #[test]
5290    fn load_tlut_quadruples_entries() {
5291        let mut mem = alloc::vec![0u8; 0x200];
5292        mem[0x100..0x104].copy_from_slice(&[0xF8, 0x01, 0x07, 0xC1]); // entry0, entry1
5293        let bus = SliceBus {
5294            mem,
5295            dp_raised: false,
5296        };
5297        let mut rdp = Rdp::new();
5298        rdp.tiles[0].tmem_addr = 0x100; // -> byte 0x800 (upper half)
5299        rdp.tex_image_addr = 0x100;
5300        // SL=0 SH=1 (field 1<<2=4) -> 2 entries.
5301        rdp.load_tlut(0x0000_0000, 0x0000_4000, &bus);
5302        // Entry 0 quadrupled at 0x800..0x808.
5303        for k in 0..4 {
5304            assert_eq!(rdp.tmem_byte(0x800 + k * 2), 0xF8, "entry0 copy {k} hi");
5305            assert_eq!(rdp.tmem_byte(0x801 + k * 2), 0x01, "entry0 copy {k} lo");
5306        }
5307        // Entry 1 quadrupled at 0x808..0x810.
5308        assert_eq!(rdp.tmem_byte(0x808), 0x07);
5309        assert_eq!(rdp.tmem_byte(0x809), 0xC1);
5310        assert_eq!(rdp.tmem_byte(0x80E), 0x07, "entry1 4th copy");
5311        assert_eq!(rdp.tiles[0].sh, 4, "Load TLUT latches the tile size");
5312    }
5313
5314    /// **`fetch_texel` never debug-panics on oversized coordinates.** An
5315    /// unclipped `s`/`t` must wrap into the 4 KiB TMEM space rather than
5316    /// overflowing (ADR 0004 determinism). In a debug build, non-wrapping
5317    /// arithmetic here would panic; this exercises every format at `u32::MAX`
5318    /// coordinates and asserts a deterministic (repeatable) result.
5319    #[test]
5320    fn fetch_texel_oversized_coords_wrap_deterministically() {
5321        let rdp = Rdp::new();
5322        for &(fmt, size) in &[
5323            (0, 2),
5324            (0, 3),
5325            (3, 2),
5326            (3, 1),
5327            (3, 0),
5328            (4, 1),
5329            (4, 0),
5330            (2, 1),
5331            (2, 0),
5332        ] {
5333            let mut tile = tile_fmt(fmt, size);
5334            tile.line = 0x1FF;
5335            tile.tmem_addr = 0x1FF;
5336            tile.palette = 0xF;
5337            // Must not panic, and must be deterministic for identical inputs.
5338            let a = rdp.fetch_texel(&tile, u32::MAX, u32::MAX);
5339            let b = rdp.fetch_texel(&tile, u32::MAX, u32::MAX);
5340            assert_eq!(a, b, "fmt {fmt} size {size} is deterministic");
5341        }
5342    }
5343
5344    /// **The dispatcher routes 0x30 to `load_tlut`.** Drives the FIFO dispatch
5345    /// entry so a removed/misrouted arm is caught by an observable TMEM write.
5346    #[test]
5347    fn dispatch_routes_load_tlut() {
5348        let mut mem = alloc::vec![0u8; 0x200];
5349        mem[0x100..0x102].copy_from_slice(&[0xAB, 0xCD]);
5350        let mut bus = SliceBus {
5351            mem,
5352            dp_raised: false,
5353        };
5354        let mut rdp = Rdp::new();
5355        rdp.tiles[0].tmem_addr = 0x100;
5356        rdp.tex_image_addr = 0x100;
5357        rdp.dispatch(OP_LOAD_TLUT, 0x0000_0000, 0x0000_0000, 0, &mut bus); // 1 entry
5358        assert_eq!(rdp.tmem_byte(0x800), 0xAB, "0x30 routed to load_tlut");
5359        assert_eq!(rdp.tmem_byte(0x801), 0xCD);
5360    }
5361
5362    // ---- T-32-004: coordinate wrap + copy-mode Texture Rectangle ----
5363
5364    /// **`wrap_coord` applies shift, tile-origin subtraction, mirror, and mask.**
5365    /// The coordinate is `s10.5`; a texel index of `n` is `n << 5`.
5366    #[test]
5367    fn wrap_coord_shift_subtract_mirror_mask() {
5368        // Plain: texel 3 (= 3<<5 = 96), no shift/mask/mirror, SL 0 -> 3.
5369        assert_eq!(wrap_coord(96, 0, 0, false, 0), 3);
5370        // Subtract SL: SL=1 (u10.2) -> shifts the origin left by one texel.
5371        assert_eq!(wrap_coord(96, 0, 0, false, 4), 2, "SL=1 texel subtracted");
5372        // Mask to 2 bits (mask_s=2 -> wrap every 4 texels): texel 5 -> 1.
5373        assert_eq!(wrap_coord(5 << 5, 0, 2, false, 0), 1, "masked to 2 bits");
5374        // Mirror with mask 2: texel 5 is in the odd span [4,7] -> reflects to 2.
5375        assert_eq!(wrap_coord(5 << 5, 0, 2, true, 0), 2, "mirrored");
5376        // Right shift (code 1) halves the coordinate before the texel divide.
5377        assert_eq!(wrap_coord(4 << 5, 1, 0, false, 0), 2, "shift code 1 = >>1");
5378        // Left shift (code 12 = left by 4): coord 0x10 -> 0x100 -> texel 8.
5379        assert_eq!(wrap_coord(0x10, 12, 0, false, 0), 8, "shift code 12 = <<4");
5380        // A negative coordinate stays negative through the left shift.
5381        assert_eq!(
5382            wrap_coord(-0x10, 12, 0, false, 0),
5383            -8,
5384            "left shift preserves sign"
5385        );
5386    }
5387
5388    /// **`sample_coord` applies shift, tile-origin subtraction, clamp, then mask
5389    /// (R-13).** The sampler order differs from `wrap_coord` only by the clamp,
5390    /// which sits between the subtraction and the mask. Every case is hand-derived
5391    /// from the ParaLLEl-RDP algorithm; a mutation to any step (drop the clamp,
5392    /// mask before clamp, clamp against raw `SH` vs `SH-SL`) fails a row here.
5393    #[test]
5394    fn sample_coord_shifts_subtracts_clamps_then_masks() {
5395        // s.5 coordinate: texel n = n << 5. Tile SH = 3 texels (0xC in u10.2).
5396        let sh = 3u16 << 2;
5397        // In-bounds, clamp forced by mask==0: texels pass straight through.
5398        assert_eq!(sample_coord(1 << 5, 0, 0, false, false, 0, sh), 1);
5399        assert_eq!(
5400            sample_coord(3 << 5, 0, 0, false, false, 0, sh),
5401            3,
5402            "SH itself"
5403        );
5404        // Past SH with clamp on: clamps to (SH>>2)-(SL>>2) = 3 texels.
5405        assert_eq!(
5406            sample_coord(5 << 5, 0, 0, false, true, 0, sh),
5407            3,
5408            "over-SH clamps"
5409        );
5410        // Negative coordinate with clamp on: clamps low to 0.
5411        assert_eq!(
5412            sample_coord(-(1 << 5), 0, 0, false, true, 0, sh),
5413            0,
5414            "below origin clamps to 0"
5415        );
5416        // Wrap (mask=2, no clamp): texel 5 wraps mod 4 -> 1.
5417        assert_eq!(
5418            sample_coord(5 << 5, 0, 2, false, false, 0, sh),
5419            1,
5420            "wraps mod 4"
5421        );
5422        // Mirror (mask=2): texel 5 (0b101) reflects on the alternate span -> 2.
5423        assert_eq!(sample_coord(5 << 5, 0, 2, true, false, 0, sh), 2, "mirrors");
5424        // Tile-origin subtraction: SL = 1 texel (0x4 in u10.2) shifts the index down
5425        // (texel 2 in-bounds, so this tests the subtraction, not the clamp).
5426        assert_eq!(
5427            sample_coord(2 << 5, 0, 0, false, false, 1 << 2, sh),
5428            1,
5429            "SL=1 subtracted"
5430        );
5431        // Shift code 1 = >>1 on the s.5 coord: texel 4 -> 2.
5432        assert_eq!(
5433            sample_coord(4 << 5, 1, 0, false, false, 0, sh),
5434            2,
5435            "shift >>1"
5436        );
5437        // Left-shift codes (11-15): code 12 = <<4. Mask off (mask=5) isolates the
5438        // shift. `0x10 << 4 = 0x100`, `>> 5 = 8`; matches the tested `wrap_coord`.
5439        assert_eq!(
5440            sample_coord(0x10, 12, 5, false, false, 0, sh),
5441            8,
5442            "shift code 12 = <<4"
5443        );
5444        // The left shift wraps in i16 (SIGN16), matching `tcshift_cycle`: `1024 << 5`
5445        // overflows to -32768 (not +32768), so this is NOT clamped/zeroed as a
5446        // positive would be. With mask 10 it lands at 0 — the point is that the code
5447        // reproduces the hardware wrap rather than widening to i32 first.
5448        assert_eq!(
5449            sample_coord(1024, 11, 10, false, false, 0, sh),
5450            0,
5451            "left shift wraps in 16-bit space (SIGN16)"
5452        );
5453        // CLAMP PRECEDES MASK: with both clamp on AND a non-zero mask, texel 5 past
5454        // SH=3 must clamp to 3 (then `3 & 3 = 3`), NOT wrap to `5 & 3 = 1`. Masking
5455        // first would give 1 — this row is the one that fails under that mutation.
5456        assert_eq!(
5457            sample_coord(5 << 5, 0, 2, false, true, 0, sh),
5458            3,
5459            "clamp precedes mask"
5460        );
5461    }
5462
5463    /// **`sample_axis` captures the sub-texel fraction and zeroes it on clamp
5464    /// (R-13 bilinear).** The base agrees with `sample_coord` (point); the extra
5465    /// outputs are the 5-bit `frac` the 3-point filter weights by and the `diff` to
5466    /// the neighbor texel (here always `+1`, in-range with no seam).
5467    #[test]
5468    fn sample_axis_returns_fraction_zeroed_on_clamp() {
5469        let sh = 7u16 << 2; // 8-texel tile
5470        // 1.5 texels, no clamp (mask=3): base 1, frac 0x10 (half a texel), diff +1.
5471        assert_eq!(
5472            sample_axis(0x30, 0, 3, false, false, 0, sh, false),
5473            (1, 0x10, 1)
5474        );
5475        // Whole texel: frac 0.
5476        assert_eq!(
5477            sample_axis(2 << 5, 0, 3, false, false, 0, sh, false),
5478            (2, 0, 1)
5479        );
5480        // Past SH with clamp forced (mask==0): base clamps to 7, frac zeroed, diff +1.
5481        assert_eq!(
5482            sample_axis(0xF0, 0, 0, false, false, 0, sh, false),
5483            (7, 0, 1)
5484        );
5485        // Below the origin with clamp: base 0, frac zeroed.
5486        assert_eq!(
5487            sample_axis(-0x10, 0, 0, false, false, 0, sh, false),
5488            (0, 0, 1)
5489        );
5490    }
5491
5492    /// **`mask_coupled` derives the neighbor `sdiff`/`tdiff` (R-13 seam).** `+1`
5493    /// normally; `0` at a wrap seam (duplicate); `-base` at a mirror-off period end
5494    /// (wrap the neighbor to 0); `-1` in a mirrored half. A mutation to any case
5495    /// (drop the seam, wrong mirror sign) fails a row.
5496    #[test]
5497    fn mask_coupled_derives_the_neighbor_diff() {
5498        // mask == 0: identity base, +1.
5499        assert_eq!(mask_coupled(5, 0, false, false), (5, 1));
5500        // Mirror off, mid-period (mask=2 → 4 texels): base 1, +1.
5501        assert_eq!(mask_coupled(1, 2, false, false), (1, 1));
5502        // Mirror off, period END (base == maskbits = 3): neighbor wraps to 0 (-3).
5503        assert_eq!(mask_coupled(3, 2, false, false), (3, -3));
5504        // Mirror off, T period end uses -(base & 0xff) — same as -base for base 3.
5505        assert_eq!(mask_coupled(3, 2, false, true), (3, -3));
5506        // T-only `& 0xff`: mask 10, base 0x3ff (== maskbits) → -(0x3ff & 0xff) = -0xff,
5507        // NOT -0x3ff. This is the row where the T branch differs from the S branch.
5508        assert_eq!(mask_coupled(0x3ff, 10, false, true), (0x3ff, -0xff));
5509        assert_eq!(
5510            mask_coupled(0x3ff, 10, false, false),
5511            (0x3ff, -0x3ff),
5512            "S uses -base"
5513        );
5514        // Mirror ON, forward half (base 1 → wrap bit clear, masked 1): +1.
5515        assert_eq!(mask_coupled(1, 2, true, false), (1, 1));
5516        // Mirror ON, mirrored half (base 6 → wrap bit set, inverted+masked 1): -1.
5517        assert_eq!(mask_coupled(6, 2, true, false), (1, -1));
5518        // Mirror ON seam (base 3 = top of forward half): duplicate, diff 0.
5519        assert_eq!(mask_coupled(3, 2, true, false), (3, 0));
5520        // NEGATIVE base (clamp off, coord below SL) is handled bit-correctly, as in
5521        // Angrylion: `(s >> mask) & 1` is bit `mask` of `s` for ANY sign (arithmetic
5522        // shift preserves the low bits), NOT "1 for all negatives". base -3, mask 1:
5523        // wrap = (-3 >> 1) & 1 = bit 1 of -3 = 0; masked -3 & 1 = 1; (1-0)&1 = seam → 0.
5524        assert_eq!(mask_coupled(-3, 1, true, false), (1, 0));
5525    }
5526
5527    /// **`bilinear_3point` blends the four texels by the two triangle cases
5528    /// (R-13).** Hand-computed from the ParaLLEl-RDP formula: a mutation to the
5529    /// upper/lower selector, the delta pairing, or the `+0x10 >> 5` round fails a
5530    /// row. `t0=(s,t)`, `t1=(s+1,t)`, `t2=(s,t+1)`, `t3=(s+1,t+1)`.
5531    #[test]
5532    fn bilinear_3point_blends_both_triangles() {
5533        let (t0, t1, t2, t3) = ([0, 0, 0, 0], [32, 0, 0, 0], [0, 32, 0, 0], [32, 32, 0, 0]);
5534        // Lower triangle: sfrac=0x10 (½), tfrac=0. R = 0 + (16·32 + 0 + 16)>>5 = 16.
5535        assert_eq!(
5536            bilinear_3point(t0, t1, t2, t3, 0x10, 0, false)[0],
5537            16,
5538            "lower R"
5539        );
5540        assert_eq!(
5541            bilinear_3point(t0, t1, t2, t3, 0x10, 0, false)[1],
5542            0,
5543            "lower G"
5544        );
5545        // Upper triangle: sfrac=tfrac=0x18 (¾, sum 0x30 ≥ 0x20). Weights t3 ½, t2 ¼,
5546        // t1 ¼ → R = 32·½ + 0·¼ + 32·¼ = 24; G = 32·½ + 32·¼ + 0·¼ = 24.
5547        assert_eq!(
5548            bilinear_3point(t0, t1, t2, t3, 0x18, 0x18, false)[0],
5549            24,
5550            "upper R"
5551        );
5552        assert_eq!(
5553            bilinear_3point(t0, t1, t2, t3, 0x18, 0x18, false)[1],
5554            24,
5555            "upper G"
5556        );
5557        // Zero fraction is the exact base texel (no blend).
5558        assert_eq!(
5559            bilinear_3point(t0, t1, t2, t3, 0, 0, false),
5560            t0,
5561            "frac 0 = base texel"
5562        );
5563    }
5564
5565    /// **`mid_texel` averages all four texels at the exact center (R-13).** At
5566    /// `sfrac == tfrac == 0x10` the 3-point filter picks the UPPER triangle and
5567    /// ignores `t0`; `mid_texel` instead averages all four neighbors (Angrylion
5568    /// `tex.c` `center` case). `t0` is placed off the gradient plane so the two
5569    /// disagree — a mutation that drops the center branch returns the 3-point value.
5570    #[test]
5571    fn bilinear_mid_texel_averages_the_four_texels_at_the_center() {
5572        let (t0, t1, t2, t3) = ([200, 0, 0, 0], [32, 0, 0, 0], [64, 0, 0, 0], [96, 0, 0, 0]);
5573        // 3-point UPPER ignores t0: 96 + ((16·(64−96) + 16·(32−96) + 16) >> 5) = 48.
5574        assert_eq!(
5575            bilinear_3point(t0, t1, t2, t3, 0x10, 0x10, false)[0],
5576            48,
5577            "3-point ignores t0"
5578        );
5579        // Four-texel average uses t0: 96 + (((96<<6) − (96<<7) + ((!96+200)<<6) + 0xc0) >> 8)
5580        // = 96 + (640 >> 8) = 96 + 2 = 98.
5581        assert_eq!(
5582            bilinear_3point(t0, t1, t2, t3, 0x10, 0x10, true)[0],
5583            98,
5584            "mid_texel averages all four"
5585        );
5586        // Off-center, `mid_texel` has no effect (the center condition is false).
5587        assert_eq!(
5588            bilinear_3point(t0, t1, t2, t3, 0x10, 0, true),
5589            bilinear_3point(t0, t1, t2, t3, 0x10, 0, false),
5590            "mid_texel only fires at the exact center"
5591        );
5592    }
5593
5594    /// **`lod_delta` takes the largest folded 17-bit delta (R-13).** Hand-computed
5595    /// from Angrylion `tclod_4x17_to_15`: each axis' difference is folded to its
5596    /// magnitude, the result is the max over S, T and `previous`, and bit 14 is the
5597    /// "too large" marker.
5598    #[test]
5599    fn lod_delta_folds_and_takes_the_maximum() {
5600        // S steps 48, T steps 16 -> 48 wins.
5601        assert_eq!(lod_delta(0, 48, 0, 16, 0), 48, "max over the two axes");
5602        // `previous` participates in the same max.
5603        assert_eq!(lod_delta(0, 48, 0, 16, 112), 112, "previous participates");
5604        // A NEGATIVE step folds to a magnitude (`~d & 0x1ffff`), not a signed value:
5605        // going from 48 down to 0 is a delta of 48 - 1 = 47 after the fold.
5606        assert_eq!(lod_delta(48, 0, 0, 0, 0), 47, "negative delta folds");
5607        // A delta big enough to reach bits 16:14 sets the 0x4000 saturation marker.
5608        assert!(
5609            lod_delta(0, 0x1_0000, 0, 0, 0) & 0x4000 != 0,
5610            "0x4000 marks a too-large LOD"
5611        );
5612    }
5613
5614    /// **`lod_signals` reproduces the Angrylion `lf` cases (R-13).** Hand-computed
5615    /// per branch; each row fails if the branch order, the `<< 3`, the `l_tile`
5616    /// shift, or the `max_level` "distant" test is wrong.
5617    #[test]
5618    fn lod_signals_covers_each_branch() {
5619        let frac =
5620            |clamp, lod, min, max, sharp, det| lod_signals(clamp, lod, min, max, sharp, det).frac;
5621        // The oracle vector's own case: lod 112, max_level 2 -> l_tile = log2(3) = 1,
5622        // not distant, so lf = ((112 << 3) >> 1) & 0xff = 0xc0.
5623        assert_eq!(frac(false, 112, 0, 2, false, false), 0xC0, "in-range");
5624        // Same LOD with NO mip chain (max_level 0) is "distant" -> saturates.
5625        assert_eq!(frac(false, 112, 0, 0, false, false), 0xFF, "distant");
5626        // A clamped coordinate saturates regardless of the LOD.
5627        assert_eq!(frac(true, 112, 0, 2, false, false), 0xFF, "lodclamp");
5628        // Magnifying (lod < 32) with a mip chain and no sharpen/detail -> 0.
5629        assert_eq!(frac(false, 16, 0, 2, false, false), 0, "magnify");
5630        // Magnifying with SHARPEN keeps the fraction live and sets bit 8.
5631        assert_eq!(
5632            frac(false, 16, 0, 2, true, false),
5633            (16 << 3) | 0x100,
5634            "sharpen keeps the fraction and sets 0x100"
5635        );
5636        // `min_level` is the floor the magnify branch uses instead of the LOD.
5637        assert_eq!(
5638            frac(false, 4, 8, 2, false, true),
5639            8 << 3,
5640            "detail uses min_level as the floor"
5641        );
5642        // The mip signals that drive tile selection.
5643        let s = lod_signals(false, 112, 0, 2, false, false);
5644        assert_eq!(
5645            (s.l_tile, s.magnify, s.distant),
5646            (1, false, false),
5647            "level 1"
5648        );
5649        let far = lod_signals(false, 112, 0, 1, false, false);
5650        assert!(far.distant, "l_tile >= max_level is distant");
5651        let mag = lod_signals(false, 16, 0, 2, false, false);
5652        assert!(mag.magnify && mag.l_tile == 0, "magnify pins level 0");
5653    }
5654
5655    /// **`lod_mip_tiles` picks the mip pair (R-13).** Hand-computed from the
5656    /// tile-selection tail of Angrylion `tclod_2cycle`: the pair straddles the mip
5657    /// boundary, collapses where there is nothing to blend toward, and wraps into
5658    /// the 8 descriptors.
5659    #[test]
5660    fn lod_mip_tiles_selects_the_pair() {
5661        let sig = |l_tile, magnify, distant| LodSignals {
5662            frac: 0,
5663            l_tile,
5664            magnify,
5665            distant,
5666        };
5667        // In-range level 1 from base 0 -> sample tiles 1 and 2 (the oracle vector).
5668        assert_eq!(
5669            lod_mip_tiles(0, sig(1, false, false), 2, false, false),
5670            (1, 2),
5671            "straddles the mip boundary"
5672        );
5673        // Distant pins the level to `max_level` and collapses the pair.
5674        assert_eq!(
5675            lod_mip_tiles(0, sig(1, false, true), 3, false, false),
5676            (3, 3),
5677            "distant pins to max_level and collapses"
5678        );
5679        // Plain magnification also collapses (nothing finer to blend toward)...
5680        assert_eq!(
5681            lod_mip_tiles(0, sig(0, true, false), 2, false, false),
5682            (0, 0),
5683            "magnify collapses"
5684        );
5685        // ...unless sharpen texturing is on, which keeps the second tile.
5686        assert_eq!(
5687            lod_mip_tiles(0, sig(0, true, false), 2, true, false),
5688            (0, 1),
5689            "sharpen keeps the pair while magnifying"
5690        );
5691        // Detail texturing shifts both one level finer.
5692        assert_eq!(
5693            lod_mip_tiles(0, sig(1, false, false), 2, false, true),
5694            (2, 3),
5695            "detail shifts by one"
5696        );
5697        // Detail while MAGNIFYING does not take the extra finer step, and the pair
5698        // collapses onto consecutive tiles rather than straddling.
5699        assert_eq!(
5700            lod_mip_tiles(0, sig(0, true, false), 2, false, true),
5701            (0, 1),
5702            "detail + magnify"
5703        );
5704        // Detail while DISTANT pins the level to max_level and stops straddling.
5705        assert_eq!(
5706            lod_mip_tiles(0, sig(1, false, true), 2, false, true),
5707            (3, 3),
5708            "detail + distant"
5709        );
5710        // Every index wraps into the 8 tile descriptors.
5711        assert_eq!(
5712            lod_mip_tiles(7, sig(1, false, false), 2, false, false),
5713            (0, 1),
5714            "wraps mod 8"
5715        );
5716    }
5717
5718    /// **A copy-mode Texture Rectangle round-trips a texture.** `Load Tile` loads a
5719    /// 4×2 16-bit texture into TMEM; a 1:1 `Texture Rectangle` (copy mode) blits it
5720    /// into a 16-bit color image. Because the load and the copy fetch share the
5721    /// odd-row swap, the framebuffer must equal the source texture exactly — the
5722    /// first textured picture, end to end.
5723    #[test]
5724    fn texture_rectangle_copy_round_trips_a_texture() {
5725        let mut mem = alloc::vec![0u8; 0x400];
5726        // Source 4x2 16-bit texture at 0x100 (8 distinct texels).
5727        let tex: [u16; 8] = [
5728            0x0102, 0x0304, 0x0506, 0x0708, 0x090A, 0x0B0C, 0x0D0E, 0x0F10,
5729        ];
5730        for (i, &v) in tex.iter().enumerate() {
5731            mem[0x100 + i * 2] = (v >> 8) as u8;
5732            mem[0x100 + i * 2 + 1] = (v & 0xFF) as u8;
5733        }
5734        // Texture Rectangle command word 1 at 0x308 (word 0 supplied to dispatch):
5735        // S=0 T=0 | DsDx=4.0 (0x1000) DtDy=1.0 (0x400) -> a 1:1 blit.
5736        mem[0x308..0x30C].copy_from_slice(&0u32.to_be_bytes()); // S=0, T=0
5737        mem[0x30C..0x310].copy_from_slice(&0x1000_0400u32.to_be_bytes());
5738        let mut bus = SliceBus {
5739            mem,
5740            dp_raised: false,
5741        };
5742        let mut rdp = Rdp::new();
5743        // Load the texture into TMEM (tile 0: 16-bit, line 1).
5744        rdp.tex_image_size = 2;
5745        rdp.tex_image_width = 4;
5746        rdp.tex_image_addr = 0x100;
5747        rdp.tiles[0].size = 2;
5748        rdp.tiles[0].line = 1;
5749        rdp.load_tile(0x0000_0000, 0x0000_C004, &bus); // SL0 TL0 SH3 TH1 -> 4x2
5750        // Color image: 16-bit, width 4, at 0x200.
5751        rdp.color_image_size = 2;
5752        rdp.color_image_width = 4;
5753        rdp.color_image = 0x200;
5754        // Scissor covering the 4x2 rect (a real command list always sets it).
5755        rdp.scissor_lrx = 4 << 2;
5756        rdp.scissor_lry = 2 << 2;
5757        // Texture Rectangle: word0 XL=3<<2 (0xC), YL=1<<2 (4), tile 0, XH=0, YH=0.
5758        rdp.dispatch(
5759            OP_TEXTURE_RECTANGLE,
5760            0x0000_C004,
5761            0x0000_0000,
5762            0x300,
5763            &mut bus,
5764        );
5765        // The color image equals the source texture, texel for texel.
5766        for (i, &v) in tex.iter().enumerate() {
5767            let hi = bus.mem[0x200 + i * 2];
5768            let lo = bus.mem[0x200 + i * 2 + 1];
5769            assert_eq!(
5770                u16::from_be_bytes([hi, lo]),
5771                v,
5772                "framebuffer pixel {i} matches the source texel"
5773            );
5774        }
5775    }
5776
5777    /// **`Texture Rectangle Flip` and unsupported sizes draw nothing** (R-8): the
5778    /// copy path is wired only for a 16-bit tile into a 16-bit color image.
5779    #[test]
5780    fn texture_rectangle_unsupported_configs_draw_nothing() {
5781        let mut mem = alloc::vec![0u8; 0x400];
5782        mem[0x308..0x310].copy_from_slice(&[0u8; 8]);
5783        let mut bus = SliceBus {
5784            mem,
5785            dp_raised: false,
5786        };
5787        let mut rdp = Rdp::new();
5788        rdp.tiles[0].size = 2;
5789        rdp.tiles[0].line = 1;
5790        rdp.color_image_size = 2;
5791        rdp.color_image_width = 4;
5792        rdp.color_image = 0x200;
5793        // Flip is deferred -> draws nothing.
5794        rdp.dispatch(
5795            OP_TEXTURE_RECTANGLE_FLIP,
5796            0x0000_C004,
5797            0x0000_0000,
5798            0x300,
5799            &mut bus,
5800        );
5801        assert!(
5802            bus.mem[0x200..0x210].iter().all(|&b| b == 0),
5803            "Flip draws nothing"
5804        );
5805        // 8-bit color image (unsupported) -> draws nothing.
5806        rdp.color_image_size = 1;
5807        rdp.dispatch(
5808            OP_TEXTURE_RECTANGLE,
5809            0x0000_C004,
5810            0x0000_0000,
5811            0x300,
5812            &mut bus,
5813        );
5814        assert!(
5815            bus.mem[0x200..0x210].iter().all(|&b| b == 0),
5816            "8-bit target draws nothing"
5817        );
5818    }
5819
5820    // ---- T-33-001: flat-fill triangle rasterizer ----
5821
5822    /// **`Fill Triangle` (0x08) flat-fills a right triangle.** A left-major triangle
5823    /// with a vertical left edge at x=2 and a hypotenuse widening 1 pixel per row
5824    /// fills the staircase {row0:x2, row1:x2-3, row2:x2-4, row3:x2-5} — verified
5825    /// pixel-for-pixel against a 32-bit color image, which pins the edge-walk and
5826    /// the s11.2/s11.16 fixed-point decode. This exact staircase is oracle-confirmed:
5827    /// `fill_tri_wide_16` (T-33-005) renders the same geometry byte-for-byte in Angrylion.
5828    #[test]
5829    fn fill_triangle_flat_fills_a_right_triangle() {
5830        let mut mem = alloc::vec![0u8; 0x400];
5831        // Edge words at cmd_base 0x300: word1 (L, unused) = 0; word2 (H major):
5832        // xh = 2.0 (0x2_0000), dxhdy = 0; word3 (M): xm = 2.0, dxmdy = 1.0 (0x1_0000).
5833        // The slope is dx per *pixel* row (R-14): 1.0 widens the span one pixel per row.
5834        mem[0x310..0x314].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xh
5835        mem[0x318..0x31C].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xm
5836        mem[0x31C..0x320].copy_from_slice(&0x0001_0000u32.to_be_bytes()); // dxmdy = 1.0
5837        let mut bus = SliceBus {
5838            mem,
5839            dp_raised: false,
5840        };
5841        let mut rdp = Rdp::new();
5842        rdp.color_image_size = 3; // 32-bit
5843        rdp.color_image_width = 8;
5844        rdp.color_image = 0x200;
5845        rdp.fill_color = 0xAABB_CCDD;
5846        // FILL mode, explicitly. This test is named for FILL-mode behavior
5847        // and asserts the fill register lands in the framebuffer, but it used
5848        // to leave `cycle_type` at its 1-cycle default and pass anyway --
5849        // because a flat triangle took the fill register whatever the mode
5850        // (ledger R-21's triangle half). It was testing the bug. Same fallout
5851        // R-21 recorded for the five `fill_rectangle_*` tests.
5852        rdp.other_modes.cycle_type = CYCLE_TYPE_FILL;
5853        rdp.scissor_lrx = 8 << 2;
5854        rdp.scissor_lry = 8 << 2;
5855        // word0: opcode 0x08, flip/lmajor (bit 55), yl=16, ym=16, yh=0.
5856        rdp.dispatch(0x08, 0x0880_0010, 0x0010_0000, 0x300, &mut bus);
5857
5858        let filled = |bus: &SliceBus, x: usize, row: usize| -> bool {
5859            let a = 0x200 + row * 32 + x * 4;
5860            u32::from_be_bytes([bus.mem[a], bus.mem[a + 1], bus.mem[a + 2], bus.mem[a + 3]])
5861                == 0xAABB_CCDD
5862        };
5863        let expected = [
5864            (2, 0),
5865            (2, 1),
5866            (3, 1),
5867            (2, 2),
5868            (3, 2),
5869            (4, 2),
5870            (2, 3),
5871            (3, 3),
5872            (4, 3),
5873            (5, 3),
5874        ];
5875        for row in 0..4 {
5876            for x in 0..8 {
5877                let want = expected.contains(&(x, row));
5878                assert_eq!(filled(&bus, x, row), want, "pixel ({x},{row})");
5879            }
5880        }
5881    }
5882
5883    /// **The triangle span is clipped to the scissor.** The same right triangle
5884    /// with the scissor's right edge at x=3 must lose the pixels the hypotenuse
5885    /// would otherwise reach (x=4 on row 2, x=5 on row 3) — exercising the X
5886    /// scissor boundary with an independent expectation.
5887    #[test]
5888    fn fill_triangle_is_clipped_to_the_scissor() {
5889        let mut mem = alloc::vec![0u8; 0x400];
5890        mem[0x310..0x314].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xh = 2.0
5891        mem[0x318..0x31C].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xm = 2.0
5892        mem[0x31C..0x320].copy_from_slice(&0x0001_0000u32.to_be_bytes()); // dxmdy = 1.0 (R-14)
5893        let mut bus = SliceBus {
5894            mem,
5895            dp_raised: false,
5896        };
5897        let mut rdp = Rdp::new();
5898        rdp.color_image_size = 3;
5899        rdp.color_image_width = 8;
5900        rdp.color_image = 0x200;
5901        rdp.fill_color = 0xAABB_CCDD;
5902        // FILL mode, explicitly — see the sibling test above: this asserts the
5903        // fill register reaches the framebuffer and used to pass without ever
5904        // selecting the mode that makes that true (ledger R-21's triangle half).
5905        rdp.other_modes.cycle_type = CYCLE_TYPE_FILL;
5906        rdp.scissor_lrx = 3 << 2; // right edge at x=3 -> clips x>=4
5907        rdp.scissor_lry = 8 << 2; // all rows kept
5908        rdp.dispatch(0x08, 0x0880_0010, 0x0010_0000, 0x300, &mut bus);
5909
5910        let filled = |bus: &SliceBus, x: usize, row: usize| -> bool {
5911            let a = 0x200 + row * 32 + x * 4;
5912            u32::from_be_bytes([bus.mem[a], bus.mem[a + 1], bus.mem[a + 2], bus.mem[a + 3]])
5913                == 0xAABB_CCDD
5914        };
5915        // The hypotenuse pixels past x=3 are clipped away.
5916        assert!(!filled(&bus, 4, 2), "x=4 row 2 clipped by scissor");
5917        assert!(!filled(&bus, 5, 3), "x=5 row 3 clipped by scissor");
5918        // The in-scissor part of every row is still drawn.
5919        assert!(filled(&bus, 2, 0));
5920        assert!(filled(&bus, 3, 1));
5921        assert!(filled(&bus, 3, 3), "x=3 row 3 kept (at the scissor edge)");
5922    }
5923
5924    // ---- T-33-002: the color combiner ----
5925
5926    /// **`(A − B) * C + D` matches the hand-computed RDP arithmetic.** The `+0x80`
5927    /// rounding before `>> 8`, C's plain 9-bit sign, and D added unscaled.
5928    #[test]
5929    fn combiner_equation_matches_hand_computed() {
5930        // Passthrough C: A=One (0x100), B=0, D=0 -> the result is C.
5931        assert_eq!(combine_channel(0x100, 0, 128, 0), 128, "One*C passthrough");
5932        assert_eq!(combine_channel(0x100, 0, 255, 0), 255);
5933        // Lerp: (200-100)*128/256 + 100 = 50 + 100 = 150.
5934        assert_eq!(combine_channel(200, 100, 128, 100), 150);
5935        // clamp_9bit folds an over-range result: 300 -> 300-0x80=0x94 -> sext9 stays
5936        // positive (0x94<0x100) -> +0x80 = 0x114 -> clamp to 0xFF.
5937        assert_eq!(clamp_9bit(300), 0xFF, "over-range saturates");
5938        assert_eq!(clamp_9bit(-10), 0, "negative clamps to 0");
5939    }
5940
5941    /// **`Set Combine Mode` (0x3C) decodes all 16 selects.** Each field is seeded
5942    /// distinctly so a swapped bit range surfaces as a wrong select.
5943    #[test]
5944    fn set_combine_mode_decodes_selects() {
5945        // Each field gets a distinct value in its own (non-overlapping) bit range.
5946        let mut rdp = Rdp::new();
5947        let hi = (0xA << 20) | (0x15 << 15) | (1 << 12) | (2 << 9) | (0xB << 5) | 0x1A;
5948        let lo = (3 << 28)
5949            | (0xC << 24)
5950            | (3 << 21)
5951            | (4 << 18)
5952            | (5 << 15)
5953            | (6 << 12)
5954            | (7 << 9)
5955            | (1 << 6)
5956            | (2 << 3)
5957            | 3;
5958        rdp.set_combine_mode(hi, lo);
5959        assert_eq!(rdp.combine.cyc0.rgb_a, 0xA);
5960        assert_eq!(rdp.combine.cyc0.rgb_c, 0x15);
5961        assert_eq!(rdp.combine.cyc0.rgb_b, 3);
5962        assert_eq!(rdp.combine.cyc0.rgb_d, 5);
5963        assert_eq!(rdp.combine.cyc0.a_a, 1);
5964        assert_eq!(rdp.combine.cyc0.a_c, 2);
5965        assert_eq!(rdp.combine.cyc0.a_b, 6);
5966        assert_eq!(rdp.combine.cyc0.a_d, 7);
5967        assert_eq!(rdp.combine.cyc1.rgb_a, 0xB);
5968        assert_eq!(rdp.combine.cyc1.rgb_c, 0x1A);
5969        assert_eq!(rdp.combine.cyc1.rgb_b, 0xC);
5970        assert_eq!(rdp.combine.cyc1.rgb_d, 1);
5971        assert_eq!(rdp.combine.cyc1.a_a, 3);
5972        assert_eq!(rdp.combine.cyc1.a_c, 4);
5973        assert_eq!(rdp.combine.cyc1.a_b, 2);
5974        assert_eq!(rdp.combine.cyc1.a_d, 3);
5975    }
5976
5977    /// **A one-cycle combiner passes texel0 through.** `A = One`, `B = Zero`,
5978    /// `C = Texel0`, `D = Zero` for both RGB and alpha, so the output equals the
5979    /// texel — an observable evaluation, seeded so a no-op differs.
5980    #[test]
5981    fn combine_cycle_passes_texel0_through() {
5982        let cfg = CombineCycle {
5983            rgb_a: 6, // One
5984            rgb_b: 8, // Zero (select 8+; unambiguous, unlike select 7 = K4)
5985            rgb_c: 1, // Texel0
5986            rgb_d: 7, // Zero
5987            a_a: 6,   // One
5988            a_b: 7,   // Zero
5989            a_c: 1,   // Texel0 alpha
5990            a_d: 7,   // Zero
5991        };
5992        let inp = CombinerInputs {
5993            texel0: [10, 20, 30, 40],
5994            ..CombinerInputs::default()
5995        };
5996        assert_eq!(Rdp::combine_cycle(cfg, &inp), [10, 20, 30, 40]);
5997    }
5998
5999    /// **`PRIM_LOD_FRAC` reaches the combiner as RGB mul-select 14 and alpha
6000    /// mul-select 6 (R-10).** `A = One`, `B = Zero`, `C = PrimLODFrac` for both RGB
6001    /// and alpha, so the output equals `One * prim_lod_frac >> 8 ≈ prim_lod_frac`
6002    /// (`256 * 100 + 0x80 >> 8 = 100`). Mutation guard: if either select fell back
6003    /// to the R-10 "→ 0" arm the output would be `[0, 0, 0, 0]`, so the seeded
6004    /// `100` value cannot pass vacuously.
6005    #[test]
6006    fn combine_cycle_routes_prim_lod_frac() {
6007        let cfg = CombineCycle {
6008            rgb_a: 6,  // One
6009            rgb_b: 8,  // Zero
6010            rgb_c: 14, // Prim LOD fraction
6011            rgb_d: 7,  // Zero
6012            a_a: 6,    // One
6013            a_b: 7,    // Zero
6014            a_c: 6,    // Prim LOD fraction (alpha mul-select 6)
6015            a_d: 7,    // Zero
6016        };
6017        let inp = CombinerInputs {
6018            prim_lod_frac: 100,
6019            ..CombinerInputs::default()
6020        };
6021        assert_eq!(Rdp::combine_cycle(cfg, &inp), [100, 100, 100, 100]);
6022    }
6023
6024    /// **`Set Convert` `K4`/`K5` reach the combiner as RGB sub-B select 7 and RGB
6025    /// mul-select 15 (R-10).** `A = One`, `B = K4`, `C = K5`, `D = Zero`, so RGB is
6026    /// `(One − K4) * K5 >> 8 = (256 − 64) * 64 + 0x80 >> 8 = 48`. Alpha is a fixed
6027    /// `One` (K4/K5 are RGB-only) so it does not confound the RGB check. Mutation
6028    /// guard: an unwired `K4` gives `64`, an unwired `K5` gives `0`, either one
6029    /// unwired changes the result away from `48`.
6030    #[test]
6031    fn combine_cycle_routes_convert_k4_k5() {
6032        let cfg = CombineCycle {
6033            rgb_a: 6,  // One
6034            rgb_b: 7,  // Convert K4 (sub-B)
6035            rgb_c: 15, // Convert K5 (mul)
6036            rgb_d: 7,  // Zero
6037            a_a: 7,    // Zero
6038            a_b: 7,    // Zero
6039            a_c: 7,    // Zero
6040            a_d: 6,    // One
6041        };
6042        let inp = CombinerInputs {
6043            k4: 64,
6044            k5: 64,
6045            ..CombinerInputs::default()
6046        };
6047        assert_eq!(Rdp::combine_cycle(cfg, &inp), [48, 48, 48, 255]);
6048    }
6049
6050    /// **Chroma-key center/scale reach the combiner as RGB sub-B select 6 and RGB
6051    /// mul-select 6 (`Set Key R`/`GB`, R-10).** `A = One`, `B = KeyCenter`,
6052    /// `C = KeyScale`, `D = Zero`, so RGB is `(One − center) * scale >> 8`. Per-channel
6053    /// center `[32, 64, 96]` and scale `[64, 128, 192]` give distinct results
6054    /// (`(256−32)*64 = 56`, `(256−64)*128 = 96`, `(256−96)*192 = 120`, each `+ 0x80 >> 8`),
6055    /// so a channel-swap on either input is caught. Alpha is a fixed `One` (keys are
6056    /// RGB-only). Mutation guard: an unwired `KeyCenter` (→ 0) gives `[64, 128, 192]`-ish
6057    /// and an unwired `KeyScale` (→ 0) gives `[0, 0, 0]` — either changes the result.
6058    #[test]
6059    fn combine_cycle_routes_chroma_key() {
6060        let cfg = CombineCycle {
6061            rgb_a: 6, // One
6062            rgb_b: 6, // KeyCenter (sub-B)
6063            rgb_c: 6, // KeyScale (mul)
6064            rgb_d: 7, // Zero
6065            a_a: 7,   // Zero
6066            a_b: 7,   // Zero
6067            a_c: 7,   // Zero
6068            a_d: 6,   // One
6069        };
6070        let inp = CombinerInputs {
6071            key_center: [32, 64, 96],
6072            key_scale: [64, 128, 192],
6073            ..CombinerInputs::default()
6074        };
6075        assert_eq!(Rdp::combine_cycle(cfg, &inp), [56, 96, 120, 255]);
6076    }
6077
6078    /// **`chroma_key_min` folds each channel, offsets by the width, and takes the
6079    /// minimum (R-10).** Per channel `k = SIGN(col17, 17)`; if `k > 0`, `k = -k`
6080    /// (or `-k + 0x10` when the low nibble is 8); then `k = (width << 4) + k`; the
6081    /// result is `min(kr, kg, kb)` clamped to `[0, 0xff]`. Hand-computed cases:
6082    #[test]
6083    fn chroma_key_min_folds_and_takes_the_minimum() {
6084        // Positive col17, low nibble != 8: k = (width<<4) - col17.
6085        // r: 128 - 0x10 = 112; g: 128 - 0x20 = 96; b: 128 - 0x30 = 80 -> min 80.
6086        assert_eq!(chroma_key_min([0x10, 0x20, 0x30], [8, 8, 8]), 80);
6087        // Low-nibble == 8 special fold: k = -col17 + 0x10. col17 0x18 -> -0x18+0x10 = -8;
6088        // r: 128 - 8 = 120; the wider g/b (256) leave r the minimum.
6089        assert_eq!(chroma_key_min([0x18, 0x300, 0x300], [8, 0x40, 0x40]), 120);
6090        // A large col17 drives k negative -> the minimum clamps to 0.
6091        assert_eq!(chroma_key_min([0x400, 0x10, 0x10], [8, 8, 8]), 0);
6092        // Bit 16 set: SIGN(col17, 17) is NEGATIVE (col17 - 0x20000), so the `k > 0`
6093        // fold is skipped. 0x1FFF0 -> -16; r: (8<<4) - 16 = 112, the minimum vs the
6094        // wider g/b. This exercises the signed-fold branch (a broken sign-extend that
6095        // read 0x1FFF0 as positive would fold to a large negative and clamp to 0).
6096        assert_eq!(
6097            chroma_key_min([0x1_FFF0, 0x300, 0x300], [8, 0x40, 0x40]),
6098            112
6099        );
6100    }
6101
6102    /// **Two-cycle mode chains cycle 0 into cycle 1's `Combined` input.** Cycle 0
6103    /// passes texel0 through; cycle 1 selects `Combined` for A (with C=One-ish),
6104    /// so the final output reflects cycle 0's result — not cycle 1 reading a stale
6105    /// combined value.
6106    #[test]
6107    fn combine_two_cycle_chains() {
6108        let passthrough_texel0 = CombineCycle {
6109            rgb_a: 6,
6110            rgb_b: 7,
6111            rgb_c: 1,
6112            rgb_d: 7,
6113            a_a: 6,
6114            a_b: 7,
6115            a_c: 1,
6116            a_d: 7,
6117        };
6118        // Cycle 1: pass the Combined input through (A=One, B=Zero, C=Combined, D=Zero).
6119        let passthrough_combined = CombineCycle {
6120            rgb_a: 6,
6121            rgb_b: 7,
6122            rgb_c: 0, // Combined
6123            rgb_d: 7,
6124            a_a: 6,
6125            a_b: 7,
6126            a_c: 0, // combined alpha via C? alpha C 0 = lod-frac (0); use D instead
6127            a_d: 0, // combined alpha
6128        };
6129        let mut rdp = Rdp::new();
6130        rdp.combine.cyc0 = passthrough_texel0;
6131        rdp.combine.cyc1 = passthrough_combined;
6132        let inp = CombinerInputs {
6133            texel0: [11, 22, 33, 44],
6134            ..CombinerInputs::default()
6135        };
6136        let out = rdp.combine(inp, true);
6137        // RGB is cycle0's texel0 passed through cycle1's Combined.
6138        assert_eq!(&out[0..3], &[11, 22, 33], "2-cycle chains RGB");
6139        // Alpha also chains: cycle0 passes texel0's alpha (44) to Combined, and
6140        // cycle1's D = combined-alpha (C = lod-frac = 0), so the output is 44.
6141        assert_eq!(out[3], 44, "2-cycle chains alpha");
6142    }
6143
6144    /// **Two-cycle mode swaps texel0/texel1 before cycle 1 (R-13).** Both cycles
6145    /// output TEXEL0 (`D` select). Cycle 0 sees texel0 (red); the swap then makes
6146    /// cycle 1's TEXEL0 the original texel1 (green), so the pixel is green. Without
6147    /// the swap it would stay red — the mutation this row catches.
6148    #[test]
6149    fn combine_two_cycle_swaps_texels() {
6150        let out_texel0 = CombineCycle {
6151            rgb_a: 0,
6152            rgb_b: 0,
6153            rgb_c: 0,
6154            rgb_d: 1, // Texel0 in the add slot
6155            a_a: 0,
6156            a_b: 0,
6157            a_c: 0,
6158            a_d: 1,
6159        };
6160        let mut rdp = Rdp::new();
6161        rdp.combine.cyc0 = out_texel0;
6162        rdp.combine.cyc1 = out_texel0;
6163        let inp = CombinerInputs {
6164            texel0: [255, 0, 0, 255],
6165            texel1: [0, 255, 0, 255],
6166            ..CombinerInputs::default()
6167        };
6168        assert_eq!(
6169            rdp.combine(inp, true),
6170            [0, 255, 0, 255],
6171            "cycle 1 reads the swapped texel1 (green), not texel0 (red)"
6172        );
6173    }
6174
6175    // ---- T-33-003: the blender ----
6176
6177    /// **`Set Other Modes` (0x2F) decodes every field the blender uses.** Each is
6178    /// seeded distinctly in its own bit range so a swapped range surfaces as a
6179    /// wrong select — the two blend cycles interleave `P0 P1 A0 A1 M0 M1 B0 B1`.
6180    #[test]
6181    fn set_other_modes_decodes_fields() {
6182        let mut rdp = Rdp::new();
6183        let hi = (1 << 20) // cycle_type = 1 (2-cycle)
6184            | (1 << 6); // rgb_dither_mode = 1 (bayer), command bits 39:38
6185        let lo = (2 << 30) // P0
6186            | (3 << 28)    // P1
6187            | (1 << 26)    // A0
6188            | (2 << 24)    // A1
6189            | (3 << 22)    // M0
6190            | (1 << 20)    // M1
6191            | (2 << 18)    // B0
6192            | (3 << 16)    // B1
6193            | (1 << 14)    // force_blend
6194            | (2 << 10)    // z_mode
6195            | (1 << 8)     // cvg_dest
6196            | (1 << 6)     // image_read_en
6197            | (1 << 5)     // z_update_en
6198            | (1 << 4)     // z_compare_en
6199            | (1 << 3)     // aa_enable
6200            | 1; // alpha_compare_en
6201        rdp.set_other_modes(hi, lo);
6202        let om = rdp.other_modes;
6203        assert_eq!(om.cycle_type, 1);
6204        assert_eq!(
6205            om.blend[0],
6206            BlendCycle {
6207                p: 2,
6208                a: 1,
6209                m: 3,
6210                b: 2
6211            }
6212        );
6213        assert_eq!(
6214            om.blend[1],
6215            BlendCycle {
6216                p: 3,
6217                a: 2,
6218                m: 1,
6219                b: 3
6220            }
6221        );
6222        assert!(om.force_blend);
6223        assert_eq!(om.z_mode, 2);
6224        assert_eq!(om.cvg_dest, 1);
6225        assert!(om.image_read_en);
6226        assert!(om.z_update_en);
6227        assert!(om.z_compare_en);
6228        assert!(om.aa_enable);
6229        assert!(om.alpha_compare_en);
6230        assert_eq!(om.rgb_dither_mode, 1);
6231
6232        // **`tlut_en` (bit 47) and `tlut_type` (bit 46) decode independently.**
6233        // They are ADJACENT bits, so a swapped extraction is the likely error and
6234        // would pass any test that sets both or neither. Assert each with the other
6235        // clear, in both polarities, so a swap fails and so does dropping either.
6236        let om = |hi: u32| {
6237            let mut r = Rdp::new();
6238            r.set_other_modes(hi, 0);
6239            r.other_modes
6240        };
6241        let a = om(1 << 15); // tlut_en only
6242        assert!(a.tlut_en, "bit 47 must set tlut_en");
6243        assert!(!a.tlut_type, "bit 47 must NOT set tlut_type");
6244        let b = om(1 << 14); // tlut_type only
6245        assert!(!b.tlut_en, "bit 46 must NOT set tlut_en");
6246        assert!(b.tlut_type, "bit 46 must set tlut_type");
6247    }
6248
6249    /// **The magic-matrix RGB dither matches Angrylion's `rgb_dither` cell-for-cell.**
6250    /// Verified against the `dither_tri_32` oracle: for the flat shade `0x112233`
6251    /// (low 3 bits R=1 G=2 B=3), a channel rounds up to `(c & 0xf8) + 8` exactly
6252    /// where the matrix cell is **strictly less than** that channel's low 3 bits.
6253    /// - Cell 5 (magic `(2,1)`): 5 ≥ 1,2,3 → no channel rounds → `0x112233`.
6254    /// - Cell 2 (magic `(2,2)`): 2 < 3 only → B rounds → `0x112238`.
6255    /// - Cell 0 (magic `(3,3)`): 0 < 1,2,3 → all round → `0x182838`.
6256    ///
6257    /// A mutation of the round-up predicate or the matrix contents changes at least
6258    /// one of these, so the test fails without the exact Angrylion behavior.
6259    #[test]
6260    fn rgb_dither_matches_angrylion_magic_matrix() {
6261        // The magic matrix is indexed `(y & 3) * 4 + (x & 3)`.
6262        assert_eq!(rgb_dither_value(0, 1, 2), 5); // (x=1,y=2)
6263        assert_eq!(rgb_dither_value(0, 2, 2), 2); // (x=2,y=2)
6264        assert_eq!(rgb_dither_value(0, 3, 3), 0); // (x=3,y=3)
6265
6266        let shade = [0x11, 0x22, 0x33, 0xFF];
6267        assert_eq!(apply_rgb_dither(shade, 5), [0x11, 0x22, 0x33, 0xFF]);
6268        assert_eq!(apply_rgb_dither(shade, 2), [0x11, 0x22, 0x38, 0xFF]);
6269        assert_eq!(apply_rgb_dither(shade, 0), [0x18, 0x28, 0x38, 0xFF]);
6270
6271        // Dither mode 3 ("off") returns a constant 7, which never rounds up.
6272        assert_eq!(rgb_dither_value(3, 0, 0), 7);
6273        assert_eq!(apply_rgb_dither(shade, 7), shade);
6274
6275        // The 5-bit saturation: a channel already at the top level stays put, and a
6276        // dither-invariant channel (low 3 bits zero) is never touched.
6277        assert_eq!(
6278            apply_rgb_dither([0xFF, 0xF8, 0x00, 0x00], 0),
6279            [0xFF, 0xF8, 0x00, 0x00]
6280        );
6281    }
6282
6283    /// **Alpha-compare gates on `combiner_alpha >= Set Blend Color alpha`.** With the
6284    /// gate off every alpha passes; with it on, only alphas at or above the threshold
6285    /// survive. Mutating `>=` to `>` flips the boundary case, and dropping the enable
6286    /// check makes the "gate off" case fail — so the test pins both.
6287    #[test]
6288    fn alpha_compare_gates_on_blend_color_alpha() {
6289        let mut rdp = Rdp::new();
6290        rdp.blend_color = 0x0000_0080; // threshold alpha = 0x80
6291
6292        // Gate off: everything passes regardless of the threshold.
6293        rdp.other_modes.alpha_compare_en = false;
6294        assert!(rdp.alpha_compare_passes(0x00));
6295        assert!(rdp.alpha_compare_passes(0x7F));
6296
6297        // Gate on: `alpha >= 0x80` passes, below fails, and the boundary is inclusive.
6298        rdp.other_modes.alpha_compare_en = true;
6299        assert!(!rdp.alpha_compare_passes(0x00));
6300        assert!(!rdp.alpha_compare_passes(0x7F));
6301        assert!(rdp.alpha_compare_passes(0x80));
6302        assert!(rdp.alpha_compare_passes(0xFF));
6303    }
6304
6305    /// **Alpha-compare suppresses the Z-write on the depth path.** A z-suffixed
6306    /// shaded triangle with alpha-compare on and `z_compare` off (depth always
6307    /// passes, so alpha is the only gate). With a flat shade alpha **below** the
6308    /// threshold every pixel is rejected, so the Z buffer stays at its cleared value;
6309    /// **above** the threshold the pixels draw and write Z. A mutant that drops the
6310    /// alpha-compare `continue` in `depth_span` (Z-writing rejected pixels) fails the
6311    /// first assertion — the check the color-only `alpha_compare_z_16` vector cannot
6312    /// make (it reads only the color framebuffer).
6313    #[test]
6314    fn alpha_compare_suppresses_zwrite_on_depth_path() {
6315        let render = |shade_alpha: u32| -> u16 {
6316            let mut bus = ZBufBus {
6317                mem: alloc::vec![0u8; 0x1000],
6318                hidden: alloc::vec![0u8; 0x800],
6319            };
6320            let mut rdp = Rdp::new();
6321            rdp.color_image = 0x200;
6322            rdp.color_image_size = 2; // 16-bit
6323            rdp.color_image_width = 8;
6324            rdp.z_image = 0x400;
6325            rdp.blend_color = 0x0000_0080; // alpha-compare threshold 0x80
6326            rdp.scissor_lrx = 8 << 2;
6327            rdp.scissor_lry = 8 << 2;
6328            rdp.other_modes.alpha_compare_en = true;
6329            rdp.other_modes.z_update_en = true;
6330            rdp.other_modes.z_compare_en = false; // depth always passes; alpha is the only gate
6331            // Shade-passthrough combiner: cyc1 rgb_d = shade (4), a_d = shade alpha (4).
6332            rdp.combine.cyc1 = CombineCycle {
6333                rgb_a: 0,
6334                rgb_b: 0,
6335                rgb_c: 0,
6336                rgb_d: 4,
6337                a_a: 0,
6338                a_b: 0,
6339                a_c: 0,
6340                a_d: 4,
6341            };
6342            let base = 0x600usize;
6343            bus.mem[base + 0x10..base + 0x14].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xh
6344            bus.mem[base + 0x18..base + 0x1C].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xm
6345            bus.mem[base + 0x1C..base + 0x20].copy_from_slice(&0x0001_0000u32.to_be_bytes()); // dxmdy = 1.0
6346            // Shade int-base (base + 0x20/0x24): R=0xFF, G=B=0, A = shade_alpha.
6347            bus.mem[base + 0x20..base + 0x24].copy_from_slice(&(0xFFu32 << 16).to_be_bytes());
6348            bus.mem[base + 0x24..base + 0x28].copy_from_slice(&(shade_alpha & 0xFF).to_be_bytes());
6349            // z-suffix after the 4-word base + 8-word shade block = base + 0x60.
6350            bus.mem[base + 0x60..base + 0x64].copy_from_slice(&0x0800_0000u32.to_be_bytes());
6351            rdp.dispatch(0x0D, 0x0D80_0010, 0x0010_0000, base as u32, &mut bus);
6352            rdp.zbuffer_read(2, 1, &bus).0
6353        };
6354        assert_eq!(render(0x40), 0, "alpha-rejected pixel does not write Z");
6355        assert_ne!(render(0xC0), 0, "alpha-passing pixel writes Z");
6356    }
6357
6358    /// **`Set Blend Color` / `Set Fog Color` latch their RGBA8888 registers.**
6359    #[test]
6360    fn set_blend_and_fog_color_latch() {
6361        let mut bus = SliceBus {
6362            mem: alloc::vec![0u8; 0x100],
6363            dp_raised: false,
6364        };
6365        let mut rdp = Rdp::new();
6366        rdp.dispatch(OP_SET_BLEND_COLOR, 0, 0x1122_3344, 0, &mut bus);
6367        rdp.dispatch(OP_SET_FOG_COLOR, 0, 0x5566_7788, 0, &mut bus);
6368        assert_eq!(rdp.blend_color, 0x1122_3344);
6369        assert_eq!(rdp.fog_color, 0x5566_7788);
6370    }
6371
6372    /// **`(P * a0 + M * (a1 + 1)) >> 5` matches the hand-computed no-divide blend.**
6373    /// `P = pixel`, `M = memory`, `A = pixel-alpha` (128 → a0 = 16), `B = one`
6374    /// (0xFF → a1 = 31): ch0 = 100·16 + 10·32 = 1920 → 60; ch1 → 95; ch2 → 130.
6375    #[test]
6376    fn blend_cycle_matches_hand_computed() {
6377        let cycle = BlendCycle {
6378            p: 0,
6379            a: 0,
6380            m: 1,
6381            b: 2,
6382        };
6383        let inp = BlendInputs {
6384            pixel: [100, 150, 200, 128],
6385            memory: [10, 20, 30, 40],
6386            ..BlendInputs::default()
6387        };
6388        assert_eq!(Rdp::blend_cycle(cycle, &inp), [60, 95, 130]);
6389    }
6390
6391    /// **Two-cycle mode chains cycle 0's RGB into cycle 1's pixel input.** Cycle 0
6392    /// blends pixel⊕fog → [93,93,93]; cycle 1 re-blends that against fog with
6393    /// `B = zero` → [90,90,90], which differs from cycle 0 alone — proving the
6394    /// chain feeds forward rather than re-reading the original pixel.
6395    #[test]
6396    fn blend_two_cycle_chains() {
6397        let mut rdp = Rdp::new();
6398        rdp.other_modes.cycle_type = 1;
6399        rdp.other_modes.blend[0] = BlendCycle {
6400            p: 0,
6401            a: 0,
6402            m: 3,
6403            b: 2,
6404        };
6405        rdp.other_modes.blend[1] = BlendCycle {
6406            p: 0,
6407            a: 0,
6408            m: 3,
6409            b: 3,
6410        };
6411        let inp = BlendInputs {
6412            pixel: [80, 80, 80, 0xFF],
6413            fog: [16, 16, 16, 0xFF],
6414            ..BlendInputs::default()
6415        };
6416        // Cycle 0 alone would give [93,93,93]; the chained result is [90,90,90].
6417        assert_eq!(
6418            Rdp::blend_cycle(rdp.other_modes.blend[0], &inp),
6419            [93, 93, 93]
6420        );
6421        assert_eq!(rdp.blend(inp), [90, 90, 90], "2-cycle chains forward");
6422    }
6423
6424    /// **The `B = 1 − A` select complements the *resolved* `A`, not pixel alpha.**
6425    /// `A` selects fog alpha (0xFF → a0 = 31) and `B` selects `1 − A`, so
6426    /// `a1 = (~0xFF) >> 3 = 0` and `a1 + 1 = 1`: `100·31 + 10·1 = 3110 → 97`.
6427    /// Pixel alpha is 0x00 here, so the old `!pixel_alpha` bug would use
6428    /// `a1 = (~0x00) >> 3 = 31` → `100·31 + 10·32 = 3420 → 106`; asserting 97
6429    /// fails against that regression (ParaLLEl-RDP `blender.h:106`, `~a0`).
6430    #[test]
6431    fn blend_inv_alpha_complements_selected_a_not_pixel() {
6432        let cycle = BlendCycle {
6433            p: 0,
6434            a: 1,
6435            m: 1,
6436            b: 0,
6437        };
6438        let inp = BlendInputs {
6439            pixel: [100, 100, 100, 0x00],
6440            memory: [10, 10, 10, 40],
6441            fog: [0, 0, 0, 0xFF],
6442            ..BlendInputs::default()
6443        };
6444        assert_eq!(Rdp::blend_cycle(cycle, &inp), [97, 97, 97]);
6445    }
6446
6447    // ---- T-33-004: the Z-buffer machinery ----
6448
6449    /// **The Z codec matches the ParaLLEl-RDP `z_encode.h` arithmetic.** Boundary
6450    /// values are hand-computed; `z_compress ∘ z_decompress` round-trips canonical
6451    /// stored values; `dz` is `1 << n` with an integer-`log2` inverse.
6452    #[test]
6453    fn z_codec_matches_hand_computed() {
6454        // decompress: 0 → 0; max 14-bit (0x3FFF) → max 18-bit (0x3FFFF); a mid value.
6455        assert_eq!(z_decompress(0), 0);
6456        assert_eq!(z_decompress(0x3FFF), 0x3_FFFF);
6457        assert_eq!(z_decompress(0x3000), 0x3_F000); // exp 6, man 0
6458        // round-trip canonical stored values.
6459        for stored in [0u16, 0x2000, 0x3FFF] {
6460            assert_eq!(
6461                z_compress(z_decompress(stored)),
6462                stored,
6463                "round-trip {stored:#x}"
6464            );
6465        }
6466        // dz: 1<<n and its integer-log2 inverse (0 maps to 0 via find_msb == -1).
6467        assert_eq!(dz_decompress(15), 0x8000);
6468        assert_eq!(dz_decompress(0), 1);
6469        assert_eq!(dz_compress(0x8000), 15);
6470        assert_eq!(dz_compress(1), 0);
6471        assert_eq!(dz_compress(0), 0);
6472        assert_eq!(combine_dz(0x180), 0x100, "largest POT <= 384 is 256");
6473        assert_eq!(combine_dz(0), 0);
6474    }
6475
6476    /// **`Set Primitive Depth` (0x2E) and `Set Depth Image` (0x3E) latch.** z in
6477    /// `lo[31:16]`, dz in `lo[15:0]`; the depth-image base masks to 24 bits.
6478    #[test]
6479    fn set_prim_depth_and_depth_image_latch() {
6480        let mut bus = SliceBus {
6481            mem: alloc::vec![0u8; 0x100],
6482            dp_raised: false,
6483        };
6484        let mut rdp = Rdp::new();
6485        rdp.dispatch(OP_SET_PRIM_DEPTH, 0, (0x1234 << 16) | 0x0080, 0, &mut bus);
6486        assert_eq!(rdp.prim_z, 0x1234);
6487        assert_eq!(rdp.prim_dz, 0x0080);
6488        rdp.dispatch(OP_SET_DEPTH_IMAGE, 0, 0xAB00_1240, 0, &mut bus);
6489        assert_eq!(rdp.z_image, 0x0000_1240, "24-bit masked base");
6490    }
6491
6492    /// Build [`DepthInputs`] for a memory pixel at stored depth `0x3000`
6493    /// (`memory_z == 0x3F000`), `dz == 0`, precision-factor 6 (so no `dz`
6494    /// adjustment), with the given mode. `aa`/`force_blend`/`coverage` are off so
6495    /// the depth decision is pure less-than.
6496    fn depth_inputs(z_mode: u8) -> DepthInputs {
6497        DepthInputs {
6498            current_depth: 0x3000,
6499            current_dz: 0,
6500            current_coverage: 0,
6501            z_compare: true,
6502            z_mode,
6503            force_blend: false,
6504            aa_enable: false,
6505        }
6506    }
6507
6508    /// **Opaque Z mode: the nearer pixel passes, the farther pixel is rejected.**
6509    /// The observable occluding-vs-occluded pair against a memory depth of
6510    /// `0x3F000`: an in-front pixel (`z = 0x30000`) writes, a behind one
6511    /// (`z = 0x3FF00`) does not.
6512    #[test]
6513    fn depth_test_opaque_occludes() {
6514        let inp = depth_inputs(0);
6515        assert!(
6516            Rdp::depth_test(0x30000, 0, 0, 1, &inp).depth_pass,
6517            "nearer pixel passes"
6518        );
6519        assert!(
6520            !Rdp::depth_test(0x3FF00, 0, 0, 1, &inp).depth_pass,
6521            "farther pixel rejected"
6522        );
6523    }
6524
6525    /// **Transparent Z mode passes strictly-in-front pixels only.** Same pair:
6526    /// front passes, behind fails (no coverage/decal subtlety).
6527    #[test]
6528    fn depth_test_transparent_passes_front() {
6529        let inp = depth_inputs(2);
6530        assert!(Rdp::depth_test(0x30000, 0, 0, 1, &inp).depth_pass);
6531        assert!(!Rdp::depth_test(0x3FF00, 0, 0, 1, &inp).depth_pass);
6532    }
6533
6534    /// **Decal Z mode passes only coplanar pixels.** A pixel at the memory depth
6535    /// (`z = 0x3F000`) passes; an in-front pixel (`z = 0x30000`) — which opaque
6536    /// mode would accept — is rejected, distinguishing decal from opaque.
6537    #[test]
6538    fn depth_test_decal_passes_coplanar_only() {
6539        let inp = depth_inputs(3);
6540        assert!(
6541            Rdp::depth_test(0x3_F000, 0, 0, 1, &inp).depth_pass,
6542            "coplanar passes"
6543        );
6544        assert!(
6545            !Rdp::depth_test(0x30000, 0, 0, 1, &inp).depth_pass,
6546            "in-front (non-coplanar) rejected"
6547        );
6548    }
6549
6550    /// **`z_compare` off: every pixel passes**, regardless of stored depth — the
6551    /// depth test is bypassed and only coverage/blend state is derived.
6552    #[test]
6553    fn depth_test_disabled_always_passes() {
6554        let mut inp = depth_inputs(0);
6555        inp.z_compare = false;
6556        assert!(Rdp::depth_test(0x3FF00, 0, 0, 1, &inp).depth_pass);
6557        assert!(Rdp::depth_test(0x00000, 0, 0, 1, &inp).depth_pass);
6558    }
6559
6560    /// **Interpenetrating Z mode reduces coverage at an intersect.** With the
6561    /// `front && farther && overflow` intersect condition met (a near pixel just
6562    /// short of `memory_z = 0x3F000`, coverage overflowing), the pixel passes and
6563    /// its coverage is scaled: `cvg_coeff = (0x3F000 − 0x3EFFC) & 0xf = 4`, so
6564    /// `coverage_count = min((4·4) >> 3, 8) = 2` — hand-computed from `depth_test.h`.
6565    #[test]
6566    fn depth_test_interpenetrating_reduces_coverage() {
6567        let inp = DepthInputs {
6568            current_depth: 0x3000, // memory_z = 0x3F000, precision-factor 6
6569            current_dz: 0,
6570            current_coverage: 4, // + coverage_count 4 => overflow (>= 8)
6571            z_compare: true,
6572            z_mode: 1,
6573            force_blend: false,
6574            aa_enable: false,
6575        };
6576        let r = Rdp::depth_test(0x3_EFFC, 0, 0, 4, &inp);
6577        assert!(r.depth_pass, "intersect passes");
6578        assert_eq!(r.coverage_count, 2, "coverage scaled down at the intersect");
6579    }
6580
6581    /// **The `precision_factor < 3` coplanar path forces a pass.** A memory pixel
6582    /// with a low exponent (`precision-factor 2`) and `current_dz == 15`
6583    /// (`memory_dz == 0x8000`) is treated as coplanar, so even a pixel *behind*
6584    /// `memory_z` passes opaque mode — exercising the stored-`dz` adjustment that
6585    /// the plain occluding pairs (precision-factor 6) deliberately avoid.
6586    #[test]
6587    fn depth_test_precision_factor_coplanar_forces_pass() {
6588        let inp = DepthInputs {
6589            current_depth: 0x1000, // memory_z = 0x30000, precision-factor 2 (< 3)
6590            current_dz: 15,        // memory_dz = 0x8000 -> coplanar branch
6591            current_coverage: 0,
6592            z_compare: true,
6593            z_mode: 0,
6594            force_blend: false,
6595            aa_enable: false,
6596        };
6597        // 0x3FF00 is behind memory_z (0x30000); without the coplanar path it would
6598        // fail opaque mode, but coplanar makes `nearer` unconditionally true.
6599        assert!(Rdp::depth_test(0x3_FF00, 0, 0, 1, &inp).depth_pass);
6600    }
6601
6602    /// **Out-of-domain inputs are sanitized, not panicked on.** Every argument here
6603    /// is outside its hardware domain — a `current_depth`/`current_dz` with junk in
6604    /// the upper bits, a negative `z`, a huge `dz`, an out-of-4-bit `dz_compressed`.
6605    /// The boundary clamps/masks bound them all, so the shifts (`1 << dz`,
6606    /// `combine_dz`, `combined_dz << 3`) and the `z ± combined_dz` sums stay in
6607    /// range. Without the sanitization this panics in a debug build.
6608    #[test]
6609    fn depth_test_out_of_domain_inputs_do_not_panic() {
6610        let inp = DepthInputs {
6611            current_depth: 0xFFFF, // masked to 14 bits
6612            current_dz: 200,       // masked to 4 bits (→ 8)
6613            current_coverage: 0,
6614            z_compare: true,
6615            z_mode: 0,
6616            force_blend: false,
6617            aa_enable: false,
6618        };
6619        // Negative z (clamped to 0), a large dz (clamped to the 18-bit range, so
6620        // combine_dz << 3 stays bounded), and dz_compressed 20 (clamped to 0xf).
6621        let r = Rdp::depth_test(-5, 0x7FFF_FFFF, 20, 1, &inp);
6622        assert!(
6623            r.blend_shift[0] <= 4 && r.blend_shift[1] <= 4,
6624            "invariant holds"
6625        );
6626    }
6627
6628    /// A test bus that models the RDRAM hidden bits (one 2-bit value per 16-bit
6629    /// halfword), so the full 4-bit `dz` round-trip can be exercised.
6630    struct ZBufBus {
6631        mem: Vec<u8>,
6632        hidden: Vec<u8>,
6633    }
6634    impl RdramBus for ZBufBus {
6635        fn rdram_read(&self, addr: u32) -> u8 {
6636            self.mem.get(addr as usize).copied().unwrap_or(0)
6637        }
6638        fn rdram_write(&mut self, addr: u32, val: u8) {
6639            if let Some(b) = self.mem.get_mut(addr as usize) {
6640                *b = val;
6641            }
6642        }
6643        fn rdram_read_hidden(&self, addr: u32) -> u8 {
6644            self.hidden.get((addr >> 1) as usize).copied().unwrap_or(0) & 0x3
6645        }
6646        fn rdram_write_hidden(&mut self, addr: u32, val: u8) {
6647            if let Some(b) = self.hidden.get_mut((addr >> 1) as usize) {
6648                *b = val & 0x3;
6649            }
6650        }
6651    }
6652    impl VideoBus for ZBufBus {
6653        fn raise_dp_interrupt(&mut self) {}
6654    }
6655
6656    /// **The Z buffer round-trips the compressed z and the full 4-bit dz.** The dz
6657    /// splits across the halfword's low 2 bits and the hidden bits, so a value like
6658    /// `0xB` (`0b1011`) only survives if the hidden path carries the low 2 bits —
6659    /// without it, `read` would return `0b1000` (`8`). `0x30000` is a canonical
6660    /// depth that `z_compress`/`z_decompress` reproduce exactly.
6661    #[test]
6662    fn zbuffer_round_trips_z_and_dz() {
6663        let mut bus = ZBufBus {
6664            mem: alloc::vec![0u8; 0x1000],
6665            hidden: alloc::vec![0u8; 0x800],
6666        };
6667        let mut rdp = Rdp::new();
6668        rdp.z_image = 0x200;
6669        rdp.color_image_width = 8;
6670        rdp.zbuffer_write(3, 2, 0x30000, 0xB, &mut bus);
6671        let (cz, dz) = rdp.zbuffer_read(3, 2, &bus);
6672        assert_eq!(cz, z_compress(0x30000), "compressed z stored and loaded");
6673        assert_eq!(
6674            z_decompress(cz),
6675            0x30000,
6676            "canonical depth decompresses exactly"
6677        );
6678        assert_eq!(dz, 0xB, "full 4-bit dz survives via halfword + hidden bits");
6679        // A different pixel is untouched (independent entry).
6680        assert_eq!(rdp.zbuffer_read(4, 2, &bus), (0, 0));
6681    }
6682
6683    /// **`interpolate_z` matches the hand-computed ParaLLEl-RDP snap.** A flat depth
6684    /// (`z_base = 0x0800_0000`, no gradient) snaps to `0x4000`; a pure horizontal
6685    /// gradient (`dzdx = 1.0`) advances `4 · 0x1_0000` over four pixels, which the
6686    /// `>> 10 << 2 >> 5` snap folds to `0x20`.
6687    #[test]
6688    fn interpolate_z_matches_hand_computed() {
6689        assert_eq!(interpolate_z(0x0800_0000, 0, 0, 0, 0, 0, 0), 0x4000);
6690        assert_eq!(interpolate_z(0, 0x0001_0000, 0, 0, 0, 0, 4), 0x20);
6691        // A negative (below-near-plane) depth clamps to 0.
6692        assert_eq!(interpolate_z(-0x0001_0000, 0, 0, 0, 0, 0, 0), 0);
6693    }
6694
6695    /// **A Z-buffered triangle occludes a farther one and yields to a nearer one.**
6696    /// The first-ever depth-tested rendering: three overlapping right triangles into
6697    /// a Z buffer pre-cleared to the far plane, with flat depths `z_px` 0x4000 (near),
6698    /// 0x8000 (far), 0x2000 (nearer). The near draws (vs the cleared buffer), the far
6699    /// is **rejected** (stays the near color), and the nearer **overwrites** — so the
6700    /// test discriminates both the accept and reject paths of `depth_test`.
6701    #[test]
6702    fn depth_tested_triangle_occludes_farther_and_yields_to_nearer() {
6703        let mut bus = ZBufBus {
6704            mem: alloc::vec![0u8; 0x1000],
6705            hidden: alloc::vec![0u8; 0x800],
6706        };
6707        // Pre-clear the Z buffer to the far plane (compressed 0x3FFF → z 0x3FFFF).
6708        for b in &mut bus.mem[0x400..0x500] {
6709            *b = 0xFF;
6710        }
6711        let mut rdp = Rdp::new();
6712        rdp.color_image = 0x200;
6713        rdp.color_image_size = 3; // 32-bit
6714        rdp.color_image_width = 8;
6715        rdp.z_image = 0x400;
6716        rdp.scissor_lrx = 8 << 2;
6717        rdp.scissor_lry = 8 << 2;
6718        rdp.other_modes.z_compare_en = true;
6719        rdp.other_modes.z_update_en = true;
6720        rdp.other_modes.z_mode = 0; // opaque
6721
6722        // Draw the same staircase triangle (as the flat-fill test) at each cmd_base,
6723        // now as the Z-buffered variant (opcode 0x09), with a flat z-suffix (z_base
6724        // only; dzdx/dzde/dzdy = 0). The command word matches the flat-fill test with
6725        // the z-flag bit (56) set → hi 0x0980_0010.
6726        let draw = |bus: &mut ZBufBus, rdp: &mut Rdp, base: usize, z_base: u32, color: u32| {
6727            bus.mem[base + 0x10..base + 0x14].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xh
6728            bus.mem[base + 0x18..base + 0x1C].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xm
6729            bus.mem[base + 0x1C..base + 0x20].copy_from_slice(&0x0000_4000u32.to_be_bytes()); // dxmdy
6730            bus.mem[base + 0x20..base + 0x24].copy_from_slice(&z_base.to_be_bytes()); // z_base
6731            rdp.fill_color = color;
6732            rdp.dispatch(0x09, 0x0980_0010, 0x0010_0000, base as u32, bus);
6733        };
6734        let px = |bus: &ZBufBus, x: usize, row: usize| -> u32 {
6735            let a = 0x200 + row * 32 + x * 4;
6736            u32::from_be_bytes([bus.mem[a], bus.mem[a + 1], bus.mem[a + 2], bus.mem[a + 3]])
6737        };
6738
6739        // 1-cycle sub-pixel coverage excludes the degenerate top vertex (2,0); check the
6740        // drawn pixel (2,1). The no-shade fill path writes the FILL color verbatim (no
6741        // coverage-alpha), so the full 32-bit value is asserted.
6742        draw(&mut bus, &mut rdp, 0x600, 0x0800_0000, 0x1111_1111); // near  (z_px 0x4000)
6743        assert_eq!(px(&bus, 2, 1), 0x1111_1111, "near draws vs cleared buffer");
6744        draw(&mut bus, &mut rdp, 0x700, 0x1000_0000, 0x2222_2222); // far   (z_px 0x8000)
6745        assert_eq!(
6746            px(&bus, 2, 1),
6747            0x1111_1111,
6748            "far is occluded (depth rejects)"
6749        );
6750        assert_eq!(px(&bus, 2, 3), 0x1111_1111);
6751        draw(&mut bus, &mut rdp, 0x800, 0x0400_0000, 0x3333_3333); // nearer(z_px 0x2000)
6752        assert_eq!(
6753            px(&bus, 2, 1),
6754            0x3333_3333,
6755            "nearer overwrites (depth accepts)"
6756        );
6757    }
6758
6759    /// **`decode_triangle_z` does not panic on an `i32::MIN` gradient.** The z-suffix
6760    /// is unvalidated RDRAM; a `dzdx`/`dzde` of `0x8000_0000` would overflow `.abs()`.
6761    /// `saturating_abs` keeps it total.
6762    #[test]
6763    fn decode_triangle_z_survives_i32_min_gradient() {
6764        let mut bus = ZBufBus {
6765            mem: alloc::vec![0u8; 0x100],
6766            hidden: alloc::vec![0u8; 0x80],
6767        };
6768        // z-flag set (bit 24), no shade/tex -> z-suffix at cmd_base + 0x20; put
6769        // i32::MIN at dzdx (za + 4 = 0x24).
6770        bus.mem[0x24..0x28].copy_from_slice(&0x8000_0000u32.to_be_bytes());
6771        assert!(Rdp::decode_triangle_z(1 << 24, 0, &bus).is_some());
6772    }
6773
6774    // ---- T-33-004 PR-B 2b: shade interpolation ----
6775
6776    /// **`decode_shade` assembles the RGBA base and `interpolate_shade` yields the
6777    /// byte colors.** The shade block's int-base word packs `R.i`/`G.i` in the hi
6778    /// u32 (bits 56:48 / 40:32) and `B.i`/`A.i` in the lo u32; a flat base (no
6779    /// deltas) of `(100, 150, 200, 255)` interpolates to exactly those bytes.
6780    #[test]
6781    fn decode_shade_assembles_base_and_interpolates() {
6782        let mut bus = ZBufBus {
6783            mem: alloc::vec![0u8; 0x100],
6784            hidden: alloc::vec![0u8; 0x80],
6785        };
6786        // Shade block at cmd_base(0) + 4 words = 0x20. Word0 int-base:
6787        // hi = (R.i << 16) | G.i, lo = (B.i << 16) | A.i. Frac/deltas left 0.
6788        bus.mem[0x20..0x24].copy_from_slice(&((0x64u32 << 16) | 0x96).to_be_bytes()); // R=100 G=150
6789        bus.mem[0x24..0x28].copy_from_slice(&((0xC8u32 << 16) | 0xFF).to_be_bytes()); // B=200 A=255
6790        let shade = Rdp::decode_shade(1 << 26, 0, &bus).expect("shade block present");
6791        assert_eq!(shade.base, [0x64_0000, 0x96_0000, 0xC8_0000, 0xFF_0000]);
6792        assert_eq!(shade.dx, [0; 4]);
6793        assert_eq!(shade.de, [0; 4]);
6794        assert_eq!(
6795            interpolate_shade(&shade.base, &shade.dx, &shade.de, 0, 0, 0, 0),
6796            [100, 150, 200, 255],
6797            "flat base interpolates to the byte color"
6798        );
6799    }
6800
6801    /// **A shaded triangle renders the interpolated color through the combiner.**
6802    /// A flat-shaded triangle (base `(0x11, 0x22, 0x33, 0xFF)`) with a shade-
6803    /// passthrough combiner (`D = shade`, `A = B` so `(A−B)·C = 0`) writes that
6804    /// color — not the FILL register — into the 32-bit color image, proving the
6805    /// decode → interpolate → combine → write path.
6806    #[test]
6807    fn shaded_triangle_renders_combined_shade() {
6808        let mut bus = ZBufBus {
6809            mem: alloc::vec![0u8; 0x1000],
6810            hidden: alloc::vec![0u8; 0x800],
6811        };
6812        let mut rdp = Rdp::new();
6813        rdp.color_image = 0x200;
6814        rdp.color_image_size = 3; // 32-bit
6815        rdp.color_image_width = 8;
6816        rdp.scissor_lrx = 8 << 2;
6817        rdp.scissor_lry = 8 << 2;
6818        rdp.fill_color = 0xDEAD_BEEF; // must NOT appear
6819        // Shade-passthrough combiner: cyc1 D = shade (4), A = B (cancel).
6820        rdp.combine.cyc1 = CombineCycle {
6821            rgb_a: 0,
6822            rgb_b: 0,
6823            rgb_c: 0,
6824            rgb_d: 4,
6825            a_a: 0,
6826            a_b: 0,
6827            a_c: 0,
6828            a_d: 4,
6829        };
6830        // Staircase triangle (as the flat-fill test) with the shade flag (bit 58 ->
6831        // hi bit 26), flat base color (0x11, 0x22, 0x33, 0xFF).
6832        let base = 0x600usize;
6833        bus.mem[base + 0x10..base + 0x14].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xh
6834        bus.mem[base + 0x18..base + 0x1C].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xm
6835        bus.mem[base + 0x1C..base + 0x20].copy_from_slice(&0x0001_0000u32.to_be_bytes()); // dxmdy = 1.0 (R-14)
6836        // Shade int-base at base + 0x20 / 0x24.
6837        bus.mem[base + 0x20..base + 0x24].copy_from_slice(&((0x11u32 << 16) | 0x22).to_be_bytes());
6838        bus.mem[base + 0x24..base + 0x28].copy_from_slice(&((0x33u32 << 16) | 0xFF).to_be_bytes());
6839        // opcode 0x0C = Fill Shaded Triangle (bit 58 set); hi = 0x0880_0010 | (1<<26).
6840        rdp.dispatch(0x0C, 0x0C80_0010, 0x0010_0000, base as u32, &mut bus);
6841
6842        let px = |bus: &ZBufBus, x: usize, row: usize| -> u32 {
6843            let a = 0x200 + row * 32 + x * 4;
6844            u32::from_be_bytes([bus.mem[a], bus.mem[a + 1], bus.mem[a + 2], bus.mem[a + 3]])
6845        };
6846        // 1-cycle mode stores sub-pixel coverage in the alpha byte (validated against
6847        // Angrylion by `shade_tri_frac_16`), so check the combiner RGB at a fully-
6848        // covered interior pixel — full coverage stores `7 << 5 = 0xE0`. The top
6849        // vertex (2,0) is a degenerate single point, excluded by the AA-off top-left
6850        // sample rule.
6851        assert_eq!(
6852            px(&bus, 2, 3),
6853            0x1122_33E0,
6854            "shaded RGB + full-coverage alpha"
6855        );
6856        assert_eq!(px(&bus, 0, 0), 0, "outside the triangle stays clear");
6857    }
6858
6859    /// **A combined shaded + depth-tested triangle (0x0D) decodes both blocks at the
6860    /// right offsets.** With the shade block at `+0x20` and the z block at `+0x60`
6861    /// (past the 8-word shade block), the pixel must be the shade color *and* the
6862    /// stored depth must be the z-block's value — if `decode_triangle_z` misread the
6863    /// shade block as z, the stored `compressed_z` would differ.
6864    #[test]
6865    fn shaded_and_depth_tested_triangle_reads_both_blocks() {
6866        let mut bus = ZBufBus {
6867            mem: alloc::vec![0u8; 0x1000],
6868            hidden: alloc::vec![0u8; 0x800],
6869        };
6870        for b in &mut bus.mem[0x400..0x500] {
6871            *b = 0xFF; // Z buffer pre-cleared to the far plane
6872        }
6873        let mut rdp = Rdp::new();
6874        rdp.color_image = 0x200;
6875        rdp.color_image_size = 3;
6876        rdp.color_image_width = 8;
6877        rdp.z_image = 0x400;
6878        rdp.scissor_lrx = 8 << 2;
6879        rdp.scissor_lry = 8 << 2;
6880        rdp.other_modes.z_compare_en = true;
6881        rdp.other_modes.z_update_en = true;
6882        rdp.combine.cyc1 = CombineCycle {
6883            rgb_a: 0,
6884            rgb_b: 0,
6885            rgb_c: 0,
6886            rgb_d: 4,
6887            a_a: 0,
6888            a_b: 0,
6889            a_c: 0,
6890            a_d: 4,
6891        };
6892        let base = 0x600usize;
6893        bus.mem[base + 0x10..base + 0x14].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xh
6894        bus.mem[base + 0x18..base + 0x1C].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xm
6895        bus.mem[base + 0x1C..base + 0x20].copy_from_slice(&0x0000_4000u32.to_be_bytes()); // dxmdy
6896        // Shade block int-base at +0x20 (color 0x1122_33FF).
6897        bus.mem[base + 0x20..base + 0x24].copy_from_slice(&((0x11u32 << 16) | 0x22).to_be_bytes());
6898        bus.mem[base + 0x24..base + 0x28].copy_from_slice(&((0x33u32 << 16) | 0xFF).to_be_bytes());
6899        // Z block at +0x60 (past the 8-word shade block): z_base -> z_px 0x4000.
6900        bus.mem[base + 0x60..base + 0x64].copy_from_slice(&0x0800_0000u32.to_be_bytes());
6901        // opcode 0x0D = shade (bit 58) + z (bit 56); hi = 0x0880_0010 | (1<<26) | (1<<24).
6902        rdp.dispatch(0x0D, 0x0D80_0010, 0x0010_0000, base as u32, &mut bus);
6903
6904        // 1-cycle coverage excludes the degenerate top vertex (2,0); check the drawn
6905        // pixel (2,1). The shade RGB is `0x112233`; the alpha holds sub-pixel coverage.
6906        let a = 0x200 + 32 + 2 * 4; // pixel (2, 1)
6907        let color =
6908            u32::from_be_bytes([bus.mem[a], bus.mem[a + 1], bus.mem[a + 2], bus.mem[a + 3]]);
6909        assert_eq!(
6910            color & 0xFFFF_FF00,
6911            0x1122_3300,
6912            "shade block decoded (color)"
6913        );
6914        let (cz, _) = rdp.zbuffer_read(2, 1, &bus);
6915        assert_eq!(
6916            cz,
6917            z_compress(0x4000),
6918            "z block decoded at +0x60, not the shade block"
6919        );
6920    }
6921
6922    /// **A textured triangle samples the tile through the combiner.** A flat texture
6923    /// coordinate (`s = t = 0`, scale-independent of the perspective divide) samples
6924    /// texel `(0, 0)` — an opaque red RGBA16 — and a texel-passthrough combiner
6925    /// (`D = texel0`) writes `0xFF0000FF`, not the FILL register, proving the
6926    /// `decode_texture` → `interpolate_st` → `fetch_texel` → combine → write path.
6927    #[test]
6928    fn textured_triangle_samples_the_texel() {
6929        let mut bus = ZBufBus {
6930            mem: alloc::vec![0u8; 0x1000],
6931            hidden: alloc::vec![0u8; 0x800],
6932        };
6933        let mut rdp = Rdp::new();
6934        rdp.color_image = 0x200;
6935        rdp.color_image_size = 3;
6936        rdp.color_image_width = 8;
6937        rdp.scissor_lrx = 8 << 2;
6938        rdp.scissor_lry = 8 << 2;
6939        rdp.fill_color = 0xDEAD_BEEF; // must NOT appear
6940        // Tile 0: RGBA16 at TMEM 0; texel (0,0) = 0xF801 (opaque red).
6941        rdp.tiles[0].format = 0;
6942        rdp.tiles[0].size = 2;
6943        rdp.tiles[0].tmem_addr = 0;
6944        rdp.tiles[0].line = 0;
6945        rdp.tmem_write(0, 0xF8);
6946        rdp.tmem_write(1, 0x01);
6947        // Texel-passthrough combiner: cyc1 D = texel0 (1), A = B (cancel).
6948        rdp.combine.cyc1 = CombineCycle {
6949            rgb_a: 0,
6950            rgb_b: 0,
6951            rgb_c: 0,
6952            rgb_d: 1,
6953            a_a: 0,
6954            a_b: 0,
6955            a_c: 0,
6956            a_d: 1,
6957        };
6958        let base = 0x600usize;
6959        bus.mem[base + 0x10..base + 0x14].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xh
6960        bus.mem[base + 0x18..base + 0x1C].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xm
6961        bus.mem[base + 0x1C..base + 0x20].copy_from_slice(&0x0001_0000u32.to_be_bytes()); // dxmdy = 1.0 (R-14)
6962        // Texture block at base + 0x20 (no shade): all-zero -> s = t = 0.
6963        // opcode 0x0A = texture (bit 57); hi = 0x0880_0010 | (1 << 25).
6964        rdp.dispatch(0x0A, 0x0A80_0010, 0x0010_0000, base as u32, &mut bus);
6965
6966        let px = |bus: &ZBufBus, x: usize, row: usize| -> u32 {
6967            let a = 0x200 + row * 32 + x * 4;
6968            u32::from_be_bytes([bus.mem[a], bus.mem[a + 1], bus.mem[a + 2], bus.mem[a + 3]])
6969        };
6970        // 1-cycle sub-pixel coverage stores `7 << 5 = 0xE0` in the alpha at a
6971        // fully-covered interior pixel; the degenerate top vertex (2,0) is excluded.
6972        assert_eq!(
6973            px(&bus, 2, 3),
6974            0xFF00_00E0,
6975            "textured red + full-coverage alpha, not the FILL color"
6976        );
6977    }
6978
6979    /// **`decode_texture` pairs the interleaved int/frac words per the wiki.** The
6980    /// block is `word0 = s.i/t.i`, `word2 = s.f/t.f`, `word4 = dsde.i` — so the base
6981    /// assembles from words 0 (int) and **2** (frac). Distinct frac bytes absent
6982    /// from word 4 make a mispaired decode (e.g. int + de) surface as a wrong base.
6983    #[test]
6984    fn decode_texture_pairs_interleaved_int_frac() {
6985        let mut bus = ZBufBus {
6986            mem: alloc::vec![0u8; 0x100],
6987            hidden: alloc::vec![0u8; 0x80],
6988        };
6989        // Word0 int-base hi = (s.i << 16) | t.i; word2 frac-base hi = (s.f << 16) | t.f.
6990        // Word4 (de int) left 0, so a base that read word4 as its frac would be wrong.
6991        bus.mem[0x20..0x24].copy_from_slice(&((0x0005u32 << 16) | 0x0007).to_be_bytes());
6992        bus.mem[0x30..0x34].copy_from_slice(&((0x8000u32 << 16) | 0x4000).to_be_bytes());
6993        let tex = Rdp::decode_texture(1 << 25, 0, &bus).expect("texture block present");
6994        assert_eq!(
6995            [tex.base[0], tex.base[1]],
6996            [0x0005_8000, 0x0007_4000],
6997            "base = word0 (int) + word2 (frac), not word4"
6998        );
6999        assert_eq!(tex.de, [0, 0, 0], "de reads word4/word6 (all zero here)");
7000    }
7001
7002    /// **A shaded + textured triangle (0x0E) reads the texture block past the 8-word
7003    /// shade block.** The shade block is 8 words, so the texture block sits at
7004    /// `+0x60`. The texture coordinate there selects texel column 1 (green); if the
7005    /// texture offset were wrong (e.g. a 16-word shade assumption → `+0xA0`), it would
7006    /// read zeros and sample column 0 (red) instead. The green result pins `+0x60`.
7007    #[test]
7008    fn shaded_and_textured_triangle_reads_texture_past_shade() {
7009        let mut bus = ZBufBus {
7010            mem: alloc::vec![0u8; 0x1000],
7011            hidden: alloc::vec![0u8; 0x800],
7012        };
7013        let mut rdp = Rdp::new();
7014        rdp.color_image = 0x200;
7015        rdp.color_image_size = 3;
7016        rdp.color_image_width = 8;
7017        rdp.scissor_lrx = 8 << 2;
7018        rdp.scissor_lry = 8 << 2;
7019        rdp.tiles[0].format = 0;
7020        rdp.tiles[0].size = 2;
7021        // An 8×8 tile so S = texel 1 is in-bounds: the R-13 tile transform forces
7022        // the clamp when `mask == 0`, and a coordinate past `SH` clamps to the last
7023        // texel — with the default `SH = 0` this would clamp S = 1 back to texel 0.
7024        rdp.tiles[0].sh = 7 << 2;
7025        rdp.tiles[0].th = 7 << 2;
7026        // texel (0,0) = red 0xF801, texel (1,0) = green 0x07C1.
7027        rdp.tmem_write(0, 0xF8);
7028        rdp.tmem_write(1, 0x01);
7029        rdp.tmem_write(2, 0x07);
7030        rdp.tmem_write(3, 0xC1);
7031        rdp.combine.cyc1 = CombineCycle {
7032            rgb_a: 0,
7033            rgb_b: 0,
7034            rgb_c: 0,
7035            rgb_d: 1, // texel0
7036            a_a: 0,
7037            a_b: 0,
7038            a_c: 0,
7039            a_d: 1,
7040        };
7041        let base = 0x600usize;
7042        bus.mem[base + 0x10..base + 0x14].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xh
7043        bus.mem[base + 0x18..base + 0x1C].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xm
7044        bus.mem[base + 0x1C..base + 0x20].copy_from_slice(&0x0000_4000u32.to_be_bytes()); // dxmdy
7045        // Shade block at +0x20 (8 words). Texture block at +0x60: the RDP texel
7046        // coordinate is s.5, so S = 32 (`0x20`) selects texel index 32 >> 5 = 1
7047        // (green). This is the R-13 coordinate scale — under the old `v >> 16`
7048        // (no `>> 5`) this same field would have selected column 1 directly.
7049        bus.mem[base + 0x60..base + 0x64].copy_from_slice(&(0x0020u32 << 16).to_be_bytes());
7050        // opcode 0x0E = shade (bit 58) + texture (bit 57); hi = 0x0880_0010 | (1<<26) | (1<<25).
7051        rdp.dispatch(0x0E, 0x0E80_0010, 0x0010_0000, base as u32, &mut bus);
7052
7053        // This near-vertical triangle (DxMDy 0.25) covers column 2 only partially, so
7054        // check the combiner RGB (the point of this test — the texture is decoded at
7055        // +0x60, past the shade block); the alpha holds sub-pixel coverage, exercised
7056        // separately by `shade_tri_frac_16`. Pixel (2,1) is drawn (the top vertex is a
7057        // degenerate point).
7058        let a = 0x200 + 32 + 2 * 4; // pixel (2, 1)
7059        let color =
7060            u32::from_be_bytes([bus.mem[a], bus.mem[a + 1], bus.mem[a + 2], bus.mem[a + 3]]);
7061        assert_eq!(
7062            color & 0xFFFF_FF00,
7063            0x00FF_0000,
7064            "texel column 1 (green) — texture read at +0x60"
7065        );
7066        assert_ne!(
7067            color & 0xFF,
7068            0,
7069            "the covered pixel stores non-zero coverage"
7070        );
7071    }
7072
7073    /// **`perspective_divide` matches the hand-computed ParaLLEl-RDP arithmetic.** For
7074    /// `w = 0x4000` the LUT gives `rcp = 0x4000`, `shift = 0`, so `s → (s·0x4000) >> 13`
7075    /// (`0x10 → 0x20`); `w = 0x2000` gives `shift = 1` so `>> 12` (`0x100 → 0x400`); and
7076    /// `w <= 0` sets the carry to `0x7FFF`.
7077    #[test]
7078    fn perspective_divide_matches_hand_computed() {
7079        assert_eq!(perspective_divide(0x10, 0x20, 0x4000), (0x20, 0x40));
7080        assert_eq!(perspective_divide(0x100, 0, 0x2000), (0x400, 0));
7081        assert_eq!(
7082            perspective_divide(0x10, 0x20, -1),
7083            (0x7FFF, 0x7FFF),
7084            "w<=0 carry"
7085        );
7086        // The LUT's first/last entries pin the transcription boundaries.
7087        assert_eq!(PERSPECTIVE_TABLE[0], (0x4000, -1008));
7088        assert_eq!(PERSPECTIVE_TABLE[63], (0x2041, -260));
7089    }
7090
7091    /// **A translucent triangle blends with the framebuffer.** A shaded triangle
7092    /// (combiner → red, alpha `0x80`) over a green background, with `force_blend`
7093    /// and blend modes `P = pixel`, `A = pixel-alpha`, `M = memory`, `B = 1−A`, blends
7094    /// 50/50: `a0 = 0x80>>3 = 16`, `a1+1 = (~0x80>>3)+1 = 16`, so each channel is
7095    /// `(pixel + memory)/2` → `0x7F7F00`. Without the memory read (or with blend off)
7096    /// it would be plain red — the green contribution proves the blender ran.
7097    #[test]
7098    fn translucent_triangle_blends_with_framebuffer() {
7099        let mut bus = ZBufBus {
7100            mem: alloc::vec![0u8; 0x1000],
7101            hidden: alloc::vec![0u8; 0x800],
7102        };
7103        // Pre-fill the color image with green (0x00FF00FF) and the Z buffer far.
7104        for row in 0..8 {
7105            for x in 0..8 {
7106                let a = 0x200 + row * 32 + x * 4;
7107                bus.mem[a..a + 4].copy_from_slice(&0x00FF_00FFu32.to_be_bytes());
7108            }
7109        }
7110        for b in &mut bus.mem[0x400..0x500] {
7111            *b = 0xFF;
7112        }
7113        let mut rdp = Rdp::new();
7114        rdp.color_image = 0x200;
7115        rdp.color_image_size = 3;
7116        rdp.color_image_width = 8;
7117        rdp.z_image = 0x400;
7118        rdp.scissor_lrx = 8 << 2;
7119        rdp.scissor_lry = 8 << 2;
7120        rdp.other_modes.z_compare_en = true;
7121        rdp.other_modes.z_update_en = true;
7122        rdp.other_modes.force_blend = true; // -> depth_test sets blend_en
7123        rdp.other_modes.rgb_dither_mode = 3; // dither off: isolate the blend under test
7124        rdp.other_modes.blend[0] = BlendCycle {
7125            p: 0,
7126            a: 0,
7127            m: 1,
7128            b: 0,
7129        }; // pixel, pixel-a, memory, 1-A
7130        rdp.combine.cyc1 = CombineCycle {
7131            rgb_a: 0,
7132            rgb_b: 0,
7133            rgb_c: 0,
7134            rgb_d: 4, // shade rgb
7135            a_a: 0,
7136            a_b: 0,
7137            a_c: 0,
7138            a_d: 4, // shade alpha
7139        };
7140        let base = 0x600usize;
7141        bus.mem[base + 0x10..base + 0x14].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xh
7142        bus.mem[base + 0x18..base + 0x1C].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xm
7143        bus.mem[base + 0x1C..base + 0x20].copy_from_slice(&0x0000_4000u32.to_be_bytes()); // dxmdy
7144        // Shade int-base: R = 0xFF, G = B = 0, A = 0x80.
7145        bus.mem[base + 0x20..base + 0x24].copy_from_slice(&(0xFFu32 << 16).to_be_bytes());
7146        bus.mem[base + 0x24..base + 0x28].copy_from_slice(&0x0000_0080u32.to_be_bytes());
7147        // opcode 0x0D = shade (bit 58) + z (bit 56); z block at +0x60 (near).
7148        bus.mem[base + 0x60..base + 0x64].copy_from_slice(&0x0800_0000u32.to_be_bytes()); // z_px 0x4000
7149        rdp.dispatch(0x0D, 0x0D80_0010, 0x0010_0000, base as u32, &mut bus);
7150
7151        // 1-cycle coverage excludes the degenerate top vertex (2,0) and stores coverage
7152        // in the alpha; check the blended RGB at the drawn pixel (2,1).
7153        let a = 0x200 + 32 + 2 * 4; // pixel (2, 1)
7154        let color =
7155            u32::from_be_bytes([bus.mem[a], bus.mem[a + 1], bus.mem[a + 2], bus.mem[a + 3]]);
7156        assert_eq!(
7157            color & 0xFFFF_FF00,
7158            0x7F7F_0000,
7159            "50/50 blend of red over green (not plain red)"
7160        );
7161    }
7162
7163    /// **`unpack_rgba5551` widens each 5-bit channel by high-bit replication** and
7164    /// maps the 1-bit alpha to `0x00`/`0xFF` — the exact inverse of `pack_rgba5551`
7165    /// on the packable values. `0x1F → 0xFF`, `0x00 → 0x00`, `0x10 → 0x84`
7166    /// (`0b10000 << 3 | 0b10000 >> 2 = 0x80 | 0x04`).
7167    #[test]
7168    fn unpack_rgba5551_widens_by_high_bit_replication() {
7169        assert_eq!(unpack_rgba5551(0xFFFF), [0xFF, 0xFF, 0xFF, 0xFF]);
7170        assert_eq!(unpack_rgba5551(0x0000), [0x00, 0x00, 0x00, 0x00]);
7171        // R = 0x10 (bits 15:11), everything else zero, alpha bit set.
7172        assert_eq!(unpack_rgba5551(0x8001), [0x84, 0x00, 0x00, 0xFF]);
7173        // Pure green (G = 0x1F) with alpha — the 16-bit background the blend test uses.
7174        assert_eq!(unpack_rgba5551(0x07C1), [0x00, 0xFF, 0x00, 0xFF]);
7175        // Round-trip every packable RGBA8888 whose low bits are already truncated.
7176        for &v in &[0x00u8, 0x08, 0x84, 0xF8, 0xFF] {
7177            let packed = pack_rgba5551([v & 0xF8, 0, v & 0xF8, 0x80]);
7178            let un = unpack_rgba5551(packed);
7179            assert_eq!(pack_rgba5551(un), packed, "round-trip stable for {v:#04x}");
7180        }
7181    }
7182
7183    /// **The blender also runs against a 16-bit RGBA5551 framebuffer.** The same
7184    /// red-over-green 50/50 blend as [`translucent_triangle_blends_with_framebuffer`]
7185    /// but with a 16-bit color image, exercising `read_pixel`'s RGBA5551 decode and
7186    /// `write_pixel`'s repack. Memory green `0x07C1` unpacks to `0x00FF00`; the blend
7187    /// `0x7F7F00` repacks to `0x7BC1` (`R,G = 0x7F>>3 = 0x0F`, alpha bit `0x80>>7 = 1`).
7188    #[test]
7189    fn translucent_triangle_blends_16bit_framebuffer() {
7190        let mut bus = ZBufBus {
7191            mem: alloc::vec![0u8; 0x1000],
7192            hidden: alloc::vec![0u8; 0x800],
7193        };
7194        // Pre-fill the 16-bit color image with green (RGBA5551 0x07C1); Z buffer far.
7195        for row in 0..8 {
7196            for x in 0..8 {
7197                let a = 0x200 + row * 16 + x * 2;
7198                bus.mem[a..a + 2].copy_from_slice(&0x07C1u16.to_be_bytes());
7199            }
7200        }
7201        for b in &mut bus.mem[0x400..0x500] {
7202            *b = 0xFF;
7203        }
7204        let mut rdp = Rdp::new();
7205        rdp.color_image = 0x200;
7206        rdp.color_image_size = 2; // 16-bit RGBA5551
7207        rdp.color_image_width = 8;
7208        rdp.z_image = 0x400;
7209        rdp.scissor_lrx = 8 << 2;
7210        rdp.scissor_lry = 8 << 2;
7211        rdp.other_modes.z_compare_en = true;
7212        rdp.other_modes.z_update_en = true;
7213        rdp.other_modes.force_blend = true;
7214        rdp.other_modes.rgb_dither_mode = 3; // dither off: isolate the blend under test
7215        rdp.other_modes.blend[0] = BlendCycle {
7216            p: 0,
7217            a: 0,
7218            m: 1,
7219            b: 0,
7220        };
7221        rdp.combine.cyc1 = CombineCycle {
7222            rgb_a: 0,
7223            rgb_b: 0,
7224            rgb_c: 0,
7225            rgb_d: 4,
7226            a_a: 0,
7227            a_b: 0,
7228            a_c: 0,
7229            a_d: 4,
7230        };
7231        let base = 0x600usize;
7232        bus.mem[base + 0x10..base + 0x14].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xh
7233        bus.mem[base + 0x18..base + 0x1C].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xm
7234        bus.mem[base + 0x1C..base + 0x20].copy_from_slice(&0x0000_4000u32.to_be_bytes()); // dxmdy
7235        bus.mem[base + 0x20..base + 0x24].copy_from_slice(&(0xFFu32 << 16).to_be_bytes()); // R=0xFF
7236        bus.mem[base + 0x24..base + 0x28].copy_from_slice(&0x0000_0080u32.to_be_bytes()); // A=0x80
7237        bus.mem[base + 0x60..base + 0x64].copy_from_slice(&0x0800_0000u32.to_be_bytes()); // z_px
7238        rdp.dispatch(0x0D, 0x0D80_0010, 0x0010_0000, base as u32, &mut bus);
7239
7240        // Drawn pixel (2,1); the RGBA5551 alpha bit (bit 0) now holds sub-pixel
7241        // coverage, so mask it and check the RGB (0x7BC0 = the 50/50 red-over-green).
7242        let a = 0x200 + 16 + 2 * 2; // pixel (2, 1), bpp = 2
7243        let color = u16::from_be_bytes([bus.mem[a], bus.mem[a + 1]]);
7244        assert_eq!(
7245            color & 0xFFFE,
7246            0x7BC0,
7247            "50/50 blend of red over green, repacked to RGBA5551"
7248        );
7249    }
7250
7251    /// **The blender's `A`-select 2 takes the interpolated shade alpha, not the
7252    /// combiner output alpha.** These are independent inputs; this test forces them
7253    /// apart so a regression that fed `color[3]` back in would be caught. The alpha
7254    /// combiner outputs the env alpha (`0xF0`) while the interpolated shade alpha is
7255    /// `0x80`; the blender selects `A = 2` (shade alpha). With shade alpha `0x80`,
7256    /// `a0 = 16` / `a1 + 1 = 16` gives the 50/50 red-over-green `0x7F7F00`. Had the
7257    /// combiner alpha `0xF0` leaked in, `a0 = 30` / `a1 + 1 = 2` would give
7258    /// `0xEF0F00` — a distinct value, so the test mutation-checks the fix.
7259    #[test]
7260    fn blender_shade_alpha_is_interpolated_not_combiner_output() {
7261        let mut bus = ZBufBus {
7262            mem: alloc::vec![0u8; 0x1000],
7263            hidden: alloc::vec![0u8; 0x800],
7264        };
7265        for row in 0..8 {
7266            for x in 0..8 {
7267                let a = 0x200 + row * 32 + x * 4;
7268                bus.mem[a..a + 4].copy_from_slice(&0x00FF_00FFu32.to_be_bytes()); // green
7269            }
7270        }
7271        for b in &mut bus.mem[0x400..0x500] {
7272            *b = 0xFF;
7273        }
7274        let mut rdp = Rdp::new();
7275        rdp.color_image = 0x200;
7276        rdp.color_image_size = 3;
7277        rdp.color_image_width = 8;
7278        rdp.z_image = 0x400;
7279        rdp.env_color = 0x0000_00F0; // env alpha = 0xF0 (the combiner output alpha)
7280        rdp.scissor_lrx = 8 << 2;
7281        rdp.scissor_lry = 8 << 2;
7282        rdp.other_modes.z_compare_en = true;
7283        rdp.other_modes.z_update_en = true;
7284        rdp.other_modes.force_blend = true;
7285        rdp.other_modes.rgb_dither_mode = 3; // dither off: isolate the blend under test
7286        rdp.other_modes.blend[0] = BlendCycle {
7287            p: 0,
7288            a: 2, // shade alpha -- the input under test
7289            m: 1,
7290            b: 0,
7291        };
7292        rdp.combine.cyc1 = CombineCycle {
7293            rgb_a: 0,
7294            rgb_b: 0,
7295            rgb_c: 0,
7296            rgb_d: 4, // shade rgb -> red
7297            a_a: 7,
7298            a_b: 7,
7299            a_c: 7,
7300            a_d: 5, // env alpha -> combiner output alpha = 0xF0 (!= shade alpha 0x80)
7301        };
7302        let base = 0x600usize;
7303        bus.mem[base + 0x10..base + 0x14].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xh
7304        bus.mem[base + 0x18..base + 0x1C].copy_from_slice(&0x0002_0000u32.to_be_bytes()); // xm
7305        bus.mem[base + 0x1C..base + 0x20].copy_from_slice(&0x0000_4000u32.to_be_bytes()); // dxmdy
7306        bus.mem[base + 0x20..base + 0x24].copy_from_slice(&(0xFFu32 << 16).to_be_bytes()); // R=0xFF
7307        bus.mem[base + 0x24..base + 0x28].copy_from_slice(&0x0000_0080u32.to_be_bytes()); // shade A=0x80
7308        bus.mem[base + 0x60..base + 0x64].copy_from_slice(&0x0800_0000u32.to_be_bytes()); // z_px
7309        rdp.dispatch(0x0D, 0x0D80_0010, 0x0010_0000, base as u32, &mut bus);
7310
7311        // Drawn pixel (2,1); the RGB proves shade alpha 0x80 drove the 50/50 blend
7312        // (combiner alpha 0xF0 would give 0xEF0F00). The stored alpha now holds
7313        // sub-pixel coverage rather than the combiner alpha, so check RGB only.
7314        let a = 0x200 + 32 + 2 * 4; // pixel (2, 1)
7315        let color =
7316            u32::from_be_bytes([bus.mem[a], bus.mem[a + 1], bus.mem[a + 2], bus.mem[a + 3]]);
7317        assert_eq!(
7318            color & 0xFFFF_FF00,
7319            0x7F7F_0000,
7320            "shade alpha 0x80 drives a 50/50 blend, not combiner alpha 0xF0"
7321        );
7322    }
7323
7324    /// **`quantize_x` maps `s.16` edge X to the `s.3` coverage domain with the
7325    /// sticky bit.** An integer pixel `p` maps to `p << 3` (`p·8`); any discarded
7326    /// fraction bit forces the low bit set so the coordinate stays strictly inside
7327    /// the half-open span. Negative coordinates arithmetic-shift toward −∞.
7328    #[test]
7329    fn quantize_x_maps_to_subpixel_domain_with_sticky() {
7330        assert_eq!(quantize_x(5 << 16), 40, "pixel 5 -> 5*8");
7331        // Pixel 5 + a small fraction (0x1000, below sub-pixel resolution): 40 | sticky.
7332        assert_eq!(
7333            quantize_x((5 << 16) | 0x1000),
7334            41,
7335            "sticky bit forces the LSB"
7336        );
7337        // Exactly half a pixel: sub-pixel offset 4 within pixel 5, no discarded bits.
7338        assert_eq!(quantize_x((5 << 16) | (1 << 15)), 44, "pixel 5.5 -> 44");
7339        assert_eq!(
7340            quantize_x(-(3 << 16)),
7341            -24,
7342            "pixel -3 -> -24 (arithmetic shift)"
7343        );
7344    }
7345
7346    /// **`compute_coverage` yields a full mask for an interior pixel and a partial
7347    /// mask at an edge.** With the left edge quantized to sub-pixel `43` (between
7348    /// X-samples 2 and 4), pixel 5's samples at offsets `{0, 2}` fall outside and
7349    /// `{4, 6}` inside, so the four Y-subpixels each cover their high sample only:
7350    /// mask `0xAA`, count 4. A fully-enclosed pixel is `0xFF` (8); a fully-excluded
7351    /// one is `0` (hand-computed against `coverage.h:31-44`).
7352    #[test]
7353    fn compute_coverage_full_partial_and_empty() {
7354        // Fully inside: left edge at 0, right edge far away.
7355        assert_eq!(compute_coverage([0; 4], [800; 4], 5), 0xFF);
7356        assert_eq!(compute_coverage([0; 4], [800; 4], 5).count_ones(), 8);
7357        // Fully outside: right edge behind the pixel.
7358        assert_eq!(compute_coverage([800; 4], [0; 4], 5), 0x00);
7359        // Left edge at sub-pixel 43: each Y-subpixel's low X-sample (offset 0 or 2)
7360        // is outside and its high sample (4 or 6) inside, so every Y-subpixel keeps
7361        // its odd bit only -> 0xAA.
7362        let mask = compute_coverage([43; 4], [800; 4], 5);
7363        assert_eq!(mask, 0xAA, "high sample of each Y-subpixel covered");
7364        assert_eq!(mask.count_ones(), 4);
7365    }
7366
7367    /// **The mask bit layout is `2·Ysub + Xsample`, and the X-sample offsets
7368    /// alternate by Y-subpixel.** Covering only Y-subpixel 0 sets bits `{0, 1}`
7369    /// (`0x03`), proving the two X-samples of a Y-subpixel occupy adjacent bits.
7370    /// A uniform left edge at sub-pixel `41` then discriminates the diamond
7371    /// offsets: pixel 5's samples are at `{40, 44}` for Y-subpixels 0/2 and
7372    /// `{42, 46}` for 1/3, so 0/2 lose their offset-0 sample (`40 < 41`) while 1/3
7373    /// keep both — mask `0xEE`. (Hand-computed against `coverage.h:31-44`.)
7374    #[test]
7375    fn compute_coverage_bit_layout_and_diamond_offsets() {
7376        // Only Y-subpixel 0's span is valid; the others are poisoned (inverted).
7377        let only_y0 = compute_coverage([0, 800, 800, 800], [800, 0, 0, 0], 5);
7378        assert_eq!(only_y0, 0x03, "Y-subpixel 0 occupies bits 0 and 1");
7379        // Uniform left edge at 41: 0/2 (offsets 0,4) drop offset 0; 1/3 (offsets 2,6) keep both.
7380        let mask = compute_coverage([41; 4], [800; 4], 5);
7381        assert_eq!(
7382            mask, 0xEE,
7383            "Y0/Y2 lose their offset-0 sample; Y1/Y3 keep both"
7384        );
7385        assert_eq!(mask.count_ones(), 6);
7386    }
7387}
7388
7389/// **Coverage must survive the round trip through RDRAM** (ledger R-24).
7390#[cfg(test)]
7391mod coverage_writeback_tests {
7392    use super::{Rdp, VideoBus};
7393    use alloc::vec;
7394    use rustyn64_cart::RdramBus as _;
7395
7396    /// A minimal RDRAM with the hidden 9th-bit plane, modeled the way
7397    /// `rustyn64_core::Bus` does: two bits per halfword, four halfwords per byte.
7398    struct Ram {
7399        main: vec::Vec<u8>,
7400        hidden: vec::Vec<u8>,
7401    }
7402
7403    impl VideoBus for Ram {}
7404
7405    impl rustyn64_cart::RdramBus for Ram {
7406        fn rdram_read(&self, addr: u32) -> u8 {
7407            self.main.get(addr as usize).copied().unwrap_or(0)
7408        }
7409        fn rdram_write(&mut self, addr: u32, val: u8) {
7410            if let Some(b) = self.main.get_mut(addr as usize) {
7411                *b = val;
7412            }
7413        }
7414        fn rdram_read_hidden(&self, addr: u32) -> u8 {
7415            let halfword = (addr as usize) >> 1;
7416            self.hidden
7417                .get(halfword >> 2)
7418                .map_or(0, |b| (b >> ((halfword & 3) * 2)) & 3)
7419        }
7420        fn rdram_write_hidden(&mut self, addr: u32, val: u8) {
7421            let halfword = (addr as usize) >> 1;
7422            if let Some(b) = self.hidden.get_mut(halfword >> 2) {
7423                let shift = (halfword & 3) * 2;
7424                *b = (*b & !(3 << shift)) | ((val & 3) << shift);
7425            }
7426        }
7427    }
7428
7429    /// Every coverage value `0..=7` must read back exactly, reassembled the way
7430    /// `Bus::vi_read_cov` does it: top bit from the RGBA5551 alpha, low two bits
7431    /// from the hidden plane.
7432    ///
7433    /// **Mutation check:** delete the `write_coverage` call in the span loop, or
7434    /// make it write `cov` instead of `cov & 3`, and this goes red. Before the
7435    /// fix, every value read back as `cov & 4` — which is why the VI never saw
7436    /// `cvg == 7` and its coverage-gated filters were dead.
7437    #[test]
7438    fn coverage_survives_the_round_trip_for_every_value() {
7439        for cov in 0u8..=7 {
7440            let mut ram = Ram {
7441                main: vec![0u8; 64],
7442                hidden: vec![0u8; 16],
7443            };
7444            let (row, x, bpp) = (0u32, 3u32, 2u32);
7445            // What the span loop writes: coverage in the alpha byte's top bits,
7446            // then the low two bits into the hidden plane.
7447            let rgba = [0x10u8, 0x20, 0x30, cov << 5];
7448            Rdp::write_pixel(row, x, bpp, rgba, &mut ram);
7449            Rdp::write_coverage(row, x, bpp, cov, &mut ram);
7450
7451            // What the VI reads: `((px & 1) << 2) | rdram_read_hidden(byte)`.
7452            let addr = row + x * bpp;
7453            let px = u16::from_be_bytes([ram.rdram_read(addr), ram.rdram_read(addr + 1)]);
7454            let got = ((u32::from(px) & 1) << 2) | u32::from(ram.rdram_read_hidden(addr));
7455            assert_eq!(
7456                got,
7457                u32::from(cov),
7458                "coverage {cov} read back as {got}: the hidden plane lost the low two bits"
7459            );
7460        }
7461    }
7462
7463    /// A 32-bit color image keeps all three bits in the alpha byte, so the hidden
7464    /// plane must be left ALONE — writing it there would store a second copy the
7465    /// hardware does not keep, and the VI reads `(px >> 5) & 7` regardless.
7466    #[test]
7467    fn a_32bit_color_image_does_not_touch_the_hidden_plane() {
7468        let mut ram = Ram {
7469            main: vec![0u8; 64],
7470            hidden: vec![0xFFu8; 16],
7471        };
7472        Rdp::write_coverage(0, 3, 4, 7, &mut ram);
7473        assert_eq!(
7474            ram.hidden,
7475            vec![0xFFu8; 16],
7476            "a 32-bit image must not write the hidden plane"
7477        );
7478    }
7479}
7480
7481/// The census predicate must agree with the step it claims to describe.
7482#[cfg(all(test, feature = "work-counters"))]
7483mod census_predicate_tests {
7484    use super::{DP_STATUS_FREEZE, DP_STATUS_XBUS, Rdp};
7485
7486    /// `is_idle_for_census` duplicates `tick_without_bus`'s early-outs because it
7487    /// must not consume the stall the real step consumes — measuring would
7488    /// otherwise change what is measured. Duplicated logic drifts, so the two are
7489    /// pinned together here across every early-out.
7490    ///
7491    /// Mutation check: drop any one clause from the predicate and this goes red.
7492    #[test]
7493    fn census_predicate_agrees_with_the_real_early_outs() {
7494        let mut rdp = Rdp::new();
7495        rdp.status |= DP_STATUS_FREEZE;
7496        assert!(rdp.is_idle_for_census());
7497        assert!(rdp.tick_without_bus().is_none(), "frozen needs no bus");
7498
7499        let mut rdp = Rdp::new();
7500        rdp.status |= DP_STATUS_XBUS;
7501        assert!(rdp.is_idle_for_census());
7502        assert!(rdp.tick_without_bus().is_none(), "XBUS needs no bus");
7503
7504        // Checked BEFORE `tick_without_bus`, which DECREMENTS the stall. The
7505        // predicate must not, and calling the real step first would hide that.
7506        let mut rdp = Rdp::new();
7507        rdp.stall = 2;
7508        assert!(rdp.is_idle_for_census());
7509        assert!(rdp.is_idle_for_census());
7510        assert_eq!(rdp.stall, 2, "the census predicate must be read-only");
7511        assert!(rdp.tick_without_bus().is_none(), "a stall needs no bus");
7512
7513        let mut rdp = Rdp::new();
7514        assert!(rdp.is_idle_for_census(), "an empty FIFO is idle");
7515        assert!(rdp.tick_without_bus().is_none());
7516
7517        // NOT idle: a pending command with nothing else blocking.
7518        let mut rdp = Rdp::new();
7519        rdp.dpc_write(0, 0x100);
7520        rdp.dpc_write(1, 0x108);
7521        assert!(
7522            !rdp.is_idle_for_census(),
7523            "a pending command must not count as idle, or the census reports a \
7524             ceiling that does not exist"
7525        );
7526        assert!(rdp.tick_without_bus().is_some());
7527    }
7528}