From 7f57da7c315fe6a58a584a0dfd3bd1057aec0a12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Wed, 25 Nov 2026 15:12:05 +0100 Subject: [PATCH 1/3] perf: keep models' CPU vertices compact, by field (lossless) A loaded model keeps its vertices on the CPU after upload (the software GI field gathers positions from them whenever the scene changes; a node made again after its mesh's last node went uploads them again; picking reads them). As Vec that is 96 bytes a vertex: 681 MB of a 2.4 GB city scene on an iPad. MeshData.vertices is now a VertexStore: positions as their own column, and every other field a column that holds one value when all vertices share its bits (colour, joints and weights on static meshes; often normal or tangent). to_vertices() gives back the exact Vec, bit for bit (tested), at the few places that upload or need whole vertices; counts, positions, the normal sum and single vertices have accessors that never rebuild. The GI gather takes positions. Texture streaming's uv-density cache is keyed by the node's geometry identity (the vertices' address is no longer stable). Measured in the game (Mac, max resident memory, same source, A/B/A): Nineveh 1770 -> 1264 MB, cold open 1593/1710 -> 1282, Joppa 1914/1921 -> 1826, deck 1293 -> 1188, village 1142/1162 -> 1050. Frames old vs new are within the old-vs-old noise in all five scenes; load times unchanged. Co-Authored-By: Claude --- native/shared/src/ffi_core/scene.rs | 4 +- native/shared/src/models.rs | 16 +- native/shared/src/models_cooked_scene.rs | 3 +- native/shared/src/models_gltf.rs | 6 +- native/shared/src/models_gltf_bake.rs | 19 +- native/shared/src/models_gltf_tests.rs | 9 +- native/shared/src/models_vertex_store.rs | 216 ++++++++++++++++++ native/shared/src/models_virtual_geometry.rs | 2 +- native/shared/src/picking.rs | 12 +- native/shared/src/renderer/mod.rs | 36 +-- .../shared/src/renderer/texture_streaming.rs | 4 +- .../shared/src/renderer/virtual_model_api.rs | 3 +- native/shared/src/scene.rs | 49 ++-- native/shared/src/scene/node_vertices.rs | 68 ++++++ native/shared/src/scene/shared_mesh.rs | 18 +- native/shared/src/scene_gi_soup.rs | 52 +++-- native/shared/tests/golden_render.rs | 13 +- .../tests/golden_render/fractional_dynamic.rs | 8 +- .../shared/tests/golden_render/joint_pages.rs | 3 +- .../tests/golden_render/morph_targets.rs | 2 +- .../golden_render/motion_producer_audit.rs | 2 +- .../tests/golden_render/quality_presets.rs | 2 +- .../golden_render/temporal_history_skinned.rs | 7 +- .../tests/golden_render/transparency.rs | 10 +- .../visibility_buffer_shading_runtime.rs | 6 +- native/web/src/lib.rs | 2 +- native/web/src/render_settings.rs | 20 +- 27 files changed, 458 insertions(+), 134 deletions(-) create mode 100644 native/shared/src/models_vertex_store.rs create mode 100644 native/shared/src/scene/node_vertices.rs diff --git a/native/shared/src/ffi_core/scene.rs b/native/shared/src/ffi_core/scene.rs index 6d973813..993a68ee 100644 --- a/native/shared/src/ffi_core/scene.rs +++ b/native/shared/src/ffi_core/scene.rs @@ -534,7 +534,7 @@ macro_rules! __bloom_ffi_scene { pub extern "C" fn bloom_scene_node_vertex_count(handle: f64) -> f64 { $crate::ffi::guard("bloom_scene_node_vertex_count", move || { match engine().scene.nodes.get(handle) { - Some(node) => node.vertices().len() as f64, + Some(node) => node.vertex_count() as f64, None => -1.0, } }) @@ -751,7 +751,7 @@ macro_rules! __bloom_ffi_scene { let eng = engine(); if let Some(node) = eng.scene.nodes.get(handle) { let current = $crate::geometry::GeometryData { - vertices: node.vertices().to_vec(), + vertices: node.vertices().into_owned(), indices: node.indices().to_vec(), }; let result = $crate::geometry::subtract_box( diff --git a/native/shared/src/models.rs b/native/shared/src/models.rs index 034ee4ae..2a3b9bcd 100644 --- a/native/shared/src/models.rs +++ b/native/shared/src/models.rs @@ -2,6 +2,10 @@ use crate::handles::HandleRegistry; use crate::renderer::Vertex3D; use std::sync::Arc; +#[path = "models_vertex_store.rs"] +mod vertex_store; +pub use vertex_store::VertexStore; + #[derive(Copy, Clone, Debug, Default, Eq, PartialEq)] pub enum MaterialAlphaMode { #[default] @@ -443,7 +447,9 @@ pub(crate) fn exclusive_texture_indices(meshes: &[Arc]) -> Vec { #[derive(Clone)] pub struct MeshData { - pub vertices: Vec, + /// The CPU vertices, by field and compact (models_vertex_store.rs): use + /// `positions()` where positions do, `to_vertices()` for whole ones. + pub vertices: VertexStore, /// Compact glTF TEXCOORD_1 sidecar retained only when an active physical /// transmission/thickness texture requests it. Keeping it out of /// `Vertex3D` preserves every ordinary vertex ABI and fetch footprint. @@ -840,7 +846,7 @@ impl ModelManager { let model = ModelData { meshes: vec![Arc::new(MeshData { - vertices, + vertices: vertices.into(), secondary_tex_coords: None, indices, texture_idx: None, @@ -964,7 +970,7 @@ impl ModelManager { let model = ModelData { meshes: vec![Arc::new(MeshData { - vertices, + vertices: vertices.into(), secondary_tex_coords: None, indices, texture_idx: None, @@ -1037,7 +1043,7 @@ impl ModelManager { let indices = index_data.to_vec(); let model = ModelData { meshes: vec![Arc::new(MeshData { - vertices, + vertices: vertices.into(), secondary_tex_coords: None, indices, texture_idx: None, @@ -1172,7 +1178,7 @@ impl ModelManager { let model = ModelData { meshes: vec![Arc::new(MeshData { - vertices, + vertices: vertices.into(), secondary_tex_coords: None, indices, texture_idx: None, diff --git a/native/shared/src/models_cooked_scene.rs b/native/shared/src/models_cooked_scene.rs index e9888e7f..43c3bf5a 100644 --- a/native/shared/src/models_cooked_scene.rs +++ b/native/shared/src/models_cooked_scene.rs @@ -119,7 +119,8 @@ fn convert_primitive( weights: vertex.weights, tangent: vertex.tangent, }) - .collect(), + .collect::>() + .into(), secondary_tex_coords: primitive.secondary_tex_coords, indices: primitive.indices, texture_idx: remap_texture(material.base_color_texture, texture_handles)?, diff --git a/native/shared/src/models_gltf.rs b/native/shared/src/models_gltf.rs index e77e6f70..d559da1e 100644 --- a/native/shared/src/models_gltf.rs +++ b/native/shared/src/models_gltf.rs @@ -1030,7 +1030,7 @@ fn import_gltf_with_textures( }; let morph = morph_slots.read(&reader, &vertices, skin_vertex_scale, mesh.index()); let source = Arc::new(MeshData { - vertices, + vertices: vertices.into(), secondary_tex_coords, indices, texture_idx: tex_idx, @@ -1450,7 +1450,7 @@ fn load_gltf_staged_impl( source_meshes[mesh.index()].push(( primitive.index() as u32, MeshData { - vertices, + vertices: vertices.into(), secondary_tex_coords, indices, texture_idx: tex_idx, @@ -1644,7 +1644,7 @@ pub(super) fn load_gltf(data: &[u8]) -> Option { source_meshes[mesh.index()].push(( primitive.index() as u32, MeshData { - vertices, + vertices: vertices.into(), secondary_tex_coords, indices, texture_idx: None, diff --git a/native/shared/src/models_gltf_bake.rs b/native/shared/src/models_gltf_bake.rs index 45915267..e76081fd 100644 --- a/native/shared/src/models_gltf_bake.rs +++ b/native/shared/src/models_gltf_bake.rs @@ -53,7 +53,7 @@ fn vertex_is_skinned(vertex: &Vertex3D) -> bool { } fn mesh_is_skinned(mesh: &MeshData) -> bool { - mesh.vertices.iter().any(vertex_is_skinned) + (0..mesh.vertices.len()).any(|i| mesh.vertices.weight(i).iter().sum::() > 0.01) } pub(super) fn shared_or_owned_instance( @@ -80,7 +80,8 @@ pub(super) fn shared_or_owned_instance( fn bake_owned_mesh_instance(mut instance: MeshData, world: &[[f32; 4]; 4]) -> MeshData { let normal_transform = mat4_inverse_transpose_3x3(world); let has_skinning = mesh_is_skinned(&instance); - for vertex in &mut instance.vertices { + let mut vertices = instance.vertices.to_vertices(); + for vertex in &mut vertices { if vertex_is_skinned(vertex) { continue; } @@ -101,11 +102,7 @@ fn bake_owned_mesh_instance(mut instance: MeshData, world: &[[f32; 4]; 4]) -> Me // the node's linear part (positions, tangents) and its inverse // transpose (normals). Skinned vertices' deltas stay in bind space. if let Some(morph) = instance.morph.as_ref() { - let rigid: Vec = instance - .vertices - .iter() - .map(|v| !vertex_is_skinned(v)) - .collect(); + let rigid: Vec = vertices.iter().map(|v| !vertex_is_skinned(v)).collect(); if rigid.iter().any(|r| *r) { instance.morph = morph .mapped(|v, d| { @@ -118,6 +115,7 @@ fn bake_owned_mesh_instance(mut instance: MeshData, world: &[[f32; 4]; 4]) -> Me .map(Arc::new); } } + instance.vertices = vertices.into(); instance } @@ -206,8 +204,8 @@ pub(super) fn model_bounds( .get(index) .copied() .unwrap_or(crate::renderer::IDENTITY_MAT4); - for vertex in &mesh.vertices { - let position = mat4_transform_point(&transform, &vertex.position); + for vertex in mesh.vertices.positions() { + let position = mat4_transform_point(&transform, vertex); for axis in 0..3 { minimum[axis] = minimum[axis].min(position[axis]); maximum[axis] = maximum[axis].max(position[axis]); @@ -235,7 +233,8 @@ mod tests { joints: [0.0; 4], weights: [0.0; 4], tangent: [0.0; 4], - }], + }] + .into(), secondary_tex_coords: None, indices: vec![0], texture_idx: None, diff --git a/native/shared/src/models_gltf_tests.rs b/native/shared/src/models_gltf_tests.rs index 4c2d50b0..10dcbcc9 100644 --- a/native/shared/src/models_gltf_tests.rs +++ b/native/shared/src/models_gltf_tests.rs @@ -508,7 +508,7 @@ fn staged_mask_loader_routes_coverage_variant_and_keeps_plain_loader_image_neutr assert_eq!(staged.textures[0].alpha_coverage_reference, Some(0.625)); assert_eq!(staged.model.meshes[0].texture_idx, Some(1)); assert!(staged.model.meshes[0].alpha_coverage_mips); - let color = staged.model.meshes[0].vertices[0].color; + let color = staged.model.meshes[0].vertices.get(0).color; for (actual, expected) in color.into_iter().zip([0.1, 0.1, 0.45, 0.4]) { assert!( (actual - expected).abs() < 1e-6, @@ -1071,6 +1071,7 @@ fn physical_metadata_round_trips_through_plain_and_staged_glb_loaders() { assert_eq!(mesh.layered_pbr.anisotropy_rotation, 0.75, "{label}"); assert!( mesh.vertices + .to_vertices() .iter() .all(|vertex| vertex.tangent == [1.0, 0.0, 0.0, -1.0]), "{label}: authored mirrored tangents were not preserved" @@ -1117,8 +1118,8 @@ fn shared_static_node_scale_preserves_world_bounds_and_volume_contract() { ] { assert_eq!(model.meshes.len(), 1, "{label}"); let mesh = &model.meshes[0]; - assert_eq!(mesh.vertices[1].position, [1.0, 0.0, 0.0], "{label}"); - assert_eq!(mesh.vertices[2].position, [0.0, 1.0, 0.0], "{label}"); + assert_eq!(mesh.vertices.get(1).position, [1.0, 0.0, 0.0], "{label}"); + assert_eq!(mesh.vertices.get(2).position, [0.0, 1.0, 0.0], "{label}"); assert_eq!(model.mesh_transform(0)[0][0], 2.0, "{label}"); assert_eq!(model.mesh_transform(0)[1][1], 2.0, "{label}"); assert_eq!(model.mesh_transform(0)[2][2], 2.0, "{label}"); @@ -1207,7 +1208,7 @@ fn physical_texcoord_1_is_retained_lazily_and_exactly() { "{label} loader must preserve authored TEXCOORD_1 exactly" ); assert_eq!( - model.meshes[0].vertices[1].uv, + model.meshes[0].vertices.get(1).uv, [1.0, 0.0], "{label} loader must leave the established UV0 vertex ABI intact" ); diff --git a/native/shared/src/models_vertex_store.rs b/native/shared/src/models_vertex_store.rs new file mode 100644 index 00000000..9fd6df54 --- /dev/null +++ b/native/shared/src/models_vertex_store.rs @@ -0,0 +1,216 @@ +//! A mesh's CPU vertices, stored by field and losslessly compact. +//! +//! A loaded model keeps its vertices on the CPU after they are uploaded: the +//! software GI field gathers positions from them whenever the scene changes, +//! a scene node made again after its mesh's last node went uploads them +//! again, and picking reads them. As `Vec` that is 96 bytes a +//! vertex; a city scene on an iPad held 681 MB of them (2026-11-25). Most of +//! a static mesh's fields are the same for every vertex (colour, joints, +//! weights, often the tangent), so each field is its own column, and a column +//! whose every value is the same holds that value once. A static mesh keeps +//! 32 to 48 bytes a vertex. `to_vertices()` gives back the exact +//! `Vec` (bit for bit), for an upload or anything else that needs +//! whole vertices; positions are a slice, with no copy. + +use crate::renderer::Vertex3D; + +#[derive(Clone, Debug)] +enum Column { + Same(T), + Each(Vec), +} + +impl Column { + fn get(&self, i: usize) -> T { + match self { + Column::Same(v) => *v, + Column::Each(v) => v[i], + } + } + fn bytes(&self) -> usize { + match self { + Column::Same(_) => std::mem::size_of::(), + Column::Each(v) => v.len() * std::mem::size_of::(), + } + } +} + +/// One column from `field` of each vertex: a single value when every vertex +/// has the same bits, else every value. +fn column( + vertices: &[Vertex3D], + field: impl Fn(&Vertex3D) -> [f32; N], +) -> Column<[f32; N]> { + let Some(first) = vertices.first().map(&field) else { + return Column::Same([0.0; N]); + }; + let same = + |a: &[f32; N], b: &[f32; N]| a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits()); + if vertices.iter().all(|v| same(&field(v), &first)) { + Column::Same(first) + } else { + Column::Each(vertices.iter().map(field).collect()) + } +} + +#[derive(Clone, Debug)] +pub struct VertexStore { + positions: Vec<[f32; 3]>, + normals: Column<[f32; 3]>, + colors: Column<[f32; 4]>, + uvs: Column<[f32; 2]>, + joints: Column<[f32; 4]>, + weights: Column<[f32; 4]>, + tangents: Column<[f32; 4]>, +} + +impl Default for VertexStore { + fn default() -> Self { + Self::from_vertices(&[]) + } +} + +impl VertexStore { + pub fn from_vertices(vertices: &[Vertex3D]) -> Self { + Self { + positions: vertices.iter().map(|v| v.position).collect(), + normals: column(vertices, |v| v.normal), + colors: column(vertices, |v| v.color), + uvs: column(vertices, |v| v.uv), + joints: column(vertices, |v| v.joints), + weights: column(vertices, |v| v.weights), + tangents: column(vertices, |v| v.tangent), + } + } + + pub fn len(&self) -> usize { + self.positions.len() + } + + pub fn is_empty(&self) -> bool { + self.positions.is_empty() + } + + /// Every vertex's position (a slice of the store: no copy). + pub fn positions(&self) -> &[[f32; 3]] { + &self.positions + } + + /// Vertex `i` whole. + pub fn get(&self, i: usize) -> Vertex3D { + Vertex3D { + position: self.positions[i], + normal: self.normals.get(i), + color: self.colors.get(i), + uv: self.uvs.get(i), + joints: self.joints.get(i), + weights: self.weights.get(i), + tangent: self.tangents.get(i), + } + } + + pub fn uv(&self, i: usize) -> [f32; 2] { + self.uvs.get(i) + } + + pub fn normal(&self, i: usize) -> [f32; 3] { + self.normals.get(i) + } + + pub fn weight(&self, i: usize) -> [f32; 4] { + self.weights.get(i) + } + + /// The sum of every normal, added in vertex order (as a loop over the + /// whole vertices would, so the result has the same bits). + pub fn normal_sum(&self) -> [f32; 3] { + let mut sum = [0.0f32; 3]; + for i in 0..self.len() { + let n = self.normals.get(i); + sum[0] += n[0]; + sum[1] += n[1]; + sum[2] += n[2]; + } + sum + } + + /// The vertices whole, exactly as they were stored. + pub fn to_vertices(&self) -> Vec { + (0..self.len()).map(|i| self.get(i)).collect() + } + + /// Bytes this store holds (for reports). + pub fn bytes(&self) -> usize { + self.positions.len() * 12 + + self.normals.bytes() + + self.colors.bytes() + + self.uvs.bytes() + + self.joints.bytes() + + self.weights.bytes() + + self.tangents.bytes() + } +} + +impl From> for VertexStore { + fn from(vertices: Vec) -> Self { + Self::from_vertices(&vertices) + } +} + +impl From<&[Vertex3D]> for VertexStore { + fn from(vertices: &[Vertex3D]) -> Self { + Self::from_vertices(vertices) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn v(i: usize, skinned: bool) -> Vertex3D { + let f = i as f32; + Vertex3D { + position: [f, f * 2.0, -f], + normal: [0.0, 1.0, 0.0], + color: [1.0, 1.0, 1.0, 1.0], + uv: [f * 0.1, 0.5], + joints: if skinned { + [f, 1.0, 0.0, 0.0] + } else { + [0.0; 4] + }, + weights: if skinned { + [0.75, 0.25, 0.0, 0.0] + } else { + [0.0; 4] + }, + tangent: [1.0, 0.0, 0.0, if i % 2 == 0 { 1.0 } else { -1.0 }], + } + } + + fn bits(vs: &[Vertex3D]) -> Vec { + bytemuck::cast_slice::(vs).to_vec() + } + + #[test] + fn vertices_come_back_bit_for_bit() { + for skinned in [false, true] { + let mut vs: Vec = (0..1000).map(|i| v(i, skinned)).collect(); + vs[7].normal = [-0.0, 1.0, f32::NAN]; // signed zero and NaN keep their bits + let store = VertexStore::from_vertices(&vs); + assert_eq!(store.len(), vs.len()); + assert_eq!(bits(&store.to_vertices()), bits(&vs)); + assert_eq!(store.positions()[5], vs[5].position); + assert_eq!(bits(&[store.get(7)]), bits(&[vs[7]])); + } + assert!(VertexStore::from_vertices(&[]).to_vertices().is_empty()); + } + + #[test] + fn a_static_mesh_takes_well_under_half() { + let vs: Vec = (0..1000).map(|i| v(i, false)).collect(); + let store = VertexStore::from_vertices(&vs); + // positions, uvs and tangents vary; normal, colour, joints and weights are one value each + assert!(store.bytes() < vs.len() * 40, "{} bytes", store.bytes()); + } +} diff --git a/native/shared/src/models_virtual_geometry.rs b/native/shared/src/models_virtual_geometry.rs index 60f69c01..c750aea8 100644 --- a/native/shared/src/models_virtual_geometry.rs +++ b/native/shared/src/models_virtual_geometry.rs @@ -328,7 +328,7 @@ mod tests { fn mesh() -> Arc { Arc::new(MeshData { - vertices: vec![Vertex3D::default(); 3], + vertices: vec![Vertex3D::default(); 3].into(), secondary_tex_coords: None, indices: vec![0, 1, 2], texture_idx: None, diff --git a/native/shared/src/picking.rs b/native/shared/src/picking.rs index 058945d0..db21f79e 100644 --- a/native/shared/src/picking.rs +++ b/native/shared/src/picking.rs @@ -99,9 +99,9 @@ pub fn raycast_scene(scene: &SceneGraph, origin: &[f32; 3], direction: &[f32; 3] if tri.len() < 3 { continue; } - let v0 = &node.vertices()[tri[0] as usize]; - let v1 = &node.vertices()[tri[1] as usize]; - let v2 = &node.vertices()[tri[2] as usize]; + let v0 = &node.vertex(tri[0] as usize); + let v1 = &node.vertex(tri[1] as usize); + let v2 = &node.vertex(tri[2] as usize); if let Some((t, u, v)) = ray_triangle_intersection( &local_origin, @@ -179,9 +179,9 @@ pub fn raycast_scene_all( if tri.len() < 3 { continue; } - let v0 = &node.vertices()[tri[0] as usize]; - let v1 = &node.vertices()[tri[1] as usize]; - let v2 = &node.vertices()[tri[2] as usize]; + let v0 = &node.vertex(tri[0] as usize); + let v1 = &node.vertex(tri[1] as usize); + let v2 = &node.vertex(tri[2] as usize); if let Some((t, u, v)) = ray_triangle_intersection( &local_origin, diff --git a/native/shared/src/renderer/mod.rs b/native/shared/src/renderer/mod.rs index 53a35d3a..3c23821c 100644 --- a/native/shared/src/renderer/mod.rs +++ b/native/shared/src/renderer/mod.rs @@ -10144,13 +10144,10 @@ impl Renderer { shared_identity.and_then(|identity| shared_pt_geometry.get(&identity).copied()) { window - } else if build_static_pt_geometry - && !n.vertices().is_empty() - && !n.indices().is_empty() - { + } else if build_static_pt_geometry && n.vertex_count() != 0 && !n.indices().is_empty() { let vb = (geo_vertices.len() / 24) as u32; let ib = geo_indices.len() as u32; - geo_vertices.extend_from_slice(bytemuck::cast_slice(n.vertices())); + geo_vertices.extend_from_slice(bytemuck::cast_slice(&n.vertices())); geo_indices.extend_from_slice(n.indices()); let window = (vb, ib, n.indices().len() as u32); if let Some(identity) = shared_identity { @@ -10200,7 +10197,7 @@ impl Renderer { &mut geo_secondary_uvs, vertex_base as usize, if index_count != 0 { - n.vertices().len() + n.vertex_count() } else { 0 }, @@ -14175,9 +14172,10 @@ impl Renderer { // Check if any vertex is skinned — cached alongside the meshes so // per-frame draws don't rescan every vertex. let is_skinned = meshes.iter().any(|m| { - m.vertices - .iter() - .any(|v| v.weights[0] + v.weights[1] + v.weights[2] + v.weights[3] > 0.01) + (0..m.vertices.len()).any(|i| { + let w = m.vertices.weight(i); + w[0] + w[1] + w[2] + w[3] > 0.01 + }) }); if is_skinned { self.model_skinned.insert(handle_bits); @@ -14220,16 +14218,18 @@ impl Renderer { // (min > max) when the mesh has no vertices. let mut local_min = [f32::MAX; 3]; let mut local_max = [f32::MIN; 3]; - for v in mesh.vertices.iter() { + for p in mesh.vertices.positions() { for a in 0..3 { - if v.position[a] < local_min[a] { - local_min[a] = v.position[a]; + if p[a] < local_min[a] { + local_min[a] = p[a]; } - if v.position[a] > local_max[a] { - local_max[a] = v.position[a]; + if p[a] > local_max[a] { + local_max[a] = p[a]; } } } + // whole vertices for the upload (the mesh keeps them compact) + let whole = mesh.vertices.to_vertices(); if mesh.vertices.is_empty() { local_min = [1.0; 3]; local_max = [-1.0; 3]; @@ -14244,7 +14244,7 @@ impl Renderer { .device .create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("cached_skinned_model_vb"), - contents: bytemuck::cast_slice(&mesh.vertices), + contents: bytemuck::cast_slice(&whole), usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::STORAGE, }), index: self @@ -14263,7 +14263,7 @@ impl Renderer { let geometry = self.gpu_driven.upload_static_or_dedicated( &self.device, &self.queue, - &mesh.vertices, + &whole, &mesh.indices, ); if let gpu_driven::MeshGeometry::Shared(slice) = &geometry { @@ -14500,7 +14500,7 @@ impl Renderer { layered_uses_uv1, material_bg, material_textures: [base_color_idx, normal_idx, mr_idx, em_idx, occ_idx], - uv_density: texture_streaming::uv_density(&mesh.vertices, &mesh.indices), + uv_density: texture_streaming::uv_density(&whole, &mesh.indices), _material_uniform: material_uniform, shadow_cutout_bg, _shadow_cutoff_buf: shadow_cutoff_buf, @@ -14508,7 +14508,7 @@ impl Renderer { // TLAS path (skinned only; a handful of enemy models, // a few thousand verts each). cpu_vertices: if is_skinned { - Some(mesh.vertices.clone()) + Some(whole.clone()) } else { None }, diff --git a/native/shared/src/renderer/texture_streaming.rs b/native/shared/src/renderer/texture_streaming.rs index 2a820fc5..b2f302a6 100644 --- a/native/shared/src/renderer/texture_streaming.rs +++ b/native/shared/src/renderer/texture_streaming.rs @@ -803,12 +803,12 @@ impl Renderer { { continue; } - let key = node.vertices().as_ptr() as usize; + let key = node.geometry_identity(); let local = *self .texture_streaming .uv_density .entry(key) - .or_insert_with(|| uv_density(node.vertices(), node.indices())); + .or_insert_with(|| uv_density(&node.vertices(), node.indices())); let world = node.world_transform(); let scale = (0..3) .map(|c| (world[c][0].powi(2) + world[c][1].powi(2) + world[c][2].powi(2)).sqrt()) diff --git a/native/shared/src/renderer/virtual_model_api.rs b/native/shared/src/renderer/virtual_model_api.rs index 506fa64c..9f1a31b7 100644 --- a/native/shared/src/renderer/virtual_model_api.rs +++ b/native/shared/src/renderer/virtual_model_api.rs @@ -491,7 +491,8 @@ fn build_roles( weights: [0.0; 4], tangent: vertex.tangent, }) - .collect(); + .collect::>() + .into(); mesh.indices = primitive.indices.clone(); mesh.secondary_tex_coords = None; let proxy = Arc::new(mesh); diff --git a/native/shared/src/scene.rs b/native/shared/src/scene.rs index 675bf82b..611277cd 100644 --- a/native/shared/src/scene.rs +++ b/native/shared/src/scene.rs @@ -451,14 +451,6 @@ impl SceneNode { } } - /// Read the node's effective local vertex payload. Imported geometry may - /// be backed by an immutable shared model primitive. - pub fn vertices(&self) -> &[Vertex3D] { - self.shared_model_mesh - .as_ref() - .map_or(self.vertices.as_slice(), |mesh| mesh.vertices.as_slice()) - } - /// Read the node's effective local index payload. Imported geometry may /// be backed by an immutable shared model primitive. pub fn indices(&self) -> &[u32] { @@ -993,7 +985,7 @@ impl SceneGraph { } next_node += 1; if !node.visible - || node.vertices().is_empty() + || node.vertex_count() == 0 || node.indices().is_empty() || (exclude_physical_transmission && node.material.has_gi_transmission()) { @@ -1001,7 +993,7 @@ impl SceneGraph { } let before = vbuf.len(); tri_count += crate::scene_gi_soup::append_node_triangles_in( - node.vertices(), + &node.positions(), node.indices(), &node.world_transform(), min_feature, @@ -1204,10 +1196,10 @@ impl SceneGraph { }; let mut bmin = [f32::MAX; 3]; let mut bmax = [f32::MIN; 3]; - for vertex in &mesh.vertices { + for position in mesh.vertices.positions() { for axis in 0..3 { - bmin[axis] = bmin[axis].min(vertex.position[axis]); - bmax[axis] = bmax[axis].max(vertex.position[axis]); + bmin[axis] = bmin[axis].min(position[axis]); + bmax[axis] = bmax[axis].max(position[axis]); } } if mesh.vertices.is_empty() { @@ -1867,8 +1859,12 @@ impl SceneGraph { && lod.gpu_geometry.is_none() && !lod.gpu_geometry_refused { - let (vertices, indices) = match lod.shared.as_ref() { - Some(mesh) => (&mesh.vertices[..], &mesh.indices[..]), + let shared_whole; + let (vertices, indices): (&[Vertex3D], &[u32]) = match lod.shared.as_ref() { + Some(mesh) => { + shared_whole = mesh.vertices.to_vertices(); + (&shared_whole[..], &mesh.indices[..]) + } None => (&lod.vertices[..], &lod.indices[..]), }; if !vertices.is_empty() && !indices.is_empty() { @@ -1905,7 +1901,7 @@ impl SceneGraph { let geometry_changed = node.geo_dirty; if geometry_changed || node.gpu_vb.is_none() { - let resource_key = (!node.vertices().is_empty() && !node.indices().is_empty()) + let resource_key = (node.vertex_count() != 0 && !node.indices().is_empty()) .then(|| node_geometry_key(node, shared_mesh_cache)); if node.gpu_resource_key != resource_key { if let Some(old_key) = node.gpu_resource_key.take() { @@ -1971,7 +1967,7 @@ impl SceneGraph { node.gpu_vb = Some(device.create_buffer_init( &wgpu::util::BufferInitDescriptor { label: Some("scene_shared_vb"), - contents: bytemuck::cast_slice(node.vertices()), + contents: bytemuck::cast_slice(&node.vertices()), usage: vb_usage, }, )); @@ -1984,7 +1980,7 @@ impl SceneGraph { )); } node.gpu_index_count = node.indices().len() as u32; - node.gpu_vertex_count = node.vertices().len() as u32; + node.gpu_vertex_count = node.vertex_count() as u32; node.geo_dirty = false; // Ticket 014 V4 — flat normal/albedo + card-slot @@ -1996,12 +1992,7 @@ impl SceneGraph { // remain hw-rt-gated because only the HW trace reads // those (and the per-mesh SDFs are currently dormant). if !node.indices().is_empty() { - let mut n_sum = [0.0_f32; 3]; - for v in node.vertices() { - n_sum[0] += v.normal[0]; - n_sum[1] += v.normal[1]; - n_sum[2] += v.normal[2]; - } + let n_sum = node.normal_sum(); let world_transform = node.world_transform(); let t = &world_transform; let nx = t[0][0] * n_sum[0] + t[1][0] * n_sum[1] + t[2][0] * n_sum[2]; @@ -2082,8 +2073,7 @@ impl SceneGraph { // pull the position prefix out as a // [[f32; 3]] slice so the hash only sees // geometry-relevant bytes. - let positions: Vec<[f32; 3]> = - node.vertices().iter().map(|v| v.position).collect(); + let positions: Vec<[f32; 3]> = node.positions().into_owned(); let hash = crate::sdf_cache::compute_mesh_hash(&positions, node.indices()); node.mesh_hash = Some(hash); @@ -2176,7 +2166,7 @@ impl SceneGraph { // Main/depth GPU submission uses one deduplicated arena slice. // The legacy buffers above deliberately stay alive for secondary // passes, which makes this an additive and reversible fast path. - if geometry_changed && (node.vertices().is_empty() || node.indices().is_empty()) { + if geometry_changed && (node.vertex_count() == 0 || node.indices().is_empty()) { if let Some(old_key) = node.gpu_geometry_key.take() { release_scene_geometry(shared_gpu_geometry, retired_gpu_geometry, old_key); } @@ -2188,7 +2178,7 @@ impl SceneGraph { if gpu_driven.enabled() && gpu_driven_scene_active && (geometry_changed || (node.gpu_geometry.is_none() && !node.gpu_geometry_refused)) - && !node.vertices().is_empty() + && node.vertex_count() != 0 && !node.indices().is_empty() { let key = node_geometry_key(node, shared_mesh_cache); @@ -2204,7 +2194,7 @@ impl SceneGraph { let slice = gpu_driven.upload_static( device, queue, - node.vertices(), + &node.vertices(), node.indices(), ); if let Some(slice) = slice { @@ -2764,6 +2754,7 @@ impl SceneGraph { mod draw_lists; mod helpers; +mod node_vertices; mod shared_mesh; use helpers::*; pub(crate) use helpers::{aabb_outside_frustum, extract_frustum_planes}; diff --git a/native/shared/src/scene/node_vertices.rs b/native/shared/src/scene/node_vertices.rs new file mode 100644 index 00000000..1360acf1 --- /dev/null +++ b/native/shared/src/scene/node_vertices.rs @@ -0,0 +1,68 @@ +//! A scene node's vertices, read without copying the shared primitive's +//! compact store (models_vertex_store.rs) where a count, a position or a sum +//! is enough. + +use super::SceneNode; +use crate::renderer::Vertex3D; + +impl SceneNode { + /// Read the node's effective local vertex payload. Imported geometry may + /// be backed by an immutable shared model primitive. + /// + /// Whole vertices: borrowed for geometry the node owns, rebuilt from the + /// compact store for a shared model primitive. Counts, positions and + /// normals have their own accessors that never rebuild. + pub fn vertices(&self) -> std::borrow::Cow<'_, [Vertex3D]> { + match self.shared_model_mesh.as_ref() { + Some(mesh) => std::borrow::Cow::Owned(mesh.vertices.to_vertices()), + None => std::borrow::Cow::Borrowed(self.vertices.as_slice()), + } + } + + /// An address that stays the same while the node shows the same + /// geometry: the shared primitive's, or the node's own vertices'. + pub(crate) fn geometry_identity(&self) -> usize { + match self.shared_model_mesh.as_ref() { + Some(mesh) => std::sync::Arc::as_ptr(mesh) as usize, + None => self.vertices.as_ptr() as usize, + } + } + + pub fn vertex_count(&self) -> usize { + self.shared_model_mesh + .as_ref() + .map_or(self.vertices.len(), |mesh| mesh.vertices.len()) + } + + /// Vertex `i` whole. + pub fn vertex(&self, i: usize) -> Vertex3D { + match self.shared_model_mesh.as_ref() { + Some(mesh) => mesh.vertices.get(i), + None => self.vertices[i], + } + } + + /// Every vertex's position (a slice of the shared primitive's store). + pub fn positions(&self) -> std::borrow::Cow<'_, [[f32; 3]]> { + match self.shared_model_mesh.as_ref() { + Some(mesh) => std::borrow::Cow::Borrowed(mesh.vertices.positions()), + None => std::borrow::Cow::Owned(self.vertices.iter().map(|v| v.position).collect()), + } + } + + /// The sum of every vertex normal, in vertex order. + pub fn normal_sum(&self) -> [f32; 3] { + match self.shared_model_mesh.as_ref() { + Some(mesh) => mesh.vertices.normal_sum(), + None => { + let mut sum = [0.0f32; 3]; + for v in &self.vertices { + sum[0] += v.normal[0]; + sum[1] += v.normal[1]; + sum[2] += v.normal[2]; + } + sum + } + } + } +} diff --git a/native/shared/src/scene/shared_mesh.rs b/native/shared/src/scene/shared_mesh.rs index 2ef94ca4..07743890 100644 --- a/native/shared/src/scene/shared_mesh.rs +++ b/native/shared/src/scene/shared_mesh.rs @@ -58,7 +58,7 @@ impl SharedMeshCache { let entry = self.entry(mesh); *entry .key - .get_or_insert_with(|| scene_geometry_key(&mesh.vertices, &mesh.indices)) + .get_or_insert_with(|| scene_geometry_key(&mesh.vertices.to_vertices(), &mesh.indices)) } /// Vertex and index buffers of a shared mesh used as a reduced-detail @@ -75,7 +75,7 @@ impl SharedMeshCache { ( device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("scene_shared_lod_vb"), - contents: bytemuck::cast_slice(&mesh.vertices), + contents: bytemuck::cast_slice(&mesh.vertices.to_vertices()), usage: wgpu::BufferUsages::VERTEX, }), device.create_buffer_init(&wgpu::util::BufferInitDescriptor { @@ -94,7 +94,7 @@ impl SharedMeshCache { pub(super) fn node_geometry_key(node: &SceneNode, cache: &mut SharedMeshCache) -> SceneGeometryKey { match node.shared_model_mesh.as_ref() { Some(mesh) => cache.key(mesh), - None => scene_geometry_key(node.vertices(), node.indices()), + None => scene_geometry_key(&node.vertices(), node.indices()), } } @@ -106,7 +106,7 @@ mod tests { let mut vertex = Vertex3D::default(); vertex.position = [x, 0.0, 0.0]; Arc::new(MeshData { - vertices: vec![vertex; 3], + vertices: vec![vertex; 3].into(), secondary_tex_coords: None, indices: vec![0, 1, 2], texture_idx: None, @@ -133,7 +133,10 @@ mod tests { let mut cache = SharedMeshCache::default(); let a = mesh(1.0); let key = cache.key(&a); - assert_eq!(key, scene_geometry_key(&a.vertices, &a.indices)); + assert_eq!( + key, + scene_geometry_key(&a.vertices.to_vertices(), &a.indices) + ); assert_eq!(cache.key(&a), key); assert_eq!(cache.entries.len(), 1); assert_ne!(cache.key(&mesh(2.0)), key); @@ -153,6 +156,9 @@ mod tests { cache.entries.insert(Arc::as_ptr(&b) as usize, stale); let key_b = cache.key(&b); assert_ne!(key_b, key_a); - assert_eq!(key_b, scene_geometry_key(&b.vertices, &b.indices)); + assert_eq!( + key_b, + scene_geometry_key(&b.vertices.to_vertices(), &b.indices) + ); } } diff --git a/native/shared/src/scene_gi_soup.rs b/native/shared/src/scene_gi_soup.rs index a93b5b21..33ef8597 100644 --- a/native/shared/src/scene_gi_soup.rs +++ b/native/shared/src/scene_gi_soup.rs @@ -9,8 +9,6 @@ //! `min_feature` apart and the distance to it moves by at most that. Larger //! triangles are untouched. -use crate::renderer::Vertex3D; - /// Floats per soup vertex: the world position and nothing else. The bake /// shader wants the `Vertex3D` stride, and gets it when the triangles a bake /// uses are packed for upload (`sdf_clipmap_prep::pack_binned_triangles`); a @@ -66,7 +64,7 @@ fn bounds_inside(bmin: [f32; 3], bmax: [f32; 3], lo: [f32; 3], hi: [f32; 3]) -> /// only the triangles that reach into the region: a 500 m ground tile under a /// 120 m region would otherwise put all of itself into every soup. pub(crate) fn append_node_triangles_in( - vertices: &[Vertex3D], + vertices: &[[f32; 3]], indices: &[u32], world_transform: &[[f32; 4]; 4], min_feature: f32, @@ -94,7 +92,7 @@ pub(crate) fn append_node_triangles_in( /// Append one mesh in world space; returns the triangles appended. #[cfg(test)] pub(crate) fn append_node_triangles( - vertices: &[Vertex3D], + vertices: &[[f32; 3]], indices: &[u32], world_transform: &[[f32; 4]; 4], min_feature: f32, @@ -113,7 +111,7 @@ pub(crate) fn append_node_triangles( } fn append_triangles( - vertices: &[Vertex3D], + vertices: &[[f32; 3]], indices: &[u32], world_transform: &[[f32; 4]; 4], min_feature: f32, @@ -131,14 +129,14 @@ fn append_triangles( // Only the surviving triangles' corners are emitted. vbuf.reserve(kept.len() * STRIDE); for (slot, &index) in kept.iter().enumerate() { - push_position(vbuf, world_transform, vertices[index as usize].position); + push_position(vbuf, world_transform, vertices[index as usize]); ibuf.push(base + slot as u32); } return (kept.len() / 3) as u32; } vbuf.reserve(vertices.len() * STRIDE); for vertex in vertices { - push_position(vbuf, world_transform, vertex.position); + push_position(vbuf, world_transform, *vertex); } ibuf.extend(indices.iter().map(|&index| base + index)); (indices.len() / 3) as u32 @@ -148,7 +146,7 @@ fn append_triangles( /// thinning, or `None` when nothing was dropped and the mesh should be /// emitted as it is. fn select_triangles( - vertices: &[Vertex3D], + vertices: &[[f32; 3]], indices: &[u32], world_transform: &[[f32; 4]; 4], min_feature: f32, @@ -180,7 +178,7 @@ fn select_triangles( let mut kept: Vec = Vec::new(); let mut dropped_any = false; for (triangle, corners) in indices.chunks_exact(3).enumerate() { - let position = |corner: u32| vertices.get(corner as usize).map(|v| v.position); + let position = |corner: u32| vertices.get(corner as usize).copied(); let (Some(a), Some(b), Some(c)) = ( position(corners[0]), position(corners[1]), @@ -234,6 +232,11 @@ fn select_triangles( #[cfg(test)] mod tests { use super::*; + use crate::renderer::Vertex3D; + + fn pos(v: &[Vertex3D]) -> Vec<[f32; 3]> { + v.iter().map(|v| v.position).collect() + } const IDENTITY: [[f32; 4]; 4] = [ [1.0, 0.0, 0.0, 0.0], @@ -310,8 +313,14 @@ mod tests { fn large_triangles_are_emitted_unchanged() { let (vertices, indices) = grid(4, 4.0); // 0.5 m² triangles let (mut vbuf, mut ibuf) = (Vec::new(), Vec::new()); - let count = - append_node_triangles(&vertices, &indices, &IDENTITY, 0.08, &mut vbuf, &mut ibuf); + let count = append_node_triangles( + &pos(&vertices), + &indices, + &IDENTITY, + 0.08, + &mut vbuf, + &mut ibuf, + ); assert_eq!(count, 32); assert_eq!(ibuf, indices); assert_eq!(vbuf.len(), vertices.len() * STRIDE); @@ -322,8 +331,14 @@ mod tests { // 1 m² in 20 000 triangles of 0.5 cm² each; samples 10 cm apart. let (vertices, indices) = grid(100, 1.0); let (mut vbuf, mut ibuf) = (Vec::new(), Vec::new()); - let count = - append_node_triangles(&vertices, &indices, &IDENTITY, 0.1, &mut vbuf, &mut ibuf); + let count = append_node_triangles( + &pos(&vertices), + &indices, + &IDENTITY, + 0.1, + &mut vbuf, + &mut ibuf, + ); assert!((100..=121).contains(&count), "kept {count}"); assert_eq!(ibuf.len() as u32, count * 3); assert_eq!(vbuf.len(), ibuf.len() * STRIDE); @@ -351,7 +366,7 @@ mod tests { let bounds = ([0.0, 0.0, 0.0], [400.0, 0.0, 400.0]); let (mut vbuf, mut ibuf) = (Vec::new(), Vec::new()); let count = append_node_triangles_in( - &vertices, + &pos(&vertices), &indices, &IDENTITY, 0.08, @@ -370,7 +385,7 @@ mod tests { let whole = ([-10.0, -50.0, -10.0], [410.0, 50.0, 410.0]); let (mut vbuf, mut ibuf) = (Vec::new(), Vec::new()); let count = append_node_triangles_in( - &vertices, + &pos(&vertices), &indices, &IDENTITY, 0.08, @@ -382,7 +397,7 @@ mod tests { assert_eq!((count, ibuf.len()), (3200, indices.len())); let away = ([900.0, -50.0, 900.0], [950.0, 50.0, 950.0]); let count = append_node_triangles_in( - &vertices, + &pos(&vertices), &indices, &IDENTITY, 0.08, @@ -395,7 +410,7 @@ mod tests { // No thinning asked for: the clip still applies. let (mut vbuf, mut ibuf) = (Vec::new(), Vec::new()); let count = append_node_triangles_in( - &vertices, + &pos(&vertices), &indices, &IDENTITY, 0.0, @@ -415,7 +430,8 @@ mod tests { big[1][1] = 100.0; big[2][2] = 100.0; // triangles are now 0.5 m² each let (mut vbuf, mut ibuf) = (Vec::new(), Vec::new()); - let count = append_node_triangles(&vertices, &indices, &big, 0.1, &mut vbuf, &mut ibuf); + let count = + append_node_triangles(&pos(&vertices), &indices, &big, 0.1, &mut vbuf, &mut ibuf); assert_eq!(count, 20_000); } } diff --git a/native/shared/tests/golden_render.rs b/native/shared/tests/golden_render.rs index 4c41bb9c..7c3a0e54 100644 --- a/native/shared/tests/golden_render.rs +++ b/native/shared/tests/golden_render.rs @@ -712,13 +712,16 @@ fn gltf_blend_is_fractional_and_not_cutout_or_opaque() { assert!(eng.renderer.cache_model_if_static( OPAQUE_HANDLE, &[cached_mesh( - cached_opaque_vertices, + cached_opaque_vertices.into(), MaterialAlphaMode::Opaque )] )); assert!(eng.renderer.cache_model_if_static( BLEND_HANDLE, - &[cached_mesh(cached_blend_vertices, MaterialAlphaMode::Blend)] + &[cached_mesh( + cached_blend_vertices.into(), + MaterialAlphaMode::Blend + )] )); let (_, _, cached_opaque) = render(&mut eng, 3, |eng| { draw(eng); @@ -820,7 +823,7 @@ fn mask_coverage_mips_preserve_subpixel_silhouette_area() { ]; let indices = vec![0, 1, 2, 0, 2, 3]; let mask_mesh = |texture_idx, alpha_coverage_mips| MeshData { - vertices: vertices.clone(), + vertices: vertices.clone().into(), secondary_tex_coords: None, indices: indices.clone(), texture_idx: Some(texture_idx), @@ -959,7 +962,7 @@ fn gltf_transmission_uses_physical_retained_and_cached_paths() { assert!(eng.renderer.cache_model_if_static( TRANSMISSION_HANDLE, &[MeshData { - vertices: glass_vertices, + vertices: glass_vertices.into(), secondary_tex_coords: None, indices: glass_indices, texture_idx: None, @@ -1077,7 +1080,7 @@ fn physical_texcoord_1_matches_between_retained_cached_shadow_and_reactive_paths const UV1_HANDLE: u64 = 0x7A11_5101; const FALLBACK_HANDLE: u64 = 0x7A11_5102; let mesh = |secondary_tex_coords| MeshData { - vertices: glass_vertices.clone(), + vertices: glass_vertices.clone().into(), secondary_tex_coords, indices: glass_indices.clone(), texture_idx: None, diff --git a/native/shared/tests/golden_render/fractional_dynamic.rs b/native/shared/tests/golden_render/fractional_dynamic.rs index 2c1a791f..093feb56 100644 --- a/native/shared/tests/golden_render/fractional_dynamic.rs +++ b/native/shared/tests/golden_render/fractional_dynamic.rs @@ -330,7 +330,7 @@ fn fractional_skinned_motion_tracks_native_and_fresh_recovery() { assert!(eng.renderer.cache_model_if_static( HANDLE, &[MeshData { - vertices, + vertices: vertices.into(), secondary_tex_coords: None, indices, texture_idx: Some(texture), @@ -461,7 +461,8 @@ fn fractional_alpha_tested_motion_tracks_native_and_fresh_recovery() { vertex([1.0, 0.0, 0.0], [1.0, 1.0]), vertex([1.0, 2.8, 0.0], [1.0, 0.0]), vertex([-1.0, 2.8, 0.0], [0.0, 0.0]), - ], + ] + .into(), secondary_tex_coords: None, indices: vec![0, 1, 2, 0, 2, 3], texture_idx: Some(texture), @@ -798,7 +799,8 @@ fn fractional_procedural_foliage_tracks_native_at_fixed_time() { vertex([1.15, 0.0, 0.0], [1.0, 1.0]), vertex([1.15, 4.2, 0.0], [1.0, 0.0]), vertex([-1.15, 4.2, 0.0], [0.0, 0.0]), - ], + ] + .into(), secondary_tex_coords: None, indices: vec![0, 1, 2, 0, 2, 3], texture_idx: Some(texture), diff --git a/native/shared/tests/golden_render/joint_pages.rs b/native/shared/tests/golden_render/joint_pages.rs index cda74d86..e4ba34fe 100644 --- a/native/shared/tests/golden_render/joint_pages.rs +++ b/native/shared/tests/golden_render/joint_pages.rs @@ -118,7 +118,8 @@ fn cache_square(eng: &mut EngineState, handle: u64, joints: usize, half_size: f3 vertex(1.0, -1.0), vertex(1.0, 1.0), vertex(-1.0, 1.0), - ], + ] + .into(), secondary_tex_coords: None, indices: vec![0, 1, 2, 0, 2, 3], texture_idx: None, diff --git a/native/shared/tests/golden_render/morph_targets.rs b/native/shared/tests/golden_render/morph_targets.rs index 74ffd4ac..58a42c5f 100644 --- a/native/shared/tests/golden_render/morph_targets.rs +++ b/native/shared/tests/golden_render/morph_targets.rs @@ -18,7 +18,7 @@ const GRID: usize = 24; fn mesh(vertices: Vec, indices: Vec, morph: Option>) -> MeshData { MeshData { - vertices, + vertices: vertices.into(), secondary_tex_coords: None, indices, texture_idx: None, diff --git a/native/shared/tests/golden_render/motion_producer_audit.rs b/native/shared/tests/golden_render/motion_producer_audit.rs index 7f16169d..d83d63fc 100644 --- a/native/shared/tests/golden_render/motion_producer_audit.rs +++ b/native/shared/tests/golden_render/motion_producer_audit.rs @@ -20,7 +20,7 @@ fn quad_vertices(half_extent: f32) -> Vec { fn untextured_mesh(vertices: Vec, alpha_mode: MaterialAlphaMode) -> MeshData { MeshData { - vertices, + vertices: vertices.into(), secondary_tex_coords: None, indices: vec![0, 1, 2, 0, 2, 3], texture_idx: None, diff --git a/native/shared/tests/golden_render/quality_presets.rs b/native/shared/tests/golden_render/quality_presets.rs index 42d7b11e..143f3373 100644 --- a/native/shared/tests/golden_render/quality_presets.rs +++ b/native/shared/tests/golden_render/quality_presets.rs @@ -152,7 +152,7 @@ fn install_glossy_detail_fixture(eng: &mut EngineState) { assert!(eng.renderer.cache_model_if_static( GLOSSY_DETAIL_HANDLE, &[MeshData { - vertices, + vertices: vertices.into(), secondary_tex_coords: None, indices, texture_idx: Some(base_color), diff --git a/native/shared/tests/golden_render/temporal_history_skinned.rs b/native/shared/tests/golden_render/temporal_history_skinned.rs index c8f950cd..69b04776 100644 --- a/native/shared/tests/golden_render/temporal_history_skinned.rs +++ b/native/shared/tests/golden_render/temporal_history_skinned.rs @@ -84,7 +84,8 @@ fn fs_reactive(in: VsOut) -> ReactiveTranslucentOut { vertex([0.55, -0.55, 0.0]), vertex([0.55, 0.55, 0.0]), vertex([-0.55, 0.55, 0.0]), - ], + ] + .into(), secondary_tex_coords: None, indices: vec![0, 1, 2, 0, 2, 3], texture_idx: None, @@ -334,7 +335,7 @@ fn cached_skinned_motion_sequence_bounds_animation_trails() { assert!(eng.renderer.cache_model_if_static( HANDLE, &[MeshData { - vertices, + vertices: vertices.into(), secondary_tex_coords: None, indices, texture_idx: None, @@ -450,7 +451,7 @@ fn cached_alpha_tested_card_motion_writes_velocity_and_bounds_trails() { assert!(eng.renderer.cache_model_if_static( HANDLE, &[MeshData { - vertices, + vertices: vertices.into(), secondary_tex_coords: None, indices: vec![0, 1, 2, 0, 2, 3], texture_idx: Some(texture), diff --git a/native/shared/tests/golden_render/transparency.rs b/native/shared/tests/golden_render/transparency.rs index 05930c9a..1b752374 100644 --- a/native/shared/tests/golden_render/transparency.rs +++ b/native/shared/tests/golden_render/transparency.rs @@ -49,7 +49,7 @@ fn layered_pbr_runs_on_opaque_sorted_reactive_and_weighted_paths() { assert!(eng.renderer.cache_model_if_static( HANDLE, &[MeshData { - vertices, + vertices: vertices.into(), secondary_tex_coords: None, indices, texture_idx: None, @@ -147,7 +147,7 @@ fn layered_pbr_runs_on_opaque_sorted_reactive_and_weighted_paths() { assert!(eng.renderer.cache_model_if_static( REFRACTIVE_HANDLE, &[MeshData { - vertices: refractive_vertices, + vertices: refractive_vertices.into(), secondary_tex_coords: None, indices: refractive_indices, texture_idx: None, @@ -231,7 +231,7 @@ fn layered_pbr_runs_on_opaque_sorted_reactive_and_weighted_paths() { assert!(eng.renderer.cache_model_if_static( REFRACTIVE_UV1_HANDLE, &[MeshData { - vertices: uv1_vertices, + vertices: uv1_vertices.into(), secondary_tex_coords: Some(uv1), indices: uv1_indices, texture_idx: None, @@ -481,10 +481,10 @@ fn weighted_transparency_is_order_independent_for_intersecting_imported_blend() const BLUE_HANDLE: u64 = 0x0170_0002; assert!(eng .renderer - .cache_model_if_static(RED_HANDLE, &[blend_mesh(red_vertices)])); + .cache_model_if_static(RED_HANDLE, &[blend_mesh(red_vertices.into())])); assert!(eng .renderer - .cache_model_if_static(BLUE_HANDLE, &[blend_mesh(blue_vertices)])); + .cache_model_if_static(BLUE_HANDLE, &[blend_mesh(blue_vertices.into())])); let custom_material = custom_material_z .map(|_| { eng.renderer.compile_material_with_options( diff --git a/native/shared/tests/visibility_buffer_shading_runtime.rs b/native/shared/tests/visibility_buffer_shading_runtime.rs index 86ab2a71..cd7d6e1d 100644 --- a/native/shared/tests/visibility_buffer_shading_runtime.rs +++ b/native/shared/tests/visibility_buffer_shading_runtime.rs @@ -283,7 +283,7 @@ fn opt_in_visibility_shading_replaces_eligible_forward_pixels() { }; let material_model = ModelData { meshes: vec![Arc::new(MeshData { - vertices: vertices.clone(), + vertices: vertices.clone().into(), secondary_tex_coords: None, indices: vec![0, 1, 2], texture_idx: None, @@ -408,7 +408,7 @@ fn opt_in_visibility_shading_replaces_eligible_forward_pixels() { vertex.color = [0.95, 0.05, 0.1, 0.65]; } let compatibility_mesh = Arc::new(MeshData { - vertices: compatibility_vertices, + vertices: compatibility_vertices.into(), secondary_tex_coords: None, indices: vec![0, 1, 2], texture_idx: None, @@ -573,7 +573,7 @@ fn opt_in_visibility_shading_replaces_eligible_forward_pixels() { let mut skinned_vertices = compatibility_vertices_for_skinning(); skinned_vertices[2].joints = [1.0, 0.0, 0.0, 0.0]; let skinned_mesh = Arc::new(MeshData { - vertices: skinned_vertices, + vertices: skinned_vertices.into(), secondary_tex_coords: None, indices: vec![0, 1, 2], texture_idx: None, diff --git a/native/web/src/lib.rs b/native/web/src/lib.rs index 56052ea6..7a5ec9c7 100644 --- a/native/web/src/lib.rs +++ b/native/web/src/lib.rs @@ -1524,7 +1524,7 @@ pub fn bloom_scene_attach_model(node_handle: f64, model_handle: f64, mesh_index: } let mesh = &model_data.meshes[mi]; - let vertices = mesh.vertices.clone(); + let vertices = mesh.vertices.to_vertices(); let indices = mesh.indices.clone(); let base_color_tex = mesh.texture_idx; let normal_tex = mesh.normal_texture_idx; diff --git a/native/web/src/render_settings.rs b/native/web/src/render_settings.rs index bce2acf1..152fff2f 100644 --- a/native/web/src/render_settings.rs +++ b/native/web/src/render_settings.rs @@ -106,7 +106,15 @@ pub fn bloom_set_shadow_filter_4tap(on: f64) -> f64 { } #[wasm_bindgen] #[allow(clippy::too_many_arguments)] -pub fn bloom_set_far_shadow(cx: f64, cz: f64, half_x: f64, half_z: f64, y_min: f64, y_max: f64, refresh: f64) -> f64 { +pub fn bloom_set_far_shadow( + cx: f64, + cz: f64, + half_x: f64, + half_z: f64, + y_min: f64, + y_max: f64, + refresh: f64, +) -> f64 { engine().renderer.set_far_shadow( cx as f32, cz as f32, @@ -231,7 +239,9 @@ pub fn bloom_set_auto_resolution(target_hz: f64, enabled: f64) -> f64 { } #[wasm_bindgen] pub fn bloom_set_aerial_perspective(strength: f64) -> f64 { - engine().renderer.set_aerial_perspective_strength(strength as f32); + engine() + .renderer + .set_aerial_perspective_strength(strength as f32); 1.0 } #[wasm_bindgen] @@ -398,7 +408,9 @@ pub fn bloom_set_foliage_shadow_motion(on: f64) -> f64 { #[wasm_bindgen] pub fn bloom_set_weather(cloud_cover: f64, wetness: f64) -> f64 { - engine().renderer.set_weather(cloud_cover as f32, wetness as f32); + engine() + .renderer + .set_weather(cloud_cover as f32, wetness as f32); 1.0 } @@ -496,7 +508,7 @@ pub fn bloom_scene_attach_model_lod( return 0.0; } let mesh = &md.meshes[mi]; - let (v, i) = (mesh.vertices.clone(), mesh.indices.clone()); + let (v, i) = (mesh.vertices.to_vertices(), mesh.indices.clone()); eng.scene .set_lod_geometry(node, lod_index as usize, v, i, max_coverage as f32); 1.0 From b586946406f409292ac8dc075fe55250e156e11e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Wed, 25 Nov 2026 15:35:25 +0100 Subject: [PATCH 2/3] bloom-cook and the layered-glTF example read the compact vertex store Co-Authored-By: Claude --- native/shared/examples/validate_layered_gltf.rs | 6 +++--- tools/bloom-cook/scene_cook.rs | 4 +++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/native/shared/examples/validate_layered_gltf.rs b/native/shared/examples/validate_layered_gltf.rs index dc006fca..17c31ddf 100644 --- a/native/shared/examples/validate_layered_gltf.rs +++ b/native/shared/examples/validate_layered_gltf.rs @@ -87,7 +87,7 @@ fn main() -> ExitCode { let authored_tangents = model .meshes .iter() - .flat_map(|mesh| &mesh.vertices) + .flat_map(|mesh| mesh.vertices.to_vertices()) .filter(|vertex| { let tangent = vertex.tangent; tangent[0] * tangent[0] + tangent[1] * tangent[1] + tangent[2] * tangent[2] > 1e-6 @@ -150,7 +150,7 @@ fn main() -> ExitCode { let mut normal_maximum = [f32::NEG_INFINITY; 3]; let mut position_minimum = [f32::INFINITY; 3]; let mut position_maximum = [f32::NEG_INFINITY; 3]; - for vertex in &mesh.vertices { + for vertex in &mesh.vertices.to_vertices() { for channel in 0..3 { normal_minimum[channel] = normal_minimum[channel].min(vertex.normal[channel]); normal_maximum[channel] = normal_maximum[channel].max(vertex.normal[channel]); @@ -166,7 +166,7 @@ fn main() -> ExitCode { (position_minimum[2] + position_maximum[2]) * 0.5, ]; let mut radial_normal_dot = [f32::INFINITY, f32::NEG_INFINITY, 0.0]; - for vertex in &mesh.vertices { + for vertex in &mesh.vertices.to_vertices() { let radial = [ vertex.position[0] - center[0], vertex.position[1] - center[1], diff --git a/tools/bloom-cook/scene_cook.rs b/tools/bloom-cook/scene_cook.rs index 97bdf707..f170435c 100644 --- a/tools/bloom-cook/scene_cook.rs +++ b/tools/bloom-cook/scene_cook.rs @@ -158,8 +158,9 @@ fn convert_primitive( ) -> Option { let invalid_positions = mesh .vertices + .positions() .iter() - .map(|vertex| vertex.position.iter().any(|value| !value.is_finite())) + .map(|position| position.iter().any(|value| !value.is_finite())) .collect::>(); sanitation.non_finite_position_vertices = sanitation .non_finite_position_vertices @@ -190,6 +191,7 @@ fn convert_primitive( } let vertices = mesh .vertices + .to_vertices() .iter() .zip(invalid_positions) .map(|(vertex, invalid_position)| { From 9b0cdf5ec08a2b0d74896161fc0da3dd77a9041a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ralph=20K=C3=BCpper?= Date: Wed, 25 Nov 2026 15:36:00 +0100 Subject: [PATCH 3/3] scene: a shared LOD rebuilds its whole vertices only when it uploads (review) Co-Authored-By: Claude --- native/shared/src/scene.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/native/shared/src/scene.rs b/native/shared/src/scene.rs index 611277cd..80db2545 100644 --- a/native/shared/src/scene.rs +++ b/native/shared/src/scene.rs @@ -1859,24 +1859,25 @@ impl SceneGraph { && lod.gpu_geometry.is_none() && !lod.gpu_geometry_refused { - let shared_whole; - let (vertices, indices): (&[Vertex3D], &[u32]) = match lod.shared.as_ref() { - Some(mesh) => { - shared_whole = mesh.vertices.to_vertices(); - (&shared_whole[..], &mesh.indices[..]) - } - None => (&lod.vertices[..], &lod.indices[..]), + let (vertex_count, indices) = match lod.shared.as_ref() { + Some(mesh) => (mesh.vertices.len(), &mesh.indices[..]), + None => (lod.vertices.len(), &lod.indices[..]), }; - if !vertices.is_empty() && !indices.is_empty() { + if vertex_count != 0 && !indices.is_empty() { let key = match lod.shared.as_ref() { Some(mesh) => shared_mesh_cache.key(mesh), - None => scene_geometry_key(vertices, indices), + None => scene_geometry_key(&lod.vertices, indices), }; let slice = if let Some(cached) = shared_gpu_geometry.get_mut(&key) { cached.references = cached.references.saturating_add(1); Some(cached.slice) } else { - let slice = gpu_driven.upload_static(device, queue, vertices, indices); + // whole vertices only for the upload itself + let vertices = match lod.shared.as_ref() { + Some(mesh) => std::borrow::Cow::Owned(mesh.vertices.to_vertices()), + None => std::borrow::Cow::Borrowed(&lod.vertices[..]), + }; + let slice = gpu_driven.upload_static(device, queue, &vertices, indices); if let Some(slice) = slice { shared_gpu_geometry.insert( key,