diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index a40c1425..d2b068aa 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -2603,6 +2603,46 @@ scene's preparation. In the same walking frame the upper middle of the picture, string of lights, has 0.67 of the offline light after the upscaler in both builds: small bright things lose light there while the camera moves, and their glow with it. Not checked on Vulkan, nor in a browser. +**A mesh that does not deform is held compacted (2026-12-02, after it).** A BLAS is built into the worst case its +geometry could need, and a build that is done can say what it does need. The scene's upload built every BLAS and kept +it as built: Bistro's 2.8 million triangles held 293 MB of them, Tokyo's 23 million 2.4 GB. + +- `Gpu::upload`. A mesh that does not deform is built once. Its BLAS is made to allow compaction (traced fast, as + before), and when its batch's build is done it is copied into a structure of the size the build reported; the one + it was built in is freed. The batches are as they were (4 million triangles at most, for the build's scratch room) + and a batch is compacted before the next is built: what is held at once is the compacted ones and one batch as + built. Deforming meshes (posed skinned models', particle systems') are rebuilt every pose and stay as built; so do + the meshes edits make, and the procedural boxes'. +- The TLAS was built with the last batch, in one call. A compacted copy is a write of the queue's own and goes out + with whatever is submitted next. Where several views share a device (the unit suite's tests, side by side) it went + out with another's submit, the TLAS was then built over a structure whose copy was not done, and on Metal a TLAS + built so loses the instance: five tests failed in one run of the suite, none of them when run alone. + The copies are now submitted and waited for and the TLAS built after them, by itself. With that the suite passed + five times running; with the wait taken out again it failed in two runs of two (one test, then two). +- Edits. wgpu builds no compacted structure again (a validation error). A mesh of the build whose geometry an edit + rewrites where it lies (the same sections: three.js's dynamic draw usage) takes a new BLAS of the same geometries + first, built fast as an edit's, and is built again in that one from then on (`Gpu::renew_mesh`). The objects that + draw it are placed again by that edit, as they are when its vertices outgrow their run and it takes a new one. +- Measured (an M4, Metal; each structure's size before and after as wgpu-core has them, printed for this). Tokyo's + 1,248 structures 2,401 MB → 1,129; Bistro's one 293.1 → 137.1; a small scene's 6.4 → 2.8; Zero-Day's 608.2 → + 488.7 (one mesh has nearly all of its 5.9 million triangles). A plaza of skinned mannequins: none to compact. + Bistro's offline render with and without is the same in every pixel. Five clips alternated (without, with, with, + without), a frame's GPU time: the city's 17.80 → 17.72 ms, the others within 1 % and none slower by more than 0.1 %; their + pictures' measures the same to the last digit, and their loading within its own spread. Twelve clips against + offline, this build beside main's (main, this, this, main): ΔE the same on every clip to 0.01, which is what two + runs of one build differ by; the frame within 0.5 % on eleven, and on the twelfth main's first run was the slow + one. +- `tri_blas_mb` is what the builds allocate, as it was. wgpu does not hand out a structure's size; a function for it + in the vendored wgpu was written and taken out again: the browser's module is built against the released wgpu + (`renderer/web`), and the renderer's source is kept to what that one has. +- `THREERT_BLAS_COMPACT=0` leaves every BLAS as built. +- Unit suite 297 (one new: a compacted mesh's geometry changed where it lies, twice, each against a build; without + the new BLAS it fails with wgpu's error), render suite 276. + +Not done. A mesh that comes by an edit (a streamed city's cells are those) is held as built: its copy would have to +come some frames after its build, its instances be placed again, and a mesh that is rebuilt every frame left alone. +wgpu has no refit (`PreferUpdate` builds): a deforming mesh is rebuilt. Not checked on Vulkan. + **The live passes from one place (2026-11-14, after it).** A buffer and a pass more (the locks' carry, above) took seven edits that had to agree: the declaration in live.wgsl, the bind group layout's entries, the pass list, the buffers' sizes and order, the bind group's entries, the dispatch grid (in two copies), and the merged layout's table. diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md index adf12350..3682b6ef 100644 --- a/docs/RUNTIME.md +++ b/docs/RUNTIME.md @@ -1710,6 +1710,17 @@ Vertices and indices, one layout for hardware and software traversal (`renderer/ Tokyo 1.17, Zero Day 1.03, a crowd of skinned walkers 0.98, small scenes of smooth models 0.5 to 0.7, a voxel level's meshes 1.88 (a face's four corners are no other face's). With the BLASes, on the GPU: Tokyo 6.4 GB -> 3.9, Zero Day 1.6 -> 0.95. +- **The BLASes are compacted** (2026-12-02; `Gpu::upload`). A build allocates a structure's worst case. A mesh that + does not deform is built once: its BLAS, traced fast as before, is copied when it is built into a structure of + the size the build then reports, and the one it was built in is freed. A city of 1,248 meshes and 23 million + triangles 2,401 MB -> 1,129, a street of one mesh and 2.8 million 293 -> 137, a small scene 6.4 -> 2.8; one mesh + of 5.9 million triangles 608 -> 489 (an M4, Metal). The builds go in batches as before and a batch is compacted + before the next is built: what is held at once is the compacted ones and one batch as built. A deforming mesh's + (a posed skinned model's, a particle system's) is rebuilt every pose and stays as built; so does a mesh an edit + makes. wgpu builds no compacted structure again: a mesh of the build whose geometry an edit rewrites where it lies + takes a new BLAS first, built fast as an edit's (`Gpu::renew_mesh`). The frame's time and the scene's loading are + what they were. `tri_blas_mb` is still what the builds allocate: wgpu does not say what a structure was compacted + to. `THREERT_BLAS_COMPACT=0` leaves every BLAS as built. - The build still flattens a file's indexed geometry and finds the sharing again (1.2 s on Tokyo's 23 M triangles): carrying a file's indices through is a later step. - Under hardware traversal the kernel binds one buffer fewer than it did (a triangle's attributes were a second diff --git a/docs/VOXEL.md b/docs/VOXEL.md index 834c5816..38de034f 100644 --- a/docs/VOXEL.md +++ b/docs/VOXEL.md @@ -64,8 +64,9 @@ today, built from CC0 `.vox` content and procedural generation. Its lines: leaks light, every voxel shows its own colour (below). - **Memory:** ≤ 2 GB per level, the BLASes, triangle data and procedural data together (`tri_blas_mb`, `tri_data_mb`, `proc_blas_mb`, `proc_data_mb`); the benchmark level is accepted against it. Today: as meshes 516 MB (BLASes 256.4, - data 259.6), as region boxes 267 MB. If destruction's pieces or more content bring it near, compressed attributes, - BLAS compaction and LOD come forward. + data 259.6), as region boxes 267 MB. (The BLASes at what their builds allocate: since 2026-12-02 the build's meshes + are held compacted, docs/RUNTIME.md "The scene's triangles", which this level has not been measured with.) If + destruction's pieces or more content bring it near, compressed attributes and LOD come forward. - **Features:** fire, smoke, water, vehicles, joints, ropes; a game API over voxel edits, bodies, joints, lights, scene queries and effects. diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs index 88735dea..a895cce2 100644 --- a/renderer/src/gpu.rs +++ b/renderer/src/gpu.rs @@ -270,6 +270,7 @@ fn mesh_entries<'a>(accel: &'a Accel, meshes: &[u32]) -> Vec, /// One per instanced mesh (model space), referenced by the TLAS's model instances. meshes: Vec, + /// By mesh: its BLAS is a compacted one (`Gpu::upload`: of a mesh that does not deform). wgpu builds no compacted + /// structure again: an edit that rewrites the mesh where it is takes a new one first (`Gpu::renew_mesh`). + packed: Vec, /// Per mesh: its (first pool triangle, count) geometries and their sizes (`mesh_entries`). mesh_geo: Vec<(Vec<(u32, u32)>, Vec)>, /// The build's triangle BLAS bytes per triangle (Metal's sizes): edits' memory estimates (live/mod.rs `room_stats`). @@ -937,6 +941,13 @@ pub enum Top<'a> { Sw(&'a mut crate::units::Units), } +impl Accel { + /// Whether mesh `k`'s BLAS is a compacted one. + pub fn packed(&self, k: u32) -> bool { + self.packed[k as usize] + } +} + impl<'a> Top<'a> { /// The scene's, or None under software traversal without units (edits rebuild then). pub fn of(accel: &'a mut Option, units: &'a mut Option) -> Option> { @@ -2710,7 +2721,7 @@ impl Gpu { // (The indices' first word in the words' heap.) let index_first = (words.at(Stream::Indices) / 4) as u32; // (Room for one at least: a scene of the sky alone.) - let mut t = d.create_tlas(&wgpu::CreateTlasDescriptor { label: None, max_instances: (scene.instances.len() + scene.procs.len() + room.records).max(1) as u32, flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE, update_mode: wgpu::AccelerationStructureUpdateMode::Build }); + let t = d.create_tlas(&wgpu::CreateTlasDescriptor { label: None, max_instances: (scene.instances.len() + scene.procs.len() + room.records).max(1) as u32, flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE, update_mode: wgpu::AccelerationStructureUpdateMode::Build }); // Per mesh: its geometries, one a section (`InstMesh::parts`): first triangle, count. let mesh_parts: Vec> = scene.meshes.iter().map(|m| m.parts(&scene.sections).into_iter().map(|(at, count)| (m.first + at, count)).collect()).collect(); // (A translucent particle system's is not flagged opaque: the translucency pass asks for every hit.) @@ -2740,17 +2751,24 @@ impl Gpu { .collect() }) .collect(); - // Deforming meshes (posed skinned models') are rebuilt every new pose: built fast rather than traced fast. + // A mesh that does not deform is built once, traced fast, and compacted when it is built (below): a build + // allocates a structure's worst case. Deforming meshes (posed skinned models', particle systems') are + // rebuilt every new pose: built fast rather than traced fast, and left as built. + let compacting = std::env::var("THREERT_BLAS_COMPACT").map(|v| v != "0").unwrap_or(true); + let still = |k: usize| compacting && !scene.meshes[k].deforms && scene.meshes[k].count > 0; let meshes: Vec = mesh_sizes .iter() - .zip(&scene.meshes) - .map(|(s, m)| { - let flags = if m.deforms { wgpu::AccelerationStructureFlags::PREFER_FAST_BUILD } else { wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE }; + .enumerate() + .map(|(k, s)| { + let flags = if scene.meshes[k].deforms { wgpu::AccelerationStructureFlags::PREFER_FAST_BUILD } else { wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE }; + let flags = if still(k) { flags | wgpu::AccelerationStructureFlags::ALLOW_COMPACTION } else { flags }; d.create_blas(&wgpu::CreateBlasDescriptor { label: None, flags, update_mode: wgpu::AccelerationStructureUpdateMode::Build }, wgpu::BlasGeometrySizeDescriptors::Triangles { descriptors: s.clone() }) }) .collect(); - // What the triangle BLASes hold (Metal's own sizes; each instanced mesh once). A geometry: its first vertex - // and how many, its first triangle and how many. + // What the triangle BLASes' builds allocate (Metal's own sizes; each instanced mesh once): what a deforming + // mesh's and an edit's hold. A compacted one keeps a part of it, which wgpu does not tell: half in a city + // and a street, four fifths in one mesh of six million triangles (docs/RUNTIME.md "The scene's triangles"). + // A geometry: its first vertex and how many, its first triangle and how many. let mut blas_per_tri = 0.0; let parts: Vec> = mesh_parts.iter().zip(&ix.meshes).map(|(ps, &(vfirst, vcount))| ps.iter().map(|&(first, count)| (vfirst, vcount.max(1), first, count)).collect()).collect(); if let Some(bytes) = parts.iter().map(|ps| self.tri_blas_bytes(&b_vertices, &words.buffer, index_first, ps)).sum::>() { @@ -2759,13 +2777,6 @@ impl Gpu { blas_per_tri = bytes as f64 / tris.max(1) as f64; } anyhow::ensure!(scene.instances.len() + scene.procs.len() <= 1 << 24, "too many instances for 24-bit custom data"); - for (k, inst) in scene.instances.iter().enumerate() { - let w = inst.world; - let row = |r: usize| [w.x_axis[r], w.y_axis[r], w.z_axis[r], w.w_axis[r]]; - let [r0, r1, r2] = [row(0), row(1), row(2)]; - let xf = [r0[0], r0[1], r0[2], r0[3], r1[0], r1[1], r1[2], r1[3], r2[0], r2[1], r2[2], r2[3]]; - t[k] = Some(wgpu::TlasInstance::new(&meshes[inst.mesh as usize], xf, k as u32, instance_mask(inst.cast_shadow, inst.hidden))); - } // Procedural geometry: one AABB BLAS per distinct geometry (object space; kept across uploads by the // geometry's hash, so a rebuild builds only new ones), and per mesh a TLAS instance of it after the model // instances, whose custom data is the mesh's record; its hits are told apart by their kind. @@ -2795,73 +2806,72 @@ impl Gpu { timings.push(("proc_blas_mb".into(), kept.values().map(|(_, b)| *b).sum::() as f64 / (1 << 20) as f64)); *built = kept; drop(built); - for (j, p) in scene.procs.iter().enumerate() { - let record = (scene.gpu_instances.len() + j) as u32; - let k = scene.proc_layout.as_ref().map_or(j, |l| l.blob_of[j]); - t[proc_base + j] = Some(wgpu::TlasInstance::new(&geo_blas[k], tlas_rows(p.world), record, instance_mask(p.cast_shadow, p.hidden))); - } - let entries: Vec = meshes - .iter() - .zip(&mesh_sizes) - .zip(&mesh_parts) - .zip(&ix.meshes) - .map(|(((blas, sizes), parts), &(first_vertex, _))| wgpu::BlasBuildEntry { - blas, - geometry: wgpu::BlasGeometries::TriangleGeometries( - sizes - .iter() - .zip(parts) - .map(|(size, &(first, _))| wgpu::BlasTriangleGeometry { - size, - vertex_buffer: &b_vertices, - first_vertex, - vertex_stride: VERTEX_STRIDE, - index_buffer: Some(&words.buffer), - first_index: Some(index_first + first * 3), - transform_buffer: None, - transform_buffer_offset: None, - }) - .collect(), - ), - }) - .chain(proc_new.iter().map(|(k, boxes, size)| wgpu::BlasBuildEntry { - blas: &geo_blas[*k], - geometry: wgpu::BlasGeometries::AabbGeometries(vec![wgpu::BlasAabbGeometry { size, stride: 24, aabb_buffer: boxes, primitive_offset: 0 }]), - })) - .collect(); - // In batches of at most BLAS_BATCH_TRIS triangles (a BLAS larger alone), each submitted and waited for, the - // TLAS with the last: wgpu-core gives one build a single scratch buffer for all its BLASes, the sum of theirs, - // and on a GPU of 8 GB a city's (a few thousand meshes) did not fit beside the scene. - let tris_of = |e: &wgpu::BlasBuildEntry<'_>| -> u64 { - match &e.geometry { - wgpu::BlasGeometries::TriangleGeometries(g) => g.iter().map(|x| x.size.index_count.unwrap_or(x.size.vertex_count) as u64 / 3).sum(), - wgpu::BlasGeometries::AabbGeometries(g) => g.iter().map(|x| x.size.primitive_count as u64).sum(), - } - }; + let mesh_geo: Vec<(Vec<(u32, u32)>, Vec)> = mesh_parts.into_iter().zip(mesh_sizes).collect(); + let mut a = Accel { tlas: t, vertices: b_vertices.clone(), indices: words.buffer.clone(), index_first, mesh_verts: ix.meshes.clone(), packed: vec![false; meshes.len()], meshes, mesh_geo, blas_per_tri }; + // The BLASes' builds (the meshes', then the new procedural ones'), in batches of at most BLAS_BATCH_TRIS + // triangles (a BLAS larger alone), each submitted and waited for: wgpu-core gives one build a single scratch + // buffer for all its BLASes, the sum of theirs, and on a GPU of 8 GB a city's (a few thousand meshes) did not + // fit beside the scene. A batch's still meshes are compacted before the next is built (each a copy into a + // structure of the size its build reported; the one it was built in is freed), so what is held at once is + // the compacted ones and one batch as built. + let tris: Vec = a.mesh_geo.iter().map(|(parts, _)| parts.iter().map(|p| p.1 as u64).sum()).chain(proc_new.iter().map(|p| p.2.primitive_count as u64)).collect(); + let n = a.meshes.len(); let mut start = 0; - loop { - let mut end = start; - let mut tris = 0; - while end < entries.len() && (end == start || tris + tris_of(&entries[end]) <= BLAS_BATCH_TRIS) { - tris += tris_of(&entries[end]); + while start < tris.len() { + let (mut end, mut sum) = (start + 1, tris[start]); + while end < tris.len() && sum + tris[end] <= BLAS_BATCH_TRIS { + sum += tris[end]; end += 1; } + let batch: Vec = (start..end.min(n)).map(|k| k as u32).collect(); + let mut entries = mesh_entries(&a, &batch); + entries.extend(proc_new[start.max(n) - n..end.max(n) - n].iter().map(|(k, boxes, size)| wgpu::BlasBuildEntry { + blas: &geo_blas[*k], + geometry: wgpu::BlasGeometries::AabbGeometries(vec![wgpu::BlasAabbGeometry { size, stride: 24, aabb_buffer: boxes, primitive_offset: 0 }]), + })); let mut enc = d.create_command_encoder(&Default::default()); - if end == entries.len() { - enc.build_acceleration_structures(entries[start..end].iter(), [&t]); - } else { - enc.build_acceleration_structures(entries[start..end].iter(), std::iter::empty::<&wgpu::Tlas>()); - } + enc.build_acceleration_structures(entries.iter(), std::iter::empty::<&wgpu::Tlas>()); self.queue.submit([enc.finish()]); + drop(entries); + // (The size a structure compacts to is read back when its build is done: the wait hands it over.) + let packed: Vec = batch.iter().map(|&k| k as usize).filter(|&k| still(k)).collect(); + for &k in &packed { + a.meshes[k].prepare_compaction_async(|_| {}); + } self.device.poll(wgpu::PollType::wait_indefinitely())?; - if end == entries.len() { - break; + for k in packed { + if a.meshes[k].ready_for_compaction() { + a.meshes[k] = self.queue.compact_blas(&a.meshes[k]); + a.packed[k] = true; + } } start = end; } - drop(entries); - let mesh_geo = mesh_parts.into_iter().zip(mesh_sizes).collect(); - accel = Some(Accel { tlas: t, vertices: b_vertices.clone(), indices: words.buffer.clone(), index_first, mesh_verts: ix.meshes.clone(), meshes, mesh_geo, blas_per_tri }); + // The last compacted copies are done before the TLAS is built over them: they are the queue's own writes, + // which go with whatever is submitted next, and on Metal a TLAS built in another submit than a BLAS it + // references, before that one is done, can see it unbuilt (`build_top`). + if a.packed.contains(&true) { + self.queue.submit([]); + self.device.poll(wgpu::PollType::wait_indefinitely())?; + } + // The instances, of the BLASes as they are now, and the TLAS over them. + for (k, inst) in scene.instances.iter().enumerate() { + let w = inst.world; + let row = |r: usize| [w.x_axis[r], w.y_axis[r], w.z_axis[r], w.w_axis[r]]; + let [r0, r1, r2] = [row(0), row(1), row(2)]; + let xf = [r0[0], r0[1], r0[2], r0[3], r1[0], r1[1], r1[2], r1[3], r2[0], r2[1], r2[2], r2[3]]; + a.tlas[k] = Some(wgpu::TlasInstance::new(&a.meshes[inst.mesh as usize], xf, k as u32, instance_mask(inst.cast_shadow, inst.hidden))); + } + for (j, p) in scene.procs.iter().enumerate() { + let record = (scene.gpu_instances.len() + j) as u32; + let k = scene.proc_layout.as_ref().map_or(j, |l| l.blob_of[j]); + a.tlas[proc_base + j] = Some(wgpu::TlasInstance::new(&geo_blas[k], tlas_rows(p.world), record, instance_mask(p.cast_shadow, p.hidden))); + } + let mut enc = d.create_command_encoder(&Default::default()); + enc.build_acceleration_structures(std::iter::empty::<&wgpu::BlasBuildEntry>(), [&a.tlas]); + self.queue.submit([enc.finish()]); + self.device.poll(wgpu::PollType::wait_indefinitely())?; + accel = Some(a); timings.push(("accel_build_ms".into(), tb.elapsed().as_secs_f64() * 1000.0)); } fn e(binding: u32, b: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> { @@ -3809,10 +3819,22 @@ impl Gpu { pub fn set_mesh(&self, accel: &mut Accel, k: u32, first: usize, mesh: &crate::scene::InstMesh, sections: &[crate::scene::Section]) { let (blas, geo) = self.mesh_blas_for(first, mesh, sections); accel.meshes[k as usize] = blas; + accel.packed[k as usize] = false; accel.mesh_geo[k as usize] = geo; accel.mesh_verts[k as usize] = (mesh.vfirst, mesh.vcount); } + /// Mesh `k`, whose triangles an edit rewrote where they are, is to be built again: if its BLAS is the upload's + /// compacted one, a new one in its slot with the same geometries (built fast, as an edit's: a geometry that is + /// rewritten once is rewritten again). The TLAS instances of the mesh are to be placed again (`Top::place`): + /// they hold the BLAS they were placed with. + pub fn renew_mesh(&self, accel: &mut Accel, k: u32) { + if std::mem::take(&mut accel.packed[k as usize]) { + let sizes = accel.mesh_geo[k as usize].1.clone(); + accel.meshes[k as usize] = self.device.create_blas(&wgpu::CreateBlasDescriptor { label: Some("edit mesh"), flags: wgpu::AccelerationStructureFlags::PREFER_FAST_BUILD, update_mode: wgpu::AccelerationStructureUpdateMode::Build }, wgpu::BlasGeometrySizeDescriptors::Triangles { descriptors: sizes }); + } + } + fn mesh_blas_for(&self, first: usize, mesh: &crate::scene::InstMesh, sections: &[crate::scene::Section]) -> (wgpu::Blas, (Vec<(u32, u32)>, Vec)) { let parts: Vec<(u32, u32)> = mesh.parts(sections).into_iter().map(|(at, count)| (first as u32 + at, count)).collect(); let sizes: Vec = parts @@ -3836,6 +3858,7 @@ impl Gpu { // every frame): `mesh_blas_for`. let (blas, geo) = self.mesh_blas_for(first, mesh, sections); accel.meshes.push(blas); + accel.packed.push(false); accel.mesh_geo.push(geo); accel.mesh_verts.push((mesh.vfirst, mesh.vcount)); accel.meshes.len() as u32 - 1 diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs index f76b6b75..568b3a10 100644 --- a/renderer/src/live/edits.rs +++ b/renderer/src/live/edits.rs @@ -300,6 +300,10 @@ pub(super) fn make_mesh(cx: &mut Meshing, data: scene::MeshData, colored: bool, if let gpu::Top::Hw(accel) = &mut *cx.top { cx.g.set_mesh(accel, k, old.first as usize, &cx.meshes[k as usize], cx.sections); } + } else if let gpu::Top::Hw(accel) = &mut *cx.top { + // (The scene's build compacted its BLAS, if it had not deformed: one that can be built again, placed + // by this edit as the one above is.) + cx.g.renew_mesh(accel, k); } let im = cx.meshes[k as usize]; cx.split.deformed += 1; diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs index a428ca32..7962207b 100644 --- a/renderer/src/live/inplace_tests.rs +++ b/renderer/src/live/inplace_tests.rs @@ -2499,6 +2499,40 @@ fn a_mesh_of_several_materials_is_edited_in_place() { against_a_build("meshes of several materials removed", &mut live, &w); } +/// A mesh of the build's that does not deform is held compacted under hardware traversal (`Gpu::upload`), and wgpu +/// builds no compacted structure again. Its geometry changed, its sections as they were: the mesh is rewritten where +/// it lies and its BLAS is a new one (`Gpu::renew_mesh`), which the next change builds again as it is. Each time the +/// picture is a build's. +#[test] +fn a_mesh_the_build_compacted_is_rewritten_where_it_lies() { + let presets = crate::default_presets_dir(); + let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, 96, 54)); + let quad = |s: f32| Geometry { positions: vec![-s, -s, 0.0, s, -s, 0.0, s, s, 0.0, -s, s, 0.0], normals: [0.0, 0.0, 1.0].repeat(4), uvs: vec![0.0; 8], indices: vec![0, 1, 2, 0, 2, 3], groups: vec![], colors: vec![] }; + let mut w = world(); + w.set_geometry(30, quad(0.3)).unwrap(); + w.set_object(40, "card".into(), None, Kind::Mesh { geometry: 30, material: 1, own_blas: true, materials: vec![] }, true, false).unwrap(); + w.set_transform(40, Vec3::new(0.3, -0.4, 0.9), glam::Quat::from_rotation_y(0.2), Vec3::ONE).unwrap(); + let mut live = match open(&w) { + Ok(c) => c, + Err(e) => return eprintln!("skipped: {e}"), + }; + w.take_changes(); + let mesh = |c: &LiveCore| c.sc.instances[c.sc.tables.retained.instance(40).expect("a mesh is an instance").instance as usize].mesh; + let (its, meshes) = (mesh(&live), live.sc.meshes.len()); + // (Software traversal has no BLAS: None.) + let packed = |c: &LiveCore| c.sc.up.accel.as_ref().map(|a| a.packed(its)); + assert_ne!(packed(&live), Some(false), "the build compacted its BLAS"); + for (what, s) in [("a compacted mesh's geometry changed", 0.2), ("and changed again", 0.26)] { + w.set_geometry(30, quad(s)).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback); + assert_eq!((mesh(&live), live.sc.meshes.len()), (its, meshes), "{what}: the mesh where it lies"); + assert_ne!(packed(&live), Some(true), "{what}: its BLAS is one that is built again"); + list_is_its_triangles(what, &live); + let mut fresh = open(&w).unwrap(); + lit_as_a_build(what, &mut live, &mut fresh); + } +} + /// A material that becomes a cutout, or stops being one, in place: the instances with a row of it say so (a mesh, a /// mesh of several materials, an instanced object's copies), and the picture is a build's. In a scene without a /// cutout the kernel has no alpha test: the first one is a rebuild's. A material created after the build, of any