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.

The emitters' weights are made on the GPU (#290)

Yujiaf46bc9deac3f
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 4e0ffe9..248449d 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -476,7 +476,8 @@ Earlier direction (2026-11-05, kept for the history below): finish the three.js
the light tree in the frame, ~13–15 ms over Tokyo's 1.4 M emitters, ~90 times in the Shiba fly-past (the
street lamps and the window groups switching).
- Scenes with many emitters now rebuild both on a worker thread (`EmitterWorker`). The edits land with the
- result, a few frames later.
+ result, a few frames later. (Removed 2026-11-27: the GPU makes the weights in the edit's frame, "The
+ emitters' weights are made on the GPU".)
- The fly-past's frame interval p95 went from 29.7 / 28.5 to 17.20 / 17.17 ms, and its commits over 5 ms from
91 to 0.
- Acceptance (2026-11-11, branch `tokyo-1a-acceptance`; `node tools/tokyo/accept-1a.ts`, clips by
@@ -2920,6 +2921,22 @@ Mutations: 26. 25 failed a test there was; one, a texture put on a shelf too low
Found by review: a translucent particle's material given another function kept the kernel's old dispatch for the
translucency pass, which has its particles' functions alone; the kernel is made again where those are others.
+**The emitters' weights are made on the GPU (2026-11-27).** An emitter's weight (its area × its material's emissive
+luminance × its object's power), the cumulative table, its guide and the light tree's powers were made on the CPU,
+over every emitter, at each power or material edit: 59 to 74 ms in the frame of a material edit in Tokyo's
+time-of-day room (1.63 M emitters), and 53 to 58 ms on a worker thread for a lamp switch, which landed three or
+four frames later. Passes make them now (`emitter_weights.wgsl`) from the GPU's own records, materials and powers,
+in the frame after anything they depend on changed: the edit costs the commit nothing, and that frame 3.5 ms of
+GPU time there (0.1 ms or less at 10 000 to 20 000 emitters). The kernel reads the total and the tail's share from
+the table's header. The CPU still makes the table's order and the tree when emitters are added; a retired run's
+records say so, a particle's record has its nominal area. The worker thread and the deferred powers are gone.
+Scenes whose emitters move make their weights every frame. On the heavy clips the pictures and a frame's GPU time
+are as before (within 2 %). Left for later: only the changed runs (if a city's dusk needs it), and the emissive
+map in the weight (tried on the CPU at load: Zero-Day's ΔE 3.32 → 3.09 and flicker 2.06 → 1.80, the crowd's
+flicker 1.97 → 2.09: not taken as built).
+Tests: `the_gpu_weighs_the_emitters_as_the_cpu_does` and its variant without a tree hold the GPU's tables against
+the CPU's through power and material edits and removals.
+
**A camera ray's fog light is seen directly (2026-11-26).** The ambient light height fog scatters towards the
camera joins the emission signal, as the aerial haze does: it was part of the surface's diffuse light, which the
filters divide by the surface's albedo, so fog before a black surface was lost. The first step of taking fog out
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 7c59e38..7bfb947 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -936,7 +936,8 @@ reads files under the asset root as it goes and adds what they hold without rebu
be); showing an object that was hidden when the scene was built or rebuilt (move it out of sight instead of hiding
it); a model of nodes the file lacks (it draws nothing and has no instance to hide).
- **Emitters cost the commit**: each commit that adds or removes emitting triangles writes the emitter CDF and the
- light tree's dynamic part over every emitter of the scene. Add a cell's emitting meshes together, and draw far lights
+ light tree's dynamic part over every emitter of the scene. (A power or a material edit does not: the GPU makes
+ the weights again in that frame.) Add a cell's emitting meshes together, and draw far lights
with unlit materials (`MeshBasicMaterial`, or glTF `KHR_materials_unlit`, whose emission is then what it shows): they
are seen and light nothing.
- **Instances cost what changed.** An `InstancedMesh` adds its copies as TLAS instances, in place, all of them
@@ -1624,7 +1625,9 @@ The kernel's read-only scene data other than triangles is two storage buffers, e
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; what moves an emitter after the load is copied again on the GPU,
- `emitter_fill.wgsl`).
+ `emitter_fill.wgsl`). The emitters' weights, their cumulative table, its guide, the tree's powers and the
+ table's header (the total, the share outside the tree) are made on the GPU too, in the frame after anything
+ they depend on changed (`emitter_weights.wgsl`).
- `words` (binding 5), 32-bit words (`Stream`): the environment's CDF, the procedural geometry's data, the vertex
colours, the instances' rows, and the triangles' indices ("The scene's triangles" below) (`env_cdf_at`,
`pword`, `vcolor_word`, `tri_indices`). Integers are read as integers, not through a float's bits.
diff --git a/games/tokyo/tokyo-tod.game.ts b/games/tokyo/tokyo-tod.game.ts
index 917eabe..41a4327 100644
--- a/games/tokyo/tokyo-tod.game.ts
+++ b/games/tokyo/tokyo-tod.game.ts
@@ -159,9 +159,8 @@ export function sceneFor(id: string) {
const win = new GLTFModel(`assets/city/glb/${area.area}/${t.file}`, { nodes: [node] });
win.name = `windows ${t.x} ${t.z} ${g}`;
scene.add(win);
- // A group switches on every tile in the same frame: any power change costs the live view's commit ~13 ms (the
- // emitter CDF and the light tree rebuilt over all 1.4 M emitters, renderer/src/live/edits.rs write_emitters), so fewer
- // switching frames is better until that is incremental.
+ // A group switches on every tile in the same frame. (When this was written a power change rebuilt the emitters'
+ // table on the CPU; the GPU makes it again now, in the frame of the change.)
lamps.push({ name: win.name, at: windowSwitchAt(g) });
}
}
diff --git a/renderer/shaders/emitter_weights.wgsl b/renderer/shaders/emitter_weights.wgsl
new file mode 100644
index 0000000..dd24da0
--- /dev/null
+++ b/renderer/shaders/emitter_weights.wgsl
@@ -0,0 +1,190 @@
+// The light list's weights made again on the GPU from what the kernel shades with: each emitter's weight (its
+// triangle's area as its record has it now x its material's emissive luminance x its object's power, x the light LOD
+// without a tree), the cumulative table and its guide, the light tree's node powers, and the table's header (the
+// total, the share outside the tree). What lib.rs `emitter_cdf` and ltree.rs `refit` make on the CPU at load; run when
+// something they depend on changed (gpu.rs `weigh_emitters`).
+struct Params {
+ // Emitters (= entries), the tree's nodes (0: no tree), vec4s an object, bit 0: light LOD.
+ n: u32,
+ nodes: u32,
+ stride: u32,
+ flags: u32,
+ // Where each table starts in `tables` (vec4s): the emitters' records, their table, the tree's nodes, the
+ // instances; the materials, the objects; where the rows start in `words`.
+ list: u32,
+ entries: u32,
+ tree: u32,
+ instances: u32,
+ materials: u32,
+ objects: u32,
+ rows: u32,
+ pad: u32,
+ // Light LOD (lib.rs `emitter_lod`): its reference and d0; the cull's radius, far distance and cone cosine; the
+ // cone's direction.
+ lod: vec4<f32>,
+ cull: vec4<f32>,
+ dir: vec4<f32>,
+};
+@group(0) @binding(0) var<uniform> W: Params;
+// The scene's tables, one buffer (heap.rs `Table`). An emitter's record is four vec4s (lib.rs `GpuEmitterTri`): (v0,
+// its triangle), (e1, its instance), (e2, its code), (its section, flags, its nominal area, -). The emitters' table:
+// an entry an emitter in its order (its emitter: bits, cumulative weight, weight, area), the guide (four indices a
+// vec4), the header. A tree node: its sphere packed in two words, its power, its child word.
+@group(0) @binding(1) var<storage, read_write> tables: array<vec4<u32>>;
+// The scene's words: four a row of an instance, the first has its material.
+@group(0) @binding(2) var<storage, read> words: array<u32>;
+// The level at work, the number of levels, each level's (first, count) in the list that follows: the tree's nodes
+// by depth, the deepest first (ltree.rs `levels`).
+@group(0) @binding(3) var<storage, read_write> levels: array<u32>;
+// A block of the table: (its sum, the sum before it); after the last, the total.
+@group(0) @binding(4) var<storage, read_write> blocks: array<vec4<f32>>;
+
+fn entry(k: u32) -> vec4<f32> { return bitcast<vec4<f32>>(tables[W.entries + k]); }
+fn entry_put(k: u32, e: vec4<f32>) { tables[W.entries + k] = bitcast<vec4<u32>>(e); }
+fn node(i: u32) -> vec4<f32> { return bitcast<vec4<f32>>(tables[W.tree + i]); }
+
+const INSTANCE_VEC4: u32 = 10u;
+const MATERIAL_VEC4: u32 = 18u;
+const NO_INST: u32 = 0xffffffffu;
+const EMITTER_MOVES: u32 = 0x80000000u;
+const EMITTER_GONE: u32 = 2u;
+const EMITTER_NOMINAL: u32 = 4u;
+const ROW_MATERIAL: u32 = 0xffffffu;
+const LEAF: u32 = 0x80000000u;
+const GUIDE: u32 = 65536u;
+const BLOCK: u32 = 256u;
+const LEVELS: u32 = 32u;
+
+fn block_count() -> u32 { return (W.n + BLOCK - 1u) / BLOCK; }
+
+fn light_lod(c: vec3<f32>) -> f32 {
+ let d = distance(c, W.lod.xyz);
+ if (W.cull.x > 0.0 && d > W.cull.x && !(d <= W.cull.y && dot(c - W.lod.xyz, W.dir.xyz) >= W.cull.z * d)) { return 0.0; }
+ let k = W.lod.w / max(d, W.lod.w);
+ return k * k;
+}
+
+@compute @workgroup_size(64)
+fn weigh(@builtin(global_invocation_id) id: vec3<u32>) {
+ if (id.x >= W.n) { return; }
+ let e = tables[W.entries + id.x];
+ let r = W.list + e.x * 4u;
+ let r0 = tables[r];
+ let r1 = tables[r + 1u];
+ let r2 = tables[r + 2u];
+ let r3 = tables[r + 3u];
+ let e1 = bitcast<vec3<f32>>(r1.xyz);
+ let e2 = bitcast<vec3<f32>>(r2.xyz);
+ var area = 0.5 * length(cross(e1, e2));
+ if ((r3.y & EMITTER_NOMINAL) != 0u) { area = bitcast<f32>(r3.z); }
+ var w = 0.0;
+ if ((r3.y & EMITTER_GONE) != 0u || r1.w == NO_INST) {
+ area = 0.0;
+ } else {
+ // (The instance's record: its seventh vec4 has its object and its rows.)
+ let info = tables[W.instances + r1.w * INSTANCE_VEC4 + 6u];
+ let m = words[W.rows + (info.w + r3.x) * 4u] & ROW_MATERIAL;
+ let emissive = bitcast<vec4<f32>>(tables[W.materials + m * MATERIAL_VEC4 + 1u]).rgb;
+ w = area * dot(emissive, vec3<f32>(0.2126, 0.7152, 0.0722)) * bitcast<f32>(tables[W.objects + info.y * W.stride].w);
+ if ((W.flags & 1u) != 0u && (r2.w & EMITTER_MOVES) == 0u) { w *= light_lod(bitcast<vec3<f32>>(r0.xyz) + (e1 + e2) / 3.0); }
+ }
+ tables[W.entries + id.x] = vec4<u32>(e.x, 0u, bitcast<u32>(max(w, 0.0)), bitcast<u32>(area));
+}
+
+// The cumulative weights by blocks: inside each block, then the blocks' own, then both over the total.
+@compute @workgroup_size(64)
+fn scan_a(@builtin(global_invocation_id) id: vec3<u32>) {
+ if (id.x >= block_count()) { return; }
+ let lo = id.x * BLOCK;
+ let hi = min(lo + BLOCK, W.n);
+ var sum = 0.0;
+ for (var k = lo; k < hi; k++) {
+ var e = entry(k);
+ sum += e.z;
+ e.y = sum;
+ entry_put(k, e);
+ }
+ blocks[id.x] = vec4<f32>(sum, 0.0, 0.0, 0.0);
+}
+
+@compute @workgroup_size(1)
+fn scan_b(@builtin(global_invocation_id) id: vec3<u32>) {
+ if (id.x > 0u) { return; }
+ var sum = 0.0;
+ let nb = block_count();
+ for (var b = 0u; b < nb; b++) {
+ blocks[b].y = sum;
+ sum += blocks[b].x;
+ }
+ blocks[nb] = vec4<f32>(sum, 0.0, 0.0, 0.0);
+}
+
+@compute @workgroup_size(64)
+fn scan_c(@builtin(global_invocation_id) id: vec3<u32>) {
+ if (id.x >= W.n) { return; }
+ let total = blocks[block_count()].x;
+ // (Exactly 1 from the last entry that weighs something on, whatever the division rounds to.)
+ var e = entry(id.x);
+ let c = blocks[id.x / BLOCK].y + e.y;
+ e.y = select(0.0, select(c / total, 1.0, c >= total), total > 0.0);
+ entry_put(id.x, e);
+}
+
+// The guide: index k is the first entry whose cumulative weight is not below k / GUIDE. Four a vec4, a vec4 an
+// invocation.
+@compute @workgroup_size(64)
+fn guide(@builtin(global_invocation_id) id: vec3<u32>) {
+ if (id.x > GUIDE / 4u) { return; }
+ var out = vec4<u32>(0u);
+ for (var c = 0u; c < 4u; c++) {
+ let k = id.x * 4u + c;
+ if (k > GUIDE) { break; }
+ let u = f32(k) / f32(GUIDE);
+ var lo = 0u;
+ var hi = W.n;
+ for (var s = 0u; s < 32u && lo < hi; s++) {
+ let mid = (lo + hi) / 2u;
+ if (entry(mid).y < u) { lo = mid + 1u; } else { hi = mid; }
+ }
+ out[c] = lo;
+ }
+ tables[W.entries + W.n + id.x] = out;
+}
+
+// The tree's powers, a level a dispatch, the deepest first: a leaf's from its entries, a node's from its two
+// children. `next` moves to the level above.
+@compute @workgroup_size(64)
+fn tree(@builtin(global_invocation_id) id: vec3<u32>) {
+ let level = levels[0];
+ if (W.nodes == 0u || level >= min(levels[1], LEVELS)) { return; }
+ if (id.x >= levels[3u + 2u * level]) { return; }
+ let i = levels[2u + 2u * LEVELS + levels[2u + 2u * level] + id.x];
+ var nd = node(i);
+ let w = bitcast<u32>(nd.w);
+ var power = 0.0;
+ if ((w & LEAF) != 0u) {
+ let lo = w & 0x1fffffffu;
+ let hi = lo + ((w >> 29u) & 3u) + 1u;
+ for (var j = lo; j < hi; j++) { power += entry(j).z; }
+ } else {
+ power = node(w).z + node(w + 1u).z;
+ }
+ nd.z = power;
+ tables[W.tree + i] = bitcast<vec4<u32>>(nd);
+}
+
+@compute @workgroup_size(1)
+fn next(@builtin(global_invocation_id) id: vec3<u32>) {
+ if (id.x > 0u) { return; }
+ levels[0] += 1u;
+}
+
+// The header: the total, and the share of it that is not the tree's.
+@compute @workgroup_size(1)
+fn finish(@builtin(global_invocation_id) id: vec3<u32>) {
+ if (id.x > 0u) { return; }
+ let total = blocks[block_count()].x;
+ var tail = 0.0;
+ if (W.nodes > 0u && total > 0.0) { tail = max((total - node(0u).z) / total, 0.0); }
+ entry_put(W.n + GUIDE / 4u + 1u, vec4<f32>(total, tail, 0.0, 0.0));
+}
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index 3ac7f36..a736e3d 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -101,7 +101,7 @@ struct Params {
size: vec4<u32>, // width, height, sample index, seed
counts: vec4<u32>, // lights, emitters, max bounces, rr depth
env: vec4<f32>, // has env map, env width, env height, sun light index (-1 none)
- misc: vec4<f32>, // clamp (absolute radiance), emitter total weight, env total weight, _
+ misc: vec4<f32>, // clamp (absolute radiance), - (the emitters' total weight is their table's: `emitter_totals`), env total weight, _
sky_color: vec4<f32>, // constant sky radiance when no env map
counts2: vec4<u32>, // directional lights (first in `lights`), environment NEE on, output height for texture LOD (0 = traced height), first shadowed local light
time: vec4<f32>, // scene time (s), wetness, rain, -
@@ -115,7 +115,7 @@ struct Params {
light_lod: vec4<f32>, // live light LOD (lib.rs emitter_lod): reference position, d0 (0 = off)
emit_power: vec4<f32>, // the emitter CDF's power and cull as the CPU built it (lib.rs `EmitterCull`); not read here
lod_view: vec4<f32>, // emitter cull's view cone (lib.rs EmitterCull): forward direction, cos of the half-angle
- ltree: vec4<f32>, // light tree (ltree.rs): -, its entry count (bits: the moving emitters' first), P(pick a moving one), candidates at camera hits (0 = off)
+ ltree: vec4<f32>, // light tree (ltree.rs): -, its entry count (bits: the moving emitters' first), - (the tail's share is the table's: `emitter_totals`), candidates at camera hits (0 = off)
procs: vec4<u32>, // procedural geometry (F_PROC): -, object count, first record in `instances`, -
aerial: vec4<f32>, // the sky's aerial perspective (F_AERIAL): density multiple, Rayleigh scale, Mie scale, -
background: vec4<f32>, // three.js scene.background (radiance), 1 (F_BACKGROUND)
@@ -462,6 +462,16 @@ fn emitter_guide(k: u32) -> u32 {
return bitcast<u32>(emitter_at(P.counts.y + k / 4u)[k % 4u]);
}
+// The table's header, after the guide (lib.rs `emitter_header`): x the total weight, y the share of it outside the
+// light tree. Requires counts.y > 0.
+fn emitter_totals() -> vec4<f32> { return emitter_at(P.counts.y + EMITTER_GUIDE / 4u + 1u); }
+
+// Whether the light list has an emitter that weighs something now: counts.y is its size, the total the table's.
+fn emitters_on() -> bool {
+ if (P.counts.y == 0u) { return false; }
+ return emitter_totals().x > 0.0;
+}
+
// One emitter CDF entry: the first whose cumulative weight is not below u. The guide table bounds the binary search to
// u's bucket (u * EMITTER_GUIDE is exact for the 24-bit u), which holds the same entry a search over the whole CDF
// finds. Requires counts.y > 0.
@@ -529,22 +539,24 @@ fn emitter_pick_range(lo: u32, hi: u32, r: f32) -> vec4<f32> {
}
// An emitter entry for a point x (normal n), its selection probability `p` and its weight `w` (area x luminance x
-// power, as the CDF weighs). With the tree: the moving emitters by power with probability P.ltree.z, else the tree
+// power, as the CDF weighs). With the tree: the moving emitters by power with probability `emitter_totals().y`, else the tree
// descended by importance to a leaf, and one of its few entries by weight. Without it: the CDF entry (p = weight /
// total).
struct EPick { e: vec4<f32>, p: f32, w: f32 };
fn emitter_draw(x: vec3<f32>, n: vec3<f32>, rd: u32) -> EPick {
let r3 = rng3(rd);
+ let tot = emitter_totals();
+ if (!(tot.x > 0.0)) { return EPick(vec4<f32>(0.0), 0.0, 0.0); }
if (!lt_on()) {
let e = emitter_pick_u(r3.x);
- return EPick(e, e.z / P.misc.y, e.z);
+ return EPick(e, e.z / tot.x, e.z);
}
- if (r3.x < P.ltree.z) {
+ if (r3.x < tot.y) {
let e = emitter_pick_range(bitcast<u32>(P.ltree.y), P.counts.y, r3.y);
- return EPick(e, e.z / P.misc.y, e.z);
+ return EPick(e, e.z / tot.x, e.z);
}
- var p = 1.0 - P.ltree.z;
+ var p = 1.0 - tot.y;
var u = r3.y;
var w = bitcast<u32>(lt_node(0u).w);
for (var k = 0u; k <= LT_PATH_BITS && (w & LT_LEAF) == 0u; k++) {
@@ -576,11 +588,12 @@ fn emitter_draw(x: vec3<f32>, n: vec3<f32>, rd: u32) -> EPick {
// (its code names its path) by the same choices down the path and its weight in its leaf; any other (its code is its
// entry in the CDF) by its entry's weight.
fn emitter_pmf(ei: u32, em: EmitterTri, x: vec3<f32>, n: vec3<f32>) -> f32 {
- if (P.misc.y <= 0.0) { return 0.0; }
+ let tot = emitter_totals();
+ if (!(tot.x > 0.0)) { return 0.0; }
let code = em.code & ~EMITTER_MOVES;
- if ((code >> LT_PATH_BITS) == 0u) { return emitter_at(code).z / P.misc.y; }
+ if ((code >> LT_PATH_BITS) == 0u) { return emitter_at(code).z / tot.x; }
let depth = (code >> LT_PATH_BITS) - 1u;
- var p = 1.0 - P.ltree.z;
+ var p = 1.0 - tot.y;
var w = bitcast<u32>(lt_node(0u).w);
for (var k = 0u; k < depth; k++) {
let l = lt_node(w);
@@ -1994,7 +2007,7 @@ fn emitter_attrs(em: EmitterTri) -> TriAttr {
// ray left) over the triangle's area. One it never picks (no entry, no weight: switched off, culled, a procedural
// surface) is the BSDF ray's alone.
fn emit_mis(hit: Hit, d: vec3<f32>, pdf: f32) -> f32 {
- if (is_proc(hit) || !has(F_INST) || P.counts.y == 0u) { return 1.0; }
+ if (is_proc(hit) || !has(F_INST) || !emitters_on()) { return 1.0; }
// The hit triangle's emitter: its index in its section, counted from the section's first entry (its instance's
// row's; none: it is not light-sampled).
let rows = instance_at(hit.inst).info.w;
@@ -2464,7 +2477,7 @@ fn direct_light(s: Surface, lb: Lobes, v: vec3<f32>) -> vec3<f32> {
// gpu.rs `KernelSwitches::light_pick`: past the camera hit, the directional lights and one of the other kinds a
// scene has (local lights, emitters, the sky), weighted by their number.
@if(light_pick) let has_local = P.counts.x > P.counts2.x;
- @if(light_pick) let has_emit = P.counts.y > 0u;
+ @if(light_pick) let has_emit = emitters_on();
@if(light_pick) let has_env = P.counts2.y != 0u && (P.env.x > 0.5 || luminance(P.sky_color.rgb) > 0.0);
@if(light_pick) var take_local = true;
@if(light_pick) var take_emit = true;
@@ -2491,7 +2504,7 @@ fn direct_light(s: Surface, lb: Lobes, v: vec3<f32>) -> vec3<f32> {
if (two_sided(lb)) { ne = vec3<f32>(0.0); }
mis_x = o;
mis_n = ne;
- var emitters = P.counts.y;
+ var emitters = select(0u, P.counts.y, emitters_on());
@if(light_pick) if (!take_emit) { emitters = 0u; }
if (emitters > 0u) {
var es: ES;
@@ -2652,7 +2665,7 @@ fn fog_scatter(o: vec3<f32>, d: vec3<f32>, t0: f32, t1: f32, tr: f32, rd: u32) -
}
// One shadow ray: either the local lights (RIS) or one emissive point, chosen with equal odds when both exist.
let has_l = P.counts.x > P.counts2.x;
- let has_e = P.counts.y > 0u;
+ let has_e = emitters_on();
let both = has_l && has_e;
let use_e = has_e && (!has_l || r2.y < 0.5);
let wk = select(1.0, 2.0, both);
@@ -2995,7 +3008,7 @@ fn phase_direct(x: vec3<f32>, d: vec3<f32>, g: f32, rd: u32) -> vec3<f32> {
if (any(vis > vec3<f32>(0.0))) { sum += pick_ls.c * tr3(vis) * hg_phase(g, dot(pick_ls.l, d)) * (wsum * f32(nl) / (3.0 * pick_w)); }
}
}
- if (P.counts.y > 0u) {
+ if (emitters_on()) {
mis_x = x;
mis_n = vec3<f32>(0.0);
let es = sample_emitter(x, vec3<f32>(0.0), rng_sub(rd, 0x400u));
@@ -3097,7 +3110,7 @@ fn point_direct(x: vec3<f32>, rd: u32) -> vec3<f32> {
if (any(vis > vec3<f32>(0.0))) { sum += pick_ls.c * ph * (wsum * f32(nl) / (3.0 * pick_w)) * tr3(vis); }
}
}
- if (P.counts.y > 0u) {
+ if (emitters_on()) {
var wsum = 0.0;
var pick: ES;
var pick_t = 0.0;
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index c149bdc..93e8898 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -87,6 +87,8 @@ pub struct Gpu {
grid_layout: wgpu::BindGroupLayout,
/// The pass that fills runs of the light list from their triangles (emitter_fill.wgsl), made when first needed.
fill: std::sync::OnceLock<wgpu::ComputePipeline>,
+ /// The passes that make the emitters' weights again (emitter_weights.wgsl), made when first needed.
+ weigh: std::sync::OnceLock<(wgpu::BindGroupLayout, [wgpu::ComputePipeline; 8])>,
/// Hardware ray queries (Metal / Vulkan RT). Software BVH traversal otherwise.
pub hwrt: bool,
/// Last uploaded texture pages, reused while the scene's texture set is unchanged (live edits re-upload often).
@@ -145,7 +147,7 @@ pub struct Params {
pub motion: [f32; 4], // live motion vectors: 1 = on; `render --signals`; software traversal's units: the top tree's root, their count (bits)
/// Light LOD (live; `emitter_lod`): reference position, d0 (0 = off).
pub light_lod: [f32; 4],
- /// x: the emitter CDF's total without light LOD (camera-hit MIS weighs by power alone; = misc[1] when it is off);
+ /// x: the emitters' power as the CPU last built their table (not read by the kernel);
/// y: live emitter cull radius (lib.rs emitter_lod; 0 = off); z: the cull's reach inside the view cone (0 = none).
pub emit_power: [f32; 4],
/// Live emitter cull's view cone (lib.rs `EmitterCull`): the forward direction it was built for (xyz), the cosine
@@ -476,6 +478,17 @@ pub struct EmitterFill {
longest: u32,
}
+/// What the emitter weight passes keep between runs (emitter_weights.wgsl): their parameters, the tree's levels (sent
+/// again when the tree is another: `tree`, its nodes and `LightTree::structure`) with each level's node count, and
+/// the blocks' sums.
+pub struct EmitterWeights {
+ params: wgpu::Buffer,
+ levels: wgpu::Buffer,
+ blocks: wgpu::Buffer,
+ counts: Vec<u32>,
+ tree: (usize, u32),
+}
+
/// A scene's fill a frame: of the particles' emitters, after their passes. None where the scene has no such
/// emitters.
#[derive(Default)]
@@ -2230,7 +2243,7 @@ impl Gpu {
dlss_sdk,
#[cfg(dlss)]
dlss_rr,
- instance, adapter, timestamps, device, queue, adapter_info, whole_tables, switches, approx, approx_default: approx, pipeline_cache, source: std::sync::Arc::new(src), module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), warming: Default::default(), layout, live_layout, no_live, no_live_bufs, no_grid_view, grid_layout, fill: Default::default(), hwrt, pages: Default::default(), streams: Default::default(), tl_layout, tl_pipeline_layout, tl_live_layout, no_live_tl, tl_pipelines: Default::default(), kernel_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default(),
+ instance, adapter, timestamps, device, queue, adapter_info, whole_tables, switches, approx, approx_default: approx, pipeline_cache, source: std::sync::Arc::new(src), module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), warming: Default::default(), layout, live_layout, no_live, no_live_bufs, no_grid_view, grid_layout, fill: Default::default(), weigh: Default::default(), hwrt, pages: Default::default(), streams: Default::default(), tl_layout, tl_pipeline_layout, tl_live_layout, no_live_tl, tl_pipelines: Default::default(), kernel_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default(),
})
}
@@ -3185,6 +3198,92 @@ impl Gpu {
pass.dispatch_workgroups(f.longest.div_ceil(64), f.count, 1);
}
+ fn weigh_pipelines(&self) -> &(wgpu::BindGroupLayout, [wgpu::ComputePipeline; 8]) {
+ self.weigh.get_or_init(|| {
+ let d = &self.device;
+ let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("emitter weights"), source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/emitter_weights.wgsl").into()) });
+ let buffer = |binding: u32, ty: wgpu::BufferBindingType| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None }, count: None };
+ let entries: Vec<_> = (0..5).map(|b| buffer(b, match b { 0 => wgpu::BufferBindingType::Uniform, 2 => wgpu::BufferBindingType::Storage { read_only: true }, _ => wgpu::BufferBindingType::Storage { read_only: false } })).collect();
+ let layout = d.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("emitter weights"), entries: &entries });
+ let pl = d.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("emitter weights"), bind_group_layouts: &[Some(&layout)], immediate_size: 0 });
+ let pipes = ["weigh", "scan_a", "scan_b", "scan_c", "guide", "tree", "next", "finish"].map(|name| d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some(name), layout: Some(&pl), module: &module, entry_point: Some(name), compilation_options: Default::default(), cache: self.cache() }));
+ (layout, pipes)
+ })
+ }
+
+ /// The emitters' weights again (emitter_weights.wgsl): each entry's weight from its record, material and object as
+ /// the encoder's earlier commands and the writes queued before its submission leave them, the cumulative table,
+ /// its guide, the tree's powers and the table's header. `n` emitters; `lod`, `cull`: the light LOD (`lod[3]` 0:
+ /// none); `ts`: where the pass writes its two timestamps.
+ #[allow(clippy::too_many_arguments)]
+ pub fn weigh_emitters(&self, up: &Uploaded, st: &mut Option<EmitterWeights>, n: u32, tree: Option<&crate::ltree::LightTree>, stride: u32, lod: [f32; 4], cull: crate::EmitterCull, e: &mut wgpu::CommandEncoder, ts: Option<(&wgpu::QuerySet, u32)>) {
+ if n == 0 {
+ return;
+ }
+ let (d, q) = (&self.device, &self.queue);
+ let nodes = tree.map_or(0, |t| t.nodes.len());
+ let (levels_bytes, blocks_bytes) = ((2 + 64 + nodes.max(1)) as u64 * 4, (n.div_ceil(256) as u64 + 1) * 16);
+ if st.as_ref().is_none_or(|s| s.levels.size() < levels_bytes || s.blocks.size() < blocks_bytes) {
+ let make = |label, size: u64, usage| d.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage, mapped_at_creation: false });
+ *st = Some(EmitterWeights {
+ params: make("emitter weights", 96, wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST),
+ levels: make("emitter weights: levels", (levels_bytes + levels_bytes / 2).next_multiple_of(16), wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST),
+ blocks: make("emitter weights: blocks", (blocks_bytes + blocks_bytes / 2).next_multiple_of(16), wgpu::BufferUsages::STORAGE),
+ counts: vec![],
+ tree: (usize::MAX, 0),
+ });
+ }
+ let s = st.as_mut().unwrap();
+ // The tree's levels, when it is another tree; the level at work back to the first.
+ let key = (nodes, tree.map_or(0, |t| t.structure));
+ if s.tree != key {
+ let (list, counts) = tree.map_or((vec![], vec![]), |t| t.levels());
+ let mut words = vec![0u32; 2 + 64];
+ words[1] = counts.len() as u32;
+ let mut at = 0;
+ for (l, &c) in counts.iter().enumerate() {
+ (words[2 + 2 * l], words[3 + 2 * l]) = (at, c);
+ at += c;
+ }
+ words.extend(&list);
+ q.write_buffer(&s.levels, 0, bytemuck::cast_slice(&words));
+ (s.tree, s.counts) = (key, counts);
+ } else {
+ q.write_buffer(&s.levels, 0, bytemuck::bytes_of(&0u32));
+ }
+ let f = |v: f32| v.to_bits();
+ let (heap, words) = (&up.heap, &up.words);
+ let at = |t: Table| (heap.at(t) / 16) as u32;
+ let params: [u32; 24] = [
+ n, nodes as u32, stride, (lod[3] > 0.0) as u32,
+ at(Table::EmitterTris), at(Table::Emitters), at(Table::LightTree), at(Table::Instances),
+ at(Table::Materials), at(Table::Objects), (words.at(Stream::Rows) / 4) as u32, 0,
+ f(lod[0]), f(lod[1]), f(lod[2]), f(lod[3]),
+ f(cull.radius), f(cull.far), f(cull.cos), 0,
+ f(cull.dir[0]), f(cull.dir[1]), f(cull.dir[2]), 0,
+ ];
+ q.write_buffer(&s.params, 0, bytemuck::cast_slice(&params));
+ let (layout, pipes) = self.weigh_pipelines();
+ let entries = [buffer_entry(0, &s.params), buffer_entry(1, &heap.buffer), buffer_entry(2, &words.buffer), buffer_entry(3, &s.levels), buffer_entry(4, &s.blocks)];
+ let bg = d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("emitter weights"), layout, entries: &entries });
+ let tw = ts.map(|(q, i)| wgpu::ComputePassTimestampWrites { query_set: q, beginning_of_pass_write_index: Some(i), end_of_pass_write_index: Some(i + 1) });
+ let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("emitter weights"), timestamp_writes: tw });
+ pass.set_bind_group(0, &bg, &[]);
+ let [weigh, scan_a, scan_b, scan_c, guide, tree_pass, next, finish] = pipes;
+ for (pipe, groups) in [(weigh, n.div_ceil(64)), (scan_a, n.div_ceil(256).div_ceil(64)), (scan_b, 1), (scan_c, n.div_ceil(64)), (guide, (crate::EMITTER_GUIDE as u32 / 4 + 1).div_ceil(64))] {
+ pass.set_pipeline(pipe);
+ pass.dispatch_workgroups(groups, 1, 1);
+ }
+ for &count in &s.counts {
+ pass.set_pipeline(tree_pass);
+ pass.dispatch_workgroups(count.div_ceil(64).max(1), 1, 1);
+ pass.set_pipeline(next);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+ pass.set_pipeline(finish);
+ pass.dispatch_workgroups(1, 1, 1);
+ }
+
/// One frame of the stateful GPU particles (gpu_particles.wgsl): each system's emissions (its rate over `dt`, and the
/// game's spawns, `spawns` per node, 8 floats each), the update, collision and retirement of the rest, their quads;
/// with `rebuild`, the systems' BLASes after (else the stateless pass that follows rebuilds them).
diff --git a/renderer/src/lib.rs b/renderer/src/lib.rs
index c4c4509..094dd2c 100644
--- a/renderer/src/lib.rs
+++ b/renderer/src/lib.rs
@@ -124,6 +124,15 @@ pub const NO_INST: u32 = u32::MAX;
pub const EMITTER_MOVES: u32 = 1 << 31;
/// `GpuEmitterTri::flags`: a rect light's card (`EmitterTri::card`).
pub const EMITTER_CARD: u32 = 1;
+/// `GpuEmitterTri::flags`: its run was retired (`tables::Tables::retire`): it weighs nothing.
+pub const EMITTER_GONE: u32 = 2;
+/// `GpuEmitterTri::flags`: it is weighed by the nominal area in `GpuEmitterTri::nominal` (`EmitterTri::nominal`).
+pub const EMITTER_NOMINAL: u32 = 4;
+
+/// An emitter's `GpuEmitterTri::flags` while it is in use.
+pub fn emitter_flags(e: &EmitterTri) -> u32 {
+ (if e.card { EMITTER_CARD } else { 0 }) | (if e.nominal { EMITTER_NOMINAL } else { 0 })
+}
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`,
@@ -142,7 +151,9 @@ pub struct GpuEmitterTri {
pub code: u32,
pub part: u32,
pub flags: u32,
- pub spare: [u32; 2],
+ /// With `EMITTER_NOMINAL`: the area it is weighed by (f32 bits).
+ pub nominal: u32,
+ pub spare: u32,
}
impl GpuEmitterTri {
@@ -151,7 +162,7 @@ impl GpuEmitterTri {
let v = |r: usize| [rows[r][0], rows[r][1], rows[r][2]];
// (As a hit has it: with an instance its section, without one its row, which is its triangle's.)
let part = if e.inst == NO_INST { e.tri } else { e.part };
- 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 }, part, flags: if e.card { EMITTER_CARD } else { 0 }, spare: [0; 2] }
+ 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 }, part, flags: emitter_flags(e), nominal: if e.nominal { e.area.to_bits() } else { 0 }, spare: 0 }
}
/// As `new`, from its vertices.
@@ -430,9 +441,10 @@ pub fn emitter_codes(tris: &[EmitterTri], order: &[u32], tree: Option<&ltree::Li
}
/// Emitter CDF entries (its emitter's index in `tris`: bits, normalized cumulative weight, weight, area), one per
-/// emitter in `order` (`emitter_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.
+/// emitter in `order` (`emitter_order`); then the guide table; then the header the kernel reads the totals from
+/// (`emitter_header`: the total weight here, the tail's share for whoever has the tree); 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.
@@ -464,9 +476,17 @@ pub fn emitter_cdf(tris: &[EmitterTri], order: &[u32], materials: &[scene::GpuMa
})
.collect();
out.extend(guide.chunks(4).map(|c| std::array::from_fn(|j| f32::from_bits(c.get(j).copied().unwrap_or(0)))));
+ out.push([total, 0.0, 0.0, 0.0]);
(out, total, power)
}
+/// Where the emitter table of `n` emitters has its header (pathtrace.wgsl `emitter_totals`): after the entries and
+/// the guide. (The total weight, the share of it outside the light tree: `emitter_draw` takes the tail with that
+/// probability.)
+pub fn emitter_header(n: usize) -> usize {
+ n + (EMITTER_GUIDE + 1).div_ceil(4)
+}
+
/// Height fog and volumetric fog kernel parameters (`Params::fog`, `fog_color`, `vol`, `vol2`).
pub fn fog_params(fog: Option<&desc::Fog>) -> [[f32; 4]; 4] {
[
@@ -650,9 +670,10 @@ pub fn prepare_as(hwrt: bool, sc: &mut scene::Scene, timings: &mut Vec<(String,
g.code = code;
}
let emitter_runs = EmitterRuns::of(&emitter_tris);
- let (emitters, total, _) = emitter_cdf(&emitter_tris, &order, &sc.materials, &sc.objects, sc.object_stride(), [0.0; 4], EmitterCull::default());
+ let (mut emitters, total, _) = emitter_cdf(&emitter_tris, &order, &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]);
+ emitters[emitter_header(emitter_tris.len())][1] = ltree_param[2];
// Sky / environment.
let t = Instant::now();
@@ -697,7 +718,7 @@ pub fn prepare_as(hwrt: bool, sc: &mut scene::Scene, timings: &mut Vec<(String,
size: [sc.width, sc.height, 0, rng_seed()],
// (The preset's and the exposure's: `Params::set_preset`; the sky's: `SkyBaked::write`; the environment's:
// `EnvSettings::write`. Below.)
- counts: [sc.lights.len() as u32, if total > 0.0 { emitter_tris.len() as u32 } else { 0 }, 0, 0],
+ counts: [sc.lights.len() as u32, emitter_tris.len() as u32, 0, 0],
env: [0.0, 0.0, 0.0, -1.0],
misc: [0.0, total, 0.0, 0.0],
sky_color: [0.0; 4],
@@ -1450,7 +1471,8 @@ mod light_lod_tests {
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;
assert!(total > 0.0);
- assert_eq!(t.len(), tris.len() + (EMITTER_GUIDE + 1).div_ceil(4));
+ assert_eq!(t.len(), emitter_header(tris.len()) + 1);
+ assert_eq!(t[emitter_header(tris.len())], [total, 0.0, 0.0, 0.0]);
// pathtrace.wgsl: the search over [lo, hi), the guide table, emitter_pick.
let search = |mut lo: u32, mut hi: u32, u: f32| {
while lo < hi {
diff --git a/renderer/src/live/edits.rs b/renderer/src/live/edits.rs
index 7b98cb9..b1b9de1 100644
--- a/renderer/src/live/edits.rs
+++ b/renderer/src/live/edits.rs
@@ -1119,9 +1119,14 @@ impl LiveCore {
if d.materials || d.emitters || std::mem::take(&mut self.emitters_reweigh) {
let mut new = self.add_material_emitters();
new.append(&mut self.pending_emitters);
- self.write_emitters(&new);
- } else if d.deferred {
- self.send_powers();
+ // New records, or a tree that has had emitters added in place (its slot is grown again over those that
+ // weigh something): the table's order and the tree, on the CPU. Any other edit changes weights alone,
+ // which the GPU makes again (`weights_dirty`).
+ self.slot_used |= !new.is_empty();
+ if self.slot_used {
+ self.write_emitters(&new);
+ }
+ self.weights_dirty = true;
}
if d.materials || changes.environment {
// (Fog or a background appearing, a clear coat: the kernel's variant with it, compiled once, then cached.)
@@ -1362,7 +1367,7 @@ impl LiveCore {
let inst = &mut instances[r as usize];
for j in old {
let e = crate::EmitterTri { moves: true, in_tree: false, ..tables.emitter_tris[j] };
- tables.emitter_tris[j].area = 0.0;
+ tables.retire(j..j + 1);
let w = pool_tris[e.tri as usize].map(|v| glam::Vec3A::from(to.transform_point3(v.into())));
self.pending_emitters.push((tables.emitter_tris.len() as u32, crate::GpuEmitterTri::of(&e, w, 0)));
tables.emitter_tris.push(e);
@@ -1927,9 +1932,7 @@ impl LiveCore {
let starts = scene::section_emitters(sects, &mine, &tables.materials);
let n = scene::rows_emitters(sects, &mine, &tables.materials);
let old = emitter_run(&tables.emitter_tris, instances, r as u32);
- for e in &mut tables.emitter_tris[old] {
- e.area = 0.0;
- }
+ tables.retire(old);
let first = tables.emitter_tris.len() as u32;
instances[r].first_emitter = first;
for (s, start) in starts.iter().enumerate() {
@@ -1963,7 +1966,9 @@ impl LiveCore {
/// 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();
+ // (The table and the tree as the CPU makes them, from its own areas: the GPU makes the weights again after.)
+ self.weights_dirty = true;
+ self.slot_used |= !new.is_empty();
let LoadedScene { tables: e, base: b, pool_tris, instances, codes_sent: sent, .. } = &mut self.sc;
let size = std::mem::size_of::<crate::GpuEmitterTri>();
let mut w_tris = Gather::default();
@@ -2017,11 +2022,27 @@ impl LiveCore {
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);
- self.sc.tables.defer_powers = self.sc.emit.is_some();
+ }
+
+ /// The runs retired since the last frame (`Tables::retire`): their records' `EMITTER_GONE`, but for a record
+ /// given to another emitter since (it has an area again). True if any was written.
+ pub(super) fn flush_retired(&mut self) -> bool {
+ let t = &mut self.sc.tables;
+ if t.retired.is_empty() {
+ return false;
+ }
+ let (size, at) = (std::mem::size_of::<crate::GpuEmitterTri>(), std::mem::offset_of!(crate::GpuEmitterTri, flags));
+ let mut w = Gather::default();
+ for run in std::mem::take(&mut t.retired) {
+ for i in run {
+ let e = &t.emitter_tris[i];
+ if e.area == 0.0 {
+ w.put((i * size + at) as u64, bytemuck::bytes_of(&(crate::emitter_flags(e) | crate::EMITTER_GONE)));
+ }
+ }
}
+ w.flush_section(&self.g.queue, &self.sc.up.heap, Table::EmitterTris);
+ true
}
/// The emitter CDF `em` (its total weight and the emitters' power) and the light tree's nodes into their tables,
@@ -2050,99 +2071,21 @@ impl LiveCore {
/// The kernel's emitter parameters for a CDF of this total weight (and the emitters' power) and the tree.
pub(super) fn emitter_params(&mut self, total: f32, power: f32) {
- let LoadedScene { tables: e, base: b, .. } = &mut self.sc;
+ let LoadedScene { tables: e, base: b, up, .. } = &mut self.sc;
b.emit_power[0] = power;
- b.misc[1] = total;
+ let mut tail = 0.0;
if let Some(t) = e.light_tree.as_ref() {
// The tree's entries (with the slot: the static ones and those added in place), the rest by power share.
if t.dynamic.is_some() {
b.ltree[1] = f32::from_bits(t.order.len() as u32);
}
- b.ltree[2] = if power > 0.0 { ((power - t.power) / power).max(0.0) } else { 0.0 };
- }
- b.counts[1] = if total > 0.0 { e.emitter_tris.len() as u32 } else { 0 };
- }
-
- /// Power edits held back (`Tables::deferred`) to the emitter worker, unless it is on a job (they go with the next,
- /// when that one lands). Lockstep frames wait for the result.
- pub(super) fn send_powers(&mut self) {
- let Some(w) = self.sc.emit.as_mut() else { return };
- if w.flight.is_some() || self.sc.tables.deferred.is_empty() {
- return;
- }
- let e = &mut self.sc.tables;
- let powers = std::mem::take(&mut e.deferred);
- let mut objects = e.objects.clone();
- for &(row, power, _) in &powers {
- objects[row][3] = power;
- }
- let b = &self.sc.base;
- let job = EmitterJob { materials: e.materials.clone(), objects, lod: b.light_lod, cull: crate::EmitterCull::of(b) };
- if w.ask.send(job).is_err() {
- // (The worker is gone: write them now.)
- e.put_powers(&powers);
- 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(&[]);
- return;
- }
- w.flight = Some(powers);
- if self.fixed_dt.is_some() {
- if let Ok(r) = self.sc.emit.as_ref().unwrap().done.recv() {
- self.land_emitters(r);
- }
- }
- }
-
- /// The emitter worker's result, if it has one: its edits land with it, and the edits held back since go out.
- pub(super) fn take_emitters(&mut self) {
- let Some(r) = self.sc.emit.as_ref().and_then(|w| w.done.try_recv().ok()) else { return };
- self.land_emitters(r);
- self.send_powers();
- }
-
- /// A job's edits and its emitter CDF and tree powers, together: the objects' powers, the CDF, the tree.
- pub(super) fn land_emitters(&mut self, r: EmitterBuilt) {
- let Some(powers) = self.sc.emit.as_mut().and_then(|w| w.flight.take()) else { return };
- let e = &mut self.sc.tables;
- e.put_powers(&powers);
- self.sc.up.heap.write(&self.g.queue, Table::Objects, 0, bytemuck::cast_slice(&e.objects));
- if let Some(t) = e.light_tree.as_mut() {
- for (n, &p) in t.nodes.iter_mut().zip(&r.node_powers) {
- n[2] = p;
- }
- t.power = t.nodes.first().map_or(0.0, |n| n[2]);
- }
- // (Same entries and nodes as the CDF the scene was loaded with: their tables hold them.)
- let mut enc = self.g.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("emitters") });
- let (heap, cdf) = (&self.sc.up.heap, r.entries as u64 * 16);
- for (t, from, bytes) in [(Table::Emitters, 0, cdf), (Table::LightTree, cdf, r.bytes - cdf)] {
- if bytes > 0 {
- enc.copy_buffer_to_buffer(&r.staging, from, &heap.buffer, heap.at(t), bytes.min(heap.cap(t)));
- }
+ tail = if power > 0.0 { ((power - t.power) / power).max(0.0) } else { 0.0 };
}
- self.g.queue.submit([enc.finish()]);
- self.emitter_params(r.total, r.power);
- self.lit_changed = self.frame.max(1);
- }
-
- /// Before another emitter edit (`write_emitters`, a light-LOD rebuild): the job in flight waited for and its result
- /// dropped, its edits and those held back written into the objects (and uploaded), so the rebuild sees them all.
- pub(super) fn land_powers_now(&mut self) {
- let Some(w) = self.sc.emit.as_mut() else { return };
- let mut powers = vec![];
- if let Some(f) = w.flight.take() {
- let _ = w.done.recv();
- powers = f;
- }
- let e = &mut self.sc.tables;
- powers.append(&mut e.deferred);
- if !powers.is_empty() {
- e.put_powers(&powers);
- self.sc.up.heap.write(&self.g.queue, Table::Objects, 0, bytemuck::cast_slice(&e.objects));
- // The lighting changed (as when a result lands): `live_lighting` for the next 45 frames.
- self.lit_changed = self.frame.max(1);
+ b.counts[1] = e.emitter_tris.len() as u32;
+ // The table's header (after whatever wrote the table itself): the total and the tail's share.
+ let at = crate::emitter_header(e.emitter_tris.len()) as u64 * 16;
+ if at + 16 <= up.heap.cap(Table::Emitters) {
+ up.heap.write(&self.g.queue, Table::Emitters, at, bytemuck::cast_slice(&[total, tail, 0.0, 0.0]));
}
}
@@ -2206,7 +2149,7 @@ impl LiveCore {
for r in first..first + capacity as usize {
let run = emitter_run(&sc.tables.emitter_tris, &sc.instances, r as u32);
reweigh |= !run.is_empty();
- sc.tables.emitter_tris[run].iter_mut().for_each(|e| e.area = 0.0);
+ sc.tables.retire(run);
let inst = &mut sc.instances[r];
let mesh = sc.meshes[inst.mesh as usize];
let mut row = scene::row_of(mat, &sc.tables.materials);
@@ -2591,6 +2534,8 @@ impl LiveCore {
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..]));
+ // (The nodes went with the powers of the CPU's last refit: made again, as the moved emitters' areas are.)
+ self.weights_dirty = true;
}
/// Copies the GPU's current vertices of deforming meshes to the previous frame's, each where it lies: (its first
@@ -2665,7 +2610,7 @@ impl LiveCore {
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);
+ tables.retire(run.clone());
!run.is_empty()
};
for id in &ch.removed {
@@ -2678,7 +2623,7 @@ impl LiveCore {
// (A copy's emitters go as an instance's do.)
let run = emitter_run(&tables.emitter_tris, instances, r as u32);
emitters_changed |= !run.is_empty();
- tables.emitter_tris[run].iter_mut().for_each(|e| e.area = 0.0);
+ tables.retire(run);
if let Some(i) = instances.get_mut(r) {
i.hidden = true;
}
@@ -2700,7 +2645,7 @@ impl LiveCore {
top.clear(rec);
let run = emitter_run(&tables.emitter_tris, instances, rec as u32);
emitters_changed |= !run.is_empty();
- tables.emitter_tris[run].iter_mut().for_each(|e| e.area = 0.0);
+ tables.retire(run);
if let Some(i) = instances.get_mut(rec) {
(i.hidden, i.masked) = (true, false);
if edit.in_room(rec) {
diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rs
index 8c8040f..7e0eb33 100644
--- a/renderer/src/live/frame.rs
+++ b/renderer/src/live/frame.rs
@@ -21,15 +21,15 @@ pub(super) const TIMER_SLOTS: usize = 4;
/// Gap (ms) past which a slot's post pass is not its trace's frame's (`frame_gpu_ms`).
pub(super) const TIMER_GAP_MS: f32 = 2.0;
-/// A frame's GPU time (ms) from its slot's timestamps (trace, post, a free pair, particle pass pairs; zero: not run):
-/// from its first pass (particles or trace) to the end of its post pass. The post pass follows the trace's command
+/// A frame's GPU time (ms) from its slot's timestamps (trace, post, the emitter weights', particle pass pairs; zero:
+/// not run): from its first pass (particles, the emitters' weights or trace) to the end of its post pass. The post pass follows the trace's command
/// buffer within ~0.2 ms, after the frame's further samples (`spp` - 1 more traces, untimed, each about as long as
/// the first). In 2–3 % of the crowd scene's frames (Metal) a slot read the post pair of the frame that used the slot
/// next, 4 frames on: the span then read 70–80 ms while frames came every 16.7 ms. A post pass that begins more than
/// TIMER_GAP_MS past where those traces would end (twice their length) is not this frame's: the frame is counted as
/// its passes, the further traces at the first one's length.
pub(super) fn frame_gpu_ms(t: &[u64; 8], spp: u32, period_ns: f32) -> Option<f32> {
- let start = [t[6], t[0]].into_iter().filter(|&v| v > 0).min()?;
+ let start = [t[6], t[4], t[0]].into_iter().filter(|&v| v > 0).min()?;
if t[3] <= start {
return None;
}
@@ -45,7 +45,7 @@ impl FrameTimer {
pub(super) fn new(d: &wgpu::Device) -> FrameTimer {
let n = TIMER_SLOTS as u64;
FrameTimer {
- // Per slot: trace pass begin / end, post pass begin / end, a free pair, particle pass begin / end
+ // Per slot: trace pass begin / end, post pass begin / end, the emitter weights', particle pass begin / end
// (Metal writes a pass's timestamps in pairs).
queries: d.create_query_set(&wgpu::QuerySetDescriptor { label: Some("frame timer"), ty: wgpu::QueryType::Timestamp, count: (n * 8) as u32 }),
resolve: d.create_buffer(&wgpu::BufferDescriptor { label: None, size: n * 4 * wgpu::QUERY_RESOLVE_BUFFER_ALIGNMENT, usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }),
@@ -173,20 +173,15 @@ impl LiveCore {
b.emit_power[1] = cull;
b.emit_power[2] = cull * EMITTER_CULL_VIEW;
b.lod_view = [self.cam.fwd.x, self.cam.fwd.y, self.cam.fwd.z, cone];
- // Power edits held back for the emitter worker land first (its job in flight was built for the old reference:
- // 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, &crate::emitter_order(&e.emitter_tris, e.light_tree.as_ref()), &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;
+ // The weights carry the factor: made again from the new reference.
+ self.weights_dirty = true;
}
pub fn render(&mut self, spp: u32, extra: impl FnOnce(&mut wgpu::CommandEncoder, &wgpu::Buffer)) {
// A dynamic sky's bake that finished since the last frame (time of day).
self.take_sky();
- self.take_emitters();
+ // Runs of the light list retired since the last frame: their records say so, and the weights follow.
+ self.weights_dirty |= self.flush_retired();
// Settings a game or page requested since the last frame.
if let Some(r) = self.rendering_control.as_ref().and_then(|c| c.take()) { self.set_rendering(r); }
let (w, h) = (self.w, self.h);
@@ -312,6 +307,8 @@ impl LiveCore {
let tile_at = (((halton(self.frame % 64 + 1, 2) * 8.0) as u32).min(7), ((halton(self.frame % 64 + 1, 3) * 8.0) as u32).min(7));
// Something moves (triangles re-transformed, instances' transforms): the kernel writes motion vectors.
let moving = self.sc.moving_instances || gpu::Gpu::particle_meshes(&self.sc.up);
+ // (Whether this frame's first sample ran the emitter weight passes with their timestamps.)
+ let mut weighed = false;
for k in 0..spp.max(1) {
let mut p = self.sc.base;
p.motion[1] = reconstruction.raw_signal() as u32 as f32;
@@ -386,6 +383,16 @@ impl LiveCore {
if let (Some(f), 0) = (&self.sc.up.fills.particles, k) {
g.fill_emitters(f, &mut e);
}
+ // The emitters' weights again, when something they are made of changed.
+ if k == 0 && std::mem::take(&mut self.weights_dirty) && !self.sc.tables.emitter_tris.is_empty() {
+ let (t, b) = (&self.sc.tables, &self.sc.base);
+ let ts = match (&self.profile, &self.timer, timed) {
+ (None, Some(t), Some(slot)) => Some((&t.queries, slot as u32 * 8 + 4)),
+ _ => None,
+ };
+ weighed = ts.is_some();
+ g.weigh_emitters(&self.sc.up, &mut self.weights, t.emitter_tris.len() as u32, t.light_tree.as_ref(), t.stride as u32, b.light_lod, crate::EmitterCull::of(b), &mut e, ts);
+ }
{
let tw = match (&self.profile, &self.timer, timed) {
(Some(p), _, _) if k == 0 => Some(wgpu::ComputePassTimestampWrites { query_set: &p.queries, beginning_of_pass_write_index: Some(0), end_of_pass_write_index: Some(1) }),
@@ -443,8 +450,8 @@ impl LiveCore {
let at = slot as u64 * 4 * wgpu::QUERY_RESOLVE_BUFFER_ALIGNMENT;
e.resolve_query_set(&t.queries, q..q + 2, &t.resolve, at);
e.copy_buffer_to_buffer(&t.resolve, at, &t.reads[slot].0, 0, 16);
- // The free pair and the particle pair (pairs 2 and 3); zeros when the pass did not run.
- for (pair, ran) in [(2u32, false), (3, self.sc.up.particles.is_some() || self.sc.up.gpu_particles.is_some())] {
+ // The emitter weights' pair and the particle pair (pairs 2 and 3); zeros when the pass did not run.
+ for (pair, ran) in [(2u32, weighed), (3, self.sc.up.particles.is_some() || self.sc.up.gpu_particles.is_some())] {
let at = at + pair as u64 * wgpu::QUERY_RESOLVE_BUFFER_ALIGNMENT;
if ran {
e.resolve_query_set(&t.queries, q + pair * 2..q + pair * 2 + 2, &t.resolve, at);
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index b51c02a..42bf925 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -1267,6 +1267,16 @@ fn emitting_copies_changed_in_place_are_lit_as_a_build_lights_them() {
}
}
+/// The emitters' total weight as the kernel reads it: the header of their table on the GPU.
+fn kernel_total(c: &LiveCore) -> f32 {
+ let heap = &c.sc.up.heap;
+ let n = c.sc.tables.emitter_tris.len();
+ if n == 0 {
+ return 0.0;
+ }
+ read_back::<[f32; 4]>(c, &heap.buffer, heap.at(Table::Emitters) + crate::emitter_header(n) as u64 * 16, 16)[0][0]
+}
+
/// A view that took edits in place against one built from the edited world: the emitters that weigh something are as
/// many, each weighs what a build's does where a build's is, the kernel's total weight is a build's, and so is the
/// picture after 64 frames.
@@ -1282,10 +1292,13 @@ fn lit_as_a_build(what: &str, live: &mut LiveCore, fresh: &mut LiveCore) {
for (l, f) in wl.iter().zip(&wf) {
assert!((l.0 - f.0).abs() <= 1e-5 * f.0 && (Vec3::from(l.1) - Vec3::from(f.1)).length() <= 1e-4, "{what}: an emitter weighs {l:?}, a build's {f:?}");
}
- let (tl, tf) = (live.sc.base.misc[1], fresh.sc.base.misc[1]);
- assert!((tl - tf).abs() <= 1e-4 * tf.abs(), "{what}: the kernel's total weight {tl}, a build's {tf}");
forget(live);
let (a, b) = (picture(live, 64), picture(fresh, 64));
+ // (After a frame: the weights an edit left dirty are made by then.)
+ let (tl, tf) = (kernel_total(live), kernel_total(fresh));
+ assert!((tl - tf).abs() <= 1e-4 * tf.abs(), "{what}: the kernel's total weight {tl}, a build's {tf}");
+ // (And the build's table, which its first frame made on the GPU, is what the CPU makes of the same scene.)
+ weights_as_the_cpus(&format!("{what}, the build"), fresh);
assert!(apart(&a, &b) < 0.5, "{what}: the picture is {:.2} steps from a build's", apart(&a, &b));
}
@@ -1456,7 +1469,6 @@ fn power_edits_keep_the_light_lists_codes() {
w.set_transform(14, Vec3::new(-0.35 + 0.1 * k as f32, -0.45, 0.6), glam::Quat::from_rotation_z(0.3 * k as f32), Vec3::ONE).unwrap();
}
live.commit(&mut w).unwrap();
- live.land_powers_now();
list_is_its_triangles(&what(&format!("power {power}{}", if k > 0 { " and a material that starts emitting" } else { "" })), &live);
}
let t = &live.sc.tables;
@@ -5249,3 +5261,118 @@ fn the_fogs_ambient_light_is_seen_directly() {
assert!(p[at..at + 3].iter().all(|&c| c > 20), "the black quad in fog is drawn in the fog's colour: {:?}", &p[at..at + 4]);
}
}
+
+/// The emitters' table and the light tree's powers as the GPU holds them, against what the CPU makes of the same
+/// scene now (`emitter_cdf`, `LightTree::refit`): every weight, area, cumulative weight, node power and the header;
+/// and the table against itself: the cumulative weights rise to 1, each guide index is the first entry not below its
+/// bucket's start.
+fn weights_as_the_cpus(what: &str, live: &LiveCore) {
+ let (e, b) = (&live.sc.tables, &live.sc.base);
+ let n = e.emitter_tris.len();
+ let order = crate::emitter_order(&e.emitter_tris, e.light_tree.as_ref());
+ let (cdf, total, power) = crate::emitter_cdf(&e.emitter_tris, &order, &e.materials, &e.objects, e.stride, b.light_lod, crate::EmitterCull::of(b));
+ let heap = &live.sc.up.heap;
+ let table = read_back::<[f32; 4]>(live, &heap.buffer, heap.at(Table::Emitters), (crate::emitter_header(n) as u64 + 1) * 16);
+ let rel = |x: f32, y: f32| if x == y { 0.0 } else { (x - y).abs() / x.abs().max(y.abs()) };
+ for k in 0..n {
+ let (g, c) = (table[k], cdf[k]);
+ assert_eq!(g[0].to_bits(), c[0].to_bits(), "{what}: entry {k} is its emitter's");
+ assert!(rel(g[2], c[2]) <= 1e-5, "{what}: entry {k} weighs {} on the GPU, {} on the CPU", g[2], c[2]);
+ assert!(c[2] <= 0.0 || rel(g[3], c[3]) <= 1e-5, "{what}: entry {k}'s area {} on the GPU, {} on the CPU", g[3], c[3]);
+ assert!((g[1] - c[1]).abs() <= 1e-5, "{what}: entry {k}'s cumulative weight {} on the GPU, {} on the CPU", g[1], c[1]);
+ assert!(k == 0 || g[1] >= table[k - 1][1], "{what}: the cumulative weights rise at entry {k}");
+ }
+ let head = table[crate::emitter_header(n)];
+ assert!(rel(head[0], total) <= 1e-5, "{what}: the total {} on the GPU, {total} on the CPU", head[0]);
+ if total > 0.0 {
+ assert_eq!(table[n - 1][1], 1.0, "{what}: the cumulative weights end at 1");
+ for k in 0..=crate::EMITTER_GUIDE {
+ let u = k as f32 / crate::EMITTER_GUIDE as f32;
+ let first = table[..n].partition_point(|t| t[1] < u);
+ assert_eq!(table[n + k / 4][k % 4].to_bits() as usize, first, "{what}: guide index {k}");
+ }
+ }
+ let mut tail = 0.0;
+ if let Some(t) = &e.light_tree {
+ let mut t = t.clone();
+ let w: Vec<f32> = t.order.iter().map(|&i| crate::emitter_power(&e.emitter_tris[i as usize], &e.materials, &e.objects, e.stride)).collect();
+ t.refit(&|k| w[k]);
+ let nodes = read_back::<[f32; 4]>(live, &heap.buffer, heap.at(Table::LightTree), t.nodes.len() as u64 * 16);
+ for (i, (g, c)) in nodes.iter().zip(&t.nodes).enumerate() {
+ assert!(rel(g[2], c[2]) <= 1e-5, "{what}: node {i}'s power {} on the GPU, {} on the CPU", g[2], c[2]);
+ assert!(g[0].to_bits() == c[0].to_bits() && g[1].to_bits() == c[1].to_bits() && g[3].to_bits() == c[3].to_bits(), "{what}: node {i}'s sphere and children are kept");
+ }
+ tail = if power > 0.0 { ((power - t.power) / power).max(0.0) } else { 0.0 };
+ }
+ assert!((head[1] - tail).abs() <= 1e-5, "{what}: the tail's share {} on the GPU, {tail} on the CPU", head[1]);
+}
+
+/// `count` small emitters before a wall, their weights made on the GPU (emitter_weights.wgsl): as loaded, with some
+/// dimmed and some switched off, with all switched off, and back.
+fn weights_on_the_gpu(count: u32) {
+ let mut w = world();
+ for id in [11, 12, 20] {
+ w.set_visible(id, false).unwrap();
+ }
+ w.set_transform(10, Vec3::ZERO, glam::Quat::IDENTITY, Vec3::splat(10.0)).unwrap();
+ let mut seed = 12345u32;
+ let mut next = || {
+ seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
+ (seed >> 8) as f32 / 16777216.0
+ };
+ for i in 0..count {
+ w.set_object(100 + i, format!("emitter {i}"), None, Kind::Mesh { geometry: 3, material: 5, own_blas: false, materials: vec![] }, true, false).unwrap();
+ let at = Vec3::new((i % 20) as f32 - 9.5 + (next() - 0.5) * 0.4, (i / 20) as f32 - 9.5 + (next() - 0.5) * 0.4, 0.3);
+ w.set_transform(100 + i, at, glam::Quat::from_rotation_y(3.14159), Vec3::splat(0.05 + 0.1 * next())).unwrap();
+ }
+ let presets = crate::default_presets_dir();
+ let mut live = match gpu::Gpu::new().and_then(|g| LiveCore::new(g, &w, Path::new("."), &presets, 192, 108)) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ assert_eq!(live.sc.tables.light_tree.is_some(), count >= 256, "a light tree from 256 emitters on");
+ w.take_changes();
+ // (As loaded the table is the CPU's: made again once by hand. From then on each edit leaves it to the GPU.)
+ live.weights_dirty = true;
+ picture(&mut live, 1);
+ weights_as_the_cpus("as loaded", &live);
+ let mut edited = |what: &str, w: &mut World, live: &mut LiveCore| {
+ assert!(!live.commit(w).unwrap(), "{what}: in place ({:?})", live.fallback);
+ assert!(live.weights_dirty, "{what}: the weights are to be made again");
+ picture(live, 1);
+ weights_as_the_cpus(what, live);
+ };
+ for i in 0..count {
+ if i % 3 == 0 {
+ w.set_power(100 + i, if i % 2 == 0 { 0.25 } else { 0.0 }).unwrap();
+ }
+ }
+ edited("some dimmed, some off", &mut w, &mut live);
+ for i in 0..count {
+ w.set_power(100 + i, 0.0).unwrap();
+ }
+ edited("all off", &mut w, &mut live);
+ assert_eq!(kernel_total(&live), 0.0, "all off: nothing weighs");
+ for i in 0..count {
+ w.set_power(100 + i, 1.0 + (i % 5) as f32).unwrap();
+ }
+ edited("back on", &mut w, &mut live);
+ // Their material brighter, and of another colour.
+ w.set_material(5, serde_json::from_value(serde_json::json!({ "name": "m", "color": [0.0, 0.0, 0.0], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1.0, 0.5, 0.2], "emissiveIntensity": 90.0, "doubleSided": true })).unwrap());
+ edited("the material brighter", &mut w, &mut live);
+ // Some removed: their runs are retired.
+ for i in (0..count).step_by(7) {
+ w.remove(100 + i);
+ }
+ edited("some removed", &mut w, &mut live);
+}
+
+#[test]
+fn the_gpu_weighs_the_emitters_as_the_cpu_does() {
+ weights_on_the_gpu(400);
+}
+
+#[test]
+fn the_gpu_weighs_the_emitters_as_the_cpu_does_without_a_tree() {
+ weights_on_the_gpu(100);
+}
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index 45efde3..1ebe924 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -1,5 +1,5 @@
//! A scene loaded for the live view (`load_scene`, `LoadedScene`), and the worker threads its loading and its
-//! dynamic sky and emitters use (`DynamicSky`, `EmitterWorker`).
+//! dynamic sky use (`DynamicSky`).
use super::*;
@@ -7,7 +7,7 @@ pub(super) struct LoadedScene {
/// Load phases (parse, bvh, sky, accel build, upload) in ms.
pub(super) timings: Vec<(String, f64)>,
/// The meshes' triangles (model space) and their placements, kept on the CPU for picking and selection outlines.
- /// (A mesh the GPU skins has its build's pose here, but for its triangles that emit, which a new pose places:
+ /// (A mesh the GPU skins has its build's pose here, but for its triangles that which a new pose places:
/// `repose_skinned`. `LiveCore::mesh_tris` has the mesh as it is now.)
pub(super) pool_tris: Vec<[glam::Vec3A; 3]>,
/// The vertices that move, the first and how many (`indexed::Indexed::dynamic`); by skin source, the model's
@@ -59,8 +59,6 @@ pub(super) struct LoadedScene {
pub(super) volume_fns: Vec<(String, String, String)>,
/// Where in-place geometry edits write next (`edit_geometry`); a rebuild starts it afresh.
pub(super) edit: EditState,
- /// Power edits' emitter rebuilds on a worker (`EmitterWorker`), for scenes with many emitters.
- pub(super) emit: Option<EmitterWorker>,
/// The light list's path codes as the GPU has them (`GpuEmitterTri::code`, by emitter): the upload's, then what
/// `write_emitters` wrote, which writes only those that changed since.
pub(super) codes_sent: Vec<u32>,
@@ -140,99 +138,6 @@ impl DynamicSky {
}
}
-/// Scenes with at least this many emitters rebuild their emitter CDF for power edits on a worker (`EmitterWorker`).
-#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
-pub(super) const ASYNC_EMITTERS: usize = 100_000;
-
-/// Power edits in a scene with many emitters (a city's lamps and windows switching with the clock): the emitter CDF and
-/// the light tree's node powers are rebuilt on a worker thread (~13 ms over 1.4 M emitters, which held up the frame in
-/// `write_emitters`), and the edits land with them, in a later frame (`take_emitters`): the objects' powers, the CDF
-/// and the tree's powers together, so sampling and shading switch at once. The worker writes the CDF and the tree's
-/// nodes into a mapped staging buffer; the frame only copies it on the GPU (a 22 MB `write_buffer` cost it ~5 ms).
-/// Lockstep frames wait for it, so they repeat. Scenes whose emitters change in place (added in place: the tree's slot;
-/// moving emitters, whose nodes the frame refits) keep `write_emitters`; so does any other emitter edit (materials),
-/// which first lands the edits held back.
-pub(super) struct EmitterWorker {
- pub(super) ask: mpsc::Sender<EmitterJob>,
- pub(super) done: mpsc::Receiver<EmitterBuilt>,
- /// The emitters it was made for: a list that grew (added in place) makes another.
- pub(super) count: usize,
- /// The edits of the job it is on (they land with its result).
- pub(super) flight: Option<Vec<(usize, f32, f32)>>,
-}
-
-#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
-pub(super) struct EmitterJob {
- pub(super) materials: Vec<scene::GpuMaterial>,
- pub(super) objects: Vec<[f32; 4]>,
- pub(super) lod: [f32; 4],
- pub(super) cull: crate::EmitterCull,
-}
-
-pub(super) struct EmitterBuilt {
- /// The CDF then the tree's nodes, as the emitters buffer holds them (`put_emitters`), and their bytes.
- pub(super) staging: wgpu::Buffer,
- pub(super) bytes: u64,
- /// The CDF's entries (its guide table included).
- pub(super) entries: usize,
- pub(super) total: f32,
- pub(super) power: f32,
- /// The light tree's node powers (`nodes[i][2]`), for the frame's copy of the tree.
- pub(super) node_powers: Vec<f32>,
-}
-
-impl EmitterWorker {
- /// wasm32: none, and power edits rebuild in the frame as before (the browser's WebGPU device and buffers stay on
- /// the thread that made them).
- #[cfg(target_arch = "wasm32")]
- pub(super) fn new(_e: &tables::Tables, _device: &wgpu::Device) -> Option<EmitterWorker> {
- None
- }
-
- #[cfg(not(target_arch = "wasm32"))]
- pub(super) fn new(e: &tables::Tables, device: &wgpu::Device) -> Option<EmitterWorker> {
- // (Nor where an instance's emitters change in place, an instanced object's copies: the worker weighs its own
- // copy of the list.)
- let changing = e.light_tree.as_ref().is_some_and(|t| t.dynamic.is_some() || t.moving_count > 0) || e.emitter_tris.iter().any(|t| t.moves && t.inst != crate::NO_INST);
- if e.emitter_tris.len() < ASYNC_EMITTERS || changing {
- return None;
- }
- let device = device.clone();
- let (tris, mut tree, stride) = (e.emitter_tris.clone(), e.light_tree.clone(), e.stride);
- let order = crate::emitter_order(&tris, tree.as_ref());
- let (ask, asked) = mpsc::channel::<EmitterJob>();
- let (tx, done) = mpsc::channel();
- std::thread::Builder::new()
- .name("emitters".into())
- .spawn(move || {
- while let Ok(j) = asked.recv() {
- let (em, total, power) = crate::emitter_cdf(&tris, &order, &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]);
- t.nodes.iter().map(|n| n[2]).collect()
- });
- let nodes: &[[f32; 4]] = tree.as_ref().map_or(&[], |t| &t.nodes);
- let bytes = ((em.len() + nodes.len()) * 16) as u64;
- let staging = device.create_buffer(&wgpu::BufferDescriptor { label: Some("emitters staging"), size: bytes.max(16), usage: wgpu::BufferUsages::MAP_WRITE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: true });
- let at = em.len() as u64 * 16;
- for (range, data) in [(0..at, bytemuck::cast_slice::<_, u8>(&em)), (at..bytes, bytemuck::cast_slice(nodes))] {
- if !data.is_empty() {
- let Ok(mut m) = staging.slice(range).get_mapped_range_mut() else { break };
- m.copy_from_slice(data);
- }
- }
- staging.unmap();
- if tx.send(EmitterBuilt { staging, bytes, entries: em.len(), total, power, node_powers }).is_err() {
- break;
- }
- }
- })
- .ok()?;
- Some(EmitterWorker { ask, done, count: e.emitter_tris.len(), flight: None })
- }
-}
-
pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &Path, w: u32, h: u32, targets: &Targets) -> Result<(LoadedScene, ViewState, Environment)> {
let t0 = Instant::now();
let mut sc = scene::build(world, assets, presets, None)?;
@@ -247,8 +152,6 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
// (THREERT_EDIT_REBUILD=1: every edit rebuilds, a material that starts emitting too: the A/B.)
tables.emit_in_place = std::env::var("THREERT_EDIT_REBUILD").map_or(true, |v| v != "1");
tables.moving_mats = std::mem::take(&mut prep.moving_mats);
- let emit = EmitterWorker::new(&tables, &g.device);
- tables.defer_powers = emit.is_some();
let fixed_features = (!sc.textures.is_empty(), !sc.shaders.is_empty());
let shaders = sc.shaders.clone();
let volume_fns = sc.volume_fns.clone();
@@ -327,5 +230,5 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
verts: Holes::new(vertices, vertices + room.tris * 3),
free_skinned: vec![],
};
- Ok((LoadedScene { timings, triangles, pool_tris, dynamic_verts, skins, skin_trees, pool_place, meshes, instances, sections, rows, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), instance_features, name: sc.name.clone(), up, base, tables, fixed_features, shaders, translucent_mats, translucent_used, volume_fns, edit, emit, codes_sent }, view, env))
+ Ok((LoadedScene { timings, triangles, pool_tris, dynamic_verts, skins, skin_trees, pool_place, meshes, instances, sections, rows, gpu_instances, procs, proc_first, moving_instances: tables.retained.moves_instances(), instance_features, name: sc.name.clone(), up, base, tables, fixed_features, shaders, translucent_mats, translucent_used, volume_fns, edit, codes_sent }, view, env))
}
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index 11c87ba..0815223 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -363,6 +363,15 @@ pub struct LiveCore {
emitters_reweigh: bool,
/// Emitters made in place this commit, for `write_emitters` (`start_moving`: a still mesh's, moving from now on).
pending_emitters: Vec<(u32, crate::GpuEmitterTri)>,
+ /// Something the emitters' weights are made of changed (a material, a power, a record, the table or the tree as
+ /// the CPU wrote them), or the scene is new (its first frame makes them, and the passes' pipelines with them, not
+ /// its first edit): the next frame makes them again on the GPU (`gpu::Gpu::weigh_emitters`), with what its
+ /// passes keep.
+ weights_dirty: bool,
+ weights: Option<gpu::EmitterWeights>,
+ /// Emitters have been added in place since the scene was built: an emitter edit grows the tree's slot again
+ /// (`write_emitters`).
+ slot_used: bool,
/// Objects whose instance a move hid or brought back this commit (a placement without size): their rows' power.
flipped: Vec<u32>,
/// Likewise for posed skinned models' meshes (`repose_skinned`): the spans the last new poses took (each mesh's
@@ -577,7 +586,7 @@ impl LiveCore {
let mut core = LiveCore {
kernel: None,
more_features: Default::default(),
- reconstructor, quality: Quality::Native, frame_generation: FrameGeneration::Off, latency: Latency::Auto, rendering_control: None, pending_emitters: vec![], flipped: vec![], top_builds: 0, particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: Default::default(), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, build_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, cache, kernel_bg, tl_kernel_bg, emitters_moved: false, emitters_reweigh: false, pose_spans: vec![], pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };
+ reconstructor, quality: Quality::Native, frame_generation: FrameGeneration::Off, latency: Latency::Auto, rendering_control: None, pending_emitters: vec![], weights_dirty: true, weights: None, slot_used: false, flipped: vec![], top_builds: 0, particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: Default::default(), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, build_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, cache, kernel_bg, tl_kernel_bg, emitters_moved: false, emitters_reweigh: false, pose_spans: vec![], pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };
core.spark_lights = core.sc.tables.emitter_tris.iter().any(|e| e.nominal);
core.apply_post();
Ok(core)
@@ -693,6 +702,8 @@ impl LiveCore {
// What the grid programs had simulated goes with the grids that are still the same.
self.g.carry_grids(&self.sc.up, &s.up);
self.sc = s;
+ // (What the weight passes kept was the old scene's; the first frame makes the weights, as after a load.)
+ (self.weights, self.weights_dirty, self.slot_used) = (None, true, false);
// (Its data is its own kernel's: the load made that one.)
self.kernel = None;
self.spark_lights = self.sc.tables.emitter_tris.iter().any(|e| e.nominal);
@@ -1204,6 +1215,8 @@ mod timer_tests {
assert_eq!(frame_gpu_ms(&[0, 0, 0, 0, 0, 0, 0, 0], 1, 1.0), None);
let particles_first = [2_000_000, 9_000_000, 9_200_000, 14_000_000, 0, 0, 1_000_000, 1_900_000];
assert_eq!(frame_gpu_ms(&particles_first, 1, 1.0), Some(13.0));
+ let weights_first = [2_000_000, 9_000_000, 9_200_000, 14_000_000, 1_500_000, 1_900_000, 0, 0];
+ assert_eq!(frame_gpu_ms(&weights_first, 1, 1.0), Some(12.5));
// 3 samples: two more traces (untimed) between the first and the post pass, a 16.2 ms gap: the span. The post
// pair of frame 458 under 3 samples: still out of place (trace 7.85 ms, gap 66.7 ms), counted as the passes.
let three = [1_000_000, 9_000_000, 25_200_000, 31_000_000, 0, 0, 0, 0];
diff --git a/renderer/src/ltree.rs b/renderer/src/ltree.rs
index 9e65812..062cb85 100644
--- a/renderer/src/ltree.rs
+++ b/renderer/src/ltree.rs
@@ -70,6 +70,8 @@ pub struct LightTree {
pub code: Vec<u32>,
/// Total power of the tree's emitters.
pub power: f32,
+ /// Counts the times its nodes were grown again (`set_dynamic`): what reads the topology knows it is another.
+ pub structure: u32,
/// The moving emitters' subtree (node 2, under the root; none without moving emitters): its entries
/// `moving_first..moving_first + moving_count` (after the static ones), its nodes below node 2 from `moving_nodes`.
pub moving_first: u32,
@@ -223,6 +225,34 @@ impl LightTree {
Ok(deepest as usize)
}
+ /// The nodes by depth, the deepest first, and each depth's count: the order a bottom-up sum of the powers takes
+ /// them in (emitter_weights.wgsl `tree`). Without the leaves over nothing (the empty slot: its word names no
+ /// entry of its own, its power stays 0).
+ pub fn levels(&self) -> (Vec<u32>, Vec<u32>) {
+ let n = self.nodes.len();
+ let mut depth = vec![u32::MAX; n];
+ if n > 0 {
+ depth[0] = 0;
+ }
+ for i in 0..n {
+ let w = self.nodes[i][3].to_bits();
+ if depth[i] != u32::MAX && w & LEAF == 0 && (w as usize + 1) < n {
+ (depth[w as usize], depth[w as usize + 1]) = (depth[i] + 1, depth[i] + 1);
+ }
+ }
+ let empty = |i: usize| self.nodes[i][3].to_bits() & LEAF != 0 && self.ranges[i].0 == self.ranges[i].1;
+ let mut list: Vec<u32> = (0..n as u32).filter(|&i| depth[i as usize] != u32::MAX && !empty(i as usize)).collect();
+ list.sort_by_key(|&i| std::cmp::Reverse(depth[i as usize]));
+ let mut counts: Vec<u32> = vec![];
+ for (k, &i) in list.iter().enumerate() {
+ if k == 0 || depth[i as usize] != depth[list[k - 1] as usize] {
+ counts.push(0);
+ }
+ *counts.last_mut().unwrap() += 1;
+ }
+ (list, counts)
+ }
+
/// Node powers again from the entries' weights (power / material edits; `weight(k)` of entry k = position in
/// `order`): same topology, sums bottom-up (children come after their parent).
pub fn refit(&mut self, weight: &dyn Fn(usize) -> f32) {
@@ -297,6 +327,7 @@ impl LightTree {
/// their codes in `code`; the root's power the sum again. The static subtree, its entries and codes are kept.
pub fn set_dynamic(&mut self, items: Vec<DynItem>) {
let Some((fixed, ns)) = self.dynamic else { return };
+ self.structure = self.structure.wrapping_add(1);
let ns = ns as usize;
self.nodes.truncate(fixed);
self.ranges.truncate(fixed);
diff --git a/renderer/src/tables.rs b/renderer/src/tables.rs
index 581bdad..7f42be6 100644
--- a/renderer/src/tables.rs
+++ b/renderer/src/tables.rs
@@ -19,11 +19,8 @@ pub struct Dirty {
/// A local light moved, or went dark or lit: the light groups are sorted again (`Tables::regroup_lights`).
pub lights_moved: bool,
pub objects: bool,
- /// Emitter weights changed (powers): the emitter CDF and the light tree's powers are rebuilt.
+ /// Emitter weights changed (powers): they are made again (live/edits.rs `commit`).
pub emitters: bool,
- /// Power edits held back (`Tables::defer_powers`): the live view's emitter worker rebuilds the CDF and the tree's
- /// powers for them, and they land together.
- pub deferred: bool,
/// A material's class changed (glass or not, a cutout or not): the instances with a row of one have their rows
/// remade (live/edits.rs `remake_classes`).
pub reclassed: bool,
@@ -31,7 +28,7 @@ pub struct Dirty {
impl Dirty {
pub fn any(&self) -> bool {
- self.materials || self.lights || self.objects || self.emitters || self.deferred
+ self.materials || self.lights || self.objects || self.emitters
}
}
@@ -59,11 +56,8 @@ pub struct Tables {
pub light_index: HashMap<u32, Vec<usize>>,
/// vec4s an object in `objects` (`scene::object_stride`).
pub stride: usize,
- /// Power edits are held back in `deferred` instead of written to `objects` (the live view's emitter worker: a
- /// scene with many emitters, live/load.rs `EmitterWorker`).
- pub defer_powers: bool,
- /// Held-back power edits: (the object's first row in `objects`, its power, the time of the edit).
- pub deferred: Vec<(usize, f32, f32)>,
+ /// Runs of the light list retired since the last commit's end (`retire`), for their records' `EMITTER_GONE`.
+ pub retired: Vec<std::ops::Range<usize>>,
}
impl Tables {
@@ -86,12 +80,23 @@ impl Tables {
reclassed: vec![],
light_index,
stride: sc.object_stride(),
- defer_powers: false,
- deferred: vec![],
+ retired: vec![],
}
}
/// Writes power edits into `objects` (the power, and the time of the edit, the second row's w).
+ /// A run of the light list retired: its emitters weigh nothing from now on (their entries and the tree keep
+ /// their places), on the CPU by their area, on the GPU by their records' `EMITTER_GONE`, written at the commit's
+ /// end.
+ pub fn retire(&mut self, run: std::ops::Range<usize>) {
+ for e in &mut self.emitter_tris[run.clone()] {
+ e.area = 0.0;
+ }
+ if !run.is_empty() {
+ self.retired.push(run);
+ }
+ }
+
pub fn put_powers(&mut self, powers: &[(usize, f32, f32)]) {
for &(row, power, now) in powers {
self.objects[row][3] = power;
@@ -121,15 +126,9 @@ impl Tables {
// no weight until it comes back.)
let unseen = matches!(o.kind, Kind::Mesh { .. } | Kind::Model { .. }) && (!w.shown(*id) || scene::placed_world(w.world_matrix(*id), glam::Vec3::ZERO).1);
let power = if unseen { 0.0 } else { o.power.max(0.0) };
- if self.defer_powers {
- self.deferred.retain(|p| p.0 != row);
- self.deferred.push((row, power, now));
- d.deferred = true;
- } else {
- self.put_powers(&[(row, power, now)]);
- d.objects = true;
- d.emitters = true;
- }
+ self.put_powers(&[(row, power, now)]);
+ d.objects = true;
+ d.emitters = true;
}
self.update_light(w, *id, &mut d);
}