diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index daf3b28..a27dd4e 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -2776,6 +2776,31 @@ in-place tests' world, rows given back; two models in a shared pose posed again (tests/render/data/arm.glb, a skinned strip of two materials); `geometry/emitter-model-live` (a model's emitting section that is not its first, the model a unit under software traversal). +**A posed rigid model is edited in place (2026-11-20).** As a mesh and a still model are. Hidden, its parts are +instances no ray sees, their emitters at no weight, and it is posed and moved on; shown, it is placed where it +stands (`show_meshes`, `repose_rigid`). Removed, its instances are no object's (`edit_geometry`). One the scene has +is placed again as an instance of each of its parts' meshes (`Retained::rigid_meshes`), a part a record of the room, +in a run. Its pose update goes through what is above the instances under either traversal (the TLAS, +or the units' top tree): under software traversal a new pose or a move was a rebuild's. +An edit places an instance by one function now (`place_instance`: its rows, its emitters, its record, its place +above the triangles), for a mesh, a still model and a rigid model's part alike. With it a still model whose mesh +emits is placed again in place, where that was a rebuild's. +Its parts are the nodes any clip of the file moves, not those of the clip it plays (`skin::Model::moving_nodes`), +and the nodes its pose names: another clip is posed in place. Until now the parts were the playing clip's, and a +model given another clip, or a pose that named another node, was posed in place with the wrong parts (the nodes +the new pose moves stayed in the part merged for the old one). A pose that names other nodes is a rebuild's +(`RigidModel::pose`). +Still a rebuild: one with triangles flattened beside its parts (`flatten_coincident`'s) hidden, removed or placed +again; a pose that names other nodes than the last; a model hidden when the scene was built, shown; a skinned model +added, hidden or removed; a model the scene has not, added. +Measured, software traversal, an interior of 7,300 nodes whose clip plays (4,181 units): every frame rebuilt the +scene, 2.9 s a frame; now none does, a frame's commit is 1.2 ms and the frame 19 ms (1280 x 720 at half scale). +Tests, natively and under software traversal, each against a build's light list and picture: a posed rigid model +hidden, posed and moved while hidden, shown, removed; a still and a posed rigid model with emitters placed again, +the latter then posed, moved, hidden, shown and removed, its records and rows the room's again and the next one's; +one with flattened triangles hidden and removed by a rebuild; one given another clip of its file, in place +(`tests/render/data/two-clips.glb`); one whose pose names a node no clip moves, by a rebuild. + **A posed rigid model is its parts' instances (2026-11-20).** A model posed by a clip that moves nodes, without skins, was built in two ways at once: the nodes the clip leaves alone flattened into world-space triangles a placement, each node it moves an instance of a mesh made a placement. Now the model is parts (`scene::RigidModel`), diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md index f0dd3e1..802ce6a 100644 --- a/docs/RUNTIME.md +++ b/docs/RUNTIME.md @@ -1193,9 +1193,9 @@ its BLASes, or the units), so the engine's path is the same under both traversal | a mesh is removed | its record cleared, its tree given back and filled, the top tree | The scene is rebuilt, as before this step, by: the first instanced mesh of a scene that has none (its kernel has no -unit walk: one rebuild, as hardware traversal's first instance is); an edit of a procedural object; a posed model's -pose (its triangles are in the still tree) and a rigid group's (its parts are units, placed again by a rebuild -still); an instance of a mesh that deforms; **room that is +unit walk: one rebuild, as hardware traversal's first instance is); an edit of a procedural object; a skinned +model's pose (its triangles are in the still tree; a rigid group's parts are units, posed in place); an instance of +a mesh that deforms; **room that is full** (the edit room and the tree ranges are sized at the build, a quarter of the scene and at least 65,536 triangles and 1,024 records, and do not grow under software traversal: under hardware traversal they do; what an edit replaces stays behind until the next rebuild, under both; a scene with units and no geometry of its own to @@ -1407,7 +1407,7 @@ guard's 1.2 ms there is not its form). In Chrome (`tools/web-hello.ts --frames`) | `instancing` (1,000, all moving) | 3.39 / 7.89; flat rebuilds the scene every frame (276 ms of CPU a frame; units 6.5) | offline at one instant, 64 spp: ΔE 0.37, SSIM 0.995 | | `bistro` (1 unit of 2.83 M triangles) | 23.1 / 22.2 | ΔE 0.69, SSIM 0.990 | | `zero-day` (1 unit of 5.87 M) | 14.5 / 12.8 | ΔE 1.20, SSIM 0.963: the scene's own spread, see below | -| `zero-day-animated` (3,991) | every frame rebuilds the scene (2.6 s), with units as flat: a rigid group's pose, as before step 7b | – | +| `zero-day-animated` (4,181) | posed in place since 2026-11-20: 16.3 ms at 1280 × 720, half scale, a frame's commit 1.2 ms (before: every frame rebuilt the scene, 2.9 s) | – | `zero-day`'s picture: two runs of the flat kernel are ΔE 0.11 apart, so units' 1.20 is not noise of one kernel. Offline at 1,024 spp the three traversals are as far from one another: units against flat ΔE 0.97, hardware diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.ts index 7122a14..b2d65ec 100644 --- a/packages/scene/src/core.ts +++ b/packages/scene/src/core.ts @@ -1253,7 +1253,8 @@ export interface AnimationPose { * Local transforms of nodes (joints) by name, over the clip's: 4 numbers, a rotation (quaternion x, y, z, w), or 7, * a translation (x, y, z, in the node's parent's space) and then the rotation. A skinned mesh follows its joints * (aim, look, procedural steps). Each model posed this way is skinned on its own; set a new object (or change these - * numbers and set it again) for a new pose. + * numbers and set it again) for a new pose. A model without skins is drawn in parts by the nodes that move: name the + * same nodes in every pose (one that names others rebuilds the scene). */ nodes?: Record>; } diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs index a836960..207d5ab 100644 --- a/renderer/src/live/edits.rs +++ b/renderer/src/live/edits.rs @@ -209,12 +209,99 @@ impl Holes { } } -/// What an edit places at an object's record: a procedural object with its BLAS (hardware traversal), or an instance -/// of a mesh. +/// What an edit places for an object: a procedural object with its BLAS (hardware traversal) and its record, an +/// instance of a mesh, or a posed rigid model's parts. pub(super) enum Placed { - Proc(wgpu::Blas, scene::ProcObject), + Proc(wgpu::Blas, scene::ProcObject, scene::GpuInstance), /// An instance and its rows (its mesh's sections' materials, classes and emitters). Mesh(scene::Instance, Vec), + /// A part: its node (`scene::STILL_NODES`: those its clip leaves alone), its instance and its rows. Their records + /// follow each other. + Parts(Vec<(usize, scene::Instance, Vec)>), +} + +/// What `place_instance` writes to. +pub(super) struct Placing<'a, 'b> { + edit: &'a mut EditState, + grow: &'a Grow<'a>, + words: &'a mut Heap, + tables: &'a mut tables::Tables, + instances: &'a mut Vec, + gpu_instances: &'a mut Vec, + meshes: &'a [scene::InstMesh], + sections: &'a [scene::Section], + rows: &'a mut Vec, + pool_tris: &'a [[glam::Vec3A; 3]], + pool_place: &'a [[u32; 2]], + w_rows: &'a mut Gather, + w_records: &'a mut Gather, + new_emitters: &'a mut Vec<(u32, crate::GpuEmitterTri)>, + emitters_changed: &'a mut bool, + top: &'a mut gpu::Top<'b>, + inst_base: usize, +} + +/// An instance placed at `record` by an edit: its rows in the room, each with where its section's triangles start; +/// its emitters, if a section's material emits (`moves`: as moving ones); its kernel record; its place above the +/// triangles; its value where the build's are (`instances[record]`). +pub(super) fn place_instance(cx: &mut Placing, record: usize, inst: &mut scene::Instance, mine: &mut [scene::Row], moves: bool) -> std::result::Result<(), String> { + let im = cx.meshes[inst.mesh as usize]; + let sects = im.sections(cx.sections); + for (s, row) in sects.iter().zip(mine.iter_mut()) { + row[1] = cx.edit.pool_first as u32 + im.first + s.first; + } + let row_at = rows_for(cx.edit, cx.grow, cx.words, cx.instances, cx.meshes, record, mine.len())?; + inst.rows = row_at as u32; + // Its sections whose material emits: its emitters, a run of the light list, a section after another. The run its + // record had, if that has as many and none is the light tree's (those keep their place there, at no weight); else + // a new one at the list's end. A section's start goes in its row. + let n = scene::rows_emitters(sects, mine, &cx.tables.materials) as usize; + if n > 0 { + let starts = scene::section_emitters(sects, mine, &cx.tables.materials); + let old = emitter_run(&cx.tables.emitter_tris, cx.instances, record as u32); + let first = if old.len() == n && cx.tables.emitter_tris[old.clone()].iter().all(|e| !e.in_tree) { old.start } else { cx.tables.emitter_tris.len() }; + inst.first_emitter = first as u32; + for (row, start) in mine.iter_mut().zip(&starts) { + row[2] = start.map_or(scene::NO_EMITTER, |x| first as u32 + x); + } + let (place, of) = (mesh_places(&im, cx.sections, cx.pool_place), mine.iter().map(scene::row_material).collect::>()); + let numbered = |j: usize| { + let (s, i) = place[j]; + starts.get(s as usize).copied().flatten().map(|x| ((x + i) as usize, of[s as usize])) + }; + let (a, b) = (im.first as usize, (im.first + im.count) as usize); + let made = crate::instance_emitters(inst, record as u32, &cx.pool_tris[a..b], (cx.edit.pool_first + a) as u32, &numbered, n, &cx.tables.materials, moves); + for (j, (e, w)) in made.into_iter().enumerate() { + cx.new_emitters.push(((first + j) as u32, crate::GpuEmitterTri::of(&e, w, 0))); + match cx.tables.emitter_tris.get_mut(first + j) { + Some(old) => *old = e, + None => cx.tables.emitter_tris.push(e), + } + } + for (&mat, start) in of.iter().zip(&starts) { + if start.is_some() { + cx.tables.emissive.insert(mat); + } + } + *cx.emitters_changed = true; + } + cx.w_rows.put((row_at * 16) as u64, bytemuck::cast_slice(mine)); + if cx.rows.len() < row_at + mine.len() { + cx.rows.resize(row_at + mine.len(), [0; 4]); + } + cx.rows[row_at..row_at + mine.len()].copy_from_slice(mine); + let gpu = cx.top.record(inst.gpu(cx.edit.pool_first as u32 + im.first), inst.mesh, inst.cast_shadow); + cx.w_records.put((record * std::mem::size_of::()) as u64, bytemuck::bytes_of(&gpu)); + if record >= cx.gpu_instances.len() { + cx.gpu_instances.resize(record + 1, scene::GpuInstance::default()); + } + cx.gpu_instances[record] = gpu; + cx.top.place(cx.inst_base + record, inst.mesh, inst.world, gpu::INSTANCE_BIT | record as u32, inst.cast_shadow, inst.hidden); + if cx.instances.len() <= record { + cx.instances.resize(record + 1, scene::Instance { name: String::new(), hidden: true, ..inst.clone() }); + } + cx.instances[record] = inst.clone(); + Ok(()) } /// Each of a mesh's pool triangles' section and its index in it: as they lie (a section after another), or, where a @@ -438,7 +525,7 @@ impl LiveCore { changes.lights.insert(id); true } - Some(crate::world::Kind::Mesh { .. } | crate::world::Kind::Model { animation: None, .. } | crate::world::Kind::Group) => self.show_meshes(world, id, &mut changes, &mut top), + Some(crate::world::Kind::Mesh { .. } | crate::world::Kind::Model { .. } | crate::world::Kind::Group) => self.show_meshes(world, id, &mut changes, &mut top), _ => false, }; if !done { @@ -922,17 +1009,18 @@ impl LiveCore { self.emitters_reweigh = true; } - /// An object shown or hidden by its `visible`, in place: the meshes and still models under it (itself, if it is one) each by its - /// instance's mask above the triangles, where no ray sees a hidden one, and its row's power (`Tables::apply`: a - /// hidden mesh's emitters at no weight). False where something under it is drawn another way, or a mesh is not - /// such an instance (the build flattened it, or an edit took it out while it was hidden): the caller rebuilds. + /// An object shown or hidden by its `visible`, in place: the meshes and models under it (itself, if it is one) + /// each by its instance's mask above the triangles (a posed rigid model's every part's), where no ray sees a + /// hidden one, and its row's power (`Tables::apply`: a hidden mesh's emitters at no weight). False where + /// something under it is drawn another way, or a mesh is not such an instance (the build flattened it, or an edit + /// took it out while it was hidden): the caller rebuilds. fn show_meshes(&mut self, world: &World, id: u32, changes: &mut crate::world::Changes, build: &mut gpu::TopBuild) -> bool { let children = world.children(); for k in world.subtree_with(id, &children) { match &world.objects[&k].kind { crate::world::Kind::Group | crate::world::Kind::Camera(_) => {} // (One this commit adds is placed as it is, shown or not: `edit_geometry`.) - crate::world::Kind::Mesh { .. } | crate::world::Kind::Model { animation: None, .. } if changes.added.contains(&k) => {} + crate::world::Kind::Mesh { .. } | crate::world::Kind::Model { .. } if changes.added.contains(&k) => {} crate::world::Kind::Mesh { .. } | crate::world::Kind::Model { animation: None, .. } => { let Some(r) = self.sc.tables.retained.instance(k).filter(|i| whole(i, &self.sc.instances, &self.sc.meshes)).map(|i| i.instance as usize) else { return false }; let Some(inst) = self.sc.instances.get_mut(r) else { return false }; @@ -952,6 +1040,29 @@ impl LiveCore { changes.powers.insert(k); self.weigh_run(r as u32); } + // A posed rigid model: every part's instance. Shown, it is placed where it stands and posed as it is + // now (`repose_rigid`, this commit: a move while it was hidden placed nothing). + crate::world::Kind::Model { .. } => { + let Some(records) = self.sc.tables.retained.rigid(k).filter(|r| r.rest.mats.is_empty()).map(|r| r.records()) else { return false }; + let unseen = !world.shown(k); + if records.iter().all(|&r| self.sc.instances.get(r as usize).is_some_and(|i| i.hidden == unseen)) { + continue; + } + let Some(mut top) = gpu::Top::of(&mut self.sc.up.accel, &mut self.sc.up.units) else { return false }; + for &r in &records { + let Some(inst) = self.sc.instances.get_mut(r as usize) else { return false }; + (inst.hidden, inst.masked) = (unseen, unseen); + top.moved(top.inst_base() + r as usize, inst.world, Some((inst.cast_shadow, unseen))); + } + build.instances = true; + changes.powers.insert(k); + for r in records { + self.weigh_run(r); + } + if !unseen { + changes.poses.insert(k); + } + } _ => return false, } } @@ -1592,11 +1703,24 @@ impl LiveCore { /// Posed rigid models (`scene::RigidModel`): each moving node's instance takes object x node transform from the clip /// (previous rows kept for motion vectors), the instance of the nodes left alone the object's where the object /// moved (its emitters moving ones from its first move, `emitters_start_moving`), and their flattened triangles - /// are re-transformed in place; the commit builds the dynamic BLASes (if they have such triangles) and the TLAS. - /// False when it cannot (no hardware RT, a model hidden or changed): the caller rebuilds. + /// are re-transformed in place; the commit builds the dynamic BLASes (if they have such triangles) and what is + /// above the instances (the TLAS, or software traversal's top tree over its units). A hidden model's parts are + /// placed as a shown one's, unseen. False when it cannot (software traversal without units, a part that is no + /// unit, or flattened triangles there; a pose that names other nodes; a model changed): the caller rebuilds. pub(super) fn repose_rigid(&mut self, world: &World, ids: &[u32], build: &mut gpu::TopBuild) -> Result { - if self.sc.up.accel.is_none() { - return Ok(false); + // (Nothing is changed unless all of it can be.) + { + let Some(top) = gpu::Top::of(&mut self.sc.up.accel, &mut self.sc.up.units) else { return Ok(false) }; + let (retained, instances) = (&self.sc.tables.retained, &self.sc.instances); + let placed = |id: &u32| retained.rigid(*id).is_some_and(|r| r.rest.finals.len() == r.rest.mats.len() && r.records().iter().all(|&i| instances.get(i as usize).is_some_and(|x| top.has_mesh(x.mesh)))); + // (A pose that names other nodes is other parts.) + let same_parts = |id: &u32| match world.objects.get(id).map(|o| &o.kind) { + Some(crate::world::Kind::Model { animation, .. }) => retained.rigid(*id).is_some_and(|r| animation.as_ref().map_or(String::new(), scene::rigid_pose_key) == r.pose), + _ => false, + }; + if !ids.iter().all(|id| placed(id) && same_parts(id)) { + return Ok(false); + } } let mut placements: Vec<(u32, glam::Mat4)> = vec![]; // (Object, where it stands now, and the instance of its nodes left alone if this is its first move.) @@ -1605,9 +1729,6 @@ impl LiveCore { for id in ids { let Some(o) = world.objects.get(id) else { return Ok(false) }; let crate::world::Kind::Model { uri, animation, .. } = &o.kind else { return Ok(false) }; - if !world.shown(*id) { - return Ok(false); - } let globals = scene::model_gltf(uri, &self.assets)?.node_globals(animation.as_ref())?; let m = world.world_matrix(*id); let r = self.sc.tables.retained.rigid(*id).expect("a rigid model (`commit`)"); @@ -1619,9 +1740,6 @@ impl LiveCore { worlds.push((*id, m, r.still.filter(|_| !r.still_moves))); } let d = &r.rest; - if d.finals.len() != d.mats.len() { - return Ok(false); - } let (first, verts, attrs, blas) = &mut self.sc.dynamic; for (j, (node, p, n, uv, tg)) in r.rest_local.iter().enumerate() { let (pw, nw, uvw, tw) = scene::placed_tri(scene::RigidModel::part_world(m, *node, &globals), p, n, uv, *tg); @@ -1647,27 +1765,26 @@ impl LiveCore { self.emitters_start_moving(still, to); } } - // The instances: rows, previous rows (motion vectors), TLAS transforms. + // The instances: rows, previous rows (motion vectors), and their places above the triangles (TLAS transforms, + // or software traversal's units). let size = std::mem::size_of::() as u64; - let accel = self.sc.up.accel.as_mut().unwrap(); let (mut ilo, mut ihi) = (usize::MAX, 0usize); - for &(i, w) in &placements { - let inst = &mut self.sc.instances[i as usize]; - let old = self.sc.gpu_instances[i as usize]; - // (A node its clip scales to nothing: at a point, where no ray sees it.) - let (w, gone) = scene::placed_world(w, inst.world.w_axis.truncate()); - inst.world = w; - let mut r = inst.gpu(old.info[0]); - r.p = old.m; - self.sc.gpu_instances[i as usize] = r; - (ilo, ihi) = (ilo.min(i as usize), ihi.max(i as usize + 1)); - let row = |k: usize| [w.x_axis[k], w.y_axis[k], w.z_axis[k], w.w_axis[k]]; - if let Some(t) = accel.tlas[accel.inst_base + i as usize].as_mut() { - t.transform = [row(0), row(1), row(2)].concat().try_into().unwrap(); - t.mask = gpu::instance_mask(inst.cast_shadow, gone || inst.hidden); + { + let mut top = gpu::Top::of(&mut self.sc.up.accel, &mut self.sc.up.units).expect("checked above"); + for &(i, w) in &placements { + let inst = &mut self.sc.instances[i as usize]; + let old = self.sc.gpu_instances[i as usize]; + // (A node its clip scales to nothing: at a point, where no ray sees it.) + let (w, gone) = scene::placed_world(w, inst.world.w_axis.truncate()); + inst.world = w; + let mut r = top.record(inst.gpu(old.info[0]), inst.mesh, inst.cast_shadow); + r.p = old.m; + self.sc.gpu_instances[i as usize] = r; + (ilo, ihi) = (ilo.min(i as usize), ihi.max(i as usize + 1)); + top.moved(top.inst_base() + i as usize, w, Some((inst.cast_shadow, gone || inst.hidden))); + // (Rigid models' instances are theirs alone: no other update this commit placed them.) + self.inst_moving.push(i); } - // (Rigid models' instances are theirs alone: no other update this commit placed them.) - self.inst_moving.push(i); } if lo < hi { self.emitters_moved = true; @@ -2078,6 +2195,34 @@ impl LiveCore { tables.retained.proxies.remove(id); continue; } + // A posed rigid model: its parts' instances out, as an instance is; what an edit placed goes back to the + // room. (One with triangles flattened beside them is the build's to take out.) + if let Some(r) = tables.retained.rigid(*id) { + if !r.rest.mats.is_empty() { + return Err("an object the build placed otherwise (a model in parts, something it flattened) removed".into()); + } + for rec in r.records() { + let rec = rec as usize; + top.clear(inst_base + rec); + let run = emitter_run(&tables.emitter_tris, instances, rec as u32); + emitters_changed |= !run.is_empty(); + tables.emitter_tris[run].iter_mut().for_each(|e| e.area = 0.0); + if let Some(i) = instances.get_mut(rec) { + (i.hidden, i.masked) = (true, false); + if edit.in_room(rec) { + drop_mesh_user(i.mesh, edit, tables, meshes); + } + } + if edit.in_room(rec) { + edit.records.give(rec, 1); + edit.give_rows(rec); + } + } + if let Some(k) = tables.retained.proxies.remove(id).and_then(|p| p.object).filter(|&k| k as usize >= edit.base.2) { + edit.objects.give(k as usize, 1); + } + continue; + } emitters_changed |= release(*id, tables, instances); // (A still model the build placed, whose instance is all of it, is taken out by it too.) let at = slot_of(*id, edit, tables).or_else(|| tables.retained.instance(*id).filter(|i| whole(i, instances, meshes)).map(|i| (inst_base + i.instance as usize, i.instance as usize))); @@ -2154,7 +2299,7 @@ impl LiveCore { None => return Err("edit room: objects (particles, or the device's limits)".into()), }, }; - let (record, gpu, blas, entry) = match &o.kind { + let (record, blas, entry) = match &o.kind { Kind::Procedural { .. } => { // (Software traversal walks procedural objects by their count and their own trees in the region: // the build lays those out.) @@ -2208,42 +2353,66 @@ impl LiveCore { let blas = g.proc_blas(&p.blob, &mut pending_procs); let entry = p.object_entry(o); let gpu = p.gpu(header as u32); - (at.map(|(_, r)| r), gpu, Placed::Proc(blas, p), entry) + (at.map(|(_, r)| r), Placed::Proc(blas, p, gpu), entry) } Kind::Model { uri, nodes, animation, functions } => { - // A static model already in the scene: another instance of its mesh (one not in it brings materials - // and textures, which load with a rebuild). - if animation.is_some() { - return Err("an animated model".into()); - } + // A model already in the scene: another instance of its mesh, or of each of its parts' meshes if it + // is a posed rigid one (one not in the scene brings materials and textures, which load with a + // rebuild). if !functions.is_empty() { return Err("a model with material functions (its materials load with a rebuild)".into()); } if features & gpu::F_INST == 0 || m.determinant() == 0.0 || std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "0") { return Err("a model the build would flatten (no size, instancing off, or the scene's first instance)".into()); } - let mesh = *tables.retained.model_mesh.get(&(uri.clone(), nodes.clone())).ok_or("a model not in the scene (its materials and textures load with a rebuild)")?; - let im = meshes[mesh as usize]; - if !top.has_mesh(mesh) { - return Err("a model whose mesh is no unit (it deforms; software traversal flattens it)".into()); - } // (Shadow rays pass the glass among a caster's other sections under a kernel feature: a scene where // no instance of the model cast a shadow was built without it.) - let its = tables.retained.mesh_rows.get(&mesh).ok_or("a model's mesh without its rows")?; - if scene::rows_bits(its) & scene::INST_GLASS != 0 && scene::rows_cast(its, o.cast_shadow) && features & gpu::F_IGLASS == 0 { - return Err("the scene's first shadow caster with glass among its sections (kernel feature)".into()); - } - *edit.users.entry(mesh).or_default() += 1; - if let Some(k) = was { - drop_mesh_user(k, edit, tables, meshes); + let glass_caster = |its: &[scene::Row]| scene::rows_bits(its) & scene::INST_GLASS != 0 && scene::rows_cast(its, o.cast_shadow) && features & gpu::F_IGLASS == 0; + if let Some(a) = animation { + let parts = nodes.is_none().then(|| tables.retained.rigid_meshes.get(&(uri.clone(), scene::rigid_pose_key(a)))).flatten().ok_or("an animated model that is no rigid one of the scene's with this pose's nodes (its meshes are a build's to make)")?.clone(); + let globals = scene::model_gltf(uri, assets).and_then(|g| g.node_globals(Some(a))).map_err(|e| e.to_string())?; + let (mut lo, mut hi) = (glam::Vec3A::splat(f32::MAX), glam::Vec3A::splat(f32::MIN)); + let mut placed = vec![]; + for &(node, mesh) in &parts { + if !top.has_mesh(mesh) { + return Err("a model whose mesh is no unit (software traversal flattens it)".into()); + } + let mine = tables.retained.mesh_rows.get(&mesh).ok_or("a model's mesh without its rows")?.clone(); + if glass_caster(&mine) { + return Err("the scene's first shadow caster with glass among its sections (kernel feature)".into()); + } + // (A part without size, a node its clip scales to nothing: at a point, as the build has it.) + let (w_n, _) = scene::placed_world(scene::RigidModel::part_world(m, node, &globals), m.w_axis.truncate()); + let (plo, phi) = meshes[mesh as usize].placed_bounds(w_n); + (lo, hi) = (lo.min(plo), hi.max(phi)); + let inst = scene::Instance { mesh, world: w_n, object: object as u32, cast_shadow: scene::rows_cast(&mine, o.cast_shadow), name: o.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: scene::rows_bits(&mine) }; + placed.push((node, inst, mine)); + } + for &(_, mesh) in &parts { + *edit.users.entry(mesh).or_default() += 1; + } + let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), o.power, (hi - lo).max(glam::Vec3A::ZERO), o.custom, [1.0; 3]); + (None, Placed::Parts(placed), entry) + } else { + let mesh = *tables.retained.model_mesh.get(&(uri.clone(), nodes.clone())).ok_or("a model not in the scene (its materials and textures load with a rebuild)")?; + let im = meshes[mesh as usize]; + if !top.has_mesh(mesh) { + return Err("a model whose mesh is no unit (it deforms; software traversal flattens it)".into()); + } + // (Its rows, the mesh's own, are placed with its record below.) + let mine = tables.retained.mesh_rows.get(&mesh).ok_or("a model's mesh without its rows")?.clone(); + if glass_caster(&mine) { + return Err("the scene's first shadow caster with glass among its sections (kernel feature)".into()); + } + *edit.users.entry(mesh).or_default() += 1; + if let Some(k) = was { + drop_mesh_user(k, edit, tables, meshes); + } + let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: scene::rows_cast(&mine, o.cast_shadow), name: o.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: scene::rows_bits(&mine) }; + let (lo, hi) = im.placed_bounds(m); + let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, o.custom, [1.0; 3]); + (at.map(|(_, r)| r), Placed::Mesh(inst, mine), entry) } - // (Its rows, the mesh's own, are placed with its record below.) - let mine = tables.retained.mesh_rows.get(&mesh).ok_or("a model's mesh without its rows")?; - let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: scene::rows_cast(mine, o.cast_shadow), name: o.name.clone(), sub: None, hidden: false, masked: false, first_emitter: 0, rows: 0, bits: scene::rows_bits(mine) }; - let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first), mesh, inst.cast_shadow); - let (lo, hi) = im.placed_bounds(m); - let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), o.power, hi - lo, o.custom, [1.0; 3]); - (at.map(|(_, r)| r), gpu, Placed::Mesh(inst, mine.clone()), entry) } Kind::Mesh { .. } | Kind::Instanced { procedural: false, .. } => { // A mesh, or (added in place) an instanced mesh: their mesh made alike. A mesh with several @@ -2533,90 +2702,48 @@ impl LiveCore { return Err("the scene's first shadow caster with glass among its sections (kernel feature)".into()); } let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: scene::rows_cast(&mine, o.cast_shadow), name: o.name.clone(), sub: None, hidden: unseen, masked: unseen, first_emitter: 0, rows: 0, bits: scene::rows_bits(&mine) }; - let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first), mesh, inst.cast_shadow); let (lo, hi) = im.placed_bounds(m); let entry = scene::object_row(m.transform_point3(glam::Vec3::ZERO), if unseen { 0.0 } else { o.power }, hi - lo, o.custom, [1.0; 3]); - (at.map(|(_, r)| r), gpu, Placed::Mesh(inst, mine), entry) + (at.map(|(_, r)| r), Placed::Mesh(inst, mine), entry) } _ => return Err("not an object an edit places".into()), }; - // Its record, TLAS instance and object entry: where it had them, or new ones from the room. + // Its record (a posed rigid model's: a part each, in a run), TLAS instance and object entry: where it had + // them, or new ones from the room. + let n = match &blas { + Placed::Parts(parts) => parts.len(), + _ => 1, + }; let (slot, record) = match (at, record) { (Some((slot, _)), Some(r)) => (slot, r), _ => { - let r = match edit.records.take(1) { + let r = match edit.records.take(n) { Some(r) => r, - None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, 1, &mut up.heap, accel), gpu::Top::Sw(_) => false } => { + None if match &mut top { gpu::Top::Hw(accel) => grow.records(&mut edit.records, n, &mut up.heap, accel), gpu::Top::Sw(_) => false } => { edit.grows += 1; edit.rebind = true; - edit.records.take(1).ok_or("edit room: records")? + edit.records.take(n).ok_or("edit room: records")? } None => return Err(if matches!(top, gpu::Top::Sw(_)) { "edit room: records (software traversal's does not grow)" } else { "edit room: records (particles, or the device's limits)" }.into()), }; (inst_base + r, r) } }; - // An instance of a mesh that emits: its emitters, a run of the light list. The run its record had, if that - // has as many and none is the light tree's (those keep their place there, at no weight); else a new one at - // the list's end. Its first goes in its record. - let (mut gpu, mut blas) = (gpu, blas); - if let Placed::Mesh(inst, mine) = &mut blas { - let im = meshes[inst.mesh as usize]; - let sects = im.sections(sections); - // Its rows, each with where its section's triangles start. - for (s, row) in sects.iter().zip(mine.iter_mut()) { - row[1] = edit.pool_first as u32 + im.first + s.first; - } - let row_at = rows_for(edit, &grow, &mut up.words, instances, meshes, record, mine.len())?; - (inst.rows, gpu.info[3]) = (row_at as u32, row_at as u32); - // Its sections whose material emits: its emitters, a run of the light list, a section after another. - // The run its record had, if that has as many and none is the light tree's (those keep their place - // there, at no weight); else a new one at the list's end. A section's start goes in its row. - let n = scene::rows_emitters(sects, mine, &tables.materials) as usize; - if n > 0 { - let starts = scene::section_emitters(sects, mine, &tables.materials); - let old = emitter_run(&tables.emitter_tris, instances, record as u32); - let first = if old.len() == n && tables.emitter_tris[old.clone()].iter().all(|e| !e.in_tree) { old.start } else { tables.emitter_tris.len() }; - inst.first_emitter = first as u32; - for (row, start) in mine.iter_mut().zip(&starts) { - row[2] = start.map_or(scene::NO_EMITTER, |x| first as u32 + x); - } - let (place, of) = (mesh_places(&im, sections, pool_place), mine.iter().map(scene::row_material).collect::>()); - let numbered = |j: usize| { - let (s, i) = place[j]; - starts.get(s as usize).copied().flatten().map(|x| ((x + i) as usize, of[s as usize])) - }; - let (a, b) = (im.first as usize, (im.first + im.count) as usize); - let made = crate::instance_emitters(inst, record as u32, &pool_tris[a..b], (edit.pool_first + a) as u32, &numbered, n, &tables.materials, o.driven || world.movable(id)); - for (j, (e, w)) in made.into_iter().enumerate() { - new_emitters.push(((first + j) as u32, crate::GpuEmitterTri::of(&e, w, 0))); - match tables.emitter_tris.get_mut(first + j) { - Some(old) => *old = e, - None => tables.emitter_tris.push(e), - } - } - for (&mat, start) in of.iter().zip(&starts) { - if start.is_some() { - tables.emissive.insert(mat); - } - } - emitters_changed = true; - } - w_rows.put((row_at * 16) as u64, bytemuck::cast_slice(mine)); - if rows.len() < row_at + mine.len() { - rows.resize(row_at + mine.len(), [0; 4]); - } - rows[row_at..row_at + mine.len()].copy_from_slice(mine); - } - w_records.put((record * std::mem::size_of::()) as u64, bytemuck::bytes_of(&gpu)); - if record >= gpu_instances.len() { - gpu_instances.resize(record + 1, scene::GpuInstance::default()); - } - gpu_instances[record] = gpu; // Above the triangles, and the record's value where the build's are: `instances[record]`, or `procs` at the // record less the first procedural one (hidden fillers at the records between, which are other objects'). + // (A mesh a body drives moves as an instance does, as the build's: `commit`.) + let moves = o.driven || world.movable(id); + let mut place = |record: usize, inst: &mut scene::Instance, mine: &mut [scene::Row], moves: bool| { + let mut cx = Placing { edit: &mut *edit, grow: &grow, words: &mut up.words, tables: &mut *tables, instances: &mut *instances, gpu_instances: &mut *gpu_instances, meshes: &meshes[..], sections: §ions[..], rows: &mut *rows, pool_tris: &pool_tris[..], pool_place: &pool_place[..], w_rows: &mut w_rows, w_records: &mut w_records, new_emitters: &mut new_emitters, emitters_changed: &mut emitters_changed, top: &mut top, inst_base }; + place_instance(&mut cx, record, inst, mine, moves) + }; let draw = match blas { - Placed::Proc(blas, p) => { + Placed::Proc(blas, p, gpu) => { + w_records.put((record * std::mem::size_of::()) as u64, bytemuck::bytes_of(&gpu)); + if record >= gpu_instances.len() { + gpu_instances.resize(record + 1, scene::GpuInstance::default()); + } + gpu_instances[record] = gpu; top.place_blas(slot, &blas, m, record as u32, mask(o.cast_shadow)); let j = record - proc_first; if procs.len() <= j { @@ -2625,15 +2752,30 @@ impl LiveCore { procs[j] = p; scene::Draw::Procedural(j as u32) } - Placed::Mesh(inst, _) => { - top.place(slot, inst.mesh, m, gpu::INSTANCE_BIT | record as u32, inst.cast_shadow, inst.hidden); - if instances.len() <= record { - instances.resize(record + 1, scene::Instance { name: String::new(), hidden: true, ..inst.clone() }); - } + Placed::Mesh(mut inst, mut mine) => { + place(record, &mut inst, &mut mine, moves)?; let mesh = if matches!(o.kind, Kind::Model { .. }) { scene::MeshKind::Model } else { scene::MeshKind::Own }; - instances[record] = inst; - // (A mesh a body drives moves as an instance does, as the build's: `commit`.) - scene::Draw::Instance(scene::InstanceRef { instance: record as u32, mesh, moves: o.driven || world.movable(id) }) + scene::Draw::Instance(scene::InstanceRef { instance: record as u32, mesh, moves }) + } + // A posed rigid model: a part a record, the nodes a pose may move with moving emitters; where it + // stands as an update finds it (`repose_rigid` tells a move by that). + Placed::Parts(parts) => { + let pose = match &o.kind { + Kind::Model { animation: Some(a), .. } => scene::rigid_pose_key(a), + _ => String::new(), + }; + let mut rigid = scene::RigidModel { world: world.world_matrix(id), pose, ..Default::default() }; + // (Its row of the object table: where a new pose or a move writes its pivot.) + rigid.rest.object = object as u32; + for (j, (node, mut inst, mut mine)) in parts.into_iter().enumerate() { + place(record + j, &mut inst, &mut mine, node != scene::STILL_NODES)?; + if node == scene::STILL_NODES { + rigid.still = Some((record + j) as u32); + } else { + rigid.instances.push((node, (record + j) as u32)); + } + } + scene::Draw::Rigid(rigid) } }; let st = tables.stride; diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs index 3746923..7de22c4 100644 --- a/renderer/src/live/inplace_tests.rs +++ b/renderer/src/live/inplace_tests.rs @@ -117,6 +117,15 @@ fn forget(core: &mut LiveCore) { core.reset = true; } +/// Whether the rays see the instance at `record`: by its mask above the triangles, or its unit. +fn seen_by_rays(c: &LiveCore, record: u32) -> bool { + match (&c.sc.up.accel, &c.sc.up.units) { + (Some(a), _) => a.tlas[a.inst_base + record as usize].as_ref().is_some_and(|t| t.mask != 0), + (None, Some(u)) => u.slots.get(record as usize).copied().flatten().is_some_and(|x| !x.hidden), + _ => false, + } +} + /// Mean absolute difference of two pictures, in 8-bit steps. fn apart(a: &[u8], b: &[u8]) -> f64 { assert_eq!(a.len(), b.len()); @@ -2006,7 +2015,97 @@ fn a_material_turned_glass_stops_casting_its_shadow_in_place() { /// a node 5 m along x, a grey quad on a node the clip moves) is posed and moved in place: a new pose moves the /// node's instance alone; one moved takes the part left alone with it, whose emitters are moving ones from that /// first move (still ones, in the light tree, until then), movable object or not. Each time the light list is its -/// triangles and the picture a build's. +/// triangles and the picture a build's. Under software traversal too, where its parts are units. +/// A posed rigid model given another clip of its file, which moves another node (tests/render/data/two-clips.glb), is +/// posed in place: its parts are the nodes any clip moves, so they are the same ones. +#[test] +fn a_posed_rigid_model_given_another_clip_is_posed_in_place() { + 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 pose = |clip: &str, time| Some(crate::desc::Animation { clip: clip.into(), time, r#loop: true, nodes: Default::default() }); + let mut w = world(); + w.set_object(32, "posed".into(), None, Kind::Model { uri: "tests/render/data/two-clips.glb".into(), nodes: None, animation: pose("raise-left", 0.5), functions: vec![] }, true, false).unwrap(); + w.set_transform(32, Vec3::new(-0.2, 0.1, 0.6), glam::Quat::IDENTITY, Vec3::splat(0.12)).unwrap(); + let mut live = match open(&w) { + Ok(c) => c, + Err(e) => return eprintln!("skipped: {e}"), + }; + w.take_changes(); + let parts = |c: &LiveCore| { + let r = c.sc.tables.retained.rigid(32).expect("a posed rigid model"); + (r.instances.iter().map(|&(node, i)| (node, c.sc.instances[i as usize].world)).collect::>(), r.still.map(|i| c.sc.instances[i as usize].world)) + }; + let against_a_build = |what: &str, live: &mut LiveCore, w: &World| { + let mut fresh = open(w).unwrap(); + assert_eq!(parts(live), parts(&fresh), "{what}: its parts and where they stand, as a build's"); + forget(live); + let (a, b) = (picture(live, 48), picture(&mut fresh, 48)); + assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b)); + }; + let loaded = parts(&live); + let at = |p: &(Vec<(usize, glam::Mat4)>, Option), node: usize| p.0.iter().find(|q| q.0 == node).expect("the node's part").1; + assert_eq!((loaded.0.len(), loaded.1.is_some()), (2, true), "a part each node a clip moves, and the node none does"); + against_a_build("a posed rigid model, as loaded", &mut live, &w); + w.set_animation(32, pose("raise-right", 0.75)).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "another clip of the file: in place ({:?})", live.fallback); + let other = parts(&live); + assert!(at(&other, 1) != at(&loaded, 1) && at(&other, 2) != at(&loaded, 2) && other.1 == loaded.1, "the first clip's node is back where the file has it, the other's is raised, the third stays"); + against_a_build("another clip of the file", &mut live, &w); +} + +/// A pose that moves other nodes than the one its parts were made for (it names a node the clip leaves alone): the +/// parts are a build's to make again. In place the named node would stay where the part it is merged into stands. +#[test] +fn a_posed_rigid_model_whose_new_pose_moves_other_nodes_is_rebuilt() { + 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 pose = |time, nodes: &[(&str, [f32; 7])]| Some(crate::desc::Animation { clip: "slide".into(), time, r#loop: true, nodes: nodes.iter().map(|(n, v)| (n.to_string(), v.to_vec())).collect() }); + let model = |a| Kind::Model { uri: "tests/render/data/panel-slider.glb".into(), nodes: None, animation: a, functions: vec![] }; + let mut w = world(); + w.set_object(32, "posed".into(), None, model(pose(0.25, &[])), true, false).unwrap(); + w.set_transform(32, Vec3::new(-0.6, 0.2, 0.6), glam::Quat::IDENTITY, Vec3::splat(0.08)).unwrap(); + let mut live = match open(&w) { + Ok(c) => c, + Err(e) => return eprintln!("skipped: {e}"), + }; + w.take_changes(); + let against_a_build = |what: &str, live: &mut LiveCore, w: &World| { + list_is_its_triangles(what, live); + let mut fresh = open(w).unwrap(); + let parts = |c: &LiveCore| c.sc.tables.retained.rigid(32).map(|r| (r.instances.iter().map(|&(node, i)| (node, c.sc.instances[i as usize].world)).collect::>(), r.still.map(|i| c.sc.instances[i as usize].world))); + assert_eq!(parts(live), parts(&fresh), "{what}: its parts and where they stand, as a build's"); + forget(live); + let (a, b) = (picture(live, 48), picture(&mut fresh, 48)); + assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b)); + a + }; + let before = against_a_build("a posed rigid model, as loaded", &mut live, &w); + // The panel, a node the clip leaves alone, named by the pose: lifted and turned. + let lifted = [("panel", [2.0, 4.0, 0.0, 0.0, 0.0, 0.38268343, 0.92387953])]; + w.set_animation(32, pose(0.25, &lifted)).unwrap(); + assert!(live.commit(&mut w).unwrap(), "a pose that names a node the clip leaves alone: a rebuild"); + let named = against_a_build("a pose that names a node the clip leaves alone", &mut live, &w); + assert!(apart(&before, &named) > 0.5, "the named node's pose is in the picture ({:.2} steps)", apart(&before, &named)); + // The same nodes named, posed on: in place. + w.set_animation(32, pose(0.75, &[("panel", [3.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0])])).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "the same nodes posed on: in place ({:?})", live.fallback); + against_a_build("the same nodes posed on", &mut live, &w); + // Another placed with the same node named: the scene's parts, in place; posed on in place; named no more, a rebuild. + w.set_object(33, "second".into(), None, model(pose(0.5, &lifted)), true, false).unwrap(); + w.set_transform(33, Vec3::new(0.5, -0.4, 0.7), glam::Quat::IDENTITY, Vec3::splat(0.08)).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "another with the same node named: in place ({:?})", live.fallback); + w.set_animation(33, pose(0.9, &lifted)).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "it, posed on: in place ({:?})", live.fallback); + against_a_build("another with the same node named, posed on", &mut live, &w); + w.set_animation(33, pose(0.9, &[])).unwrap(); + assert!(live.commit(&mut w).unwrap(), "it, its node named no more: a rebuild"); + against_a_build("another, its node named no more", &mut live, &w); + // Named no more: a rebuild again. + w.set_animation(32, pose(0.75, &[])).unwrap(); + assert!(live.commit(&mut w).unwrap(), "a pose that names the node no more: a rebuild"); + against_a_build("a pose that names the node no more", &mut live, &w); +} + #[test] fn a_posed_rigid_model_is_posed_and_moved_in_place_with_the_nodes_its_clip_leaves_alone() { let presets = crate::default_presets_dir(); @@ -2020,8 +2119,7 @@ fn a_posed_rigid_model_is_posed_and_moved_in_place_with_the_nodes_its_clip_leave w.set_object(33, "movable".into(), None, model(0.25), true, true).unwrap(); w.set_transform(33, Vec3::new(0.2, -0.7, 0.6), glam::Quat::IDENTITY, size).unwrap(); let mut live = match open(&w) { - Ok(c) if c.g.hwrt => c, - Ok(_) => return eprintln!("skipped: no hardware RT"), + Ok(c) => c, Err(e) => return eprintln!("skipped: {e}"), }; w.take_changes(); @@ -2092,8 +2190,7 @@ fn a_posed_rigid_model_under_groups_is_not_moved_by_a_new_pose() { let local = |id: u32| w.objects[&id].local(); assert_ne!((local(50) * local(51)) * local(32), w.world_matrix(32), "the test's transforms: the two products differ"); let mut live = match open(&w) { - Ok(c) if c.g.hwrt => c, - Ok(_) => return eprintln!("skipped: no hardware RT"), + Ok(c) => c, Err(e) => return eprintln!("skipped: {e}"), }; w.take_changes(); @@ -2110,6 +2207,274 @@ fn a_posed_rigid_model_under_groups_is_not_moved_by_a_new_pose() { assert!(apart(&a, &b) < 0.5, "the picture is {:.2} steps from a build's", apart(&a, &b)); } +/// A posed rigid model is hidden, shown and removed in place, under either traversal. Hidden, its parts are +/// instances no ray sees, their emitters at no weight, and it is posed and moved on; shown, it stands where it was +/// moved to, as its clip has it now; removed, its instances are no object's. Each time the light list is its +/// triangles and the picture a build's. +#[test] +fn a_posed_rigid_model_is_hidden_shown_and_removed_in_place() { + 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 slide = |time| Some(crate::desc::Animation { clip: "slide".into(), time, r#loop: true, nodes: Default::default() }); + let model = |time| Kind::Model { uri: "tests/render/data/panel-slider.glb".into(), nodes: None, animation: slide(time), functions: vec![] }; + let size = Vec3::splat(0.08); + let mut w = world(); + w.set_object(32, "posed".into(), None, model(0.25), true, false).unwrap(); + w.set_transform(32, Vec3::new(-1.3, 0.6, 0.5), glam::Quat::IDENTITY, size).unwrap(); + w.set_object(33, "movable".into(), None, model(0.25), true, true).unwrap(); + w.set_transform(33, Vec3::new(0.2, -0.7, 0.6), glam::Quat::IDENTITY, size).unwrap(); + let mut live = match open(&w) { + Ok(c) => c, + Err(e) => return eprintln!("skipped: {e}"), + }; + w.take_changes(); + let records = |c: &LiveCore, id: u32| c.sc.tables.retained.rigid(id).expect("a posed rigid model").records(); + let (a, b) = (records(&live, 32), records(&live, 33)); + let seen = |c: &LiveCore, of: &[u32]| of.iter().map(|&i| (c.sc.instances[i as usize].hidden, c.sc.instances[i as usize].masked)).collect::>(); + let lit = |c: &LiveCore, of: &[u32]| c.sc.tables.emitter_tris.iter().filter(|e| of.contains(&e.inst) && crate::emitter_power(e, &c.sc.tables.materials, &c.sc.tables.objects, c.sc.tables.stride) > 0.0).count(); + let rays = |c: &LiveCore, of: &[u32]| of.iter().map(|&i| seen_by_rays(c, i)).collect::>(); + // (The panel's two triangles: 32 m2 each in the model, 0.08 x 0.08 of that as it is placed.) + let areas = |c: &LiveCore, of: &[u32]| c.sc.tables.emitter_tris.iter().filter(|e| of.contains(&e.inst) && e.area > 0.0).map(|e| (e.area * 1e4).round() / 1e4).collect::>(); + let against_a_build = |what: &str, live: &mut LiveCore, w: &World| { + list_is_its_triangles(what, live); + let mut fresh = open(w).unwrap(); + forget(live); + let (a, b) = (picture(live, 48), picture(&mut fresh, 48)); + assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b)); + a + }; + let before = against_a_build("posed rigid models, as loaded", &mut live, &w); + assert_eq!((lit(&live, &a), lit(&live, &b)), (2, 2), "each panel's two emitters weigh something"); + // Hidden: instances no ray sees, emitters at no weight. + w.set_visible(33, false).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "a posed rigid model hidden: in place ({:?})", live.fallback); + assert_eq!((seen(&live, &b), lit(&live, &b), seen(&live, &a), lit(&live, &a)), (vec![(true, true); 2], 0, vec![(false, false); 2], 2), "its parts are unseen, the other model's are not"); + assert_eq!((rays(&live, &b), rays(&live, &a)), (vec![false; 2], vec![true; 2]), "no ray sees its parts"); + assert_eq!((areas(&live, &b), areas(&live, &a)), (vec![32.0; 2], vec![0.2048; 2]), "an unseen instance's emitters have their mesh's own area, as a hidden mesh's"); + let hidden = against_a_build("a posed rigid model hidden", &mut live, &w); + assert!(apart(&before, &hidden) > 0.5, "it is gone from the picture ({:.2} steps)", apart(&before, &hidden)); + // Posed while hidden, then moved while hidden: nothing of it is drawn. + w.set_animation(33, slide(0.8)).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "posed while hidden: in place ({:?})", live.fallback); + assert_eq!(rays(&live, &b), vec![false; 2], "posed while hidden: no ray sees its parts"); + w.set_transform(33, Vec3::new(-0.5, -0.1, 0.9), glam::Quat::from_rotation_z(0.5), size).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "moved while hidden: in place ({:?})", live.fallback); + assert_eq!((seen(&live, &b), lit(&live, &b)), (vec![(true, true); 2], 0)); + let still = against_a_build("a hidden posed rigid model posed and moved", &mut live, &w); + assert!(apart(&hidden, &still) < 0.5, "nothing of it is in the picture ({:.2} steps)", apart(&hidden, &still)); + // Shown: where it was moved to, as its clip has it now. + w.set_visible(33, true).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "shown again: in place ({:?})", live.fallback); + assert_eq!((seen(&live, &b), lit(&live, &b)), (vec![(false, false); 2], 2), "its parts are seen, its emitters weigh something again"); + assert_eq!((rays(&live, &b), areas(&live, &b)), (vec![true; 2], vec![0.2048; 2]), "the rays see them, their emitters as they are placed"); + let shown = against_a_build("a posed rigid model shown where it was moved to while hidden", &mut live, &w); + assert!(apart(&hidden, &shown) > 0.5 && apart(&before, &shown) > 0.5, "it is in the picture, and not where it was ({:.2}, {:.2} steps)", apart(&hidden, &shown), apart(&before, &shown)); + // The one that is not movable, hidden and shown where it stands. + w.set_visible(32, false).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "the other hidden: in place ({:?})", live.fallback); + w.set_visible(32, true).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "the other shown: in place ({:?})", live.fallback); + let again = against_a_build("a posed rigid model hidden and shown where it stands", &mut live, &w); + assert!(apart(&shown, &again) < 0.5, "as before it was hidden ({:.2} steps)", apart(&shown, &again)); + // Removed: its instances are no object's, its emitters at no weight. + w.remove(33); + assert!(!live.commit(&mut w).unwrap(), "a posed rigid model removed: in place ({:?})", live.fallback); + assert!(live.sc.tables.retained.rigid(33).is_none() && seen(&live, &b) == vec![(true, false); 2] && lit(&live, &b) == 0, "its parts are no object's"); + let removed = against_a_build("a posed rigid model removed", &mut live, &w); + assert!(apart(&again, &removed) > 0.5, "it is gone from the picture ({:.2} steps)", apart(&again, &removed)); + assert_eq!(rays(&live, &b), vec![false; 2], "no ray sees what was its parts"); + // The other posed on after: its own parts alone. + w.set_animation(32, slide(0.6)).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "the other posed on: in place ({:?})", live.fallback); + against_a_build("the other model posed on after the removal", &mut live, &w); + // And removed, never having moved: the part its clip leaves alone goes with the node. + w.remove(32); + assert!(!live.commit(&mut w).unwrap(), "the one that never moved removed: in place ({:?})", live.fallback); + assert_eq!((rays(&live, &a), lit(&live, &a)), (vec![false; 2], 0), "no ray sees what was its parts, its emitters weigh nothing"); + against_a_build("a posed rigid model that never moved removed", &mut live, &w); +} + +/// A model the scene has is placed again in place, with its emitters: a still one (tests/render/data/panel.glb), and +/// a posed rigid one (panel-slider.glb), a part a record of the room in a run, each an instance of the mesh the +/// build's placement has. The one placed is then posed, moved, hidden, shown and removed as one a build placed; its +/// records and rows are the room's again, and the next one placed takes them. Each time the light list is its +/// triangles and the picture a build's. +#[test] +fn a_model_with_emitters_is_placed_again_in_place() { + 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 slide = |time| Some(crate::desc::Animation { clip: "slide".into(), time, r#loop: true, nodes: Default::default() }); + let still = || Kind::Model { uri: "tests/render/data/panel.glb".into(), nodes: None, animation: None, functions: vec![] }; + let posed = |time| Kind::Model { uri: "tests/render/data/panel-slider.glb".into(), nodes: None, animation: slide(time), functions: vec![] }; + let mut w = world(); + w.set_object(30, "still".into(), None, still(), true, false).unwrap(); + w.set_transform(30, Vec3::new(-1.4, 0.7, 0.4), glam::Quat::from_rotation_y(0.4), Vec3::splat(0.05)).unwrap(); + w.set_object(32, "posed".into(), None, posed(0.25), true, false).unwrap(); + w.set_transform(32, Vec3::new(-1.3, -0.6, 0.5), glam::Quat::IDENTITY, Vec3::splat(0.08)).unwrap(); + // (A mesh the scene says it edits: room for what is placed.) + w.set_object(28, "own".into(), None, Kind::Mesh { geometry: 3, material: 1, own_blas: true, materials: vec![] }, true, false).unwrap(); + w.set_transform(28, Vec3::new(1.4, -0.7, 0.4), glam::Quat::IDENTITY, Vec3::ONE).unwrap(); + let mut live = match open(&w) { + Ok(c) => c, + Err(e) => return eprintln!("skipped: {e}"), + }; + w.take_changes(); + let pictured = |what: &str, live: &mut LiveCore, w: &World| { + list_is_its_triangles(what, live); + let mut fresh = open(w).unwrap(); + forget(live); + let (a, b) = (picture(live, 48), picture(&mut fresh, 48)); + assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b)); + a + }; + let lit = |c: &LiveCore, of: &[u32]| c.sc.tables.emitter_tris.iter().filter(|e| of.contains(&e.inst) && crate::emitter_power(e, &c.sc.tables.materials, &c.sc.tables.objects, c.sc.tables.stride) > 0.0).count(); + let before = pictured("as loaded", &mut live, &w); + // The still model again. + w.set_object(31, "still again".into(), None, still(), true, false).unwrap(); + w.set_transform(31, Vec3::new(1.2, 0.7, 0.5), glam::Quat::from_rotation_y(-0.3), Vec3::splat(0.05)).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "a still model with emitters placed again: in place ({:?})", live.fallback); + let (first, again) = (*live.sc.tables.retained.instance(30).unwrap(), *live.sc.tables.retained.instance(31).expect("it is an instance")); + assert_eq!((live.sc.instances[again.instance as usize].mesh, lit(&live, &[again.instance])), (live.sc.instances[first.instance as usize].mesh, 2), "an instance of the model's mesh, its two emitters its own"); + list_is_its_triangles("a still model with emitters placed again", &live); + lit_as_a_build("a still model with emitters placed again", &mut live, &mut open(&w).unwrap()); + // The posed rigid model again, elsewhere in its clip. + let place = |w: &mut World, id: u32, time: f32, at: Vec3| { + w.set_object(id, format!("posed{id}"), None, posed(time), true, false).unwrap(); + w.set_transform(id, at, glam::Quat::from_rotation_z(0.3), Vec3::splat(0.08)).unwrap(); + }; + // (One whose pose names a node moves other nodes: other parts, a build's to make.) + let named = crate::desc::Animation { clip: "slide".into(), time: 0.75, r#loop: true, nodes: [("panel".to_string(), vec![0.0, 0.0, 0.0, 1.0])].into() }; + w.set_object(35, "named".into(), None, Kind::Model { uri: "tests/render/data/panel-slider.glb".into(), nodes: None, animation: Some(named), functions: vec![] }, true, false).unwrap(); + w.set_transform(35, Vec3::new(0.2, 0.3, 0.8), glam::Quat::from_rotation_z(0.3), Vec3::splat(0.08)).unwrap(); + assert!(live.commit(&mut w).unwrap(), "a model whose pose names a node the clip leaves alone: a rebuild"); + w.remove(35); + live.commit(&mut w).unwrap(); + place(&mut w, 33, 0.75, Vec3::new(0.2, 0.3, 0.8)); + assert!(!live.commit(&mut w).unwrap(), "a posed rigid model placed again: in place ({:?})", live.fallback); + let (built, r) = (live.sc.tables.retained.rigid(32).unwrap().clone(), live.sc.tables.retained.rigid(33).expect("a posed rigid model").clone()); + let (records, mesh) = (r.records(), |c: &LiveCore, i: u32| c.sc.instances[i as usize].mesh); + assert_eq!((r.instances.len(), mesh(&live, r.still.unwrap()), mesh(&live, r.instances[0].1)), (1, mesh(&live, built.still.unwrap()), mesh(&live, built.instances[0].1)), "its parts are instances of the meshes the build's placement has"); + let run: Vec = (0..2).map(|j| records.iter().min().unwrap() + j).collect(); + assert!(records.iter().all(|&i| live.sc.edit.in_room(i as usize) && run.contains(&i)), "a part a record of the room, in a run ({records:?})"); + assert_eq!((lit(&live, &[r.still.unwrap()]), r.moving()), (2, vec![r.instances[0].1]), "its panel's emitters are its own, still ones"); + assert!(live.sc.tables.emitter_tris.iter().filter(|e| e.inst == r.still.unwrap()).all(|e| !e.moves), "they are no moving emitters"); + list_is_its_triangles("a posed rigid model placed again", &live); + let mut fresh = open(&w).unwrap(); + // (Each part where a build places it: its node, and where its instance stands.) + let parts = |c: &LiveCore| { + let r = c.sc.tables.retained.rigid(33).unwrap(); + let mut of: Vec<(usize, Vec)> = r.instances.iter().map(|&(n, i)| (n, i)).chain(r.still.map(|i| (scene::STILL_NODES, i))).map(|(n, i)| (n, c.sc.instances[i as usize].world.to_cols_array().iter().map(|x| (x * 1e4).round() as i64).collect())).collect(); + of.sort(); + of + }; + assert_eq!(parts(&live), parts(&fresh), "each part stands where a build places it"); + assert!(records.iter().all(|&i| seen_by_rays(&live, i)), "the rays see its parts"); + lit_as_a_build("a posed rigid model placed again", &mut live, &mut fresh); + let placed = pictured("a posed rigid model placed again", &mut live, &w); + assert!(apart(&before, &placed) > 0.5, "the models placed are in the picture ({:.2} steps)", apart(&before, &placed)); + // Posed on, moved, hidden and shown, as one the build placed. + w.set_animation(33, slide(0.4)).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "the one placed posed on: in place ({:?})", live.fallback); + assert!(!live.sc.tables.retained.rigid(33).unwrap().still_moves, "a new pose is no move: its panel stays, its emitters still ones"); + pictured("the one placed posed on", &mut live, &w); + w.set_transform(33, Vec3::new(-0.3, 0.1, 1.0), glam::Quat::from_rotation_z(-0.4), Vec3::splat(0.08)).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "the one placed moved: in place ({:?})", live.fallback); + // (Every model's row of the object table as a build's: the moved one's pivot in its own row, no other's touched. + // Its world bounds' size apart: a move in place keeps the size the object was placed with, for every kind.) + let object_rows = |c: &LiveCore| { + let st = c.sc.tables.stride; + [30u32, 31, 32, 33].map(|id| { + c.sc.tables.retained.proxies[&id].object.map(|o| { + let mut row = c.sc.tables.objects[o as usize * st..(o as usize + 1) * st].to_vec(); + row[1] = [0.0; 4]; + row + }) + }) + }; + assert_eq!(object_rows(&live), object_rows(&open(&w).unwrap()), "the one placed moved: each model's row of the object table, as a build's"); + let moved = pictured("the one placed moved", &mut live, &w); + assert!(apart(&placed, &moved) > 0.5, "the move is in the picture ({:.2} steps)", apart(&placed, &moved)); + w.set_visible(33, false).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "the one placed hidden: in place ({:?})", live.fallback); + pictured("the one placed hidden", &mut live, &w); + w.set_visible(33, true).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "the one placed shown: in place ({:?})", live.fallback); + let shown = pictured("the one placed shown", &mut live, &w); + assert!(apart(&moved, &shown) < 0.5, "as before it was hidden ({:.2} steps)", apart(&moved, &shown)); + // Removed: its records and rows are the room's again, and the next one placed takes the records. + let rows: Vec<(u32, u32)> = records.iter().map(|&i| (live.sc.instances[i as usize].rows, live.sc.meshes[live.sc.instances[i as usize].mesh as usize].sect_count)).collect(); + w.remove(33); + assert!(!live.commit(&mut w).unwrap(), "the one placed removed: in place ({:?})", live.fallback); + assert!(rows.iter().all(|&(at, n)| rows_free(&live, at, n)) && lit(&live, &records) == 0, "its rows are the room's again, its emitters weigh nothing"); + pictured("the one placed removed", &mut live, &w); + // (Made visible in the commit that adds it: placed as it is, by the edit that places it.) + place(&mut w, 34, 0.5, Vec3::new(0.4, -0.2, 0.9)); + w.set_visible(34, false).unwrap(); + w.set_visible(34, true).unwrap(); + assert!(!live.commit(&mut w).unwrap(), "another placed after: in place ({:?})", live.fallback); + let mut next = live.sc.tables.retained.rigid(34).unwrap().records(); + next.sort_unstable(); + assert_eq!(next, run, "it takes the records the first gave back"); + list_is_its_triangles("another posed rigid model placed after one was removed", &live); + lit_as_a_build("another posed rigid model placed after one was removed", &mut live, &mut open(&w).unwrap()); +} + +/// A posed rigid model with triangles flattened beside its parts (tests/render/data/panel-decal.glb: a cutout on +/// exactly an emitter's vertices leaves the mesh with it) is hidden, and removed, by a rebuild: an instance's mask +/// hides no world-space triangle. The picture is a build's. +#[test] +fn a_posed_rigid_model_with_flattened_triangles_is_hidden_and_removed_by_a_rebuild() { + 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 model = || Kind::Model { uri: "tests/render/data/panel-decal.glb".into(), nodes: None, animation: Some(crate::desc::Animation { clip: "slide".into(), time: 0.25, r#loop: true, nodes: Default::default() }), functions: vec![] }; + let scene = || { + let mut w = world(); + w.set_object(32, "posed".into(), None, model(), true, false).unwrap(); + w.set_transform(32, Vec3::new(-0.4, 0.3, 0.6), glam::Quat::IDENTITY, Vec3::splat(0.08)).unwrap(); + w + }; + let pictured = |what: &str, live: &mut LiveCore, w: &World| { + let mut fresh = open(w).unwrap(); + forget(live); + let (a, b) = (picture(live, 48), picture(&mut fresh, 48)); + assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b)); + a + }; + let mut w = scene(); + let mut live = match open(&w) { + Ok(c) if c.g.hwrt => c, + Ok(_) => return eprintln!("skipped: no hardware RT"), + Err(e) => return eprintln!("skipped: {e}"), + }; + w.take_changes(); + assert!(!live.sc.tables.retained.rigid(32).expect("a posed rigid model").rest.mats.is_empty(), "the model has triangles flattened beside its part"); + let before = picture(&mut live, 48); + w.set_visible(32, false).unwrap(); + assert!(live.commit(&mut w).unwrap(), "hidden: a rebuild"); + let hidden = pictured("a posed rigid model with flattened triangles hidden", &mut live, &w); + assert!(apart(&before, &hidden) > 0.5, "it is gone from the picture ({:.2} steps)", apart(&before, &hidden)); + let mut w = scene(); + let mut live = open(&w).unwrap(); + w.take_changes(); + w.remove(32); + assert!(live.commit(&mut w).unwrap(), "removed: a rebuild"); + let removed = pictured("a posed rigid model with flattened triangles removed", &mut live, &w); + assert!(apart(&hidden, &removed) < 0.5, "as when it was hidden ({:.2} steps)", apart(&hidden, &removed)); + // Placed again: what is flattened beside its part is a build's to make. + let mut w = scene(); + // (A mesh the scene says it edits: room for what is placed.) + w.set_object(28, "own".into(), None, Kind::Mesh { geometry: 3, material: 1, own_blas: true, materials: vec![] }, true, false).unwrap(); + w.set_transform(28, Vec3::new(1.4, -0.7, 0.4), glam::Quat::IDENTITY, Vec3::ONE).unwrap(); + let mut live = open(&w).unwrap(); + w.take_changes(); + let one = picture(&mut live, 48); + w.set_object(33, "again".into(), None, model(), true, false).unwrap(); + w.set_transform(33, Vec3::new(0.6, -0.4, 0.8), glam::Quat::IDENTITY, Vec3::splat(0.08)).unwrap(); + assert!(live.commit(&mut w).unwrap(), "placed again: a rebuild"); + let two = pictured("a posed rigid model with flattened triangles placed again", &mut live, &w); + assert!(apart(&one, &two) > 0.5, "the second is in the picture ({:.2} steps)", apart(&one, &two)); +} + /// Models in a shared pose posed again in place (tests/render/data/arm.glb: a skinned strip, a dark half and a light /// half that a joint swings): their mesh is skinned where it lies, each triangle still in its section. The picture is /// a build's. diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs index 615288f..4622d0c 100644 --- a/renderer/src/scene.rs +++ b/renderer/src/scene.rs @@ -753,6 +753,9 @@ pub struct Retained { /// Static models' instanced meshes by (uri, nodes), those with nothing flattened per placement: a model added in /// place is another instance of one (live/edits.rs `edit_geometry`). pub model_mesh: HashMap<(String, Option>), u32>, + /// Posed rigid models' parts by (uri, `rigid_pose_key`), each its node (`STILL_NODES`) and its mesh, where every + /// part is a mesh with nothing flattened beside: one added in place is an instance of each. + pub rigid_meshes: HashMap<(String, String), Vec<(usize, u32)>>, /// A model's mesh's rows as every instance of it has them (the file's materials, `model_sections`; where a /// section's triangles and emitters are is each instance's to fill). pub mesh_rows: HashMap>, @@ -896,15 +899,16 @@ pub struct InstancedPlace { pub drawn: u32, } -/// A posed glTF model without skins whose clip moves some of its nodes (Zero Day's 551 moving objects), in parts -/// (`RigidPart`), each an instance of a mesh every placement of the model shares: the nodes the clip leaves alone -/// merged into one mesh in the model's space, placed by the object's transform; each node it moves a mesh in the -/// node's space, placed at object x node transform, so a new pose moves instances only (a part's emitters are its +/// A posed glTF model without skins whose clips move some of its nodes (Zero Day's 551 moving objects), in parts +/// (`RigidPart`), each an instance of a mesh every placement of the model shares: the nodes no clip of the file +/// moves and the pose does not name merged into one mesh in the model's space, placed by the object's transform; +/// each other node a mesh in the node's space, placed at object x node transform, so a new pose, of whichever clip, +/// moves instances only (a part's emitters are its /// instance's in the light list, filled again when it moves). What `flatten_coincident` takes out of a part's mesh /// is flattened: `rest`, re-transformed in place from `rest_local`. #[derive(Clone, Default)] pub struct RigidModel { - /// (glTF node, instance index): the nodes the clip moves. + /// (glTF node, instance index): the nodes a pose may move. pub instances: Vec<(usize, u32)>, /// The instance of the nodes it leaves alone, if any is drawn. It moves with the object alone; its emitters are /// still ones until the object first moves (`still_moves`: live/edits.rs `repose_rigid`). @@ -917,11 +921,19 @@ pub struct RigidModel { /// Per `rest` triangle: its node (`STILL_NODES`: the model's own space) and its triangle there (positions, /// normals, uvs, tangent). pub rest_local: Vec<(usize, [Vec3; 3], [Vec3; 3], [Vec2; 3], Option<(Vec3, f32)>)>, + /// `rigid_pose_key` of the pose its parts were made for: a pose with another is other parts (a build's to make). + pub pose: String, } -/// In place of a node: the nodes a rigid model's clip leaves alone, merged (their space is the model's). +/// In place of a node: the nodes no pose of a rigid model moves, merged (their space is the model's). pub const STILL_NODES: usize = usize::MAX; +/// What a rigid model's parts go by, beside the model: the nodes its pose names (`skin::Model::moving_nodes`: they +/// are parts with the nodes the file's clips move, whichever clip plays). +pub fn rigid_pose_key(a: &desc::Animation) -> String { + a.nodes.keys().cloned().collect::>().join("\u{0}") +} + impl RigidModel { /// The records of all its instances. pub fn records(&self) -> Vec { @@ -1747,8 +1759,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se if instancing && posed && nodes.is_none() && glb.rigid() { let a = animation.as_ref().unwrap(); let globals = glb.node_globals(Some(a))?; - // (What moves is the clip's nodes and the nodes the pose names.) - let pkey = (key.clone(), format!("{}\u{0}{}", a.clip, a.nodes.keys().cloned().collect::>().join("\u{0}"))); + let pkey = (key.clone(), rigid_pose_key(a)); if !rigid_parts.contains_key(&pkey) { let moving = glb.moving_nodes(a)?; // (THREERT_RIGID_NODES=all: no node merged, every one an instance of a mesh of its own: the A/B @@ -1800,6 +1811,10 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se let (merged, rest) = (lists.iter().filter(|l| l.0 == STILL_NODES).map(|l| l.1.len()).sum::(), parts.iter().map(|p| p.rest.len()).sum::()); eprintln!("rigid: {uri} ({}): {merged} triangles of the nodes left alone in one mesh, {} nodes apart, {rest} triangles flattened a placement", a.clip, lists.iter().filter(|l| l.0 != STILL_NODES).count()); } + // (What an edit can place again: every part a mesh whole in the pool, the file's own materials.) + if functions.is_empty() && parts.iter().all(|p| p.mesh.is_some() && p.rest.is_empty()) { + retained.rigid_meshes.insert((uri.clone(), rigid_pose_key(a)), parts.iter().filter_map(|p| Some((p.node, p.mesh?))).collect()); + } rigid_parts.insert(pkey.clone(), std::rc::Rc::new(parts)); } let parts = rigid_parts[&pkey].clone(); @@ -1808,7 +1823,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se let (mut olo, mut ohi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN)); // (Where the object stands as an update finds it, `World::world_matrix`: the same product as `m`, // multiplied in another order, so not always the same bits.) - let mut rigid = RigidModel { world: w.world_matrix(*id), ..Default::default() }; + let mut rigid = RigidModel { world: w.world_matrix(*id), pose: rigid_pose_key(a), ..Default::default() }; rigid.rest.first = tris.len() as u32; rigid.rest.object = oi; for part in parts.iter() { @@ -1958,9 +1973,8 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se if std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "log") { eprintln!("instancing: {uri} {nodes:?}: {} opaque, {} cutout, {} glass instanced; {} flattened per placement", classed[0].len(), classed[1].len(), classed[2].len(), classed[FLAT].len()); } - // (What an edit can place another instance of: a mesh whole in the pool. One with emitters is - // not: an edit does not make a model's instance its emitters yet.) - if let Some(k) = k.filter(|&k| meshes[k as usize].rest_count == 0 && pool_emitters(&classed, &emitting) == 0) { + // (What an edit can place another instance of: a mesh whole in the pool.) + if let Some(k) = k.filter(|&k| meshes[k as usize].rest_count == 0) { retained.model_mesh.insert(key.clone(), k); } mesh_of.insert(key, k); @@ -2426,11 +2440,6 @@ fn flatten_coincident(classed: &mut [Vec<(usize, u32)>; 4], emitting: &std::coll } } -/// The emitting triangles a mesh keeps (`InstMesh::emitters`): those of `classed` that stay in the pool. -fn pool_emitters(classed: &[Vec<(usize, u32)>; 4], emitting: &std::collections::HashSet) -> u32 { - classed[..FLAT].iter().flatten().filter(|(_, mat)| emitting.contains(mat)).count() as u32 -} - /// Whether a material created since the build can be drawn in place (tables.rs `add_materials`): 0 only when it is /// opaque, does not emit and is no glass (the build sorts triangles and lights by those). pub fn material_class(g: &GpuMaterial) -> u32 { diff --git a/renderer/src/skin.rs b/renderer/src/skin.rs index db7e3f3..2ce72f5 100644 --- a/renderer/src/skin.rs +++ b/renderer/src/skin.rs @@ -224,12 +224,16 @@ impl Model { self.prims.iter().all(|p| p.skin.is_none()) } - /// Per node: whether the pose moves it (a channel of its clip or a node it poses is it or one of its ancestors). + /// Per node: whether a pose may move it (a channel of any clip of the file, or a node this pose names, is it or one + /// of its ancestors). Any clip, not the pose's alone: the model is the same parts whichever clip it plays. pub fn moving_nodes(&self, pose: &desc::Animation) -> Result> { let mut direct = vec![false; self.parents.len()]; if !pose.clip.is_empty() { - for ch in &self.clip(&pose.clip)?.channels { - direct[ch.node] = true; + self.clip(&pose.clip)?; + } + for ch in self.gltf.0.animations().flat_map(|a| a.channels()) { + if ch.target().property() != gltf::animation::Property::MorphTargetWeights { + direct[ch.target().node().index()] = true; } } for name in pose.nodes.keys() { @@ -438,6 +442,18 @@ mod tests { assert!(m.node_triangles(Mat4::IDENTITY, None, &|_| true, true).unwrap().iter().all(|(_, t)| hand(t) == 1.0)); } + /// Which nodes are parts does not depend on the clip that plays (tests/render/data/two-clips.glb: a clip for the + /// node "left", another for "right", none for "base"). + #[test] + fn the_nodes_any_clip_moves_are_moving_whichever_plays() { + let m = Model::new(gltf::import("../tests/render/data/two-clips.glb").unwrap()).unwrap(); + let pose = |clip: &str| desc::Animation { clip: clip.into(), time: 0.5, r#loop: true, nodes: Default::default() }; + assert_eq!(m.moving_nodes(&pose("raise-left")).unwrap(), vec![false, true, true]); + assert_eq!(m.moving_nodes(&pose("raise-right")).unwrap(), vec![false, true, true]); + assert_eq!(m.moving_nodes(&pose("")).unwrap(), vec![false, true, true]); + assert!(m.moving_nodes(&pose("raise-both")).is_err(), "no such clip"); + } + #[test] fn nodes_posed_by_name_over_the_clip() { let m = Model::new(gltf::import_slice(RIGID.as_bytes()).unwrap()).unwrap(); diff --git a/renderer/src/world.rs b/renderer/src/world.rs index 9db491a..06cc26f 100644 --- a/renderer/src/world.rs +++ b/renderer/src/world.rs @@ -549,9 +549,9 @@ impl World { // (Movable as the build sees it: the object or any ancestor, `movable`.) let static_parent = parent.is_none_or(|p| !self.objects.contains_key(&p) || !self.movable(p)); let mesh = matches!(kind, Kind::Mesh { .. }); - // A new instanced mesh or static model is placed in place too (ROADMAP § 6 step 5; live/edits.rs `edit_geometry` + // A new instanced mesh or model is placed in place too (ROADMAP § 6 step 5; live/edits.rs `edit_geometry` // says when it cannot); changing one still rebuilds, but for an instanced mesh's materials (`rematerialed`). - let placed_new = !self.objects.contains_key(&id) && matches!(kind, Kind::Instanced { procedural: false, .. } | Kind::Model { animation: None, .. }); + let placed_new = !self.objects.contains_key(&id) && matches!(kind, Kind::Instanced { procedural: false, .. } | Kind::Model { .. }); let fresh = (edits_in_place(&kind) || placed_new) && (mesh || (!movable && static_parent)) && match self.objects.get(&id) { @@ -796,8 +796,8 @@ impl World { let in_place = match &o.kind { Kind::Particles { emitter_area, .. } => *emitter_area <= 0.0, Kind::Volume { .. } => true, - // (A mesh's or a still model's instance by its mask, a group's each: the renderer says whether it can.) - Kind::Mesh { .. } | Kind::Model { animation: None, .. } | Kind::Group => true, + // (A mesh's or a model's instances by their masks, a group's each: the renderer says whether it can.) + Kind::Mesh { .. } | Kind::Model { .. } | Kind::Group => true, Kind::Light(l) => !sun && !matches!(l, desc::Light::Rect { visible: true, .. }), _ => false, }; @@ -960,10 +960,10 @@ impl World { doomed.extend(self.objects.iter().filter(|(_, o)| o.parent == Some(p)).map(|(i, _)| *i)); k += 1; } - // A mesh, procedural geometry, or a group of those, is removed in place, and so is a lone instanced mesh or static + // A mesh, procedural geometry, or a group of those, is removed in place, and so is a lone instanced mesh or // model (or never added, if it came in this batch; live/edits.rs `edit_geometry` rebuilds for what it cannot // take out). - let alone = |o: &Object| doomed.len() == 1 && matches!(o.kind, Kind::Instanced { procedural: false, .. } | Kind::Model { animation: None, .. }); + let alone = |o: &Object| doomed.len() == 1 && matches!(o.kind, Kind::Instanced { procedural: false, .. } | Kind::Model { .. }); if doomed.iter().all(|d| self.objects.get(d).is_some_and(|o| edits_in_place(&o.kind) || alone(o) || (doomed.len() > 1 && matches!(o.kind, Kind::Group)))) { for d in &doomed { self.instanced.remove(d); diff --git a/tests/render/data/two-clips.glb b/tests/render/data/two-clips.glb new file mode 100644 index 0000000..c99fb9e Binary files /dev/null and b/tests/render/data/two-clips.glb differ