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, first part: the light list holds its triangles (#147)

Yujiac24531544ffb
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index a4ab955..89870cb 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2626,6 +2626,26 @@ entry of its own beside its copies', so its node's power or customData wrote ove
in what they can do: what the build flattened or placed as a model's instance is rebuilt to change, what an edit
placed is not moved unless a body drives it (step E).
+**The light list holds its triangles (2026-11-17, scene step D, first part).** Light sampling read an emitter's
+triangle from the triangles' table as world space, so whatever emits had to be stored there in world space:
+flattened, or a mesh of its own written in world space (Tokyo: 1,627,052 triangles flattened for it). The list has
+its own copy now, the way real-time engines keep a light list: `Table::EmitterTris`, one `GpuEmitterTri` an emitter
+(v0, e1, e2 in world space; its triangle, for the attributes; its object, for its power; the light tree's path
+code). The kernel's emitter sampling, light LOD, cull and the BSDF rays' weight (`emit_mis`) read it; a CDF entry
+names its emitter, and a triangle's attributes its emitter entry (`x.w`, where the path code was). The copies
+follow what moves: those of the emitters the CPU moves are rewritten when they do (`move_emitters`), those of the
+emitters edits make are written with their entries (`write_emitters`). A particle's is still read where its pass
+places it (F_PEMIT). Nothing is placed otherwise yet. What it costs: 48 B an emitter (Tokyo +78 MB); the trace
++0.07 to 0.10 ms where emitters are sampled (Bistro 7.18 -> 7.29 ms, Zero Day 7.52 -> 7.59, the crowd 7.25 ->
+7.32, Kabukichō 12.57 -> 12.63, Tokyo 4.41 -> 4.42; nothing in a scene without emitters), not attributed: a typed
+view of the table times the same, so does reading the rows without the record's struct; the crowd's 21,280 moving
+emitters take 0.2 ms of CPU a frame to rewrite (commit 4.88 -> 5.08 ms), which a GPU pass is to take over, with
+the particles' and the instances' (the next parts). Pictures: the big scenes within main's own run-to-run
+difference; of the suite's 239 outputs, 26 that repeat themselves differ from main's, in the last bits offline
+(up to 3.7e-7) and by a sample that falls otherwise in a few live ones (up to 2.1e-3 of a value; sums within
+3e-5). That is Metal's compiler rounding the new kernel otherwise: on Vulkan (RTX 5090) every one of the 26 is
+byte-identical to main's, natively and under software traversal.
+
## 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/docs/RUNTIME.md b/docs/RUNTIME.md
index 9488580..428deae 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -1484,8 +1484,9 @@ too is an override, from F_TINT).
The kernel's read-only scene data other than triangles is two storage buffers, each a row of sections
(`renderer/src/heap.rs`):
- `tables` (group 0, binding 4), vec4s (`Table`): the light tree's nodes, materials, lights, the light groups'
- spheres, the emitter CDF with its guide table, the texture pages' rects, objects, instance records, media and the
- GGX energy table.
+ spheres, the emitter CDF with its guide table, the texture pages' rects, objects, instance records, media, the
+ GGX and glass energy tables, and the emitters' triangles (`GpuEmitterTri`: the light list's own world-space
+ copies, so a light sample reads no placement).
- `words` (binding 5), 32-bit words (`Stream`): the environment's CDF, the procedural geometry's data, the vertex
colours (`env_cdf_at`, `pword`, `vcolor_word`). Integers are read as integers, not through a float's bits.
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index 8501203..bac702f 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -122,7 +122,7 @@ struct Params {
ltile: vec4<u32>, // live light tiles (`lt_list_start`): 1 with last frame's lists (0: none), tiles a row, the grid's offset when they were built (x | y << 16), candidates a vertex the camera sees takes from its list
ltile2: vec4<u32>, // the traced size they were built at, -, -
lt_cam: array<vec4<f32>, 4>, // the camera they were built under: position (w = tan(fov/2)), forward (w = aspect), right, up
- table_first: array<vec4<u32>, 3>, // each table's first vec4 in `tables` (heap.rs `Table`): light tree (0), materials, lights, light groups; emitters, tex_info, objects, instances; media, energy LUT, glass energy, -
+ table_first: array<vec4<u32>, 3>, // each table's first vec4 in `tables` (heap.rs `Table`): light tree (0), materials, lights, light groups; emitters, tex_info, objects, instances; media, energy LUT, glass energy, emitter triangles
word_first: vec4<u32>, // each stream's first word in `words` (heap.rs `Stream`): environment CDF (0), procedural data, vertex colours, -
live_first: array<vec4<u32>, 2>, // the merged layout: each of group 1's vec4 sections' first vec4 in `ML.vecs` (heap.rs `Live`): cache values (0), refl, motion, direct; lists, -, -, -
live_len: vec4<u32>, // and the vec4s of refl, motion, direct, lists
@@ -165,8 +165,9 @@ struct Medium { w0: vec4<f32>, w1: vec4<f32>, w2: vec4<f32>, a: vec4<u32>, b: ve
// The scene's tables: sections of one buffer of vec4s (heap.rs `Table`), each from the vec4 `P.table_first` names:
// - materials (scene::GpuMaterial), lights (scene::GpuLight), and per LIGHT_GROUP local lights a sphere (centre,
// radius) holding all their light (lib.rs `light_groups`);
-// - emitters: (triangle index bits, cumulative weight (normalized), weight, area) for i < counts.y, then the guide
-// table: EMITTER_GUIDE + 1 entry indices (bits), four per vec4 (lib.rs emitter_cdf); the light tree's nodes;
+// - emitters: (its emitter's index: bits, cumulative weight (normalized), weight, area) for i < counts.y, then the
+// guide table: EMITTER_GUIDE + 1 entry indices (bits), four per vec4 (lib.rs emitter_cdf); the emitters'
+// triangles (`EmitterTri`); the light tree's nodes;
// - tex_info, per texture: (u0, v0, du, dv) of its rect in the page, (layer, wrap, width, height). See texpack.rs;
// - objects, per object (scene node): pivot (world position), world bounds size (UE ObjectPositionWS /
// ObjectBounds), then what `OBJECT_STRIDE` says;
@@ -184,6 +185,19 @@ fn lt_node(i: u32) -> vec4<f32> { return table_f(i); }
fn light_group_at(i: u32) -> vec4<f32> { return table_f(P.table_first[0].w + i); }
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; `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 };
+const EMITTER_TRI_VEC4: u32 = 3u;
+const EMITTER_MOVES: u32 = 0x80000000u;
+fn emitter_tri_at(i: u32) -> EmitterTri {
+ let b = P.table_first[2].w + i * EMITTER_TRI_VEC4;
+ let r0 = tables[b];
+ let r1 = tables[b + 1u];
+ let r2 = tables[b + 2u];
+ return EmitterTri(bitcast<vec3<f32>>(r0.xyz), r0.w, bitcast<vec3<f32>>(r1.xyz), r1.w, bitcast<vec3<f32>>(r2.xyz), r2.w);
+}
// The seven tables read at every hit or light, through `material_at`, `light_at`, `emitter_at`, `tex_info_at`,
// `object_at`, `instance_at` and `medium_at` in every layout.
@if(merged || whole_tables) {
@@ -438,16 +452,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 triangle ti (attrs x.w: its path code, 0 = a
-// moving one), the same choices down its path; 0 for triangles not light-sampled.
-fn emitter_sel(ti: u32, x: vec3<f32>, n: vec3<f32>) -> f32 {
- let a = attrs[ti];
- let code = bitcast<u32>(a.x.w);
+// 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).
+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 || (has(F_PEMIT) && a.x.z < 0.0)) { return 0.0; }
- var area = 0.5 * length(cross(tri_verts[ti * 3u + 1u].xyz, tri_verts[ti * 3u + 2u].xyz));
+ 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) * obj_power(a) * area / P.misc.y;
+ return luminance(material_at(bitcast<u32>(a.uv.w)).emissive.rgb) * power_of(em.obj) * area / P.misc.y;
}
let depth = (code >> LT_PATH_BITS) - 1u;
var p = 1.0 - P.ltree.z;
@@ -469,7 +482,7 @@ fn emitter_sel(ti: u32, x: vec3<f32>, n: vec3<f32>) -> f32 {
for (var j = lo; j < hi; j++) {
let c = emitter_at(j);
wsum += c.z;
- if (bitcast<u32>(c.x) == ti) { we = c.z; }
+ if (bitcast<u32>(c.x) == ei) { we = c.z; }
}
return p * we / wsum;
}
@@ -1115,7 +1128,8 @@ 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 obj_power(a: TriAttr) -> f32 { return object_at(object_of(a) * OBJECT_STRIDE).w; }
+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)); }
// 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 {
@@ -1804,42 +1818,53 @@ fn sun_disks(d: vec3<f32>, pdf: f32) -> vec3<f32> {
return c;
}
+// The triangle of emitter `i`. (F_PEMIT, `placed`: a particle's is where its pass puts it each frame, in the
+// triangles' table: the list has no copy of it yet.)
+fn emitter_tri_of(i: u32, placed: bool) -> EmitterTri {
+ var em = emitter_tri_at(i);
+ if (has(F_PEMIT) && placed) {
+ em.v0 = tri_verts[em.tri * 3u].xyz;
+ em.e1 = tri_verts[em.tri * 3u + 1u].xyz;
+ em.e2 = tri_verts[em.tri * 3u + 2u].xyz;
+ }
+ return em;
+}
+
// 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)) { return 1.0; }
+ 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);
+ if (entry == 0u) { return 1.0; }
+ let em = emitter_tri_of(entry - 1u, ha.x.z != 0.0);
+ let cr = cross(em.e1, em.e2);
+ let area = 0.5 * length(cr);
+ let cos_l = abs(dot(normalize(cr), d));
if (lt_on()) {
// The light tree's pmf where the ray left (the vertex that sampled emitters), per area of the hit triangle.
- if (P.counts.y == 0u) { return 1.0; }
- let sel = emitter_sel(hit.tri, mis_x, mis_n);
+ let sel = emitter_sel(entry - 1u, em, ha, mis_x, mis_n);
if (!(sel > 0.0)) { return 1.0; }
- let crt = cross(tri_verts[hit.tri * 3u + 1u].xyz, tri_verts[hit.tri * 3u + 2u].xyz);
- let at = 0.5 * length(crt);
- return power_heuristic(pdf, sel / max(at, 1e-12) * hit.t * hit.t / max(abs(dot(normalize(crt), d)), 1e-6));
+ return power_heuristic(pdf, sel / max(area, 1e-12) * hit.t * hit.t / max(cos_l, 1e-6));
}
- if (P.counts.y == 0u || P.misc.y <= 0.0 || emitter_culled(hit.tri)) { return 1.0; }
- let cr = cross(tri_verts[hit.tri * 3u + 1u].xyz, tri_verts[hit.tri * 3u + 2u].xyz);
- let area = 0.5 * length(cr);
- let cos_l = abs(dot(normalize(cr), d));
- let ha = attrs[hit.tri];
+ 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) * obj_power(ha) / P.emit_power.x;
+ let pdf_a = luminance(mat.emissive.rgb) * power_of(em.obj) / 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 (> 0) is what the CDF weighed them by, the point is uniform over the actual
- // area; without one (< 0) they are not light-sampled and the BSDF ray is the only estimator.
- if (ha.x.z < 0.0) { return 1.0; }
+ // Particles (x.z > 0): a nominal area is what the CDF weighed them by, the point is uniform over the actual area.
+ // (Those without one, x.z < 0, are not light-sampled: no entry.)
return power_heuristic(pdf, pdf_w * ha.x.z / max(area, 1e-12));
}
-// Light LOD factor of emitter triangle ti (lib.rs emitter_lod): the emitter CDF's weights carry it, so every pdf of an
-// emitter point does too. Moving triangles have none (lib.rs EmitterTri::moves).
-fn emitter_lod(ti: u32) -> f32 {
- let v0 = tri_verts[ti * 3u];
- if (P.light_lod.w <= 0.0 || (bitcast<u32>(v0.w) & TRI_DYNAMIC) != 0u) { return 1.0; }
- let c = v0.xyz + (tri_verts[ti * 3u + 1u].xyz + tri_verts[ti * 3u + 2u].xyz) / 3.0;
+// Light LOD factor of an emitter (lib.rs emitter_lod): the emitter CDF's weights carry it, so every pdf of an
+// emitter point does too. Moving ones have none (lib.rs EmitterTri::moves).
+fn emitter_lod(em: EmitterTri) -> f32 {
+ if (P.light_lod.w <= 0.0 || (em.code & EMITTER_MOVES) != 0u) { return 1.0; }
+ let c = em.v0 + (em.e1 + em.e2) / 3.0;
let k = P.light_lod.w / max(distance(c, P.light_lod.xyz), P.light_lod.w);
return k * k;
}
@@ -1847,22 +1872,15 @@ fn emitter_lod(ti: u32) -> f32 {
// Live: emitters farther than P.emit_power.y from the light LOD's reference are never proposed (lib.rs emitter_lod),
// so BSDF rays that hit them keep their whole light (emit_mis), unless they lie in the view cone (P.lod_view) within
// P.emit_power.z: those light what the camera sees. The same centroid and test as lib.rs EmitterCull::culls.
-fn emitter_culled(ti: u32) -> bool {
+fn emitter_culled(em: EmitterTri) -> bool {
if (P.emit_power.y <= 0.0 || P.light_lod.w <= 0.0) { return false; }
- let v0 = tri_verts[ti * 3u];
- if ((bitcast<u32>(v0.w) & TRI_DYNAMIC) != 0u) { return false; }
- let c = v0.xyz + (tri_verts[ti * 3u + 1u].xyz + tri_verts[ti * 3u + 2u].xyz) / 3.0;
+ if ((em.code & EMITTER_MOVES) != 0u) { return false; }
+ let c = em.v0 + (em.e1 + em.e2) / 3.0;
let d = distance(c, P.light_lod.xyz);
if (d <= P.emit_power.y) { return false; }
return !(d <= P.emit_power.z && dot(c - P.light_lod.xyz, P.lod_view.xyz) >= P.lod_view.w * d);
}
-fn emitter_pdf_area(tri: u32, emissive: vec3<f32>) -> f32 {
- // Selection probability (area * luminance / total) times 1/area => luminance / total.
- if (P.counts.y == 0u || P.misc.y <= 0.0) { return 0.0; }
- return luminance(emissive) / P.misc.y;
-}
-
// ------------------------------------------------------------------------------------------------
// Direct lighting (NEE)
@@ -2091,18 +2109,17 @@ fn local_lights(s: Surface, lb: Lobes, v: vec3<f32>, o: vec3<f32>, x: vec3<f32>,
// weight `w` (1 / pdf, or the RIS weight).
struct ES { le: vec3<f32>, l: vec3<f32>, dist: f32, pdf_w: f32, w: f32 };
-// Emitted radiance of triangle ti at (b1, b2) toward -l (emissive map, animation, material function, node power).
-fn emitter_radiance(ti: u32, b1: f32, b2: f32, l: vec3<f32>) -> vec3<f32> {
- let a = attrs[ti];
- let mi = bitcast<u32>(a.uv.w);
- let m = material_at(mi);
+// 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 m = material_at(bitcast<u32>(a.uv.w));
// 5 cm footprint: a blurred texel is plenty for lighting and keeps NEE cheap.
- let pw = obj_power(a);
+ let pw = power_of(em.obj);
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);
mb.emissive *= pw;
- le = emissive_material_function(m.tex1.w - 1, mat_in_at(ti, b1, b2, -l, log2(0.05)), m, mb).emissive;
+ le = emissive_material_function(m.tex1.w - 1, mat_in_at(em.tri, b1, b2, -l, log2(0.05)), m, mb).emissive;
}
return le;
}
@@ -2122,10 +2139,10 @@ fn emitter_radiance(ti: u32, b1: f32, b2: f32, l: vec3<f32>) -> vec3<f32> {
fn sample_emitter_ris(x: vec3<f32>, n: vec3<f32>, m: u32, sf: Surface, lb: Lobes, v: vec3<f32>, rd: u32) -> ES {
var r = ES(vec3<f32>(0.0), vec3<f32>(0.0, 1.0, 0.0), 0.0, 0.0, 0.0);
var wsum = 0.0;
- var pick_ti = 0u;
var pick_b = vec2<f32>(0.0);
var pick_ph = 0.0;
var pick_e = vec4<f32>(0.0);
+ var pick_placed = false;
var pick_sel = 0.0;
for (var k = 0u; k < m; k++) {
let dk = rng_sub(rd, k);
@@ -2136,10 +2153,10 @@ fn sample_emitter_ris(x: vec3<f32>, n: vec3<f32>, m: u32, sf: Surface, lb: Lobes
var b2 = bb.y;
if (pk.p <= 0.0) { continue; }
if (b1 + b2 > 1.0) { b1 = 1.0 - b1; b2 = 1.0 - b2; }
- let ti = bitcast<u32>(e.x);
- let e1 = tri_verts[ti * 3u + 1u].xyz;
- let e2 = tri_verts[ti * 3u + 2u].xyz;
- let lp = tri_verts[ti * 3u].xyz + e1 * b1 + e2 * b2;
+ let em = emitter_tri_of(bitcast<u32>(e.x), e.w < 0.0);
+ let e1 = em.e1;
+ let e2 = em.e2;
+ let lp = em.v0 + e1 * b1 + e2 * b2;
let ln = normalize(cross(e1, e2));
let dl = lp - x;
let d2 = max(dot(dl, dl), 1e-8);
@@ -2148,7 +2165,7 @@ fn sample_emitter_ris(x: vec3<f32>, n: vec3<f32>, m: u32, sf: Surface, lb: Lobes
if (m > 1u) { g = abs(dot(ln, l)) * luminance(eval_bsdf(sf, lb, v, l)) / d2; }
// target (emitted luminance x G) over source pdf (luminance x light LOD / total, per area) = total x G / LOD;
// with the tree the source pdf is its selection probability / area (weight / area = luminance x power)
- let lk = emitter_lod(ti);
+ let lk = emitter_lod(em);
var w = select(P.misc.y * g / lk, pk.w * g / pk.p, lt_on());
// Particle emitters (e.w < 0): weighed by a nominal area -e.w, sampled over the actual one (0 when not shown).
var ae = e.w;
@@ -2160,28 +2177,28 @@ fn sample_emitter_ris(x: vec3<f32>, n: vec3<f32>, m: u32, sf: Surface, lb: Lobes
if (w <= 0.0) { continue; }
wsum += w;
if (bb.z * wsum < w) {
- pick_ti = ti;
pick_b = vec2<f32>(b1, b2);
pick_ph = pk.w / (abs(e.w) * lk) * g;
pick_e = vec4<f32>(e.x, e.y, e.z / lk, ae);
+ pick_placed = e.w < 0.0;
pick_sel = pk.p;
}
}
if (pick_ph <= 0.0) { return r; }
- let ti = pick_ti;
- let e1 = tri_verts[ti * 3u + 1u].xyz;
- let e2 = tri_verts[ti * 3u + 2u].xyz;
- let lp = tri_verts[ti * 3u].xyz + e1 * pick_b.x + e2 * pick_b.y;
+ let em = emitter_tri_of(bitcast<u32>(pick_e.x), pick_placed);
+ let e1 = em.e1;
+ let e2 = em.e2;
+ let lp = em.v0 + e1 * pick_b.x + e2 * pick_b.y;
let ln = normalize(cross(e1, e2));
let dl = lp - x;
let d2 = dot(dl, dl);
let dist = sqrt(d2);
let l = dl / dist;
var cos_l = dot(ln, -l);
- let m_card = material_at(bitcast<u32>(attrs[ti].uv.w)).tex1.z == MAT_EMITTER_CARD;
+ let m_card = material_at(bitcast<u32>(attrs[em.tri].uv.w)).tex1.z == MAT_EMITTER_CARD;
if (!m_card) { cos_l = abs(cos_l); }
if (cos_l <= 0.0) { return r; }
- r.le = emitter_radiance(ti, pick_b.x, pick_b.y, l);
+ r.le = emitter_radiance(em, pick_b.x, pick_b.y, l);
r.l = l;
r.dist = dist;
// MIS by the source pdf: power alone without the tree (emit_mis), the tree's pmf with it
@@ -2197,10 +2214,10 @@ fn sample_emitter(x: vec3<f32>, n: vec3<f32>, rd: u32) -> ES {
let pk = emitter_draw(x, n, rd);
let e = pk.e;
if (pk.p <= 0.0) { return r; } // switched off (power 0)
- let ti = bitcast<u32>(e.x);
- let v0 = tri_verts[ti * 3u].xyz;
- let e1 = tri_verts[ti * 3u + 1u].xyz;
- let e2 = tri_verts[ti * 3u + 2u].xyz;
+ let em = emitter_tri_of(bitcast<u32>(e.x), e.w < 0.0);
+ let v0 = em.v0;
+ let e1 = em.e1;
+ let e2 = em.e2;
let bb = rng2(rng_sub(rd, 1u));
var b1 = bb.x;
var b2 = bb.y;
@@ -2213,20 +2230,10 @@ fn sample_emitter(x: vec3<f32>, n: vec3<f32>, rd: u32) -> ES {
let d2 = dot(dl, dl);
let dist = sqrt(d2);
let l = dl / dist;
- let a = attrs[ti];
- let mi = bitcast<u32>(a.uv.w);
- let m = material_at(mi);
var cos_l = dot(ln, -l);
- if (m.tex1.z != MAT_EMITTER_CARD) { cos_l = abs(cos_l); }
+ if (material_at(bitcast<u32>(attrs[em.tri].uv.w)).tex1.z != MAT_EMITTER_CARD) { cos_l = abs(cos_l); }
if (cos_l <= 0.0 || (has(F_PEMIT) && !(cos_l > 0.0))) { return r; } // also a particle not shown (no area: NaN)
- // 5 cm footprint: a blurred texel is plenty for lighting and keeps NEE cheap.
- let pw = obj_power(a);
- r.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);
- mb.emissive *= pw;
- r.le = emissive_material_function(m.tex1.w - 1, mat_in_at(ti, b1, b2, -l, log2(0.05)), m, mb).emissive;
- }
+ r.le = emitter_radiance(em, b1, b2, l);
r.l = l;
r.dist = dist;
r.pdf_w = pk.p / area * d2 / cos_l;
diff --git a/renderer/shaders/records.wgsl b/renderer/shaders/records.wgsl
index 84643d6..8471bd5 100644
--- a/renderer/shaders/records.wgsl
+++ b/renderer/shaders/records.wgsl
@@ -3,7 +3,8 @@
// `live_source`, build.rs).
// A triangle's shading attributes (scene.rs GpuTriAttr): normals (w: uv parts), uv parts (w: material index, bits),
-// tangent (w: bitangent sign), x: (texel density, object (bits), a particle's area, light-tree path code).
+// tangent (w: bitangent sign), x: (texel density, object (bits), a particle's area, its emitter entry + 1 (bits; 0: it
+// is not light-sampled)).
struct TriAttr { n0: vec4<f32>, n1: vec4<f32>, n2: vec4<f32>, uv: vec4<f32>, t: vec4<f32>, x: vec4<f32> };
// A sample the kernel leaves in `accum`. Live: color = diffuse lighting at the first hit (w: first-hit distance, 0 =
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index 7702476..7af8eed 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -2183,7 +2183,7 @@ impl Gpu {
/// Uploads a prepared scene (geometry, materials, textures, environment, acceleration structures) and returns the
/// bind group used by both the offline and the live kernels. `accum` holds one 80-byte Pixel per output pixel.
#[allow(clippy::too_many_arguments)]
- pub fn upload(&self, scene: &Scene, accum: &wgpu::Buffer, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], timings: &mut Vec<(String, f64)>) -> Result<Uploaded> {
+ pub fn upload(&self, scene: &Scene, accum: &wgpu::Buffer, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], emitter_tris: &[crate::GpuEmitterTri], light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], timings: &mut Vec<(String, f64)>) -> Result<Uploaded> {
let d = &self.device;
let t0 = Instant::now();
// (The vertices too: the kernel's tree over no triangle is a leaf of triangle 0, which these zeros make a
@@ -2301,6 +2301,7 @@ impl Gpu {
(Table::Media, bytemuck::cast_slice(&scene.media), 0),
(Table::Energy, bytemuck::cast_slice(energy), 0),
(Table::GlassEnergy, bytemuck::cast_slice(crate::glass_energy_lut()), 0),
+ (Table::EmitterTris, bytemuck::cast_slice(emitter_tris), 0),
];
assert!(parts.iter().enumerate().all(|(k, p)| p.0.index() == k), "the tables in `Table`'s order");
let heap = Heap::filled(d, &parts.map(|p| (p.1.len() + p.2) as u64), |put| parts.iter().for_each(|p| put(p.0, 0, p.1)));
@@ -3409,10 +3410,10 @@ impl Gpu {
#[cfg(not(target_arch = "wasm32"))]
/// Render `spp` samples. `base` holds everything except the per-dispatch sample index.
#[allow(clippy::too_many_arguments)]
- pub fn render(&self, scene: &Scene, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], base: Params, spp: u32, timings: &mut Vec<(String, f64)>) -> Result<Frame> {
+ pub fn render(&self, scene: &Scene, tri_verts: &[[f32; 4]], groups: [usize; GROUPS], nodes: &[u8], emitters: &[[f32; 4]], emitter_tris: &[crate::GpuEmitterTri], light_tree: &[[f32; 4]], env: &EnvMap, env_cdf: &[f32], energy: &[[f32; 4]], base: Params, spp: u32, timings: &mut Vec<(String, f64)>) -> Result<Frame> {
let d = &self.device;
let (w, h) = (scene.width, scene.height);
- let up = self.upload(scene, &self.accum_buffer(w, h), tri_verts, groups, nodes, emitters, light_tree, env, env_cdf, energy, timings)?;
+ let up = self.upload(scene, &self.accum_buffer(w, h), tri_verts, groups, nodes, emitters, emitter_tris, light_tree, env, env_cdf, energy, timings)?;
let pipeline = self.pipeline(&up.kernel, false);
// Particles: placed once, at the scene time and camera.
if up.particles.is_some() {
diff --git a/renderer/src/heap.rs b/renderer/src/heap.rs
index 954a77b..a2c84d5 100644
--- a/renderer/src/heap.rs
+++ b/renderer/src/heap.rs
@@ -35,7 +35,7 @@ pub enum Table {
Lights,
/// One sphere (centre, radius) per `LIGHT_GROUP` local lights (lib.rs `light_groups`).
LightGroups,
- /// The emitter CDF: (triangle bits, cumulative weight, weight, area) per emissive triangle (lib.rs `emitter_cdf`).
+ /// The emitter CDF: (its emitter's index: bits, cumulative weight, weight, area) per entry (lib.rs `emitter_cdf`).
Emitters,
/// Two vec4s a texture (texpack.rs).
TexInfo,
@@ -49,10 +49,12 @@ pub enum Table {
Energy,
/// The glass energy table (lib.rs `glass_energy_lut`).
GlassEnergy,
+ /// The emitters' triangles in world space (lib.rs `GpuEmitterTri`), three vec4s an emitter.
+ EmitterTris,
}
impl Section for Table {
- const COUNT: usize = 11;
+ const COUNT: usize = 12;
const UNIT: u64 = 16;
const LABEL: &'static str = "tables";
fn index(self) -> usize {
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index bcc9f8e..7575006 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -70,6 +70,8 @@ pub struct Prepared {
pub nodes: Vec<bvh::GpuNode>,
/// The emitter CDF (`emitter_cdf`): one entry per `emitter_tris`, then the guide table.
pub emitters: Vec<[f32; 4]>,
+ /// The emitters' triangles as light sampling reads them, one per `emitter_tris`.
+ pub gpu_emitter_tris: Vec<GpuEmitterTri>,
pub env: gpu::EnvMap,
pub env_cdf: Vec<f32>,
pub params: gpu::Params,
@@ -129,6 +131,39 @@ pub struct EmitterTri {
pub in_tree: bool,
}
+/// `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`.
+#[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 e2: [f32; 3],
+ pub code: u32,
+}
+
+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 } }
+ }
+
+ /// As `new`, from its vertices.
+ pub fn of(e: &EmitterTri, [a, b, c]: [glam::Vec3A; 3], code: u32) -> 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)
+ }
+}
+
/// An emitter triangle's power: area x emissive-factor luminance x object power (its CDF weight without light LOD).
pub fn emitter_power(e: &EmitterTri, materials: &[scene::GpuMaterial], objects: &[[f32; 4]], stride: usize) -> f32 {
let m = &materials[e.mat as usize];
@@ -316,21 +351,22 @@ pub fn light_groups(lights: &[scene::GpuLight]) -> Vec<[f32; 4]> {
/// Buckets of the emitter CDF's guide table (pathtrace.wgsl `EMITTER_GUIDE`, a power of two).
pub const EMITTER_GUIDE: usize = 65536;
-/// Emitter CDF entries (triangle bits, normalized cumulative weight, weight, area), one per triangle, then the guide
-/// table; the total weight and the total without light LOD (Params::emit_power). Weight = area x emissive luminance x
-/// object power (x light LOD). Triangles switched off keep a zero-weight entry.
+/// Emitter CDF entries (its emitter's index in `emitter_tris`: bits, normalized cumulative weight, weight, area), one
+/// per `entries` item (an emitter and its index), in their order; then the guide table; the total weight and the total
+/// without light LOD (Params::emit_power). Weight = area x emissive luminance x object power (x light LOD). Triangles
+/// switched off keep a zero-weight entry.
/// Guide table (the cutpoint method): EMITTER_GUIDE + 1 indices, four per vec4 (bits); index k is where the kernel's
/// binary search lands for u = k / EMITTER_GUIDE, so a draw u only searches between the indices of its bucket and the
/// next, and finds the same entry as a search over the whole CDF.
-pub fn emitter_cdf(tris: &[EmitterTri], materials: &[scene::GpuMaterial], objects: &[[f32; 4]], stride: usize, lod: [f32; 4], cull: EmitterCull) -> (Vec<[f32; 4]>, f32, f32) {
+pub fn emitter_cdf<'a>(entries: impl ExactSizeIterator<Item = (usize, &'a EmitterTri)>, materials: &[scene::GpuMaterial], objects: &[[f32; 4]], stride: usize, lod: [f32; 4], cull: EmitterCull) -> (Vec<[f32; 4]>, f32, f32) {
let (mut total, mut power) = (0.0f32, 0.0f32);
- let mut out = Vec::with_capacity(tris.len());
- for e in tris {
+ let mut out = Vec::with_capacity(entries.len());
+ for (i, e) in entries {
let lod_k = if e.moves { 1.0 } else { emitter_lod(e.c, lod, cull) };
let p = emitter_power(e, materials, objects, stride);
power += p;
total += p * lod_k;
- out.push([f32::from_bits(e.tri), total, p * lod_k, if e.nominal { -e.area } else { e.area }]);
+ out.push([f32::from_bits(i as u32), total, p * lod_k, if e.nominal { -e.area } else { e.area }]);
}
if total > 0.0 {
for e in &mut out {
@@ -595,7 +631,7 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
}
let tri_order = bvh.order[..pool_first.min(bvh.order.len())].to_vec();
// Many static emitters: a light tree samples them by importance at the shading point (`ltree`); each one's path
- // code in its triangle's attrs x.w (emit_mis). THREERT_LTREE=0: the CDF alone (A/B).
+ // code with its triangle in the list (emit_mis). THREERT_LTREE=0: the CDF alone (A/B).
// (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");
@@ -604,11 +640,10 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
// The tree's emitters first, in leaf order (each node covers a range of entries), then the rest as they were.
let mut taken = vec![false; emitter_tris.len()];
let mut ordered: Vec<EmitterTri> = Vec::with_capacity(emitter_tris.len());
- for (k, &i) in t.order.iter().enumerate() {
+ for &i in &t.order {
taken[i as usize] = true;
let mut e = emitter_tris[i as usize];
e.in_tree = true;
- sc.attrs[e.tri as usize].x[3] = f32::from_bits(t.code[k]);
ordered.push(e);
}
ordered.extend(emitter_tris.iter().zip(&taken).filter(|(_, t)| !**t).map(|(e, _)| *e));
@@ -616,7 +651,14 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
// From here on an entry of the tree is its position in `emitter_tris` (the live view's refits read it so).
t.order = (0..t.order.len() as u32).collect();
}
- let (emitters, total, _) = emitter_cdf(&emitter_tris, &sc.materials, &sc.objects, sc.object_stride(), [0.0; 4], EmitterCull::default());
+ // The list's triangles (the tree's entries are the first, each with its code), and each triangle's entry + 1 in
+ // its attributes (x.w), for the rays that hit it (emit_mis).
+ let code = |i: usize| light_tree.as_ref().and_then(|t| t.code.get(i)).copied().unwrap_or(0);
+ let gpu_emitter_tris: Vec<GpuEmitterTri> = emitter_tris.iter().enumerate().map(|(i, e)| GpuEmitterTri::new(e, &tri_verts[e.tri as usize * 3..][..3], code(i))).collect();
+ for (i, e) in emitter_tris.iter().enumerate() {
+ sc.attrs[e.tri as usize].x[3] = f32::from_bits(i as u32 + 1);
+ }
+ let (emitters, total, _) = emitter_cdf(emitter_tris.iter().enumerate(), &sc.materials, &sc.objects, sc.object_stride(), [0.0; 4], EmitterCull::default());
// The moving emitters (after the tree's in the CDF) are picked with the probability of their share of power.
let ltree_param = light_tree.as_ref().map_or([0.0; 4], |t| [0.0, f32::from_bits(t.order.len() as u32), if total > 0.0 { ((total - t.power) / total).max(0.0) } else { 0.0 }, ltree::RIS_OFFLINE as f32]);
@@ -707,7 +749,7 @@ pub fn prepare_as(hwrt: bool, units: bool, sc: &mut scene::Scene, timings: &mut
first += u32::try_from(count).expect("more than 2^32 triangles");
}
let energy = energy_lut();
- Prepared { tri_verts, groups, nodes, emitters, env, env_cdf, params, energy, emitter_tris, light_tree, env_nee_floor, mat_runs, fixed_mats, tri_order }
+ Prepared { tri_verts, groups, nodes, emitters, gpu_emitter_tris, env, env_cdf, params, energy, emitter_tris, light_tree, env_nee_floor, mat_runs, fixed_mats, tri_order }
}
/// Instances as world-space triangles (software traversal), appended to the flattened ones with their objects.
@@ -1231,7 +1273,7 @@ mod light_lod_tests {
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 })
.collect();
- let (t, total, _) = emitter_cdf(&tris, &mats, &[], 3, [20.0, 0.0, 30.0, 10.0], EmitterCull::default());
+ let (t, total, _) = emitter_cdf(tris.iter().enumerate(), &mats, &[], 3, [20.0, 0.0, 30.0, 10.0], EmitterCull::default());
let n = tris.len() as u32;
assert!(total > 0.0);
assert_eq!(t.len(), tris.len() + (EMITTER_GUIDE + 1).div_ceil(4));
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 4ec181b..bf33b13 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -502,9 +502,10 @@ impl LiveCore {
catch_up.flush_section(&self.g.queue, &self.sc.up.heap, Table::Instances);
}
if rigid_ok && (dynamic.is_empty() || (!changes.structural && self.repose(world, &dynamic, &mut top)?)) {
- // Moved emitters: the light tree's moving subtree around them, once (after every in-place update).
+ // Moved emitters: their triangles in the list and the light tree's moving subtree around them, once (after
+ // every in-place update).
if std::mem::take(&mut self.emitters_moved) {
- self.refit_moving_tree();
+ self.move_emitters();
}
changes.poses.clear();
changes.moved.clear();
@@ -570,8 +571,8 @@ impl LiveCore {
up.heap.write(q, Table::Objects, 0, bytemuck::cast_slice(&e.objects));
}
if d.materials || d.emitters {
- self.add_material_emitters();
- self.write_emitters();
+ let new = self.add_material_emitters();
+ self.write_emitters(&new);
} else if d.deferred {
self.send_powers();
}
@@ -818,9 +819,10 @@ impl LiveCore {
/// Emitter entries for the materials that started emitting (`Tables::started_emitting`): their flattened static
/// triangles (`mat_runs`), positions from `tris`, in the power-share part of the CDF (path code 0, as the light
- /// tree's moving emitters; ROADMAP § 6 step 3). `write_emitters` uploads them.
- pub(super) fn add_material_emitters(&mut self) {
+ /// tree's moving emitters; ROADMAP § 6 step 3). Returns them (each one's index and triangle) for `write_emitters`.
+ pub(super) fn add_material_emitters(&mut self) -> Vec<(u32, crate::GpuEmitterTri)> {
let sc = &mut self.sc;
+ let mut new = vec![];
for mat in std::mem::take(&mut sc.tables.started_emitting) {
for &[first, end, obj] in sc.mat_runs.get(&mat).map_or(&[][..], |v| v.as_slice()) {
for k in first..end {
@@ -828,26 +830,38 @@ impl LiveCore {
let area = 0.5 * (b - a).cross(c - a).length();
if area > 0.0 {
let centre = (a + b + c) / 3.0;
- sc.tables.emitter_tris.push(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 };
+ new.push((sc.tables.emitter_tris.len() as u32, crate::GpuEmitterTri::of(&e, [a, b, c], 0)));
+ sc.tables.emitter_tris.push(e);
}
}
}
}
+ new
}
/// The emitter CDF from `Tables::emitter_tris` (weights from materials and powers; entries added in place at its
/// end, removed ones at area 0), the light tree refit to the new weights and its nodes after the CDF, the CDF's
/// share of power, its count. With the tree's slot for emitters added in place (scenes that can edit geometry), their
/// subtree is grown again first and their entries go right after the static ones (ROADMAP § 6 step 4); without it
- /// they stay at the end, by power share. The buffer grows (and the scene bind group is made again) when entries
- /// were added past it: a scene that adds none keeps its layout.
- pub(super) fn write_emitters(&mut self) {
+ /// they stay at the end, by power share. `new`: the emitters made or made again since the last call (each one's
+ /// index and triangle): their triangles into the list, their entries into their triangles' attributes. The tables
+ /// grow (and the scene bind group is made again) when entries were added past them: a scene that adds none keeps
+ /// its layout.
+ 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 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)));
+ }
+ 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
// those alive, their entries right after the static ones in the CDF (in its leaf order: each leaf's entry is its
- // position) and their path codes in their triangles' attrs (written over the code 0 an edit gave them).
+ // position) and their path codes with their triangles in the list (written over the code 0 they were made with).
let mut perm: Option<Vec<usize>> = None;
if let Some(t) = e.light_tree.as_mut() {
if let Some((_, ns)) = t.dynamic {
@@ -860,37 +874,37 @@ impl LiveCore {
let Some([va, vb, vc]) = verts(x.tri as usize).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();
t.set_dynamic(items);
- let at = std::mem::offset_of!(scene::GpuTriAttr, x) + 12;
- let mut codes = Gather::default();
+ let at = std::mem::offset_of!(crate::GpuEmitterTri, code);
let mut placed = vec![false; e.emitter_tris.len()];
let mut p: Vec<usize> = (0..ns).collect();
for k in ns..t.order.len() {
let i = t.order[k] as usize;
- codes.put((e.emitter_tris[i].tri as usize * std::mem::size_of::<scene::GpuTriAttr>() + at) as u64, bytemuck::bytes_of(&t.code[k]));
+ w_tris.put((i * size + at) as u64, bytemuck::bytes_of(&t.code[k]));
placed[i] = true;
p.push(i);
}
- codes.flush(&g.queue, &up.attrs);
+ // (One the subtree no longer holds: no code.)
+ for i in was.into_iter().filter(|&i| !placed[i as usize]) {
+ w_tris.put((i as usize * size + at) as u64, bytemuck::bytes_of(&0u32));
+ }
p.extend((ns..e.emitter_tris.len()).filter(|&i| !placed[i]));
perm = Some(p);
}
}
- let permuted: Vec<crate::EmitterTri>;
- let list = match &perm {
- Some(p) => {
- permuted = p.iter().map(|&i| e.emitter_tris[i]).collect();
- &permuted[..]
- }
- None => &e.emitter_tris[..],
+ let (em, total, power) = match &perm {
+ Some(p) => crate::emitter_cdf(p.iter().map(|&i| (i, &e.emitter_tris[i])), &e.materials, &e.objects, e.stride, b.light_lod, crate::EmitterCull::of(b)),
+ None => crate::emitter_cdf(e.emitter_tris.iter().enumerate(), &e.materials, &e.objects, e.stride, b.light_lod, crate::EmitterCull::of(b)),
};
- let (em, total, power) = crate::emitter_cdf(list, &e.materials, &e.objects, e.stride, b.light_lod, crate::EmitterCull::of(b));
if let Some(t) = e.light_tree.as_mut() {
let (tris, mats, objs, st) = (&e.emitter_tris, &e.materials, &e.objects, e.stride);
let w: Vec<f32> = t.order.iter().map(|&i| crate::emitter_power(&tris[i as usize], mats, objs, st)).collect();
t.refit(&|k| w[k]);
}
self.put_emitters(&em, total, power);
+ // (After `put_emitters`: the list's room for them is there.)
+ w_tris.flush_section(&self.g.queue, &self.sc.up.heap, Table::EmitterTris);
// Emitters added in place since the worker was made: another, over them.
if self.sc.emit.as_ref().is_some_and(|w| w.count != self.sc.tables.emitter_tris.len()) {
self.sc.emit = EmitterWorker::new(&self.sc.tables, &self.g.device);
@@ -898,25 +912,27 @@ impl LiveCore {
}
}
- /// The emitter CDF `em` (its total weight and the emitters' power) and the light tree's nodes into their tables
- /// (grown, and the scene's bind groups made again, when they no longer fit), and the kernel's parameters.
+ /// The emitter CDF `em` (its total weight and the emitters' power) and the light tree's nodes into their tables,
+ /// and the kernel's parameters. The tables, and the one of the emitters' triangles, are grown (and the scene's bind
+ /// groups made again) when they no longer hold the list.
pub(super) fn put_emitters(&mut self, em: &[[f32; 4]], total: f32, power: f32) {
let g = &self.g;
- let LoadedScene { tables: e, base: b, up, .. } = &mut self.sc;
+ let LoadedScene { tables: e, up, .. } = &mut self.sc;
let nodes: &[[f32; 4]] = e.light_tree.as_ref().map_or(&[], |t| &t.nodes);
+ let tris = e.emitter_tris.len() * std::mem::size_of::<crate::GpuEmitterTri>();
let mut grew = false;
- for (t, data) in [(Table::Emitters, em), (Table::LightTree, nodes)] {
- let need = (data.len() * 16) as u64;
+ for (t, need) in [(Table::Emitters, em.len() * 16), (Table::LightTree, nodes.len() * 16), (Table::EmitterTris, tris)] {
+ let need = need as u64;
if need > up.heap.cap(t) {
up.heap.grow(&g.device, &g.queue, t, need + need / 2);
grew = true;
}
- up.heap.write(&g.queue, t, 0, bytemuck::cast_slice(data));
}
+ up.heap.write(&g.queue, Table::Emitters, 0, bytemuck::cast_slice(em));
+ up.heap.write(&g.queue, Table::LightTree, 0, bytemuck::cast_slice(nodes));
if grew {
g.rebind_scene(up);
}
- let _ = b;
self.emitter_params(total, power);
}
@@ -956,7 +972,7 @@ impl LiveCore {
self.sc.emit = None;
e.defer_powers = false;
self.sc.up.heap.write(&self.g.queue, Table::Objects, 0, bytemuck::cast_slice(&self.sc.tables.objects));
- self.write_emitters();
+ self.write_emitters(&[]);
return;
}
w.flight = Some(powers);
@@ -1365,17 +1381,31 @@ impl LiveCore {
Ok(true)
}
- /// now (the CPU copy of the dynamic tail), its nodes and the root uploaded (`ltree::LightTree::refit_moving`).
- pub(super) fn refit_moving_tree(&mut self) {
+ /// The moving emitters moved (`LoadedScene::moving_emitters`): their triangles in the list as they are now (the CPU
+ /// copy of the dynamic tail), each run of consecutive ones in one write; and the light tree's moving subtree refit
+ /// around them, its nodes and the root uploaded (`ltree::LightTree::refit_moving`).
+ pub(super) fn move_emitters(&mut self) {
let first = self.sc.dynamic.0;
let (verts, tables) = (&self.sc.dynamic.1, &mut self.sc.tables);
let tris = &tables.emitter_tris;
+ let (q, heap) = (&self.g.queue, &self.sc.up.heap);
+ let size = std::mem::size_of::<crate::GpuEmitterTri>() as u64;
+ for run in self.sc.moving_emitters.chunk_by(|a, b| b.0 == a.0 + 1) {
+ let now: Vec<crate::GpuEmitterTri> = run
+ .iter()
+ .map(|&(i, code)| {
+ let e = &tris[i as usize];
+ let r = (e.tri as usize - first) * 3;
+ crate::GpuEmitterTri::new(e, &verts[r..r + 3], code)
+ })
+ .collect();
+ heap.write(q, Table::EmitterTris, run[0].0 as u64 * size, bytemuck::cast_slice(&now));
+ }
let Some(t) = tables.light_tree.as_mut().filter(|t| t.moving_count > 0) else { return };
t.refit_moving(&|k| {
let r = (tris[k].tri as usize - first) * 3;
crate::ltree::tri_vertices(&verts[r..r + 3])
});
- let (q, heap) = (&self.g.queue, &self.sc.up.heap);
heap.write(q, Table::LightTree, 0, bytemuck::cast_slice(&t.nodes[..1]));
heap.write(q, Table::LightTree, 2 * 16, bytemuck::cast_slice(&t.nodes[2..3]));
heap.write(q, Table::LightTree, t.moving_nodes as u64 * 16, bytemuck::cast_slice(&t.nodes[t.moving_nodes..]));
@@ -1546,8 +1576,9 @@ impl LiveCore {
};
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.
+ // 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 };
@@ -1906,8 +1937,10 @@ impl LiveCore {
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 };
- match free.pop() {
- Some(i) => tables.emitter_tris[i] = e,
+ 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),
}
}
@@ -2098,7 +2131,7 @@ impl LiveCore {
split.objects = ch.added.len() + ch.removed.len();
self.edit_split.add(&split);
if emitters_changed {
- self.write_emitters();
+ self.write_emitters(&new_emitters);
}
Ok(())
}
diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rs
index 087e7b6..7fde36d 100644
--- a/renderer/src/live/frame.rs
+++ b/renderer/src/live/frame.rs
@@ -244,7 +244,7 @@ impl LiveCore {
// dropped), so the CDF built here has the powers the objects hold and the reference the kernel reads.
self.land_powers_now();
let (e, b) = (&self.sc.tables, &mut self.sc.base);
- let (em, total, power) = crate::emitter_cdf(&e.emitter_tris, &e.materials, &e.objects, e.stride, b.light_lod, crate::EmitterCull::of(b));
+ let (em, total, power) = crate::emitter_cdf(e.emitter_tris.iter().enumerate(), &e.materials, &e.objects, e.stride, b.light_lod, crate::EmitterCull::of(b));
self.sc.up.heap.write(&self.g.queue, Table::Emitters, 0, bytemuck::cast_slice(&em));
b.misc[1] = total;
b.emit_power[0] = power;
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 20bf5ff..1bbb8a6 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -378,3 +378,118 @@ fn an_instanced_object_added_in_place_keeps_its_copies_data() {
assert_eq!(entries(&live), entries(&fresh), "each copy's data, in place against a build's");
assert_eq!(entries(&fresh), [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]]);
}
+
+/// What the kernel's light sampling reads against the triangles it stands for, on the GPU: every emitter of the list
+/// (a particle's is placed by its pass) 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.
+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 });
+ let mut e = c.g.device.create_command_encoder(&Default::default());
+ e.copy_buffer_to_buffer(b, at, &to, 0, bytes);
+ c.g.queue.submit([e.finish()]);
+ to.slice(..).map_async(wgpu::MapMode::Read, |_| {});
+ c.g.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
+ let bytes = to.slice(..).get_mapped_range().unwrap().to_vec();
+ bytes
+ };
+ let (tables, up) = (&c.sc.tables, &c.sc.up);
+ let size = std::mem::size_of::<crate::GpuEmitterTri>();
+ let list = read(&up.heap.buffer, up.heap.at(Table::EmitterTris), (tables.emitter_tris.len() * size) as u64);
+ let (verts, attrs) = (read(&up.verts, 0, up.verts.size()), read(&up.attrs, 0, up.attrs.size()));
+ let codes: std::collections::HashMap<u32, u32> = tables.light_tree.as_ref().map_or_else(Default::default, |t| t.order.iter().copied().zip(t.code.iter().copied()).collect());
+ let mut alive = 0;
+ for (i, e) in tables.emitter_tris.iter().enumerate().filter(|(_, e)| !e.nominal) {
+ let r: crate::GpuEmitterTri = bytemuck::pod_read_unaligned(&list[i * size..][..size]);
+ let code = codes.get(&(i as u32)).copied().unwrap_or(0) | if e.moves { crate::EMITTER_MOVES } else { 0 };
+ assert_eq!(r.code, code, "{what}: emitter {i}'s path code");
+ if e.area <= 0.0 {
+ continue;
+ }
+ 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);
+ 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), 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).
+#[test]
+fn the_light_list_holds_its_triangles() {
+ let presets = crate::default_presets_dir();
+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, 96, 54));
+ // 300 small emitting triangles: enough for a light tree.
+ let strip = |w: &mut World| {
+ let (mut positions, mut indices) = (vec![], vec![]);
+ for q in 0..150u32 {
+ let x = -1.5 + q as f32 * 0.02;
+ positions.extend([x, -0.9, 0.2, x + 0.008, -0.9, 0.2, x + 0.008, -0.892, 0.2, x, -0.892, 0.2]);
+ indices.extend([0, 1, 2, 0, 2, 3].map(|k| q * 4 + k));
+ }
+ w.set_geometry(6, Geometry { normals: [0.0, 0.0, 1.0].repeat(600), uvs: vec![0.0; 1200], positions, indices, groups: vec![], colors: vec![] }).unwrap();
+ w.set_object(17, "strip".into(), None, Kind::Mesh { geometry: 6, material: 5, own_blas: false, materials: vec![] }, true, false).unwrap();
+ };
+ // An emitter the CPU moves.
+ for tree in [true, false] {
+ let mut w = world();
+ w.set_object(13, "mover".into(), None, Kind::Mesh { geometry: 3, material: 5, own_blas: false, materials: vec![] }, true, true).unwrap();
+ w.set_transform(13, Vec3::new(0.35, -0.45, 0.6), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ if tree {
+ strip(&mut w);
+ }
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ assert_eq!(live.sc.tables.light_tree.as_ref().is_some_and(|t| t.moving_count > 0), tree, "the mover is in the tree's moving subtree");
+ assert!(!live.sc.moving_emitters.is_empty());
+ list_is_its_triangles("a moving emitter, as loaded", &live);
+ w.set_transform(13, Vec3::new(0.1, -0.3, 0.9), glam::Quat::from_rotation_z(0.5), Vec3::ONE).unwrap();
+ let rebuilt = live.commit(&mut w).unwrap();
+ assert!(!(rebuilt && live.g.hwrt), "the mover moved in place ({:?})", live.fallback);
+ list_is_its_triangles("a moving emitter, moved", &live);
+ }
+ // Emitters made in place, in a scene with the tree's slot for them (one that has a mesh of its own: its geometry
+ // can be edited).
+ let mut w = world();
+ strip(&mut w);
+ w.set_material(7, serde_json::from_value(serde_json::json!({ "name": "m", "color": [0.5, 0.5, 0.5], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true })).unwrap());
+ w.set_object(14, "own".into(), None, Kind::Mesh { geometry: 3, material: 7, own_blas: true, materials: vec![] }, true, false).unwrap();
+ w.set_transform(14, Vec3::new(-0.6, 0.5, 0.7), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ let mut live = open(&w).unwrap();
+ w.take_changes();
+ list_is_its_triangles("as loaded", &live);
+ if !live.g.hwrt {
+ return;
+ }
+ assert!(live.sc.tables.light_tree.as_ref().is_some_and(|t| t.dynamic.is_some()), "the tree has the slot");
+ type Edit = (&'static str, Box<dyn Fn(&mut World)>);
+ let quad = |s: f32| Geometry { positions: vec![-s, -s, 0.0, s, -s, 0.0, s, s, 0.0, -s, s, 0.0], normals: [0.0, 0.0, 1.0].repeat(4), uvs: vec![0.0; 8], indices: vec![0, 1, 2, 0, 2, 3], groups: vec![], colors: vec![] };
+ let edits: Vec<Edit> = vec![
+ (
+ "an emitting mesh added",
+ Box::new(move |w| {
+ w.set_geometry(8, quad(0.25)).unwrap();
+ w.set_object(16, "added".into(), None, Kind::Mesh { geometry: 8, material: 5, own_blas: true, materials: vec![] }, true, false).unwrap();
+ w.set_transform(16, Vec3::new(0.0, 0.65, 0.5), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ }),
+ ),
+ ("the added mesh's triangles changed", Box::new(move |w| w.set_geometry(8, quad(0.15)).unwrap())),
+ ("a material starts emitting", Box::new(|w| w.set_material(1, serde_json::from_value(serde_json::json!({ "name": "m", "color": [0.8, 0.4, 0.8], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1, 1, 1], "emissiveIntensity": 2, "doubleSided": true })).unwrap()))),
+ ("the added mesh removed", Box::new(|w| drop(w.remove(16)))),
+ ];
+ for (what, edit) in &edits {
+ let before = live.sc.tables.emitter_tris.len();
+ edit(&mut w);
+ assert!(!live.commit(&mut w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ list_is_its_triangles(what, &live);
+ // (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");
+ }
+}
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index 8d2464f..03f32d3 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -25,6 +25,10 @@ pub(super) struct LoadedScene {
/// Some object's move is an instance's transform (`Retained::moves_instances`: kept where the proxies change,
/// here and in a geometry edit): the frame's kernel then writes motion vectors.
pub(super) moving_instances: bool,
+ /// The emitters of the dynamic tail (`EmitterTri::moves`, particles apart: their pass places them), in the list's
+ /// order, each with its path code (the light tree's moving subtree keeps its shape): the list's copies of their
+ /// triangles follow them (edits.rs `move_emitters`).
+ pub(super) moving_emitters: Vec<(u32, u32)>,
/// The scene has instanced meshes or procedural geometry (the raster experiment draws only flattened triangles:
/// primary visibility is traced).
pub(super) instanced: bool,
@@ -173,7 +177,7 @@ impl EmitterWorker {
.name("emitters".into())
.spawn(move || {
while let Ok(j) = asked.recv() {
- let (em, total, power) = crate::emitter_cdf(&tris, &j.materials, &j.objects, stride, j.lod, j.cull);
+ let (em, total, power) = crate::emitter_cdf(tris.iter().enumerate(), &j.materials, &j.objects, stride, j.lod, j.cull);
let node_powers = tree.as_mut().map_or(vec![], |t| {
let w: Vec<f32> = t.order.iter().map(|&i| crate::emitter_power(&tris[i as usize], &j.materials, &j.objects, stride)).collect();
t.refit(&|k| w[k]);
@@ -219,7 +223,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
let (mat_runs, tri_order) = (std::mem::take(&mut prep.mat_runs), std::mem::take(&mut prep.tri_order));
let fixed_features = (!sc.textures.is_empty(), !sc.shaders.is_empty(), prep.groups);
// (The light tree is the tables' by now: its nodes from there.)
- let up = g.upload(&sc, &targets.accum, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, crate::ltree::nodes_of(tables.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, &mut timings)?;
+ let up = g.upload(&sc, &targets.accum, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, crate::ltree::nodes_of(tables.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, &mut timings)?;
let _ = g.pipeline(&up.kernel, true); // compile the scene's kernel variant now, not in the first frame
if !g.merged {
let _ = g.kernel_pass(&up.kernel, "finish");
@@ -285,5 +289,10 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
pool_first: prep.groups.iter().sum(),
blobs,
};
- Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, meshes, instances, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), instanced, instance_features, name: sc.name.clone(), up, base, tables, fixed_features, dynamic, edit, emit, mat_runs, tri_order }, view, env))
+ let codes: std::collections::HashMap<u32, u32> = tables.light_tree.as_ref().map_or_else(Default::default, |t| {
+ let moving = t.moving_first as usize..(t.moving_first + t.moving_count) as usize;
+ t.order[moving.clone()].iter().copied().zip(t.code[moving].iter().copied()).collect()
+ });
+ let moving_emitters = tables.emitter_tris.iter().enumerate().filter(|(_, e)| e.moves && !e.nominal).map(|(i, _)| (i as u32, codes.get(&(i as u32)).copied().unwrap_or(0))).collect();
+ Ok((LoadedScene { timings, triangles, tris, tri_nodes, tri_instances, pool_tris, meshes, instances, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), moving_emitters, instanced, instance_features, name: sc.name.clone(), up, base, tables, fixed_features, dynamic, edit, emit, mat_runs, tri_order }, view, env))
}
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index 99d4aaa..3d5b3cd 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -1263,7 +1263,7 @@ mod instanced_tests {
let mut sc = crate::scene::build(&w, Path::new("."), &presets, None).unwrap();
(sc.width, sc.height) = (64, 36);
let prep = crate::prepare(g, &mut sc, &mut vec![]);
- let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 16, &mut vec![]).unwrap();
+ let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 16, &mut vec![]).unwrap();
frame.color.iter().flatten().map(|v| v.to_bits()).collect::<Vec<u32>>()
};
let (a, b) = (offline(&views), offline(&whole));
@@ -1312,7 +1312,7 @@ mod instanced_tests {
let mut sc = crate::scene::build(&w, Path::new("."), &presets, None).unwrap();
(sc.width, sc.height) = (64, 36);
let prep = crate::prepare(g, &mut sc, &mut vec![]);
- let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 16, &mut vec![]).unwrap();
+ let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, crate::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, prep.params, 16, &mut vec![]).unwrap();
frame.color.iter().flatten().map(|v| v.to_bits()).collect::<Vec<u32>>()
};
let (a, b) = (offline(&plain), offline(&uniform));
diff --git a/renderer/src/main.rs b/renderer/src/main.rs
index 529733d..957331f 100644
--- a/renderer/src/main.rs
+++ b/renderer/src/main.rs
@@ -273,15 +273,16 @@ fn main() -> Result<()> {
let applied = e.apply(&w, &changes, 0.0)?;
let (b, pb) = build(&w)?;
// Same sampling distribution: entries switched off (zero weight) only exist on the edited side, so only the
- // entries are compared, not the guide table after them (indices into the entries).
- let bits = |v: &[[f32; 4]], n: usize| v[..n].iter().filter(|e| e[2] > 0.0).flat_map(|e| e.map(f32::to_bits)).collect::<Vec<_>>();
- let (ea, _, _) = threert_render::emitter_cdf(&e.emitter_tris, &e.materials, &e.objects, e.stride, [0.0; 4], threert_render::EmitterCull::default());
+ // entries are compared (each by its emitter's triangle: its index differs with them), not the guide table
+ // after them (indices into the entries).
+ let bits = |v: &[[f32; 4]], tris: &[threert_render::EmitterTri]| v[..tris.len()].iter().filter(|e| e[2] > 0.0).flat_map(|e| [tris[e[0].to_bits() as usize].tri, e[1].to_bits(), e[2].to_bits(), e[3].to_bits()]).collect::<Vec<_>>();
+ let (ea, _, _) = threert_render::emitter_cdf(e.emitter_tris.iter().enumerate(), &e.materials, &e.objects, e.stride, [0.0; 4], threert_render::EmitterCull::default());
let power = |o: &[[f32; 4]]| o.iter().step_by(e.stride).map(|p| p[3].to_bits()).collect::<Vec<_>>();
let checks = [
("materials", bytemuck::cast_slice::<_, u8>(&e.materials) == bytemuck::cast_slice::<_, u8>(&b.materials)),
("lights", bytemuck::cast_slice::<_, u8>(&e.lights) == bytemuck::cast_slice::<_, u8>(&b.lights)),
("object power", power(&e.objects) == power(&b.objects)),
- ("emitters", bits(&ea, e.emitter_tris.len()) == bits(&pb.emitters, pb.emitter_tris.len())),
+ ("emitters", bits(&ea, &e.emitter_tris) == bits(&pb.emitters, &pb.emitter_tris)),
];
println!("{}", serde_json::json!({ "structural": applied.is_none(), "checks": checks.iter().map(|(k, ok)| (k.to_string(), *ok)).collect::<std::collections::BTreeMap<_, _>>() }));
if applied.is_none() || checks.iter().any(|(_, ok)| !ok) {
@@ -482,7 +483,7 @@ fn render(g: &gpu::Gpu, job: &Job, presets: &Path, init_ms: f64, hosts: &mut Hos
if job.signals.is_some() {
params.motion[1] = 1.0;
}
- let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, threert_render::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, params, spp, &mut timings)?;
+ let frame = g.render(&sc, &prep.tri_verts, prep.groups, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, threert_render::ltree::nodes_of(prep.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, params, spp, &mut timings)?;
if let Some(prefix) = &job.signals {
// The raw (undenoised) means: diffuse = color less specular and emission.
let diffuse: Vec<f32> = frame.color.iter().zip(&frame.specular).zip(&frame.emission).flat_map(|((c, s), e)| [0, 1, 2].map(|k| (c[k] - s[k] - e[k]).max(0.0))).collect();
diff --git a/renderer/src/merged.rs b/renderer/src/merged.rs
index d626fe1..7f40680 100644
--- a/renderer/src/merged.rs
+++ b/renderer/src/merged.rs
@@ -194,7 +194,12 @@ mod tests {
assert!(kernel_template().contains(&format!("const {constant}: u32 = {}u;", bytes / 16)), "{constant}");
assert_eq!(layout(&m, name).1 as usize, bytes, "{name}");
}
- assert_eq!(<Table as crate::heap::Section>::COUNT, Table::GlassEnergy as usize + 1);
+ assert_eq!(<Table as crate::heap::Section>::COUNT, Table::EmitterTris as usize + 1);
+ // The emitters' triangles.
+ assert!(kernel_template().contains(&format!("const EMITTER_TRI_VEC4: u32 = {}u;", std::mem::size_of::<crate::GpuEmitterTri>() / 16)));
+ 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)));
// 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 e5030c0..dbeb846 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -357,7 +357,7 @@ pub struct GpuTriAttr {
pub n2: [f32; 4], // normal2, w = uv1.x
pub uv: [f32; 4], // uv1.y, uv2.x, uv2.y, material (bits)
pub t: [f32; 4], // tangent (dP/du), w = bitangent sign
- pub x: [f32; 4], // texture LOD constant 0.5*log2(uv area / world area), object index (bits), -, -
+ pub x: [f32; 4], // texture LOD constant 0.5*log2(uv area / world area), object index (bits), a particle's area, its emitter entry + 1 (bits; 0: not light-sampled)
}
#[repr(C)]