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.

Scene step D, fourth part: emitters on instances, a model's (#154)

Yujia00ae78aa39ef
diff --git a/docs/PARITY.md b/docs/PARITY.md
index 39707cb..2ebbc00 100644
--- a/docs/PARITY.md
+++ b/docs/PARITY.md
@@ -38,9 +38,9 @@ Engine (renderer + DSL; at the time also the scene IR and its UE adapter, both s
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
space with one BLAS (opaque geometry + cutout geometry), one TLAS instance per placement (transform, shadow mask,
- custom data = instance record), shading transforms the hit triangle; glass, emissive and material-function
- triangles are flattened per placement (shadow rays, emitter sampling), animated / movable / mirrored models
- entirely. `THREERT_INSTANCING=0` flattens everything, `=log` lists what each model instances.
+ custom data = instance record), shading transforms the hit triangle; glass and material-function triangles
+ are flattened per placement (shadow rays, a function's inputs), skinned and mirrored models entirely. A model's
+ triangles that only emit stay in its mesh: each placement's are a run of the light list. `THREERT_INSTANCING=0` flattens everything, `=log` lists what each model instances.
`node tools/check-instancing.ts` renders instanced cutout props (scaled and not) instanced, flattened and through
software traversal, and fails when they differ (crops: `docs/img/bugbot-instanced-cutouts.jpg`).
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index b56cb16..192074d 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2676,6 +2676,30 @@ voxel level's destruction bench runs as before (no fallback, edit 0.7 ms). No co
that hits an instance's emitter to its analytic value (`geometry/emitter-instance`: no test saw that entry). A
model's and an instanced object's emitters are still flattened (the next parts).
+**Emitters on instances: a model's (2026-11-17, scene step D, fourth part).** A model's triangles that only emit
+were flattened at every placement (world space, for light sampling: the reason #147 took away), and a movable or
+posed model re-transformed them on the CPU every frame. They stay in the model's mesh now, as every real-time
+engine has them: a static placement's, a movable model's (the instance moves), and a rigid posed model's moving
+nodes' (`repose_rigid` fills their runs of the light list through the pass). The mesh's emitting triangles are
+numbered among its triangles (`number_emitters`), an instance's are a run of the list. What the build flattens of a
+model is its glass and its material functions, and one case of emitters: a triangle that emits with a cutout on
+exactly its vertices goes with the cutout (Zero Day has one such pair: kept in one mesh the decal's pass-through
+stepped the ray past the emitter, a region 3 % dark; the unbiased check on Zero Day is the guard, and fails
+without the rule; `flatten_coincident`, for a still placement and a rigid model's moving node alike). A mesh that deforms (a shared pose, a skinned model) still flattens its emitters; a model with
+emitters added in place still rebuilds, as before. Flattened a placement: Tokyo 1,800,744 -> 0 triangles, Bistro
+20,638 -> 0, Zero Day 10,105 -> 4, the crowd's Bistro's moving nodes 18,400 -> 0.
+Cost and gain (trace p50, main -> this): the crowd 7.38 -> 7.37 ms and its commit 4.46 -> 3.61 ms (the 18,400
+triangles are no longer re-transformed, uploaded and built again each frame); Bistro 7.20 -> 7.13; Zero Day 7.68
+-> 7.71; **Tokyo 4.47 -> 4.60 (+2.9 %)**. Tokyo's cost is the emitting triangles' being instanced: with every model
+flattened (`THREERT_INSTANCING=0`) both builds read 4.44 to 4.48, and instancing the other 21.3 M triangles costs
+nothing. Its mechanism is not established (ruled out, each by a build: the record's reads, the attributes' and
+the list's order, `emit_mis`'s descents, the shadow rays' ends; it grows with the paths' depth). Taken on the
+user's word (2026-11-17): the mesh whole in its instance is the standard structure, and what direct-light
+resampling and moving a still model in place need; the way back, if wanted, is merging still geometry whole, as
+its own measured step, not taking emitters out of their meshes again.
+Tests: `geometry/emitter-model` (a model's emitters, analytic; tests/render/data/panel.glb), the readback test
+with a model still, movable and posed. Still flattened: an instanced object's copies (the next part).
+
## 2. Temporal fixes
Targets (2026-11-08): bench-temporal, bench-ghosting and their UE MRQ references move to Bistro night (§ 0 step 7); the
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index fd7a697..8cb8474 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -684,11 +684,17 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
emitter_tris.push(e);
}
}
- // (A mesh that emits: its triangles numbered as they lie here, for its instances' emitters.)
+ // (A mesh that emits: its emitting triangles numbered as they lie here, for its instances' emitters.)
for m in sc.meshes.iter().filter(|m| m.emitters > 0) {
- scene::number_emitters(&mut sc.attrs[pool_first + m.first as usize..pool_first + (m.first + m.count) as usize]);
- }
- let moving: std::collections::HashSet<u32> = sc.retained.proxies.values().filter_map(|p| match &p.draw { scene::Draw::Instance(i) if i.moves => Some(i.instance), _ => None }).collect();
+ 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'.)
+ 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(),
+ _ => vec![],
+ }).collect();
for r in 0..sc.instances.len() {
let m = sc.meshes[sc.instances[r].mesh as usize];
if m.emitters == 0 {
@@ -916,7 +922,7 @@ fn flatten_instances(sc: &mut scene::Scene) {
sc.tri_flags.push(scene::instance_tri_flags(&inst, &sc.pool_attrs[k as usize], &sc.materials));
sc.attrs.push(scene::instance_attr(&sc.pool_attrs[k as usize], inst.world, inst.object));
}
- // A second range for the node when its glass / emissive part was flattened at build: node_tris joins them.
+ // A second range for the node when its glass / function part was flattened at build: node_tris joins them.
sc.tri_nodes.push((inst.name, first, sc.tris.len() as u32));
if let Some(i) = inst.sub {
sc.tri_instances.push((first, sc.tris.len() as u32, i));
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 12f4685..1709269 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -781,13 +781,7 @@ impl LiveCore {
self.sc.up.heap.write(q, Table::Instances, lo as u64 * size, bytemuck::cast_slice(&self.sc.gpu_instances[lo..=hi]));
}
self.sc.up.heap.write(q, Table::Objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
- // Their emitters (instances of a mesh that emits): the runs of the light list taken again on the GPU, through
- // the records just queued; the light tree's moving subtree after (`move_emitters`).
- let runs: Vec<[u32; 2]> = placed.iter().map(|&(_, i)| emitter_run(&self.sc.tables.emitter_tris, &self.sc.instances, i)).filter(|r| !r.is_empty()).map(|r| [r.start as u32, r.len() as u32]).collect();
- if !runs.is_empty() {
- self.g.fill_emitter_runs(&self.sc.up, &runs);
- self.emitters_moved = true;
- }
+ self.fill_moved(placed.iter().map(|&(_, i)| i));
self.inst_moved = true;
build.instances = true;
true
@@ -1238,6 +1232,7 @@ impl LiveCore {
if ilo < ihi {
self.sc.up.heap.write(&self.g.queue, Table::Instances, ilo as u64 * size, bytemuck::cast_slice(&self.sc.gpu_instances[ilo..ihi]));
}
+ self.fill_moved(placements.iter().map(|&(i, _)| i));
self.inst_moved = true;
self.sc.up.heap.write(&self.g.queue, Table::Objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
if lo < hi {
@@ -1395,6 +1390,16 @@ impl LiveCore {
Ok(true)
}
+ /// The emitters of instances that moved (those of a mesh that emits): their runs of the light list taken again on
+ /// the GPU, through the records just queued; the light tree's moving subtree after (`move_emitters`).
+ pub(super) fn fill_moved(&mut self, records: impl Iterator<Item = u32>) {
+ let runs: Vec<[u32; 2]> = records.map(|i| emitter_run(&self.sc.tables.emitter_tris, &self.sc.instances, i)).filter(|r| !r.is_empty()).map(|r| [r.start as u32, r.len() as u32]).collect();
+ if !runs.is_empty() {
+ self.g.fill_emitter_runs(&self.sc.up, &runs);
+ self.emitters_moved = true;
+ }
+ }
+
/// The emitters the CPU moves moved: their triangles in the list taken again on the GPU, from the triangles this
/// commit uploaded (`gpu::EmitterFills::moved`); and the light tree's moving subtree refit around them (the CPU copy
/// of the dynamic tail), its nodes and the root uploaded (`ltree::LightTree::refit_moving`).
@@ -1789,7 +1794,7 @@ impl LiveCore {
// An emitting material (no glass, no function): 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).
let emits = scene::emits_only(&gm);
- let class = scene::own_mesh_class(&gm);
+ let class = scene::mesh_class(&gm);
if class == 2 || (emits && capacity.is_some()) {
return Err("a glass or function material (an instanced mesh: emitting too)".into());
}
@@ -1831,7 +1836,7 @@ impl LiveCore {
};
// (A mesh that emits: its triangles numbered as they lie, for its instances' emitters.)
if emits {
- scene::number_emitters(&mut a);
+ scene::number_emitters(&mut a, &tables.materials);
}
// (A unit's cutout triangles carry their flag; hardware traversal has them in a geometry apart.)
let flags = f32::from_bits(if tree.is_some() && class == 1 { scene::TRI_MASKED } else { 0 });
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index aea329d..1ec7375 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -429,9 +429,9 @@ fn list_is_its_triangles(what: &str, c: &LiveCore) {
/// The light list's copies of its emitters' triangles follow them: as loaded, after an emitter the CPU moves has
/// moved (in the light tree's moving subtree, and without a tree), after an emitting mesh a body drives has moved,
-/// after a particle's pass has placed it, and after the edits that make emitters in place (a mesh added, given other
-/// triangles and removed, with the tree's slot for them; a material that starts emitting): each of these also
-/// against a build's picture.
+/// after a model's placement or its clip has moved its emitters, after a particle's pass has placed it, and after
+/// the edits that make emitters in place (a mesh added, given other triangles and removed, with the tree's slot for
+/// them; a material that starts emitting): the moves and edits also against a build's picture.
#[test]
fn the_light_list_holds_its_triangles() {
let presets = crate::default_presets_dir();
@@ -481,6 +481,54 @@ fn the_light_list_holds_its_triangles() {
let rebuilt = live.commit(&mut w).unwrap();
assert!(!(rebuilt && live.g.hwrt), "the driven mesh moved in place ({:?})", live.fallback);
list_is_its_triangles("a driven emitting mesh, moved", &live);
+ // A model's emitters (tests/render/data/panel.glb: a grey quad, then a quad that only emits: its emitting triangles
+ // are not its mesh's first): a placement that stays, one that is movable and moves, and one posed by a clip that
+ // moves its node (a rigid model: the node is an instance), each against a build's picture.
+ let open_at_root = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new(".."), &presets, 96, 54));
+ let model = |animation| Kind::Model { uri: "tests/render/data/panel.glb".into(), nodes: None, animation, functions: vec![] };
+ let slide = |time| Some(crate::desc::Animation { clip: "slide".into(), time, r#loop: true });
+ let small = Vec3::splat(0.05);
+ let mut w = world();
+ w.set_object(30, "still".into(), None, model(None), true, false).unwrap();
+ w.set_transform(30, Vec3::new(-0.6, -0.5, 0.6), glam::Quat::from_rotation_y(0.4), small).unwrap();
+ w.set_object(31, "movable".into(), None, model(None), true, true).unwrap();
+ w.set_transform(31, Vec3::new(0.5, -0.5, 0.6), glam::Quat::IDENTITY, small).unwrap();
+ w.set_object(32, "posed".into(), None, model(slide(0.25)), true, false).unwrap();
+ w.set_transform(32, Vec3::new(0.0, 0.6, 0.4), glam::Quat::IDENTITY, small).unwrap();
+ let mut live = open_at_root(&w).unwrap();
+ 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");
+ // (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| {
+ let records: Vec<u32> = match &live.sc.tables.retained.proxies[&id].draw {
+ scene::Draw::Instance(i) => vec![i.instance],
+ scene::Draw::Rigid(r) => r.instances.iter().map(|&(_, i)| i).collect(),
+ _ => vec![],
+ };
+ let of: Vec<bool> = live.sc.tables.emitter_tris.iter().filter(|e| records.contains(&e.inst)).map(|e| e.moves).collect();
+ (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");
+ 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![
+ ("a movable model moved", Box::new(move |w| w.set_transform(31, Vec3::new(0.2, -0.2, 0.9), glam::Quat::from_rotation_z(0.5), small).unwrap())),
+ ("a posed model's node moved by its clip", Box::new(move |w| w.set_animation(32, slide(0.75)).unwrap())),
+ ];
+ for (what, edit) in &moves {
+ edit(&mut w);
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ list_is_its_triangles(what, &live);
+ let mut fresh = open_at_root(&w).unwrap();
+ forget(&mut live);
+ let (a, b) = (picture(&mut live, 24), picture(&mut fresh, 24));
+ assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));
+ }
+ }
// A light-sampled particle: collapsed as loaded, placed by its pass in the first frame.
let mut w = world();
w.set_particle_fn("spark", "fn pf_spark(i: PIn, p: array<vec4<f32>, 8>) -> POut { return POut(vec3<f32>(0.3, 0.2, 1.0), vec3<f32>(0.05, 0.0, 0.0), vec3<f32>(0.0, 0.05, 0.0), true, vec4<f32>(0.0)); }".into(), String::new());
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index 0f9ca7a..de290f6 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -990,7 +990,7 @@ impl LiveCore {
/// World-space triangles of a node (empty for lights without geometry, cameras, hidden nodes).
pub fn node_tris(&self, id: &str) -> Vec<[glam::Vec3A; 3]> {
- // World-space triangles (an instance's glass / emissive part among them), then its instanced mesh.
+ // World-space triangles (an instance's glass / function part among them), then its instanced mesh.
let mut out: Vec<[glam::Vec3A; 3]> = scene::node_ranges(&self.sc.tri_nodes, id).flat_map(|r| self.sc.tris[r].iter().copied()).collect();
// A model's first instance; every drawn instance of an instanced object.
let mut of_node = self.sc.instances.iter().filter(|i| i.name == id && !i.hidden);
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index 784ca40..b0e7da4 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -50,7 +50,7 @@ pub struct InstMesh {
pub count: u32,
/// The first `opaque` pool triangles are opaque (BLAS geometry 0), the rest cutout (geometry 1, any-hit test).
pub opaque: u32,
- /// Triangles each placement flattens instead (glass, emissive, material functions), in the build's rest arrays.
+ /// Triangles each placement flattens instead (glass, material functions), in the build's rest arrays.
pub rest_first: u32,
pub rest_count: u32,
/// Model-space bounds (object bounds of its instances, picking).
@@ -328,7 +328,7 @@ pub fn instance_tri_flags(inst: &Instance, a: &GpuTriAttr, materials: &[GpuMater
}
/// Triangle ranges of node `id` in build order: one, or two for an instanced node flattened by software traversal (its
-/// glass / emissive part from the build, its mesh appended by `prepare`).
+/// glass / function part from the build, its mesh appended by `prepare`).
pub fn node_ranges<'a>(tri_nodes: &'a [(String, u32, u32)], id: &'a str) -> impl Iterator<Item = std::ops::Range<usize>> + 'a {
tri_nodes.iter().filter(move |(n, _, _)| n == id).map(|(_, a, b)| *a as usize..*b as usize)
}
@@ -712,8 +712,9 @@ pub struct InstancedPlace {
/// A posed glTF model without skins whose clip moves some of its nodes (Zero Day's 551 moving objects): the nodes the
/// clip leaves alone are ordinary static triangles; each moving mesh node is an instance of its own mesh (its triangles
/// in the node's space, one BLAS built once), placed at object x node transform, so a new pose moves instances
-/// only. Their glass / emissive / function triangles are flattened (shadow rays, emitter sampling):
-/// `rest`, re-transformed in place from `rest_local`.
+/// only (a node's emitters are its instance's in the light list, filled again when it moves). Their glass / function
+/// triangles are flattened (shadow rays, a function's inputs), and what `flatten_coincident` takes with them: `rest`,
+/// re-transformed in place from `rest_local`.
#[derive(Clone, Default)]
pub struct RigidModel {
/// (glTF node, instance index).
@@ -1267,7 +1268,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
// Whether a mesh's triangles carry its geometry's vertex colours: any of its materials asks for them.
let colored = |g: &world::Geometry, mats: &mut dyn Iterator<Item = &u32>| !g.colors.is_empty() && mats.filter(|k| w.materials.get(k).is_some_and(|m| m.vertex_colors)).count() > 0;
let mut pool_attrs: Vec<GpuTriAttr> = vec![];
- // Model-space triangles of instanced meshes that each placement flattens (glass, emissive, functions).
+ // Model-space triangles of instanced meshes that each placement flattens (glass, functions).
let mut rest_tris: Vec<[Vec3A; 3]> = vec![];
let mut rest_attrs: Vec<GpuTriAttr> = vec![];
let mut meshes: Vec<InstMesh> = vec![];
@@ -1318,7 +1319,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
// that only emits is: each instance has its emitters in the light list (`InstMesh::emitters`).
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 = own_mesh_class(&materials[mat as usize]);
+ let class = mesh_class(&materials[mat as usize]);
let vc = colored(g, &mut std::iter::once(material));
if class < 2 {
let mesh = match retained.own_mesh.get(&(*geometry, mat)) {
@@ -1462,7 +1463,8 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let mesh_key = (key.clone(), nodes.clone());
// (material index, instancing class: 0 opaque, 1 cutout, 2 flattened per placement: glass (shadow rays
// pass), emissive (emitter sampling), material function)
- let mut resolve = |gm: Option<gltf::Material>| -> Result<(u32, u32)> {
+ // A material of the file: its index, its class in a mesh (`mesh_class`), whether it only emits.
+ let mut resolve = |gm: Option<gltf::Material>| -> Result<(u32, u32, bool)> {
let idx = gm.as_ref().and_then(|g| g.index()).unwrap_or(usize::MAX);
let i = match asset_materials.get(&(key.clone(), idx)) {
Some(i) => *i,
@@ -1487,7 +1489,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
i
}
};
- Ok((i, material_class(&materials[i as usize])))
+ Ok((i, mesh_class(&materials[i as usize]), emits_only(&materials[i as usize])))
};
// A posed model's triangles are dynamic (re-skinned in place). A movable one is an instance whose
// transform moves (hardware RT), unless it has triangles flattened per placement: then they are dynamic
@@ -1531,10 +1533,16 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
for (ni, list) in &by_node {
let w_n = m * globals[*ni];
let mut classed: [Vec<(usize, u32)>; 3] = Default::default();
+ let mut emitting: std::collections::HashSet<u32> = Default::default();
for &k in list {
- let (mat, class) = resolve(local[k].1.material.and_then(|i| doc.materials().nth(i)))?;
+ let (mat, class, emits) = resolve(local[k].1.material.and_then(|i| doc.materials().nth(i)))?;
classed[class as usize].push((k, mat));
+ if emits {
+ emitting.insert(mat);
+ }
}
+ flatten_coincident(&mut classed, &emitting, &|k| local[k].1.p);
+ let emitters = pool_emitters(&classed, &emitting);
if classed[0].len() + classed[1].len() > 0 {
let first_pool = pool_tris.len() as u32;
let (mut lo, mut hi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));
@@ -1556,7 +1564,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
ohi = ohi.max(q);
}
let count = (classed[0].len() + classed[1].len()) as u32;
- meshes.push(InstMesh { first: first_pool, count, opaque: classed[0].len() as u32, rest_first: 0, rest_count: 0, lo, hi, deforms: false, emitters: 0 });
+ meshes.push(InstMesh { first: first_pool, count, opaque: classed[0].len() as u32, rest_first: 0, rest_count: 0, lo, hi, deforms: false, emitters });
rigid.instances.push((*ni, instances.len() as u32));
instances.push(Instance { mesh: meshes.len() as u32 - 1, world: w_n, object: oi, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false, first_emitter: 0 });
}
@@ -1603,8 +1611,10 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let local = glb.triangles(Mat4::IDENTITY, nodes.as_deref(), Some(a))?;
let mut classed: [Vec<(usize, u32)>; 3] = Default::default();
for (k, t) in local.iter().enumerate() {
- let (mat, class) = resolve(t.material.and_then(|i| doc.materials().nth(i)))?;
- classed[class as usize].push((k, mat));
+ // (A mesh that deforms does not keep its emitters: the light list does not follow a
+ // pose yet.)
+ let (mat, class, emits) = resolve(t.material.and_then(|i| doc.materials().nth(i)))?;
+ classed[if emits { 2 } else { class as usize }].push((k, mat));
}
// Triangles flattened per placement (glass, emissive, functions): each model skinned alone.
let g = (classed[2].is_empty() && !local.is_empty()).then(|| {
@@ -1653,32 +1663,20 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
Some(k) => *k,
None => {
// Model-space triangles by class: opaque and cutout ones go to the pool (one BLAS, opaque
- // geometry then cutout geometry); glass, emissive and function triangles are flattened per
- // placement (shadow-ray pass-through, emitter sampling).
+ // geometry then cutout geometry), those that only emit among them (each instance has its
+ // emitters in the light list: `InstMesh::emitters`); glass and function triangles are
+ // flattened per placement (shadow-ray pass-through, a function's world-space inputs).
let local = glb.triangles(Mat4::IDENTITY, nodes.as_deref(), None)?;
let mut classed: [Vec<(usize, u32)>; 3] = Default::default();
+ let mut emitting: std::collections::HashSet<u32> = Default::default();
for (k, t) in local.iter().enumerate() {
- let (mat, class) = resolve(t.material.and_then(|i| doc.materials().nth(i)))?;
+ let (mat, class, emits) = resolve(t.material.and_then(|i| doc.materials().nth(i)))?;
classed[class as usize].push((k, mat));
- }
- // A pool triangle on exactly the same vertices as a flattened one (Zero Day: masked decals
- // over emissive quads of the same shape) is flattened with it. Split between the model's
- // BLAS and the world-space triangles, the two met the ray at one t with different rounding,
- // and a decal hit that its alpha let through stepped the ray past the emitter too (black
- // through the decal; the software BVH, which flattens both, saw the emitter).
- if !classed[2].is_empty() {
- let key = |k: usize| {
- let mut v = local[k].p.map(|p| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]);
- v.sort_unstable();
- v
- };
- let flat: std::collections::HashSet<[[u32; 3]; 3]> = classed[2].iter().map(|&(k, _)| key(k)).collect();
- for c in 0..2 {
- let (stay, go): (Vec<_>, Vec<_>) = classed[c].iter().partition(|&&(k, _)| !flat.contains(&key(k)));
- classed[c] = stay;
- classed[2].extend(go);
+ if emits {
+ emitting.insert(mat);
}
}
+ flatten_coincident(&mut classed, &emitting, &|k| local[k].p);
let k = (classed[0].len() + classed[1].len() > 0).then(|| {
let (first, rest_first) = (pool_tris.len() as u32, rest_tris.len() as u32);
let (mut lo, mut hi) = (Vec3A::splat(f32::MAX), Vec3A::splat(f32::MIN));
@@ -1697,13 +1695,16 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
}
}
let count = (classed[0].len() + classed[1].len()) as u32;
- meshes.push(InstMesh { first, count, opaque: classed[0].len() as u32, rest_first, rest_count: classed[2].len() as u32, lo, hi, deforms: false, emitters: 0 });
+ let emitters = pool_emitters(&classed, &emitting);
+ meshes.push(InstMesh { first, count, opaque: classed[0].len() as u32, rest_first, rest_count: classed[2].len() as u32, lo, hi, deforms: false, emitters });
meshes.len() as u32 - 1
});
if std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "log") {
eprintln!("instancing: {uri} {nodes:?}: {} opaque, {} cutout instanced; {} flattened per placement", classed[0].len(), classed[1].len(), classed[2].len());
}
- if let Some(k) = k.filter(|&k| meshes[k as usize].rest_count == 0) {
+ // (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 && meshes[k as usize].emitters == 0) {
retained.model_mesh.insert(key.clone(), k);
}
mesh_of.insert(key, k);
@@ -1720,7 +1721,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);
retained.proxy(*id).object = Some(oi);
let inst = Instance { mesh, world: m, object: oi, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false, first_emitter: 0 };
- // Its glass / emissive triangles as ordinary world-space ones (same object).
+ // Its glass / function triangles as ordinary world-space ones (same object).
for k in im.rest_first..im.rest_first + im.rest_count {
tris.push(inst.tri(&rest_tris[k as usize]));
tri_flags.push(flags);
@@ -2138,8 +2139,36 @@ pub fn dynamic_tris(w: &World, id: u32, d: &DynamicModel, assets: &Path) -> Resu
})
}
+/// A model's triangles by class (`classed`: opaque, cutout, flattened; each a triangle's index and material): those on
+/// exactly the same vertices leave the mesh together, a pool triangle with a flattened one and one that emits (a
+/// material of `emitting`) with a cutout over it (Zero Day: masked decals over emissive quads of the same shape). A
+/// cutout hit that its alpha lets through steps the ray on past it (trace_hw.wgsl), and past what lies at the same t:
+/// in one BLAS the emitter under the decal went with it (black through the decal). Flattened, the two are in BLASes
+/// apart and the opaque one is met first, as the software BVH has it.
+fn flatten_coincident(classed: &mut [Vec<(usize, u32)>; 3], emitting: &std::collections::HashSet<u32>, p: &dyn Fn(usize) -> [Vec3; 3]) {
+ let key = |k: usize| {
+ let mut v = p(k).map(|p| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]);
+ v.sort_unstable();
+ v
+ };
+ let mut flat: std::collections::HashSet<[[u32; 3]; 3]> = classed[2].iter().map(|&(k, _)| key(k)).collect();
+ let cutouts: std::collections::HashSet<[[u32; 3]; 3]> = classed[1].iter().map(|&(k, _)| key(k)).collect();
+ flat.extend(classed[0].iter().filter(|(_, mat)| emitting.contains(mat)).map(|&(k, _)| key(k)).filter(|v| cutouts.contains(v)));
+ for c in 0..2 {
+ let (stay, go): (Vec<_>, Vec<_>) = classed[c].iter().partition(|&&(k, _)| !flat.contains(&key(k)));
+ classed[c] = stay;
+ classed[2].extend(go);
+ }
+}
+
+/// The emitting triangles a mesh keeps (`InstMesh::emitters`): those of `classed` that stay in the pool.
+fn pool_emitters(classed: &[Vec<(usize, u32)>; 3], emitting: &std::collections::HashSet<u32>) -> u32 {
+ classed[..2].iter().flatten().filter(|(_, mat)| emitting.contains(mat)).count() as u32
+}
+
/// Instancing class of a GPU material: 0 opaque, 1 cutout (any-hit), 2 flattened per placement (glass: shadow rays pass;
-/// emissive: emitter sampling; material functions).
+/// material functions; emissive, where the light list does not follow the mesh: one that deforms, an instanced
+/// object's copies. Elsewhere `mesh_class`).
pub fn material_class(g: &GpuMaterial) -> u32 {
let flat = g.layer[0] > 0.0 || g.tex1[3] != 0 || g.emissive[..3].iter().any(|e| *e > 0.0);
if flat {
@@ -2199,18 +2228,22 @@ pub fn emits_only(g: &GpuMaterial) -> bool {
g.layer[0] <= 0.0 && g.tex1[3] == 0 && g.emissive[..3].iter().any(|e| *e > 0.0)
}
-/// `material_class` for an `own_blas` mesh: one that only emits is opaque or cutout, not flattened.
-pub fn own_mesh_class(g: &GpuMaterial) -> u32 {
+/// `material_class` in a mesh whose instances have their emitters in the light list (an `own_blas` mesh, a model's
+/// that does not deform): a material that only emits is opaque or cutout there, not flattened.
+pub fn mesh_class(g: &GpuMaterial) -> u32 {
if emits_only(g) { u32::from(g.uv2[3] > 0.0) } else { material_class(g) }
}
-/// Numbers an emitting mesh's triangles (their attributes' x.w = the number + 1): an instance's emitter of a
-/// triangle is its first plus the number. Returns how many.
-pub fn number_emitters(attrs: &mut [GpuTriAttr]) -> u32 {
- for (k, a) in attrs.iter_mut().enumerate() {
- a.x[3] = f32::from_bits(k as u32 + 1);
+/// Numbers a mesh's triangles that emit (those of a material that only emits; their attributes' x.w = the number +
+/// 1, the others' 0): an instance's emitter of a triangle is its first plus the number. Returns how many.
+pub fn number_emitters(attrs: &mut [GpuTriAttr], materials: &[GpuMaterial]) -> u32 {
+ let mut n = 0;
+ for a in attrs.iter_mut() {
+ let emits = materials.get(a.uv[3].to_bits() as usize).is_some_and(emits_only);
+ n += u32::from(emits);
+ a.x[3] = f32::from_bits(if emits { n } else { 0 });
}
- attrs.len() as u32
+ n
}
/// The `InstMesh` of an `own_blas` mesh's triangles at pool index `first` (class: `material_class`, 0 or 1).
@@ -2467,6 +2500,32 @@ mod instance_tests {
assert_eq!((sc.instances.len(), sc.tris.len(), sc.tri_instances.iter().map(|r| r.2).collect::<Vec<_>>()), (0, 2, vec![0, 1]), "mirrored: the drawn copies flattened");
}
+ /// A cutout on exactly an emitter's vertices leaves the mesh with it (`flatten_coincident`), in a model that stays
+ /// and in a rigid model's moving node (tests/render/data/panel-decal.glb: panel.glb, a grey quad and an emitting
+ /// one, with a masked quad on the emitting one's vertices): each mesh keeps the grey quad alone.
+ #[test]
+ fn a_cutout_on_an_emitter_is_flattened_with_it() {
+ let mut w = World::default();
+ let cam = serde_json::from_value(serde_json::json!({ "fov": 50, "near": 0.1, "far": 100, "exposure": { "mode": "manual", "ev100": 0 } })).unwrap();
+ w.set_object(9, "camera".into(), None, Kind::Camera(cam), true, false).unwrap();
+ w.set_settings(world::Settings { camera: Some(9), ..Default::default() });
+ let model = |animation| Kind::Model { uri: "tests/render/data/panel-decal.glb".into(), nodes: None, animation, functions: vec![] };
+ w.set_object(1, "still".into(), None, model(None), true, false).unwrap();
+ w.set_object(2, "posed".into(), None, model(Some(desc::Animation { clip: "slide".into(), time: 0.25, r#loop: true })), true, false).unwrap();
+ let sc = build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();
+ let mesh = |name: &str| {
+ let m = &sc.meshes[sc.instances.iter().find(|i| i.name == name).unwrap().mesh as usize];
+ (m.count, m.rest_count, m.emitters)
+ };
+ assert_eq!((mesh("still"), mesh("posed")), ((2, 4, 0), (2, 0, 0)), "(triangles in the mesh, flattened a placement, emitters in the mesh)");
+ let count = |f: &dyn Fn(usize) -> bool| (0..sc.tris.len()).filter(|&k| f(k)).count();
+ let emits = |k: usize| sc.materials[sc.attrs[k].uv[3].to_bits() as usize].emissive[..3].iter().any(|e| *e > 0.0);
+ let flattened = (sc.tris.len(), count(&emits), count(&|k| sc.tri_flags[k] & TRI_MASKED != 0), count(&|k| sc.tri_flags[k] & TRI_DYNAMIC != 0));
+ assert_eq!(flattened, (8, 4, 4, 4), "flattened: (triangles, emitting, cutout, the moving node's)");
+ let Draw::Rigid(r) = &sc.retained.proxies[&2].draw else { panic!("the posed model is rigid") };
+ assert_eq!((r.instances.len(), r.rest.mats.len()), (1, 4));
+ }
+
#[test]
fn node_ranges_returns_every_range() {
let nodes = vec![("lamp".to_string(), 10, 12), ("box".to_string(), 12, 20), ("lamp".to_string(), 40, 90)];
diff --git a/tests/render/data/panel-decal.glb b/tests/render/data/panel-decal.glb
new file mode 100644
index 0000000..a85b7a1
Binary files /dev/null and b/tests/render/data/panel-decal.glb differ
diff --git a/tests/render/data/panel.glb b/tests/render/data/panel.glb
new file mode 100644
index 0000000..6678000
Binary files /dev/null and b/tests/render/data/panel.glb differ
diff --git a/tests/render/geometry-emitter-model.ts b/tests/render/geometry-emitter-model.ts
new file mode 100644
index 0000000..2cba67f
--- /dev/null
+++ b/tests/render/geometry-emitter-model.ts
@@ -0,0 +1,31 @@
+// A model's triangles that only emit stay in its mesh, and each placement's are in the light list (scene.rs
+// `InstMesh::emitters`): light sampling finds them where the placement puts them, and a ray that hits one is weighed
+// against that emitter. tests/render/data/panel.glb (a small grey quad, then an 8 x 8 m quad of 1 nit: the emitting
+// triangles are not the mesh's first), placed twice: far away at a hundredth of its size (it holds the list's first
+// entries), and facing down 1 m above a Lambert 0.5 floor. As geometry/emitter-instance: the floor below the centre
+// reads 0.5 / pi x 2.989.
+import { GLTFModel } from "@threert/scene";
+import { camera, lambert, plane, result, sceneWithSky, type TestMeta } from "./lib.ts";
+
+const corner = (x: number, y: number) => (x / Math.sqrt(1 + x * x)) * Math.atan(y / Math.sqrt(1 + x * x)) + (y / Math.sqrt(1 + y * y)) * Math.atan(x / Math.sqrt(1 + y * y));
+const E = 4 * (1 / 2) * corner(4, 4);
+const URI = "tests/render/data/panel.glb";
+
+export const test: TestMeta = {
+ id: "geometry/emitter-model", features: ["emitters", "lambert", "instancing", "gltf"], reference: "analytic", temporal: false,
+ metric: { kind: "radiance", region: [0.48, 0.47, 0.52, 0.53], expected: (0.5 / Math.PI) * E, tolerance: 0.03 },
+ requires: [URI],
+ spp: 256,
+ note: "camera under the panel at (3, 0.8, 0) looking at the floor point below its centre",
+};
+
+export default () => {
+ const scene = sceneWithSky(0);
+ const far = new GLTFModel(URI);
+ far.position.set(900, -50, 0);
+ far.scale.setScalar(0.01);
+ const panel = new GLTFModel(URI);
+ panel.rotation.x = Math.PI / 2;
+ panel.position.y = 1;
+ return result(scene, camera(scene, [3, 0.8, 0], [0, 0, 0]), [plane(40, lambert(0.5), "floor"), far, panel]);
+};