From 97ea2541bb6414ec5950e9e63b4b5c260f88fdc1 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:01:26 -0600 Subject: [PATCH 1/2] metal: cover BC2/BC3 edge blocks and report missing BC support apart The section 12 audit of #214 found three gaps: no level narrower than a block row (Metal's zero-stride single-row upload) or of 1x1, no checks for zero extents or oversized and block-count-mismatched payloads, and a missing BC capability surfaced the same way as an implementation fault. Adds a 5x3 and 1x1 GPU test with hand-derived anchors, the extra upload rejections, and MetalError::is_capability_unavailable; the GPU tests now print CAPABILITY UNAVAILABLE or IMPLEMENTATION FAILURE. Rounding the texture to whole blocks, accepting oversized payloads, or a device without BC support each makes the tests fail with the matching message. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- CHANGELOG.md | 4 + crates/metal/src/compute.rs | 13 ++- crates/metal/tests/native/texture_bc_alpha.rs | 91 ++++++++++++++++++- crates/metal/tests/native_compute.rs | 11 +++ crates/texture/src/upload.rs | 35 ++++++- 5 files changed, 148 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2654abdf..40e78b48 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,10 @@ remains unsupported. orders, padded row and slice pitches, two layers and two mips against the CPU decoders and hand-derived anchors. On an Apple M5 Pro the native decoder's interpolated values were within 1.14 codes of the exact values, so up to two codes from the truncating CPU reference. + Edge levels of 5×3 (one block row) and 1×1 are covered, invalid payloads (zero extents, + short, oversized or block-count-mismatched buffers, bad pitches) are rejected before upload, + and `MetalError::is_capability_unavailable` separates a device without BC support from an + implementation failure. - Added CPU block decoders for BC2, BC3, BC4 and BC5 (UNORM and SNORM) in `xenora-texture`, with tests whose expected texels were derived by hand from the Microsoft and Khronos block-compression specifications. Interpolated values truncate toward zero, as the existing BC1 decoder does; GPU upload and sampling of these formats are not implemented yet. - Added `dbt::tests::sib_store_executes_through_the_native_dbt`, an independent DBT execution test that runs the SIB store form `mov [rsp + 0x20], rbx` through the native ARM64 DBT and diff --git a/crates/metal/src/compute.rs b/crates/metal/src/compute.rs index bc0475c2..ddd9b2bb 100644 --- a/crates/metal/src/compute.rs +++ b/crates/metal/src/compute.rs @@ -88,6 +88,17 @@ pub struct MetalError { } impl MetalError { + /// Operation name of the error returned when the device lacks BC texture + /// compression, which is a hardware capability, not an implementation fault. + pub const BC_UNAVAILABLE: &'static str = "supportsBCTextureCompression"; + + /// Whether the device lacks a required capability, as opposed to a failure + /// in Xenora's validation or Metal execution. + #[must_use] + pub fn is_capability_unavailable(&self) -> bool { + self.operation == Self::BC_UNAVAILABLE + } + pub(crate) fn new(operation: &'static str, detail: impl Into) -> Self { Self { operation, @@ -332,7 +343,7 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], .ok_or_else(|| MetalError::new("texture bounds", "expected 1..=4096 texels"))?; if !self.device.supportsBCTextureCompression() { return Err(MetalError::new( - "supportsBCTextureCompression", + MetalError::BC_UNAVAILABLE, format!("{name} is unavailable"), )); } diff --git a/crates/metal/tests/native/texture_bc_alpha.rs b/crates/metal/tests/native/texture_bc_alpha.rs index b5c8a409..62fd323c 100644 --- a/crates/metal/tests/native/texture_bc_alpha.rs +++ b/crates/metal/tests/native/texture_bc_alpha.rs @@ -8,7 +8,7 @@ //! decoder is the value under test, so expected and actual values come from //! different decoders. -use super::context; +use super::{context, native}; use xenora_texture::{BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc, decode_bc2, decode_bc3}; /// The specifications define colour and BC3 alpha interpolation in real @@ -156,11 +156,11 @@ fn read_and_compare( let mut worst = 0; let reads = std::array::from_fn(|layer| { let decoded = layers[layer].map(decode); - let base = gpu.read_bc_alpha_upload(&upload, layer, 0).unwrap(); + let base = native(gpu.read_bc_alpha_upload(&upload, layer, 0)); let expected = reference(&decoded[..4], 2, WIDTH, HEIGHT); let label = format!("{format:?} layer {layer}"); worst = worst.max(assert_close(&format!("{label} mip 0"), &base, &expected)); - let small = gpu.read_bc_alpha_upload(&upload, layer, 1).unwrap(); + let small = native(gpu.read_bc_alpha_upload(&upload, layer, 1)); let expected = reference(&decoded[4..], 1, 2, 2); worst = worst.max(assert_close(&format!("{label} mip 1"), &small, &expected)); [base, small] @@ -285,3 +285,88 @@ fn reads_pitched_bc3_interpolated_alpha_across_mips_and_layers() { assert_near("six-value index 3", small[3], 92.0); println!("checked 58 BC3 texels from four subresources, worst channel difference {worst}"); } + +/// Reads one-mip, one-layer uploads of `width`×`height` from `blocks` laid +/// out with `row_pitch`, comparing with the CPU decoder. +fn read_edge( + format: BcAlphaFormat, + decode: fn([u8; 16]) -> [[u8; 4]; 16], + blocks: &[[u8; 16]], + (width, height, row_pitch): (usize, usize, usize), +) -> Vec { + let bytes = blocks.as_flattened(); + let upload = BcAlphaUpload::new( + bytes, + BcAlphaUploadDesc { + width, + height, + mips: 1, + layers: 1, + format, + row_pitch, + slice_pitch: bytes.len(), + }, + ) + .unwrap(); + let actual = native(context().read_bc_alpha_upload(&upload, 0, 0)); + let decoded: Vec<_> = blocks.iter().copied().map(decode).collect(); + let expected = reference(&decoded, width.div_ceil(4), width, height); + assert_close(&format!("{format:?} {width}x{height}"), &actual, &expected); + actual +} + +#[test] +fn reads_bc2_and_bc3_edge_blocks() { + let ramp = [0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe]; + let reverse = ramp.map(|byte: u8| !byte); + let [descending, equal] = [DESCENDING, EQUAL].map(colour); + // 5×3 is one row of two blocks: Metal receives a zero row stride, and + // both blocks are cut at row 3, the second also at column 1. The row + // pitch keeps one padding block. + let wide = (5, 3, 48); + let bc2 = read_edge( + BcAlphaFormat::Bc2, + decode_bc2, + &[block(ramp, descending), block(reverse, equal), PAD], + wide, + ); + // (0, 0) red, nibble 0; (4, 0) green, reversed nibble 15; (0, 2) red, + // nibble 8; (4, 2) green, reversed nibble 7. + assert_eq!( + [bc2[0], bc2[4], bc2[10], bc2[14]], + [0x0000_00ff, 0xff00_ff00, 0x8800_00ff, 0x7700_ff00] + ); + let bc3 = read_edge( + BcAlphaFormat::Bc3, + decode_bc3, + &[ + block(bc3_alpha(200, 20), descending), + block(bc3_alpha(20, 200), equal), + PAD, + ], + wide, + ); + // Row 0 of block 0 is indices 6, 7, 0, 1: (2, 0) and (3, 0) are the + // endpoints 200 and 20. Column 0 of block 1 is indices 6, 2, 6: green + // with the fixed 0, then (4 * 20 + 200) / 5 = 56. + assert_eq!([alpha(bc3[2]), alpha(bc3[3])], [200, 20]); + assert_eq!([bc3[4], bc3[14]], [0x0000_ff00; 2]); + assert_near("six-value index 2", alpha(bc3[9]), 56.0); + // 1×1 is a single block cut to its first texel. + let one = (1, 1, 16); + let bc2 = read_edge( + BcAlphaFormat::Bc2, + decode_bc2, + &[block(reverse, descending)], + one, + ); + assert_eq!(bc2, [0xff00_00ff]); + let bc3 = read_edge( + BcAlphaFormat::Bc3, + decode_bc3, + &[block(bc3_alpha(20, 200), descending)], + one, + ); + assert_eq!(bc3, [0x0000_00ff]); + println!("checked 32 BC2 and BC3 texels from 5x3 and 1x1 edge levels"); +} diff --git a/crates/metal/tests/native_compute.rs b/crates/metal/tests/native_compute.rs index 49e38e3d..c366a8d2 100644 --- a/crates/metal/tests/native_compute.rs +++ b/crates/metal/tests/native_compute.rs @@ -31,6 +31,17 @@ fn context() -> NativeCompute { NativeCompute::new().expect("native Metal device and queue") } +/// Unwraps a native result, reporting a missing device capability apart from +/// an implementation failure. Both fail the test; neither counts as a pass. +fn native(result: Result) -> T { + result.unwrap_or_else(|error| { + if error.is_capability_unavailable() { + panic!("CAPABILITY UNAVAILABLE on this device, not an implementation failure: {error}") + } + panic!("IMPLEMENTATION FAILURE: {error}") + }) +} + fn verify_words(body: &str, input: &[u32], expected: &[u32]) { let actual = context() .run_words(&fixture(body), "fixture", input) diff --git a/crates/texture/src/upload.rs b/crates/texture/src/upload.rs index a66dd279..a8d80ac2 100644 --- a/crates/texture/src/upload.rs +++ b/crates/texture/src/upload.rs @@ -341,15 +341,46 @@ mod tests { mips: 4, ..ALPHA_DESC }, + BcAlphaUploadDesc { + width: 0, + ..ALPHA_DESC + }, + BcAlphaUploadDesc { + height: 0, + ..ALPHA_DESC + }, + BcAlphaUploadDesc { + layers: 0, + ..ALPHA_DESC + }, + BcAlphaUploadDesc { + mips: 0, + ..ALPHA_DESC + }, ] { assert_eq!( BcAlphaUpload::new(&bytes, desc).unwrap_err(), TextureError::InvalidLayout ); } + // Short, oversized, and one block too few or too many for the layout. + let long = [0; 449]; + for bytes in [&bytes[..447], &long[..], &bytes[..432], &[0; 464][..]] { + assert_eq!( + BcAlphaUpload::new(bytes, ALPHA_DESC).unwrap_err(), + TextureError::InvalidByteLength + ); + } assert_eq!( - BcAlphaUpload::new(&bytes[..447], ALPHA_DESC).unwrap_err(), - TextureError::InvalidByteLength + BcAlphaUpload::new( + &bytes, + BcAlphaUploadDesc { + width: usize::MAX, + ..ALPHA_DESC + } + ) + .unwrap_err(), + TextureError::SizeOverflow ); } } From d94121bbb01d98a69969ff4f753b782fc39607fb Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:11:43 -0600 Subject: [PATCH 2/2] metal: compare non-interpolated BC2/BC3 codes exactly An independent review of the #214 tests found that the full-texel check applied the two-code interpolation tolerance to every channel, so an endpoint, a BC2 alpha nibble or BC3's fixed 0 or 255 outside the anchors could be off by two and still pass. The tolerance now comes from each texel's own indices: zero for stored and fixed codes, two only for interpolated ones. A readback kernel that lowers near-opaque alpha by two now fails all three tests. The 1.14-code bound is stated as 8/7. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- CHANGELOG.md | 2 +- crates/metal/tests/native/texture_bc_alpha.rs | 82 +++++++++++++------ 2 files changed, 58 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40e78b48..4288b669 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,7 @@ remains unsupported. GPU tests cover explicit and interpolated (six- and eight-value) alpha, both colour endpoint orders, padded row and slice pitches, two layers and two mips against the CPU decoders and hand-derived anchors. On an Apple M5 Pro the native decoder's interpolated values were within - 1.14 codes of the exact values, so up to two codes from the truncating CPU reference. + 8/7 (about 1.14) codes of the exact values, so up to two codes from the truncating CPU reference. Edge levels of 5×3 (one block row) and 1×1 are covered, invalid payloads (zero extents, short, oversized or block-count-mismatched buffers, bad pitches) are rejected before upload, and `MetalError::is_capability_unavailable` separates a device without BC support from an diff --git a/crates/metal/tests/native/texture_bc_alpha.rs b/crates/metal/tests/native/texture_bc_alpha.rs index 62fd323c..d0733431 100644 --- a/crates/metal/tests/native/texture_bc_alpha.rs +++ b/crates/metal/tests/native/texture_bc_alpha.rs @@ -13,7 +13,7 @@ use xenora_texture::{BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc, decode_bc2 /// The specifications define colour and BC3 alpha interpolation in real /// numbers, and the CPU reference truncates them. On an Apple M5 Pro the -/// native decoder's interpolated values lie within 1.14 codes of the real +/// native decoder's interpolated values lie within 8/7 (1.143) codes of the real /// value (they match 6-bit fixed-point weights), so they can sit two codes /// above the truncated reference: 124 against 122 for BC3 alpha /// (4 * 200 + 3 * 20) / 7 = 122.86. Endpoints, BC2 alpha and BC3's fixed @@ -89,14 +89,48 @@ fn upload_bytes(layers: [Layer; 2]) -> Vec { bytes } -/// Crops decoded blocks (a row-major block grid) to a `width`×`height` level -/// of words with red in the lowest byte, as the readback kernel writes them. -fn reference(blocks: &[[[u8; 4]; 16]], blocks_x: usize, width: usize, height: usize) -> Vec { +/// Per-channel tolerance of each texel of `block`: zero where the index +/// selects a stored endpoint, a BC2 alpha nibble or BC3's fixed 0 or 255, +/// and [`TOLERANCE`] only for interpolated codes. +fn tolerances(format: BcAlphaFormat, block: [u8; 16]) -> [[u8; 4]; 16] { + let colour = u32::from_le_bytes([block[12], block[13], block[14], block[15]]); + let mut alpha_bits = [0; 8]; + alpha_bits[..6].copy_from_slice(&block[2..8]); + let alpha_indices = u64::from_le_bytes(alpha_bits); + let six_value = block[0] <= block[1]; + std::array::from_fn(|t| { + let rgb = if (colour >> (2 * t)) & 3 < 2 { + 0 + } else { + TOLERANCE + }; + let index = (alpha_indices >> (3 * t)) & 7; + let a = match format { + BcAlphaFormat::Bc2 => 0, + BcAlphaFormat::Bc3 if index < 2 || (six_value && index >= 6) => 0, + BcAlphaFormat::Bc3 => TOLERANCE, + }; + [rgb, rgb, rgb, a] + }) +} + +/// Crops a row-major grid of blocks to a `width`×`height` level of CPU-decoded +/// words (red in the lowest byte, as the readback kernel writes them), each +/// with its per-channel tolerance. +fn reference( + format: BcAlphaFormat, + decode: fn([u8; 16]) -> [[u8; 4]; 16], + blocks: &[[u8; 16]], + blocks_x: usize, + (width, height): (usize, usize), +) -> Vec<(u32, [u8; 4])> { let mut texels = Vec::new(); for y in 0..height { for x in 0..width { - let decoded = blocks[(y / 4) * blocks_x + x / 4]; - texels.push(u32::from_le_bytes(decoded[(y % 4) * 4 + x % 4])); + let block = blocks[(y / 4) * blocks_x + x / 4]; + let t = (y % 4) * 4 + x % 4; + let word = u32::from_le_bytes(decode(block)[t]); + texels.push((word, tolerances(format, block)[t])); } } texels @@ -106,24 +140,24 @@ fn alpha(word: u32) -> u8 { word.to_le_bytes()[3] } -/// Returns the largest per-channel difference, failing on any texel above the -/// tolerance with its index and both values. -fn assert_close(label: &str, actual: &[u32], expected: &[u32]) -> u8 { +/// Returns the largest per-channel difference, failing on any channel above +/// its tolerance with the texel index and both values. +fn assert_close(label: &str, actual: &[u32], expected: &[(u32, [u8; 4])]) -> u8 { assert_eq!(actual.len(), expected.len(), "{label}: texel count"); let mut worst = 0; - for (texel, (&got, &want)) in actual.iter().zip(expected).enumerate() { - let diff = got + for (texel, (&got, &(want, tolerance))) in actual.iter().zip(expected).enumerate() { + for ((g, w), limit) in got .to_le_bytes() - .iter() + .into_iter() .zip(want.to_le_bytes()) - .map(|(g, w)| g.abs_diff(w)) - .max() - .unwrap(); - assert!( - diff <= TOLERANCE, - "{label}: texel {texel} got {got:#010x}, want {want:#010x}" - ); - worst = worst.max(diff); + .zip(tolerance) + { + assert!( + g.abs_diff(w) <= limit, + "{label}: texel {texel} got {got:#010x}, want {want:#010x} (per-channel limit {tolerance:?})" + ); + worst = worst.max(g.abs_diff(w)); + } } worst } @@ -155,13 +189,12 @@ fn read_and_compare( let gpu = context(); let mut worst = 0; let reads = std::array::from_fn(|layer| { - let decoded = layers[layer].map(decode); let base = native(gpu.read_bc_alpha_upload(&upload, layer, 0)); - let expected = reference(&decoded[..4], 2, WIDTH, HEIGHT); + let expected = reference(format, decode, &layers[layer][..4], 2, (WIDTH, HEIGHT)); let label = format!("{format:?} layer {layer}"); worst = worst.max(assert_close(&format!("{label} mip 0"), &base, &expected)); let small = native(gpu.read_bc_alpha_upload(&upload, layer, 1)); - let expected = reference(&decoded[4..], 1, 2, 2); + let expected = reference(format, decode, &layers[layer][4..], 1, (2, 2)); worst = worst.max(assert_close(&format!("{label} mip 1"), &small, &expected)); [base, small] }); @@ -309,8 +342,7 @@ fn read_edge( ) .unwrap(); let actual = native(context().read_bc_alpha_upload(&upload, 0, 0)); - let decoded: Vec<_> = blocks.iter().copied().map(decode).collect(); - let expected = reference(&decoded, width.div_ceil(4), width, height); + let expected = reference(format, decode, blocks, width.div_ceil(4), (width, height)); assert_close(&format!("{format:?} {width}x{height}"), &actual, &expected); actual }