diff --git a/crates/dds/src/bptc.rs b/crates/dds/src/bptc.rs new file mode 100644 index 000000000..e6a5f317d --- /dev/null +++ b/crates/dds/src/bptc.rs @@ -0,0 +1,1152 @@ +//! BPTC blocks: BC7 (8-bit RGBA) and BC6H (half-float RGB), written from the Khronos Data Format +//! Specification's "BPTC Compressed Texture Image Formats" section. Each 16-byte block holds 4×4 +//! texels, row by row. Tables are the specification's, numbered as it numbers them. + +/// A block's bits, read from the lowest up. +struct Bits { + value: u128, + pos: u32, +} + +impl Bits { + fn new(block: &[u8; 16]) -> Self { + Self { value: u128::from_le_bytes(*block), pos: 0 } + } + + /// The next `n` bits (at most 16), as a number. + fn take(&mut self, n: u8) -> u32 { + let n = u32::from(n); + let mask = !u128::MAX.checked_shl(n).unwrap_or(0); + let out = self.value.checked_shr(self.pos).unwrap_or(0) & mask; + self.pos = self.pos.saturating_add(n); + out as u32 + } +} + +/// Interpolation weights by index bits (Table 119). +const WEIGHTS_2: [i32; 4] = [0, 21, 43, 64]; +const WEIGHTS_3: [i32; 8] = [0, 9, 18, 27, 37, 46, 55, 64]; +const WEIGHTS_4: [i32; 16] = [0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64]; + +fn weight(index_bits: u8, index: u32) -> i32 { + let table: &[i32] = match index_bits { + 2 => &WEIGHTS_2, + 3 => &WEIGHTS_3, + _ => &WEIGHTS_4, + }; + table.get(index as usize).copied().unwrap_or(0) +} + +/// Equation 2: a value between two endpoints. +fn interpolate(e0: i32, e1: i32, weight: i32) -> i32 { + ((64 - weight) * e0 + weight * e1 + 32) >> 6 +} + +/// Which subset texel `i` is in, for a block with `subsets` subsets and partition `partition`. +fn subset(subsets: u8, partition: usize, i: usize) -> usize { + let part = match subsets { + 2 => u32::from(PARTITIONS_2.get(partition).copied().unwrap_or(0)) >> i & 1, + 3 => PARTITIONS_3.get(partition).copied().unwrap_or(0) >> (2 * i) & 3, + _ => 0, + }; + part as usize +} + +/// Whether texel `i` is an anchor (its index is stored with one bit fewer). +fn anchor(subsets: u8, partition: usize, i: usize) -> bool { + let at = |table: &[u8; 64]| table.get(partition).is_some_and(|a| usize::from(*a) == i); + i == 0 + || match subsets { + 2 => at(&ANCHOR_2), + 3 => at(&ANCHOR_3_SECOND) || at(&ANCHOR_3_THIRD), + _ => false, + } +} + +/// The 16 indices of a block, each `bits` wide (anchors one fewer). +fn indices(r: &mut Bits, bits: u8, subsets: u8, partition: usize) -> [u32; 16] { + let mut out = [0; 16]; + for (i, x) in out.iter_mut().enumerate() { + *x = r.take(bits - u8::from(anchor(subsets, partition, i))); + } + out +} + +/// BC7's modes (Table 109): subsets, partition bits, rotation bits, index selection bits, colour +/// bits, alpha bits, per-endpoint P-bits, shared P-bits, index bits, secondary index bits. +const BC7_MODES: [[u8; 10]; 8] = [ + [3, 4, 0, 0, 4, 0, 1, 0, 3, 0], + [2, 6, 0, 0, 6, 0, 0, 1, 3, 0], + [3, 6, 0, 0, 5, 0, 0, 0, 2, 0], + [2, 6, 0, 0, 7, 0, 1, 0, 2, 0], + [1, 0, 2, 1, 5, 6, 0, 0, 2, 3], + [1, 0, 2, 0, 7, 8, 0, 0, 2, 2], + [1, 0, 0, 0, 7, 7, 1, 0, 4, 0], + [2, 6, 0, 0, 5, 5, 1, 0, 2, 0], +]; + +/// The 16 RGBA texels of a BC7 block. +pub fn bc7(block: &[u8; 16]) -> [[u8; 4]; 16] { + let mode = block[0].trailing_zeros(); + // A low byte of 0 is reserved: every channel of every texel is 0. + let Some(&[subsets, partition_bits, rotation_bits, selection_bits, colour_bits, alpha_bits, endpoint_p, shared_p, index_bits, index2_bits]) = + BC7_MODES.get(mode as usize) + else { + return [[0; 4]; 16]; + }; + let mut r = Bits::new(block); + r.pos = mode + 1; + let partition = r.take(partition_bits) as usize; + let rotation = r.take(rotation_bits); + let swapped = r.take(selection_bits) == 1; + let ends = usize::from(subsets) * 2; + // Endpoints: every endpoint's red, then green, blue and alpha; then the P-bits. + let mut raw = [[0u32; 4]; 6]; + for channel in 0..4 { + let bits = if channel < 3 { colour_bits } else { alpha_bits }; + for e in raw.iter_mut().take(ends) { + e[channel] = r.take(bits); + } + } + let mut p = [0u32; 6]; + if endpoint_p == 1 { + for x in p.iter_mut().take(ends) { + *x = r.take(1); + } + } + if shared_p == 1 { + for pair in p.chunks_mut(2).take(usize::from(subsets)) { + pair.fill(r.take(1)); + } + } + let has_p = endpoint_p + shared_p > 0; + let endpoints: [[i32; 4]; 6] = std::array::from_fn(|e| { + std::array::from_fn(|channel| { + let bits = u32::from(if channel < 3 { colour_bits } else { alpha_bits }); + let (v, bits) = match (raw[e][channel], bits) { + (_, 0) => return 255, + (v, bits) if has_p => (v << 1 | p[e], bits + 1), + other => other, + }; + // The stored bits are a byte's top bits; its top bits repeat into the rest. + (v << (8 - bits) | v >> (2 * bits - 8)) as i32 + }) + }); + let primary = indices(&mut r, index_bits, subsets, partition); + let secondary = if index2_bits > 0 { indices(&mut r, index2_bits, 1, 0) } else { [0; 16] }; + let (colour, colour_index_bits) = if swapped { (secondary, index2_bits) } else { (primary, index_bits) }; + let (alpha, alpha_index_bits) = if index2_bits > 0 && !swapped { (secondary, index2_bits) } else { (primary, index_bits) }; + std::array::from_fn(|i| { + let s = subset(subsets, partition, i); + let (e0, e1) = (endpoints.get(2 * s).copied().unwrap_or_default(), endpoints.get(2 * s + 1).copied().unwrap_or_default()); + let (wc, wa) = (weight(colour_index_bits, colour[i]), weight(alpha_index_bits, alpha[i])); + let mut px: [u8; 4] = std::array::from_fn(|c| interpolate(e0[c], e1[c], if c < 3 { wc } else { wa }) as u8); + if (1..=3).contains(&rotation) { + px.swap(rotation as usize - 1, 3); + } + px + }) +} + +// BC6H's fields: endpoint `e`'s red, green and blue are fields `3e`, `3e + 1` and `3e + 2`. +const R0: u8 = 0; +const G0: u8 = 1; +const B0: u8 = 2; +const R1: u8 = 3; +const G1: u8 = 4; +const B1: u8 = 5; +const R2: u8 = 6; +const G2: u8 = 7; +const B2: u8 = 8; +const R3: u8 = 9; +const G3: u8 = 10; +const B3: u8 = 11; +/// The partition number. +const PB: u8 = 12; + +/// A BC6H mode (Tables 121 and 122). +struct Bc6hMode { + id: u8, + /// Endpoints after the first are stored as differences from it. + transformed: bool, + subsets: u8, + endpoint_bits: u8, + /// Red, green and blue bits of the endpoints after the first. + delta_bits: [u8; 3], + /// After the mode bits, in block order: `(field, a, b)` is the spec's `field a..b`, so the + /// next `|a - b| + 1` bits of the block go to the field's bits `b`, `b ± 1`, …, `a`. + fields: &'static [(u8, u8, u8)], +} + +fn sign_extend(v: i32, bits: u8) -> i32 { + let shift = 32 - u32::from(bits); + (v << shift) >> shift +} + +/// An endpoint value stretched to 16 bits (the unquantization pseudocode). +fn unquantize(x: i32, bits: u8, signed: bool) -> i32 { + let n = i32::from(bits); + if !signed { + return match x { + _ if n >= 15 => x, + 0 => 0, + _ if x == (1 << n) - 1 => 0xffff, + _ => ((x << 15) + 0x4000) >> (n - 1), + }; + } + if n >= 16 { + return x; + } + let magnitude = match x.abs() { + 0 => 0, + a if a >= (1 << (n - 1)) - 1 => 0x7fff, + a => ((a << 15) + 0x4000) >> (n - 1), + }; + if x < 0 { -magnitude } else { magnitude } +} + +/// An interpolated value as a half float's bits. +fn finish(i: i32, signed: bool) -> u16 { + match (signed, i < 0) { + (false, _) => ((i * 31) >> 6) as u16, + (true, true) => (((-i * 31) >> 5) | 0x8000) as u16, + (true, false) => ((i * 31) >> 5) as u16, + } +} + +/// The 16 RGB texels of a BC6H block as half floats' bits; a reserved mode gives black. +fn bc6h_halves(block: &[u8; 16], signed: bool) -> [[u16; 3]; 16] { + let mut r = Bits::new(block); + let id = match r.take(2) { + low @ 0..=1 => low, + low => low | r.take(3) << 2, + }; + let Some(mode) = BC6H_MODES.iter().find(|m| u32::from(m.id) == id) else { + return [[0; 3]; 16]; + }; + let mut fields = [0i32; 13]; + for &(field, a, b) in mode.fields { + for k in 0..=a.abs_diff(b) { + let bit = if a >= b { b + k } else { b - k }; + if let Some(f) = fields.get_mut(usize::from(field)) { + *f |= (r.take(1) as i32) << bit; + } + } + } + let bits = mode.endpoint_bits; + let ends = usize::from(mode.subsets) * 2; + let mut endpoints = [[0i32; 3]; 4]; + for (e, endpoint) in endpoints.iter_mut().enumerate().take(ends) { + for (c, v) in endpoint.iter_mut().enumerate() { + let (base, stored) = (fields[c], fields[3 * e + c]); + let x = match e { + 0 => stored, + _ if mode.transformed => (base + sign_extend(stored, mode.delta_bits[c])) & ((1 << bits) - 1), + _ => stored, + }; + *v = unquantize(if signed { sign_extend(x, bits) } else { x }, bits, signed); + } + } + let partition = fields[usize::from(PB)] as usize; + let index_bits = if mode.subsets == 2 { 3 } else { 4 }; + let index = indices(&mut r, index_bits, mode.subsets, partition); + std::array::from_fn(|i| { + let s = subset(mode.subsets, partition, i); + let (e0, e1) = (endpoints.get(2 * s).copied().unwrap_or_default(), endpoints.get(2 * s + 1).copied().unwrap_or_default()); + let w = weight(index_bits, index[i]); + std::array::from_fn(|c| finish(interpolate(e0[c], e1[c], w), signed)) + }) +} + +/// A half float's value. +pub fn half(h: u16) -> f32 { + let sign = if h & 0x8000 == 0 { 1.0 } else { -1.0 }; + let (exponent, mantissa) = (i32::from(h >> 10 & 31), f32::from(h & 1023)); + sign * match exponent { + 0 => mantissa * 2f32.powi(-24), + 31 if mantissa != 0.0 => f32::NAN, + 31 => f32::INFINITY, + e => (1024.0 + mantissa) * 2f32.powi(e - 25), + } +} + +/// A linear light value as an 8-bit sRGB value; 0..1 is kept, brighter and negative values clip. +pub fn srgb8(v: f32) -> u8 { + let v = v.clamp(0.0, 1.0); + let s = if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + (s * 255.0 + 0.5) as u8 +} + +/// The 16 texels of a BC6H block, tone-mapped to 8-bit sRGB (opaque). +pub fn bc6h(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] { + bc6h_halves(block, signed).map(|[r, g, b]| [srgb8(half(r)), srgb8(half(g)), srgb8(half(b)), 255]) +} + +/// Two-subset partitions (Table 114): bit `i` is texel `i`'s subset. +const PARTITIONS_2: [u16; 64] = [ + 0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80, 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000, 0xf710, 0x008e, + 0x7100, 0x08ce, 0x008c, 0x7310, 0x3100, 0x8cce, 0x088c, 0x3110, 0x6666, 0x366c, 0x17e8, 0x0ff0, 0x718e, 0x399c, 0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, + 0x3c3c, 0x55aa, 0x9696, 0xa55a, 0x73ce, 0x13c8, 0x324c, 0x3bdc, 0x6996, 0xc33c, 0x9966, 0x0660, 0x0272, 0x04e4, 0x4e40, 0x2720, 0xc936, 0x936c, + 0x39c6, 0x639c, 0x9336, 0x9cc6, 0x817e, 0xe718, 0xccf0, 0x0fcc, 0x7744, 0xee22, +]; + +/// Three-subset partitions (Table 115): bits `2i` and `2i + 1` are texel `i`'s subset. +const PARTITIONS_3: [u32; 64] = [ + 0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8, 0xa5a50000, 0xa0a05050, 0x5555a0a0, 0x5a5a5050, 0xaa550000, 0xaa555500, 0xaaaa5500, 0x90909090, + 0x94949494, 0xa4a4a4a4, 0xa9a59450, 0x2a0a4250, 0xa5945040, 0x0a425054, 0xa5a5a500, 0x55a0a0a0, 0xa8a85454, 0x6a6a4040, 0xa4a45000, 0x1a1a0500, + 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400, 0xa08585a0, 0xaa821414, 0x50a4a450, 0x6a5a0200, 0xa9a58000, 0x5090a0a8, 0xa8a09050, 0x24242424, + 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50, 0x500aa550, 0xaaaa4444, 0x66660000, 0xa5a0a5a0, 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600, + 0xaa444444, 0x54a854a8, 0x95809580, 0x96969600, 0xa85454a8, 0x80959580, 0xaa141414, 0x96960000, 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000, + 0x40804080, 0xa9a8a9a8, 0xaaaaaa44, 0x2a4a5254, +]; + +/// The anchor texel of the second subset of two-subset partitions (Table 118). +const ANCHOR_2: [u8; 64] = [ + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, 2, 2, 8, 8, 2, 2, 15, 15, 6, 8, 2, 8, 15, 15, 2, + 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15, +]; + +/// The anchor texels of the second and third subsets of three-subset partitions (Tables 116, 117). +const ANCHOR_3_SECOND: [u8; 64] = [ + 3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, 15, 15, 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, + 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3, +]; + +const ANCHOR_3_THIRD: [u8; 64] = [ + 15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, 10, 15, 15, 10, 8, 15, 3, 15, 10, 10, 8, 9, 10, + 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8, +]; + +/// BC6H's modes, in the order of Table 121. +const BC6H_MODES: [Bc6hMode; 14] = [ + Bc6hMode { + id: 0, + transformed: true, + subsets: 2, + endpoint_bits: 10, + delta_bits: [5, 5, 5], + fields: &[ + (G2, 4, 4), + (B2, 4, 4), + (B3, 4, 4), + (R0, 9, 0), + (G0, 9, 0), + (B0, 9, 0), + (R1, 4, 0), + (G3, 4, 4), + (G2, 3, 0), + (G1, 4, 0), + (B3, 0, 0), + (G3, 3, 0), + (B1, 4, 0), + (B3, 1, 1), + (B2, 3, 0), + (R2, 4, 0), + (B3, 2, 2), + (R3, 4, 0), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 1, + transformed: true, + subsets: 2, + endpoint_bits: 7, + delta_bits: [6, 6, 6], + fields: &[ + (G2, 5, 5), + (G3, 4, 4), + (G3, 5, 5), + (R0, 6, 0), + (B3, 0, 0), + (B3, 1, 1), + (B2, 4, 4), + (G0, 6, 0), + (B2, 5, 5), + (B3, 2, 2), + (G2, 4, 4), + (B0, 6, 0), + (B3, 3, 3), + (B3, 5, 5), + (B3, 4, 4), + (R1, 5, 0), + (G2, 3, 0), + (G1, 5, 0), + (G3, 3, 0), + (B1, 5, 0), + (B2, 3, 0), + (R2, 5, 0), + (R3, 5, 0), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 2, + transformed: true, + subsets: 2, + endpoint_bits: 11, + delta_bits: [5, 4, 4], + fields: &[ + (R0, 9, 0), + (G0, 9, 0), + (B0, 9, 0), + (R1, 4, 0), + (R0, 10, 10), + (G2, 3, 0), + (G1, 3, 0), + (G0, 10, 10), + (B3, 0, 0), + (G3, 3, 0), + (B1, 3, 0), + (B0, 10, 10), + (B3, 1, 1), + (B2, 3, 0), + (R2, 4, 0), + (B3, 2, 2), + (R3, 4, 0), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 6, + transformed: true, + subsets: 2, + endpoint_bits: 11, + delta_bits: [4, 5, 4], + fields: &[ + (R0, 9, 0), + (G0, 9, 0), + (B0, 9, 0), + (R1, 3, 0), + (R0, 10, 10), + (G3, 4, 4), + (G2, 3, 0), + (G1, 4, 0), + (G0, 10, 10), + (G3, 3, 0), + (B1, 3, 0), + (B0, 10, 10), + (B3, 1, 1), + (B2, 3, 0), + (R2, 3, 0), + (B3, 0, 0), + (B3, 2, 2), + (R3, 3, 0), + (G2, 4, 4), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 10, + transformed: true, + subsets: 2, + endpoint_bits: 11, + delta_bits: [4, 4, 5], + fields: &[ + (R0, 9, 0), + (G0, 9, 0), + (B0, 9, 0), + (R1, 3, 0), + (R0, 10, 10), + (B2, 4, 4), + (G2, 3, 0), + (G1, 3, 0), + (G0, 10, 10), + (B3, 0, 0), + (G3, 3, 0), + (B1, 4, 0), + (B0, 10, 10), + (B2, 3, 0), + (R2, 3, 0), + (B3, 1, 1), + (B3, 2, 2), + (R3, 3, 0), + (B3, 4, 4), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 14, + transformed: true, + subsets: 2, + endpoint_bits: 9, + delta_bits: [5, 5, 5], + fields: &[ + (R0, 8, 0), + (B2, 4, 4), + (G0, 8, 0), + (G2, 4, 4), + (B0, 8, 0), + (B3, 4, 4), + (R1, 4, 0), + (G3, 4, 4), + (G2, 3, 0), + (G1, 4, 0), + (B3, 0, 0), + (G3, 3, 0), + (B1, 4, 0), + (B3, 1, 1), + (B2, 3, 0), + (R2, 4, 0), + (B3, 2, 2), + (R3, 4, 0), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 18, + transformed: true, + subsets: 2, + endpoint_bits: 8, + delta_bits: [6, 5, 5], + fields: &[ + (R0, 7, 0), + (G3, 4, 4), + (B2, 4, 4), + (G0, 7, 0), + (B3, 2, 2), + (G2, 4, 4), + (B0, 7, 0), + (B3, 3, 3), + (B3, 4, 4), + (R1, 5, 0), + (G2, 3, 0), + (G1, 4, 0), + (B3, 0, 0), + (G3, 3, 0), + (B1, 4, 0), + (B3, 1, 1), + (B2, 3, 0), + (R2, 5, 0), + (R3, 5, 0), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 22, + transformed: true, + subsets: 2, + endpoint_bits: 8, + delta_bits: [5, 6, 5], + fields: &[ + (R0, 7, 0), + (B3, 0, 0), + (B2, 4, 4), + (G0, 7, 0), + (G2, 5, 5), + (G2, 4, 4), + (B0, 7, 0), + (G3, 5, 5), + (B3, 4, 4), + (R1, 4, 0), + (G3, 4, 4), + (G2, 3, 0), + (G1, 5, 0), + (G3, 3, 0), + (B1, 4, 0), + (B3, 1, 1), + (B2, 3, 0), + (R2, 4, 0), + (B3, 2, 2), + (R3, 4, 0), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 26, + transformed: true, + subsets: 2, + endpoint_bits: 8, + delta_bits: [5, 5, 6], + fields: &[ + (R0, 7, 0), + (B3, 1, 1), + (B2, 4, 4), + (G0, 7, 0), + (B2, 5, 5), + (G2, 4, 4), + (B0, 7, 0), + (B3, 5, 5), + (B3, 4, 4), + (R1, 4, 0), + (G3, 4, 4), + (G2, 3, 0), + (G1, 4, 0), + (B3, 0, 0), + (G3, 3, 0), + (B1, 5, 0), + (B2, 3, 0), + (R2, 4, 0), + (B3, 2, 2), + (R3, 4, 0), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 30, + transformed: false, + subsets: 2, + endpoint_bits: 6, + delta_bits: [6, 6, 6], + fields: &[ + (R0, 5, 0), + (G3, 4, 4), + (B3, 0, 0), + (B3, 1, 1), + (B2, 4, 4), + (G0, 5, 0), + (G2, 5, 5), + (B2, 5, 5), + (B3, 2, 2), + (G2, 4, 4), + (B0, 5, 0), + (G3, 5, 5), + (B3, 3, 3), + (B3, 5, 5), + (B3, 4, 4), + (R1, 5, 0), + (G2, 3, 0), + (G1, 5, 0), + (G3, 3, 0), + (B1, 5, 0), + (B2, 3, 0), + (R2, 5, 0), + (R3, 5, 0), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 3, + transformed: false, + subsets: 1, + endpoint_bits: 10, + delta_bits: [10, 10, 10], + fields: &[(R0, 9, 0), (G0, 9, 0), (B0, 9, 0), (R1, 9, 0), (G1, 9, 0), (B1, 9, 0)], + }, + Bc6hMode { + id: 7, + transformed: true, + subsets: 1, + endpoint_bits: 11, + delta_bits: [9, 9, 9], + fields: &[(R0, 9, 0), (G0, 9, 0), (B0, 9, 0), (R1, 8, 0), (R0, 10, 10), (G1, 8, 0), (G0, 10, 10), (B1, 8, 0), (B0, 10, 10)], + }, + Bc6hMode { + id: 11, + transformed: true, + subsets: 1, + endpoint_bits: 12, + delta_bits: [8, 8, 8], + fields: &[(R0, 9, 0), (G0, 9, 0), (B0, 9, 0), (R1, 7, 0), (R0, 10, 11), (G1, 7, 0), (G0, 10, 11), (B1, 7, 0), (B0, 10, 11)], + }, + Bc6hMode { + id: 15, + transformed: true, + subsets: 1, + endpoint_bits: 16, + delta_bits: [4, 4, 4], + fields: &[(R0, 9, 0), (G0, 9, 0), (B0, 9, 0), (R1, 3, 0), (R0, 10, 15), (G1, 3, 0), (G0, 10, 15), (B1, 3, 0), (B0, 10, 15)], + }, +]; + +#[cfg(test)] +mod tests { + use super::{B0, B1, B2, B3, BC6H_MODES, G0, G1, G2, G3, PB, R0, R1, R2, R3, bc6h, bc6h_halves, bc7, half, srgb8}; + + /// Pack `(value, bits)` fields into a block from the lowest bit up. + fn pack(fields: &[(u32, u32)]) -> [u8; 16] { + let (mut v, mut pos) = (0u128, 0); + for &(x, n) in fields { + assert!(u128::from(x) < 1 << n, "{x} doesn't fit in {n} bits"); + v |= u128::from(x) << pos; + pos += n; + } + assert_eq!(pos, 128, "a block is 128 bits"); + v.to_le_bytes() + } + + /// The mode bits of BC7 mode `m`, then `fields`. + fn bc7_block(m: u32, fields: &[(u32, u32)]) -> [u8; 16] { + pack(&[&[(1 << m, m + 1)], fields].concat()) + } + + /// One `bits`-wide field per value. + fn each(values: &[u32], bits: u32) -> Vec<(u32, u32)> { + values.iter().map(|v| (*v, bits)).collect() + } + + /// 16 indices, `bits` wide, one bit fewer at the `anchors`. + fn texel_indices(values: [u32; 16], bits: u32, anchors: &[usize]) -> Vec<(u32, u32)> { + values.iter().enumerate().map(|(i, v)| (*v, bits - u32::from(anchors.contains(&i)))).collect() + } + + fn index_set(set: &[(usize, u32)]) -> [u32; 16] { + let mut out = [0; 16]; + for (i, v) in set { + out[*i] = *v; + } + out + } + + /// Grey endpoints: the same value in red, green and blue. + fn grey(values: &[u32], bits: u32) -> Vec<(u32, u32)> { + [each(values, bits), each(values, bits), each(values, bits)].concat() + } + + // Each case's colours are worked out from the specification by hand: endpoint bits (and the + // P-bit) are a byte's top bits with its top bits repeated below, and a texel is + // ((64 - w) × e0 + w × e1 + 32) >> 6 with the weight w of its index. + + #[test] + fn bc7_mode_0_three_subsets_with_endpoint_p_bits() { + // Partition 0 of three subsets: rows 0011 / 0011 / 0221 / 2222; anchors 0, 3 and 15. + // Endpoints (4 bits + P-bit): 15+1 → 255, 0 → 0, 8+0 → 132, 8+1 → 140, 2+1 → 41, 4+0 → 66. + let idx = index_set(&[(1, 7), (2, 4), (3, 3), (9, 5), (15, 3)]); + let b = bc7_block( + 0, + &[&[(0, 4)], &grey(&[15, 0, 8, 8, 2, 4], 4)[..], &each(&[1, 0, 0, 1, 1, 0], 1), &texel_indices(idx, 3, &[0, 3, 15])].concat(), + ); + let px = bc7(&b); + let g = |v: u8| [v, v, v, 255]; + assert_eq!(px[0], g(255)); + assert_eq!(px[1], g(0), "index 7: the second endpoint"); + assert_eq!(px[2], g(137), "subset 1, weight 37: (27×132 + 37×140 + 32) >> 6"); + assert_eq!(px[3], g(135), "subset 1's anchor, weight 27"); + assert_eq!(px[9], g(59), "subset 2, weight 46: (18×41 + 46×66 + 32) >> 6"); + assert_eq!(px[15], g(52), "subset 2's anchor, weight 27"); + assert_eq!((px[8], px[10], px[11]), (g(255), g(41), g(132))); + } + + #[test] + fn bc7_mode_1_shared_p_bits() { + // Partition 13: texels 0-7 subset 0, 8-15 subset 1 (anchor 15). Endpoints (6 bits + + // shared P-bit): 63+1 → 255, 0+1 → 2; 32+0 → 129, 16+0 → 64. + let idx = index_set(&[(1, 7), (8, 2), (15, 3)]); + let b = bc7_block(1, &[&[(13, 6)], &grey(&[63, 0, 32, 16], 6)[..], &each(&[1, 0], 1), &texel_indices(idx, 3, &[0, 15])].concat()); + let px = bc7(&b); + let g = |v: u8| [v, v, v, 255]; + assert_eq!((px[0], px[1], px[2]), (g(255), g(2), g(255))); + assert_eq!(px[8], g(111), "weight 18: (46×129 + 18×64 + 32) >> 6"); + assert_eq!(px[15], g(102), "anchor, weight 27"); + assert_eq!(px[9], g(129)); + } + + #[test] + fn bc7_mode_2_matches_the_specifications_example() { + // Partition 6 of three subsets: rows 0022 / 0022 / 1111 / 1111; anchors 0, 15 and 3 (the + // specification's worked example: texel 9 is subset 1, its index at bits 115-116). + // Endpoints (5 bits): 31 → 255, 0, 10 → 82, 20 → 165, 1 → 8, 30 → 247. + let idx = index_set(&[(0, 1), (2, 2), (3, 1), (9, 3), (15, 1)]); + let b = bc7_block(2, &[&[(6, 6)], &grey(&[31, 0, 10, 20, 1, 30], 5)[..], &texel_indices(idx, 2, &[0, 15, 3])].concat()); + assert_eq!(u128::from_le_bytes(b) >> 115 & 3, 3, "texel 9's index where the specification says"); + let px = bc7(&b); + let g = |v: u8| [v, v, v, 255]; + assert_eq!(px[0], g(171), "weight 21: (43×255 + 32) >> 6"); + assert_eq!(px[2], g(169), "subset 2, weight 43: (21×8 + 43×247 + 32) >> 6"); + assert_eq!(px[3], g(86), "subset 2's anchor, weight 21"); + assert_eq!(px[9], g(165)); + assert_eq!(px[15], g(109), "subset 1's anchor, weight 21: (43×82 + 21×165 + 32) >> 6"); + assert_eq!((px[1], px[8], px[6]), (g(255), g(82), g(8))); + } + + #[test] + fn bc7_mode_3_seven_bit_endpoints() { + // Partition 0: columns 2-3 are subset 1 (anchor 15). Endpoints (7 bits + P-bit): + // 100+1 → 201, 10+0 → 20, 127+1 → 255, 0+0 → 0. + let idx = index_set(&[(0, 1), (1, 2), (2, 3), (15, 1)]); + let b = bc7_block(3, &[&[(0, 6)], &grey(&[100, 10, 127, 0], 7)[..], &each(&[1, 0, 1, 0], 1), &texel_indices(idx, 2, &[0, 15])].concat()); + let px = bc7(&b); + let g = |v: u8| [v, v, v, 255]; + assert_eq!(px[0], g(142), "weight 21: (43×201 + 21×20 + 32) >> 6"); + assert_eq!(px[1], g(79), "weight 43"); + assert_eq!(px[2], g(0)); + assert_eq!(px[15], g(171)); + assert_eq!((px[3], px[4]), (g(255), g(201))); + } + + #[test] + fn bc7_mode_4_rotation_and_index_selection() { + // Rotation 1 swaps alpha and red; the selection bit takes colour from the 3-bit indices + // and alpha from the 2-bit ones. Red 31 → 255 to 0, green 0 to 255, blue 16 → 132, + // alpha (6 bits) 63 → 255 to 0. + let colour = index_set(&[(0, 3), (1, 7)]); + let alpha = index_set(&[(0, 1)]); + let ends = [each(&[31, 0, 0, 31, 16, 16], 5), each(&[63, 0], 6)].concat(); + let b = bc7_block(4, &[&[(1, 2), (1, 1)], &ends[..], &texel_indices(alpha, 2, &[0]), &texel_indices(colour, 3, &[0])].concat()); + let px = bc7(&b); + // Before the swap: red (37×255 + 32) >> 6 = 147, green 108, blue 132, alpha 171. + assert_eq!(px[0], [171, 108, 132, 147]); + assert_eq!(px[1], [255, 255, 132, 0]); + assert_eq!(px[2], [255, 0, 132, 255]); + } + + #[test] + fn bc7_mode_5_separate_alpha_indices() { + // Red 127 → 255 to 0, green 64 → 129, blue 0 to 255; alpha (8 bits) 200 to 100. + let colour = index_set(&[(0, 1), (5, 2)]); + let alpha = index_set(&[(0, 1), (5, 3)]); + let ends = [each(&[127, 0, 64, 64, 0, 127], 7), each(&[200, 100], 8)].concat(); + let b = bc7_block(5, &[&[(0, 2)], &ends[..], &texel_indices(colour, 2, &[0]), &texel_indices(alpha, 2, &[0])].concat()); + let px = bc7(&b); + assert_eq!(px[0], [171, 129, 84, 167], "weight 21 for colour and alpha: (43×200 + 21×100 + 32) >> 6"); + assert_eq!(px[5], [84, 129, 171, 100]); + assert_eq!(px[1], [255, 129, 0, 200]); + } + + #[test] + fn bc7_mode_6_four_bit_indices() { + // Endpoints (7 bits + P-bit) in every channel: [255, 1, 129, 255] and [0, 254, 64, 100]. + let idx = index_set(&[(0, 7), (1, 15), (2, 8)]); + let ends = each(&[127, 0, 0, 127, 64, 32, 127, 50], 7); + let b = bc7_block(6, &[&ends[..], &each(&[1, 0], 1), &texel_indices(idx, 4, &[0])].concat()); + let px = bc7(&b); + assert_eq!(px[0], [135, 120, 99, 182], "the anchor's largest index, 7: weight 30"); + assert_eq!(px[1], [0, 254, 64, 100]); + assert_eq!(px[2], [120, 135, 94, 173], "weight 34: red (30×255 + 32) >> 6"); + assert_eq!(px[3], [255, 1, 129, 255]); + } + + #[test] + fn bc7_mode_7_two_subsets_with_alpha() { + // Partition 1: column 3 is subset 1 (anchor 15). Endpoints (5 bits + P-bit): + // [255; 4], [0; 4], [130, 0, 0, 251], [4, 134, 69, 4]. + let idx = index_set(&[(0, 1), (3, 3), (15, 1)]); + let ends = [each(&[31, 0, 16, 0], 5), each(&[31, 0, 0, 16], 5), each(&[31, 0, 0, 8], 5), each(&[31, 0, 31, 0], 5)].concat(); + let b = bc7_block(7, &[&[(1, 6)], &ends[..], &each(&[1, 0, 0, 1], 1), &texel_indices(idx, 2, &[0, 15])].concat()); + let px = bc7(&b); + assert_eq!(px[0], [171; 4]); + assert_eq!(px[3], [4, 134, 69, 4]); + assert_eq!(px[15], [89, 44, 23, 170], "weight 21: red (43×130 + 21×4 + 32) >> 6"); + assert_eq!((px[7], px[1]), ([130, 0, 0, 251], [255; 4])); + } + + #[test] + fn bc7_reserved_block_is_all_zero() { + assert_eq!(bc7(&[0; 16]), [[0; 4]; 16]); + } + + /// A BC6H block of mode `id`: `values` by field (missing ones are 0), then the indices. + fn bc6h_block(id: u8, values: &[(u8, i32)], index: [u32; 16]) -> [u8; 16] { + let mode = BC6H_MODES.iter().find(|m| m.id == id).unwrap(); + let value = |f: u8| values.iter().find(|(g, _)| *g == f).map_or(0, |(_, v)| *v); + let mut fields = vec![(u32::from(id), if id < 2 { 2 } else { 5 })]; + for &(f, a, b) in mode.fields { + for k in 0..=a.abs_diff(b) { + let bit = if a >= b { b + k } else { b - k }; + fields.push(((value(f) >> bit) as u32 & 1, 1)); + } + } + let bits = if mode.subsets == 2 { 3 } else { 4 }; + let partition = value(PB) as usize; + for (i, x) in index.iter().enumerate() { + fields.push((*x, bits - u32::from(super::anchor(mode.subsets, partition, i)))); + } + pack(&fields) + } + + /// The same endpoints for every mode: the first is (largest, 0, middle); the others are small + /// differences from it (or, without transformed endpoints, values near it). Two-subset modes + /// use partition 13 (texels 8-15 are subset 1); indices pick each endpoint and two blends. + fn bc6h_case(id: u8) -> ([u8; 16], Vec) { + let mode = BC6H_MODES.iter().find(|m| m.id == id).unwrap(); + let (max, mid, d) = ((1 << mode.endpoint_bits) - 1, 1 << (mode.endpoint_bits - 1), mode.delta_bits); + let mut v = vec![(R0, max), (G0, 0), (B0, mid)]; + if mode.transformed { + v.extend([(R1, -1), (G1, 1), (B1, 0)]); + } else { + v.extend([(R1, max - 1), (G1, 1), (B1, mid)]); + } + match (mode.transformed, mode.subsets) { + (true, 2) => v.extend([(R2, 0), (G2, 2), (B2, -2), (R3, -(1 << (d[0] - 1))), (G3, 0), (B3, 1), (PB, 13)]), + (false, 2) => v.extend([(R2, max), (G2, 2), (B2, mid - 2), (R3, 0), (G3, max), (B3, mid + 1), (PB, 13)]), + _ => {} + } + if mode.subsets == 2 { + (bc6h_block(id, &v, index_set(&[(1, 7), (8, 7), (2, 4), (9, 3)])), vec![0, 1, 2, 8, 9, 15]) + } else { + (bc6h_block(id, &v, index_set(&[(1, 15), (2, 8)])), vec![0, 1, 2]) + } + } + + // Half-float results for `bc6h_case`, from a separate decoder written from the specification's + // pseudocode. By hand, for mode 3's first texel: red is the largest 10-bit value → 0xffff → + // (0xffff × 31) >> 6 = 0x7bff (65504); blue 512 → ((512 << 15) + 0x4000) >> 9 = 32800 → + // (32800 × 31) >> 6 = 0x3e0f. Signed, red is -1 → -96 → 0x805d and blue -512 → -0x7fff → 0xfbff. + + const UNSIGNED: [(u8, &[[u16; 3]]); 14] = [ + ( + 0, + &[ + [0x7bff, 0x0000, 0x3e0f], + [0x7bd1, 0x002e, 0x3e0f], + [0x7be4, 0x001b, 0x3e0f], + [0x7a00, 0x0000, 0x3e2e], + [0x7b27, 0x002d, 0x3df8], + [0x7bff, 0x004d, 0x3dd1], + ], + ), + ( + 1, + &[ + [0x7bff, 0x0000, 0x3e7c], + [0x7a8c, 0x0174, 0x3e7c], + [0x7b28, 0x00d7, 0x3e7c], + [0x5c84, 0x0000, 0x3f74], + [0x6eb7, 0x0166, 0x3dc5], + [0x7bff, 0x026c, 0x3c8c], + ], + ), + ( + 2, + &[ + [0x7bff, 0x0000, 0x3e07], + [0x7be8, 0x0017, 0x3e07], + [0x7bf2, 0x000d, 0x3e07], + [0x7b00, 0x0000, 0x3e17], + [0x7b93, 0x0016, 0x3dfc], + [0x7bff, 0x0026, 0x3de8], + ], + ), + ( + 6, + &[ + [0x7bff, 0x0000, 0x3e07], + [0x7be8, 0x0017, 0x3e07], + [0x7bf2, 0x000d, 0x3e07], + [0x7b7c, 0x0000, 0x3e17], + [0x7bc8, 0x0016, 0x3dfc], + [0x7bff, 0x0026, 0x3de8], + ], + ), + ( + 10, + &[ + [0x7bff, 0x0000, 0x3e07], + [0x7be8, 0x0017, 0x3e07], + [0x7bf2, 0x000d, 0x3e07], + [0x7b7c, 0x0000, 0x3e17], + [0x7bc8, 0x0016, 0x3dfc], + [0x7bff, 0x0026, 0x3de8], + ], + ), + ( + 14, + &[ + [0x7bff, 0x0000, 0x3e1f], + [0x7ba3, 0x005d, 0x3e1f], + [0x7bca, 0x0035, 0x3e1f], + [0x7801, 0x0000, 0x3e5d], + [0x7a4f, 0x0059, 0x3df1], + [0x7bff, 0x009b, 0x3da3], + ], + ), + ( + 18, + &[ + [0x7bff, 0x0000, 0x3e3e], + [0x7b46, 0x00ba, 0x3e3e], + [0x7b94, 0x006b, 0x3e3e], + [0x6c42, 0x0000, 0x3eba], + [0x755b, 0x00b3, 0x3de2], + [0x7bff, 0x0136, 0x3d46], + ], + ), + ( + 22, + &[ + [0x7bff, 0x0000, 0x3e3e], + [0x7b46, 0x00ba, 0x3e3e], + [0x7b94, 0x006b, 0x3e3e], + [0x7402, 0x0000, 0x3eba], + [0x78a0, 0x00b3, 0x3de2], + [0x7bff, 0x0136, 0x3d46], + ], + ), + ( + 26, + &[ + [0x7bff, 0x0000, 0x3e3e], + [0x7b46, 0x00ba, 0x3e3e], + [0x7b94, 0x006b, 0x3e3e], + [0x7402, 0x0000, 0x3eba], + [0x78a0, 0x00b3, 0x3de2], + [0x7bff, 0x0136, 0x3d46], + ], + ), + ( + 30, + &[ + [0x7bff, 0x0000, 0x3ef8], + [0x7918, 0x02e8, 0x3ef8], + [0x7a51, 0x01ae, 0x3ef8], + [0x0000, 0x7bff, 0x40e8], + [0x47af, 0x371c, 0x3d8b], + [0x7bff, 0x04d8, 0x3b18], + ], + ), + (3, &[[0x7bff, 0x0000, 0x3e0f], [0x7bd1, 0x002e, 0x3e0f], [0x7be7, 0x0018, 0x3e0f]]), + (7, &[[0x7bff, 0x0000, 0x3e07], [0x7be8, 0x0017, 0x3e07], [0x7bf3, 0x000c, 0x3e07]]), + (11, &[[0x7bff, 0x0000, 0x3e03], [0x7bf4, 0x000b, 0x3e03], [0x7bf9, 0x0006, 0x3e03]]), + (15, &[[0x7bff, 0x0000, 0x3e00], [0x7bff, 0x0000, 0x3e00], [0x7bff, 0x0000, 0x3e00]]), + ]; + const SIGNED: [(u8, &[[u16; 3]]); 14] = [ + ( + 0, + &[ + [0x805d, 0x0000, 0xfbff], + [0x809b, 0x005d, 0xfbff], + [0x8080, 0x0036, 0xfbff], + [0x843d, 0x0000, 0xfbff], + [0x81ff, 0x005a, 0x132a], + [0x805d, 0x009b, 0x7ba3], + ], + ), + ( + 1, + &[ + [0x82e8, 0x0000, 0xfbff], + [0x84d8, 0x02e8, 0xfbff], + [0x8406, 0x01ae, 0xfbff], + [0xc0e8, 0x0000, 0xfbff], + [0x9d10, 0x02cc, 0x11b1], + [0x82e8, 0x04d8, 0x7918], + ], + ), + ( + 2, + &[ + [0x802e, 0x0000, 0xfbff], + [0x804d, 0x002e, 0xfbff], + [0x803f, 0x001b, 0xfbff], + [0x821e, 0x0000, 0xfbff], + [0x80ff, 0x002c, 0x1345], + [0x802e, 0x004d, 0x7bd1], + ], + ), + ( + 6, + &[ + [0x802e, 0x0000, 0xfbff], + [0x804d, 0x002e, 0xfbff], + [0x803f, 0x001b, 0xfbff], + [0x8126, 0x0000, 0xfbff], + [0x8097, 0x002c, 0x1345], + [0x802e, 0x004d, 0x7bd1], + ], + ), + ( + 10, + &[ + [0x802e, 0x0000, 0xfbff], + [0x804d, 0x002e, 0xfbff], + [0x803f, 0x001b, 0xfbff], + [0x8126, 0x0000, 0xfbff], + [0x8097, 0x002c, 0x1345], + [0x802e, 0x004d, 0x7bd1], + ], + ), + ( + 14, + &[ + [0x80ba, 0x0000, 0xfbff], + [0x8136, 0x00ba, 0xfbff], + [0x8101, 0x006b, 0xfbff], + [0x887a, 0x0000, 0xfbff], + [0x83ff, 0x00b3, 0x12f4], + [0x80ba, 0x0136, 0x7b46], + ], + ), + ( + 18, + &[ + [0x8174, 0x0000, 0xfbff], + [0x826c, 0x0174, 0xfbff], + [0x8203, 0x00d7, 0xfbff], + [0xa074, 0x0000, 0xfbff], + [0x8e88, 0x0166, 0x1288], + [0x8174, 0x026c, 0x7a8c], + ], + ), + ( + 22, + &[ + [0x8174, 0x0000, 0xfbff], + [0x826c, 0x0174, 0xfbff], + [0x8203, 0x00d7, 0xfbff], + [0x90f4, 0x0000, 0xfbff], + [0x87fe, 0x0166, 0x1288], + [0x8174, 0x026c, 0x7a8c], + ], + ), + ( + 26, + &[ + [0x8174, 0x0000, 0xfbff], + [0x826c, 0x0174, 0xfbff], + [0x8203, 0x00d7, 0xfbff], + [0x90f4, 0x0000, 0xfbff], + [0x87fe, 0x0166, 0x1288], + [0x8174, 0x026c, 0x7a8c], + ], + ), + ( + 30, + &[ + [0x85d0, 0x0000, 0xfbff], + [0x89b0, 0x05d0, 0xfbff], + [0x880d, 0x035c, 0xfbff], + [0x0000, 0x85d0, 0xfbff], + [0x835c, 0x0326, 0x1003], + [0x85d0, 0x09b0, 0x7630], + ], + ), + (3, &[[0x805d, 0x0000, 0xfbff], [0x809b, 0x005d, 0xfbff], [0x807d, 0x0031, 0xfbff]]), + (7, &[[0x802e, 0x0000, 0xfbff], [0x804d, 0x002e, 0xfbff], [0x803e, 0x0019, 0xfbff]]), + (11, &[[0x8017, 0x0000, 0xfbff], [0x8026, 0x0017, 0xfbff], [0x801f, 0x000c, 0xfbff]]), + (15, &[[0x8000, 0x0000, 0xfc00], [0x8001, 0x0000, 0xfc00], [0x8001, 0x0000, 0xfc00]]), + ]; + + #[test] + fn bc6h_every_mode_unsigned_and_signed() { + for (signed, expected) in [(false, &UNSIGNED), (true, &SIGNED)] { + for (id, want) in expected { + let (block, texels) = bc6h_case(*id); + let got = bc6h_halves(&block, signed); + let got: Vec<[u16; 3]> = texels.iter().map(|t| got[*t]).collect(); + assert_eq!(&got[..], *want, "mode {id}, signed {signed}"); + } + } + // Reserved modes (19, 23, 27, 31) are black. + for id in [19u32, 23, 27, 31] { + assert_eq!(bc6h_halves(&pack(&[(id, 5), (0, 123)]), false), [[0; 3]; 16]); + } + } + + #[test] + fn bc6h_tone_maps_to_srgb() { + assert_eq!([0x0000, 0x3800, 0x3c00, 0x7bff, 0xfc00, 0xbc00, 0x0001].map(|h| srgb8(half(h))), [0, 188, 255, 255, 0, 0, 0]); + assert_eq!(half(0x3555), 0.333_251_95, "a normal half: (1024 + 0x155) × 2^(13 - 25)"); + assert_eq!(half(0x0200), 2f32.powi(-15), "a subnormal half"); + // Mode 3's first texel: red 65504 and blue 1.5 clip to white, green is 0. + assert_eq!(bc6h(&bc6h_case(3).0, false)[0], [255, 0, 255, 255]); + } + + #[test] + fn any_block_decodes_without_panicking() { + let mut x = 0x9e37_79b9_7f4a_7c15u128 << 64 | 0x2545_f491_4f6c_dd1d; + for _ in 0..20_000 { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + let b = x.to_le_bytes(); + let _ = (bc7(&b), bc6h(&b, false), bc6h(&b, true)); + } + } +} diff --git a/crates/dds/src/eac.rs b/crates/dds/src/eac.rs new file mode 100644 index 000000000..fe523c90e --- /dev/null +++ b/crates/dds/src/eac.rs @@ -0,0 +1,107 @@ +//! ETC1 and EAC 4×4 block decoders. +//! +//! EAC's 11-bit channel blocks are reduced to display bytes after reconstruction and clamping. +//! The signed layouts map -1..1 to 0..255 so negative values remain visible; zero is 128. +//! Layout and modifier tables: . + +// Positive halves of the Khronos EAC modifier tables. Negative entries are -positive - 1. +const MODIFIERS: [[i16; 4]; 16] = [ + [2, 5, 8, 14], + [2, 6, 9, 12], + [1, 4, 7, 12], + [1, 3, 5, 12], + [2, 5, 7, 11], + [2, 6, 8, 10], + [3, 6, 7, 10], + [2, 4, 7, 10], + [1, 5, 7, 9], + [1, 4, 7, 9], + [1, 3, 7, 9], + [1, 4, 6, 9], + [2, 3, 6, 9], + [0, 1, 2, 9], + [3, 5, 7, 8], + [2, 4, 6, 8], +]; + +fn split_halves(block: &[u8; 16]) -> ([u8; 8], [u8; 8]) { + let mut first = [0u8; 8]; + let mut second = [0u8; 8]; + for (i, x) in block.iter().enumerate() { + if i < 8 { + first[i] = *x; + } else { + second[i - 8] = *x; + } + } + (first, second) +} + +/// ETC1 uses big-endian blocks and column-major selector bits, independently of the split. +/// Differential bases outside RGB555 are undefined by the format and are refused. +pub(crate) fn etc1(block: &[u8; 8]) -> Option<[[u8; 4]; 16]> { + const ETC1_MODIFIERS: [[i16; 2]; 8] = [[2, 8], [5, 17], [9, 29], [13, 42], [18, 60], [24, 80], [33, 106], [47, 183]]; + let bits = u64::from_be_bytes(*block); + let differential = bits & (1 << 33) != 0; + let horizontal = bits & (1 << 32) != 0; + let mut bases = [[0i16; 3]; 2]; + for (channel, shift) in [56, 48, 40].into_iter().enumerate() { + let value = ((bits >> shift) & 255) as i16; + let (first, second) = if differential { + let first = value >> 3; + let delta = ((value & 7) ^ 4) - 4; + let second = first + delta; + if !(0..=31).contains(&second) { + return None; + } + ((first << 3) | (first >> 2), (second << 3) | (second >> 2)) + } else { + ((value >> 4) * 17, (value & 15) * 17) + }; + bases[0][channel] = first; + bases[1][channel] = second; + } + let first_table = ETC1_MODIFIERS.get(((bits >> 37) & 7) as usize)?; + let second_table = ETC1_MODIFIERS.get(((bits >> 34) & 7) as usize)?; + Some(std::array::from_fn(|pixel| { + let (x, y) = (pixel % 4, pixel / 4); + let second = if horizontal { y >= 2 } else { x >= 2 }; + let (base, table) = if second { (bases[1], second_table) } else { (bases[0], first_table) }; + let selector = x * 4 + y; + let magnitude = if bits & (1 << selector) == 0 { table[0] } else { table[1] }; + let delta = if bits & (1 << (selector + 16)) == 0 { magnitude } else { -magnitude }; + let rgb = base.map(|channel| (channel + delta).clamp(0, 255) as u8); + [rgb[0], rgb[1], rgb[2], 255] + })) +} + +fn channel(block: &[u8; 8], signed: bool) -> [u8; 16] { + let bits = u64::from_be_bytes(*block); + let base = if signed { i16::from((block[0] as i8).max(-127)) * 8 } else { i16::from(block[0]) * 8 + 4 }; + let scale = (i16::from(block[1] >> 4) * 8).max(1); + let table = MODIFIERS.get(usize::from(block[1] & 15)).copied().unwrap_or_default(); + std::array::from_fn(|pixel| { + let (x, y) = (pixel % 4, pixel / 4); + let selector = ((bits >> (45 - 3 * (x * 4 + y))) & 7) as usize; + let magnitude = table.get(selector & 3).copied().unwrap_or_default(); + let modifier = if selector < 4 { -magnitude - 1 } else { magnitude }; + let value = base + modifier * scale; + if signed { + let value = u32::try_from(value.clamp(-1023, 1023) + 1023).unwrap_or_default(); + ((value * 255 + 1023) / 2046) as u8 + } else { + let value = u32::try_from(value.clamp(0, 2047)).unwrap_or_default(); + ((value * 255 + 1023) / 2047) as u8 + } + }) +} + +pub(crate) fn scalar(block: &[u8; 8], signed: bool) -> [[u8; 4]; 16] { + channel(block, signed).map(|value| [value, value, value, 255]) +} + +pub(crate) fn dual(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] { + let (red, green) = split_halves(block); + let (red, green) = (channel(&red, signed), channel(&green, signed)); + std::array::from_fn(|pixel| [red[pixel], green[pixel], 0, 255]) +} diff --git a/crates/dds/src/lib.rs b/crates/dds/src/lib.rs index 4eb8ff994..354067f26 100644 --- a/crates/dds/src/lib.rs +++ b/crates/dds/src/lib.rs @@ -39,6 +39,10 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod bc; +pub mod bptc; +mod eac; +mod packed; +pub mod pixels; use std::borrow::Cow; use std::fmt; @@ -84,6 +88,8 @@ pub enum DdsError { Alloc(usize), /// The decoded output exceeds the caller-selected per-buffer byte limit. LimitExceeded { required: usize, limit: u64 }, + /// Input pixel data ended before the declared dimensions or block count. + Truncated(String), } impl fmt::Display for DdsError { @@ -94,6 +100,7 @@ impl fmt::Display for DdsError { DdsError::Encode(reason) => write!(f, "DDS encode failed: {reason}"), DdsError::Alloc(len) => write!(f, "cannot allocate {len} bytes for the texture"), DdsError::LimitExceeded { required, limit } => write!(f, "decoded texture requires {required} bytes, exceeding limit {limit}"), + DdsError::Truncated(reason) => write!(f, "truncated pixel data: {reason}"), } } } diff --git a/crates/dds/src/packed.rs b/crates/dds/src/packed.rs new file mode 100644 index 000000000..6434a6e3c --- /dev/null +++ b/crates/dds/src/packed.rs @@ -0,0 +1,51 @@ +//! Four-byte packed RGB layouts. Words are little-endian, with red in the low bits. +//! Unsigned floats: , sections 10.2 and 10.3. + +use crate::bptc; + +pub(crate) fn rgba1010102(bytes: &[u8; 4]) -> [u8; 4] { + let word = u32::from_le_bytes(*bytes); + let channel = |shift: u32| (((word >> shift) & 1023) * 255 + 511) / 1023; + [channel(0) as u8, channel(10) as u8, channel(20) as u8, (word >> 30) as u8 * 85] +} + +// These unsigned formats share binary16's five-bit exponent and bias. Padding the +// six- or five-bit fraction with zeroes produces the same value in a positive half. +fn unsigned_float(bits: u16, padding: u32) -> f32 { + bptc::half(bits << padding) +} + +pub(crate) fn rgb111110(bytes: &[u8; 4]) -> [u8; 4] { + let word = u32::from_le_bytes(*bytes); + let channel = |shift: u32, mask: u32, padding: u32| bptc::srgb8(unsigned_float(((word >> shift) & mask) as u16, padding)); + [channel(0, 0x7ff, 4), channel(11, 0x7ff, 4), channel(22, 0x3ff, 5), 255] +} + +pub(crate) fn rgb9e5(bytes: &[u8; 4]) -> [u8; 4] { + let packed = u32::from_le_bytes(*bytes); + let scale = 2.0f32.powi((packed >> 27) as i32 - 24); + let channel = |shift: u32| bptc::srgb8(((packed >> shift) & 0x1ff) as f32 * scale); + [channel(0), channel(9), channel(18), 255] +} + +#[cfg(test)] +mod tests { + use super::unsigned_float; + + #[test] + fn unsigned_float_boundaries_are_preserved_before_display_quantization() { + for (fraction_bits, padding, smallest, largest_subnormal, maximum) in + [(6, 4, 0x3580_0000, 0x387c_0000, 65024.0), (5, 5, 0x3600_0000, 0x3878_0000, 64512.0)] + { + let fractions = 1u16 << fraction_bits; + assert_eq!(unsigned_float(0, padding).to_bits(), 0); + assert_eq!(unsigned_float(1, padding).to_bits(), smallest); + assert_eq!(unsigned_float(fractions - 1, padding).to_bits(), largest_subnormal); + assert_eq!(unsigned_float(fractions, padding).to_bits(), 0x3880_0000); + assert_eq!(unsigned_float(31 * fractions - 1, padding), maximum); + assert_eq!(unsigned_float(31 * fractions, padding), f32::INFINITY); + assert!(unsigned_float(31 * fractions + 1, padding).is_nan()); + assert!(unsigned_float(32 * fractions - 1, padding).is_nan()); + } + } +} diff --git a/crates/dds/src/pixels.rs b/crates/dds/src/pixels.rs new file mode 100644 index 000000000..8d3933911 --- /dev/null +++ b/crates/dds/src/pixels.rs @@ -0,0 +1,390 @@ +//! Turning GPU textures' stored pixels into RGBA: uncompressed layouts, packed 32-bit layouts, +//! and 4×4 block formats (BC1–BC7, ETC1, and EAC). Rows come out in the order they're stored. + +use crate::{DdsError, alloc_zeroed, bc, bptc, eac, packed, with_alpha}; + +/// Default RGBA output budget: 256 MiB, matching an 8192×8192 RGBA8 texture. +pub const DEFAULT_MAX_RGBA_BYTES: u64 = 256 << 20; + +/// How a texture's pixels are laid out. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PixelLayout { + /// Alpha only (shown as white with that alpha). + Alpha8, + /// One grey channel. + R8, + /// One unsigned 16-bit channel, shown as grey. + R16, + /// Two unsigned 8-bit channels; blue is zero and alpha is opaque. + Rg8, + /// Two unsigned 16-bit channels; blue is zero and alpha is opaque. + Rg16, + /// Three unsigned 16-bit channels; alpha is opaque. + Rgb16, + /// Four unsigned 16-bit channels, including alpha. + Rgba16, + RHalf, + RgHalf, + RgbaHalf, + RFloat, + RgFloat, + RgbaFloat, + /// Nine-bit RGB mantissas with a shared five-bit exponent, displayed as opaque sRGB. + Rgb9e5, + /// Packed unsigned 10-bit RGB with two-bit alpha, low bits first. + Rgba1010102, + /// Packed unsigned 11/11/10-bit floating-point RGB, displayed as opaque sRGB. + Rgb111110Float, + Rgb24, + Rgba32, + Argb32, + Bgra32, + Rgb565, + Rgba4444, + Argb4444, + /// BC1 / DXT1. + Dxt1, + /// BC2 / DXT3: four-colour blocks with one explicit four-bit alpha value per texel. + Dxt3, + /// BC3 / DXT5. + Dxt5, + /// One channel in blocks (shown as grey). + Bc4, + /// Two channels in blocks, usually a normal map (blue is rebuilt from red and green). + Bc5, + /// High dynamic range RGB in blocks (unsigned half floats), tone-mapped to 8-bit sRGB. + Bc6h, + /// BC6H with signed half floats. + Bc6hSigned, + Bc7, + /// ETC1 RGB, with individual or differential base colours. + Etc1, + /// One EAC channel, shown as grey. + EacR, + /// One signed EAC channel; -1..1 maps to 0..255. + EacRSigned, + /// Two EAC channels; blue is zero and alpha is opaque. + EacRg, + /// Two signed EAC channels; -1..1 maps to 0..255. + EacRgSigned, +} + +/// Bytes of a `width`×`height` picture in `layout`. +pub fn size(layout: PixelLayout, width: u32, height: u32) -> Option { + let (w, h) = (width as usize, height as usize); + let blocks = w.div_ceil(4).checked_mul(h.div_ceil(4))?; + match layout { + PixelLayout::Alpha8 | PixelLayout::R8 => w.checked_mul(h), + PixelLayout::Rgb565 | PixelLayout::Rgba4444 | PixelLayout::Argb4444 | PixelLayout::RHalf | PixelLayout::R16 | PixelLayout::Rg8 => { + w.checked_mul(h)?.checked_mul(2) + } + PixelLayout::Rgb24 => w.checked_mul(h)?.checked_mul(3), + PixelLayout::Rg16 => w.checked_mul(h)?.checked_mul(4), + PixelLayout::Rgb16 => w.checked_mul(h)?.checked_mul(6), + PixelLayout::Rgba16 => w.checked_mul(h)?.checked_mul(8), + PixelLayout::Rgba32 + | PixelLayout::Argb32 + | PixelLayout::Bgra32 + | PixelLayout::RgHalf + | PixelLayout::RFloat + | PixelLayout::Rgb9e5 + | PixelLayout::Rgba1010102 + | PixelLayout::Rgb111110Float => w.checked_mul(h)?.checked_mul(4), + PixelLayout::RgbaHalf | PixelLayout::RgFloat => w.checked_mul(h)?.checked_mul(8), + PixelLayout::RgbaFloat => w.checked_mul(h)?.checked_mul(16), + PixelLayout::Dxt1 | PixelLayout::Bc4 | PixelLayout::Etc1 | PixelLayout::EacR | PixelLayout::EacRSigned => blocks.checked_mul(8), + PixelLayout::Dxt3 + | PixelLayout::Dxt5 + | PixelLayout::Bc5 + | PixelLayout::Bc6h + | PixelLayout::Bc6hSigned + | PixelLayout::Bc7 + | PixelLayout::EacRg + | PixelLayout::EacRgSigned => blocks.checked_mul(16), + } +} + +/// Convert an IEEE 754 binary16 half-float's bits to `f32`. +pub fn half_to_f32(h: u16) -> f32 { + bptc::half(h) +} + +/// Convert a linear-light value to 8-bit sRGB; 0..1 is kept, brighter and negative values clip. +pub fn linear_to_srgb8(v: f32) -> u8 { + bptc::srgb8(v) +} + +/// Decode one BC1 (DXT1) 8-byte block into 16 RGBA8 texels (row by row). +pub fn decode_bc1_block(block: &[u8; 8]) -> [[u8; 4]; 16] { + bc::decode_colour(block, true) +} + +/// Decode one BC2 (DXT3) 16-byte block into 16 RGBA8 texels (row by row). +pub fn decode_bc2_block(block: &[u8; 16]) -> [[u8; 4]; 16] { + with_alpha(bc::decode_colour(block.get(8..).unwrap_or_default(), false), bc::decode_bc2_alpha(block.get(..8).unwrap_or_default())) +} + +/// Decode one BC3 (DXT5) 16-byte block into 16 RGBA8 texels (row by row). +pub fn decode_bc3_block(block: &[u8; 16]) -> [[u8; 4]; 16] { + with_alpha(bc::decode_colour(block.get(8..).unwrap_or_default(), false), bc::decode_values(block.get(..8).unwrap_or_default())) +} + +/// Decode one BC4 8-byte block into 16 greyscale RGBA8 texels (`[r, r, r, 255]`, row by row). +pub fn decode_bc4_block(block: &[u8; 8]) -> [[u8; 4]; 16] { + bc::decode_values(block).map(|r| [r, r, r, 255]) +} + +/// Decode one BC5 16-byte normal-map block into 16 RGBA8 texels with reconstructed Z (row by row). +pub fn decode_bc5_block(block: &[u8; 16]) -> [[u8; 4]; 16] { + let (r, g) = (bc::decode_values(block.get(..8).unwrap_or_default()), bc::decode_values(block.get(8..).unwrap_or_default())); + std::array::from_fn(|k| { + let (x, y) = (f32::from(r[k]) / 127.5 - 1.0, f32::from(g[k]) / 127.5 - 1.0); + let z = (1.0 - x * x - y * y).max(0.0).sqrt(); + [r[k], g[k], ((z + 1.0) * 127.5) as u8, 255] + }) +} + +/// Decode one BC6H 16-byte block into 16 sRGB8 RGBA texels (opaque). +pub fn decode_bc6h_block(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] { + bptc::bc6h(block, signed) +} + +/// Decode one BC7 16-byte block into 16 RGBA8 texels (row by row). +pub fn decode_bc7_block(block: &[u8; 16]) -> [[u8; 4]; 16] { + bptc::bc7(block) +} + +/// Decode one ETC1 8-byte block into 16 RGBA8 texels; returns `None` if differential colours overflow 5 bits. +pub fn decode_etc1_block(block: &[u8; 8]) -> Option<[[u8; 4]; 16]> { + eac::etc1(block) +} + +/// Decode one single-channel EAC 8-byte block into 16 greyscale RGBA8 texels. +pub fn decode_eac_r_block(block: &[u8; 8], signed: bool) -> [[u8; 4]; 16] { + eac::scalar(block, signed) +} + +/// Decode one dual-channel EAC 16-byte block into 16 RGBA8 texels (blue 0, alpha 255). +pub fn decode_eac_rg_block(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] { + eac::dual(block, signed) +} + +/// Decode one little-endian `RGB9E5` 4-byte pixel into opaque sRGB8 RGBA. +pub fn decode_rgb9e5(bytes: &[u8; 4]) -> [u8; 4] { + packed::rgb9e5(bytes) +} + +/// Decode one little-endian `RGBA1010102` 4-byte pixel into RGBA8. +pub fn decode_rgba1010102(bytes: &[u8; 4]) -> [u8; 4] { + packed::rgba1010102(bytes) +} + +/// Decode one little-endian `R11G11B10_FLOAT` 4-byte pixel into opaque sRGB8 RGBA. +pub fn decode_rgb111110_float(bytes: &[u8; 4]) -> [u8; 4] { + packed::rgb111110(bytes) +} + +fn unorm8(value: u16) -> u8 { + ((u32::from(value) * 255 + 32767) / 65535) as u8 +} + +fn unorm16_pixels(samples: impl Iterator, channels: usize) -> impl Iterator { + let mut samples = samples.map(unorm8); + std::iter::from_fn(move || { + let (r, g) = (samples.next()?, samples.next()?); + let b = if channels > 2 { samples.next()? } else { 0 }; + let a = if channels > 3 { samples.next()? } else { 255 }; + Some([r, g, b, a]) + }) +} + +fn float_pixels(mut samples: impl Iterator, channels: usize) -> impl Iterator { + std::iter::from_fn(move || { + let r = bptc::srgb8(samples.next()?); + if channels == 1 { + return Some([r, r, r, 255]); + } + let g = bptc::srgb8(samples.next()?); + if channels == 2 { + return Some([r, g, 0, 255]); + } + let b = bptc::srgb8(samples.next()?); + let a = (samples.next()?.clamp(0.0, 1.0) * 255.0).round() as u8; + Some([r, g, b, a]) + }) +} + +fn expand5(v: u16) -> u8 { + let v = (v & 31) as u8; + (v << 3) | (v >> 2) +} + +fn expand6(v: u16) -> u8 { + let v = (v & 63) as u8; + (v << 2) | (v >> 4) +} + +fn rgb565(v: u16) -> [u8; 4] { + [expand5(v >> 11), expand6(v >> 5), expand5(v), 255] +} + +fn nibbles(v: u16, order: [u32; 4]) -> [u8; 4] { + order.map(|shift| ((v >> shift) & 15) as u8 * 17) +} + +fn place_blocks(out: &mut [u8], w: usize, h: usize, texels: impl Iterator) { + let across = w.div_ceil(4); + for (i, block) in texels.enumerate() { + let (bx, by) = (i % across, i / across); + for (k, p) in block.iter().enumerate() { + let (x, y) = (bx * 4 + k % 4, by * 4 + k / 4); + if x < w && y < h { + let at = (y * w + x) * 4; + if let Some(dst) = out.get_mut(at..at + 4) { + dst.copy_from_slice(p); + } + } + } + } +} + +/// Decode a `width`×`height` picture (`data` starts with it) into RGBA8, rows in stored order. +/// +/// Caps the output at [`DEFAULT_MAX_RGBA_BYTES`]; use [`decode_with_limit`] for a different budget. +pub fn decode(layout: PixelLayout, width: u32, height: u32, data: &[u8]) -> Result, DdsError> { + decode_with_limit(layout, width, height, data, DEFAULT_MAX_RGBA_BYTES) +} + +/// Decode into RGBA8, allowing at most `max_bytes` of output. +/// +/// The budget applies to RGBA bytes, not the encoded input, and is checked before reading pixels +/// or reserving the output. +pub fn decode_with_limit(layout: PixelLayout, width: u32, height: u32, data: &[u8], max_bytes: u64) -> Result, DdsError> { + let need = size(layout, width, height).ok_or(DdsError::Alloc(usize::MAX))?; + let (w, h) = (width as usize, height as usize); + let out_len = + w.checked_mul(h).and_then(|pixels| pixels.checked_mul(4)).filter(|bytes| *bytes <= isize::MAX as usize).ok_or(DdsError::Alloc(usize::MAX))?; + if out_len as u64 > max_bytes { + return Err(DdsError::LimitExceeded { required: out_len, limit: max_bytes }); + } + let data = data.get(..need).ok_or_else(|| DdsError::Truncated(format!("{} bytes of pixels, {need} needed", data.len())))?; + if w == 0 || h == 0 { + return Err(DdsError::Malformed("an empty picture".into())); + } + let mut out: Vec = alloc_zeroed(out_len)?; + let mut put = |px: &mut dyn Iterator| { + for (dst, p) in out.as_chunks_mut::<4>().0.iter_mut().zip(px) { + *dst = p; + } + }; + let u16s = data.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)); + let floats = data.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)); + match layout { + PixelLayout::RHalf => put(&mut float_pixels(u16s.map(bptc::half), 1)), + PixelLayout::RgHalf => put(&mut float_pixels(u16s.map(bptc::half), 2)), + PixelLayout::RgbaHalf => put(&mut float_pixels(u16s.map(bptc::half), 4)), + PixelLayout::RFloat => put(&mut float_pixels(floats, 1)), + PixelLayout::RgFloat => put(&mut float_pixels(floats, 2)), + PixelLayout::RgbaFloat => put(&mut float_pixels(floats, 4)), + PixelLayout::Rgba1010102 => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgba1010102)), + PixelLayout::Rgb111110Float => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgb111110)), + PixelLayout::Rgb9e5 => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgb9e5)), + PixelLayout::Alpha8 => put(&mut data.iter().map(|a| [255, 255, 255, *a])), + PixelLayout::R8 => put(&mut data.iter().map(|r| [*r, *r, *r, 255])), + PixelLayout::R16 => put(&mut u16s.map(|value| { + let grey = unorm8(value); + [grey, grey, grey, 255] + })), + PixelLayout::Rg8 => put(&mut data.as_chunks::<2>().0.iter().map(|[r, g]| [*r, *g, 0, 255])), + PixelLayout::Rg16 => put(&mut unorm16_pixels(u16s, 2)), + PixelLayout::Rgb16 => put(&mut unorm16_pixels(u16s, 3)), + PixelLayout::Rgba16 => put(&mut unorm16_pixels(u16s, 4)), + PixelLayout::Rgb24 => put(&mut data.as_chunks::<3>().0.iter().map(|[r, g, b]| [*r, *g, *b, 255])), + PixelLayout::Rgba32 => put(&mut data.as_chunks::<4>().0.iter().copied()), + PixelLayout::Argb32 => put(&mut data.as_chunks::<4>().0.iter().map(|[a, r, g, b]| [*r, *g, *b, *a])), + PixelLayout::Bgra32 => put(&mut data.as_chunks::<4>().0.iter().map(|[b, g, r, a]| [*r, *g, *b, *a])), + PixelLayout::Rgb565 => put(&mut u16s.map(rgb565)), + PixelLayout::Rgba4444 => put(&mut u16s.map(|v| nibbles(v, [12, 8, 4, 0]))), + PixelLayout::Argb4444 => put(&mut u16s.map(|v| nibbles(v, [8, 4, 0, 12]))), + PixelLayout::Dxt1 => place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(decode_bc1_block)), + PixelLayout::Dxt3 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc2_block)), + PixelLayout::Dxt5 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc3_block)), + PixelLayout::Bc4 => place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(decode_bc4_block)), + PixelLayout::Bc5 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc5_block)), + PixelLayout::Bc6h => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|b| bptc::bc6h(b, false))), + PixelLayout::Bc6hSigned => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|b| bptc::bc6h(b, true))), + PixelLayout::Bc7 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(bptc::bc7)), + PixelLayout::EacR | PixelLayout::EacRSigned => { + place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(|block| eac::scalar(block, layout == PixelLayout::EacRSigned))) + } + PixelLayout::EacRg | PixelLayout::EacRgSigned => { + place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|block| eac::dual(block, layout == PixelLayout::EacRgSigned))) + } + PixelLayout::Etc1 => { + let mut valid = true; + let texels = data.as_chunks::<8>().0.iter().map_while(|block| { + let pixels = eac::etc1(block); + valid &= pixels.is_some(); + pixels + }); + place_blocks(&mut out, w, h, texels); + if !valid { + return Err(DdsError::Malformed("ETC1 differential colour is outside its five-bit range".into())); + } + } + } + Ok(out) +} + +/// Flip a `width`-wide RGBA8 picture upside down. +pub fn flip_rows(rgba: &[u8], width: u32) -> Vec { + let row = (width as usize).saturating_mul(4).max(1); + rgba.chunks(row).rev().flatten().copied().collect() +} + +#[cfg(test)] +mod tests { + use super::{PixelLayout, decode, decode_with_limit, flip_rows, size}; + use crate::DdsError; + + #[test] + fn uncompressed_and_swizzled_layouts() { + assert_eq!(decode(PixelLayout::Rgba32, 1, 2, &[1, 2, 3, 4, 5, 6, 7, 8]).unwrap(), [1, 2, 3, 4, 5, 6, 7, 8]); + assert_eq!(decode(PixelLayout::Argb32, 1, 1, &[9, 1, 2, 3]).unwrap(), [1, 2, 3, 9]); + assert_eq!(decode(PixelLayout::Bgra32, 1, 1, &[3, 2, 1, 9]).unwrap(), [1, 2, 3, 9]); + assert_eq!(decode(PixelLayout::Rgb24, 1, 1, &[1, 2, 3]).unwrap(), [1, 2, 3, 255]); + assert_eq!(decode(PixelLayout::Alpha8, 1, 1, &[7]).unwrap(), [255, 255, 255, 7]); + assert_eq!(decode(PixelLayout::R8, 1, 1, &[7]).unwrap(), [7, 7, 7, 255]); + assert_eq!(decode(PixelLayout::Rgb565, 1, 1, &0xf800u16.to_le_bytes()).unwrap(), [255, 0, 0, 255]); + assert_eq!(decode(PixelLayout::Rgba4444, 1, 1, &0xf00fu16.to_le_bytes()).unwrap(), [255, 0, 0, 255]); + assert_eq!(decode(PixelLayout::Argb4444, 1, 1, &0xff00u16.to_le_bytes()).unwrap(), [255, 0, 0, 255]); + assert_eq!(flip_rows(&[1, 1, 1, 1, 2, 2, 2, 2], 1), [2, 2, 2, 2, 1, 1, 1, 1]); + assert!(matches!(decode(PixelLayout::Rgba32, 2, 2, &[0; 15]), Err(DdsError::Truncated(_)))); + assert!(matches!(decode(PixelLayout::Rgba32, 0, 1, &[]), Err(DdsError::Malformed(_)))); + assert!(matches!(decode_with_limit(PixelLayout::R8, 2, 2, &[0; 4], 15), Err(DdsError::LimitExceeded { .. }))); + } + + #[test] + fn block_and_packed_layouts_crop_partial_blocks() { + assert_eq!(size(PixelLayout::Dxt1, 5, 5), Some(32)); + assert_eq!(decode(PixelLayout::Dxt1, 5, 5, &[0; 32]).unwrap().len(), 100); + // DXT1: colour 0 red, colour 1 blue; the first texel uses index 1, the rest index 0. + let px = decode(PixelLayout::Dxt1, 4, 4, &[0x00, 0xf8, 0x1f, 0x00, 0b01, 0, 0, 0]).unwrap(); + assert_eq!((&px[..4], &px[4..8]), (&[0, 0, 255, 255][..], &[255, 0, 0, 255][..])); + // DXT5: alpha 255 -> 0; first texel index 1 (0), rest index 0 (255). + let mut b = vec![255, 0, 1, 0, 0, 0, 0, 0]; + b.extend_from_slice(&[0x00, 0xf8, 0x1f, 0x00, 0, 0, 0, 0]); + let px = decode(PixelLayout::Dxt5, 4, 4, &b).unwrap(); + assert_eq!((px[3], px[7]), (0, 255)); + // BC4 & BC5. + assert_eq!(&decode(PixelLayout::Bc4, 4, 4, &[200, 10, 0, 0, 0, 0, 0, 0]).unwrap()[..4], &[200, 200, 200, 255]); + let mut n = vec![128, 128, 0, 0, 0, 0, 0, 0]; + n.extend_from_slice(&[128, 128, 0, 0, 0, 0, 0, 0]); + assert_eq!(&decode(PixelLayout::Bc5, 4, 4, &n).unwrap()[..4], &[128, 128, 254, 255]); + // Packed RGB9E5 & RGBA1010102. + let rgb9e5 = (256u32 | (128 << 9) | (64 << 18) | (15 << 27)).to_le_bytes(); + assert_eq!(decode(PixelLayout::Rgb9e5, 1, 1, &rgb9e5).unwrap(), [188, 137, 99, 255]); + let rgba10 = (1023u32 | (512 << 10) | (2 << 30)).to_le_bytes(); + assert_eq!(decode(PixelLayout::Rgba1010102, 1, 1, &rgba10).unwrap(), [255, 128, 0, 170]); + } +} diff --git a/crates/dds/tests/known_answers.rs b/crates/dds/tests/known_answers.rs new file mode 100644 index 000000000..ce6e5e9f0 --- /dev/null +++ b/crates/dds/tests/known_answers.rs @@ -0,0 +1,114 @@ +//! Independent known-answer test vectors (raw bitstreams and hand-verified spec outputs) +//! for BC6H (unsigned/signed), BC7, ETC1, and EAC R/RG (unsigned/signed). + +use craft_dds::DdsError; +use craft_dds::pixels::{self, PixelLayout}; + +#[test] +fn bc7_mode6_known_bitstream() { + // Raw 128-bit BC7 Mode 6 block (7-bit RGBA endpoints + per-endpoint P-bits, 4-bit indices): + // e0 = (241, 121, 21, 255), e1 = (40, 200, 254, 128); texels 0..3 use indices 0, 15, 8, 4. + let block: [u8; 16] = [0x40, 0x3c, 0x85, 0x47, 0x56, 0xfc, 0xff, 0xc0, 0xf0, 0x48, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44]; + let texels = pixels::decode_bc7_block(&block); + assert_eq!(texels[0], [241, 121, 21, 255]); + assert_eq!(texels[1], [40, 200, 254, 128]); + assert_eq!(texels[2], [134, 163, 145, 188]); + assert_eq!(texels[3], [188, 142, 83, 221]); + + // Reserved mode (low byte 0x00) decodes to all zeroes. + assert_eq!(pixels::decode_bc7_block(&[0; 16]), [[0, 0, 0, 0]; 16]); + + // Cropped 3x2 image keeps the top-left 3x2 texels in row-major order. + let rgba = pixels::decode(PixelLayout::Bc7, 3, 2, &block).unwrap(); + assert_eq!(rgba.len(), 3 * 2 * 4); + assert_eq!(&rgba[..4], &[241, 121, 21, 255]); + assert_eq!(&rgba[4..8], &[40, 200, 254, 128]); + assert_eq!(&rgba[8..12], &[134, 163, 145, 188]); +} + +#[test] +fn bc6h_unsigned_and_signed_known_bitstreams() { + // Mode 11 (untransformed 10-bit endpoints, 1 subset, 4-bit indices): + // e0 = (480, 400, 200), e1 = (200, 480, 400); texels 0..2 use indices 0, 15, 8. + let block: [u8; 16] = [0x03, 0x3c, 0xc8, 0x90, 0x41, 0x06, 0x3c, 0xc8, 0xf0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + + let unsigned = pixels::decode_bc6h_block(&block, false); + assert_eq!(unsigned[0], [228, 105, 7, 255]); + assert_eq!(unsigned[1], [7, 228, 105, 255]); + assert_eq!(unsigned[2], [51, 160, 39, 255]); + + let signed_pos = pixels::decode_bc6h_block(&block, true); + assert_eq!(signed_pos[0], [255, 255, 105, 255]); + assert_eq!(signed_pos[1], [105, 255, 255, 255]); + assert_eq!(signed_pos[2], [255, 255, 255, 255]); + + // Signed Mode 11 with negative 10-bit endpoints: R0 = -200 (0x338), G1 = -200 (0x338). + // Negative linear values clip to 0 in sRGB8 output. + let neg_block: [u8; 16] = [0x03, 0x67, 0x64, 0x20, 0x43, 0x06, 0x67, 0xc8, 0xf0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + let signed_neg = pixels::decode_bc6h_block(&neg_block, true); + assert_eq!(signed_neg[0], [0, 105, 255, 255]); + assert_eq!(signed_neg[1], [105, 0, 255, 255]); + assert_eq!(signed_neg[2], [0, 0, 255, 255]); + + let rgba = pixels::decode(PixelLayout::Bc6h, 2, 1, &block).unwrap(); + assert_eq!(rgba, [228, 105, 7, 255, 7, 228, 105, 255]); + let rgba_signed = pixels::decode(PixelLayout::Bc6hSigned, 2, 1, &neg_block).unwrap(); + assert_eq!(rgba_signed, [0, 105, 255, 255, 105, 0, 255, 255]); +} + +#[test] +fn etc1_known_bitstreams_and_invalid_differential() { + // Individual mode (diff=0, flip=0): left half (x<2) RGB4=(15,0,8) + 2, right half (x>=2) RGB4=(0,15,4) + 5. + let individual: [u8; 8] = [0xf0, 0x0f, 0x84, 0x04, 0x00, 0x00, 0x00, 0x00]; + let texels = pixels::decode_etc1_block(&individual).unwrap(); + for y in 0..4 { + for x in 0..4 { + let expected = if x < 2 { [255, 2, 138, 255] } else { [5, 255, 73, 255] }; + assert_eq!(texels[y * 4 + x], expected); + } + } + + // Differential mode (diff=1, flip=1 horizontal): base0=(20,10,4), delta=(+2,-2,+1), tables=(2,3). + let differential: [u8; 8] = [0xa2, 0x56, 0x21, 0x4f, 0x00, 0x00, 0x00, 0x00]; + let texels = pixels::decode_etc1_block(&differential).unwrap(); + for y in 0..4 { + for x in 0..4 { + let expected = if y < 2 { [174, 91, 42, 255] } else { [194, 79, 54, 255] }; + assert_eq!(texels[y * 4 + x], expected); + } + } + + // Differential base + delta outside 0..=31 must be rejected. + let invalid: [u8; 8] = [0x04, 0x40, 0x40, 0x02, 0x00, 0x00, 0x00, 0x00]; + assert!(pixels::decode_etc1_block(&invalid).is_none()); + assert!(matches!(pixels::decode(PixelLayout::Etc1, 4, 4, &invalid), Err(DdsError::Malformed(_)))); +} + +#[test] +fn eac_r_and_rg_unsigned_and_signed_known_bitstreams() { + // Unsigned EAC_R: base=100, mult=2, table=0, all selectors=7 (+14) -> 1028/2047 -> 128. + let eac_r_u: [u8; 8] = [0x64, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]; + assert_eq!(pixels::decode_eac_r_block(&eac_r_u, false), [[128, 128, 128, 255]; 16]); + + // Signed EAC_R: base=-64 (0xc0), mult=2, table=0, all selectors=0 (-3) -> (-560+1023)/2046 -> 58. + let eac_r_s: [u8; 8] = [0xc0, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + assert_eq!(pixels::decode_eac_r_block(&eac_r_s, true), [[58, 58, 58, 255]; 16]); + + // Column-major selector order: texel (x=1, y=0) has selector 7 (+14 -> 142), others selector 0 (-3 -> 125). + let eac_col: [u8; 8] = [0x80, 0x10, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00]; + let col_texels = pixels::decode_eac_r_block(&eac_col, false); + assert_eq!(col_texels[1], [142, 142, 142, 255]); + assert_eq!(col_texels[0], [125, 125, 125, 255]); + assert_eq!(col_texels[4], [125, 125, 125, 255]); + + // Dual-channel EAC_RG (unsigned and signed): R then G. + let mut eac_rg_u = [0u8; 16]; + eac_rg_u[..8].copy_from_slice(&eac_r_u); + eac_rg_u[8..].copy_from_slice(&[0xff, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); + assert_eq!(pixels::decode(PixelLayout::EacRg, 2, 2, &eac_rg_u).unwrap(), [128, 255, 0, 255].repeat(4)); + + let mut eac_rg_s = [0u8; 16]; + eac_rg_s[..8].copy_from_slice(&eac_r_s); + eac_rg_s[8..].copy_from_slice(&[0x7f, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); + assert_eq!(pixels::decode(PixelLayout::EacRgSigned, 2, 2, &eac_rg_s).unwrap(), [58, 255, 0, 255].repeat(4)); +}