From 59ee786a122b59539290fe05a9947050f9551ba0 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:49:17 -0600 Subject: [PATCH] metal: upload and read BC2 and BC3 blocks natively BC2 and BC3 had CPU decoders (#167) but no native Metal path, so nothing showed that the original 16-byte blocks reach the GPU and decode as the specifications describe. This adds a pitched BcAlphaUpload with the BC1 upload's validation (shared, now measured in 16-byte blocks) and NativeCompute::read_bc_alpha_upload, which places the blocks in BC2_RGBA or BC3_RGBA textures behind the existing BC capability check. The GPU tests cover explicit 4-bit alpha, six- and eight-value interpolated alpha (equal endpoints included), descending, ascending and equal colour endpoints, padded row and slice pitches, two layers and two mips. Texels are compared with the CPU decoders and hand-derived anchors. On an Apple M5 Pro interpolated values lie within 1.14 codes of the exact values, two codes at most from the truncating CPU reference, which sets the tolerance. Uploading BC3 as BC2, BC2 as BC1, or ignoring the row pitch each fails the tests. Refs #168 Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- CHANGELOG.md | 7 + crates/metal/src/compute.rs | 87 ++++-- crates/metal/tests/native/texture_bc_alpha.rs | 287 ++++++++++++++++++ crates/metal/tests/native_compute.rs | 2 + crates/texture/src/lib.rs | 4 +- crates/texture/src/upload.rs | 244 ++++++++++++--- 6 files changed, 572 insertions(+), 59 deletions(-) create mode 100644 crates/metal/tests/native/texture_bc_alpha.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index eb668ca..0801322 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,13 @@ remains unsupported. ### Added +- Added native Metal upload and readback of BC2 and BC3 textures: `xenora-texture` gains a + pitched `BcAlphaUpload` for 16-byte blocks, and `NativeCompute::read_bc_alpha_upload` sends + the original blocks to `BC2_RGBA` or `BC3_RGBA` textures when the device reports BC support. + 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. - 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 fbda896..bc0475c 100644 --- a/crates/metal/src/compute.rs +++ b/crates/metal/src/compute.rs @@ -16,7 +16,7 @@ use objc2_metal::{ MTLResourceOptions, MTLShaderValidation, MTLSize, MTLStorageMode, MTLTexture, MTLTextureDescriptor, MTLTextureUsage, }; -use xenora_texture::{Bc1Upload, TiledBc1}; +use xenora_texture::{Bc1Upload, BcAlphaFormat, BcAlphaUpload, TiledBc1}; #[path = "render.rs"] mod render; @@ -26,12 +26,12 @@ const MAX_GROUPS: usize = 64; const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP; const MAX_SOURCE_BYTES: usize = 64 * 1024; -const BC1_READBACK: &str = r" +const BC_READBACK: &str = r" #include using namespace metal; -kernel void read_bc1(texture2d image [[texture(0)]], - device uint *output [[buffer(1)]], - uint index [[thread_position_in_grid]]) { +kernel void read_bc(texture2d image [[texture(0)]], + device uint *output [[buffer(1)]], + uint index [[thread_position_in_grid]]) { uint width = image.get_width(); uint4 channels = uint4(round(image.read(uint2(index % width, index / width)) * 255.0f)); output[index] = channels.r | (channels.g << 8u) | (channels.b << 16u) | (channels.a << 24u); @@ -184,11 +184,18 @@ impl NativeCompute { let (width, height) = tiled .mip_extent(mip) .map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?; - let pixels = self.validate_bc1_extent(width, height)?; + let pixels = self.validate_bc_extent(width, height, "BC1")?; let blocks = tiled .linearize(layer, mip) .map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?; - self.read_bc1_blocks(&blocks, width.div_ceil(4) * 8, width, height, pixels) + self.read_bc_blocks( + MTLPixelFormat::BC1_RGBA, + &blocks, + width.div_ceil(4) * 8, + width, + height, + pixels, + ) } /// Sample a native Metal RGBA8 texture using a native Metal sampler on Apple Silicon GPU. @@ -269,8 +276,9 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], let level = upload .subresource(layer, mip) .map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?; - let pixels = self.validate_bc1_extent(level.width, level.height)?; - self.read_bc1_blocks( + let pixels = self.validate_bc_extent(level.width, level.height, "BC1")?; + self.read_bc_blocks( + MTLPixelFormat::BC1_RGBA, level.bytes, level.row_pitch, level.width, @@ -279,7 +287,45 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], ) } - fn validate_bc1_extent(&self, width: usize, height: usize) -> Result { + /// Read a selected subresource from a validated pitched BC2 or BC3 upload. + /// + /// The original 16-byte blocks go to a native `BC2_RGBA` or `BC3_RGBA` + /// texture, and the output has the layout of [`Self::read_bc1_upload`]. + /// + /// # Errors + /// + /// Returns an error for an invalid layer or mip, out-of-policy size, + /// unavailable BC compression, or Metal setup or execution failure. + pub fn read_bc_alpha_upload( + &self, + upload: &BcAlphaUpload<'_>, + layer: usize, + mip: u32, + ) -> Result, MetalError> { + let level = upload + .subresource(layer, mip) + .map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?; + let (format, name) = match upload.format() { + BcAlphaFormat::Bc2 => (MTLPixelFormat::BC2_RGBA, "BC2"), + BcAlphaFormat::Bc3 => (MTLPixelFormat::BC3_RGBA, "BC3"), + }; + let pixels = self.validate_bc_extent(level.width, level.height, name)?; + self.read_bc_blocks( + format, + level.bytes, + level.row_pitch, + level.width, + level.height, + pixels, + ) + } + + fn validate_bc_extent( + &self, + width: usize, + height: usize, + name: &str, + ) -> Result { let pixels = width .checked_mul(height) .filter(|pixels| (1..=MAX_GRID_WORDS).contains(pixels)) @@ -287,14 +333,15 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], if !self.device.supportsBCTextureCompression() { return Err(MetalError::new( "supportsBCTextureCompression", - "BC1 is unavailable", + format!("{name} is unavailable"), )); } Ok(pixels) } - fn read_bc1_blocks( + fn read_bc_blocks( &self, + format: MTLPixelFormat, blocks: &[u8], row_pitch: usize, width: usize, @@ -302,14 +349,11 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], pixels: usize, ) -> Result, MetalError> { autoreleasepool(|_| { - // SAFETY: The positive bounded dimensions and supported BC1 format + // SAFETY: The positive bounded dimensions and supported BC format // describe a 2D texture with just its base level. let descriptor = unsafe { MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped( - MTLPixelFormat::BC1_RGBA, - width, - height, - false, + format, width, height, false, ) }; descriptor.setStorageMode(MTLStorageMode::Shared); @@ -318,7 +362,7 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], .device .newTextureWithDescriptor(&descriptor) .ok_or_else(|| { - MetalError::new("newTextureWithDescriptor", "BC1 allocation failed") + MetalError::new("newTextureWithDescriptor", "BC allocation failed") })?; let region = MTLRegion { origin: MTLOrigin { x: 0, y: 0, z: 0 }, @@ -332,7 +376,8 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], let bytes_per_row = if height <= 4 { 0 } else { row_pitch }; // SAFETY: The region spans the whole level, including any partial // edge block. Both callers validate that the input holds all rows - // of complete BC1 blocks at the supplied, block-aligned stride. + // of complete blocks of this format at the supplied, block-aligned + // stride. unsafe { texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow( region, @@ -342,8 +387,8 @@ kernel void sample_rgba8(texture2d tex [[texture(0)]], ); } self.run( - BC1_READBACK, - "read_bc1", + BC_READBACK, + "read_bc", ComputeInput::Texture(&texture, pixels), ) .map(|profile| profile.output) diff --git a/crates/metal/tests/native/texture_bc_alpha.rs b/crates/metal/tests/native/texture_bc_alpha.rs new file mode 100644 index 0000000..b5c8a40 --- /dev/null +++ b/crates/metal/tests/native/texture_bc_alpha.rs @@ -0,0 +1,287 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Native Metal upload and readback of original BC2 and BC3 blocks. +//! +//! Every block below was written for this test. The full-texel reference is +//! the `xenora-texture` CPU decoder; the anchor texels are worked by hand from +//! the Microsoft Direct3D 11 block-compression documentation (BC2, BC3) and +//! the Khronos Data Format Specification 1.3 (S3TC DXT3/DXT5). Apple's GPU +//! decoder is the value under test, so expected and actual values come from +//! different decoders. + +use super::context; +use xenora_texture::{BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc, decode_bc2, decode_bc3}; + +/// 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 +/// 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 +/// 0 and 255 are exact and are pinned by the anchor checks. +const TOLERANCE: u8 = 2; + +/// Bound for anchors against the real-number value of an interpolated code. +const REAL_TOLERANCE: f64 = 1.5; + +fn assert_near(label: &str, actual: u8, real: f64) { + assert!( + (f64::from(actual) - real).abs() <= REAL_TOLERANCE, + "{label}: got {actual}, real value {real:.2}" + ); +} + +const WIDTH: usize = 5; +const HEIGHT: usize = 5; +const ROW_PITCH: usize = 48; +const SLICE_PITCH: usize = 112; + +/// Colour half: two little-endian RGB565 endpoints, then 2-bit indices. +/// Every row of 0xe4 selects palette entries 0, 1, 2, 3 from left to right. +fn colour((first, second): (u16, u16)) -> [u8; 8] { + let [a, b] = first.to_le_bytes(); + let [c, d] = second.to_le_bytes(); + [a, b, c, d, 0xe4, 0xe4, 0xe4, 0xe4] +} + +/// BC3 alpha half whose texel `t` selects palette entry `(t + 6) % 8`, so +/// every row starts with the indices 6 and 7 and a full block uses all eight. +fn bc3_alpha(first: u8, second: u8) -> [u8; 8] { + let bits = (0..16u64).fold(0, |bits, texel| bits | (((texel + 6) % 8) << (3 * texel))); + let i = bits.to_le_bytes(); + [first, second, i[0], i[1], i[2], i[3], i[4], i[5]] +} + +fn block(alpha: [u8; 8], colour: [u8; 8]) -> [u8; 16] { + let mut block = [0; 16]; + block[..8].copy_from_slice(&alpha); + block[8..].copy_from_slice(&colour); + block +} + +// First endpoint greater: red over blue. +const DESCENDING: (u16, u16) = (0xf800, 0x001f); +// First endpoint smaller, with odd channel values that exercise rounding. +const ASCENDING: (u16, u16) = (0x52aa, 0xad55); +// Equal endpoints: BC1 would decode index 3 as transparent black. +const EQUAL: (u16, u16) = (0x07e0, 0x07e0); + +/// White with zero alpha (BC2 nibbles 0; BC3 endpoints 0 and 0) in every +/// padding slot, so a wrong row or slice pitch reads visibly wrong texels. +const PAD: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0]; + +/// Logical blocks of one layer: the 2×2 base-level grid, then mip 1. +type Layer = [[u8; 16]; 5]; + +/// Two layers of a 5×5 texture with two mips. Each subresource has seven +/// physical blocks: rows of two logical blocks plus one padding block, a +/// padding block that closes the slice, and mip 1 uses only its block zero. +fn upload_bytes(layers: [Layer; 2]) -> Vec { + let mut bytes = Vec::new(); + for [b0, b1, b2, b3, small] in layers { + for slot in [b0, b1, PAD, b2, b3, PAD, PAD] { + bytes.extend_from_slice(&slot); + } + for slot in [small, PAD, PAD, PAD, PAD, PAD, PAD] { + bytes.extend_from_slice(&slot); + } + } + assert_eq!(bytes.len(), 2 * 2 * SLICE_PITCH); + 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 { + 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])); + } + } + texels +} + +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 { + 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 + .to_le_bytes() + .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); + } + worst +} + +/// GPU reads of both layers: `[layer][mip]`. +type Reads = [[Vec; 2]; 2]; + +/// Uploads both layers, reads all four subresources on the GPU, compares +/// them with the CPU decoder and returns the reads with the worst difference. +fn read_and_compare( + format: BcAlphaFormat, + decode: fn([u8; 16]) -> [[u8; 4]; 16], + layers: [Layer; 2], +) -> (Reads, u8) { + let bytes = upload_bytes(layers); + let upload = BcAlphaUpload::new( + &bytes, + BcAlphaUploadDesc { + width: WIDTH, + height: HEIGHT, + mips: 2, + layers: 2, + format, + row_pitch: ROW_PITCH, + slice_pitch: SLICE_PITCH, + }, + ) + .unwrap(); + let gpu = context(); + 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 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 expected = reference(&decoded[4..], 1, 2, 2); + worst = worst.max(assert_close(&format!("{label} mip 1"), &small, &expected)); + [base, small] + }); + for (layer, mip) in [(2, 0), (0, 2)] { + assert_eq!( + gpu.read_bc_alpha_upload(&upload, layer, mip) + .unwrap_err() + .operation, + "texture subresource" + ); + } + (reads, worst) +} + +#[test] +fn reads_pitched_bc2_explicit_alpha_across_mips_and_layers() { + // Nibble t in texel t, low nibble first: alpha t * 17. + let ramp = [0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe]; + let reverse = ramp.map(|byte: u8| !byte); + let opaque = [0xff; 8]; + let [descending, ascending, equal] = [DESCENDING, ASCENDING, EQUAL].map(colour); + let (reads, worst) = read_and_compare( + BcAlphaFormat::Bc2, + decode_bc2, + [ + [ + block(ramp, descending), + block(reverse, ascending), + block(opaque, equal), + block(ramp, ascending), + block(reverse, descending), + ], + [ + block(opaque, ascending), + block(ramp, equal), + block(reverse, descending), + block(opaque, descending), + block(ramp, equal), + ], + ], + ); + + // Hand-derived anchors, independent of the CPU decoder. + let base = &reads[0][0]; + // (0, 0): red endpoint, nibble 0. (1, 0): blue endpoint, nibble 1. + assert_eq!(base[0], 0x0000_00ff); + assert_eq!(base[1], 0x11ff_0000); + // (0, 2) is texel 8 of block 0: red endpoint, nibble 8 -> 0x88. + assert_eq!(base[2 * WIDTH], 0x8800_00ff); + // (3, 3) is texel 15 of block 0: nibble 15 -> opaque. + assert_eq!(alpha(base[3 * WIDTH + 3]), 0xff); + // (4, 0) is texel 0 of block 1: reversed ramp, nibble 15. + assert_eq!(alpha(base[4]), 0xff); + // (3, 4) is index 3 of block 2's equal green endpoints: opaque green, + // not BC1's transparent black. + assert_eq!(base[4 * WIDTH + 3], 0xff00_ff00); + // Layer 1 mip 1: green endpoints, ramp nibbles 0, 1, 4, 5. + assert_eq!( + reads[1][1], + [0x0000_ff00, 0x1100_ff00, 0x4400_ff00, 0x5500_ff00] + ); + println!("checked 58 BC2 texels from four subresources, worst channel difference {worst}"); +} + +#[test] +fn reads_pitched_bc3_interpolated_alpha_across_mips_and_layers() { + // First endpoint greater: eight-value palette. + let eight = bc3_alpha(200, 20); + // First endpoint smaller: six-value palette with fixed 0 and 255. + let six = bc3_alpha(20, 200); + // Equal endpoints also select the six-value palette. + let level = bc3_alpha(128, 128); + let [descending, ascending, equal] = [DESCENDING, ASCENDING, EQUAL].map(colour); + let (reads, worst) = read_and_compare( + BcAlphaFormat::Bc3, + decode_bc3, + [ + [ + block(eight, descending), + block(six, ascending), + block(level, equal), + block(eight, ascending), + block(six, descending), + ], + [ + block(six, equal), + block(eight, ascending), + block(level, descending), + block(six, ascending), + block(eight, equal), + ], + ], + ); + + // Hand-derived anchors, independent of the CPU decoder. + let base = &reads[0][0]; + let a = |x: usize, y: usize| alpha(base[y * WIDTH + x]); + // Block 0, eight-value: row 0 holds indices 6, 7, 0, 1, and row 1 + // indices 2, 3, 4, 5, each (k = index - 1) ((7 - k) * 200 + k * 20) / 7. + assert_near("index 6", a(0, 0), (2.0 * 200.0 + 5.0 * 20.0) / 7.0); + assert_near("index 7", a(1, 0), (200.0 + 6.0 * 20.0) / 7.0); + for (x, k) in (0..4).zip(1..) { + let real = f64::from((7 - k) * 200 + k * 20) / 7.0; + assert_near(&format!("index {}", k + 1), a(x, 1), real); + } + // Then the endpoints themselves, exactly; texel (0, 0) is the red endpoint. + assert_eq!([a(2, 0), a(3, 0)], [200, 20]); + assert_eq!(base[0] & 0x00ff_ffff, 0x0000_00ff); + // Block 1, six-value: column 4 holds indices 6, 2, 6, 2. Index 6 is the + // fixed 0 and index 2 is (4 * 20 + 200) / 5 = 56. + assert_eq!([a(4, 0), a(4, 2)], [0, 0]); + assert_near("six-value index 2", a(4, 1), 56.0); + assert_near("six-value index 2", a(4, 3), 56.0); + // Block 2, equal endpoints of 128: row 4 holds indices 6, 7, 0, 1, so the + // six-value mode shows as the fixed 0 and 255. + assert_eq!([a(0, 4), a(1, 4), a(2, 4), a(3, 4)], [0, 255, 128, 128]); + // Mip 1, six-value: indices 6, 7, 2, 3 -> 0, 255, 56, (3 * 20 + 2 * 200) / 5 = 92. + let small: Vec<_> = reads[0][1].iter().copied().map(alpha).collect(); + assert_eq!(small[..2], [0, 255]); + assert_near("six-value index 2", small[2], 56.0); + assert_near("six-value index 3", small[3], 92.0); + println!("checked 58 BC3 texels from four subresources, worst channel difference {worst}"); +} diff --git a/crates/metal/tests/native_compute.rs b/crates/metal/tests/native_compute.rs index 703bcd8..49e38e3 100644 --- a/crates/metal/tests/native_compute.rs +++ b/crates/metal/tests/native_compute.rs @@ -6,6 +6,8 @@ mod guest_buffer; mod offscreen; #[path = "native/texture.rs"] mod texture; +#[path = "native/texture_bc_alpha.rs"] +mod texture_bc_alpha; #[path = "native/texture_sampling.rs"] mod texture_sampling; #[path = "native/translated_render.rs"] diff --git a/crates/texture/src/lib.rs b/crates/texture/src/lib.rs index 8dfd1de..aaef28d 100644 --- a/crates/texture/src/lib.rs +++ b/crates/texture/src/lib.rs @@ -14,7 +14,9 @@ pub use bc::{ decode_bc2, decode_bc3, decode_bc4_snorm, decode_bc4_unorm, decode_bc5_snorm, decode_bc5_unorm, }; pub use sampler::{AddressMode, FilterMode, SamplerDesc, SamplerError, TextureMetadata}; -pub use upload::{Bc1Subresource, Bc1Upload, Bc1UploadDesc}; +pub use upload::{ + Bc1Subresource, Bc1Upload, Bc1UploadDesc, BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc, +}; const BLOCK_BYTES: usize = 8; const TILE_BLOCKS: usize = 2; diff --git a/crates/texture/src/upload.rs b/crates/texture/src/upload.rs index a9e6ade..a66dd27 100644 --- a/crates/texture/src/upload.rs +++ b/crates/texture/src/upload.rs @@ -32,56 +32,153 @@ pub struct Bc1Subresource<'a> { impl<'a> Bc1Upload<'a> { pub fn new(bytes: &'a [u8], desc: Bc1UploadDesc) -> Result { - let max_mips = usize::BITS - desc.width.max(desc.height).leading_zeros(); - if desc.format != 1 - || desc.usage != 1 - || desc.width == 0 - || desc.height == 0 - || desc.layers == 0 - || desc.mips == 0 - || desc.mips > max_mips - { + if desc.format != 1 || desc.usage != 1 { return Err(TextureError::InvalidLayout); } - let (blocks_x, blocks_y) = mip_blocks(desc.width, desc.height, 0); - let tight_row = blocks_x - .checked_mul(BLOCK_BYTES) - .ok_or(TextureError::SizeOverflow)?; - if desc.row_pitch < tight_row || !desc.row_pitch.is_multiple_of(BLOCK_BYTES) { - return Err(TextureError::InvalidLayout); - } - let minimum_slice = desc - .row_pitch - .checked_mul(blocks_y) - .ok_or(TextureError::SizeOverflow)?; - if desc.slice_pitch < minimum_slice || !desc.slice_pitch.is_multiple_of(BLOCK_BYTES) { - return Err(TextureError::InvalidLayout); - } - let size = desc - .slice_pitch - .checked_mul(desc.mips as usize) - .and_then(|size| size.checked_mul(desc.layers)) - .ok_or(TextureError::SizeOverflow)?; - if bytes.len() != size { - return Err(TextureError::InvalidByteLength); - } + Self::layout(desc).validate(bytes.len(), BLOCK_BYTES)?; Ok(Self { bytes, desc }) } pub fn subresource(&self, layer: usize, mip: u32) -> Result, TextureError> { - if layer >= self.desc.layers || mip >= self.desc.mips { + Self::layout(self.desc).subresource(self.bytes, layer, mip) + } + + fn layout(desc: Bc1UploadDesc) -> PitchedLayout { + PitchedLayout { + width: desc.width, + height: desc.height, + mips: desc.mips, + layers: desc.layers, + row_pitch: desc.row_pitch, + slice_pitch: desc.slice_pitch, + } + } +} + +/// A block-compressed format whose 16-byte block holds an alpha half followed +/// by a BC1-style colour half. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BcAlphaFormat { + /// Explicit 4-bit alpha per texel. + Bc2, + /// Interpolated alpha from two 8-bit endpoints and 3-bit indices. + Bc3, +} + +/// A layer-major BC2 or BC3 upload with the same pitch rules as +/// [`Bc1UploadDesc`], measured in 16-byte blocks. +#[derive(Clone, Copy, Debug)] +pub struct BcAlphaUploadDesc { + pub width: usize, + pub height: usize, + pub mips: u32, + pub layers: usize, + pub format: BcAlphaFormat, + pub row_pitch: usize, + pub slice_pitch: usize, +} + +#[derive(Debug)] +pub struct BcAlphaUpload<'a> { + bytes: &'a [u8], + desc: BcAlphaUploadDesc, +} + +impl<'a> BcAlphaUpload<'a> { + /// Size of one BC2 or BC3 block in bytes. + pub const BLOCK_BYTES: usize = 16; + + pub fn new(bytes: &'a [u8], desc: BcAlphaUploadDesc) -> Result { + Self::layout(desc).validate(bytes.len(), Self::BLOCK_BYTES)?; + Ok(Self { bytes, desc }) + } + + pub fn format(&self) -> BcAlphaFormat { + self.desc.format + } + + /// Selects one level; the returned rows hold 16-byte blocks. + pub fn subresource(&self, layer: usize, mip: u32) -> Result, TextureError> { + Self::layout(self.desc).subresource(self.bytes, layer, mip) + } + + fn layout(desc: BcAlphaUploadDesc) -> PitchedLayout { + PitchedLayout { + width: desc.width, + height: desc.height, + mips: desc.mips, + layers: desc.layers, + row_pitch: desc.row_pitch, + slice_pitch: desc.slice_pitch, + } + } +} + +/// Format-independent pitch rules shared by the pitched uploads. +struct PitchedLayout { + width: usize, + height: usize, + mips: u32, + layers: usize, + row_pitch: usize, + slice_pitch: usize, +} + +impl PitchedLayout { + fn validate(&self, len: usize, block_bytes: usize) -> Result<(), TextureError> { + let max_mips = usize::BITS - self.width.max(self.height).leading_zeros(); + if self.width == 0 + || self.height == 0 + || self.layers == 0 + || self.mips == 0 + || self.mips > max_mips + { + return Err(TextureError::InvalidLayout); + } + let (blocks_x, blocks_y) = mip_blocks(self.width, self.height, 0); + let tight_row = blocks_x + .checked_mul(block_bytes) + .ok_or(TextureError::SizeOverflow)?; + if self.row_pitch < tight_row || !self.row_pitch.is_multiple_of(block_bytes) { + return Err(TextureError::InvalidLayout); + } + let minimum_slice = self + .row_pitch + .checked_mul(blocks_y) + .ok_or(TextureError::SizeOverflow)?; + if self.slice_pitch < minimum_slice || !self.slice_pitch.is_multiple_of(block_bytes) { + return Err(TextureError::InvalidLayout); + } + let size = self + .slice_pitch + .checked_mul(self.mips as usize) + .and_then(|size| size.checked_mul(self.layers)) + .ok_or(TextureError::SizeOverflow)?; + if len != size { + return Err(TextureError::InvalidByteLength); + } + Ok(()) + } + + fn subresource<'a>( + &self, + bytes: &'a [u8], + layer: usize, + mip: u32, + ) -> Result, TextureError> { + if layer >= self.layers || mip >= self.mips { return Err(TextureError::OutOfBounds); } // Construction proved that the complete array fits in the source span. - let offset = (layer * self.desc.mips as usize + mip as usize) * self.desc.slice_pitch; - let width = (self.desc.width >> mip).max(1); - let height = (self.desc.height >> mip).max(1); + let offset = (layer * self.mips as usize + mip as usize) * self.slice_pitch; + let width = (self.width >> mip).max(1); + let height = (self.height >> mip).max(1); let rows = height.div_ceil(4); Ok(Bc1Subresource { - bytes: &self.bytes[offset..offset + rows * self.desc.row_pitch], + bytes: &bytes[offset..offset + rows * self.row_pitch], width, height, - row_pitch: self.desc.row_pitch, + row_pitch: self.row_pitch, }) } } @@ -182,4 +279,77 @@ mod tests { ); } } + + const ALPHA_DESC: BcAlphaUploadDesc = BcAlphaUploadDesc { + width: 5, + height: 5, + mips: 2, + layers: 2, + format: BcAlphaFormat::Bc3, + row_pitch: 48, + slice_pitch: 112, + }; + + #[test] + fn selects_bc_alpha_subresources_in_sixteen_byte_blocks() { + let mut bytes = [0; 448]; + // Layer 1 starts at 224; its base row 1, block 1 is at 224 + 48 + 16. + bytes[288..304].fill(0x5c); + bytes[336] = 0xa7; // Layer 1, mip 1, block 0. + let upload = BcAlphaUpload::new(&bytes, ALPHA_DESC).unwrap(); + assert_eq!(upload.format(), BcAlphaFormat::Bc3); + let base = upload.subresource(1, 0).unwrap(); + assert_eq!((base.width, base.height, base.row_pitch), (5, 5, 48)); + assert_eq!(base.bytes.len(), 96); + assert_eq!(base.bytes[64..80], [0x5c; 16]); + let small = upload.subresource(1, 1).unwrap(); + assert_eq!((small.width, small.height, small.bytes.len()), (2, 2, 48)); + assert_eq!(small.bytes[0], 0xa7); + assert_eq!( + upload.subresource(2, 0).unwrap_err(), + TextureError::OutOfBounds + ); + assert_eq!( + upload.subresource(0, 2).unwrap_err(), + TextureError::OutOfBounds + ); + } + + #[test] + fn rejects_bc1_pitches_for_sixteen_byte_blocks() { + let bytes = [0; 448]; + // Each pitch is a valid BC1 multiple of 8 but not of 16, or is + // shorter than two 16-byte blocks. + for desc in [ + BcAlphaUploadDesc { + row_pitch: 24, + ..ALPHA_DESC + }, + BcAlphaUploadDesc { + row_pitch: 40, + ..ALPHA_DESC + }, + BcAlphaUploadDesc { + slice_pitch: 104, + ..ALPHA_DESC + }, + BcAlphaUploadDesc { + slice_pitch: 80, + ..ALPHA_DESC + }, + BcAlphaUploadDesc { + mips: 4, + ..ALPHA_DESC + }, + ] { + assert_eq!( + BcAlphaUpload::new(&bytes, desc).unwrap_err(), + TextureError::InvalidLayout + ); + } + assert_eq!( + BcAlphaUpload::new(&bytes[..447], ALPHA_DESC).unwrap_err(), + TextureError::InvalidByteLength + ); + } }