From 152ceb4803429fea3bc9fbbf7b00bd8fdf811d90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Wed, 25 Nov 2026 07:33:35 +0100 Subject: [PATCH 1/5] perf: cheaper model loads and sound memory, no sky rebake for an unchanged sun - set_sun_direction marks the sky-view LUT dirty only when the direction or intensity changes; games set the sun every frame and paid a LUT rebake each time. - The model source cache fingerprints files with a four-lane 64-bit hash instead of SipHash (about 60 ms per 100 MB file on every load and repeat). - glTF loads move the GLB binary chunk into the buffer list instead of cloning it: the peak of a load is two copies of the file, not three. - Sound effects are stored as 16-bit PCM (every decoder produces 16-bit), half the memory of f32, lossless. Co-Authored-By: Claude --- native/shared/src/audio/decode.rs | 8 ++-- native/shared/src/audio/filter.rs | 6 ++- native/shared/src/audio/mod.rs | 25 ++++++++++-- native/shared/src/audio/render.rs | 10 ++--- native/shared/src/models_gltf.rs | 36 +++++++++++------ native/shared/src/models_source_cache.rs | 49 ++++++++++++++++++++++-- native/shared/src/renderer/mod.rs | 11 ++++-- 7 files changed, 112 insertions(+), 33 deletions(-) diff --git a/native/shared/src/audio/decode.rs b/native/shared/src/audio/decode.rs index 11671725..405097ff 100644 --- a/native/shared/src/audio/decode.rs +++ b/native/shared/src/audio/decode.rs @@ -32,11 +32,11 @@ pub fn parse_wav(data: &[u8]) -> Option { let samples = match bits_per_sample { 16 => pcm_data .chunks_exact(2) - .map(|chunk| i16::from_le_bytes([chunk[0], chunk[1]]) as f32 / 32768.0) + .map(|chunk| i16::from_le_bytes([chunk[0], chunk[1]])) .collect(), 8 => pcm_data .iter() - .map(|&b| (b as f32 - 128.0) / 128.0) + .map(|&b| (i16::from(b) - 128) << 8) .collect(), _ => return None, }; @@ -67,7 +67,7 @@ pub fn parse_mp3(data: &[u8]) -> Option { channels = frame.channels as u16; } for &s in &frame.data { - samples.push(s as f32 / 32768.0); + samples.push(s); } } Err(minimp3::Error::Eof) => break, @@ -95,7 +95,7 @@ pub fn parse_ogg(data: &[u8]) -> Option { while let Ok(Some(packet)) = reader.read_dec_packet_itl() { for &sample in &packet { - samples.push(sample as f32 / 32768.0); + samples.push(sample); } } diff --git a/native/shared/src/audio/filter.rs b/native/shared/src/audio/filter.rs index 85941935..3733f5ce 100644 --- a/native/shared/src/audio/filter.rs +++ b/native/shared/src/audio/filter.rs @@ -102,7 +102,11 @@ mod tests { let n = (seconds * SR) as usize; SoundData { samples: (0..n) - .map(|i| 0.5 * (2.0 * std::f32::consts::PI * freq * i as f32 / SR).sin()) + .map(|i| { + crate::audio::pcm16( + 0.5 * (2.0 * std::f32::consts::PI * freq * i as f32 / SR).sin(), + ) + }) .collect(), sample_rate: SR as u32, channels: 1, diff --git a/native/shared/src/audio/mod.rs b/native/shared/src/audio/mod.rs index 0e6c1bb0..37f5160b 100644 --- a/native/shared/src/audio/mod.rs +++ b/native/shared/src/audio/mod.rs @@ -43,12 +43,29 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; /// A loaded sound effect or music track (PCM samples). +/// +/// Kept as 16-bit integers: every decoder (WAV 8/16-bit, MP3, Vorbis) +/// produces 16-bit samples, so this is lossless and half the memory of +/// `f32` (a game's effects held about 95 MB as floats). pub struct SoundData { - pub samples: Vec, + pub samples: Vec, pub sample_rate: u32, pub channels: u16, } +impl SoundData { + /// Sample `i` in [-1, 1). + #[inline] + pub fn sample(&self, i: usize) -> f32 { + f32::from(self.samples[i]) * (1.0 / 32768.0) + } +} + +/// A float sample in [-1, 1] as 16-bit PCM (tests and generated sounds). +pub fn pcm16(x: f32) -> i16 { + (x * 32768.0).round().clamp(-32768.0, 32767.0) as i16 +} + /// Render-side playback state readable from the control side. pub struct MusicShared { pub playing: AtomicBool, @@ -702,7 +719,7 @@ mod tests { fn tone(len: usize) -> SoundData { SoundData { samples: (0..len) - .map(|i| if i % 2 == 0 { 0.5 } else { -0.5 }) + .map(|i| if i % 2 == 0 { pcm16(0.5) } else { pcm16(-0.5) }) .collect(), sample_rate: 44_100, channels: 1, @@ -1053,7 +1070,7 @@ mod tests { /// All-0.5 mono signal: peaks read gains directly. fn flat(len: usize) -> SoundData { SoundData { - samples: vec![0.5; len], + samples: vec![pcm16(0.5); len], sample_rate: 44_100, channels: 1, } @@ -1062,7 +1079,7 @@ mod tests { fn sine(freq: f32, len: usize) -> SoundData { SoundData { samples: (0..len) - .map(|i| (2.0 * std::f32::consts::PI * freq * i as f32 / 44_100.0).sin()) + .map(|i| pcm16((2.0 * std::f32::consts::PI * freq * i as f32 / 44_100.0).sin())) .collect(), sample_rate: 44_100, channels: 1, diff --git a/native/shared/src/audio/render.rs b/native/shared/src/audio/render.rs index 38156bf3..9cddf08f 100644 --- a/native/shared/src/audio/render.rs +++ b/native/shared/src/audio/render.rs @@ -311,10 +311,10 @@ impl Voice { #[inline] fn frame(&self, idx: usize) -> (f32, f32) { if self.data.channels <= 1 { - let s = self.data.samples[idx]; + let s = self.data.sample(idx); (s, s) } else { - (self.data.samples[idx * 2], self.data.samples[idx * 2 + 1]) + (self.data.sample(idx * 2), self.data.sample(idx * 2 + 1)) } } } @@ -1081,7 +1081,7 @@ impl AudioRenderer { while i < output.len() && *position < data.samples.len() { if data.channels == 1 { let sample = - filt(i, data.samples[*position]) * (g0 + dg * (i / 2) as f32); + filt(i, data.sample(*position)) * (g0 + dg * (i / 2) as f32); output[i] += sample; if i + 1 < output.len() { output[i + 1] += sample; @@ -1090,7 +1090,7 @@ impl AudioRenderer { i += 2; } else { output[i] += - filt(i, data.samples[*position]) * (g0 + dg * (i / 2) as f32); + filt(i, data.sample(*position)) * (g0 + dg * (i / 2) as f32); *position += 1; i += 1; } @@ -1177,7 +1177,7 @@ mod tests { fn dummy_sound() -> Arc { Arc::new(SoundData { - samples: vec![0.0; 16], + samples: vec![0; 16], sample_rate: 44_100, channels: 1, }) diff --git a/native/shared/src/models_gltf.rs b/native/shared/src/models_gltf.rs index e7571356..3aab4126 100644 --- a/native/shared/src/models_gltf.rs +++ b/native/shared/src/models_gltf.rs @@ -142,15 +142,18 @@ fn read_accessor_f32( } pub fn load_gltf_animation(data: &[u8]) -> Option { - let gltf = parse::parse_gltf(data)?; + let mut gltf = parse::parse_gltf(data)?; // Get buffer data let mut buffer_data: Vec> = Vec::new(); + let mut bin = gltf.blob.take(); for buffer in gltf.buffers() { match buffer.source() { gltf::buffer::Source::Bin => { - if let Some(blob) = gltf.blob.as_ref() { - buffer_data.push(blob.clone()); + // Moved, not cloned: a clone was a third copy of the file + // (after the read and the parser's) at the peak of the load. + if let Some(blob) = bin.take() { + buffer_data.push(blob); } } gltf::buffer::Source::Uri(uri) => { @@ -484,16 +487,19 @@ pub(super) fn load_gltf_with_textures( base_dir: Option<&std::path::Path>, source_label: Option<&str>, ) -> Option { - let gltf = parse::parse_gltf(data)?; + let mut gltf = parse::parse_gltf(data)?; emit_unsupported_material_extension_diagnostics(&gltf, source_label.unwrap_or("")); // Get buffer data let mut buffer_data: Vec> = Vec::new(); + let mut bin = gltf.blob.take(); for buffer in gltf.buffers() { match buffer.source() { gltf::buffer::Source::Bin => { - if let Some(blob) = gltf.blob.as_ref() { - buffer_data.push(blob.clone()); + // Moved, not cloned: a clone was a third copy of the file + // (after the read and the parser's) at the peak of the load. + if let Some(blob) = bin.take() { + buffer_data.push(blob); } } gltf::buffer::Source::Uri(uri) => { @@ -1066,15 +1072,18 @@ fn load_gltf_staged_impl( ) -> Option { use crate::staging::{StagedModel, StagedTexture}; - let gltf = parse::parse_gltf(data)?; + let mut gltf = parse::parse_gltf(data)?; emit_unsupported_material_extension_diagnostics(&gltf, source_label); let mut buffer_data: Vec> = Vec::new(); + let mut bin = gltf.blob.take(); for buffer in gltf.buffers() { match buffer.source() { gltf::buffer::Source::Bin => { - if let Some(blob) = gltf.blob.as_ref() { - buffer_data.push(blob.clone()); + // Moved, not cloned: a clone was a third copy of the file + // (after the read and the parser's) at the peak of the load. + if let Some(blob) = bin.take() { + buffer_data.push(blob); } } gltf::buffer::Source::Uri(uri) => { @@ -1522,16 +1531,19 @@ fn stage_image_variants( } pub(super) fn load_gltf(data: &[u8]) -> Option { - let gltf = parse::parse_gltf(data)?; + let mut gltf = parse::parse_gltf(data)?; emit_unsupported_material_extension_diagnostics(&gltf, ""); // Get buffer data (for .glb, embedded; for .gltf, inline base64) let mut buffer_data: Vec> = Vec::new(); + let mut bin = gltf.blob.take(); for buffer in gltf.buffers() { match buffer.source() { gltf::buffer::Source::Bin => { - if let Some(blob) = gltf.blob.as_ref() { - buffer_data.push(blob.clone()); + // Moved, not cloned: a clone was a third copy of the file + // (after the read and the parser's) at the peak of the load. + if let Some(blob) = bin.take() { + buffer_data.push(blob); } } gltf::buffer::Source::Uri(uri) => { diff --git a/native/shared/src/models_source_cache.rs b/native/shared/src/models_source_cache.rs index 58c73f96..35040c27 100644 --- a/native/shared/src/models_source_cache.rs +++ b/native/shared/src/models_source_cache.rs @@ -13,7 +13,6 @@ use super::{MeshData, ModelData, ModelPrimitiveSource}; use std::collections::HashMap; -use std::hash::{Hash, Hasher}; use std::path::Path; use std::sync::{Arc, Weak}; @@ -34,10 +33,38 @@ pub struct SourceModelCache { entries: HashMap, } +/// A fast fingerprint of the file's bytes (four independent 64-bit lanes, +/// several GB/s). It only has to notice a file that changed on disk, not +/// resist an adversary. SipHash (`DefaultHasher`) ran at about 1.5 GB/s, so +/// it cost about 60 ms per 100 MB model, on every load and every repeat. fn fingerprint(file_data: &[u8]) -> u64 { - let mut hasher = std::collections::hash_map::DefaultHasher::new(); - file_data.hash(&mut hasher); - hasher.finish() + const K: [u64; 4] = [ + 0x9e37_79b9_7f4a_7c15, + 0xc2b2_ae3d_27d4_eb4f, + 0x1656_67b1_9e37_79f9, + 0x85eb_ca77_c2b2_ae63, + ]; + let mut lane = [K[1], K[2], K[3], K[0]]; + let mut chunks = file_data.chunks_exact(32); + for c in &mut chunks { + for (i, l) in lane.iter_mut().enumerate() { + let mut w = [0u8; 8]; + w.copy_from_slice(&c[i * 8..i * 8 + 8]); + *l = (*l ^ u64::from_le_bytes(w)) + .wrapping_mul(K[i]) + .rotate_left(31); + } + } + let mut h = file_data.len() as u64 ^ K[0]; + for (i, b) in chunks.remainder().iter().enumerate() { + h = (h ^ (u64::from(*b) << ((i % 8) * 8))) + .wrapping_mul(K[1]) + .rotate_left(27); + } + for (i, l) in lane.iter().enumerate() { + h = (h ^ *l).wrapping_mul(K[i]).rotate_left(29); + } + h ^ (h >> 32) } impl SourceModelCache { @@ -114,6 +141,20 @@ mod tests { ); } + #[test] + fn the_fingerprint_notices_any_changed_byte() { + let data: Vec = (0..1000u32).map(|i| (i * 7 % 251) as u8).collect(); + let base = fingerprint(&data); + assert_eq!(base, fingerprint(&data.clone())); + for i in [0, 31, 32, 500, 991, 999] { + let mut d = data.clone(); + d[i] ^= 1; + assert_ne!(base, fingerprint(&d), "byte {i}"); + } + assert_ne!(fingerprint(&data[..999]), fingerprint(&data[..998])); + assert_ne!(fingerprint(&[0u8; 64]), fingerprint(&[0u8; 65])); + } + #[test] fn repeated_load_shares_meshes_until_the_file_changes_or_is_unloaded() { let mut models = ModelManager::new(); diff --git a/native/shared/src/renderer/mod.rs b/native/shared/src/renderer/mod.rs index a6f638a0..617f06ea 100644 --- a/native/shared/src/renderer/mod.rs +++ b/native/shared/src/renderer/mod.rs @@ -11453,9 +11453,14 @@ impl Renderer { /// that takes ~0.1 ms on desktop GPUs. pub fn set_sun_direction(&mut self, dx: f32, dy: f32, dz: f32, intensity: f32) { let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-6); - self.sun_direction = [dx / len, dy / len, dz / len]; - self.sun_intensity = intensity.max(0.0); - self.sky_view_dirty = true; + let dir = [dx / len, dy / len, dz / len]; + let intensity = intensity.max(0.0); + // Games set the sun every frame; only a real change rebakes the sky-view LUT. + if dir != self.sun_direction || intensity != self.sun_intensity { + self.sun_direction = dir; + self.sun_intensity = intensity; + self.sky_view_dirty = true; + } } /// Recompute the sky-view LUT if the sun has moved (or atmosphere From 3444530a84d10b94b9fb90e499111e58d93793b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Wed, 25 Nov 2026 07:35:48 +0100 Subject: [PATCH 2/5] glTF loads: one buffer-collection helper for the four load paths (moves the GLB chunk; keeps models_gltf.rs under the size limit) Co-Authored-By: Claude --- native/shared/src/models_gltf.rs | 126 +++++++++---------------------- 1 file changed, 34 insertions(+), 92 deletions(-) diff --git a/native/shared/src/models_gltf.rs b/native/shared/src/models_gltf.rs index 3aab4126..d371c4c6 100644 --- a/native/shared/src/models_gltf.rs +++ b/native/shared/src/models_gltf.rs @@ -141,32 +141,47 @@ fn read_accessor_f32( result } -pub fn load_gltf_animation(data: &[u8]) -> Option { - let mut gltf = parse::parse_gltf(data)?; - - // Get buffer data - let mut buffer_data: Vec> = Vec::new(); +/// The glTF's buffers, in order. The GLB binary chunk is moved out of the +/// parsed file, not cloned (a clone was a third copy of the file at the peak +/// of a load). Inline base64 buffers are decoded; an external `.bin` next to +/// the file is read from `base_dir` (with `strict`, a missing one fails the +/// load; otherwise it is an empty buffer). +fn take_buffers( + gltf: &mut gltf::Gltf, + base_dir: Option<&std::path::Path>, + strict: bool, +) -> Option>> { let mut bin = gltf.blob.take(); + let mut buffer_data: Vec> = Vec::new(); for buffer in gltf.buffers() { - match buffer.source() { - gltf::buffer::Source::Bin => { - // Moved, not cloned: a clone was a third copy of the file - // (after the read and the parser's) at the peak of the load. - if let Some(blob) = bin.take() { - buffer_data.push(blob); - } - } + let bytes = match buffer.source() { + gltf::buffer::Source::Bin => bin.take().unwrap_or_default(), gltf::buffer::Source::Uri(uri) => { if let Some(encoded) = uri.strip_prefix("data:application/octet-stream;base64,") { let mut decoded = Vec::new(); let _ = base64_decode(encoded, &mut decoded); - buffer_data.push(decoded); + decoded + } else if let Some(dir) = base_dir { + match std::fs::read(dir.join(uri)) { + Ok(bytes) => bytes, + Err(_) if strict => return None, + Err(_) => Vec::new(), + } } else { - buffer_data.push(Vec::new()); + Vec::new() } } - } + }; + buffer_data.push(bytes); } + Some(buffer_data) +} + +pub fn load_gltf_animation(data: &[u8]) -> Option { + let mut gltf = parse::parse_gltf(data)?; + + // Get buffer data + let buffer_data = take_buffers(&mut gltf, None, false)?; // Parse skeleton from the first skin let skeleton = if let Some(skin) = gltf.skins().next() { @@ -491,35 +506,7 @@ pub(super) fn load_gltf_with_textures( emit_unsupported_material_extension_diagnostics(&gltf, source_label.unwrap_or("")); // Get buffer data - let mut buffer_data: Vec> = Vec::new(); - let mut bin = gltf.blob.take(); - for buffer in gltf.buffers() { - match buffer.source() { - gltf::buffer::Source::Bin => { - // Moved, not cloned: a clone was a third copy of the file - // (after the read and the parser's) at the peak of the load. - if let Some(blob) = bin.take() { - buffer_data.push(blob); - } - } - gltf::buffer::Source::Uri(uri) => { - if let Some(encoded) = uri.strip_prefix("data:application/octet-stream;base64,") { - let mut decoded = Vec::new(); - let _ = base64_decode(encoded, &mut decoded); - buffer_data.push(decoded); - } else if let Some(dir) = base_dir { - // External .bin file alongside the .gltf. - let path = dir.join(uri); - match std::fs::read(&path) { - Ok(bytes) => buffer_data.push(bytes), - Err(_) => buffer_data.push(Vec::new()), - } - } else { - buffer_data.push(Vec::new()); - } - } - } - } + let buffer_data = take_buffers(&mut gltf, base_dir, false)?; let source_geometry_sha256 = complete_geometry_source_hash(data, &gltf, &buffer_data); // Pre-walk materials to identify which image indices are normal @@ -1075,30 +1062,7 @@ fn load_gltf_staged_impl( let mut gltf = parse::parse_gltf(data)?; emit_unsupported_material_extension_diagnostics(&gltf, source_label); - let mut buffer_data: Vec> = Vec::new(); - let mut bin = gltf.blob.take(); - for buffer in gltf.buffers() { - match buffer.source() { - gltf::buffer::Source::Bin => { - // Moved, not cloned: a clone was a third copy of the file - // (after the read and the parser's) at the peak of the load. - if let Some(blob) = bin.take() { - buffer_data.push(blob); - } - } - gltf::buffer::Source::Uri(uri) => { - if let Some(encoded) = uri.strip_prefix("data:application/octet-stream;base64,") { - let mut decoded = Vec::new(); - let _ = base64_decode(encoded, &mut decoded); - buffer_data.push(decoded); - } else if let Some(dir) = base_dir { - buffer_data.push(std::fs::read(dir.join(uri)).ok()?); - } else { - buffer_data.push(Vec::new()); - } - } - } - } + let buffer_data = take_buffers(&mut gltf, base_dir, true)?; let source_geometry_sha256 = complete_geometry_source_hash(data, &gltf, &buffer_data); // Pre-walk materials for the image indices used as normal maps — they @@ -1535,29 +1499,7 @@ pub(super) fn load_gltf(data: &[u8]) -> Option { emit_unsupported_material_extension_diagnostics(&gltf, ""); // Get buffer data (for .glb, embedded; for .gltf, inline base64) - let mut buffer_data: Vec> = Vec::new(); - let mut bin = gltf.blob.take(); - for buffer in gltf.buffers() { - match buffer.source() { - gltf::buffer::Source::Bin => { - // Moved, not cloned: a clone was a third copy of the file - // (after the read and the parser's) at the peak of the load. - if let Some(blob) = bin.take() { - buffer_data.push(blob); - } - } - gltf::buffer::Source::Uri(uri) => { - if let Some(encoded) = uri.strip_prefix("data:application/octet-stream;base64,") { - // Try to decode base64 inline data - let mut decoded = Vec::new(); - let _ = base64_decode(encoded, &mut decoded); - buffer_data.push(decoded); - } else { - buffer_data.push(Vec::new()); - } - } - } - } + let buffer_data = take_buffers(&mut gltf, None, false)?; let source_geometry_sha256 = complete_geometry_source_hash(data, &gltf, &buffer_data); let mut source_meshes: Vec> = From 9870b399e53917f6bd0bdab3d60f476c2619c1ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Wed, 25 Nov 2026 07:39:52 +0100 Subject: [PATCH 3/5] loadModelAnimation reads only the GLB's JSON and the clip and skin ranges, not the whole file A character's GLB is mostly textures (Jonah: 91 of 124 MB) and the game calls loadModelAnimation on the same file as loadModel, so every character was read and parsed twice. models_gltf_anim_file.rs reads the header, the JSON chunk and only the buffer views of the inverse bind matrices and the animation samplers into a zeroed buffer of the chunk's size (untouched pages cost nothing); glTF JSON, external or several buffers and sparse accessors fall back to the full read. Test: the ranged read equals the full read bit for bit (Fox.glb; BLOOM_ANIM_COMPARE for any files: seven of Jonah's characters checked, the face-rigged one included). Co-Authored-By: Claude --- native/shared/src/ffi_core/models.rs | 5 +- native/shared/src/models.rs | 12 +- native/shared/src/models_gltf.rs | 17 +- native/shared/src/models_gltf_anim_file.rs | 174 +++++++++++++++++++++ 4 files changed, 200 insertions(+), 8 deletions(-) create mode 100644 native/shared/src/models_gltf_anim_file.rs diff --git a/native/shared/src/ffi_core/models.rs b/native/shared/src/ffi_core/models.rs index a8da8957..e71cfff3 100644 --- a/native/shared/src/ffi_core/models.rs +++ b/native/shared/src/ffi_core/models.rs @@ -640,10 +640,7 @@ macro_rules! __bloom_ffi_models { $crate::ffi::guard("bloom_load_model_animation", move || { let path = $crate::string_header::str_from_header(path_ptr); let path: &str = &bloom_resolve_asset_path(path); - match std::fs::read(path) { - Ok(data) => engine().models.load_model_animation(&data), - Err(_) => 0.0, - } + engine().models.load_model_animation_file(std::path::Path::new(path)) }) } #[cfg(not(feature = "models3d"))] diff --git a/native/shared/src/models.rs b/native/shared/src/models.rs index d5afb17a..c298057a 100644 --- a/native/shared/src/models.rs +++ b/native/shared/src/models.rs @@ -552,8 +552,8 @@ pub use crate::anim_mixer::AnimMixer; mod gltf_load; #[cfg(feature = "models3d")] pub use gltf_load::{ - load_gltf_animation, load_gltf_staged, load_gltf_staged_from_source_path, - require_source_geometry_hash, + load_gltf_animation, load_gltf_animation_file, load_gltf_staged, + load_gltf_staged_from_source_path, require_source_geometry_hash, }; pub struct ModelAnimation { @@ -1210,6 +1210,14 @@ impl ModelManager { } } + /// As `load_model_animation`, reading only what the clips need from the file. + pub fn load_model_animation_file(&mut self, path: &std::path::Path) -> f64 { + match gltf_load::load_gltf_animation_file(path) { + Some(anim) => self.animations.alloc(anim), + None => 0.0, + } + } + /// EN-055 — a new animation INSTANCE over an already-loaded clip set. /// The parsed data (skeleton, keyframe tracks, rest rotations) is shared /// via `Arc`; the mixer, joint matrices and mask cache are fresh — so N diff --git a/native/shared/src/models_gltf.rs b/native/shared/src/models_gltf.rs index d371c4c6..09ff8b22 100644 --- a/native/shared/src/models_gltf.rs +++ b/native/shared/src/models_gltf.rs @@ -22,6 +22,8 @@ use material_import::{ apply_transmission_hack, emit_unsupported_material_extension_diagnostics, transmission_from_material, }; +#[path = "models_gltf_anim_file.rs"] +mod anim_file; #[path = "models_gltf_bake.rs"] mod bake; #[path = "models_gltf_morph.rs"] @@ -179,10 +181,21 @@ fn take_buffers( pub fn load_gltf_animation(data: &[u8]) -> Option { let mut gltf = parse::parse_gltf(data)?; - - // Get buffer data let buffer_data = take_buffers(&mut gltf, None, false)?; + animation_from(&gltf, &buffer_data) +} + +/// A GLB's skeleton and clips read from the file itself: the JSON and only the +/// byte ranges the skin and the animations use (models_gltf_anim_file.rs). +/// Anything that does not handle falls back to reading the whole file. +pub fn load_gltf_animation_file(path: &std::path::Path) -> Option { + if let Some(anim) = anim_file::load(path) { + return anim; + } + load_gltf_animation(&std::fs::read(path).ok()?) +} +fn animation_from(gltf: &gltf::Gltf, buffer_data: &[Vec]) -> Option { // Parse skeleton from the first skin let skeleton = if let Some(skin) = gltf.skins().next() { let joints_nodes: Vec<_> = skin.joints().collect(); diff --git a/native/shared/src/models_gltf_anim_file.rs b/native/shared/src/models_gltf_anim_file.rs new file mode 100644 index 00000000..3200f457 --- /dev/null +++ b/native/shared/src/models_gltf_anim_file.rs @@ -0,0 +1,174 @@ +//! Reading a GLB's skeleton and clips without reading its textures. +//! +//! `loadModelAnimation(path)` is called on the same file as `loadModel`, and +//! a character's GLB is mostly textures (Jonah's: 91 of 124 MB). This reads +//! the GLB header, the JSON chunk and only the buffer views that the skin's +//! inverse bind matrices and the animation samplers use, into an otherwise +//! untouched zeroed buffer of the binary chunk's size (fresh zero pages +//! cost no memory until written). + +use std::fs::File; +use std::io::{Read, Seek, SeekFrom}; +use std::path::Path; + +use super::ModelAnimation; + +/// `None`: not a case handled here (read the whole file instead). +/// `Some(result)`: the result of the load, read from the file's ranges. +pub(super) fn load(path: &Path) -> Option> { + let mut f = File::open(path).ok()?; + let mut hdr = [0u8; 20]; + f.read_exact(&mut hdr).ok()?; + if &hdr[0..4] != b"glTF" || &hdr[16..20] != b"JSON" { + return None; + } + let json_len = u32::from_le_bytes([hdr[12], hdr[13], hdr[14], hdr[15]]) as u64; + let mut json = vec![0u8; json_len as usize]; + f.read_exact(&mut json).ok()?; + let mut bin_hdr = [0u8; 8]; + let (bin_off, bin_len) = match f.read_exact(&mut bin_hdr) { + Ok(()) if &bin_hdr[4..8] == b"BIN\0" => ( + 20 + json_len + 8, + u32::from_le_bytes([bin_hdr[0], bin_hdr[1], bin_hdr[2], bin_hdr[3]]) as usize, + ), + Ok(()) => return None, + Err(_) => (0, 0), + }; + let gltf = super::parse::parse_gltf(&json)?; + // one buffer, the GLB's own binary chunk + let mut buffers = gltf.buffers(); + match (buffers.next(), buffers.next()) { + (Some(b), None) if matches!(b.source(), gltf::buffer::Source::Bin) => {} + (None, None) => {} + _ => return None, + } + let mut accessors: Vec = Vec::new(); + for skin in gltf.skins() { + accessors.extend(skin.inverse_bind_matrices()); + } + for anim in gltf.animations() { + for sampler in anim.samplers() { + accessors.push(sampler.input()); + accessors.push(sampler.output()); + } + } + let mut ranges: Vec<(usize, usize)> = Vec::new(); + for a in &accessors { + if a.sparse().is_some() { + return None; + } + if let Some(view) = a.view() { + let (o, l) = (view.offset(), view.length()); + if o + l > bin_len { + return None; + } + ranges.push((o, l)); + } + } + ranges.sort_unstable(); + ranges.dedup(); + let mut bin = vec![0u8; bin_len]; + for (o, l) in ranges { + f.seek(SeekFrom::Start(bin_off + o as u64)).ok()?; + f.read_exact(&mut bin[o..o + l]).ok()?; + } + let buffer_data = if bin_len > 0 { vec![bin] } else { Vec::new() }; + Some(super::animation_from(&gltf, &buffer_data)) +} + +#[cfg(test)] +mod tests { + use super::super::{animation_from, load_gltf_animation}; + use crate::models::ModelAnimation; + + /// Every number and name of a loaded clip set, bit for bit. + fn digest(a: &ModelAnimation) -> (Vec, Vec) { + let mut v: Vec = Vec::new(); + let mut names = Vec::new(); + if let Some(s) = &a.skeleton { + for j in &s.joints { + v.extend(j.inverse_bind.iter().flatten().map(|x| x.to_bits())); + v.extend( + j.rest_translation + .iter() + .chain(j.rest_rotation.iter()) + .chain(j.rest_scale.iter()) + .map(|x| x.to_bits()), + ); + v.extend(j.children.iter().map(|&c| c as u32)); + names.push(j.name.clone()); + } + v.extend(s.root_joints.iter().map(|&r| r as u32)); + } + for clip in a.animations.iter() { + names.push(clip.name.clone()); + v.push(clip.duration.to_bits()); + // (channels come out of a HashMap: their order is not fixed) + let mut chans: Vec<_> = clip.channels.iter().collect(); + chans.sort_by_key(|c| c.joint_index); + for c in chans { + v.push(c.joint_index as u32); + let f = c + .timestamps + .iter() + .chain(c.rotation_timestamps.iter()) + .chain(c.scale_timestamps.iter()); + v.extend(f.map(|x| x.to_bits())); + v.extend( + c.translations + .iter() + .flatten() + .chain(c.scales.iter().flatten()) + .map(|x| x.to_bits()), + ); + v.extend(c.rotations.iter().flatten().map(|x| x.to_bits())); + } + for m in &clip.morph_tracks { + v.extend(m.slots.iter().copied()); + v.extend(m.times.iter().chain(m.values.iter()).map(|x| x.to_bits())); + } + } + (v, names) + } + + fn same_as_full_read(path: &std::path::Path) { + let full = load_gltf_animation(&std::fs::read(path).unwrap()).expect("full read loads"); + let ranged = super::load(path) + .expect("a GLB is read by ranges") + .expect("ranged read loads"); + let (a, an) = digest(&full); + let (b, bn) = digest(&ranged); + assert!(!a.is_empty(), "{} has clip data", path.display()); + assert_eq!(an, bn); + assert!( + a == b, + "{}: ranged read differs from the full read", + path.display() + ); + let _ = animation_from; // (the shared body both paths use) + } + + #[test] + fn reading_only_the_clip_ranges_gives_the_full_reads_clips() { + let fox = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../examples/test-gltf-watch/assets/Fox.glb"); + same_as_full_read(&fox); + } + + /// BLOOM_ANIM_COMPARE=a.glb:b.glb cargo test -- --ignored anim_compare + #[test] + #[ignore] + fn anim_compare_files_from_env() { + let list = std::env::var("BLOOM_ANIM_COMPARE").unwrap_or_default(); + for p in list.split(':').filter(|p| !p.is_empty()) { + let p = std::path::Path::new(p); + same_as_full_read(p); + let t = std::time::Instant::now(); + let _ = load_gltf_animation(&std::fs::read(p).unwrap()); + let full = t.elapsed(); + let t = std::time::Instant::now(); + let _ = super::load(p); + eprintln!("{}: full {:?}, ranges {:?}", p.display(), full, t.elapsed()); + } + } +} From 64e1421d4711182f3c0ddff97a6012596ba60a32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Wed, 25 Nov 2026 08:25:14 +0100 Subject: [PATCH 4/5] Gate load_model_animation_file behind models3d (the web build has no glTF loader) Co-Authored-By: Claude --- native/shared/src/models.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/native/shared/src/models.rs b/native/shared/src/models.rs index c298057a..034ee4ae 100644 --- a/native/shared/src/models.rs +++ b/native/shared/src/models.rs @@ -1211,6 +1211,7 @@ impl ModelManager { } /// As `load_model_animation`, reading only what the clips need from the file. + #[cfg(feature = "models3d")] pub fn load_model_animation_file(&mut self, path: &std::path::Path) -> f64 { match gltf_load::load_gltf_animation_file(path) { Some(anim) => self.animations.alloc(anim), From 1f91ea72b7e2424240b68de88f6490d3d3217409 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Wed, 25 Nov 2026 08:46:16 +0100 Subject: [PATCH 5/5] Ranged animation read: fall back to the full read when an accessor runs past its buffer view Co-Authored-By: Claude --- native/shared/src/models_gltf_anim_file.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/native/shared/src/models_gltf_anim_file.rs b/native/shared/src/models_gltf_anim_file.rs index 3200f457..3bc9f2ff 100644 --- a/native/shared/src/models_gltf_anim_file.rs +++ b/native/shared/src/models_gltf_anim_file.rs @@ -59,7 +59,11 @@ pub(super) fn load(path: &Path) -> Option> { } if let Some(view) = a.view() { let (o, l) = (view.offset(), view.length()); - if o + l > bin_len { + // the accessor's last element must lie inside its view (else the + // full read would see bytes this one leaves at zero) + let stride = view.stride().unwrap_or(a.size()); + let span = a.offset() + a.count().saturating_sub(1) * stride + a.size(); + if o + l > bin_len || (a.count() > 0 && span > l) { return None; } ranges.push((o, l));