Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

A mesh is an instance of its geometry's mesh (#162)

Yujiaac4d1d1d0f96
diff --git a/docs/PARITY.md b/docs/PARITY.md
index 0b4e30d..cd8f6a1 100644
--- a/docs/PARITY.md
+++ b/docs/PARITY.md
@@ -36,7 +36,8 @@ Engine (renderer + DSL; at the time also the scene IR and its UE adapter, both s
table drives manual wrap / clamp; ray-cone LOD (Akenine-Möller 2019) picks the mip per hit; `texture.offset`;
alpha-cutout materials (`alphaTest`) through four BLAS groups (opaque / cutout × shadow / no-shadow) with ray-query
candidate confirmation, and the same test in the software BVH. Pages are cached across live re-uploads.
- Static glTF models are instanced (hardware RT; `scene::Instance`): each unique mesh's triangles once in model
+ Meshes and static glTF models are instances (`scene::Instance`; a mesh shared by the objects of the same geometry
+ and materials, one that moves moved by its transform): each unique mesh's triangles once in model
space with one BLAS (an opaque, a cutout and a glass geometry), one TLAS instance per placement (transform, shadow
mask, custom data = instance record), shading transforms the hit triangle; a shadow ray passes a mesh that is all glass by the
instance's mask and culls the glass geometry of a mixed mesh (the one not flagged opaque); `glass_tr` weighs what it lets through. A mirrored placement is an instance whose record says so. A model's
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index b850900..2643491 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2730,6 +2730,31 @@ geometric normal through a function on a mirrored mesh, vertex colours on one (e
traversal); the flattening of an instance against the build's flattening, mirrored too; a mirrored model's build; a
copy mirrored in place; an emitting instanced object added, changed and removed in place against a build.
+**A mesh is an instance of its geometry's mesh (2026-11-18, scene step E, first part).** A mesh was an instance
+only where scene code asked (`dynamicGeometry`) or a body drove it; every other one was flattened into the
+still scene's world-space groups, a movable one re-transformed on the CPU at each move. Now every shown mesh with a
+size is an instance: its triangles once in model space in the pool, one BLAS, shared by the objects of the same
+geometry and materials. A mesh of several materials (a geometry group each) is one mesh, its triangles ordered by
+class, a BLAS geometry a class (`scene::own_mesh`). A movable mesh's move is its instance's transform
+(`InstanceRef::moves`): no vertex is written again, and under software traversal it moves in place too. A material
+that starts emitting gives each instance of its meshes its emitters in place (`Tables::mesh_mats`, live/edits.rs
+`add_material_emitters`: the mesh's emitting triangles numbered again, a new run of the light list an instance, the
+old one at no weight); one a model or an instanced object has too still rebuilds. Room for edits in place stays
+where the scene said a mesh is edited or driven (`Retained::edits_meshes`).
+A moved instance whose placement has no size (scene code hides by scaling to 0) stands at a point, hidden, and
+comes back in place (`scene::placed_world`, as an instanced object's copy does).
+Still flattened: a mesh without size, `THREERT_INSTANCING=0`, a light's card, particles, triangles on the same
+vertices (`flatten_coincident`), deforming meshes. Still a rebuild, the next part: hiding a mesh, a still mesh's
+first move, removing or changing the geometry of one the scene did not say it edits.
+Not the common structure, a step of its own after this one: a mesh is shared by geometry and materials, the
+material being a triangle's attribute (two objects of one geometry with different materials hold its triangles
+twice); the common one has the material on the instance.
+Tests: a mesh of three materials whose geometry has the glass first (`shadow/glass-groups`, `-frame`, `-cutout`,
+`-live-exact`); a several-material mesh's order and counts; a material that starts emitting, against a build (a
+shared mesh, a movable one moved after, a mesh of two materials one of which emitted already, a mesh added in
+place; one an instanced object has too rebuilds); a movable mesh scaled to nothing and back. Under software
+traversal `wind/pivot-sway-live` passes now.
+
**Glass is a part of its mesh (2026-11-18).** The last reason to flatten a material's triangles at every placement
goes. A mesh's glass is a geometry of its BLAS beside the opaque and the cutout one, the only one not flagged opaque
(`InstMesh::parts`; a hit's triangle from its geometry and primitive by two starts in the instance's record). A shadow
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index 2da75b5..cc1dfba 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -87,6 +87,7 @@ pub struct Prepared {
/// place from its runs (live/edits.rs `add_material_emitters`), unless fixed.
pub mat_runs: std::collections::HashMap<u32, Vec<[u32; 3]>>,
pub fixed_mats: std::collections::HashSet<u32>,
+ pub mesh_mats: std::collections::HashSet<u32>,
/// The flattened triangles' build indices in traversal order (`Scene::tris` order: positions for new entries).
pub tri_order: Vec<u32>,
/// The brightest sky texel (luminance) from which the environment is light-sampled (`Params::counts2[1]`): 0 when
@@ -714,14 +715,7 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
let n = scene::number_emitters(&mut sc.attrs[pool_first + m.first as usize..pool_first + (m.first + m.count) as usize], &sc.materials);
assert_eq!(n, m.emitters, "a mesh's emitters as the build counted them");
}
- // (The instances an edit moves in place: a body's, a movable model's, a posed rigid model's nodes', an instanced
- // object's copies.)
- let moving: std::collections::HashSet<u32> = sc.retained.proxies.values().flat_map(|p| match &p.draw {
- scene::Draw::Instance(i) if i.moves => vec![i.instance],
- scene::Draw::Rigid(r) => r.instances.iter().map(|&(_, i)| i).collect(),
- scene::Draw::Instanced(c) if c.mesh.is_some() => (c.first..c.first + c.capacity).collect(),
- _ => vec![],
- }).collect();
+ let moving = sc.retained.moving_records();
for r in 0..sc.instances.len() {
let m = sc.meshes[sc.instances[r].mesh as usize];
if m.emitters == 0 {
@@ -741,13 +735,23 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
}
// Where each material's flattened static triangles are (runs of the traversal order, with their object), for a
// material that starts emitting in the live view (tables.rs `apply`): its emitter entries are made from them in
- // place. Materials that also cover pool or dynamic triangles cannot (`fixed_mats`).
+ // place. Materials of pool or dynamic triangles are `fixed_mats`; of those, `mesh_mats` are the ones whose pool
+ // triangles are meshes' alone (`Retained::own_mesh`: no model's, no instanced object's) and that no dynamic
+ // triangle has: each instance of such a mesh gets its emitters in place too (live/edits.rs
+ // `add_material_emitters`).
let mut mat_runs: std::collections::HashMap<u32, Vec<[u32; 3]>> = std::collections::HashMap::new();
let mut fixed_mats: std::collections::HashSet<u32> = sc.pool_attrs.iter().map(|a| a.uv[3].to_bits()).collect();
+ let own: std::collections::HashSet<u32> = sc.retained.own_mesh.values().copied().collect();
+ let (mut mesh_mats, mut others): (std::collections::HashSet<u32>, std::collections::HashSet<u32>) = Default::default();
+ for (k, m) in sc.meshes.iter().enumerate() {
+ let mats = sc.attrs[pool_first + m.first as usize..pool_first + (m.first + m.count) as usize].iter().map(|a| a.uv[3].to_bits());
+ if own.contains(&(k as u32)) { mesh_mats.extend(mats) } else { others.extend(mats) }
+ }
for (k, a) in sc.attrs[..pool_first].iter().enumerate() {
let (mat, obj) = (a.uv[3].to_bits(), a.x[1].to_bits());
if tri_verts[k * 3][3].to_bits() & scene::TRI_DYNAMIC != 0 {
fixed_mats.insert(mat);
+ others.insert(mat);
continue;
}
let runs = mat_runs.entry(mat).or_default();
@@ -756,6 +760,7 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
_ => runs.push([k as u32, k as u32 + 1, obj]),
}
}
+ mesh_mats.retain(|m| !others.contains(m));
let tri_order = bvh.order[..pool_first.min(bvh.order.len())].to_vec();
// Many static emitters: a light tree samples them by importance at the shading point (`ltree`); each one's path
// code with its triangle in the list (emit_mis). THREERT_LTREE=0: the CDF alone (A/B).
@@ -877,7 +882,7 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
first += u32::try_from(count).expect("more than 2^32 triangles");
}
let energy = energy_lut();
- Prepared { tri_verts, groups, nodes, emitters, gpu_emitter_tris, emitter_runs, env, env_cdf, params, energy, emitter_tris, light_tree, env_nee_floor, mat_runs, fixed_mats, tri_order }
+ Prepared { tri_verts, groups, nodes, emitters, gpu_emitter_tris, emitter_runs, env, env_cdf, params, energy, emitter_tris, light_tree, env_nee_floor, mat_runs, fixed_mats, mesh_mats, tri_order }
}
/// Instances as world-space triangles (software traversal), appended to the flattened ones with their objects.
@@ -1523,8 +1528,9 @@ mod units_tests {
use crate::world::{Geometry, Kind, World};
use glam::{Mat4, Quat};
- /// A world with a flattened ground, meshes of their own (`own_blas`: units under software traversal) turned and
- /// scaled, one that casts no shadow, one hidden, and an instanced mesh of five instances of which four are drawn.
+ /// A world with a ground and a light's card (the card's two triangles are the only still ones: a mesh is a unit
+ /// under software traversal), meshes turned and scaled, one that casts no shadow, one hidden, and an instanced mesh
+ /// of five instances of which four are drawn.
fn world(ground: bool) -> World {
let mut w = World::default();
w.set_material(1, serde_json::from_value(serde_json::json!({ "name": "m", "color": [0.5, 0.5, 0.5], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true })).unwrap());
@@ -1551,6 +1557,9 @@ mod units_tests {
if ground {
w.set_object(10, "ground".into(), None, mesh(2, false), true, false).unwrap();
w.set_transform(10, Vec3::new(0.0, -1.0, 0.0), Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2), Vec3::ONE).unwrap();
+ let card = serde_json::from_value(serde_json::json!({ "type": "rect", "color": [1, 1, 1], "castShadow": true, "intensity": 1, "width": 3, "height": 3, "range": 0 })).unwrap();
+ w.set_object(16, "card".into(), None, Kind::Light(card), true, false).unwrap();
+ w.set_transform(16, Vec3::new(1.0, 2.5, -1.0), Quat::from_rotation_x(std::f32::consts::FRAC_PI_2), Vec3::ONE).unwrap();
}
let place = |w: &mut World, id: u32, geometry: u32, at: [f32; 3], turn: f32, scale: [f32; 3], shadow: bool| {
w.set_object(id, format!("o{id}"), None, mesh(geometry, true), shadow, false).unwrap();
@@ -1633,14 +1642,15 @@ mod units_tests {
};
let (su, pu) = build(true);
let (sf, pf) = build(false);
- assert_eq!(su.tris.is_empty(), w.objects.get(&10).is_none(), "still triangles: the ground's only");
+ let ground = usize::from(w.objects.contains_key(&10));
+ assert_eq!(su.tris.len(), 2 * ground, "still triangles: the card's only");
let u = su.units.as_ref().expect("the scene has units");
assert!(sf.units.is_none() && sf.instances.is_empty(), "flattened: no instance is left");
- // Nine instances: four own meshes shown, one hidden (no instance at all), five of the instanced mesh of which
- // one is hidden: eight units in the top tree.
- assert_eq!((su.instances.len(), u.count), (9, 8), "{:?}", su.instances.iter().map(|i| (i.name.clone(), i.hidden)).collect::<Vec<_>>());
+ // Nine instances and the ground: four meshes shown, one hidden (no instance at all), five of the instanced mesh
+ // of which one is hidden: eight units in the top tree, and the ground.
+ assert_eq!((su.instances.len(), u.count as usize), (9 + ground, 8 + ground), "{:?}", su.instances.iter().map(|i| (i.name.clone(), i.hidden)).collect::<Vec<_>>());
assert!(gpu::instance_features(&su) & gpu::F_UNITS != 0 && gpu::instance_features(&sf) & gpu::F_UNITS == 0);
- assert_eq!((pu.params.motion[2].to_bits(), pu.params.motion[3].to_bits()), (u.layout.top_first, 8));
+ assert_eq!((pu.params.motion[2].to_bits(), pu.params.motion[3].to_bits() as usize), (u.layout.top_first, 8 + ground));
// The flattened scene holds every instance's triangles; the scene with units holds each mesh's once.
assert!(pf.tri_verts.len() > pu.tri_verts.len());
assert_eq!(pu.nodes.len(), u.layout.top_first as usize + u.layout.top_cap as usize);
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index b08cffe..25db39c 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -577,7 +577,7 @@ impl LiveCore {
up.heap.write(q, Table::Objects, 0, bytemuck::cast_slice(&e.objects));
}
if d.materials || d.emitters || std::mem::take(&mut self.emitters_reweigh) {
- let new = self.add_material_emitters();
+ let new = self.add_material_emitters(world);
self.write_emitters(&new);
} else if d.deferred {
self.send_powers();
@@ -752,8 +752,9 @@ impl LiveCore {
let (mut lo, mut hi) = (usize::MAX, 0usize);
// (Instances the last update moved and this one does not catch up in `commit`.)
for &(node, i) in placed {
- let w = world.world_matrix(node);
let inst = &mut self.sc.instances[i as usize];
+ // (A placement without size, as scene code hides by scaling to 0: at a point, where no ray sees it.)
+ let (w, gone) = scene::placed_world(world.world_matrix(node), inst.world.w_axis.truncate());
// (Software traversal: an instance of a mesh that deforms is no unit; its triangles are among the still
// scene's, in the world, and a rebuild moves them.)
if !top.has_mesh(inst.mesh) {
@@ -774,7 +775,7 @@ impl LiveCore {
let o = &mut self.sc.tables.objects[inst.object as usize * st];
(o[0], o[1], o[2]) = (pivot.x, pivot.y, pivot.z);
let slot = top.inst_base() + i as usize;
- top.moved(slot, w, None);
+ top.moved(slot, w, Some((inst.cast_shadow, gone || inst.hidden)));
self.inst_moving.push(i);
}
if merged {
@@ -827,10 +828,12 @@ impl LiveCore {
/// Emitter entries for the materials that started emitting (`Tables::started_emitting`): their flattened static
/// triangles (`mat_runs`), positions from `tris`, in the power-share part of the CDF (path code 0, as the light
/// tree's moving emitters; ROADMAP § 6 step 3). Returns them (each one's index and triangle) for `write_emitters`.
- pub(super) fn add_material_emitters(&mut self) -> Vec<(u32, crate::GpuEmitterTri)> {
+ pub(super) fn add_material_emitters(&mut self, world: &World) -> Vec<(u32, crate::GpuEmitterTri)> {
+ let (hwrt, q) = (self.g.hwrt, &self.g.queue);
let sc = &mut self.sc;
let mut new = vec![];
- for mat in std::mem::take(&mut sc.tables.started_emitting) {
+ let started = std::mem::take(&mut sc.tables.started_emitting);
+ for &mat in &started {
for &[first, end, obj] in sc.mat_runs.get(&mat).map_or(&[][..], |v| v.as_slice()) {
for k in first..end {
let Some(&[a, b, c]) = sc.tri_order.get(k as usize).and_then(|&i| sc.tris.get(i as usize)) else { continue };
@@ -844,6 +847,65 @@ impl LiveCore {
}
}
}
+ // The meshes with a triangle of one of them (`Tables::mesh_mats`): the mesh's emitting triangles are numbered
+ // again as they lie (`scene::number_emitters`: the build's numbering, with the materials as they are now), and
+ // each of its instances gets its emitters as a new run at the list's end, its first in the instance's record;
+ // the run it had, of fewer, stays at no weight.
+ if !started.is_empty() && !sc.meshes.is_empty() {
+ let LoadedScene { tables, instances, gpu_instances, meshes, pool_tris, edit, up, .. } = sc;
+ let moving = tables.retained.moving_records();
+ let mut done = std::collections::HashSet::new();
+ for (id, o) in &world.objects {
+ let crate::world::Kind::Mesh { geometry, material, materials: mesh_mats, .. } = &o.kind else { continue };
+ let gpu_of = |k: &u32| tables.retained.materials.get(k).copied();
+ if !std::iter::once(material).chain(mesh_mats).any(|k| gpu_of(k).is_some_and(|m| started.contains(&m))) {
+ continue;
+ }
+ let Some(k) = tables.retained.instance(*id).filter(|i| i.mesh.own()).and_then(|i| instances.get(i.instance as usize)).map(|i| i.mesh) else { continue };
+ if !done.insert(k) {
+ continue;
+ }
+ let gpu_mats: Option<Vec<u32>> = mesh_mats.iter().map(gpu_of).collect();
+ let (Some(g), Some(mat), Some(gpu_mats)) = (world.geometries.get(geometry), gpu_of(material), gpu_mats) else { continue };
+ let (t, mut a, _, _) = scene::own_mesh(g, mat, scene::group_materials(g, &gpu_mats).as_deref(), &tables.materials, 0);
+ // (Software traversal: a unit's triangles lie in its tree's order.)
+ if !hwrt {
+ let Ok(tree) = crate::units::mesh_tree(&t) else { continue };
+ a = tree.order.iter().map(|&i| a[i as usize]).collect();
+ }
+ let im = meshes[k as usize];
+ if a.len() != im.count as usize {
+ debug_assert!(false, "mesh {k}: {} triangles made again, {} in the pool", a.len(), im.count);
+ continue;
+ }
+ let n = scene::number_emitters(&mut a, &tables.materials);
+ meshes[k as usize].emitters = n;
+ let first_tri = edit.pool_first + im.first as usize;
+ q.write_buffer(&up.attrs, (first_tri * std::mem::size_of::<scene::GpuTriAttr>()) as u64, bytemuck::cast_slice(&a));
+ let numbered = |j: usize| (a[j].x[3].to_bits() as usize).checked_sub(1).map(|slot| (slot, a[j].uv[3].to_bits()));
+ for r in 0..instances.len() {
+ // (A record no object draws any more has none.)
+ if instances[r].mesh != k || instances[r].hidden {
+ continue;
+ }
+ let old = emitter_run(&tables.emitter_tris, instances, r as u32);
+ for e in &mut tables.emitter_tris[old] {
+ e.area = 0.0;
+ }
+ let first = tables.emitter_tris.len() as u32;
+ instances[r].first_emitter = first;
+ if let Some(rec) = gpu_instances.get_mut(r) {
+ rec.n[2][3] = f32::from_bits(first);
+ up.heap.write(q, Table::Instances, (r * std::mem::size_of::<scene::GpuInstance>()) as u64, bytemuck::bytes_of(rec));
+ }
+ let (b0, b1) = (im.first as usize, (im.first + im.count) as usize);
+ for (e, w) in crate::instance_emitters(&instances[r], r as u32, &pool_tris[b0..b1], first_tri as u32, &numbered, n as usize, &tables.materials, moving.contains(&(r as u32))) {
+ new.push((tables.emitter_tris.len() as u32, crate::GpuEmitterTri::of(&e, w, 0)));
+ tables.emitter_tris.push(e);
+ }
+ }
+ }
+ }
new
}
@@ -1677,7 +1739,7 @@ impl LiveCore {
let mut w_colors = Gather::default();
let vcolors = up.vcolors;
// (geometry, material) -> the mesh built in this batch (objects sharing a replaced geometry share it again).
- let mut fresh: std::collections::HashMap<(u32, u32), u32> = Default::default();
+ let mut fresh: std::collections::HashMap<(u32, Vec<u32>), u32> = Default::default();
let mask = |shadow: bool| if shadow { 1 } else { 2 };
for id in todo {
let Some(o) = world.objects.get(&id) else { continue };
@@ -1815,7 +1877,13 @@ impl LiveCore {
}
let mat = *tables.retained.materials.get(material).ok_or("unknown material")?;
let gm = tables.materials[mat as usize];
- // (It covers instances' triangles from here on: `Tables::fixed_mats`.)
+ // (It covers instances' triangles from here on, `Tables::fixed_mats`: meshes' alone, `mesh_mats`,
+ // if it covered none before or was theirs alone, and this is a mesh.)
+ if !matches!(o.kind, Kind::Mesh { .. }) {
+ tables.mesh_mats.remove(&mat);
+ } else if !tables.fixed_mats.contains(&mat) {
+ tables.mesh_mats.insert(mat);
+ }
tables.fixed_mats.insert(mat);
// An emitting material: a mesh as any other, each instance's emitters in the light list (given
// below, where its record is known; scene.rs; ROADMAP § 6 step 3).
@@ -1831,7 +1899,7 @@ impl LiveCore {
if colored && !vcolors {
return Err("the scene's first vertex colours (kernel feature)".into());
}
- let key = (*geometry, mat);
+ let key = (*geometry, vec![mat]);
let kept = (!ch.geometries.contains(geometry)).then(|| tables.retained.own_mesh.get(&key).copied()).flatten();
let mesh = match fresh.get(&key).copied().or(kept) {
Some(k) => k,
@@ -1963,7 +2031,7 @@ impl LiveCore {
pool_tris[rel..rel + t.len()].copy_from_slice(&t);
let _ = im;
new_meshes.push(k);
- fresh.insert(key, k);
+ fresh.insert(key.clone(), k);
tables.retained.own_mesh.insert(key, k);
k
}
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 07ea96f..2fef0ad 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -314,6 +314,9 @@ fn moves_in_place_leave_what_a_build_does() {
w.set_transform(13, at(0.2, 0.2, 0.7), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
}),
),
+ // (Scene code hides by scaling to 0: the instance stands at a point where no ray sees it, and comes back.)
+ ("the movable mesh scaled to nothing", Box::new(move |w| w.set_transform(13, at(0.2, 0.2, 0.7), glam::Quat::IDENTITY, Vec3::ZERO).unwrap())),
+ ("the movable mesh back at its size", Box::new(move |w| w.set_transform(13, at(-0.1, 0.3, 0.8), glam::Quat::IDENTITY, Vec3::ONE).unwrap())),
];
for (what, edit) in &edits {
edit(&mut w);
@@ -322,6 +325,7 @@ fn moves_in_place_leave_what_a_build_does() {
// (Software traversal places some of these another way, and may rebuild: the picture holds either way.)
assert!(!(rebuilt && live.g.hwrt), "{what}: in place ({:?})", live.fallback);
assert_eq!(live.top_builds - builds, u32::from(!rebuilt), "{what}: one build above the triangles a commit, whatever moved");
+ assert!(live.sc.instances.iter().all(|i| i.world.is_finite() && i.world.determinant() != 0.0), "{what}: every instance has a size above the triangles");
let mut fresh = open(&w).unwrap();
forget(&mut live);
let (a, b) = (picture(&mut live, 24), picture(&mut fresh, 24));
@@ -408,6 +412,8 @@ fn list_is_its_triangles(what: &str, c: &LiveCore) {
let codes = crate::emitter_codes(&tables.emitter_tris, &crate::emitter_order(&tables.emitter_tris, tables.light_tree.as_ref()), tables.light_tree.as_ref());
// (The CDF as the kernel reads it: an emitter that is not the tree's is found by the entry its code names.)
let cdf = read(&up.heap.buffer, up.heap.at(Table::Emitters), (tables.emitter_tris.len() * 16) as u64);
+ let record_size = std::mem::size_of::<scene::GpuInstance>();
+ let records = read(&up.heap.buffer, up.heap.at(Table::Instances), (c.sc.gpu_instances.len() * record_size) as u64);
let mut alive = 0;
for (i, e) in tables.emitter_tris.iter().enumerate() {
let r: crate::GpuEmitterTri = bytemuck::pod_read_unaligned(&list[i * size..][..size]);
@@ -426,7 +432,8 @@ fn list_is_its_triangles(what: &str, c: &LiveCore) {
assert_eq!(r, crate::GpuEmitterTri::new(e, &rows, code & !crate::EMITTER_MOVES), "{what}: emitter {i} of the list against its triangle {}", e.tri);
assert_eq!(a.x[3].to_bits(), i as u32 + 1, "{what}: triangle {} names its emitter", e.tri);
} else {
- let (inst, record) = (&c.sc.instances[e.inst as usize], &c.sc.gpu_instances[e.inst as usize]);
+ // (The record as the GPU has it.)
+ let (inst, record) = (&c.sc.instances[e.inst as usize], bytemuck::pod_read_unaligned::<scene::GpuInstance>(&records[e.inst as usize * record_size..][..record_size]));
let at = |k: usize| glam::Vec3::new(rows[k][0], rows[k][1], rows[k][2]);
let placed = [inst.world.transform_point3(at(0)), inst.world.transform_vector3(at(1)), inst.world.transform_vector3(at(2))];
assert_eq!((r.tri, r.inst, r.code), (e.tri, e.inst, code), "{what}: emitter {i}'s words");
@@ -712,7 +719,7 @@ fn an_emitter_scaled_in_place_is_lit_as_a_build_lights_it() {
fn the_light_list_holds_its_triangles() {
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));
- // An emitter the CPU moves.
+ // An emitter that moves: a movable mesh is an instance of its mesh, its emitters its instance's.
for tree in [true, false] {
let mut w = world();
w.set_object(13, "mover".into(), None, Kind::Mesh { geometry: 3, material: 5, own_blas: false, materials: vec![] }, true, true).unwrap();
@@ -726,7 +733,8 @@ fn the_light_list_holds_its_triangles() {
};
w.take_changes();
assert_eq!(live.sc.tables.light_tree.as_ref().is_some_and(|t| t.moving_count > 0), tree, "the mover is in the tree's moving subtree");
- assert_eq!(live.sc.up.fills.moved.is_some(), live.g.hwrt, "the mover's emitters are filled on the GPU");
+ assert!(live.sc.tables.emitter_tris.iter().any(|e| e.inst != crate::NO_INST && e.moves), "the mover's emitters are its instance's");
+ assert!(live.sc.up.fills.moved.is_none(), "no triangle is left for the CPU to move");
list_is_its_triangles("a moving emitter, as loaded", &live);
w.set_transform(13, Vec3::new(0.1, -0.3, 0.9), glam::Quat::from_rotation_z(0.5), Vec3::ONE).unwrap();
let rebuilt = live.commit(&mut w).unwrap();
@@ -764,7 +772,7 @@ fn the_light_list_holds_its_triangles() {
w.take_changes();
if live.g.hwrt {
let of_instances = live.sc.tables.emitter_tris.iter().filter(|e| e.inst != crate::NO_INST).count();
- assert_eq!(of_instances, 6, "two emitters a placement of the model, each its instance's");
+ assert_eq!(of_instances, 8, "the lamp's two, and two a placement of the model, each its instance's");
// (An instance an edit moves in place has moving emitters: no light LOD from a centroid that goes stale, the
// light tree's moving subtree. One that stays has not.)
let moves = |id: u32| {
@@ -777,7 +785,7 @@ fn the_light_list_holds_its_triangles() {
(of.len(), of.iter().all(|m| *m))
};
assert_eq!((moves(31), moves(32)), ((2, true), (2, true)), "the movable and the posed model's emitters move");
- assert!(live.sc.tables.emitter_tris.iter().filter(|e| e.inst != crate::NO_INST && !e.moves).count() == 2, "the still model's do not");
+ assert!(live.sc.tables.emitter_tris.iter().filter(|e| e.inst != crate::NO_INST && !e.moves).count() == 4, "the lamp's and the still model's do not");
list_is_its_triangles("a model's emitters, as loaded", &live);
type Move = (&'static str, Box<dyn Fn(&mut World)>);
let moves: Vec<Move> = vec![
@@ -868,3 +876,107 @@ fn the_light_list_holds_its_triangles() {
assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));
}
}
+
+/// A material that starts emitting in place lights the instances of the meshes that have it as a build lights them: a
+/// mesh of that material alone that two objects share, one of them movable (and moved afterwards: its new emitters
+/// follow it), a mesh of two materials of which the other emitted already (its instance's run of the light list
+/// grows), and a mesh added in place of a material nothing had. With and without a light tree. After each: no rebuild,
+/// the light list is its triangles, the weights and the picture are a build's. A material an instanced object has too
+/// rebuilds, one added in place as well.
+#[test]
+fn a_material_that_starts_emitting_lights_its_meshes_instances_as_a_build_does() {
+ 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 late = |emissive: f32| serde_json::from_value(serde_json::json!({ "name": "late", "color": [0.2, 0.2, 0.2], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1.0, 0.6, 0.3], "emissiveIntensity": emissive, "doubleSided": true })).unwrap();
+ for tree in [false, true] {
+ let mut w = world();
+ // (The sun away: the meshes will light the scene.)
+ w.set_visible(20, false).unwrap();
+ w.set_material(6, late(0.0));
+ // Sixteen quads in a row in one geometry, a group each, by turns of the lamp's material, which emits, and of
+ // the late one; the geometry has them out of the row's order (so that a mesh tree orders them its own way under
+ // software traversal).
+ let (mut positions, mut indices, mut groups) = (vec![], vec![], vec![]);
+ for q in 0..16u32 {
+ let x = -0.48 + 0.06 * ((q * 7) % 16) as f32;
+ positions.extend([x, -0.15, 0.0, x + 0.06, -0.15, 0.0, x + 0.06, 0.15, 0.0, x, 0.15, 0.0]);
+ indices.extend([0, 1, 2, 0, 2, 3].map(|i| 4 * q + i));
+ groups.push([6 * q, 6, q % 2]);
+ }
+ w.set_geometry(7, Geometry { positions, normals: [0.0, 0.0, 1.0].repeat(64), uvs: vec![0.0; 128], indices, groups, colors: vec![] }).unwrap();
+ let mesh = |geometry, material, materials| Kind::Mesh { geometry, material, own_blas: false, materials };
+ w.set_object(13, "one".into(), None, mesh(3, 6, vec![]), true, false).unwrap();
+ w.set_transform(13, Vec3::new(-0.6, -0.5, 0.8), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ w.set_object(14, "other".into(), None, mesh(3, 6, vec![]), true, true).unwrap();
+ w.set_transform(14, Vec3::new(0.5, -0.5, 0.9), glam::Quat::from_rotation_y(0.5), Vec3::ONE).unwrap();
+ w.set_object(15, "two".into(), None, mesh(7, 5, vec![5, 6]), true, false).unwrap();
+ w.set_transform(15, Vec3::new(0.0, 0.6, 0.7), glam::Quat::from_rotation_x(-0.3), Vec3::ONE).unwrap();
+ // A material a mesh has and an instanced object too, and one nothing has yet; a mesh the scene says it edits
+ // (room for one added in place).
+ w.set_material(7, late(0.0));
+ w.set_material(8, late(0.0));
+ w.set_material(9, late(0.0));
+ w.set_object(32, "nine".into(), None, mesh(3, 9, vec![]), true, false).unwrap();
+ w.set_transform(32, Vec3::new(-0.9, -0.1, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ w.set_object(26, "both".into(), None, mesh(3, 7, vec![]), true, false).unwrap();
+ w.set_transform(26, Vec3::new(-0.9, 0.6, 0.6), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ w.set_object(27, "copies".into(), None, Kind::Instanced { geometry: 3, procedural: false, materials: vec![7], capacity: 1 }, true, false).unwrap();
+ w.set_instances(27, 1, Some(glam::Mat4::from_translation(Vec3::new(0.9, 0.6, 0.6)).to_cols_array().to_vec()), None, None).unwrap();
+ 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(0.9, -0.1, 0.4), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ if tree {
+ strip(&mut w);
+ }
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ picture(&mut live, 4);
+ let with = if tree { "with" } else { "without" };
+ let mesh_of = |c: &LiveCore, id: u32| c.sc.instances[c.sc.tables.retained.instance(id).expect("a mesh is an instance").instance as usize].mesh;
+ assert_eq!(mesh_of(&live, 13), mesh_of(&live, 14), "the two objects share their mesh");
+ let two = mesh_of(&live, 15) as usize;
+ assert_eq!((live.sc.meshes[two].count, live.sc.meshes[two].emitters), (32, 16), "the mesh of two materials: one emits");
+ w.set_material(6, late(30.0));
+ let what = format!("a material started emitting in place, {with} a light tree");
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ assert_eq!((live.sc.meshes[two].emitters, live.sc.meshes[mesh_of(&live, 13) as usize].emitters), (32, 2), "{what}: the meshes' emitters");
+ list_is_its_triangles(&what, &live);
+ let moving = |c: &LiveCore, id: u32| {
+ let r = c.sc.tables.retained.instance(id).unwrap().instance;
+ c.sc.tables.emitter_tris.iter().filter(|e| e.inst == r && e.area > 0.0).map(|e| e.moves).collect::<Vec<_>>()
+ };
+ assert_eq!((moving(&live, 13), moving(&live, 14)), (vec![false; 2], vec![true; 2]), "{what}: the movable one's emitters move");
+ lit_as_a_build(&what, &mut live, &mut open(&w).unwrap());
+ if live.g.hwrt {
+ w.set_object(29, "added".into(), None, Kind::Mesh { geometry: 3, material: 8, own_blas: true, materials: vec![] }, true, false).unwrap();
+ w.set_transform(29, Vec3::new(-0.2, 0.1, 1.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "a mesh added, {with} a light tree: in place ({:?})", live.fallback);
+ w.set_material(8, late(20.0));
+ let what = format!("the material of a mesh added in place started emitting, {with} a light tree");
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ list_is_its_triangles(&what, &live);
+ lit_as_a_build(&what, &mut live, &mut open(&w).unwrap());
+ }
+ w.set_transform(14, Vec3::new(0.2, -0.3, 1.2), glam::Quat::from_rotation_z(0.6), Vec3::ONE).unwrap();
+ let what = format!("the movable one of them moved, {with} a light tree");
+ assert!(!(live.commit(&mut w).unwrap() && live.g.hwrt), "{what}: in place ({:?})", live.fallback);
+ list_is_its_triangles(&what, &live);
+ // (A moving emitter's centre is not kept on the CPU: the picture alone.)
+ forget(&mut live);
+ let (a, b) = (picture(&mut live, 64), picture(&mut open(&w).unwrap(), 64));
+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));
+ // A material meshes had alone, until an instanced object of it is added in place: a rebuild from then on.
+ if live.g.hwrt {
+ w.set_object(31, "more".into(), None, Kind::Instanced { geometry: 3, procedural: false, materials: vec![9], capacity: 1 }, true, false).unwrap();
+ w.set_instances(31, 1, Some(glam::Mat4::from_translation(Vec3::new(0.4, 0.2, 1.1)).to_cols_array().to_vec()), None, None).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "an instanced object added, {with} a light tree: in place ({:?})", live.fallback);
+ w.set_material(9, late(30.0));
+ assert!(live.commit(&mut w).unwrap(), "a material an instanced object added in place has too started emitting, {with} a light tree: a rebuild");
+ }
+ // (Its copies' emitters are a build's to make.)
+ w.set_material(7, late(30.0));
+ assert!(live.commit(&mut w).unwrap(), "a material an instanced object has too started emitting, {with} a light tree: a rebuild");
+ }
+}
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index e27ceb2..920d4b8 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -217,6 +217,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
// (THREERT_EDIT_REBUILD=1: every edit rebuilds, a material that starts emitting too: the A/B.)
tables.emit_in_place = std::env::var("THREERT_EDIT_REBUILD").map_or(true, |v| v != "1");
tables.fixed_mats = std::mem::take(&mut prep.fixed_mats);
+ tables.mesh_mats = std::mem::take(&mut prep.mesh_mats);
let emit = EmitterWorker::new(&tables, &g.device);
tables.defer_powers = emit.is_some();
let (mat_runs, tri_order) = (std::mem::take(&mut prep.mat_runs), std::mem::take(&mut prep.tri_order));
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index 136c178..57bfb2b 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -281,12 +281,24 @@ pub fn blas_tri(t: [[f32; 3]; 3]) -> [[f32; 3]; 3] {
/// keeps the TLAS free of non-finite numbers, and can come back in place.
pub fn instance_world(m: Mat4, t: &world::InstanceTable, i: usize) -> (Mat4, bool) {
let w = m * t.matrix(i);
- let det = glam::Mat3::from_mat4(w).determinant();
- if i < t.count as usize && w.is_finite() && det.abs() > 1e-30 {
+ if i < t.count as usize {
+ return placed_world(w, m.w_axis.truncate());
+ }
+ (at_point(if w.w_axis.is_finite() { w.w_axis.truncate() } else { m.w_axis.truncate() }), true)
+}
+
+/// An instance's world matrix as the structure above the triangles takes it, and whether the placement has no size:
+/// not finite, or not invertible (scene code hides by scaling to 0). Such an instance stands at a point (its
+/// translation, or `fallback`), hidden.
+pub fn placed_world(w: Mat4, fallback: Vec3) -> (Mat4, bool) {
+ if w.is_finite() && glam::Mat3::from_mat4(w).determinant().abs() > 1e-30 {
return (w, false);
}
- let at = if w.w_axis.is_finite() { w.w_axis.truncate() } else { m.w_axis.truncate() };
- (Mat4::from_scale_rotation_translation(Vec3::splat(1e-6), glam::Quat::IDENTITY, at), true)
+ (at_point(if w.w_axis.is_finite() { w.w_axis.truncate() } else { fallback }), true)
+}
+
+fn at_point(at: Vec3) -> Mat4 {
+ Mat4::from_scale_rotation_translation(Vec3::splat(1e-6), glam::Quat::IDENTITY, at)
}
impl ProcObject {
@@ -647,9 +659,12 @@ pub struct Retained {
pub sun: Option<u32>,
/// Posed models sharing a pose (`PoseGroup`: its members' proxies name it, `MeshKind::Pose`).
pub pose_groups: Vec<PoseGroup>,
- /// `own_blas` meshes: (geometry, GPU material) -> the shared mesh (objects with the same geometry and material
- /// share its BLAS). live/edits.rs `edit_geometry` keeps it.
- pub own_mesh: HashMap<(u32, u32), u32>,
+ /// Meshes: (geometry, GPU materials: one, or a group's each) -> the shared mesh (objects with the same geometry and
+ /// materials share its BLAS). live/edits.rs `edit_geometry` keeps it.
+ pub own_mesh: HashMap<(u32, Vec<u32>), u32>,
+ /// Whether the scene said a mesh's geometry will be edited or driven (`own_blas`, `driven`): it gets room for
+ /// edits in place (gpu.rs `EditRoom`).
+ pub edits_meshes: bool,
/// 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<Vec<String>>), u32>,
@@ -752,9 +767,23 @@ impl Retained {
self.proxies.values().any(|p| matches!(&p.draw, Draw::Rigid(_)) || matches!(&p.draw, Draw::Instance(i) if i.moves))
}
- /// Whether any object is an `own_blas` mesh's instance (what geometry edits place again).
+ /// The records of the instances an edit moves in place: a mesh's or a model's that moves (a body's, a movable
+ /// one's), a posed rigid model's nodes', an instanced object's copies.
+ pub fn moving_records(&self) -> std::collections::HashSet<u32> {
+ self.proxies
+ .values()
+ .flat_map(|p| match &p.draw {
+ Draw::Instance(i) if i.moves => vec![i.instance],
+ Draw::Rigid(r) => r.instances.iter().map(|&(_, i)| i).collect(),
+ Draw::Instanced(c) if c.mesh.is_some() => (c.first..c.first + c.capacity).collect(),
+ _ => vec![],
+ })
+ .collect()
+ }
+
+ /// Whether any object is a mesh the scene edits or drives (what geometry edits place again).
pub fn has_own_instances(&self) -> bool {
- self.proxies.values().any(|p| matches!(&p.draw, Draw::Instance(i) if i.mesh.own()))
+ self.edits_meshes
}
/// The triangles re-transformed on the CPU: the dynamic objects' and the rigid models' flattened ones.
@@ -1380,45 +1409,49 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let shown = w.shown(*id);
let flags = if n.cast_shadow { 0 } else { TRI_NO_SHADOW };
match &n.kind {
- Kind::Mesh { geometry, material, own_blas, materials: mesh_mats } if shown && instancing && mesh_mats.len() <= 1 && m.determinant() != 0.0 && (n.driven || (*own_blas && !w.movable(*id))) => {
- // Its own BLAS (scene code's `dynamicGeometry`, or a mesh a rigid body drives: its moves are the
- // instance's transform, `InstanceRef::moves`): placed like a model instance, its geometry's triangles
- // in model space in the pool, shared by the objects of the same geometry and material, whatever the
- // material (`mesh_class`: glass is its mesh's glass part; one that emits has each instance's
- // emitters in the light list, `InstMesh::emitters`).
+ Kind::Mesh { geometry, material, own_blas, materials: mesh_mats } if shown && instancing && m.determinant() != 0.0 => {
+ // A mesh is an instance of its geometry's mesh: the triangles in model space in the pool, one BLAS,
+ // shared by the objects of the same geometry and materials, whatever those are (`mesh_class`: a
+ // cutout or glass is a part of the mesh; one that emits has each instance's emitters in the light
+ // list, `InstMesh::emitters`). A move is the instance's transform (`InstanceRef::moves`).
let g = w.geometries.get(geometry).ok_or_else(|| anyhow!("object {}: unknown geometry {geometry}", n.name))?;
let mat = *retained.materials.get(material).ok_or_else(|| anyhow!("object {}: unknown material {material}", n.name))?;
- let class = mesh_class(&materials[mat as usize]);
- let vc = colored(g, &mut std::iter::once(material));
- {
- let mesh = match retained.own_mesh.get(&(*geometry, mat)) {
- Some(&k) => Some(k),
- None => {
- let (t, a) = own_mesh_tris(g, mat);
- (!t.is_empty()).then(|| {
- let mut im = own_inst_mesh(&t, pool_tris.len() as u32, class);
- if emissive(&materials[mat as usize]) {
- im.emitters = t.len() as u32;
- }
- meshes.push(im);
- put_colors(&mut pool_vcolors, pool_tris.len(), vc.then(|| tri_colors(g, false, None)));
- pool_tris.extend(t);
- pool_attrs.extend(a);
- let k = meshes.len() as u32 - 1;
- retained.own_mesh.insert((*geometry, mat), k);
- k
- })
- }
- };
- if let Some(mesh) = mesh {
- let (lo, hi) = meshes[mesh as usize].placed_bounds(m);
- let pivot = m.transform_point3(Vec3::ZERO);
- let size = hi - lo;
- let oi = (objects.len() / stride) as u32;
- objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);
- *retained.proxy(*id) = Proxy { object: Some(oi), card: None, draw: Draw::Instance(InstanceRef { instance: instances.len() as u32, mesh: MeshKind::Own, moves: n.driven }) };
- instances.push(Instance { mesh, world: m, object: oi, cast_shadow: meshes[mesh as usize].casts(n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, first_emitter: 0 });
+ // Several materials: each geometry group's triangles with its own (three.js's material array).
+ let gpu_mats = mesh_mats.iter().map(|k| retained.materials.get(k).copied().ok_or_else(|| anyhow!("object {}: unknown material {k}", n.name))).collect::<Result<Vec<u32>>>()?;
+ let per_tri = group_materials(g, &gpu_mats);
+ let key = (*geometry, if per_tri.is_some() { gpu_mats } else { vec![mat] });
+ let mesh = match retained.own_mesh.get(&key) {
+ Some(&k) => Some(k),
+ None => {
+ let (t, a, order, im) = own_mesh(g, mat, per_tri.as_deref(), &materials, pool_tris.len() as u32);
+ (!t.is_empty()).then(|| {
+ // Coloured where the triangle's own material asks (each group's; without groups, the mesh's).
+ let wants = |k: &u32| w.materials.get(k).is_some_and(|m| m.vertex_colors);
+ let vc_tri = group_materials(g, &mesh_mats.iter().map(|k| u32::from(wants(k))).collect::<Vec<_>>());
+ let vc = !g.colors.is_empty() && match &vc_tri { Some(v) => v.iter().any(|f| *f == Some(1)), None => wants(material) };
+ let colors = vc.then(|| {
+ let c = tri_colors(g, false, vc_tri.as_deref());
+ order.iter().map(|&k| c[k]).collect()
+ });
+ meshes.push(im);
+ put_colors(&mut pool_vcolors, pool_tris.len(), colors);
+ pool_tris.extend(t);
+ pool_attrs.extend(a);
+ let k = meshes.len() as u32 - 1;
+ retained.own_mesh.insert(key, k);
+ k
+ })
}
+ };
+ if let Some(mesh) = mesh {
+ let (lo, hi) = meshes[mesh as usize].placed_bounds(m);
+ let pivot = m.transform_point3(Vec3::ZERO);
+ let size = hi - lo;
+ let oi = (objects.len() / stride) as u32;
+ objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);
+ retained.edits_meshes |= *own_blas || n.driven;
+ *retained.proxy(*id) = Proxy { object: Some(oi), card: None, draw: Draw::Instance(InstanceRef { instance: instances.len() as u32, mesh: MeshKind::Own, moves: n.driven || w.movable(*id) }) };
+ instances.push(Instance { mesh, world: m, object: oi, cast_shadow: meshes[mesh as usize].casts(n.cast_shadow), name: n.name.clone(), sub: None, hidden: false, first_emitter: 0 });
}
}
Kind::Instanced { geometry, procedural, materials: mats, capacity } if shown => {
@@ -2285,6 +2318,22 @@ pub fn own_mesh_tris(g: &world::Geometry, mat: u32) -> (Vec<[Vec3A; 3]>, Vec<Gpu
(tris, attrs)
}
+/// A mesh's triangles in model space as the pool holds them, ordered by class (`mesh_class`: a geometry of the mesh's
+/// BLAS each), their attributes, where each came from among the geometry's drawn triangles, and the mesh at pool index
+/// `first`. One material, or each group's (`per_tri`: `group_materials`).
+pub fn own_mesh(g: &world::Geometry, mat: u32, per_tri: Option<&[Option<u32>]>, materials: &[GpuMaterial], first: u32) -> (Vec<[Vec3A; 3]>, Vec<GpuTriAttr>, Vec<usize>, InstMesh) {
+ let (mut t, mut flags, mut a) = (vec![], vec![], vec![]);
+ append_arrays(g, Mat4::IDENTITY, mat, 0, per_tri, &mut t, &mut flags, &mut a);
+ let material = |k: usize| &materials[a[k].uv[3].to_bits() as usize];
+ let mut order: Vec<usize> = (0..t.len()).collect();
+ order.sort_by_key(|&k| mesh_class(material(k)));
+ let of = |class: u32| order.iter().filter(|&&k| mesh_class(material(k)) == class).count() as u32;
+ let mut im = own_inst_mesh(&t, first, 0);
+ (im.opaque, im.glass) = (of(0), of(2));
+ im.emitters = order.iter().filter(|&&k| emissive(material(k))).count() as u32;
+ (order.iter().map(|&k| t[k]).collect(), order.iter().map(|&k| a[k]).collect(), order, im)
+}
+
/// A material that emits: a mesh's triangles of it are its instances' emitters in the light list
/// (`InstMesh::emitters`).
pub fn emissive(g: &GpuMaterial) -> bool {
@@ -2333,7 +2382,7 @@ pub fn own_inst_mesh(tris: &[[Vec3A; 3]], first: u32, class: u32) -> InstMesh {
/// The GPU material of each triangle of a mesh with several (`Kind::Mesh::materials`, here GPU indices) by its
/// geometry's groups; None for a triangle in no group (not drawn, as three.js). None for a mesh with one material.
-fn group_materials(g: &world::Geometry, mats: &[u32]) -> Option<Vec<Option<u32>>> {
+pub fn group_materials(g: &world::Geometry, mats: &[u32]) -> Option<Vec<Option<u32>>> {
if mats.len() <= 1 || g.groups.is_empty() {
return None;
}
@@ -2650,6 +2699,34 @@ mod instance_tests {
}
}
+ /// A mesh of several materials (a geometry group each) lies by class, opaque then cutout then glass, whatever the
+ /// order of its groups; each triangle keeps its material, `order` says where it came from among the geometry's
+ /// drawn triangles (one in no group is not drawn), and the mesh counts its parts and the triangles that emit.
+ #[test]
+ fn a_mesh_of_several_materials_lies_by_class() {
+ // Five quads along x: glass, a cutout, one in no group, an opaque one that emits, an opaque one.
+ let (mut positions, mut indices) = (vec![], vec![]);
+ for q in 0..5u32 {
+ let x = q as f32;
+ positions.extend([x, 0.0, 0.0, x + 1.0, 0.0, 0.0, x + 1.0, 1.0, 0.0, x, 1.0, 0.0]);
+ indices.extend([0, 1, 2, 0, 2, 3].map(|i| 4 * q + i));
+ }
+ let g = world::Geometry { normals: [0.0, 0.0, 1.0].repeat(20), uvs: vec![0.0; 40], positions, indices, groups: vec![[0, 6, 0], [6, 6, 1], [18, 6, 2], [24, 6, 3]], colors: vec![] };
+ let materials = [GpuMaterial { layer: [1.0, 1.5, 0.0, 0.0], ..Default::default() }, GpuMaterial { uv2: [0.0, 0.0, 0.0, 0.5], ..Default::default() }, GpuMaterial { emissive: [1.0, 1.0, 1.0, 0.0], ..Default::default() }, GpuMaterial::default()];
+ let per_tri = group_materials(&g, &[0, 1, 2, 3]).unwrap();
+ assert_eq!(per_tri, [Some(0), Some(0), Some(1), Some(1), None, None, Some(2), Some(2), Some(3), Some(3)]);
+ let (t, a, order, im) = own_mesh(&g, 0, Some(&per_tri), &materials, 10);
+ assert_eq!(order, [4, 5, 6, 7, 2, 3, 0, 1], "the opaque triangles, the cutout's, the glass's");
+ assert_eq!(a.iter().map(|a| a.uv[3].to_bits()).collect::<Vec<_>>(), [2, 2, 3, 3, 1, 1, 0, 0]);
+ assert_eq!(t.iter().map(|t| t[0].x.min(t[1].x).min(t[2].x)).collect::<Vec<_>>(), [3.0, 3.0, 4.0, 4.0, 1.0, 1.0, 0.0, 0.0], "each where its material is");
+ assert_eq!((im.first, im.count, im.opaque, im.glass, im.emitters), (10, 8, 4, 2, 2));
+ assert_eq!((im.parts(), im.part_offsets()), (vec![(0, 4, true), (4, 2, true), (6, 2, false)], [4, 6]));
+ assert_eq!((im.lo, im.hi), (Vec3A::new(0.0, 0.0, 0.0), Vec3A::new(5.0, 1.0, 0.0)), "bounds of what is drawn");
+ // One material: as the geometry has them.
+ let (_, a1, order1, one) = own_mesh(&g, 1, None, &materials, 0);
+ assert_eq!((order1, a1.len(), one.opaque, one.glass, one.emitters), ((0..10).collect::<Vec<_>>(), 10, 0, 0, 0), "a cutout mesh");
+ }
+
/// A model's glass is a part of its mesh (tests/render/data/frame-pane.glb: an opaque, a cutout and a glass quad;
/// placed twice): one mesh of three geometries, the glass the one not flagged opaque, nothing flattened; the
/// instances' records say where the second and the third start, and the kernel's feature for it is set.
diff --git a/renderer/src/tables.rs b/renderer/src/tables.rs
index a30c821..caa9c4a 100644
--- a/renderer/src/tables.rs
+++ b/renderer/src/tables.rs
@@ -42,9 +42,12 @@ pub struct Tables {
pub(crate) emissive: HashSet<u32>,
/// A material that starts emitting gets emitter entries in place (the live view sets these up, `prepare`'s
/// `mat_runs` / `fixed_mats`): it is queued in `started_emitting` for live/edits.rs `add_material_emitters`, unless its
- /// triangles include pool or dynamic ones (fixed: a rebuild flattens them). Off: such a material rebuilds.
+ /// triangles include a model's, an instanced object's or dynamic ones (`fixed_mats` less `mesh_mats`, the materials
+ /// whose pool triangles are meshes' alone). Off: such a material rebuilds. `fixed_mats` are also the materials of
+ /// instances' triangles, whose class a rebuild sorts by (`apply`).
pub emit_in_place: bool,
pub fixed_mats: HashSet<u32>,
+ pub mesh_mats: HashSet<u32>,
pub started_emitting: Vec<u32>,
/// Object -> its entries in `lights`.
pub light_index: HashMap<u32, Vec<usize>>,
@@ -73,6 +76,7 @@ impl Tables {
light_tree,
emit_in_place: false,
fixed_mats: HashSet::new(),
+ mesh_mats: HashSet::new(),
started_emitting: vec![],
light_index,
stride: sc.object_stride(),
@@ -247,7 +251,7 @@ impl Tables {
if lum <= 0.0 || self.emissive.contains(&mi) {
return true;
}
- if !self.emit_in_place || self.fixed_mats.contains(&mi) {
+ if !self.emit_in_place || (self.fixed_mats.contains(&mi) && !self.mesh_mats.contains(&mi)) {
return false;
}
self.emissive.insert(mi);
diff --git a/tests/render/shadow-glass-groups-cutout.ts b/tests/render/shadow-glass-groups-cutout.ts
new file mode 100644
index 0000000..7dc8f08
--- /dev/null
+++ b/tests/render/shadow-glass-groups-cutout.ts
@@ -0,0 +1,13 @@
+// shadow/glass-groups, the plane in the cutout square's shadow (its alpha is 1 all over: it blocks as the opaque one
+// does). The point 1 m left of the light's foot against the point 1 m right of it (lit): nothing.
+import type { TestMeta } from "./lib.ts";
+import { at } from "./shadow-glass-model.ts";
+import def, { test as base } from "./shadow-glass-groups.ts";
+
+export const test: TestMeta = {
+ ...base, id: "shadow/glass-groups-cutout",
+ metric: { kind: "ratio", a: at(-1), b: at(1), expected: 0, tolerance: 0.02 },
+ note: "the plane 1 m left of the light's foot (the cutout square's shadow) over the plane 1 m right of it (lit)",
+};
+
+export default def;
diff --git a/tests/render/shadow-glass-groups-frame.ts b/tests/render/shadow-glass-groups-frame.ts
new file mode 100644
index 0000000..585e693
--- /dev/null
+++ b/tests/render/shadow-glass-groups-frame.ts
@@ -0,0 +1,13 @@
+// shadow/glass-groups, the plane in the opaque square's shadow: a shadow ray that culls the mesh's glass still meets
+// its opaque part. The point 2 m left of the light's foot against the point 1 m right of it (lit): nothing.
+import type { TestMeta } from "./lib.ts";
+import { at } from "./shadow-glass-model.ts";
+import def, { test as base } from "./shadow-glass-groups.ts";
+
+export const test: TestMeta = {
+ ...base, id: "shadow/glass-groups-frame",
+ metric: { kind: "ratio", a: at(-2), b: at(1), expected: 0, tolerance: 0.02 },
+ note: "the plane 2 m left of the light's foot (the opaque square's shadow) over the plane 1 m right of it (lit)",
+};
+
+export default def;
diff --git a/tests/render/shadow-glass-groups-live-exact.ts b/tests/render/shadow-glass-groups-live-exact.ts
new file mode 100644
index 0000000..3ef515a
--- /dev/null
+++ b/tests/render/shadow-glass-groups-live-exact.ts
@@ -0,0 +1,8 @@
+// shadow/glass-groups in the real-time renderer without `APPROX.glassShadows`: the offline value. (Under software
+// traversal the mesh is a unit, and a shadow ray skips its glass triangles by their flag.)
+import def, { test as base } from "./shadow-glass-groups.ts";
+import { APPROX, type TestMeta } from "./lib.ts";
+
+export const test: TestMeta = { ...base, id: "shadow/glass-groups-live-exact", metric: { ...base.metric, tolerance: 0.03 }, temporal: true, live: 120, approx: APPROX.all & ~APPROX.glassShadows };
+
+export default def;
diff --git a/tests/render/shadow-glass-groups.ts b/tests/render/shadow-glass-groups.ts
new file mode 100644
index 0000000..df0420e
--- /dev/null
+++ b/tests/render/shadow-glass-groups.ts
@@ -0,0 +1,38 @@
+// A mesh of three materials (three.js's material array, a geometry group each): a glass square, a cutout square whose
+// alpha is 1 all over and a dark opaque one, side by side, as shadow/glass-model's model has them. The geometry has the
+// glass first and the opaque square last, the other way round from the mesh's BLAS (an opaque, a cutout and a glass
+// geometry). A point light (1000 cd) 2 m above an albedo-0.5 Lambert plane, the glass square half way, under the
+// light: the plane below reads 0.5 I / 4 / pi x 0.96 x 0.5. shadow/glass-groups-frame and shadow/glass-groups-cutout
+// read the plane in the other two squares' shadows.
+import { Color, Mesh, MeshPhysicalMaterial, MeshStandardMaterial, PlaneGeometry, PointLight } from "@threert/scene";
+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";
+import { CLEAR } from "./shadow-glass-tint.ts";
+
+export const test: TestMeta = {
+ id: "shadow/glass-groups", features: ["point-light", "transmission", "shadows", "material-groups", "cutout"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: [0.485, 0.48, 0.515, 0.52], expected: CLEAR * 0.96 * 0.5, tolerance: 0.02 },
+ spp: 256,
+ note: "the glass square (0.5 x 0.5 m) at y = 1 under a light at y = 2; the camera's rays to the plane pass under the mesh",
+};
+
+export default function () {
+ const scene = sceneWithSky(0);
+ const l = new PointLight(0xffffff, 1000, 0);
+ l.radius = 0.001;
+ l.position.set(0, 2, 0);
+ // Three squares along x; turned so that the first (the glass) is the one under the light, x -0.25 .. 0.25, the
+ // cutout left of it and the opaque one at x -1.25 .. -0.75.
+ const g = new PlaneGeometry(1.5, 0.5, 3, 1);
+ g.addGroup(0, 6, 0);
+ g.addGroup(6, 6, 1);
+ g.addGroup(12, 6, 2);
+ const dark = new Color().setRGB(0.05, 0.05, 0.05);
+ const pane = new MeshPhysicalMaterial({ name: "pane", color: new Color().setRGB(0.5, 0.5, 0.5), transmission: 1, ior: 1.5, roughness: 0, metalness: 0, side: "double" });
+ const grille = new MeshStandardMaterial({ name: "grille", color: dark, roughness: 1, metalness: 0, alphaTest: 0.5, side: "double" });
+ const frame = new MeshStandardMaterial({ name: "frame", color: dark, roughness: 1, metalness: 0, side: "double" });
+ const m = new Mesh(g, [pane, grille, frame]);
+ m.name = "three";
+ m.rotation.set(-Math.PI / 2, 0, Math.PI);
+ m.position.set(-0.5, 1, 0);
+ return result(scene, camera(scene, [0, 0.6, 3], [0, 0, 0], 50), [l, m, plane(20, lambert(0.5))]);
+}