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, third part: emitters on instances, a mesh of its own (#152)

Yujiaeb115c9dd30f
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index b1270f3..b56cb16 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2657,6 +2657,25 @@ within their own spread, the two light-sampled particle tests in their last bits
other code); Bistro and the crowd within main's own run-to-run difference. Next: emitters on instances, their runs
filled by the same pass through the instance's matrix.
+**Emitters on instances: a mesh of its own (2026-11-17, scene step D, third part).** A mesh with its own BLAS
+whose material only emits was a case apart: its triangles written in world space at an identity placement, never
+shared, rebuilt to move. It is a mesh as any other now: in model space, shared by the objects of its geometry and
+material, placed by its instance's matrix, moved by the instance when a body drives it. The light list has a run
+an instance (`Instance::first_emitter`: its first, carried in its record; the mesh's triangles are numbered in their
+attributes, `InstMesh::emitters`), each emitter with its triangle in world space and the instance that places it
+(`GpuEmitterTri::inst`, where the object was): a light sample still reads no matrix, and takes its attributes
+through the instance as a hit does (the object, the texture LOD's offset). A ray that hits an emitting triangle
+finds its emitter at the instance's first plus the triangle's number. An instance that moves has its run filled by
+the pass through its matrix. The edits in place work as before (a mesh added, given other triangles, removed: the
+instance's run reused or left at no weight). Under software traversal a unit's two flags share a word, and the
+word freed is every instance's first emitter. Pictures: the tests with such a mesh render other samples (13 of
+the suite's outputs differ from before, sums within 1e-4, every verdict as before); the voxel night level, whose
+192 lamps are instances of shared meshes now, reads the same to 0.15 % over a 4 x 4 grid, with 0.4 MB less BLAS; the
+voxel level's destruction bench runs as before (no fallback, edit 0.7 ms). No cost: the trace on Bistro 7.17 ->
+7.10 ms, the crowd 7.33 -> 7.29, the night level 4.16 -> 4.16. A new test holds the weight of a ray
+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).
+
## 2. Temporal fixes
Targets (2026-11-08): bench-temporal, bench-ghosting and their UE MRQ references move to Bistro night (§ 0 step 7); the
@@ -4411,6 +4430,8 @@ benchmark level. The order follows the dependencies; a step that meets a further
build gives them emitter entries (in the light tree with the static emitters); the live view's in-place edits
add, replace and remove them: a placed mesh's entries go to area 0 (their weight; the tree keeps its shape and
is refit), new ones are appended to the CDF's power-share part (path code 0, as the tree's moving emitters).
+ (Since 2026-11-17 such a mesh is a mesh as any other, in model space and shared, and each instance's emitters
+ are a run of the light list: § 1, "Emitters on instances".)
- A material that starts emitting gets emitter entries in place from its flattened static triangles (`prepare`
keeps each material's runs of them); one that also covers pool (instanced) or dynamic triangles still rebuilds.
- The emitter buffer grows (and the scene's bind group is made again) only when entries are added past it: a
diff --git a/renderer/shaders/emitter_fill.wgsl b/renderer/shaders/emitter_fill.wgsl
index d20803c..e429ebd 100644
--- a/renderer/shaders/emitter_fill.wgsl
+++ b/renderer/shaders/emitter_fill.wgsl
@@ -1,11 +1,17 @@
// The light list's triangles (lib.rs `GpuEmitterTri`) taken again from where their triangles are now: what real-time
// engines' "prepare lights" pass does. One run of the list an invocation row (gpu.rs `EmitterFill`): the emitters
-// something has moved since the list was written (the triangles the CPU reposed, the particles their passes place).
+// something has moved since the list was written (the triangles the CPU reposed, the particles their passes place,
+// the instances that moved).
struct Run { first: u32, count: u32 };
@group(0) @binding(0) var<storage, read> runs: array<Run>;
@group(0) @binding(1) var<storage, read> verts: array<vec4<f32>>;
-// Three vec4s an emitter: (v0, its triangle), (e1, its object), (e2, its path code). The words stay.
+// Three vec4s an emitter: (v0, its triangle), (e1, its instance), (e2, its path code). The words stay.
@group(0) @binding(2) var<storage, read_write> list: array<vec4<u32>>;
+// The instances' records (scene.rs `GpuInstance`: the first three vec4s are the rows of the instance's matrix). Read
+// only: they are a section of the buffer the list is one of, and a buffer is not bound to read and to write at once.
+@group(0) @binding(3) var<storage, read_write> instances: array<vec4<f32>>;
+const INSTANCE_VEC4: u32 = 10u;
+const NO_INST: u32 = 0xffffffffu;
@compute @workgroup_size(64)
fn fill(@builtin(global_invocation_id) id: vec3<u32>) {
@@ -13,7 +19,19 @@ fn fill(@builtin(global_invocation_id) id: vec3<u32>) {
if (id.x >= run.count) { return; }
let r = (run.first + id.x) * 3u;
let t = list[r].w * 3u;
+ var rows = array<vec3<f32>, 3>(verts[t].xyz, verts[t + 1u].xyz, verts[t + 2u].xyz);
+ // An instance's emitter: its mesh's triangle (v0, e1, e2 in model space) placed by the instance.
+ let inst = list[r + 1u].w;
+ if (inst != NO_INST) {
+ let m0 = instances[inst * INSTANCE_VEC4];
+ let m1 = instances[inst * INSTANCE_VEC4 + 1u];
+ let m2 = instances[inst * INSTANCE_VEC4 + 2u];
+ for (var k = 0u; k < 3u; k++) {
+ rows[k] = vec3<f32>(dot(m0.xyz, rows[k]), dot(m1.xyz, rows[k]), dot(m2.xyz, rows[k]));
+ }
+ rows[0] += vec3<f32>(m0.w, m1.w, m2.w);
+ }
for (var k = 0u; k < 3u; k++) {
- list[r + k] = vec4<u32>(bitcast<vec3<u32>>(verts[t + k].xyz), list[r + k].w);
+ list[r + k] = vec4<u32>(bitcast<vec3<u32>>(rows[k]), list[r + k].w);
}
}
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index 0e8b1ab..d322c5c 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -187,9 +187,9 @@ fn energy_at(i: u32) -> vec4<f32> { return table_f(P.table_first[2].y + i); }
fn glass_energy_at(i: u32) -> vec4<f32> { return table_f(P.table_first[2].z + i); }
// An emitter's triangle (lib.rs `GpuEmitterTri`): in world space, the light list's own copy, so a light sample reads
// no placement (what moves it is copied again: emitter_fill.wgsl); `tri`: its triangle in the triangles' table
-// (attributes), `obj`: its object-table index (power), `code`: the light tree's path code (0: not one of the
-// tree's), EMITTER_MOVES if it moves.
-struct EmitterTri { v0: vec3<f32>, tri: u32, e1: vec3<f32>, obj: u32, e2: vec3<f32>, code: u32 };
+// (attributes: `emitter_attrs`), `inst`: the instance that places it (NO_INST: none), `code`: the light tree's path
+// code (0: not one of the tree's), EMITTER_MOVES if it moves.
+struct EmitterTri { v0: vec3<f32>, tri: u32, e1: vec3<f32>, inst: u32, e2: vec3<f32>, code: u32 };
const EMITTER_TRI_VEC4: u32 = 3u;
const EMITTER_MOVES: u32 = 0x80000000u;
fn emitter_tri_at(i: u32) -> EmitterTri {
@@ -282,6 +282,11 @@ fn inst_vec(r: Instance, v: vec3<f32>) -> vec3<f32> { return vec3<f32>(dot(r.m0.
fn inst_normal(r: Instance, n: vec4<f32>) -> vec4<f32> {
return vec4<f32>(normalize(vec3<f32>(dot(r.n0.xyz, n.xyz), dot(r.n1.xyz, n.xyz), dot(r.n2.xyz, n.xyz))), n.w);
}
+// A model-space triangle's `x` (texel density, object, ...) as its instance has it: the instance's texture LOD offset
+// and object (the record's `info`).
+fn inst_x(info: vec4<u32>, x: vec4<f32>) -> vec4<f32> {
+ return vec4<f32>(x.x + bitcast<f32>(info.z), bitcast<f32>(info.y), x.z, x.w);
+}
// A model-space triangle's shading attributes placed by instance r (scene::instance_attr).
fn inst_attr(r: Instance, a: TriAttr) -> TriAttr {
var b = a;
@@ -289,7 +294,7 @@ fn inst_attr(r: Instance, a: TriAttr) -> TriAttr {
b.n1 = inst_normal(r, a.n1);
b.n2 = inst_normal(r, a.n2);
b.t = vec4<f32>(normalize(inst_vec(r, a.t.xyz)), a.t.w);
- b.x = vec4<f32>(a.x.x + bitcast<f32>(r.info.z), bitcast<f32>(r.info.y), a.x.z, a.x.w);
+ b.x = inst_x(r.info, a.x);
return b;
}
@@ -453,15 +458,15 @@ fn emitter_draw(x: vec3<f32>, n: vec3<f32>, rd: u32) -> EPick {
return EPick(e, p * e.z / wsum, e.z);
}
-// With the tree: the probability that emitter_draw(x, n) picks emitter `ei` (`em`; `a`: its triangle's attributes),
-// the same choices down its path (its code; 0: picked by its share of power).
+// With the tree: the probability that emitter_draw(x, n) picks emitter `ei` (`em`; `a`: its attributes,
+// `emitter_attrs`), the same choices down its path (its code; 0: picked by its share of power).
fn emitter_sel(ei: u32, em: EmitterTri, a: TriAttr, x: vec3<f32>, n: vec3<f32>) -> f32 {
let code = em.code & ~EMITTER_MOVES;
if (code == 0u) {
if (P.misc.y <= 0.0) { return 0.0; }
var area = 0.5 * length(cross(em.e1, em.e2));
if (has(F_PEMIT) && a.x.z > 0.0) { area = a.x.z; }
- return luminance(material_at(bitcast<u32>(a.uv.w)).emissive.rgb) * power_of(em.obj) * area / P.misc.y;
+ return luminance(material_at(bitcast<u32>(a.uv.w)).emissive.rgb) * obj_power(a) * area / P.misc.y;
}
let depth = (code >> LT_PATH_BITS) - 1u;
var p = 1.0 - P.ltree.z;
@@ -1129,8 +1134,7 @@ override OBJECT_STRIDE: u32 = select(3u, 4u, (FEAT & F_TINT) != 0u);
// An instanced object's instance colour (three.js `instanceColor`), white for every other object.
fn obj_tint(oi: u32) -> vec3<f32> { return object_at(oi * OBJECT_STRIDE + 3u).rgb; }
// Instance power (UE material "Power", scripts animate it): scales the emission of everything the node draws.
-fn power_of(oi: u32) -> f32 { return object_at(oi * OBJECT_STRIDE).w; }
-fn obj_power(a: TriAttr) -> f32 { return power_of(object_of(a)); }
+fn obj_power(a: TriAttr) -> f32 { return object_at(object_of(a) * OBJECT_STRIDE).w; }
// Inputs at a point of triangle ti (barycentrics u, v) for material functions outside full shading (alpha, NEE).
fn mat_in_at(ti: u32, u: f32, v: f32, view: vec3<f32>, lod: f32) -> MatIn {
@@ -1819,17 +1823,28 @@ fn sun_disks(d: vec3<f32>, pdf: f32) -> vec3<f32> {
return c;
}
+// What light sampling reads of an emitter's attributes (UVs, material, object, texel density), as shading has them
+// at a hit of it: its triangle's, with its instance's object and texture LOD offset if it has one. (Not the normals
+// and the tangent, which stay the mesh's: a light sample reads none, and placing them is work a sample.)
+fn emitter_attrs(em: EmitterTri) -> TriAttr {
+ var a = attrs[em.tri];
+ if (has(F_INST) && em.inst != NO_INST) { a.x = inst_x(instance_at(em.inst).info, a.x); }
+ return a;
+}
+
// MIS weight of emission that a BSDF-sampled ray (pdf `pdf`) hit, against emitter sampling in `direct_light`.
// Without sampled emitters (only material functions emit, e.g. facade windows) the BSDF ray is the only estimator.
// It weighs by emitted power alone, as emitter sampling's MIS does with or without light LOD (sample_emitter_ris).
fn emit_mis(hit: Hit, d: vec3<f32>, pdf: f32) -> f32 {
// Procedural surfaces are not light-sampled (no emitter entries): the BSDF ray is the only estimator.
if (is_proc(hit) || P.counts.y == 0u) { return 1.0; }
- // The hit triangle's emitter (its attributes' x.w: the entry + 1; 0: it is not light-sampled).
- let ha = attrs[hit.tri];
- let entry = bitcast<u32>(ha.x.w);
+ // The hit triangle's emitter: its attributes' x.w is the entry + 1 (0: it is not light-sampled), counted from its
+ // instance's first entry (the record's n2.w) when an instance places it.
+ var entry = bitcast<u32>(attrs[hit.tri].x.w);
if (entry == 0u) { return 1.0; }
+ if (has(F_INST) && hit.inst != NO_INST) { entry += bitcast<u32>(instance_at(hit.inst).n2.w); }
let em = emitter_tri_at(entry - 1u);
+ let ha = emitter_attrs(em);
let cr = cross(em.e1, em.e2);
let area = 0.5 * length(cr);
let cos_l = abs(dot(normalize(cr), d));
@@ -1841,7 +1856,7 @@ fn emit_mis(hit: Hit, d: vec3<f32>, pdf: f32) -> f32 {
}
if (P.misc.y <= 0.0 || emitter_culled(em)) { return 1.0; }
let mat = material_at(bitcast<u32>(ha.uv.w));
- let pdf_a = luminance(mat.emissive.rgb) * power_of(em.obj) / P.emit_power.x;
+ let pdf_a = luminance(mat.emissive.rgb) * obj_power(ha) / P.emit_power.x;
let pdf_w = pdf_a * hit.t * hit.t / max(cos_l, 1e-6);
if (!has(F_PEMIT) || ha.x.z == 0.0) { return power_heuristic(pdf, pdf_w); }
// Particles (x.z > 0): a nominal area is what the CDF weighed them by, the point is uniform over the actual area.
@@ -2100,10 +2115,10 @@ struct ES { le: vec3<f32>, l: vec3<f32>, dist: f32, pdf_w: f32, w: f32 };
// Emitted radiance of an emitter at (b1, b2) toward -l (emissive map, animation, material function, node power).
fn emitter_radiance(em: EmitterTri, b1: f32, b2: f32, l: vec3<f32>) -> vec3<f32> {
- let a = attrs[em.tri];
+ let a = emitter_attrs(em);
let m = material_at(bitcast<u32>(a.uv.w));
// 5 cm footprint: a blurred texel is plenty for lighting and keeps NEE cheap.
- let pw = power_of(em.obj);
+ let pw = obj_power(a);
var le = emission(m, mesh_uv(a, m, b1, b2), mesh_lod(a, m) + log2(0.05)) * pw;
if (has(F_FUNC) && m.tex1.w > 0) {
var mb = mat_base(m);
diff --git a/renderer/shaders/trace_units.wgsl b/renderer/shaders/trace_units.wgsl
index 023e572..6ad5396 100644
--- a/renderer/shaders/trace_units.wgsl
+++ b/renderer/shaders/trace_units.wgsl
@@ -4,12 +4,12 @@
//
// A unit is a model instance (`instances`, as hardware traversal's): its mesh's triangles in model space in
// `tri_verts`, from the record's first triangle; its mesh's tree in `nodes`, from the root in the record's `n0.w`
-// (child indices count from that root, a leaf's triangles from the mesh's first). `n1.w`: the unit casts shadows.
+// (child indices count from that root, a leaf's triangles from the mesh's first). `n1.w` (bits): its flags.
// The top tree, over the units' world boxes, starts at node `P.motion.z` (bits; child indices count from it); each of
// its leaves is one unit, `left_or_first` its record. `P.motion.w` (bits): how many units there are. (`P.motion.y`
-// is `render --signals`'.) `n2.w` (bits): the unit is placed by a translation alone, its normal rows the identity's
-// (units.rs `unit_record`): the ray keeps its direction and only its origin moves, which is what the rows would have
-// made of it.
+// is `render --signals`'.) The flags (units.rs `unit_record`): UNIT_SHADOW, the unit casts shadows; UNIT_SHIFTED, it
+// is placed by a translation alone, its normal rows the identity's: the ray keeps its direction and only its origin
+// moves, which is what the rows would have made of it.
//
// `trace` walks the still scene first and calls this with its hit: the ray is already cut to it.
//
@@ -33,6 +33,8 @@
//
// The root's box is tested before the walk: a ray that meets no unit reads one node, and a scene of one unit is a
// root that is a leaf, whose record only the rays that meet its box read.
+const UNIT_SHADOW: u32 = 1u;
+const UNIT_SHIFTED: u32 = 2u;
@if(units) var<private> stack: array<u32, 64>;
@if(units) fn trace_units(o: vec3<f32>, d: vec3<f32>, inv_d: vec3<f32>, hit_in: Hit, mode: u32) -> Hit {
@@ -78,10 +80,10 @@
// A top leaf: one unit. The ray in the unit's space (its direction not renormalised: t is the world's):
// `proc_point`, `proc_dir`, or the origin moved alone.
let u = instance_at(n.left_or_first);
- if (mode != TRACE_SHADOW || bitcast<u32>(u.n1.w) != 0u) {
+ if (mode != TRACE_SHADOW || (bitcast<u32>(u.n1.w) & UNIT_SHADOW) != 0u) {
rec = n.left_or_first;
ro = o - vec3<f32>(u.m0.w, u.m1.w, u.m2.w);
- if (bitcast<u32>(u.n2.w) == 0u) {
+ if ((bitcast<u32>(u.n1.w) & UNIT_SHIFTED) == 0u) {
ro = proc_dir(u, ro);
rd = proc_dir(u, d);
rinv = 1.0 / select(rd, vec3<f32>(1e-20), abs(rd) < vec3<f32>(1e-20));
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index f0c1a7c..75e8820 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -2831,7 +2831,7 @@ impl Gpu {
}
fn emitter_fill_bind_group(&self, runs: &wgpu::Buffer, verts: &wgpu::Buffer, heap: &Heap<Table>) -> wgpu::BindGroup {
- let entries = [buffer_entry(0, runs), buffer_entry(1, verts), wgpu::BindGroupEntry { binding: 2, resource: heap.binding(Table::EmitterTris) }];
+ let entries = [buffer_entry(0, runs), buffer_entry(1, verts), wgpu::BindGroupEntry { binding: 2, resource: heap.binding(Table::EmitterTris) }, wgpu::BindGroupEntry { binding: 3, resource: heap.binding(Table::Instances) }];
self.device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("emitter fill"), layout: &self.emitter_fill_pipeline().get_bind_group_layout(0), entries: &entries })
}
@@ -2850,6 +2850,14 @@ impl Gpu {
Some(EmitterFill { bg: self.emitter_fill_bind_group(&buffer, verts, heap), runs: buffer, count: runs.len() as u32, longest })
}
+ /// `runs` of the light list taken again now (the instances an edit just moved: their records are queued).
+ pub fn fill_emitter_runs(&self, up: &Uploaded, runs: &[[u32; 2]]) {
+ let Some(f) = self.emitter_fill(runs, &up.verts, &up.heap) else { return };
+ let mut e = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("emitter fill") });
+ self.fill_emitters(&f, &mut e);
+ self.queue.submit([e.finish()]);
+ }
+
/// The runs of `f` taken again from their triangles as the encoder's earlier commands, and the writes queued
/// before it is submitted, leave them.
pub fn fill_emitters(&self, f: &EmitterFill, e: &mut wgpu::CommandEncoder) {
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index fcaebe0..fd7a697 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -112,7 +112,7 @@ pub fn emitter_tri(k: usize, tri_verts: &[[f32; 4]], a: &scene::GpuTriAttr, mate
}
let c = v(0) + (e1 + e2) / 3.0;
let moves = tri_verts[k * 3][3].to_bits() & scene::TRI_DYNAMIC != 0;
- Some(EmitterTri { tri: k as u32, mat, obj: a.x[1].to_bits(), area, c: c.to_array(), moves, nominal, in_tree: false })
+ Some(EmitterTri { tri: k as u32, mat, obj: a.x[1].to_bits(), area, c: c.to_array(), moves, nominal, in_tree: false, inst: NO_INST })
}
/// An emissive triangle of the emitter CDF: triangle (traversal order), material, object, area.
@@ -131,23 +131,29 @@ pub struct EmitterTri {
pub nominal: bool,
/// One of the light tree's (`ltree`): its CDF entry is in the tree's range, at the start of the CDF.
pub in_tree: bool,
+ /// The instance that places its triangle (its record; the triangle is the mesh's, in model space), or `NO_INST`:
+ /// a triangle in world space.
+ pub inst: u32,
}
+/// No instance (pathtrace.wgsl `NO_INST`).
+pub const NO_INST: u32 = u32::MAX;
+
/// `GpuEmitterTri::code`: the emitter moves (`EmitterTri::moves`). Path codes are below it.
pub const EMITTER_MOVES: u32 = 1 << 31;
const _: () = assert!((ltree::PATH_BITS + 2) << ltree::PATH_BITS <= EMITTER_MOVES);
/// An emitter's triangle as the kernel's light sampling reads it (pathtrace.wgsl `EmitterTri`; `Table::EmitterTris`,
/// entry i for `emitter_tris[i]`): in world space, the light list's own copy, so a sample reads no placement. v0, e1,
-/// e2 as the triangles' table has them; its triangle there (attributes); its object-table index (power); the light
-/// tree's path code (0: not one of the tree's) with `EMITTER_MOVES`.
+/// e2 in world space; its triangle in the triangles' table (attributes); the instance that places it (`NO_INST`: the
+/// triangle is in world space there too); the light tree's path code (0: not one of the tree's) with `EMITTER_MOVES`.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
pub struct GpuEmitterTri {
pub v0: [f32; 3],
pub tri: u32,
pub e1: [f32; 3],
- pub obj: u32,
+ pub inst: u32,
pub e2: [f32; 3],
pub code: u32,
}
@@ -156,7 +162,7 @@ impl GpuEmitterTri {
/// `e`'s, from its triangle's rows (v0, e1, e2: `Prepared::tri_verts`), with path code `code`.
pub fn new(e: &EmitterTri, rows: &[[f32; 4]], code: u32) -> GpuEmitterTri {
let v = |r: usize| [rows[r][0], rows[r][1], rows[r][2]];
- GpuEmitterTri { v0: v(0), tri: e.tri, e1: v(1), obj: e.obj, e2: v(2), code: code | if e.moves { EMITTER_MOVES } else { 0 } }
+ GpuEmitterTri { v0: v(0), tri: e.tri, e1: v(1), inst: e.inst, e2: v(2), code: code | if e.moves { EMITTER_MOVES } else { 0 } }
}
/// As `new`, from its vertices.
@@ -164,11 +170,34 @@ impl GpuEmitterTri {
let (e1, e2) = (b - a, c - a);
GpuEmitterTri::new(e, &[[a.x, a.y, a.z, 0.0], [e1.x, e1.y, e1.z, 0.0], [e2.x, e2.y, e2.z, 0.0]], code)
}
+
+ /// Its vertices.
+ pub fn vertices(&self) -> [[f32; 3]; 3] {
+ let at = |e: [f32; 3]| [self.v0[0] + e[0], self.v0[1] + e[1], self.v0[2] + e[2]];
+ [self.v0, at(self.e1), at(self.e2)]
+ }
+}
+
+/// The emitters of an instance of a mesh that emits (`scene::InstMesh::emitters`, `count` of them): one a numbered
+/// triangle, in the numbers' order, each with its triangle as the instance places it. `tris`: the mesh's, in model
+/// space; `first`: its first triangle in the triangles' table; `numbered(k)`: triangle k's number and material, if
+/// it emits; `record`: the instance's. A hidden instance's, and a triangle of no area: no weight (area 0).
+pub fn instance_emitters(inst: &scene::Instance, record: u32, tris: &[[glam::Vec3A; 3]], first: u32, numbered: &dyn Fn(usize) -> Option<(usize, u32)>, count: usize, materials: &[scene::GpuMaterial], moves: bool) -> Vec<(EmitterTri, [glam::Vec3A; 3])> {
+ let dead = EmitterTri { tri: first, mat: 0, obj: inst.object, area: 0.0, c: [0.0; 3], moves, nominal: false, in_tree: false, inst: record };
+ let mut out = vec![(dead, [glam::Vec3A::ZERO; 3]); count];
+ for (k, t) in tris.iter().enumerate() {
+ let Some((slot, mat)) = numbered(k) else { continue };
+ let w = t.map(|v| glam::Vec3A::from(inst.world.transform_point3(v.into())));
+ let emits = materials.get(mat as usize).is_some_and(|m| 0.2126 * m.emissive[0] + 0.7152 * m.emissive[1] + 0.0722 * m.emissive[2] > 0.0);
+ let area = if emits && !inst.hidden { 0.5 * (w[1] - w[0]).cross(w[2] - w[0]).length() } else { 0.0 };
+ out[slot] = (EmitterTri { tri: first + k as u32, mat, area, c: ((w[0] + w[1] + w[2]) / 3.0).to_array(), ..dead }, w);
+ }
+ out
}
/// Runs of the light list (first emitter, count) whose triangles something moves after the load; the GPU takes them
/// again from where the triangles are (gpu.rs `EmitterFill`): the emitters of the triangles the CPU reposes, and the
-/// particles', which their passes place.
+/// particles', which their passes place. (An instance that moves has its run filled when it does: live/edits.rs.)
#[derive(Default)]
pub struct EmitterRuns {
pub moved: Vec<[u32; 2]>,
@@ -187,7 +216,7 @@ impl EmitterRuns {
}
out
};
- EmitterRuns { moved: runs(&|e| e.moves && !e.nominal), particles: runs(&|e| e.nominal) }
+ EmitterRuns { moved: runs(&|e| e.moves && !e.nominal && e.inst == NO_INST), particles: runs(&|e| e.nominal) }
}
}
@@ -211,9 +240,9 @@ pub fn switchable_power(e: &EmitterTri, materials: &[scene::GpuMaterial], object
/// weight until they switch on, instead of in the flat CDF beyond it, where the kernel draws them by power share alone
/// (no importance at the shading point) once they are on. Then, if some are off, the node powers are refit to the
/// objects' powers now; a scene with every emitter on at load gets the tree it had before, bit for bit.
-pub fn light_tree_of(tris: &[EmitterTri], tri_verts: &[[f32; 4]], materials: &[scene::GpuMaterial], objects: &[[f32; 4]], stride: usize, slot: bool) -> Option<ltree::LightTree> {
+pub fn light_tree_of(tris: &[EmitterTri], verts: &dyn Fn(usize) -> [[f32; 3]; 3], materials: &[scene::GpuMaterial], objects: &[[f32; 4]], stride: usize, slot: bool) -> Option<ltree::LightTree> {
let build = if slot { ltree::build_slotted } else { ltree::build };
- let mut t = build(tris, tri_verts, &|i| switchable_power(&tris[i], materials, objects, stride))?;
+ let mut t = build(tris, verts, &|i| switchable_power(&tris[i], materials, objects, stride))?;
let now: Vec<f32> = t.order.iter().map(|&i| emitter_power(&tris[i as usize], materials, objects, stride)).collect();
if now.iter().any(|&w| !(w > 0.0)) {
t.refit(&|k| now[k]);
@@ -643,12 +672,37 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
}
timings.push(("bvh_ms".into(), t.elapsed().as_secs_f64() * 1000.0));
- // Emissive triangle CDF (weight = area * luminance of the emissive factor * object power): the flattened
- // triangles, then the emitting own_blas meshes' (world space in the pool, `InstMesh::emits`).
+ // The light list (an emitter's weight = area x luminance of the emissive factor x object power): the flattened
+ // triangles that emit, then, an instance at a time, those of a mesh that emits (`InstMesh::emitters`): a run of
+ // the list an instance, its first in its record, its triangles' numbers counted from it. Each with its triangle in
+ // world space.
let mut emitter_tris: Vec<EmitterTri> = vec![];
- let emitting_pool = sc.meshes.iter().filter(|m| m.emits).flat_map(|m| pool_first + m.first as usize..pool_first + (m.first + m.count) as usize);
- for k in (0..pool_first).chain(emitting_pool) {
+ let mut gpu_emitter_tris: Vec<GpuEmitterTri> = vec![];
+ for k in 0..pool_first {
if let Some(e) = emitter_tri(k, &tri_verts, &sc.attrs[k], &sc.materials) {
+ gpu_emitter_tris.push(GpuEmitterTri::new(&e, &tri_verts[k * 3..][..3], 0));
+ emitter_tris.push(e);
+ }
+ }
+ // (A mesh that emits: its 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();
+ for r in 0..sc.instances.len() {
+ let m = sc.meshes[sc.instances[r].mesh as usize];
+ if m.emitters == 0 {
+ continue;
+ }
+ sc.instances[r].first_emitter = emitter_tris.len() as u32;
+ if let Some(g) = sc.gpu_instances.get_mut(r) {
+ g.n[2][3] = f32::from_bits(emitter_tris.len() as u32);
+ }
+ let (a, b) = (m.first as usize, (m.first + m.count) as usize);
+ let attrs = &sc.attrs[pool_first + a..pool_first + b];
+ let numbered = |k: usize| (attrs[k].x[3].to_bits() as usize).checked_sub(1).map(|n| (n, attrs[k].uv[3].to_bits()));
+ for (e, w) in instance_emitters(&sc.instances[r], r as u32, &sc.pool_tris[a..b], (pool_first + a) as u32, &numbered, m.emitters as usize, &sc.materials, moving.contains(&(r as u32))) {
+ gpu_emitter_tris.push(GpuEmitterTri::of(&e, w, 0));
emitter_tris.push(e);
}
}
@@ -675,19 +729,18 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
// (Switched-off objects at full power: `switchable_power`.)
let all_power: f32 = emitter_tris.iter().map(|e| switchable_power(e, &sc.materials, &sc.objects, sc.object_stride())).sum();
let use_tree = std::env::var("THREERT_LTREE").map_or(true, |v| v != "0");
- let light_tree = if use_tree { light_tree_of(&emitter_tris, &tri_verts, &sc.materials, &sc.objects, sc.object_stride(), sc.emitter_slot) } else { None };
- // The list keeps its own order (the tree and the CDF name its emitters: `emitter_order`).
- let mut codes = vec![0u32; emitter_tris.len()];
+ let light_tree = if use_tree { light_tree_of(&emitter_tris, &|i| gpu_emitter_tris[i].vertices(), &sc.materials, &sc.objects, sc.object_stride(), sc.emitter_slot) } else { None };
+ // The list keeps its own order (the tree and the CDF name its emitters: `emitter_order`); the tree's have their
+ // codes.
if let Some(t) = &light_tree {
for (k, &i) in t.order.iter().enumerate() {
emitter_tris[i as usize].in_tree = true;
- codes[i as usize] = t.code[k];
+ gpu_emitter_tris[i as usize].code |= t.code[k];
}
}
- // The list's triangles (the tree's with their codes), and each triangle's entry + 1 in its attributes (x.w), for
- // the rays that hit it (emit_mis).
- let gpu_emitter_tris: Vec<GpuEmitterTri> = emitter_tris.iter().zip(&codes).map(|(e, &code)| GpuEmitterTri::new(e, &tri_verts[e.tri as usize * 3..][..3], code)).collect();
- for (i, e) in emitter_tris.iter().enumerate() {
+ // A triangle in world space names its emitter in its attributes (x.w = the entry + 1), for the rays that hit it
+ // (emit_mis); a mesh's triangle is numbered among its mesh's, and its instance has the first.
+ for (i, e) in emitter_tris.iter().enumerate().filter(|(_, e)| e.inst == NO_INST) {
sc.attrs[e.tri as usize].x[3] = f32::from_bits(i as u32 + 1);
}
let emitter_runs = EmitterRuns::of(&emitter_tris);
@@ -1272,16 +1325,17 @@ mod light_lod_tests {
// the one a load with all of them on builds: the plain build's, its powers summed bottom-up.
let mats = [scene::GpuMaterial { emissive: [1.0, 1.0, 1.0, 0.0], ..Default::default() }];
let tris: Vec<EmitterTri> = (0..600u32)
- .map(|i| EmitterTri { tri: i, mat: 0, obj: (i % 6 != 0) as u32, area: 0.5, c: [2.0 * i as f32 + 1.0 / 3.0, 1.0 / 3.0, 0.0], moves: false, nominal: false, in_tree: false })
+ .map(|i| EmitterTri { tri: i, mat: 0, obj: (i % 6 != 0) as u32, area: 0.5, c: [2.0 * i as f32 + 1.0 / 3.0, 1.0 / 3.0, 0.0], moves: false, nominal: false, in_tree: false, inst: NO_INST })
.collect();
let verts: Vec<[f32; 4]> = (0..600).flat_map(|i| [[2.0 * i as f32, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]]).collect();
let (off, on) = ([[0.0, 0.0, 0.0, 1.0], [0.0; 4]], [[0.0, 0.0, 0.0, 1.0]; 2]);
- assert!(ltree::build(&tris, &verts, &|i| emitter_power(&tris[i], &mats, &off, 1)).is_none());
- let mut t = light_tree_of(&tris, &verts, &mats, &off, 1, false).unwrap();
+ let rows = |i: usize| ltree::tri_vertices(&verts[i * 3..i * 3 + 3]);
+ assert!(ltree::build(&tris, &rows, &|i| emitter_power(&tris[i], &mats, &off, 1)).is_none());
+ let mut t = light_tree_of(&tris, &rows, &mats, &off, 1, false).unwrap();
assert_eq!(t.order.len(), 600);
assert!((t.power - 100.0 * 0.5).abs() < 1e-3, "{}", t.power);
- let loaded = light_tree_of(&tris, &verts, &mats, &on, 1, false).unwrap();
- let plain = ltree::build(&tris, &verts, &|i| emitter_power(&tris[i], &mats, &on, 1)).unwrap();
+ let loaded = light_tree_of(&tris, &rows, &mats, &on, 1, false).unwrap();
+ let plain = ltree::build(&tris, &rows, &|i| emitter_power(&tris[i], &mats, &on, 1)).unwrap();
let bits = |t: &ltree::LightTree| t.nodes.iter().map(|n| n.map(f32::to_bits)).collect::<Vec<_>>();
assert_eq!((bits(&loaded), &loaded.order), (bits(&plain), &plain.order));
let w: Vec<f32> = t.order.iter().map(|&i| emitter_power(&tris[i as usize], &mats, &on, 1)).collect();
@@ -1304,7 +1358,7 @@ mod light_lod_tests {
let mut unit = || (rnd() >> 8) as f32 / (1 << 24) as f32;
let mats: Vec<scene::GpuMaterial> = (0..4).map(|k| scene::GpuMaterial { emissive: [k as f32 * 3.0, k as f32, 0.5 * k as f32, 0.0], ..Default::default() }).collect();
let tris: Vec<EmitterTri> = (0..3000)
- .map(|i| EmitterTri { tri: i, mat: if i % 9 == 0 { 0 } else { 1 + i % 3 }, obj: 0, area: 10f32.powf(-6.0 * unit()), c: [300.0 * unit(), 5.0, 100.0 * unit()], moves: i % 50 == 0, nominal: false, in_tree: false })
+ .map(|i| EmitterTri { tri: i, mat: if i % 9 == 0 { 0 } else { 1 + i % 3 }, obj: 0, area: 10f32.powf(-6.0 * unit()), c: [300.0 * unit(), 5.0, 100.0 * unit()], moves: i % 50 == 0, nominal: false, in_tree: false, inst: NO_INST })
.collect();
let (t, total, _) = emitter_cdf(&tris, &emitter_order(&tris, None), &mats, &[], 3, [20.0, 0.0, 30.0, 10.0], EmitterCull::default());
let n = tris.len() as u32;
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 8dba1b2..12f4685 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -3,6 +3,12 @@
use super::*;
+/// The run of the light list that is instance `record`'s: from its first emitter, those that name it.
+fn emitter_run(tris: &[crate::EmitterTri], instances: &[scene::Instance], record: u32) -> std::ops::Range<usize> {
+ let first = instances.get(record as usize).map_or(0, |i| i.first_emitter as usize).min(tris.len());
+ first..first + tris[first..].iter().take_while(|e| e.inst == record).count()
+}
+
/// Writes to one buffer gathered during an edit and sent merged: adjacent ranges as one `write_buffer` (an edit writes
/// hundreds of small records and meshes, contiguous in the room). Overlapping writes go in the order they came.
#[derive(Default)]
@@ -775,6 +781,13 @@ 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.inst_moved = true;
build.instances = true;
true
@@ -830,7 +843,7 @@ impl LiveCore {
let area = 0.5 * (b - a).cross(c - a).length();
if area > 0.0 {
let centre = (a + b + c) / 3.0;
- let e = crate::EmitterTri { tri: k, mat, obj, area, c: centre.to_array(), moves: false, nominal: false, in_tree: false };
+ let e = crate::EmitterTri { tri: k, mat, obj, area, c: centre.to_array(), moves: false, nominal: false, in_tree: false, inst: crate::NO_INST };
new.push((sc.tables.emitter_tris.len() as u32, crate::GpuEmitterTri::of(&e, [a, b, c], 0)));
sc.tables.emitter_tris.push(e);
}
@@ -851,12 +864,15 @@ impl LiveCore {
pub(super) fn write_emitters(&mut self, new: &[(u32, crate::GpuEmitterTri)]) {
self.land_powers_now();
let g = &self.g;
- let LoadedScene { tables: e, base: b, up, pool_tris, tris: flat, tri_order, edit, .. } = &mut self.sc;
+ let LoadedScene { tables: e, base: b, up, pool_tris, tris: flat, tri_order, edit, instances, .. } = &mut self.sc;
let size = std::mem::size_of::<crate::GpuEmitterTri>();
let (mut w_tris, mut w_attrs) = (Gather::default(), Gather::default());
for (i, t) in new {
w_tris.put((*i as usize * size) as u64, bytemuck::bytes_of(t));
- w_attrs.put((t.tri as usize * std::mem::size_of::<scene::GpuTriAttr>() + std::mem::offset_of!(scene::GpuTriAttr, x) + 12) as u64, bytemuck::bytes_of(&(i + 1)));
+ // (A triangle in world space names its emitter; a mesh's is numbered among its mesh's.)
+ if t.inst == crate::NO_INST {
+ w_attrs.put((t.tri as usize * std::mem::size_of::<scene::GpuTriAttr>() + std::mem::offset_of!(scene::GpuTriAttr, x) + 12) as u64, bytemuck::bytes_of(&(i + 1)));
+ }
}
w_attrs.flush(&g.queue, &up.attrs);
// Emitters added in place, with the tree's slot for them (`ltree::build_slotted`): its subtree grown again over
@@ -866,11 +882,19 @@ impl LiveCore {
if let Some((_, ns)) = t.dynamic {
let ns = ns as usize;
let (mats, objs, st, pf) = (&e.materials, &e.objects, e.stride, edit.pool_first);
- let verts = |k: usize| if k >= pf { pool_tris.get(k - pf).copied() } else { tri_order.get(k).and_then(|&i| flat.get(i as usize)).copied() };
+ // (An emitter's triangle in world space: an instance's is its mesh's, placed.)
+ let verts = |x: &crate::EmitterTri| {
+ let k = x.tri as usize;
+ let t = if k >= pf { pool_tris.get(k - pf).copied() } else { tri_order.get(k).and_then(|&i| flat.get(i as usize)).copied() };
+ match instances.get(x.inst as usize) {
+ Some(i) if x.inst != crate::NO_INST => t.map(|t| t.map(|v| glam::Vec3A::from(i.world.transform_point3(v.into())))),
+ _ => t,
+ }
+ };
let mut items = vec![];
for (i, x) in e.emitter_tris.iter().enumerate() {
let w = crate::emitter_power(x, mats, objs, st);
- let Some([va, vb, vc]) = verts(x.tri as usize).filter(|_| !x.in_tree && !x.nominal && !x.moves && w > 0.0) else { continue };
+ let Some([va, vb, vc]) = verts(x).filter(|_| !x.in_tree && !x.nominal && !x.moves && w > 0.0) else { continue };
items.push(crate::ltree::DynItem { e: i as u32, lo: va.min(vb).min(vc).to_array(), hi: va.max(vb).max(vc).to_array(), c: x.c, w });
}
let was = t.order[ns..].to_vec();
@@ -1385,8 +1409,15 @@ impl LiveCore {
let tris = &tables.emitter_tris;
let (q, heap) = (&self.g.queue, &self.sc.up.heap);
let Some(t) = tables.light_tree.as_mut().filter(|t| t.moving_count > 0) else { return };
+ let (instances, pool_tris, pool_first) = (&self.sc.instances, &self.sc.pool_tris, self.sc.edit.pool_first);
t.refit_moving(&|e| {
- let r = (tris[e].tri as usize - first) * 3;
+ let x = &tris[e];
+ // (An instance's: its mesh's triangle, placed.)
+ if x.inst != crate::NO_INST {
+ let w = instances[x.inst as usize].world;
+ return pool_tris[x.tri as usize - pool_first].map(|v| w.transform_point3(v.into()).to_array());
+ }
+ let r = (x.tri as usize - first) * 3;
crate::ltree::tri_vertices(&verts[r..r + 3])
});
heap.write(q, Table::LightTree, 0, bytemuck::cast_slice(&t.nodes[..1]));
@@ -1558,19 +1589,15 @@ impl LiveCore {
Some((inst_base + record, record))
};
let q = &g.queue;
- // An emitter mesh's entries go (area 0: their weight; the light tree keeps its shape) when it is removed, hidden
- // or placed again; those it is given are in `new_emitters` (`write_emitters`).
+ // An instance's emitters go (area 0: their weight; the light tree keeps its shape) when its object is removed,
+ // hidden or placed again; those it is given are in `new_emitters` (`write_emitters`).
let mut emitters_changed = false;
let mut new_emitters: Vec<(u32, crate::GpuEmitterTri)> = vec![];
- let release = |id: u32, tables: &mut tables::Tables, meshes: &[scene::InstMesh], pool_first: usize| -> bool {
- let Some(scene::Draw::Instance(inst)) = tables.retained.proxies.get_mut(&id).map(|p| &mut p.draw) else { return false };
- let scene::MeshKind::Emitter(k) = std::mem::replace(&mut inst.mesh, scene::MeshKind::Own) else { return false };
- let im = meshes[k as usize];
- let (lo, hi) = ((pool_first + im.first as usize) as u32, (pool_first + (im.first + im.count) as usize) as u32);
- for e in tables.emitter_tris.iter_mut().filter(|e| (lo..hi).contains(&e.tri)) {
- e.area = 0.0;
- }
- true
+ let release = |id: u32, tables: &mut tables::Tables, instances: &[scene::Instance]| -> bool {
+ let Some(record) = tables.retained.instance(id).map(|i| i.instance) else { return false };
+ let run = emitter_run(&tables.emitter_tris, instances, record);
+ tables.emitter_tris[run.clone()].iter_mut().for_each(|e| e.area = 0.0);
+ !run.is_empty()
};
for id in &ch.removed {
// An instanced mesh: its instances out. One an edit placed gives its records and entries back to the room
@@ -1591,7 +1618,7 @@ impl LiveCore {
tables.retained.proxies.remove(id);
continue;
}
- emitters_changed |= release(*id, tables, meshes, edit.pool_first);
+ emitters_changed |= release(*id, tables, instances);
let at = slot_of(*id, edit, tables);
// Drawn, and not at a record an edit can clear (a model the build placed, anything it flattened): a rebuild
// takes it out.
@@ -1626,7 +1653,7 @@ impl LiveCore {
for id in todo {
let Some(o) = world.objects.get(&id) else { continue };
let at = slot_of(id, edit, tables);
- emitters_changed |= release(id, tables, meshes, edit.pool_first);
+ emitters_changed |= release(id, tables, instances);
if !world.shown(id) {
if let Some((slot, _)) = at {
top.clear(slot);
@@ -1646,8 +1673,6 @@ impl LiveCore {
return Err("an object the build flattened".into());
}
let m = world.world_matrix(id);
- // (The emitter mesh it is placed as, if it is one: its proxy's, below.)
- let mut emitter = None;
let object = match tables.retained.object(id) {
Some(k) => k as usize,
None => match edit.objects.take(1) {
@@ -1660,8 +1685,6 @@ impl LiveCore {
None => return Err("edit room: objects (particles, or the device's limits)".into()),
},
};
- // Where its TLAS instance places it: the node, or identity for an emitter mesh (world-space triangles).
- let mut placement = m;
let (record, gpu, blas, entry) = match &o.kind {
Kind::Procedural { .. } => {
// (Software traversal walks procedural objects by their count and their own trees in the region:
@@ -1679,7 +1702,6 @@ impl LiveCore {
undraw(tables.retained.proxies.get(&id).map(|p| &p.draw), instances, procs);
continue;
};
- placement = m;
// Room for `used` words: the region grown if it lacks it.
let mut words_left = |used: usize, edit: &mut EditState| {
if used <= edit.word_cap {
@@ -1741,7 +1763,7 @@ impl LiveCore {
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: o.cast_shadow, name: o.name.clone(), sub: None, hidden: false };
+ let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: o.cast_shadow, name: o.name.clone(), sub: None, hidden: false, first_emitter: 0 };
let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.opaque), mesh, o.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]);
@@ -1764,17 +1786,13 @@ impl LiveCore {
}
let mat = *tables.retained.materials.get(material).ok_or("unknown material")?;
let gm = tables.materials[mat as usize];
- // An emitting material (no glass, no function): an emitter mesh, its triangles in world space and its
- // own (never shared), its emitter entries added (scene.rs; ROADMAP § 6 step 3).
+ // 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 = if emits { u32::from(gm.uv2[3] > 0.0) } else { scene::material_class(&gm) };
+ let class = scene::own_mesh_class(&gm);
if class == 2 || (emits && capacity.is_some()) {
return Err("a glass or function material (an instanced mesh: emitting too)".into());
}
- // (An emitter mesh's triangles are in world space: one a body moves is flattened by the build.)
- if emits && o.driven {
- return Err("an emitting mesh a rigid body drives (the build flattens it)".into());
- }
if class == 1 && features & gpu::F_MASKED == 0 {
return Err("the scene's first cutout (kernel feature)".into());
}
@@ -1782,14 +1800,14 @@ impl LiveCore {
if colored && !vcolors {
return Err("the scene's first vertex colours (kernel feature)".into());
}
- let key = if emits { (u32::MAX - id, mat) } else { (*geometry, mat) };
- let kept = (!emits && !ch.geometries.contains(geometry)).then(|| tables.retained.own_mesh.get(&key).copied()).flatten();
+ let key = (*geometry, 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,
None => {
let geo = world.geometries.get(geometry).ok_or("unknown geometry")?;
let t0 = Instant::now();
- let (mut t, mut a) = if emits { scene::emitter_mesh_tris(geo, m, mat, object as u32) } else { scene::own_mesh_tris(geo, mat) };
+ let (mut t, mut a) = scene::own_mesh_tris(geo, mat);
if t.is_empty() {
if let Some((slot, _)) = at {
top.clear(slot);
@@ -1811,6 +1829,10 @@ impl LiveCore {
Some(tree)
}
};
+ // (A mesh that emits: its triangles numbered as they lie, for its instances' emitters.)
+ if emits {
+ scene::number_emitters(&mut a);
+ }
// (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 });
// As `prepare` lays the pool out: (a, flags), e1, e2; attributes; the BLAS's vertices.
@@ -1820,7 +1842,7 @@ impl LiveCore {
// The same triangle count as the mesh it replaces: rewritten where it is, its BLAS rebuilt (no
// room used; a geometry that moves every frame, three.js's dynamic draw usage). Otherwise new
// triangles in the room and a new BLAS.
- let same = tables.retained.own_mesh.get(&key).copied().filter(|&k| meshes[k as usize].count as usize == t.len() && meshes[k as usize].emits == emits);
+ let same = tables.retained.own_mesh.get(&key).copied().filter(|&k| meshes[k as usize].count as usize == t.len() );
let (k, first, im) = match same {
Some(k) => {
let im = meshes[k as usize];
@@ -1849,7 +1871,7 @@ impl LiveCore {
None => return Err(if matches!(top, gpu::Top::Sw(_)) { "edit room: triangles (software traversal's does not grow)" } else { "edit room: triangles (particles, or the device's limits)" }.into()),
};
let mut im = scene::own_inst_mesh(&t, (first - edit.pool_first) as u32, class);
- im.emits = emits;
+ im.emitters = if emits { t.len() as u32 } else { 0 };
let t1 = Instant::now();
// A freed mesh's slot, else a new one.
let dead = edit.dead_meshes.pop();
@@ -1908,30 +1930,6 @@ impl LiveCore {
pool_tris.resize(rel + t.len(), [glam::Vec3A::ZERO; 3]);
}
pool_tris[rel..rel + t.len()].copy_from_slice(&t);
- if emits {
- // Its emitter entries, in the power-share part of the CDF (path code 0). Rewritten where
- // it was (a mesh that moves every frame: flying pieces), it takes back the entries it had
- // there (`release` left them at area 0), so the CDF does not grow frame by frame; those
- // in the light tree stay out (their triangles now carry code 0).
- let range = first as u32..(first + t.len()) as u32;
- let mut free: Vec<usize> = if same.is_some() { tables.emitter_tris.iter().enumerate().filter(|(_, e)| !e.in_tree && range.contains(&e.tri)).map(|(i, _)| i).rev().collect() } else { vec![] };
- for (j, tri) in t.iter().enumerate() {
- let [ta, tb, tc] = *tri;
- let area = 0.5 * (tb - ta).cross(tc - ta).length();
- if area > 0.0 {
- let e = crate::EmitterTri { tri: (first + j) as u32, mat, obj: object as u32, area, c: ((ta + tb + tc) / 3.0).to_array(), moves: false, nominal: false, in_tree: false };
- let i = free.pop().unwrap_or(tables.emitter_tris.len());
- new_emitters.push((i as u32, crate::GpuEmitterTri::of(&e, *tri, 0)));
- match tables.emitter_tris.get_mut(i) {
- Some(old) => *old = e,
- None => tables.emitter_tris.push(e),
- }
- }
- }
- emitter = Some(k);
- tables.emissive.insert(mat);
- emitters_changed = true;
- }
let _ = im;
new_meshes.push(k);
fresh.insert(key, k);
@@ -1979,7 +1977,7 @@ impl LiveCore {
};
let (st, size) = (tables.stride, std::mem::size_of::<scene::GpuInstance>());
if instances.len() < r0 + cap {
- let filler = scene::Instance { mesh, world: glam::Mat4::IDENTITY, object: 0, cast_shadow: false, name: String::new(), sub: None, hidden: true };
+ let filler = scene::Instance { mesh, world: glam::Mat4::IDENTITY, object: 0, cast_shadow: false, name: String::new(), sub: None, hidden: true, first_emitter: 0 };
instances.resize(r0 + cap, filler);
}
if gpu_instances.len() < r0 + cap {
@@ -1989,7 +1987,7 @@ impl LiveCore {
tables.objects.resize((o0 + cap) * st, [0.0; 4]);
}
for (i, &(wm, hidden)) in placed.iter().enumerate() {
- let inst = scene::Instance { mesh, world: wm, object: (o0 + i) as u32, cast_shadow: o.cast_shadow, name: o.name.clone(), sub: Some(i as u32), hidden };
+ let inst = scene::Instance { mesh, world: wm, object: (o0 + i) as u32, cast_shadow: o.cast_shadow, name: o.name.clone(), sub: Some(i as u32), hidden, first_emitter: 0 };
let rec = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.opaque), mesh, o.cast_shadow);
w_records.put(((r0 + i) * size) as u64, bytemuck::bytes_of(&rec));
gpu_instances[r0 + i] = rec;
@@ -2003,12 +2001,9 @@ impl LiveCore {
*tables.retained.proxy(id) = scene::Proxy { object: None, card: None, draw: scene::Draw::Instanced(scene::InstancedPlace { first: r0 as u32, capacity: cap as u32, object: o0 as u32, mesh: Some(mesh), drawn: t.count }) };
continue;
}
- if emits {
- placement = glam::Mat4::IDENTITY;
- }
- let inst = scene::Instance { mesh, world: placement, object: object as u32, cast_shadow: o.cast_shadow, name: o.name.clone(), sub: None, hidden: false };
+ let inst = scene::Instance { mesh, world: m, object: object as u32, cast_shadow: o.cast_shadow, name: o.name.clone(), sub: None, hidden: false, first_emitter: 0 };
let gpu = top.record(inst.gpu((edit.pool_first as u32) + im.first, im.opaque), mesh, o.cast_shadow);
- let (lo, hi) = im.placed_bounds(placement);
+ 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), entry)
}
@@ -2030,6 +2025,30 @@ impl LiveCore {
(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), Kind::Mesh { material, .. }) = (&mut blas, &o.kind) {
+ let im = meshes[inst.mesh as usize];
+ if let (true, Some(&mat)) = (im.emitters > 0, tables.retained.materials.get(material)) {
+ let old = emitter_run(&tables.emitter_tris, instances, record as u32);
+ let first = if old.len() == im.emitters as usize && tables.emitter_tris[old.clone()].iter().all(|e| !e.in_tree) { old.start } else { tables.emitter_tris.len() };
+ inst.first_emitter = first as u32;
+ gpu.n[2][3] = f32::from_bits(first as u32);
+ 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, &|k| Some((k, mat)), im.emitters as usize, &tables.materials, o.driven);
+ 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),
+ }
+ }
+ tables.emissive.insert(mat);
+ emitters_changed = true;
+ }
+ }
w_records.put((record * std::mem::size_of::<scene::GpuInstance>()) as u64, bytemuck::bytes_of(&gpu));
if record >= gpu_instances.len() {
gpu_instances.resize(record + 1, scene::GpuInstance::default());
@@ -2039,7 +2058,7 @@ impl LiveCore {
// record less the first procedural one (hidden fillers at the records between, which are other objects').
let draw = match blas {
Placed::Proc(blas, p) => {
- top.place_blas(slot, &blas, placement, record as u32, mask(o.cast_shadow));
+ top.place_blas(slot, &blas, m, record as u32, mask(o.cast_shadow));
let j = record - proc_first;
if procs.len() <= j {
procs.resize(j + 1, scene::ProcObject { name: String::new(), materials: vec![], hidden: true, ..p.clone() });
@@ -2048,15 +2067,11 @@ impl LiveCore {
scene::Draw::Procedural(j as u32)
}
Placed::Mesh(inst) => {
- top.place(slot, inst.mesh, placement, gpu::INSTANCE_BIT | record as u32, o.cast_shadow, false);
+ top.place(slot, inst.mesh, m, gpu::INSTANCE_BIT | record as u32, o.cast_shadow, false);
if instances.len() <= record {
instances.resize(record + 1, scene::Instance { name: String::new(), hidden: true, ..inst.clone() });
}
- let mesh = match (&o.kind, emitter) {
- (_, Some(k)) => scene::MeshKind::Emitter(k),
- (Kind::Model { .. }, _) => scene::MeshKind::Model,
- _ => scene::MeshKind::Own,
- };
+ 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 })
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 411ffd1..aea329d 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -380,8 +380,9 @@ fn an_instanced_object_added_in_place_keeps_its_copies_data() {
}
/// What the kernel's light sampling reads against the triangles it stands for, on the GPU: every emitter of the list
-/// has the light tree's path code for it, and one that is alive its triangle's rows, object and moving flag, and its
-/// triangle's attributes name it back.
+/// has the light tree's path code for it, and one that is alive its triangle's rows (an instance's: its mesh's
+/// triangle placed by the instance, to rounding), its instance and moving flag, and a ray that hits its triangle
+/// finds it (the attributes' number, from the instance's first).
fn list_is_its_triangles(what: &str, c: &LiveCore) {
let read = |b: &wgpu::Buffer, at: u64, bytes: u64| -> Vec<u8> {
let to = c.g.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: bytes, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
@@ -408,17 +409,29 @@ fn list_is_its_triangles(what: &str, c: &LiveCore) {
}
let rows: Vec<[f32; 4]> = (0..3).map(|k| bytemuck::pod_read_unaligned(&verts[(e.tri as usize * 3 + k) * 16..][..16])).collect();
let a: scene::GpuTriAttr = bytemuck::pod_read_unaligned(&attrs[e.tri as usize * 96..][..96]);
- assert_eq!(r, crate::GpuEmitterTri::new(e, &rows, code), "{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);
+ if e.inst == crate::NO_INST {
+ assert_eq!(r, crate::GpuEmitterTri::new(e, &rows, code), "{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]);
+ 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");
+ for (got, want) in [r.v0, r.e1, r.e2].into_iter().zip(placed) {
+ assert!((glam::Vec3::from(got) - want).length() <= 1e-4 * (1.0 + want.length()), "{what}: emitter {i}'s triangle {got:?}, its instance places it at {want:?}");
+ }
+ assert_eq!((record.n[2][3].to_bits(), record.n[2][3].to_bits() + a.x[3].to_bits()), (inst.first_emitter, i as u32 + 1), "{what}: triangle {} of instance {} finds its emitter", e.tri, e.inst);
+ }
alive += 1;
}
assert!(alive > 0, "{what}: the list has emitters");
}
/// 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 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).
+/// 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.
#[test]
fn the_light_list_holds_its_triangles() {
let presets = crate::default_presets_dir();
@@ -455,6 +468,19 @@ fn the_light_list_holds_its_triangles() {
assert!(!(rebuilt && live.g.hwrt), "the mover moved in place ({:?})", live.fallback);
list_is_its_triangles("a moving emitter, moved", &live);
}
+ // An emitting mesh a body drives: an instance of its mesh, whose emitters follow it.
+ let mut w = world();
+ w.set_object(13, "driven".into(), None, Kind::Mesh { geometry: 3, material: 5, own_blas: true, materials: vec![] }, true, false).unwrap();
+ w.set_driven(13).unwrap();
+ w.set_transform(13, Vec3::new(-0.6, 0.5, 0.7), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ let mut live = open(&w).unwrap();
+ w.take_changes();
+ assert!(live.sc.tables.emitter_tris.iter().any(|e| e.inst != crate::NO_INST && e.moves), "the driven mesh's emitters are its instance's");
+ list_is_its_triangles("a driven emitting mesh, as loaded", &live);
+ assert!(w.place_driven(13, Vec3::new(-0.2, 0.3, 1.0), glam::Quat::from_rotation_z(-0.4)));
+ 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 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());
@@ -510,11 +536,22 @@ fn the_light_list_holds_its_triangles() {
];
for (what, edit) in &edits {
let before = live.sc.tables.emitter_tris.len();
+ let added = live.sc.tables.retained.instance(16).map(|i| i.instance);
edit(&mut w);
assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
list_is_its_triangles(what, &live);
+ // (An instance that is gone lights nothing: its run of the list has no weight.)
+ if live.sc.tables.retained.instance(16).is_none() {
+ let left: Vec<f32> = live.sc.tables.emitter_tris.iter().filter(|e| Some(e.inst) == added).map(|e| e.area).collect();
+ assert!(!left.is_empty() && left.iter().all(|a| *a == 0.0), "{what}: the removed instance's emitters keep no weight ({left:?})");
+ }
// (A mesh given other triangles takes its entries back; the other edits that add emitters make new ones.)
let grew = live.sc.tables.emitter_tris.len() > before;
assert_eq!(grew, matches!(*what, "an emitting mesh added" | "a material starts emitting"), "{what}: the list's length");
+ // (The list agrees with the instances; that the instances are where a build puts them is the picture's to say.)
+ let mut fresh = open(&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));
}
}
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index b030165..ef434fc 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -265,11 +265,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
for i in &instances {
*users.entry(i.mesh).or_default() += 1;
}
- let emitter_meshes = tables.retained.proxies.values().filter_map(|p| match &p.draw {
- scene::Draw::Instance(scene::InstanceRef { mesh: scene::MeshKind::Emitter(k), .. }) => Some(*k),
- _ => None,
- });
- let managed = tables.retained.own_mesh.values().copied().chain(emitter_meshes).collect();
+ let managed = tables.retained.own_mesh.values().copied().collect();
let edit = EditState {
tris: Holes::new(room_base.0, room_base.0 + room.tris),
records: Holes::new(room_base.1, room_base.1 + room.records),
diff --git a/renderer/src/ltree.rs b/renderer/src/ltree.rs
index 9e2ee2f..5712972 100644
--- a/renderer/src/ltree.rs
+++ b/renderer/src/ltree.rs
@@ -350,29 +350,28 @@ impl LightTree {
}
}
-/// The tree over the emitters that are not particles and have power (`weight`), from their triangles (`tri_verts`: v0,
-/// e1, e2 per triangle, as prepared): the static ones; with moving ones too, a root over the static subtree (node 1)
+/// The tree over the emitters that are not particles and have power (`weight`), from their triangles in world space
+/// (`verts(e)`: emitter e's vertices): the static ones; with moving ones too, a root over the static subtree (node 1)
/// and the moving one (node 2). None below MIN_STATIC static emitters.
-pub fn build(tris: &[EmitterTri], tri_verts: &[[f32; 4]], weight: &dyn Fn(usize) -> f32) -> Option<LightTree> {
- build_with(tris, tri_verts, weight, false)
+pub fn build(tris: &[EmitterTri], verts: &dyn Fn(usize) -> [[f32; 3]; 3], weight: &dyn Fn(usize) -> f32) -> Option<LightTree> {
+ build_with(tris, verts, weight, false)
}
/// As `build`, with a slot for emitters added in place (scenes whose geometry the live view can edit): the root over
/// the static subtree (node 1, path bit 0 = 0) and theirs (node 2, bit 0 = 1, empty until `set_dynamic`). Without the
/// slot when there are moving emitters (their subtree is node 2; emitters added in place then go by power share).
-pub fn build_slotted(tris: &[EmitterTri], tri_verts: &[[f32; 4]], weight: &dyn Fn(usize) -> f32) -> Option<LightTree> {
- build_with(tris, tri_verts, weight, true)
+pub fn build_slotted(tris: &[EmitterTri], verts: &dyn Fn(usize) -> [[f32; 3]; 3], weight: &dyn Fn(usize) -> f32) -> Option<LightTree> {
+ build_with(tris, verts, weight, true)
}
-fn build_with(tris: &[EmitterTri], tri_verts: &[[f32; 4]], weight: &dyn Fn(usize) -> f32, slot: bool) -> Option<LightTree> {
+fn build_with(tris: &[EmitterTri], verts: &dyn Fn(usize) -> [[f32; 3]; 3], weight: &dyn Fn(usize) -> f32, slot: bool) -> Option<LightTree> {
let (mut fixed, mut moving): (Vec<Item>, Vec<Item>) = (vec![], vec![]);
for (i, t) in tris.iter().enumerate() {
let w = weight(i);
if t.nominal || !(w > 0.0) {
continue;
}
- let k = t.tri as usize * 3;
- let (lo, hi) = bounds(&tri_vertices(&tri_verts[k..k + 3]));
+ let (lo, hi) = bounds(&verts(i));
let it = Item { e: i as u32, lo, hi, c: t.c, w };
if t.moves {
moving.push(it);
@@ -418,7 +417,7 @@ mod tests {
use super::*;
fn tri(i: u32, x: f32) -> (EmitterTri, [[f32; 4]; 3]) {
- (EmitterTri { tri: i, mat: 0, obj: 0, area: 0.5, c: [x + 1.0 / 3.0, 1.0 / 3.0, 0.0], moves: false, nominal: false, in_tree: false }, [[x, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]])
+ (EmitterTri { tri: i, mat: 0, obj: 0, area: 0.5, c: [x + 1.0 / 3.0, 1.0 / 3.0, 0.0], moves: false, nominal: false, in_tree: false, inst: crate::NO_INST }, [[x, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]])
}
/// Garbage in: emitters whose triangles are not finite, that coincide, or carry weights near f32's limit make a
@@ -438,7 +437,7 @@ mod tests {
}
let w = |i: usize| if i % 11 == 0 { 3.0e38 } else { 1.0 };
for slot in [false, true] {
- let mut t = build_with(&tris, &verts, &w, slot).expect("a tree");
+ let mut t = build_with(&tris, &|i| tri_vertices(&verts[i * 3..i * 3 + 3]), &w, slot).expect("a tree");
t.check().unwrap();
t.refit(&|k| if k % 5 == 0 { f32::NAN } else { 2.0 });
t.set_dynamic((0..300).map(|k| DynItem { e: k, lo: [f32::NAN; 3], hi: [0.0; 3], c: [(k % 3) as f32, f32::INFINITY, 0.0], w: 1.0 }).collect());
@@ -452,7 +451,7 @@ mod tests {
let (tris, verts): (Vec<EmitterTri>, Vec<[[f32; 4]; 3]>) = (0..n).map(|i| tri(i, i as f32 * 2.0)).unzip();
let verts: Vec<[f32; 4]> = verts.into_iter().flatten().collect();
let w = |i: usize| 1.0 + i as f32;
- let t = build(&tris, &verts, &w).unwrap();
+ let t = build(&tris, &|i| tri_vertices(&verts[i * 3..i * 3 + 3]), &w).unwrap();
assert!((t.power - (0..n).map(|i| 1.0 + i as f32).sum::<f32>()).abs() < 1.0);
let mut seen = vec![false; n as usize];
for k in 0..n as usize {
@@ -488,9 +487,9 @@ mod tests {
fn few_or_moving_emitters_make_no_tree() {
let (tris, verts): (Vec<EmitterTri>, Vec<[[f32; 4]; 3]>) = (0..300).map(|i| tri(i, i as f32)).unzip();
let verts: Vec<[f32; 4]> = verts.into_iter().flatten().collect();
- assert!(build(&tris[..100], &verts, &|_| 1.0).is_none());
+ assert!(build(&tris[..100], &|i| tri_vertices(&verts[i * 3..i * 3 + 3]), &|_| 1.0).is_none());
let moving: Vec<EmitterTri> = tris.iter().map(|t| EmitterTri { moves: true, ..*t }).collect();
- assert!(build(&moving, &verts, &|_| 1.0).is_none());
+ assert!(build(&moving, &|i| tri_vertices(&verts[i * 3..i * 3 + 3]), &|_| 1.0).is_none());
}
/// With the slot: static codes under node 1 (bit 0 = 0); emitters added in place get node 2's subtree, their entries
@@ -500,7 +499,7 @@ mod tests {
let n = 300u32;
let (tris, verts): (Vec<EmitterTri>, Vec<[[f32; 4]; 3]>) = (0..n).map(|i| tri(i, i as f32 * 2.0)).unzip();
let verts: Vec<[f32; 4]> = verts.into_iter().flatten().collect();
- let mut t = build_slotted(&tris, &verts, &|_| 1.0).unwrap();
+ let mut t = build_slotted(&tris, &|i| tri_vertices(&verts[i * 3..i * 3 + 3]), &|_| 1.0).unwrap();
let (fixed, ns) = t.dynamic.unwrap();
assert_eq!(ns, n);
assert!(t.code.iter().all(|c| c & 1 == 0), "static entries under node 1");
@@ -542,7 +541,7 @@ mod tests {
t.moves = true;
}
let verts: Vec<[f32; 4]> = verts.into_iter().flatten().collect();
- let mut t = build(&tris, &verts, &|_| 1.0).unwrap();
+ let mut t = build(&tris, &|i| tri_vertices(&verts[i * 3..i * 3 + 3]), &|_| 1.0).unwrap();
assert_eq!((t.moving_first, t.moving_count), (300, 100));
assert!((300..400).any(|k| t.order[k] != k as u32), "the movers' leaf order is not the list's");
assert!((t.power - n as f32).abs() < 1e-3);
diff --git a/renderer/src/merged.rs b/renderer/src/merged.rs
index 7f40680..f4fac6e 100644
--- a/renderer/src/merged.rs
+++ b/renderer/src/merged.rs
@@ -200,6 +200,7 @@ mod tests {
assert!(kernel_template().contains("let b = P.table_first[2].w + i * EMITTER_TRI_VEC4;"));
assert_eq!(Table::EmitterTris as usize, 2 * 4 + 3, "`table_first[2].w`");
assert!(kernel_template().contains(&format!("const EMITTER_MOVES: u32 = {:#x}u;", crate::EMITTER_MOVES)));
+ assert!(include_str!("../shaders/emitter_fill.wgsl").contains(&format!("const INSTANCE_VEC4: u32 = {}u;", std::mem::size_of::<GpuInstance>() / 16)));
// The glass energy table's nodes.
let [mu, rough, ior] = crate::GLASS_E;
for (name, n) in [("GLASS_E_MU", mu), ("GLASS_E_ROUGH", rough), ("GLASS_E_IOR", ior)] {
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index dbeb846..784ca40 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -58,9 +58,9 @@ pub struct InstMesh {
pub hi: Vec3A,
/// Its triangles change (a shared pose, `PoseGroup`): its BLAS is rebuilt with them.
pub deforms: bool,
- /// An emitting `own_blas` mesh (`emitter_mesh_tris`): its triangles in world space, its one placement at identity,
- /// so they are light-sampled as flattened ones are (`prepare` gives them emitter entries).
- pub emits: bool,
+ /// How many emitters an instance of it has in the light list: its triangles of an emitting material, numbered in
+ /// their attributes as they lie in the triangles' table (x.w - 1; `number_emitters`). 0: it does not emit.
+ pub emitters: u32,
}
/// Pool triangles of the deforming meshes, which the build puts first in the pool.
@@ -96,6 +96,9 @@ pub struct Instance {
/// hidden (`instance_world`: TLAS mask 0, never flattened or picked).
pub sub: Option<u32>,
pub hidden: bool,
+ /// Its first emitter in the light list, if its mesh has emitters (`InstMesh::emitters`): set where the list is
+ /// made (lib.rs `prepare`, the live edits); the record carries it (n2.w), for the rays that hit an emitter of it.
+ pub first_emitter: u32,
}
/// Kernel record of an instance (`instances` binding): world matrix rows, normal matrix rows (inverse transpose),
@@ -117,8 +120,8 @@ impl Instance {
let w = self.world;
let nm = glam::Mat3::from_mat4(w).inverse().transpose();
let row = |r: usize| [w.x_axis[r], w.y_axis[r], w.z_axis[r], w.w_axis[r]];
- let nrow = |r: usize| [nm.x_axis[r], nm.y_axis[r], nm.z_axis[r], 0.0];
- GpuInstance { m: [row(0), row(1), row(2)], n: [nrow(0), nrow(1), nrow(2)], info: [first, self.object, lod_offset(w).to_bits(), opaque], p: [row(0), row(1), row(2)] }
+ let nrow = |r: usize, w: f32| [nm.x_axis[r], nm.y_axis[r], nm.z_axis[r], w];
+ GpuInstance { m: [row(0), row(1), row(2)], n: [nrow(0, 0.0), nrow(1, 0.0), nrow(2, f32::from_bits(self.first_emitter))], info: [first, self.object, lod_offset(w).to_bits(), opaque], p: [row(0), row(1), row(2)] }
}
/// Model-space triangle `t` of its mesh in world space (the same transform the flattening path applies).
pub fn tri(&self, t: &[Vec3A; 3]) -> [Vec3A; 3] {
@@ -632,14 +635,12 @@ pub enum MeshKind {
Pose(u32),
/// An `own_blas` mesh, shared by the objects of its geometry and material (`Retained::own_mesh`).
Own,
- /// An emitting `own_blas` mesh (`InstMesh::emits`): this mesh, its own, its triangles in world space.
- Emitter(u32),
}
impl MeshKind {
- /// An `own_blas` mesh, an emitter's too: what a geometry edit makes and places again (a model's is the build's).
+ /// An `own_blas` mesh: what a geometry edit makes and places again (a model's is the build's).
pub fn own(self) -> bool {
- matches!(self, MeshKind::Own | MeshKind::Emitter(_))
+ matches!(self, MeshKind::Own)
}
}
@@ -1312,11 +1313,12 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
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. Glass, emissive
- // and function materials are flattened (as a model's would be), so they are never instanced.
+ // in model space in the pool, shared by the objects of the same geometry and material. Glass and
+ // function materials are flattened (as a model's would be), so they are never instanced. A material
+ // 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 = material_class(&materials[mat as usize]);
+ let class = own_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)) {
@@ -1324,7 +1326,11 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
None => {
let (t, a) = own_mesh_tris(g, mat);
(!t.is_empty()).then(|| {
- meshes.push(own_inst_mesh(&t, pool_tris.len() as u32, class));
+ let mut im = own_inst_mesh(&t, pool_tris.len() as u32, class);
+ if emits_only(&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);
@@ -1341,34 +1347,12 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
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: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false });
- }
- continue;
- }
- // (A driven emitter's triangles cannot stay in world space: it is flattened, dynamic, below.)
- if emits_only(&materials[mat as usize]) && !n.driven {
- // An emitting material: its own BLAS too, but its triangles in world space (placed at identity,
- // never shared), so they are light-sampled as flattened triangles are and can be edited in place
- // (live/edits.rs `edit_geometry`; ROADMAP § 6 step 3).
- let oi = (objects.len() / stride) as u32;
- let (t, a) = emitter_mesh_tris(g, m, mat, oi);
- if !t.is_empty() {
- let cutout = materials[mat as usize].uv2[3] > 0.0;
- let mut im = own_inst_mesh(&t, pool_tris.len() as u32, u32::from(cutout));
- im.emits = true;
- 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 mesh = meshes.len() as u32 - 1;
- objects.extend_from_slice(&object_row(m.transform_point3(Vec3::ZERO), n.power, im.hi - im.lo, 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::Emitter(mesh), moves: false }) };
- instances.push(Instance { mesh, world: Mat4::IDENTITY, object: oi, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false });
+ instances.push(Instance { mesh, world: m, object: oi, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false, first_emitter: 0 });
}
continue;
}
put_colors(&mut vcolors, tris.len(), vc.then(|| tri_colors(g, false, None)));
- // (A driven mesh that cannot be an instance (glass, emissive, a material function): dynamic triangles,
+ // (A driven mesh that cannot be an instance (glass, a material function): dynamic triangles,
// re-transformed in place as any movable mesh's.)
append_arrays(g, m, mat, if n.driven { flags | TRI_DYNAMIC } else { flags }, None, &mut tris, &mut tri_flags, &mut attrs);
if n.driven {
@@ -1424,7 +1408,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
for (i, &(wm, hidden)) in placed.iter().enumerate() {
let (lo, hi) = meshes[mesh as usize].placed_bounds(wm);
objects.extend_from_slice(&entry(i, wm, Vec3::from(hi - lo))[..stride]);
- instances.push(Instance { mesh, world: wm, object: object + i as u32, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: Some(i as u32), hidden });
+ instances.push(Instance { mesh, world: wm, object: object + i as u32, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: Some(i as u32), hidden, first_emitter: 0 });
}
}
continue;
@@ -1572,9 +1556,9 @@ 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, emits: false });
+ 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 });
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 });
+ 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 });
}
let nm = Mat3::from_mat4(w_n).inverse().transpose();
for &(k, mat) in &classed[2] {
@@ -1641,7 +1625,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
}
// Other poses reach further (a stride, a swing): object bounds a quarter wider each way.
let pad = (hi - lo) * 0.25;
- meshes.push(InstMesh { first, count: tri_order.len() as u32, opaque: classed[0].len() as u32, rest_first: 0, rest_count: 0, lo: lo - pad, hi: hi + pad, deforms: true, emits: false });
+ meshes.push(InstMesh { first, count: tri_order.len() as u32, opaque: classed[0].len() as u32, rest_first: 0, rest_count: 0, lo: lo - pad, hi: hi + pad, deforms: true, emitters: 0 });
retained.pose_groups.push(PoseGroup { mesh: meshes.len() as u32 - 1, uri: uri.clone(), nodes: nodes.clone(), animation: a.clone(), order: tri_order, members: vec![] });
retained.pose_groups.len() as u32 - 1
});
@@ -1657,7 +1641,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
let oi = (objects.len() / stride) as u32;
objects.extend_from_slice(&object_row(pivot, n.power, size, n.custom, [1.0; 3])[..stride]);
let i = instances.len() as u32;
- instances.push(Instance { mesh, world: m, object: oi, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false });
+ instances.push(Instance { mesh, world: m, object: oi, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false, first_emitter: 0 });
*retained.proxy(*id) = Proxy { object: Some(oi), card: None, draw: Draw::Instance(InstanceRef { instance: i, mesh: MeshKind::Pose(g), moves: true }) };
retained.pose_groups[g as usize].members.push((*id, i));
continue;
@@ -1713,7 +1697,7 @@ 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, emits: false });
+ 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 });
meshes.len() as u32 - 1
});
if std::env::var("THREERT_INSTANCING").is_ok_and(|v| v == "log") {
@@ -1735,7 +1719,7 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
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).object = Some(oi);
- let inst = Instance { mesh, world: m, object: oi, cast_shadow: n.cast_shadow, name: n.name.clone(), sub: None, hidden: false };
+ 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).
for k in im.rest_first..im.rest_first + im.rest_count {
tris.push(inst.tri(&rest_tris[k as usize]));
@@ -2209,22 +2193,24 @@ pub fn own_mesh_tris(g: &world::Geometry, mat: u32) -> (Vec<[Vec3A; 3]>, Vec<Gpu
(tris, attrs)
}
-/// A material that only emits (no glass, no material function): an `own_blas` mesh of it is an emitter mesh
-/// (`InstMesh::emits`) rather than flattened.
+/// A material that only emits (no glass, no material function): an `own_blas` mesh of it is a mesh as any other, its
+/// instances' emitters in the light list (`InstMesh::emitters`).
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)
}
-/// An emitting `own_blas` mesh's triangles in world space (`m`) and their attributes carrying its object-table index,
-/// as the pool holds them (light sampling reads them without the placement). The build and the live view's in-place
-/// edits both make them here.
-pub fn emitter_mesh_tris(g: &world::Geometry, m: Mat4, mat: u32, object: u32) -> (Vec<[Vec3A; 3]>, Vec<GpuTriAttr>) {
- let (mut tris, mut flags, mut attrs) = (vec![], vec![], vec![]);
- append_arrays(g, m, mat, 0, None, &mut tris, &mut flags, &mut attrs);
- for a in &mut attrs {
- a.x[1] = f32::from_bits(object);
+/// `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 {
+ 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);
}
- (tris, attrs)
+ attrs.len() as u32
}
/// The `InstMesh` of an `own_blas` mesh's triangles at pool index `first` (class: `material_class`, 0 or 1).
@@ -2237,7 +2223,7 @@ pub fn own_inst_mesh(tris: &[[Vec3A; 3]], first: u32, class: u32) -> InstMesh {
}
}
let count = tris.len() as u32;
- InstMesh { first, count, opaque: if class == 0 { count } else { 0 }, rest_first: 0, rest_count: 0, lo, hi, deforms: false, emits: false }
+ InstMesh { first, count, opaque: if class == 0 { count } else { 0 }, rest_first: 0, rest_count: 0, lo, hi, deforms: false, emitters: 0 }
}
/// The GPU material of each triangle of a mesh with several (`Kind::Mesh::materials`, here GPU indices) by its
@@ -2418,7 +2404,7 @@ mod instance_tests {
let uv = [Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)];
let w = Mat4::from_scale_rotation_translation(Vec3::splat(2.0), glam::Quat::from_rotation_y(0.7) * glam::Quat::from_rotation_x(-0.3), Vec3::new(5.0, 1.0, -3.0));
let local = tri_attr(p, n, uv, None, 7);
- let inst = Instance { mesh: 0, world: w, object: 3, cast_shadow: true, name: "x".into(), sub: None, hidden: false };
+ let inst = Instance { mesh: 0, world: w, object: 3, cast_shadow: true, name: "x".into(), sub: None, hidden: false, first_emitter: 0 };
let placed = inst.tri(&[p[0].into(), p[1].into(), p[2].into()]);
let wp = p.map(|v| w.transform_point3(v));
let flat = tri_attr(wp, n.map(|v| (glam::Mat3::from_mat4(w).inverse().transpose() * v).normalize()), uv, None, 7);
@@ -2447,7 +2433,7 @@ mod instance_tests {
let mats = [opaque, cutout];
let p = [Vec3::ZERO, Vec3::X, Vec3::Y];
let a = |m: u32| tri_attr(p, [Vec3::Z; 3], [Vec2::ZERO, Vec2::X, Vec2::Y], None, m);
- let inst = |shadow: bool| Instance { mesh: 0, world: Mat4::IDENTITY, object: 0, cast_shadow: shadow, name: "x".into(), sub: None, hidden: false };
+ let inst = |shadow: bool| Instance { mesh: 0, world: Mat4::IDENTITY, object: 0, cast_shadow: shadow, name: "x".into(), sub: None, hidden: false, first_emitter: 0 };
assert_eq!(instance_tri_flags(&inst(true), &a(0), &mats), 0);
assert_eq!(instance_tri_flags(&inst(true), &a(1), &mats), TRI_MASKED);
assert_eq!(instance_tri_flags(&inst(false), &a(1), &mats), TRI_MASKED | TRI_NO_SHADOW);
diff --git a/renderer/src/units.rs b/renderer/src/units.rs
index 0246ea3..64be479 100644
--- a/renderer/src/units.rs
+++ b/renderer/src/units.rs
@@ -296,18 +296,22 @@ pub fn top_tree(units: &[UnitBox]) -> Result<Vec<GpuNode>, String> {
Ok(nodes)
}
-/// A unit's record: the instance's (`scene::Instance::gpu`), with, in the three words the normal rows leave unused
-/// (trace_units.wgsl reads them as bits): its mesh tree's root; whether it casts shadows; whether it is placed by a
-/// translation alone (or not moved at all). The last is read off the record's own normal rows, which are then the
-/// identity's: the walk moves the ray's origin and leaves the rest of the ray as it is, which is what multiplying by
-/// these rows comes to, to the bit (the sign of a zero aside, which no comparison in the walk sees).
+/// A unit's record: the instance's (`scene::Instance::gpu`), with, in two of the words the normal rows leave unused
+/// (trace_units.wgsl reads them as bits): its mesh tree's root; and two flags, whether it casts shadows
+/// (`UNIT_SHADOW`) and whether it is placed by a translation alone, or not moved at all (`UNIT_SHIFTED`). The last is
+/// read off the record's own normal rows, which are then the identity's: the walk moves the ray's origin and leaves
+/// the rest of the ray as it is, which is what multiplying by these rows comes to, to the bit (the sign of a zero
+/// aside, which no comparison in the walk sees). (The third word is every instance's: its first emitter.)
pub fn unit_record(mut r: GpuInstance, root: u32, cast_shadow: bool) -> GpuInstance {
r.n[0][3] = f32::from_bits(root);
- r.n[1][3] = f32::from_bits(cast_shadow as u32);
- r.n[2][3] = f32::from_bits(translation_alone(&r) as u32);
+ r.n[1][3] = f32::from_bits(if cast_shadow { UNIT_SHADOW } else { 0 } | if translation_alone(&r) { UNIT_SHIFTED } else { 0 });
r
}
+/// The flags of a unit's record (`unit_record`; trace_units.wgsl).
+pub const UNIT_SHADOW: u32 = 1;
+pub const UNIT_SHIFTED: u32 = 2;
+
/// Whether a record's normal rows are the identity's.
pub fn translation_alone(r: &GpuInstance) -> bool {
(0..3).all(|k| (0..3).all(|c| r.n[k][c] == if k == c { 1.0 } else { 0.0 }))
@@ -1081,10 +1085,10 @@ pub(crate) mod cpu {
}
} else if rec == NO_INST {
let u = self.record(n.left_or_first)?;
- if mode != TRACE_SHADOW || u.n[1][3].to_bits() != 0 {
+ if mode != TRACE_SHADOW || u.n[1][3].to_bits() & UNIT_SHADOW != 0 {
rec = n.left_or_first;
ro = o - Vec3A::new(u.m[0][3], u.m[1][3], u.m[2][3]);
- if u.n[2][3].to_bits() == 0 {
+ if u.n[1][3].to_bits() & UNIT_SHIFTED == 0 {
ro = Self::proc_dir(&u, ro);
rd = Self::proc_dir(&u, d);
rinv = Self::inv(rd);
@@ -1176,10 +1180,10 @@ mod tests {
"continue;",
"} else if (rec == NO_INST) {",
"let u = instance_at(n.left_or_first);",
- "if (mode != TRACE_SHADOW || bitcast<u32>(u.n1.w) != 0u) {",
+ "if (mode != TRACE_SHADOW || (bitcast<u32>(u.n1.w) & UNIT_SHADOW) != 0u) {",
"rec = n.left_or_first;",
"ro = o - vec3<f32>(u.m0.w, u.m1.w, u.m2.w);",
- "if (bitcast<u32>(u.n2.w) == 0u) {",
+ "if ((bitcast<u32>(u.n1.w) & UNIT_SHIFTED) == 0u) {",
"ro = proc_dir(u, ro);",
"rd = proc_dir(u, d);",
"rinv = 1.0 / select(rd, vec3<f32>(1e-20), abs(rd) < vec3<f32>(1e-20));",
@@ -1329,7 +1333,7 @@ mod tests {
fn record(&self, mesh: usize, world: Mat4, cast: bool) -> GpuInstance {
let (first, _, root, ..) = self.meshes[mesh].unwrap();
- let inst = crate::scene::Instance { mesh: mesh as u32, world, object: 0, cast_shadow: cast, name: String::new(), sub: None, hidden: false };
+ let inst = crate::scene::Instance { mesh: mesh as u32, world, object: 0, cast_shadow: cast, name: String::new(), sub: None, hidden: false, first_emitter: 0 };
unit_record(inst.gpu(first, 0), root, cast)
}
@@ -1538,7 +1542,7 @@ mod tests {
refits += sc.kept.refits;
changes += sc.kept.changes;
builds += sc.kept.builds;
- short += sc.units.iter().enumerate().filter(|(k, u)| u.is_some() && sc.instances[*k].n[2][3].to_bits() == 1).count();
+ short += sc.units.iter().enumerate().filter(|(k, u)| u.is_some() && sc.instances[*k].n[1][3].to_bits() & UNIT_SHIFTED != 0).count();
}
assert!(edits > 300 && unit_hits * 8 > rays, "{edits} edits, {unit_hits} of {rays} closest hits on units");
assert!(refits > 40 && changes > 100 && builds > 100 && short > 20, "{refits} top trees kept, {changes} with the loose units' built, {builds} built over all; {short} units placed by a translation alone at the end");
@@ -1943,12 +1947,14 @@ mod tests {
// A built tree is a level short of the bound: two of them joined are at it.
assert!(check_tree(&build_sah(&(0..1 << 12).map(|k| (Vec3A::splat(k as f32), Vec3A::splat(k as f32 + 1.0))).collect::<Vec<_>>(), 12).0, 64, |_, _| Ok(())).unwrap() <= 12);
// The record's word for a placement by a translation alone.
- let rec = |world: Mat4| unit_record(crate::scene::Instance { mesh: 0, world, object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false }.gpu(0, 0), 9, true);
- assert_eq!(rec(Mat4::IDENTITY).n[2][3].to_bits(), 1);
- assert_eq!(rec(Mat4::from_translation(Vec3::new(3.0, -2.0, 0.5))).n[2][3].to_bits(), 1);
- assert_eq!(rec(Mat4::from_rotation_y(0.3)).n[2][3].to_bits(), 0);
- assert_eq!(rec(Mat4::from_scale(Vec3::splat(2.0))).n[2][3].to_bits(), 0);
- assert_eq!(rec(Mat4::from_scale(Vec3::new(1.0, -1.0, 1.0))).n[2][3].to_bits(), 0, "a mirror");
- assert_eq!((rec(Mat4::IDENTITY).n[0][3].to_bits(), rec(Mat4::IDENTITY).n[1][3].to_bits()), (9, 1));
+ let rec = |world: Mat4| unit_record(crate::scene::Instance { mesh: 0, world, object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false, first_emitter: 0 }.gpu(0, 0), 9, true);
+ let shifted = |m: Mat4| rec(m).n[1][3].to_bits() & UNIT_SHIFTED != 0;
+ assert!(shifted(Mat4::IDENTITY));
+ assert!(shifted(Mat4::from_translation(Vec3::new(3.0, -2.0, 0.5))));
+ assert!(!shifted(Mat4::from_rotation_y(0.3)));
+ assert!(!shifted(Mat4::from_scale(Vec3::splat(2.0))));
+ assert!(!shifted(Mat4::from_scale(Vec3::new(1.0, -1.0, 1.0))), "a mirror");
+ assert_eq!((rec(Mat4::IDENTITY).n[0][3].to_bits(), rec(Mat4::IDENTITY).n[1][3].to_bits() & UNIT_SHADOW), (9, 1));
+ assert_eq!(rec(Mat4::IDENTITY).n[2][3].to_bits(), 0, "the third word is not the unit's");
}
}
diff --git a/renderer/src/units_cost.rs b/renderer/src/units_cost.rs
index 0b00c5b..53bd986 100644
--- a/renderer/src/units_cost.rs
+++ b/renderer/src/units_cost.rs
@@ -409,7 +409,7 @@ fn units_pile() {
let made = (u.kept.builds - was.0, u.kept.changes - was.1, u.kept.refits - was.2);
// At rest: the kernel's buffers as a session would have written them.
for (j, p) in pieces.iter().enumerate() {
- let inst = scene::Instance { mesh, world: pose(p, 1.0), object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false };
+ let inst = scene::Instance { mesh, world: pose(p, 1.0), object: 0, cast_shadow: true, name: String::new(), sub: None, hidden: false, first_emitter: 0 };
l.instances[first_rec + j] = units::unit_record(inst.gpu(first_tri, tris.len() as u32), root as u32, true);
}
let at = u.layout.top_first as usize;
diff --git a/renderer/src/voxel.rs b/renderer/src/voxel.rs
index beafc8f..945750a 100644
--- a/renderer/src/voxel.rs
+++ b/renderer/src/voxel.rs
@@ -115,7 +115,7 @@ pub struct PaletteEntry {
pub color: [f32; 3],
pub roughness: f32,
pub metalness: f32,
- /// Emission, nits (its colour the entry's): voxels that glow, light-sampled as emitter meshes (ROADMAP § 6 step 4).
+ /// Emission, nits (its colour the entry's): voxels that glow, light-sampled as any mesh that emits (ROADMAP § 6 step 4).
#[serde(default)]
pub emissive: f32,
/// How far an explosion reaches it: "soft" (the default: the whole radius), "medium" (0.7 of it), "hard" (0.4),
diff --git a/tests/render/geometry-emitter-instance.ts b/tests/render/geometry-emitter-instance.ts
new file mode 100644
index 0000000..b381e47
--- /dev/null
+++ b/tests/render/geometry-emitter-instance.ts
@@ -0,0 +1,34 @@
+// A ray that hits an emitter of a mesh of its own is weighed against that emitter: the light list's entry at its
+// instance's first plus the triangle's number (pathtrace.wgsl `emit_mis`). An 8 x 8 m panel of 1 nit, 1 m above a
+// Lambert 0.5 floor: light sampling and the floor's BSDF rays both carry its light (MIS), so the floor below its
+// centre reads the analytic value only with the right entry. A speck of the same material, far away, holds the
+// list's first entries: the panel's instance does not start at 0. Irradiance below the centre of a parallel square
+// (4 corner terms, X = Y = half side / height = 4): E = 4 (L / 2) [X / sqrt(1 + X^2) atan(Y / sqrt(1 + X^2)) + Y /
+// sqrt(1 + Y^2) atan(X / sqrt(1 + Y^2))] = 2.989 L, and the floor reads 0.5 / pi x E.
+import { Color, Mesh, MeshStandardMaterial, PlaneGeometry } 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);
+
+export const test: TestMeta = {
+ id: "geometry/emitter-instance", features: ["emitters", "lambert", "dynamic-emission"], 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 },
+ 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 glow = new MeshStandardMaterial({ name: "glow", color: new Color(0, 0, 0), emissive: new Color(1, 1, 1), emissiveIntensity: 1, roughness: 1 });
+ const speck = new Mesh(new PlaneGeometry(0.01, 0.01), glow);
+ speck.name = "speck";
+ speck.dynamicGeometry = true;
+ speck.position.set(900, -50, 0);
+ const panel = new Mesh(new PlaneGeometry(8, 8), glow);
+ panel.name = "panel";
+ panel.dynamicGeometry = true;
+ 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"), speck, panel]);
+};