diff --git a/docs/cooked-asset-store.md b/docs/cooked-asset-store.md index 3dc42899..be42dc23 100644 --- a/docs/cooked-asset-store.md +++ b/docs/cooked-asset-store.md @@ -459,3 +459,31 @@ renderer path, buffers, shaders, passes, draws, pixels, or frame-time behavior. The canonical variant, fallback, deduplication, and Bistro qualification is recorded in `docs/evidence/issue-136-asset-variants-v2.{md,json}`. + +## Compressed textures inside a GLB (`glb-compress`) + +`glb-compress` is independent of the store: it rewrites one GLB so every +embedded image is a KTX2 container of ASTC blocks with a full mip chain, and +the ordinary `loadModel` / staged model paths load the result. + +```shell +cargo run --release --manifest-path tools/bloom-cook/Cargo.toml -- \ + glb-compress hero.glb hero.astc.glb [--astc 4x4] [--normal-astc 4x4|keep] \ + [--quality fast|medium|thorough|exhaustive] +``` + +- On an adapter with `TEXTURE_COMPRESSION_ASTC` (every Apple GPU, most mobile + GPUs) the blocks upload untouched: a 4096² texture occupies 22 MB at 4×4 or + 10 MB at 6×6 instead of 85 MB of RGBA8 with mips, and load skips PNG inflate + and mip filtering. Other adapters decode level zero on the CPU and take the + RGBA8 path, so one file loads everywhere. BC7 payloads in KTX2 are read the + same way. +- Mips are the runtime's own: sRGB-aware averaging for colour, plain averaging + for data, renormalised direction plus accumulated variance in alpha for + normal maps. +- Base-colour images of alpha-`MASK` materials are left as they are, because + their coverage mips depend on the material cutoff. +- The command prints the PSNR of each encoded top level. The file on disk is + larger than with PNG or JPEG images (blocks are not entropy-coded). +- The images carry `mimeType: "image/ktx2"`. That is not a ratified glTF + extension for raw ASTC, so keep the source GLB for other tools. diff --git a/native/android/Cargo.lock b/native/android/Cargo.lock index d8c3e6f1..69b61d2e 100644 --- a/native/android/Cargo.lock +++ b/native/android/Cargo.lock @@ -64,6 +64,12 @@ dependencies = [ "libloading", ] +[[package]] +name = "astc-decode" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6058e6202e20b7fa445692ec4b77ca8eb02508091fcd479ea753d9f60e376b" + [[package]] name = "autocfg" version = "1.5.0" @@ -176,6 +182,7 @@ dependencies = [ name = "bloom-shared" version = "0.1.0" dependencies = [ + "astc-decode", "bloom-geometry-format", "bloom-scene-format", "bytemuck", diff --git a/native/ios/Cargo.lock b/native/ios/Cargo.lock index 124ba0fa..6b9f3f5f 100644 --- a/native/ios/Cargo.lock +++ b/native/ios/Cargo.lock @@ -38,6 +38,12 @@ dependencies = [ "libloading", ] +[[package]] +name = "astc-decode" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6058e6202e20b7fa445692ec4b77ca8eb02508091fcd479ea753d9f60e376b" + [[package]] name = "autocfg" version = "1.5.1" @@ -147,6 +153,7 @@ dependencies = [ name = "bloom-shared" version = "0.1.0" dependencies = [ + "astc-decode", "bloom-geometry-format", "bloom-scene-format", "bytemuck", diff --git a/native/linux/Cargo.lock b/native/linux/Cargo.lock index 925a8a75..ba3356fc 100644 --- a/native/linux/Cargo.lock +++ b/native/linux/Cargo.lock @@ -108,6 +108,12 @@ dependencies = [ "zbus", ] +[[package]] +name = "astc-decode" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6058e6202e20b7fa445692ec4b77ca8eb02508091fcd479ea753d9f60e376b" + [[package]] name = "async-broadcast" version = "0.7.2" @@ -392,6 +398,7 @@ dependencies = [ name = "bloom-shared" version = "0.1.0" dependencies = [ + "astc-decode", "bloom-geometry-format", "bloom-scene-format", "bytemuck", diff --git a/native/macos/Cargo.lock b/native/macos/Cargo.lock index 9ef300ae..ddc1a1ee 100644 --- a/native/macos/Cargo.lock +++ b/native/macos/Cargo.lock @@ -86,6 +86,12 @@ dependencies = [ "zbus", ] +[[package]] +name = "astc-decode" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6058e6202e20b7fa445692ec4b77ca8eb02508091fcd479ea753d9f60e376b" + [[package]] name = "async-broadcast" version = "0.7.2" @@ -372,6 +378,7 @@ dependencies = [ name = "bloom-shared" version = "0.1.0" dependencies = [ + "astc-decode", "bloom-geometry-format", "bloom-scene-format", "bytemuck", diff --git a/native/shared/Cargo.lock b/native/shared/Cargo.lock index f3430614..54bea442 100644 --- a/native/shared/Cargo.lock +++ b/native/shared/Cargo.lock @@ -38,6 +38,12 @@ dependencies = [ "libloading", ] +[[package]] +name = "astc-decode" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6058e6202e20b7fa445692ec4b77ca8eb02508091fcd479ea753d9f60e376b" + [[package]] name = "autocfg" version = "1.5.0" @@ -141,6 +147,7 @@ dependencies = [ name = "bloom-shared" version = "0.1.0" dependencies = [ + "astc-decode", "bloom-geometry-format", "bloom-scene-format", "bytemuck", diff --git a/native/shared/Cargo.toml b/native/shared/Cargo.toml index 36fda5d5..f9ad7842 100644 --- a/native/shared/Cargo.toml +++ b/native/shared/Cargo.toml @@ -39,6 +39,9 @@ image-extras = [ "dep:image_dds", "dep:serde_json", "dep:sha2", + # KTX2 images with ASTC blocks in glTF: the software decoder for + # adapters without the format. + "dep:astc-decode", ] [build-dependencies] @@ -59,6 +62,7 @@ bytemuck = { version = "1", features = ["derive"] } half = "2" image = { version = "0.25", default-features = false, features = ["png"] } image_dds = { version = "0.7", default-features = false, features = ["ddsfile", "image"], optional = true } +astc-decode = { version = "0.3", optional = true } gltf = { version = "1", features = [ "extensions", "extras", diff --git a/native/shared/src/compressed_texture.rs b/native/shared/src/compressed_texture.rs new file mode 100644 index 00000000..b5a3799e --- /dev/null +++ b/native/shared/src/compressed_texture.rs @@ -0,0 +1,421 @@ +//! Block-compressed textures that arrive ready for the GPU. +//! +//! A glTF image may be a KTX2 container holding ASTC or BC7 blocks with a +//! complete mip chain (`bloom-cook glb-compress` writes them). On a device +//! with the matching feature the blocks upload untouched: a 4096² texture +//! costs 22 MB (ASTC 4×4 / BC7) or 10 MB (ASTC 6×6) instead of the 85 MB of +//! RGBA8 plus mips, and nothing is decoded or filtered at load. Everywhere +//! else level zero is decoded on the CPU and the image takes the ordinary +//! RGBA8 path, so a compressed asset still renders on every adapter. +//! +//! Mips are authored, never derived: the cooker stores the same chains the +//! runtime builds for RGBA8 uploads (variance in normal-map alpha, sRGB-aware +//! colour averaging), so both paths shade alike. + +/// KTX2 file identifier. +pub const KTX2_MAGIC: [u8; 12] = [ + 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x32, 0x30, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A, +]; + +/// True when `bytes` starts with the KTX2 identifier. +pub fn is_ktx2(bytes: &[u8]) -> bool { + bytes.len() >= KTX2_MAGIC.len() && bytes[..KTX2_MAGIC.len()] == KTX2_MAGIC +} + +/// Block encodings the renderer uploads directly. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum BlockFormat { + /// ASTC LDR with the given block footprint in texels. + Astc { width: u8, height: u8 }, + /// BC7 (4×4 blocks). + Bc7, +} + +/// Vulkan format numbers of the supported ASTC footprints (UNORM; +1 = sRGB). +const ASTC_VK_FORMATS: [(u32, u8, u8); 14] = [ + (157, 4, 4), + (159, 5, 4), + (161, 5, 5), + (163, 6, 5), + (165, 6, 6), + (167, 8, 5), + (169, 8, 6), + (171, 8, 8), + (173, 10, 5), + (175, 10, 6), + (177, 10, 8), + (179, 10, 10), + (181, 12, 10), + (183, 12, 12), +]; +const BC7_VK_FORMAT: u32 = 145; + +impl BlockFormat { + /// `(format, container says sRGB)` for a Vulkan format number. + pub fn from_vk_format(value: u32) -> Option<(Self, bool)> { + if value == BC7_VK_FORMAT || value == BC7_VK_FORMAT + 1 { + return Some((Self::Bc7, value != BC7_VK_FORMAT)); + } + ASTC_VK_FORMATS + .iter() + .find(|(vk, _, _)| value == *vk || value == *vk + 1) + .map(|(vk, width, height)| { + ( + Self::Astc { + width: *width, + height: *height, + }, + value != *vk, + ) + }) + } + + /// The Vulkan format number, in its UNORM or sRGB flavour. + pub fn vk_format(self, srgb: bool) -> Option { + let base = match self { + Self::Bc7 => BC7_VK_FORMAT, + Self::Astc { width, height } => { + ASTC_VK_FORMATS + .iter() + .find(|(_, w, h)| *w == width && *h == height)? + .0 + } + }; + Some(base + u32::from(srgb)) + } + + /// Block footprint in texels. + pub fn block_size(self) -> (u32, u32) { + match self { + Self::Astc { width, height } => (u32::from(width), u32::from(height)), + Self::Bc7 => (4, 4), + } + } + + /// Bytes one mip level of `width`×`height` texels occupies (16 per block). + pub fn level_bytes(self, width: u32, height: u32) -> usize { + let (block_width, block_height) = self.block_size(); + width.div_ceil(block_width) as usize * height.div_ceil(block_height) as usize * 16 + } + + /// The device feature a direct upload needs. + pub fn required_feature(self) -> wgpu::Features { + match self { + Self::Astc { .. } => wgpu::Features::TEXTURE_COMPRESSION_ASTC, + Self::Bc7 => wgpu::Features::TEXTURE_COMPRESSION_BC, + } + } + + /// The texture format, always UNORM: game textures bind without hardware + /// sRGB decode because the shaders apply the transfer themselves. + pub fn texture_format(self) -> Option { + let block = match self { + Self::Bc7 => return Some(wgpu::TextureFormat::Bc7RgbaUnorm), + Self::Astc { width, height } => match (width, height) { + (4, 4) => wgpu::AstcBlock::B4x4, + (5, 4) => wgpu::AstcBlock::B5x4, + (5, 5) => wgpu::AstcBlock::B5x5, + (6, 5) => wgpu::AstcBlock::B6x5, + (6, 6) => wgpu::AstcBlock::B6x6, + (8, 5) => wgpu::AstcBlock::B8x5, + (8, 6) => wgpu::AstcBlock::B8x6, + (8, 8) => wgpu::AstcBlock::B8x8, + (10, 5) => wgpu::AstcBlock::B10x5, + (10, 6) => wgpu::AstcBlock::B10x6, + (10, 8) => wgpu::AstcBlock::B10x8, + (10, 10) => wgpu::AstcBlock::B10x10, + (12, 10) => wgpu::AstcBlock::B12x10, + (12, 12) => wgpu::AstcBlock::B12x12, + _ => return None, + }, + }; + Some(wgpu::TextureFormat::Astc { + block, + channel: wgpu::AstcChannel::Unorm, + }) + } +} + +/// A parsed block-compressed 2D texture: level zero first. +#[derive(Clone, Debug)] +pub struct CompressedImage { + pub format: BlockFormat, + pub width: u32, + pub height: u32, + /// What the container declares. The glTF material decides how the texture + /// is used; this only records authoring intent. + pub srgb: bool, + pub levels: Vec>, +} + +impl CompressedImage { + /// Parse a KTX2 file. `None` for anything that is not a plain 2D ASTC or + /// BC7 texture without supercompression, or whose levels are truncated. + pub fn from_ktx2(bytes: &[u8]) -> Option { + if !is_ktx2(bytes) { + return None; + } + let word = |at: usize| -> Option { + Some(u32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?)) + }; + let long = |at: usize| -> Option { + let value = u64::from_le_bytes(bytes.get(at..at + 8)?.try_into().ok()?); + usize::try_from(value).ok() + }; + let (format, srgb) = BlockFormat::from_vk_format(word(12)?)?; + let (width, height) = (word(20)?, word(24)?); + let (depth, layers, faces) = (word(28)?, word(32)?, word(36)?); + let level_count = word(40)?.max(1); + let supercompression = word(44)?; + if width == 0 || height == 0 || depth != 0 || layers > 1 || faces != 1 { + return None; + } + if supercompression != 0 || level_count > u32::BITS - width.max(height).leading_zeros() { + return None; + } + let mut levels = Vec::with_capacity(level_count as usize); + for index in 0..level_count as usize { + let entry = 80 + index * 24; + let (offset, length) = (long(entry)?, long(entry + 8)?); + let level_width = (width >> index).max(1); + let level_height = (height >> index).max(1); + if length != format.level_bytes(level_width, level_height) { + return None; + } + levels.push(bytes.get(offset..offset.checked_add(length)?)?.to_vec()); + } + Some(Self { + format, + width, + height, + srgb, + levels, + }) + } + + /// Serialise as KTX2 (no supercompression, smallest level stored first as + /// the format requires). Inverse of [`Self::from_ktx2`]. + pub fn to_ktx2(&self) -> Option> { + let vk_format = self.format.vk_format(self.srgb)?; + let (block_width, block_height) = self.format.block_size(); + let level_count = self.levels.len(); + if level_count == 0 { + return None; + } + // Data format descriptor: one basic block with a single 128-bit sample. + let mut dfd = Vec::with_capacity(44); + dfd.extend_from_slice(&44u32.to_le_bytes()); + dfd.extend_from_slice(&0u32.to_le_bytes()); // Khronos vendor, basic descriptor + dfd.extend_from_slice(&2u16.to_le_bytes()); // KDF 1.3 + dfd.extend_from_slice(&40u16.to_le_bytes()); // block size: 24 + one sample + dfd.push(match self.format { + BlockFormat::Astc { .. } => 162, + BlockFormat::Bc7 => 134, + }); + dfd.push(1); // BT.709 primaries + dfd.push(if self.srgb { 2 } else { 1 }); + dfd.push(0); // straight alpha + dfd.extend_from_slice(&[(block_width - 1) as u8, (block_height - 1) as u8, 0, 0]); + dfd.extend_from_slice(&[16, 0, 0, 0, 0, 0, 0, 0]); // bytes per plane + dfd.extend_from_slice(&0u16.to_le_bytes()); // bit offset + dfd.push(127); // bit length - 1 + dfd.push(0); // channel: RGBA + dfd.extend_from_slice(&[0, 0, 0, 0]); // sample position + dfd.extend_from_slice(&0u32.to_le_bytes()); + dfd.extend_from_slice(&u32::MAX.to_le_bytes()); + + let level_index_offset = 80usize; + let dfd_offset = level_index_offset + level_count * 24; + let mut cursor = (dfd_offset + dfd.len()).next_multiple_of(16); + let mut offsets = vec![0usize; level_count]; + for index in (0..level_count).rev() { + offsets[index] = cursor; + cursor = (cursor + self.levels[index].len()).next_multiple_of(16); + } + let total = offsets[0] + self.levels[0].len(); + + let mut out = Vec::with_capacity(total); + out.extend_from_slice(&KTX2_MAGIC); + for value in [ + vk_format, + 1, // type size + self.width, + self.height, + 0, // depth + 0, // layers + 1, // faces + level_count as u32, + 0, // no supercompression + dfd_offset as u32, + dfd.len() as u32, + 0, // key/value offset + 0, // key/value length + ] { + out.extend_from_slice(&value.to_le_bytes()); + } + out.extend_from_slice(&0u64.to_le_bytes()); // supercompression global data + out.extend_from_slice(&0u64.to_le_bytes()); + for index in 0..level_count { + let length = self.levels[index].len() as u64; + out.extend_from_slice(&(offsets[index] as u64).to_le_bytes()); + out.extend_from_slice(&length.to_le_bytes()); + out.extend_from_slice(&length.to_le_bytes()); + } + out.extend_from_slice(&dfd); + for index in (0..level_count).rev() { + out.resize(offsets[index], 0); + out.extend_from_slice(&self.levels[index]); + } + Some(out) + } + + /// Decode level zero to RGBA8 for adapters without the block format. + #[cfg(feature = "image-extras")] + pub fn decode_rgba8(&self) -> Option> { + let level = self.levels.first()?; + match self.format { + BlockFormat::Bc7 => image_dds::Surface { + width: self.width, + height: self.height, + depth: 1, + layers: 1, + mipmaps: 1, + image_format: image_dds::ImageFormat::BC7RgbaUnorm, + data: level.as_slice(), + } + .decode_rgba8() + .ok() + .map(|surface| surface.data), + BlockFormat::Astc { width, height } => { + let mut rgba = vec![0u8; self.width as usize * self.height as usize * 4]; + let row = self.width as usize * 4; + astc_decode::astc_decode( + level.as_slice(), + self.width, + self.height, + astc_decode::Footprint::new(u32::from(width), u32::from(height)), + |x, y, texel| { + let at = y as usize * row + x as usize * 4; + rgba[at..at + 4].copy_from_slice(&texel); + }, + ) + .ok()?; + Some(rgba) + } + } + } +} + +#[cfg(all(test, feature = "image-extras"))] +mod tests { + use super::*; + + fn sample(format: BlockFormat, srgb: bool) -> CompressedImage { + let (width, height) = (20u32, 12u32); + let levels = (0..5) + .map(|level| { + let size = format.level_bytes((width >> level).max(1), (height >> level).max(1)); + (0..size).map(|byte| (byte as u8) ^ (level as u8)).collect() + }) + .collect(); + CompressedImage { + format, + width, + height, + srgb, + levels, + } + } + + #[test] + fn ktx2_round_trip_keeps_every_level() { + for (format, srgb) in [ + ( + BlockFormat::Astc { + width: 4, + height: 4, + }, + true, + ), + ( + BlockFormat::Astc { + width: 6, + height: 6, + }, + false, + ), + ( + BlockFormat::Astc { + width: 8, + height: 5, + }, + false, + ), + (BlockFormat::Bc7, true), + ] { + let image = sample(format, srgb); + let bytes = image.to_ktx2().expect("serialises"); + let parsed = CompressedImage::from_ktx2(&bytes).expect("parses"); + assert_eq!(parsed.format, format); + assert_eq!(parsed.srgb, srgb); + assert_eq!((parsed.width, parsed.height), (image.width, image.height)); + assert_eq!(parsed.levels, image.levels); + } + } + + #[test] + fn truncated_or_foreign_files_are_rejected() { + let bytes = sample( + BlockFormat::Astc { + width: 4, + height: 4, + }, + false, + ) + .to_ktx2() + .unwrap(); + assert!(CompressedImage::from_ktx2(&bytes[..bytes.len() - 1]).is_none()); + assert!(CompressedImage::from_ktx2(b"\x89PNG\r\n\x1a\n").is_none()); + let mut wrong_format = bytes.clone(); + wrong_format[12..16].copy_from_slice(&37u32.to_le_bytes()); // R8G8B8A8_UNORM + assert!(CompressedImage::from_ktx2(&wrong_format).is_none()); + } + + #[test] + fn block_formats_map_to_vulkan_numbers_both_ways() { + for (vk, width, height) in ASTC_VK_FORMATS { + let format = BlockFormat::Astc { width, height }; + assert_eq!(BlockFormat::from_vk_format(vk), Some((format, false))); + assert_eq!(BlockFormat::from_vk_format(vk + 1), Some((format, true))); + assert_eq!(format.vk_format(true), Some(vk + 1)); + assert!(format.texture_format().is_some()); + } + assert_eq!( + BlockFormat::from_vk_format(146), + Some((BlockFormat::Bc7, true)) + ); + assert_eq!(BlockFormat::from_vk_format(37), None); + } + + #[test] + fn a_flat_astc_block_decodes_to_its_colour() { + // A void-extent block: every texel is the stored 16-bit RGBA colour. + let mut block = vec![0xFC, 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]; + for channel in [0xFFFFu16, 0x8080, 0x0000, 0xFFFF] { + block.extend_from_slice(&channel.to_le_bytes()); + } + let image = CompressedImage { + format: BlockFormat::Astc { + width: 4, + height: 4, + }, + width: 4, + height: 4, + srgb: false, + levels: vec![block], + }; + let rgba = image.decode_rgba8().expect("decodes"); + assert_eq!(rgba.len(), 64); + assert!(rgba.chunks(4).all(|texel| texel == [255, 128, 0, 255])); + } +} diff --git a/native/shared/src/ffi_core/assets.rs b/native/shared/src/ffi_core/assets.rs index ec3a8618..8bb29644 100644 --- a/native/shared/src/ffi_core/assets.rs +++ b/native/shared/src/ffi_core/assets.rs @@ -639,14 +639,7 @@ macro_rules! __bloom_ffi_assets { None => return 0.0, }; let eng = engine(); - let bind_group_idx = eng.renderer.register_texture_kind_with_color_space( - staged.width, - staged.height, - &staged.data, - staged.is_normal, - staged.is_srgb, - staged.alpha_coverage_reference, - ); + let bind_group_idx = staged.register(&mut eng.renderer); eng.textures.textures.alloc($crate::textures::TextureData { bind_group_idx, width: staged.width, diff --git a/native/shared/src/ffi_core/models.rs b/native/shared/src/ffi_core/models.rs index 47004d30..e3ab9964 100644 --- a/native/shared/src/ffi_core/models.rs +++ b/native/shared/src/ffi_core/models.rs @@ -863,16 +863,7 @@ macro_rules! __bloom_ffi_models { // visibly flatter than the same GLB through loadModel. let mut tex_map: Vec = Vec::with_capacity(staged.textures.len()); for tex in &staged.textures { - tex_map.push( - eng.renderer.register_texture_kind_with_color_space( - tex.width, - tex.height, - &tex.data, - tex.is_normal, - tex.is_srgb, - tex.alpha_coverage_reference, - ), - ); + tex_map.push(tex.register(&mut eng.renderer)); } let mut model = staged.model; // Remap EVERY texture slot, not just the base colour — this diff --git a/native/shared/src/lib.rs b/native/shared/src/lib.rs index 22b60774..48f22b1f 100644 --- a/native/shared/src/lib.rs +++ b/native/shared/src/lib.rs @@ -6,6 +6,7 @@ #[cfg(any(feature = "image-extras", feature = "models3d"))] mod adapter_profile; pub mod audio; +pub mod compressed_texture; #[cfg(all(feature = "models3d", not(target_arch = "wasm32")))] pub mod cooked_scene_store; #[cfg(all(feature = "image-extras", not(target_arch = "wasm32")))] diff --git a/native/shared/src/models_gltf.rs b/native/shared/src/models_gltf.rs index 3bd18496..0fd8ae94 100644 --- a/native/shared/src/models_gltf.rs +++ b/native/shared/src/models_gltf.rs @@ -34,7 +34,10 @@ use bake::{ complete_geometry_source_hash, model_bounds, share_scene_mesh_instances, shared_or_owned_instance, }; -use texture_io::{base64_decode, decode_texture_bytes, swap_extension}; +use texture_io::{ + base64_decode, decode_texture_bytes, register_compressed_image, stage_texture_bytes, + swap_extension, +}; use texture_semantics::srgb_material_image_indices; /// Walk the scene graph and collect EVERY world-space transform that @@ -529,10 +532,18 @@ pub(super) fn load_gltf_with_textures( let length = view.length(); if offset + length <= buffer_data[buf_idx].len() { let img_data = &buffer_data[buf_idx][offset..offset + length]; - // Decode image (PNG/JPEG) - if let Ok(img) = image::load_from_memory(img_data) { - let rgba = img.to_rgba8(); - let (w, h) = (rgba.width(), rgba.height()); + // KTX2 blocks upload as they are; PNG/JPEG decode. + if let Some(index) = register_compressed_image( + renderer, + img_data, + is_normal, + is_srgb, + mask_coverage_references.contains_key(&image_idx), + ) { + texture_indices.push(index); + } else if let Some((rgba, w, h)) = + decode_texture_bytes(img_data, "embedded-image") + { texture_indices.push(register_gltf_image_with_mask_variants( renderer, image_idx, @@ -586,7 +597,15 @@ pub(super) fn load_gltf_with_textures( } else { (None, uri.to_string()) }; - match bytes.and_then(|b| decode_texture_bytes(&b, &effective_uri)) { + let direct = bytes.as_deref().and_then(|b| { + let masked = mask_coverage_references.contains_key(&image_idx); + register_compressed_image(renderer, b, is_normal, is_srgb, masked) + }); + let decoded = match direct { + Some(_) => None, + None => bytes.and_then(|b| decode_texture_bytes(&b, &effective_uri)), + }; + match decoded { Some((rgba, w, h)) => { texture_indices.push(register_gltf_image_with_mask_variants( renderer, @@ -601,7 +620,7 @@ pub(super) fn load_gltf_with_textures( &mut mask_texture_indices, )); } - None => texture_indices.push(0), + None => texture_indices.push(direct.unwrap_or(0)), } } } @@ -1076,6 +1095,7 @@ fn load_gltf_staged_impl( let mut staged_textures: Vec = Vec::new(); let mut texture_indices: Vec = Vec::new(); for (image_idx, image) in gltf.images().enumerate() { + let masked = mask_coverage_references.contains_key(&image_idx); let decoded = match image.source() { gltf::image::Source::View { view, .. } => { let buf_idx = view.buffer().index(); @@ -1083,7 +1103,11 @@ fn load_gltf_staged_impl( let offset = view.offset(); let length = view.length(); if offset + length <= buffer.len() { - decode_texture_bytes(&buffer[offset..offset + length], "embedded-image") + stage_texture_bytes( + &buffer[offset..offset + length], + "embedded-image", + masked, + ) } else { None } @@ -1110,13 +1134,13 @@ fn load_gltf_staged_impl( } else { (None, uri.to_string()) }; - bytes.and_then(|bytes| decode_texture_bytes(&bytes, &effective_uri)) + bytes.and_then(|bytes| stage_texture_bytes(&bytes, &effective_uri, masked)) } }; - texture_indices.push(decoded.map_or(0, |(rgba, width, height)| { + texture_indices.push(decoded.map_or(0, |(rgba, width, height, compressed)| { stage_image_variants( image_idx, - rgba, + (rgba, compressed), width, height, normal_image_set.contains(&image_idx), @@ -1432,7 +1456,7 @@ fn load_gltf_staged_impl( #[allow(clippy::too_many_arguments)] fn stage_image_variants( image_index: usize, - rgba: Vec, + (rgba, compressed): (Vec, Option), width: u32, height: u32, is_normal: bool, @@ -1452,6 +1476,7 @@ fn stage_image_variants( is_normal, is_srgb: !is_normal && is_srgb, alpha_coverage_reference: None, + compressed, }); primary = Some(staged.len() as u32); } @@ -1464,6 +1489,7 @@ fn stage_image_variants( is_normal: false, is_srgb: true, alpha_coverage_reference: Some(*reference), + compressed: None, }); mask_indices.insert((image_index, reference.to_bits()), staged.len() as u32); primary.get_or_insert(staged.len() as u32); diff --git a/native/shared/src/models_gltf_texture_io.rs b/native/shared/src/models_gltf_texture_io.rs index 3600b2ce..e77ee953 100644 --- a/native/shared/src/models_gltf_texture_io.rs +++ b/native/shared/src/models_gltf_texture_io.rs @@ -1,5 +1,42 @@ //! Texture-byte and URI helpers for the glTF loader. +use crate::compressed_texture::CompressedImage; + +/// Upload a KTX2 image (ASTC / BC7 blocks with authored mips) without +/// decoding it. `None` when the bytes are something else, the adapter lacks +/// the block format, or the image feeds an alpha-MASK material: coverage +/// mips are baked per cutoff from the decoded texels, so those images take +/// the RGBA8 path. +pub(super) fn register_compressed_image( + renderer: &mut crate::renderer::Renderer, + bytes: &[u8], + is_normal: bool, + is_srgb: bool, + feeds_alpha_mask: bool, +) -> Option { + if feeds_alpha_mask { + return None; + } + let image = CompressedImage::from_ktx2(bytes)?; + renderer.register_texture_compressed(&image, is_normal, is_srgb) +} + +/// Staged (no renderer yet) counterpart of [`decode_texture_bytes`]: a KTX2 +/// image stays compressed, with no texels, unless it feeds an alpha-MASK +/// material. Whether it uploads as blocks is decided at commit. +pub(super) fn stage_texture_bytes( + bytes: &[u8], + uri: &str, + feeds_alpha_mask: bool, +) -> Option<(Vec, u32, u32, Option)> { + if !feeds_alpha_mask { + if let Some(image) = CompressedImage::from_ktx2(bytes) { + return Some((Vec::new(), image.width, image.height, Some(image))); + } + } + decode_texture_bytes(bytes, uri).map(|(rgba, width, height)| (rgba, width, height, None)) +} + /// Replace the extension on a URI (keeps directories / query strings /// untouched). Used to fall back from `foo.png` → `foo.dds` when a /// glTF references a PNG URI that isn't on disk but the DDS sibling is. @@ -20,6 +57,11 @@ pub(super) fn swap_extension(uri: &str, new_ext: &str) -> String { /// Lumberyard Bistro that ship BC-compressed textures), falling back /// to the `image` crate for PNG/JPEG/etc. Returns None on failure. pub(super) fn decode_texture_bytes(bytes: &[u8], uri: &str) -> Option<(Vec, u32, u32)> { + #[cfg(feature = "image-extras")] + if crate::compressed_texture::is_ktx2(bytes) { + let image = CompressedImage::from_ktx2(bytes)?; + return Some((image.decode_rgba8()?, image.width, image.height)); + } let is_dds = uri.to_ascii_lowercase().ends_with(".dds") || bytes.len() >= 4 && &bytes[..4] == b"DDS "; if is_dds { diff --git a/native/shared/src/renderer/device_negotiation.rs b/native/shared/src/renderer/device_negotiation.rs index f4df5e2d..9e2c3b0c 100644 --- a/native/shared/src/renderer/device_negotiation.rs +++ b/native/shared/src/renderer/device_negotiation.rs @@ -209,6 +209,7 @@ fn build_device_request_plans_with_override( for optional in [ wgpu::Features::TIMESTAMP_QUERY, wgpu::Features::TEXTURE_COMPRESSION_BC, + wgpu::Features::TEXTURE_COMPRESSION_ASTC, ] { if supported.contains(optional) { preferred_features |= optional; diff --git a/native/shared/src/renderer/texture_store.rs b/native/shared/src/renderer/texture_store.rs index d1298cb0..afabb6f5 100644 --- a/native/shared/src/renderer/texture_store.rs +++ b/native/shared/src/renderer/texture_store.rs @@ -784,6 +784,116 @@ impl Renderer { ) } + /// True when a block-compressed image can upload without decoding. + pub fn supports_compressed_image( + &self, + image: &crate::compressed_texture::CompressedImage, + ) -> bool { + image.format.texture_format().is_some() + && self + .device + .features() + .contains(image.format.required_feature()) + } + + /// Register a block-compressed texture with its authored mip chain + /// (a KTX2 image from a glTF). The blocks upload untouched. Returns + /// `None` when the adapter lacks the block format; the caller then + /// decodes level zero and takes the RGBA8 path. + pub fn register_texture_compressed( + &mut self, + image: &crate::compressed_texture::CompressedImage, + is_normal_map: bool, + srgb_rgb: bool, + ) -> Option { + if !self.supports_compressed_image(image) { + return None; + } + let format = image.format.texture_format()?; + let (block_width, block_height) = image.format.block_size(); + let (width, height) = (image.width, image.height); + let mip_count = image.levels.len() as u32; + let texture = self.device.create_texture(&wgpu::TextureDescriptor { + label: Some("compressed_texture"), + size: wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + mip_level_count: mip_count, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + for (mip, data) in image.levels.iter().enumerate() { + let blocks_w = (width >> mip).max(1).div_ceil(block_width); + let blocks_h = (height >> mip).max(1).div_ceil(block_height); + // Compressed copies are expressed in whole physical blocks. + self.queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &texture, + mip_level: mip as u32, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, + data, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(blocks_w * 16), + rows_per_image: Some(blocks_h), + }, + wgpu::Extent3d { + width: blocks_w * block_width, + height: blocks_h * block_height, + depth_or_array_layers: 1, + }, + ); + } + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("compressed_texture_bg"), + layout: &self.texture_bind_group_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(&view), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(&self.sampler), + }, + ], + }); + let idx = self.texture_bind_groups.len() as u32; + let srgb = srgb_rgb && !is_normal_map; + let global_id = self.register_global_texture( + &view, + width, + height, + mip_count, + if srgb { + TextureColorSpace::Srgb + } else { + TextureColorSpace::Linear + }, + if is_normal_map { + TextureSemantic::Normal + } else if srgb { + TextureSemantic::BaseColor + } else { + TextureSemantic::MetallicRoughness + }, + false, + ); + self.texture_bind_groups.push(bind_group); + self.textures.push(texture); + self.texture_sizes.push((width, height)); + self.global_texture_ids.push(global_id); + Some(idx) + } + /// Register a cooked DDS texture (output of bloom-cook). /// Gated on `image-extras` (DDS is a beyond-PNG runtime codec). /// diff --git a/native/shared/src/staging.rs b/native/shared/src/staging.rs index f86699dd..8da15d62 100644 --- a/native/shared/src/staging.rs +++ b/native/shared/src/staging.rs @@ -19,6 +19,40 @@ pub struct StagedTexture { /// MASK-only texture-space cutoff used to build lower mips whose alpha /// stores surviving texel coverage. None preserves ordinary color mips. pub alpha_coverage_reference: Option, + /// A KTX2 image kept as GPU blocks (`data` is then empty). It uploads + /// untouched when the adapter has the block format and is decoded at + /// commit otherwise. + pub compressed: Option, +} + +impl StagedTexture { + /// Create the GPU texture; returns the renderer texture index. + pub fn register(&self, renderer: &mut crate::renderer::Renderer) -> u32 { + #[allow(unused_mut)] + let mut decoded: Option> = None; + if let Some(image) = &self.compressed { + if let Some(index) = + renderer.register_texture_compressed(image, self.is_normal, self.is_srgb) + { + return index; + } + #[cfg(feature = "image-extras")] + { + decoded = image.decode_rgba8(); + } + if decoded.is_none() { + return 0; + } + } + renderer.register_texture_kind_with_color_space( + self.width, + self.height, + decoded.as_deref().unwrap_or(&self.data), + self.is_normal, + self.is_srgb, + self.alpha_coverage_reference, + ) + } } #[cfg(feature = "models3d")] @@ -90,6 +124,7 @@ pub fn decode_and_stage_texture(file_data: &[u8]) -> f64 { is_normal: false, is_srgb: true, alpha_coverage_reference: None, + compressed: None, }) } diff --git a/native/tvos/Cargo.lock b/native/tvos/Cargo.lock index 884c0ce7..635ef7d7 100644 --- a/native/tvos/Cargo.lock +++ b/native/tvos/Cargo.lock @@ -38,6 +38,12 @@ dependencies = [ "libloading", ] +[[package]] +name = "astc-decode" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6058e6202e20b7fa445692ec4b77ca8eb02508091fcd479ea753d9f60e376b" + [[package]] name = "autocfg" version = "1.5.0" @@ -135,6 +141,7 @@ dependencies = [ name = "bloom-shared" version = "0.1.0" dependencies = [ + "astc-decode", "bloom-geometry-format", "bloom-scene-format", "bytemuck", diff --git a/native/visionos/Cargo.lock b/native/visionos/Cargo.lock index bc13f097..b2449846 100644 --- a/native/visionos/Cargo.lock +++ b/native/visionos/Cargo.lock @@ -38,6 +38,12 @@ dependencies = [ "libloading", ] +[[package]] +name = "astc-decode" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6058e6202e20b7fa445692ec4b77ca8eb02508091fcd479ea753d9f60e376b" + [[package]] name = "autocfg" version = "1.5.1" @@ -135,6 +141,7 @@ dependencies = [ name = "bloom-shared" version = "0.1.0" dependencies = [ + "astc-decode", "bloom-geometry-format", "bloom-scene-format", "bytemuck", diff --git a/native/web/Cargo.lock b/native/web/Cargo.lock index 405f50bd..e0d3b1b0 100644 --- a/native/web/Cargo.lock +++ b/native/web/Cargo.lock @@ -38,6 +38,12 @@ dependencies = [ "libloading", ] +[[package]] +name = "astc-decode" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6058e6202e20b7fa445692ec4b77ca8eb02508091fcd479ea753d9f60e376b" + [[package]] name = "autocfg" version = "1.5.0" @@ -135,6 +141,7 @@ dependencies = [ name = "bloom-shared" version = "0.1.0" dependencies = [ + "astc-decode", "bloom-geometry-format", "bloom-scene-format", "bytemuck", diff --git a/native/windows/Cargo.lock b/native/windows/Cargo.lock index 83ae046d..cb20d09b 100644 --- a/native/windows/Cargo.lock +++ b/native/windows/Cargo.lock @@ -38,6 +38,12 @@ dependencies = [ "libloading", ] +[[package]] +name = "astc-decode" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6058e6202e20b7fa445692ec4b77ca8eb02508091fcd479ea753d9f60e376b" + [[package]] name = "autocfg" version = "1.5.0" @@ -135,6 +141,7 @@ dependencies = [ name = "bloom-shared" version = "0.1.0" dependencies = [ + "astc-decode", "bloom-geometry-format", "bloom-scene-format", "bytemuck", diff --git a/tools/bloom-cook/Cargo.lock b/tools/bloom-cook/Cargo.lock index 774a27e4..f570e47b 100644 --- a/tools/bloom-cook/Cargo.lock +++ b/tools/bloom-cook/Cargo.lock @@ -38,6 +38,12 @@ dependencies = [ "libloading", ] +[[package]] +name = "astc-decode" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6058e6202e20b7fa445692ec4b77ca8eb02508091fcd479ea753d9f60e376b" + [[package]] name = "autocfg" version = "1.5.1" @@ -119,9 +125,11 @@ dependencies = [ name = "bloom-cook" version = "0.1.0" dependencies = [ + "astc-decode", "bloom-geometry-format", "bloom-scene-format", "bloom-shared", + "ctt-astcenc", "gltf", "half", "image", @@ -216,6 +224,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -278,6 +288,31 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + [[package]] name = "crunchy" version = "0.2.4" @@ -294,6 +329,18 @@ dependencies = [ "typenum", ] +[[package]] +name = "ctt-astcenc" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc6dc5595dd5b65dd4cf644bf0d9159f0bd3de2e37c539a1a8df12fb1ecfdd77" +dependencies = [ + "bitflags", + "cc", + "paste", + "rayon", +] + [[package]] name = "ddsfile" version = "0.5.2" @@ -467,6 +514,17 @@ dependencies = [ "version_check", ] +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + [[package]] name = "gl_generator" version = "0.14.0" @@ -733,6 +791,16 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom", + "libc", +] + [[package]] name = "js-sys" version = "0.3.104" @@ -1024,6 +1092,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -1109,6 +1183,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + [[package]] name = "range-alloc" version = "0.1.5" @@ -1133,6 +1213,26 @@ dependencies = [ "objc2-quartz-core", ] +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + [[package]] name = "redox_syscall" version = "0.5.18" diff --git a/tools/bloom-cook/Cargo.toml b/tools/bloom-cook/Cargo.toml index b61a3c53..701be3da 100644 --- a/tools/bloom-cook/Cargo.toml +++ b/tools/bloom-cook/Cargo.toml @@ -16,6 +16,10 @@ gltf = { version = "1.4", default-features = false, features = [ "utils", "KHR_materials_pbrSpecularGlossiness", ] } +# glb-compress: ARM's reference ASTC encoder (vendored, built by cc) and a +# decoder to report the quality of what was written. +ctt-astcenc = { version = "0.6", features = ["rayon"] } +astc-decode = "0.3" half = "2" meshopt = "0.6.2" serde_json = "1" diff --git a/tools/bloom-cook/glb_compress.rs b/tools/bloom-cook/glb_compress.rs new file mode 100644 index 00000000..7b286e69 --- /dev/null +++ b/tools/bloom-cook/glb_compress.rs @@ -0,0 +1,699 @@ +//! `glb-compress`: rewrite a GLB so its embedded images are KTX2 containers +//! of ASTC blocks with the engine's own mip chains. +//! +//! The runtime uploads those blocks untouched on adapters with ASTC (every +//! Apple GPU, most mobile GPUs) and decodes level zero elsewhere, so one file +//! loads everywhere. A 4096² texture drops from 85 MB of RGBA8 plus mips to +//! 22 MB at 4×4 or 10 MB at 6×6, and load skips PNG inflate and mip filtering. +//! +//! Mips are built exactly as the runtime builds them for RGBA8 uploads: +//! sRGB-aware averaging for colour, plain averaging for data, and +//! renormalised direction with accumulated variance in alpha for normal maps. +//! Images that feed an alpha-MASK material are left alone: their coverage +//! mips depend on the material cutoff and the runtime bakes them from texels. +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +use bloom_shared::compressed_texture::{BlockFormat, CompressedImage}; +use serde_json::Value; + +const GLB_MAGIC: u32 = 0x4654_6C67; +const CHUNK_JSON: u32 = 0x4E4F_534A; +const CHUNK_BIN: u32 = 0x004E_4942; + +/// How one image would be encoded: normal map, sRGB colour, block footprint. +type ImagePlan = (bool, bool, (u8, u8)); + +#[derive(Clone, Copy)] +struct Options { + color: (u8, u8), + /// `None` leaves normal maps as they are. + normal: Option<(u8, u8)>, + preset: ctt_astcenc::Preset, +} + +fn parse_block(value: &str) -> Result<(u8, u8), String> { + let parsed = value + .split_once('x') + .and_then(|(w, h)| Some((w.parse::().ok()?, h.parse::().ok()?))); + match parsed { + Some((width, height)) + if BlockFormat::Astc { width, height }.vk_format(false).is_some() => + { + Ok((width, height)) + } + _ => Err(format!( + "unsupported ASTC block {value:?}: use 4x4, 5x5, 6x6, 8x8, 10x10, 12x12 or a listed in-between size" + )), + } +} + +fn parse_options(flags: &[String]) -> Result { + let mut options = Options { + color: (4, 4), + normal: Some((4, 4)), + preset: ctt_astcenc::Preset::Thorough, + }; + let mut iter = flags.iter(); + while let Some(flag) = iter.next() { + let mut value = || iter.next().ok_or_else(|| format!("{flag} needs a value")); + match flag.as_str() { + "--astc" => options.color = parse_block(value()?)?, + "--normal-astc" => { + let value = value()?; + options.normal = if value == "keep" { + None + } else { + Some(parse_block(value)?) + }; + } + "--quality" => { + options.preset = match value()?.as_str() { + "fast" => ctt_astcenc::Preset::Fast, + "medium" => ctt_astcenc::Preset::Medium, + "thorough" => ctt_astcenc::Preset::Thorough, + "exhaustive" => ctt_astcenc::Preset::Exhaustive, + other => return Err(format!("unknown --quality {other:?}")), + } + } + other => return Err(format!("unknown glb-compress flag {other:?}")), + } + } + Ok(options) +} + +/// Image index a texture-info object (`{"index": texture}`) resolves to. +fn image_of(root: &Value, info: Option<&Value>) -> Option { + let texture = info?.get("index")?.as_u64()? as usize; + let source = root + .get("textures")? + .get(texture)? + .get("source")? + .as_u64()?; + Some(source as usize) +} + +#[derive(Default)] +struct Roles { + normal: BTreeSet, + srgb: BTreeSet, + alpha_mask: BTreeSet, +} + +/// Mirrors the runtime's classification in `models_gltf*.rs`. +fn classify(root: &Value) -> Roles { + let mut roles = Roles::default(); + let empty = Vec::new(); + for material in root + .get("materials") + .and_then(Value::as_array) + .unwrap_or(&empty) + { + let extension = |name: &str, key: &str| { + let info = material.get("extensions")?.get(name)?.get(key); + image_of(root, info) + }; + roles + .normal + .extend(image_of(root, material.get("normalTexture"))); + roles.normal.extend(extension( + "KHR_materials_clearcoat", + "clearcoatNormalTexture", + )); + let pbr = material.get("pbrMetallicRoughness"); + let base = image_of(root, pbr.and_then(|pbr| pbr.get("baseColorTexture"))); + let diffuse = extension("KHR_materials_pbrSpecularGlossiness", "diffuseTexture"); + roles.srgb.extend(base); + roles.srgb.extend(diffuse); + roles + .srgb + .extend(image_of(root, material.get("emissiveTexture"))); + roles.srgb.extend(extension( + "KHR_materials_pbrSpecularGlossiness", + "specularGlossinessTexture", + )); + roles + .srgb + .extend(extension("KHR_materials_specular", "specularColorTexture")); + roles + .srgb + .extend(extension("KHR_materials_sheen", "sheenColorTexture")); + if material.get("alphaMode").and_then(Value::as_str) == Some("MASK") { + roles.alpha_mask.extend(base.or(diffuse)); + } + } + roles +} + +/// Encode one RGBA8 level with ARM's reference encoder. Blocks are tuned for +/// the 8-bit decode the runtime's UNORM formats use, and the error is weighed +/// in the stored (display-encoded) space for every role. +fn encode_level( + rgba: &[u8], + width: u32, + height: u32, + block: (u8, u8), + preset: ctt_astcenc::Preset, +) -> Result, String> { + use ctt_astcenc::bindings::{astcenc_image, astcenc_type_ASTCENC_TYPE_U8}; + let failed = |error: ctt_astcenc::Error| format!("ASTC encoder: {error:?}"); + let config = ctt_astcenc::config_init( + ctt_astcenc::Profile::Ldr, + u32::from(block.0), + u32::from(block.1), + 1, + preset, + ctt_astcenc::Flags::USE_DECODE_UNORM8, + ) + .map_err(failed)?; + let mut context = ctt_astcenc::Context::new_parallel(&config).map_err(failed)?; + let mut texels = rgba.to_vec(); + let mut slices = [texels.as_mut_ptr().cast::()]; + let mut image = astcenc_image { + dim_x: width, + dim_y: height, + dim_z: 1, + data_type: astcenc_type_ASTCENC_TYPE_U8, + data: slices.as_mut_ptr(), + }; + let format = BlockFormat::Astc { + width: block.0, + height: block.1, + }; + let mut blocks = vec![0u8; format.level_bytes(width, height)]; + context + .compress(&mut image, ctt_astcenc::Swizzle::IDENTITY, &mut blocks) + .map_err(failed)?; + Ok(blocks) +} + +struct Encoded { + ktx2: Vec, + report: String, +} + +fn encode_image( + index: usize, + bytes: &[u8], + is_normal: bool, + is_srgb: bool, + block: (u8, u8), + preset: ctt_astcenc::Preset, +) -> Result { + let image = image::load_from_memory(bytes) + .map_err(|error| format!("image {index}: {error}"))? + .to_rgba8(); + let (width, height) = image.dimensions(); + let (mip_data, mip_levels) = if is_normal { + crate::texture_cook::build_normal_mip_chain(&image) + } else { + bloom_shared::renderer::build_cooked_color_mip_chain( + width, + height, + image.as_raw(), + None, + is_srgb, + ) + }; + // Normal maps carry variance in alpha (zero at level zero). + let alpha = is_normal || image.pixels().any(|pixel| pixel[3] != 255); + let mut extents = Vec::with_capacity(mip_levels as usize); + let mut offset = 0usize; + for level in 0..mip_levels { + let (level_width, level_height) = ((width >> level).max(1), (height >> level).max(1)); + let length = (level_width * level_height * 4) as usize; + extents.push((offset, length, level_width, level_height)); + offset += length; + } + // The encoder spreads each level over every core itself. + let mut levels = Vec::with_capacity(extents.len()); + for &(offset, length, level_width, level_height) in &extents { + let texels = &mip_data[offset..offset + length]; + levels.push(encode_level( + texels, + level_width, + level_height, + block, + preset, + )?); + } + let compressed = CompressedImage { + format: BlockFormat::Astc { + width: block.0, + height: block.1, + }, + width, + height, + srgb: is_srgb && !is_normal, + levels, + }; + let psnr = level_zero_psnr(&compressed, &mip_data[..extents[0].1], alpha); + let ktx2 = compressed + .to_ktx2() + .ok_or_else(|| format!("image {index}: cannot serialise KTX2"))?; + let role = if is_normal { + "normal" + } else if is_srgb { + "colour" + } else { + "data" + }; + Ok(Encoded { + report: format!( + " image {index}: {width}x{height} {role} -> ASTC {}x{} {mip_levels} mips, \ + {:.1} MB RGBA8 -> {:.1} MB on the GPU, {} -> {} bytes in the file, PSNR {psnr:.1} dB", + block.0, + block.1, + mip_data.len() as f64 / 1e6, + compressed.levels.iter().map(Vec::len).sum::() as f64 / 1e6, + bytes.len(), + ktx2.len(), + ), + ktx2, + }) +} + +/// Peak signal-to-noise ratio of the decoded top level against its source. +fn level_zero_psnr(image: &CompressedImage, source: &[u8], alpha: bool) -> f64 { + let BlockFormat::Astc { width, height } = image.format else { + return f64::NAN; + }; + let channels = if alpha { 4 } else { 3 }; + let row = image.width as usize * 4; + let mut squared = 0f64; + let decoded = astc_decode::astc_decode( + image.levels[0].as_slice(), + image.width, + image.height, + astc_decode::Footprint::new(u32::from(width), u32::from(height)), + |x, y, texel| { + let at = y as usize * row + x as usize * 4; + for channel in 0..channels { + let difference = f64::from(texel[channel]) - f64::from(source[at + channel]); + squared += difference * difference; + } + }, + ); + if decoded.is_err() { + return f64::NAN; + } + let mean = squared / (image.width as f64 * image.height as f64 * channels as f64); + if mean == 0.0 { + f64::INFINITY + } else { + 10.0 * (255.0f64 * 255.0 / mean).log10() + } +} + +fn read_u32(bytes: &[u8], at: usize) -> Option { + Some(u32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?)) +} + +/// The JSON document, the binary chunk, and any further chunks verbatim +/// (header included) so extension data survives the rewrite. +fn split_glb(data: &[u8]) -> Result<(Value, &[u8], Vec), String> { + if read_u32(data, 0) != Some(GLB_MAGIC) || read_u32(data, 4) != Some(2) { + return Err("not a glTF 2.0 binary (.glb)".to_string()); + } + let mut json = None; + let mut bin: Option<&[u8]> = None; + let mut other = Vec::new(); + let mut at = 12usize; + while let (Some(length), Some(kind)) = (read_u32(data, at), read_u32(data, at + 4)) { + let end = at + 8 + length as usize; + let body = data.get(at + 8..end).ok_or("truncated GLB chunk")?; + match kind { + CHUNK_JSON if json.is_none() => { + json = Some(serde_json::from_slice::(body).map_err(|e| e.to_string())?) + } + CHUNK_BIN if bin.is_none() => bin = Some(body), + _ => { + other.extend_from_slice(&data[at..end]); + other.resize(other.len().next_multiple_of(4), 0); + } + } + at = end.next_multiple_of(4); + } + Ok(( + json.ok_or("GLB has no JSON chunk")?, + bin.unwrap_or(&[]), + other, + )) +} + +fn view_range(root: &Value, view: usize) -> Option<(usize, usize)> { + let view = root.get("bufferViews")?.get(view)?; + if view.get("buffer")?.as_u64()? != 0 { + return None; + } + let offset = view.get("byteOffset").and_then(Value::as_u64).unwrap_or(0) as usize; + Some((offset, view.get("byteLength")?.as_u64()? as usize)) +} + +/// Compress the images of `data` (a GLB); returns the new file and a report. +pub(crate) fn compress_glb(data: &[u8], flags: &[String]) -> Result<(Vec, String), String> { + let options = parse_options(flags)?; + let (mut root, bin, other_chunks) = split_glb(data)?; + let roles = classify(&root); + + // image index -> (buffer view, block size) + let mut jobs: BTreeMap = BTreeMap::new(); + let mut notes = Vec::new(); + let images = root.get("images").and_then(Value::as_array).cloned(); + for (index, image) in images.unwrap_or_default().iter().enumerate() { + let Some(view) = image.get("bufferView").and_then(Value::as_u64) else { + notes.push(format!(" image {index}: external file, left as it is")); + continue; + }; + let is_normal = roles.normal.contains(&index); + if roles.alpha_mask.contains(&index) { + notes.push(format!( + " image {index}: alpha-MASK base colour, left as it is" + )); + } else if let Some(block) = if is_normal { + options.normal + } else { + Some(options.color) + } { + jobs.insert(index, (view as usize, block)); + } else { + notes.push(format!(" image {index}: normal map, left as it is")); + } + } + + // Images may share a buffer view. Its bytes can only be replaced when + // every image on it is compressed the same way; otherwise one of them + // would keep a PNG MIME type over KTX2 bytes, or get the wrong mips. + let mut by_view: BTreeMap>> = BTreeMap::new(); + let images = root.get("images").and_then(Value::as_array).cloned(); + for (index, image) in images.unwrap_or_default().iter().enumerate() { + if let Some(view) = image.get("bufferView").and_then(Value::as_u64) { + let plan = jobs.get(&index).map(|&(_, block)| { + ( + roles.normal.contains(&index), + roles.srgb.contains(&index), + block, + ) + }); + by_view.entry(view as usize).or_default().push(plan); + } + } + jobs.retain(|index, (view, _)| { + let plans = &by_view[view]; + let consistent = plans.iter().all(|plan| plan.is_some() && *plan == plans[0]); + if !consistent { + notes.push(format!( + " image {index}: shares its data with an image that is used differently, \ + left as it is" + )); + } + consistent + }); + + let mut replacements: BTreeMap> = BTreeMap::new(); + for (&index, &(view, block)) in &jobs { + let (offset, length) = + view_range(&root, view).ok_or_else(|| format!("image {index}: bad buffer view"))?; + let source = bin + .get(offset..offset + length) + .ok_or_else(|| format!("image {index}: buffer view outside the binary chunk"))?; + if bloom_shared::compressed_texture::is_ktx2(source) { + notes.push(format!(" image {index}: already KTX2, left as it is")); + continue; + } + let is_normal = roles.normal.contains(&index); + let encoded = encode_image( + index, + source, + is_normal, + roles.srgb.contains(&index), + block, + options.preset, + )?; + notes.push(encoded.report); + replacements.insert(view, encoded.ktx2); + root["images"][index]["mimeType"] = Value::from("image/ktx2"); + } + + // Rebuild the binary chunk view by view so the replaced PNG bytes are gone. + let view_count = root + .get("bufferViews") + .and_then(Value::as_array) + .map_or(0, Vec::len); + let mut order: Vec = (0..view_count).collect(); + order.sort_by_key(|&view| view_range(&root, view).map_or(usize::MAX, |(offset, _)| offset)); + let mut new_bin = Vec::with_capacity(bin.len()); + for view in order { + let Some((offset, length)) = view_range(&root, view) else { + continue; + }; + let bytes = match replacements.get(&view) { + Some(bytes) => bytes.as_slice(), + None => bin + .get(offset..offset + length) + .ok_or_else(|| format!("buffer view {view} lies outside the binary chunk"))?, + }; + new_bin.resize(new_bin.len().next_multiple_of(4), 0); + root["bufferViews"][view]["byteOffset"] = Value::from(new_bin.len()); + root["bufferViews"][view]["byteLength"] = Value::from(bytes.len()); + new_bin.extend_from_slice(bytes); + } + new_bin.resize(new_bin.len().next_multiple_of(4), 0); + if root + .get("buffers") + .and_then(|buffers| buffers.get(0)) + .is_some() + { + root["buffers"][0]["byteLength"] = Value::from(new_bin.len()); + } + + let mut json = serde_json::to_vec(&root).map_err(|error| error.to_string())?; + json.resize(json.len().next_multiple_of(4), b' '); + let total = 12 + 8 + json.len() + 8 + new_bin.len() + other_chunks.len(); + let mut out = Vec::with_capacity(total); + for value in [GLB_MAGIC, 2, total as u32, json.len() as u32, CHUNK_JSON] { + out.extend_from_slice(&value.to_le_bytes()); + } + out.extend_from_slice(&json); + out.extend_from_slice(&(new_bin.len() as u32).to_le_bytes()); + out.extend_from_slice(&CHUNK_BIN.to_le_bytes()); + out.extend_from_slice(&new_bin); + out.extend_from_slice(&other_chunks); + + let report = format!( + "{} image(s) compressed, {} -> {} bytes\n{}", + replacements.len(), + data.len(), + out.len(), + notes.join("\n") + ); + Ok((out, report)) +} + +pub(crate) fn compress_glb_command( + input: &Path, + output: &Path, + flags: &[String], +) -> Result { + let data = + std::fs::read(input).map_err(|error| format!("read {}: {error}", input.display()))?; + let (out, report) = compress_glb(&data, flags)?; + if let Some(parent) = output + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + { + std::fs::create_dir_all(parent).map_err(|error| error.to_string())?; + } + std::fs::write(output, out).map_err(|error| format!("write {}: {error}", output.display()))?; + Ok(format!( + "{} -> {}: {report}", + input.display(), + output.display() + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn png(width: u32, height: u32, pixel: impl Fn(u32, u32) -> [u8; 4]) -> Vec { + let image = image::RgbaImage::from_fn(width, height, |x, y| image::Rgba(pixel(x, y))); + let mut bytes = std::io::Cursor::new(Vec::new()); + image + .write_to(&mut bytes, image::ImageFormat::Png) + .expect("PNG encodes"); + bytes.into_inner() + } + + /// A one-triangle GLB with a base-colour image and a normal map. + fn sample_glb(alpha_mode: &str) -> Vec { + let color = png(24, 16, |x, y| [(x * 10) as u8, (y * 15) as u8, 90, 255]); + let normal = png(16, 16, |_, _| [128, 128, 255, 255]); + let mut bin: Vec = Vec::new(); + for value in [0f32, 0., 0., 1., 0., 0., 0., 1., 0.] { + bin.extend_from_slice(&value.to_le_bytes()); + } + let color_at = bin.len(); + bin.extend_from_slice(&color); + bin.resize(bin.len().next_multiple_of(4), 0); + let normal_at = bin.len(); + bin.extend_from_slice(&normal); + bin.resize(bin.len().next_multiple_of(4), 0); + let json = serde_json::json!({ + "asset": {"version": "2.0"}, + "scenes": [{"nodes": [0]}], + "nodes": [{"mesh": 0}], + "meshes": [{"primitives": [{"attributes": {"POSITION": 0}, "material": 0}]}], + "materials": [{ + "alphaMode": alpha_mode, + "pbrMetallicRoughness": {"baseColorTexture": {"index": 0}}, + "normalTexture": {"index": 1} + }], + "textures": [{"source": 0}, {"source": 1}], + "images": [ + {"bufferView": 1, "mimeType": "image/png"}, + {"bufferView": 2, "mimeType": "image/png"} + ], + "accessors": [{ + "bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3", + "min": [0.0, 0.0, 0.0], "max": [1.0, 1.0, 0.0] + }], + "bufferViews": [ + {"buffer": 0, "byteOffset": 0, "byteLength": 36}, + {"buffer": 0, "byteOffset": color_at, "byteLength": color.len()}, + {"buffer": 0, "byteOffset": normal_at, "byteLength": normal.len()} + ], + "buffers": [{"byteLength": bin.len()}] + }); + let mut json = serde_json::to_vec(&json).unwrap(); + json.resize(json.len().next_multiple_of(4), b' '); + let total = 28 + json.len() + bin.len(); + let mut out = Vec::new(); + for value in [GLB_MAGIC, 2, total as u32, json.len() as u32, CHUNK_JSON] { + out.extend_from_slice(&value.to_le_bytes()); + } + out.extend_from_slice(&json); + out.extend_from_slice(&(bin.len() as u32).to_le_bytes()); + out.extend_from_slice(&CHUNK_BIN.to_le_bytes()); + out.extend_from_slice(&bin); + out + } + + fn image_bytes<'a>(root: &Value, bin: &'a [u8], image: usize) -> &'a [u8] { + let view = root["images"][image]["bufferView"].as_u64().unwrap() as usize; + let (offset, length) = view_range(root, view).unwrap(); + &bin[offset..offset + length] + } + + #[test] + fn images_become_ktx2_and_geometry_is_untouched() { + let source = sample_glb("OPAQUE"); + let (out, report) = compress_glb(&source, &["--astc".into(), "6x6".into()]).unwrap(); + assert!(report.starts_with("2 image(s) compressed"), "{report}"); + let (root, bin, _) = split_glb(&out).unwrap(); + let (source_root, source_bin, _) = split_glb(&source).unwrap(); + let (offset, length) = view_range(&root, 0).unwrap(); + let (source_offset, _) = view_range(&source_root, 0).unwrap(); + assert_eq!( + &bin[offset..offset + length], + &source_bin[source_offset..source_offset + 36] + ); + assert_eq!(root["images"][0]["mimeType"], "image/ktx2"); + assert_eq!(root["buffers"][0]["byteLength"], bin.len()); + + let color = CompressedImage::from_ktx2(image_bytes(&root, bin, 0)).unwrap(); + assert_eq!( + color.format, + BlockFormat::Astc { + width: 6, + height: 6 + } + ); + assert_eq!((color.width, color.height, color.levels.len()), (24, 16, 5)); + assert!(color.srgb); + let normal = CompressedImage::from_ktx2(image_bytes(&root, bin, 1)).unwrap(); + assert_eq!( + normal.format, + BlockFormat::Astc { + width: 4, + height: 4 + } + ); + assert_eq!( + (normal.width, normal.height, normal.levels.len()), + (16, 16, 5) + ); + assert!(!normal.srgb); + } + + #[test] + fn flat_normal_map_keeps_direction_and_zero_variance() { + let (out, _) = compress_glb(&sample_glb("OPAQUE"), &[]).unwrap(); + let (root, bin, _) = split_glb(&out).unwrap(); + let bytes = image_bytes(&root, bin, 1); + let image = CompressedImage::from_ktx2(bytes).unwrap(); + let mut worst = 0i32; + astc_decode::astc_decode( + image.levels[0].as_slice(), + 16, + 16, + astc_decode::Footprint::new(4, 4), + |_, _, texel| { + for (value, expected) in texel.iter().zip([128, 128, 255, 0]) { + worst = worst.max((i32::from(*value) - expected).abs()); + } + }, + ) + .unwrap(); + assert!(worst <= 1, "flat normal drifted by {worst}"); + } + + #[test] + fn alpha_mask_base_colour_and_kept_normals_stay_png() { + let flags = ["--normal-astc".to_string(), "keep".to_string()]; + let (out, report) = compress_glb(&sample_glb("MASK"), &flags).unwrap(); + assert!(report.starts_with("0 image(s) compressed"), "{report}"); + let (root, bin, _) = split_glb(&out).unwrap(); + assert_eq!(root["images"][0]["mimeType"], "image/png"); + assert!(image_bytes(&root, bin, 0).starts_with(b"\x89PNG")); + assert!(image_bytes(&root, bin, 1).starts_with(b"\x89PNG")); + } + + #[test] + fn shared_image_data_and_extra_chunks_are_preserved() { + // Point the normal map at the colour image's bytes: the two images + // now share a buffer view but need different mips. + let source = sample_glb("OPAQUE"); + let (mut root, bin, _) = split_glb(&source).unwrap(); + root["images"][1]["bufferView"] = Value::from(1); + let mut json = serde_json::to_vec(&root).unwrap(); + json.resize(json.len().next_multiple_of(4), b' '); + let extra = [4u32.to_le_bytes(), 0x1234_5678u32.to_le_bytes(), *b"DATA"].concat(); + let total = 28 + json.len() + bin.len() + extra.len(); + let mut glb = Vec::new(); + for value in [GLB_MAGIC, 2, total as u32, json.len() as u32, CHUNK_JSON] { + glb.extend_from_slice(&value.to_le_bytes()); + } + glb.extend_from_slice(&json); + glb.extend_from_slice(&(bin.len() as u32).to_le_bytes()); + glb.extend_from_slice(&CHUNK_BIN.to_le_bytes()); + glb.extend_from_slice(bin); + glb.extend_from_slice(&extra); + + let (out, report) = compress_glb(&glb, &[]).unwrap(); + assert!(report.starts_with("0 image(s) compressed"), "{report}"); + let (root, bin, other) = split_glb(&out).unwrap(); + assert_eq!(other, extra); + assert_eq!(root["images"][0]["mimeType"], "image/png"); + assert!(image_bytes(&root, bin, 0).starts_with(b"\x89PNG")); + assert_eq!(read_u32(&out, 8), Some(out.len() as u32)); + } + + #[test] + fn unknown_flags_and_blocks_are_rejected() { + let source = sample_glb("OPAQUE"); + assert!(compress_glb(&source, &["--astc".into(), "7x7".into()]).is_err()); + assert!(compress_glb(&source, &["--bogus".into()]).is_err()); + assert!(compress_glb(b"not a glb", &[]).is_err()); + } +} diff --git a/tools/bloom-cook/main.rs b/tools/bloom-cook/main.rs index a009fb8c..5d4fa444 100644 --- a/tools/bloom-cook/main.rs +++ b/tools/bloom-cook/main.rs @@ -16,6 +16,7 @@ //! bloom-cook texture-dir [--linear] //! bloom-cook texture-store [profile] [texture flags] //! bloom-cook texture-benchmark [texture flags] [--iterations N] +//! bloom-cook glb-compress [--astc WxH] [--normal-astc WxH|keep] [--quality Q] //! bloom-cook geometry [geometry limits] //! bloom-cook geometry-inspect //! bloom-cook geometry-store [profile] [limits] @@ -41,6 +42,7 @@ mod geometric_error; mod geometry_cook; mod geometry_format; mod geometry_quantization; +mod glb_compress; mod hierarchy; mod meshlet; mod scene_cook; @@ -106,6 +108,22 @@ fn main() -> ExitCode { } } } + Some("glb-compress") if args.len() >= 3 => { + match glb_compress::compress_glb_command( + Path::new(&args[1]), + Path::new(&args[2]), + &args[3..], + ) { + Ok(report) => { + println!("{report}"); + ExitCode::SUCCESS + } + Err(error) => { + eprintln!("bloom-cook: {error}"); + ExitCode::FAILURE + } + } + } Some("geometry") if args.len() >= 3 => { match geometry_cook::cook_geometry_command( Path::new(&args[1]), diff --git a/tools/bloom-cook/texture_cook.rs b/tools/bloom-cook/texture_cook.rs index b8432c49..c1051765 100644 --- a/tools/bloom-cook/texture_cook.rs +++ b/tools/bloom-cook/texture_cook.rs @@ -343,7 +343,7 @@ fn normal_mip_chain_dds( .map_err(|error| format!("create normal-map DDS: {error}")) } -fn build_normal_mip_chain(image: &image::RgbaImage) -> (Vec, u32) { +pub(crate) fn build_normal_mip_chain(image: &image::RgbaImage) -> (Vec, u32) { let mut mip_data = Vec::with_capacity(image.as_raw().len() * 2); for pixel in image.pixels() { mip_data.extend_from_slice(&[pixel[0], pixel[1], pixel[2], 0]);