diff --git a/native/shared/src/ffi_core/models.rs b/native/shared/src/ffi_core/models.rs index 1c85a296..c89c9af4 100644 --- a/native/shared/src/ffi_core/models.rs +++ b/native/shared/src/ffi_core/models.rs @@ -231,7 +231,8 @@ macro_rules! __bloom_ffi_models { let textures = eng.models.exclusive_texture_indices(handle); eng.models.unload_model(handle); for idx in textures { - eng.renderer.unload_texture(idx); + // a texture other models share by content stays for them + eng.renderer.release_model_texture(idx); } }) } diff --git a/native/shared/src/models_gltf.rs b/native/shared/src/models_gltf.rs index 67196edb..e77e6f70 100644 --- a/native/shared/src/models_gltf.rs +++ b/native/shared/src/models_gltf.rs @@ -519,6 +519,19 @@ pub(super) fn load_gltf_with_textures( renderer: &mut crate::renderer::Renderer, base_dir: Option<&std::path::Path>, source_label: Option<&str>, +) -> Option { + // a load that fails after taking shared textures lets them go again + renderer.shared_import_begin(); + let model = import_gltf_with_textures(data, renderer, base_dir, source_label); + renderer.shared_import_end(model.is_some()); + model +} + +fn import_gltf_with_textures( + data: &[u8], + renderer: &mut crate::renderer::Renderer, + base_dir: Option<&std::path::Path>, + source_label: Option<&str>, ) -> Option { let (mut gltf, glb_bin) = parse::parse_borrowed(data)?; emit_unsupported_material_extension_diagnostics(&gltf, source_label.unwrap_or("")); @@ -546,9 +559,22 @@ pub(super) fn load_gltf_with_textures( // Extract and register textures let mut texture_indices: Vec = Vec::new(); // maps glTF image index -> renderer texture index + // textures shared by content with other models (renderer/shared_textures.rs), held once by this one + let mut shares = crate::renderer::shared_textures::ModelShares::default(); for (image_idx, image) in gltf.images().enumerate() { let is_normal = normal_image_set.contains(&image_idx); let is_srgb = !is_normal && srgb_image_set.contains(&image_idx); + let mask = mask_coverage_references.contains_key(&image_idx); + let shared_key = crate::renderer::shared_textures::image_key( + image.extras().as_ref().map(|raw| raw.get()), + is_normal, + is_srgb, + mask, + ); + if let Some(slot) = renderer.shared_texture_hold(&mut shares, shared_key) { + texture_indices.push(slot); + continue; + } match image.source() { gltf::image::Source::View { view, .. } => { let buf_idx = view.buffer().index(); @@ -568,6 +594,7 @@ pub(super) fn load_gltf_with_textures( data, offset, length, ), ) { + renderer.shared_texture_register(&mut shares, shared_key, index); texture_indices.push(index); } else if let Some((rgba, w, h)) = decode_texture_bytes(img_data, "embedded-image") diff --git a/native/shared/src/renderer/mod.rs b/native/shared/src/renderer/mod.rs index 617f06ea..53a35d3a 100644 --- a/native/shared/src/renderer/mod.rs +++ b/native/shared/src/renderer/mod.rs @@ -112,6 +112,7 @@ mod scene_pass; mod sdf_clipmap_prep; mod shaders; mod shadow_pass; +pub(crate) mod shared_textures; mod sorted_transparency; mod ssgi_pass; #[cfg(not(target_arch = "wasm32"))] @@ -1437,6 +1438,7 @@ pub struct Renderer { // raw bind-pose joint indices; the scene VS skins them per draw) model_gpu_cache: HashMap>>, texture_streaming: texture_streaming::TextureStreaming, + shared_textures: shared_textures::SharedTextures, /// Original model-mesh indices represented by a compact compatibility-only /// cache. Absent means the handle owns an ordinary complete model cache. #[cfg(feature = "models3d")] @@ -8638,6 +8640,7 @@ impl Renderer { persistent_ib_3d_capacity: ib_3d_cap, model_gpu_cache: HashMap::new(), texture_streaming: Default::default(), + shared_textures: Default::default(), #[cfg(feature = "models3d")] model_virtual_compatibility_sources: HashMap::new(), gpu_driven, diff --git a/native/shared/src/renderer/shared_textures.rs b/native/shared/src/renderer/shared_textures.rs new file mode 100644 index 00000000..36b33ade --- /dev/null +++ b/native/shared/src/renderer/shared_textures.rs @@ -0,0 +1,219 @@ +//! Textures shared between models by content. +//! +//! Models embed their textures, and many embed the same one: the Jonah game's +//! chapters held 41 to 60 % of their texture memory twice or more (a material +//! set used by a village, a harbour and a ship; two sailors with one skin). +//! The cook tool (`bloom-cook glb-compress`) writes the SHA-256 of every KTX2 +//! image into its `extras.bloomContentHash`. An image whose hash, and use +//! (normal map, sRGB), the renderer already holds is given that texture slot +//! instead of a new one, and the slot counts the models that hold it: a +//! model's unload frees a shared slot only when no other model holds it. +//! Images without a hash (older files, PNG, alpha-mask variants) load as +//! before, one slot per model. + +use std::collections::HashMap; + +use super::Renderer; + +/// Content hash (128 bits), normal map, sRGB. +pub(crate) type SharedTextureKey = (u128, bool, bool); + +#[derive(Default)] +pub(crate) struct SharedTextures { + by_key: HashMap, + key_of: HashMap, + /// Slots the import in progress holds (taken or added), released again + /// if the import fails. + importing: Vec, +} + +/// The shared textures one model's import holds, by key (an image repeated +/// in one model is held once). +#[derive(Default)] +pub(crate) struct ModelShares(HashMap); + +/// The key an image is shared by: its content hash and use. `None` without a +/// hash, and for an image that feeds an alpha mask (it takes the RGBA path). +pub(crate) fn image_key( + extras: Option<&str>, + is_normal: bool, + srgb: bool, + feeds_alpha_mask: bool, +) -> Option { + if feeds_alpha_mask { + return None; + } + content_hash(extras).map(|hash| (hash, is_normal, srgb)) +} + +/// The top-level `bloomContentHash` of an image's `extras` object (32 hex +/// digits), if any. A key of that name nested deeper is not it. +pub(crate) fn content_hash(extras: Option<&str>) -> Option { + let bytes = extras?.as_bytes(); + let (mut depth, mut i) = (0usize, 0usize); + // the string starting at `at` (a quote): its contents and the index after it + let string = |at: usize| -> Option<(&[u8], usize)> { + let mut j = at + 1; + while j < bytes.len() { + match bytes[j] { + b'\\' => j += 2, + b'"' => return Some((&bytes[at + 1..j], j + 1)), + _ => j += 1, + } + } + None + }; + while i < bytes.len() { + match bytes[i] { + b'{' | b'[' => depth += 1, + b'}' | b']' => depth = depth.saturating_sub(1), + b'"' => { + let (text, after) = string(i)?; + let mut k = after; + while k < bytes.len() && bytes[k].is_ascii_whitespace() { + k += 1; + } + let is_key = bytes.get(k) == Some(&b':'); + if depth == 1 && is_key && text == b"bloomContentHash" { + k += 1; + while k < bytes.len() && bytes[k].is_ascii_whitespace() { + k += 1; + } + if bytes.get(k) != Some(&b'"') { + return None; + } + let (value, _) = string(k)?; + if value.len() != 32 { + return None; + } + return u128::from_str_radix(std::str::from_utf8(value).ok()?, 16).ok(); + } + i = after; + continue; + } + _ => {} + } + i += 1; + } + None +} + +impl Renderer { + /// A model's import begins: what it takes is recorded until it ends. + pub(crate) fn shared_import_begin(&mut self) { + self.shared_textures.importing.clear(); + } + + /// The import ended; a failed one lets go of the shared slots it held. + pub(crate) fn shared_import_end(&mut self, loaded: bool) { + let held = std::mem::take(&mut self.shared_textures.importing); + if !loaded { + for slot in held { + self.release_model_texture(slot); + } + } + } + + /// The slot holding the texture `key` if one does, held by this model + /// (once, however often the model uses it). + pub(crate) fn shared_texture_hold( + &mut self, + shares: &mut ModelShares, + key: Option, + ) -> Option { + let key = key?; + if let Some(&slot) = shares.0.get(&key) { + return Some(slot); + } + let slot = self.shared_texture_take(key)?; + shares.0.insert(key, slot); + Some(slot) + } + + /// `slot` was just made for this model's image `key`: others may share it. + pub(crate) fn shared_texture_register( + &mut self, + shares: &mut ModelShares, + key: Option, + slot: u32, + ) { + if let Some(key) = key { + self.shared_texture_add(key, slot); + shares.0.insert(key, slot); + } + } + + /// The slot already holding the texture `key`, now held once more. + pub(crate) fn shared_texture_take(&mut self, key: SharedTextureKey) -> Option { + let (slot, holders) = self.shared_textures.by_key.get_mut(&key)?; + *holders += 1; + let slot = *slot; + self.shared_textures.importing.push(slot); + Some(slot) + } + + /// `slot` now holds the texture `key`, for one holder. + pub(crate) fn shared_texture_add(&mut self, key: SharedTextureKey, slot: u32) { + if slot == 0 || self.shared_textures.key_of.contains_key(&slot) { + return; + } + self.shared_textures.by_key.insert(key, (slot, 1)); + self.shared_textures.key_of.insert(slot, key); + self.shared_textures.importing.push(slot); + } + + /// A model that held `slot` lets it go: the texture is unloaded unless it + /// is shared and another model still holds it. + pub fn release_model_texture(&mut self, slot: u32) { + if let Some(key) = self.shared_textures.key_of.get(&slot).copied() { + if let Some((_, holders)) = self.shared_textures.by_key.get_mut(&key) { + if *holders > 1 { + *holders -= 1; + return; + } + } + self.shared_textures.by_key.remove(&key); + self.shared_textures.key_of.remove(&slot); + } + self.unload_texture(slot); + } +} + +#[cfg(test)] +mod tests { + use super::content_hash; + + #[test] + fn the_hash_is_read_from_the_extras() { + let h = "0123456789abcdef0123456789abcdef"; + assert_eq!( + content_hash(Some(&format!("{{\"bloomContentHash\":\"{h}\"}}"))), + Some(0x0123456789abcdef0123456789abcdef) + ); + assert_eq!( + content_hash(Some(&format!( + "{{\"a\": 1, \"bloomContentHash\" : \"{h}\" }}" + ))), + Some(0x0123456789abcdef0123456789abcdef) + ); + assert_eq!(content_hash(Some("{\"bloomContentHash\":\"0123\"}")), None); + assert_eq!(content_hash(Some("{\"other\":1}")), None); + // only the top level counts, and a value that merely equals the name is not a key + let nested = format!( + "{{\"a\":{{\"bloomContentHash\":\"{}\"}},\"bloomContentHash\":\"{h}\"}}", + "0".repeat(32) + ); + assert_eq!( + content_hash(Some(&nested)), + Some(0x0123456789abcdef0123456789abcdef) + ); + assert_eq!( + content_hash(Some( + "{\"a\":{\"bloomContentHash\":\"0123456789abcdef0123456789abcdef\"}}" + )), + None + ); + assert_eq!(content_hash(Some("{\"x\":\"bloomContentHash\"}")), None); + assert_eq!(content_hash(None), None); + } +} diff --git a/tools/bloom-cook/glb_compress.rs b/tools/bloom-cook/glb_compress.rs index 23e4850f..7cc7be48 100644 --- a/tools/bloom-cook/glb_compress.rs +++ b/tools/bloom-cook/glb_compress.rs @@ -351,6 +351,47 @@ fn view_range(root: &Value, view: usize) -> Option<(usize, usize)> { } /// Compress the images of `data` (a GLB); returns the new file and a report. +/// Every KTX2 image gets `extras.bloomContentHash`: the first 128 bits of the +/// SHA-256 of its bytes, as 32 hex digits. The engine loads an image whose +/// hash (and use: colour or normal map, sRGB) it already has as the texture it +/// already has, so a texture embedded in many models is in memory once. A +/// hash made here, over all the bytes, is exact and costs the load nothing. +/// Returns how many images were marked. +fn mark_content_hashes(root: &mut Value, bin: &[u8]) -> usize { + use sha2::{Digest, Sha256}; + let count = root + .get("images") + .and_then(Value::as_array) + .map_or(0, Vec::len); + let mut marked = 0; + for index in 0..count { + let Some(view) = root["images"][index] + .get("bufferView") + .and_then(Value::as_u64) + else { + continue; + }; + let Some((offset, length)) = view_range(root, view as usize) else { + continue; + }; + let Some(bytes) = bin.get(offset..offset + length) else { + continue; + }; + if !bloom_shared::compressed_texture::is_ktx2(bytes) { + continue; + } + let digest = Sha256::digest(bytes); + let hex: String = digest[..16].iter().map(|b| format!("{b:02x}")).collect(); + let image = &mut root["images"][index]; + if !image.get("extras").is_some_and(Value::is_object) { + image["extras"] = serde_json::json!({}); + } + image["extras"]["bloomContentHash"] = Value::from(hex); + marked += 1; + } + marked +} + 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)?; @@ -459,6 +500,7 @@ pub(crate) fn compress_glb(data: &[u8], flags: &[String]) -> Result<(Vec, St new_bin.extend_from_slice(bytes); } new_bin.resize(new_bin.len().next_multiple_of(4), 0); + let hashed = mark_content_hashes(&mut root, &new_bin); if root .get("buffers") .and_then(|buffers| buffers.get(0)) @@ -481,10 +523,11 @@ pub(crate) fn compress_glb(data: &[u8], flags: &[String]) -> Result<(Vec, St out.extend_from_slice(&other_chunks); let report = format!( - "{} image(s) compressed, {} -> {} bytes\n{}", + "{} image(s) compressed, {} -> {} bytes, {} content hash(es)\n{}", replacements.len(), data.len(), out.len(), + hashed, notes.join("\n") ); Ok((out, report)) @@ -784,6 +827,32 @@ mod tests { assert_eq!(read_u32(&out, 8), Some(out.len() as u32)); } + #[test] + fn every_ktx2_image_carries_the_hash_of_its_bytes() { + use sha2::{Digest, Sha256}; + let (out, _) = compress_glb(&sample_glb("OPAQUE"), &[]).unwrap(); + let (root, bin, _) = split_glb(&out).unwrap(); + let images = root["images"].as_array().unwrap(); + let mut marked = 0; + for index in 0..images.len() { + let bytes = image_bytes(&root, bin, index); + let hash = root["images"][index]["extras"]["bloomContentHash"].as_str(); + if bloom_shared::compressed_texture::is_ktx2(bytes) { + let digest = Sha256::digest(bytes); + let hex: String = digest[..16].iter().map(|b| format!("{b:02x}")).collect(); + assert_eq!(hash, Some(hex.as_str()), "image {index}"); + marked += 1; + } else { + assert!(hash.is_none(), "image {index} is not KTX2"); + } + } + assert!(marked > 0); + // compressing again keeps the same hashes (KTX2 images are left as they are) + let (again, _) = compress_glb(&out, &[]).unwrap(); + let (root2, _, _) = split_glb(&again).unwrap(); + assert_eq!(root["images"], root2["images"]); + } + #[test] fn unknown_flags_and_blocks_are_rejected() { let source = sample_glb("OPAQUE");