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.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
A ray that sees stops at its eighth cutout, and the profile times the trace's passes (#311)
YX7b48d4ca8d03
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex abae37c..e8c4c18 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -2738,6 +2738,64 @@ distance is its surface's): in motion the clamp cuts its light, as the upscaler'surface that moves by itself is not recorded either. Dynamic resolution pays for the guides with a lower scale: notmeasured. Not checked on Vulkan, nor in a browser (both of its modules build).+**Where the trace's time goes, and a bound on it (2026-12-05, after it).** The guides of the entry above made+the frame a quarter to a third longer (three clips' GPU time 9.7 -> 13.1, 11.2 -> 14.5, 5.4 -> 6.7 ms; two scenes in+motion 16.2 -> 21.5 and 20.3 -> 27.4). This entry measures where a frame's trace spends it, and keeps what the+measurements bore out. An M4, 1280 x 720, render scale 0.5 unless said.++- The profile times the trace's passes apart. With `THREERT_PROFILE` each of the kernel's dispatches of a frame's+ first sample is a compute pass with stamps of its own (`frame.rs` `KERNEL_STAGES`), printed after `trace` as+ `trace.guides`, `.first_hit`, `.paths`, `.finish`, `.direct`, `.rest`; the trace's own time is from the first+ one's begin to the last one's end, as it was (20.36 ms for 20.44). Bistro's street view, at rest and walking:+ guides 3.33 / 3.02, camera hits 1.34 / 1.02, paths 3.88 / 4.66, `finish` 2.05 / 2.69, the resampled lights 2.88 /+ 3.30 of 20.4 / 21.9. Over three render scales each pass is a fixed part and a part by the pixel: the camera hits+ 0.77 ms + 2.4 ns, the paths 0.36 + 15.3, the lights 0.14 + 11.9, `finish` 9.8 ns alone. A kernel pass that+ returns at its first line costs 0.4 ns a thread: the fixed parts are not the kernel's size.+- They are the trees. Timed over parts of the frame, the camera hits' pass was 0.26 ms on the picture's left half+ and 1.09 on the right: a ray through a crown passes many cut-out cards, and under hardware traversal each one+ passed is a ray query started again. With the kernel's switches that take those queries away (every cutout solid+ to shadow rays, four steps for a camera ray) the frame was 20.5 -> 18.2 ms: 2.4 ms of it are queries past a+ cutout, 1.5 of them the camera rays', which are five times what they were before the guides.+- A bound on them: of the cutouts a ray that sees meets, the eighth stands whole (`A_CUTOUT_DEEP`, a live+ approximation as the others are, RUNTIME.md's table; software traversal has the same rule). The street view 20.3+ -> 19.2 ms (guides 3.35 -> 2.70, camera hits 1.33 -> 0.87). The crowd's clip: GPU 13.1 -> 12.1 ms, ΔE against the+ offline render 3.11 -> 3.12, its change from frame to frame 1.007 -> 0.922; 0.26 % of its pixels are off by more+ than 8 of 255, all in the crowns. Render tests `cutout/deep` (offline), `-live` (the eighth of ten clear cards is+ what is seen), `-live-exact`; all three under either traversal.+- Against main: two scenes in motion, the frame 21.48 -> 20.27 ms (Bistro) and 27.40 ->+ 27.27 (Zero Day); mean ΔE over their offline moments 2.82 -> 2.83 and 4.56 -> 4.56, detail the same, the change at+ rest the same or less; what a moving object leaves behind the same (ratio 1.000), the camera's bench and the ten+ lighting edits the same. Unit suite 298, render suite 283 (three new).++Tried and not kept, each built and measured.+- The cutouts' maps for every ray that asks an alpha (a cell all there stops it, one all gone lets it by, a part of+ both is asked of the texture). In the query's candidate loop the guides' pass was 3.34 -> 5.84 ms and the camera+ hits 1.35 -> 3.39: every cutout triangle along the whole ray comes back to the shader. In front of the alpha+ test, the queries as they are: no change. The cost is the query, not the texture.+- The lighting of a part of the traced pixels a frame (of each 2 x 2 block one, two or three in turn; the others'+ guides from the first pass's hits, their lighting from the lit ones around them by the surfaces' likeness, counted+ for a sixteenth of a sample in a history that has one). The frame -5 % at three of four, -15 to -17 % at two,+ -26 to -29 % at one. At the same frame time a lower render scale is the better picture: in motion, mean ΔE of the+ two scenes 3.11 / 5.58 at half the pixels against 3.02 / 4.95 at scale 0.42, and 2.94 / 5.04 at three of four+ against 2.90 / 4.72 at scale 0.46, the detail equal. The output has its guides at its own resolution, so the+ traced grid already is lighting below them, and its scale lowers every cost of the grid, where lighting a part of+ it keeps the camera hits and the denoiser whole, adds a pass and halves each pixel's own samples.+- The cache's training. `finish` is nearly all of it (an eighth of the tiles 2.05 ms, a sixteenth 0.97, none 12.65:+ every lookup then finds its voxel cold). Half of it at scale 0.5: the frame -5 to -6 %, Zero Day's ΔE +9 %. And+ as a budget of paths a frame, what a traced grid of 640 x 360 has, on the reasoning that the cache's voxels are+ sized by the angle they are seen under and a larger grid has no more of them: at scale 1.0 the two scenes in+ motion were 58.9 -> 50.7 and 75.5 -> 64.8 ms, Bistro's mean ΔE 2.24 -> 2.27, Zero Day's 3.63 -> 4.10 with its+ change from frame to frame +14 to +62 %. Where the lighting never rests the cache keeps four frames of samples,+ and every path is one that counts. Three still clips had shown a twentieth of ΔE there: a change that does+ nothing at the scale the benches run at has to be judged in motion where it does something.++Not done. The render scale is now the lighting's rate and its slope is gentle (in motion, scale 0.5 / 0.46 / 0.42:+the frame 21.2 / 19.1 / 17.1 ms and 27.3 / 24.6 / 22.4, mean ΔE 2.82 / 2.90 / 3.02 and 4.56 / 4.72 / 4.95, detail+0.563 / 0.549 / 0.541 and 0.520 / 0.506 / 0.492): the default scale and dynamic resolution's floor are as they were.+The queries past a cutout that are left (about 1.3 ms of that view) want what this renderer does not have: opacity+micromaps in the acceleration structure, or a first hit that is rasterised. The twelve clips against offline were+not run. Not checked on Vulkan, nor in a browser (both of its modules build).+**The live passes from one place (2026-11-14, after it).** A buffer and a pass more (the locks' carry, above) tookseven edits that had to agree: the declaration in live.wgsl, the bind group layout's entries, the pass list, thebuffers' sizes and order, the bind group's entries, the dispatch grid (in two copies), and the merged layout's table.diff --git a/docs/RUNTIME.md b/docs/RUNTIME.mdindex 7d64955..f0c1756 100644--- a/docs/RUNTIME.md+++ b/docs/RUNTIME.md@@ -1772,12 +1772,23 @@ view, the way to hold a live picture to the offline one).| 4 `A_CUTOUT_PATHS` | cutouts are opaque to rays past a camera hit's own, off mirror paths | a camera hit's own light is whole (`sky/cutout-clear-live`: its samples take the share those rays cannot bring, `light_mis`); what a cutout lights sends nothing on (`sky/cutout-bounce`: black) | Bistro +1.63 ms of 8.54 || 8 `A_CUTOUT_EMITTERS` | at a camera hit, emitters' shadow rays ask a cutout's map (its triangles' cells, solid or hole, made once from its alpha: renderer/src/cutout.rs) in one query and read no texture; a cutout without maps (a material whose function may change its opacity; one whose material or texture was edited since the maps were made; a mesh an edit wrote) is opaque to them | a camera hit's light past a cutout is whole (`shadow/cutout-emitter-live`, `shadow/cutout-emitter-side-live`); a cell is two texels wide, sixteen on Bistro's widest cards, and offline by the maps its foliage reads 0.9999 and 0.9994 of the light the alpha test gives | Bistro's frame +14 % (16.0 -> 18.2 ms at the street's first view, 17.9 -> 20.6 over its walk) || 16 `A_FAR_EMITTERS` | the light tree proposes no emitter beyond 120 m; without a tree, the emitter cull (60 m, 120 m in view) | panels 150 m up: 3 % of their light (`light/emitter-far`); Kabukichō's and Tokyo's shots unchanged | Tokyo from the air 4.7 -> 9.2 ms; the 3 x 3 district +0.15 |+| 32 `A_CUTOUT_DEEP` | of the cutouts a ray that sees (a camera ray, a mirror path's) meets, the eighth stands whole: the alpha is asked of the seven before it alone. Without it hardware traversal asks sixteen, then finds nothing, and software traversal asks every one (under hardware traversal every cutout passed is a ray query started again, which is what this bounds) | behind ten clear cards a glow is not seen (`cutout/deep`); Bistro's street view: 0.26 % of the picture's pixels off by more than 8 of 255, all in the trees' crowns, ΔE against the offline render 3.11 -> 3.13 | Bistro +1.1 ms of 20.3 (the output's guides 2.70 -> 3.35 ms, the camera hits 0.87 -> 1.33) |Measured 2026-11-15 and 16 with the loop guard on. Bistro held still, ΔE against the offline render: 1.82 asshipped, 1.66 without the two cutout bits (+3.5 ms; Zero Day, with few cutouts, +0.3).The emitters' row is of 2026-12-02 (an M4 at half resolution). Until then every cutout was opaque to those rays: anemitter behind a clear card read black, and beside Bistro's potted bushes and its hedge the picture had 0.78 and 0.71of the offline render's light for 0.97 and 0.99.+The deep cutouts' row is of 2026-12-05 (an M4 at half resolution, the output composed from its own guides: a camera+ray for every output pixel, so the queries a tree's crown asks are five times what they were). Timed over parts of+the frame, the camera hits' pass was 0.26 ms on the picture's left half and 1.09 on the right, where the trees are:+of that frame the queries past a cutout were 2.4 ms in all (camera rays 1.5, the shadow rays that test the alpha+0.9). Two ways to answer a cutout's alpha with its map (cutout.rs: a cell all there, all gone, or a part) were+measured first and are not in the kernel: the map in the query's candidate loop, with the triangles of a cell that+is a part taken as hits to test, was slower than the queries it saved (the guides' pass 3.34 -> 5.84 ms, the camera+hits 1.35 -> 3.39: every cutout triangle along the whole ray comes back as a candidate); the map in front of the+alpha test, the queries as they are, saved nothing (3.41, 1.35): what costs is a query started again, not the+texture read.Two more were removed that day: a single-query shadow ray past cutouts (it saved nothing: Bistro 10.13 ms with it,10.09 without, Tokyo +0.05) and the switch for the sampler below.diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgslindex 5c8d78a..cadc23a 100644--- a/renderer/shaders/pathtrace.wgsl+++ b/renderer/shaders/pathtrace.wgsl@@ -65,7 +65,9 @@ const A_MEDIA_SHADOWS: u32 = 2u; // of the media only the homogeneous ones dimconst A_CUTOUT_PATHS: u32 = 4u; // cutouts are opaque to rays past a camera hit's own, off mirror paths (`cutouts_opaque`)const A_CUTOUT_EMITTERS: u32 = 8u; // emitters' shadow rays ask a cutout's map and read no texture; one without maps is opaque to them (`emitter_tr`)const A_FAR_EMITTERS: u32 = 16u; // the light tree proposes no emitter beyond LT_FAR (`lt_imp`; without a tree: the emitter cull)+const A_CUTOUT_DEEP: u32 = 32u; // of the cutouts a ray that sees (a camera ray, a mirror path's) meets, the CUTOUT_DEEP-th stands whole: the alpha is asked of those before it alone (`trace`, `trace_units`)fn approx(a: u32) -> bool { return (APPROX & a) != 0u; }+const CUTOUT_DEEP: u32 = 8u;// Features the scene uses (gpu::F_*): the rest is compiled out, so plain scenes pay nothing for them.override FEAT: u32 = 0xffffffffu;const F_MASKED: u32 = 1u;diff --git a/renderer/shaders/trace_hw.wgsl b/renderer/shaders/trace_hw.wgslindex 2e32faf..726b702 100644--- a/renderer/shaders/trace_hw.wgsl+++ b/renderer/shaders/trace_hw.wgsl@@ -41,7 +41,17 @@// In order, each query starting past the last cutout hit its alpha let through. Shadow rays take up to 64 of them// and count as blocked past that: with 16, as closest hits take, the rest counted as unblocked (light through dense// foliage: Bistro's offline render up to 2.3 % bright in a region against the software BVH).- @if(!cutout_lite2) let steps = select(16u, 64u, any);+ // A_CUTOUT_DEEP: a closest hit takes CUTOUT_DEEP, and the cutout its last one meets stands whole, where 16 then+ // end in nothing. Each query starts the traversal again, and a view through a tree's crown is many: of Bistro's frame+ // at its street view the queries past the eighth were 1.1 ms of 20.3 (an M4, half resolution; guides 3.35 ->+ // 2.70 ms, camera hits 1.33 -> 0.87), for 0.26 % of the picture's pixels off by more than 8 of 255, all in the+ // crowns, and ΔE against the offline render 3.11 -> 3.13. (What stands in for the queries is not in reach here:+ // the cutouts' maps in the query's candidate loop, as opacity micromaps answer, were slower on Metal than the+ // queries, guides 5.84 ms; in front of the alpha test they saved nothing: the cost is the queries, not the+ // texture.)+ @if(!cutout_lite2) let deep = approx(A_CUTOUT_DEEP) && !any;+ @if(!cutout_lite2) let steps = select(select(16u, CUTOUT_DEEP, deep), 64u, any);+ @if(cutout_lite2) let deep = false;@if(cutout_lite2) let steps = 4u;// One ray query in the source for every kind of ray. `trace` is inlined where it is called, and each query written// in it costs every ray, taken or not: with a query of its own for opaque cutouts and one for a shadow ray's first@@ -63,7 +73,7 @@// out of its way by its mask).let passes = has(F_IGLASS) && mask == 1u && hit_row != NO_ROW && (hit_row & ROW_GLASS) != 0u;if (!passes) {- if (!has(F_MASKED) || solid || is_proc(h) || !cutout_hit(h) || alpha_pass(h.tri, h.inst, h.part, h.u, h.v, t)) { return Hit(t, h.tri, h.u, h.v, h.inst, h.part); }+ if (!has(F_MASKED) || solid || is_proc(h) || !cutout_hit(h) || (deep && k + 1u >= steps) || alpha_pass(h.tri, h.inst, h.part, h.u, h.v, t)) { return Hit(t, h.tri, h.u, h.v, h.inst, h.part); }hole = true;}if (first) { first = false; } else { t0 = t + 1e-4 * max(1.0, t); }diff --git a/renderer/shaders/trace_units.wgsl b/renderer/shaders/trace_units.wgslindex 63dff1e..6e6516b 100644--- a/renderer/shaders/trace_units.wgsl+++ b/renderer/shaders/trace_units.wgsl@@ -51,6 +51,9 @@ const UNIT_SHIFTED: u32 = 2u;@if(units) fn trace_units(o: vec3<f32>, d: vec3<f32>, inv_d: vec3<f32>, hit_in: Hit, mode: u32) -> Hit {var hit = hit_in;if (bitcast<u32>(P.motion.w) == 0u) { return hit; }+ // (The cutouts whose alpha let the ray by, and whether it is one that stops asking: A_CUTOUT_DEEP.)+ var passed = 0u;+ let deep = approx(A_CUTOUT_DEEP) && mode == TRACE_CLOSEST;let top = bitcast<u32>(P.motion.z);let whole = nodes[top];if (ray_aabb(o, inv_d, whole.bmin, whole.bmax, hit.t) == INF) { return hit; }@@ -120,7 +123,12 @@ const UNIT_SHIFTED: u32 = 2u;var flags = 0u;if ((ubits & (INST_CUTOUT | INST_GLASS)) != 0u) { flags = row_flags(urows, part); }if (has(F_IGLASS) && mode == TRACE_SHADOW && (flags & TRI_NO_SHADOW) != 0u) { continue; }- if (has(F_MASKED) && (flags & TRI_MASKED) != 0u && !cutouts_opaque() && !unit_cutout_stops(ti, rec, urows, part, x.y, x.z, x.x, mode)) { shadow_hole = true; continue; }+ // (A_CUTOUT_DEEP: past CUTOUT_DEEP - 1 cutouts that let a ray that sees by, the next stands whole.)+ if (has(F_MASKED) && (flags & TRI_MASKED) != 0u && !cutouts_opaque() && !(deep && passed + 1u >= CUTOUT_DEEP) && !unit_cutout_stops(ti, rec, urows, part, x.y, x.z, x.x, mode)) {+ shadow_hole = true;+ passed += 1u;+ continue;+ }hit = Hit(x.x, ti, x.y, x.z, rec, part);if (mode != TRACE_CLOSEST) { return hit; }}diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rsindex e1974a7..1b7e70c 100644--- a/renderer/src/gpu.rs+++ b/renderer/src/gpu.rs@@ -1916,8 +1916,9 @@ pub const A_MEDIA_SHADOWS: u32 = 2;pub const A_CUTOUT_PATHS: u32 = 4;pub const A_CUTOUT_EMITTERS: u32 = 8;pub const A_FAR_EMITTERS: u32 = 16;+pub const A_CUTOUT_DEEP: u32 = 32;/// All of them: what a live view takes unless it asks otherwise (`GpuOptions::approx`).-pub const A_LIVE: u32 = 31;+pub const A_LIVE: u32 = 63;// Kernel features (`override FEAT` in pathtrace.wgsl).pub const F_MASKED: u32 = 1;@@ -4354,7 +4355,7 @@ mod tests {}let wgsl = include_str!("../shaders/pathtrace.wgsl");// The live approximations: one bit each, the shader's the same, `A_LIVE` all of them.- let approx = [("A_GLASS_SHADOWS", A_GLASS_SHADOWS), ("A_MEDIA_SHADOWS", A_MEDIA_SHADOWS), ("A_CUTOUT_PATHS", A_CUTOUT_PATHS), ("A_CUTOUT_EMITTERS", A_CUTOUT_EMITTERS), ("A_FAR_EMITTERS", A_FAR_EMITTERS)];+ let approx = [("A_GLASS_SHADOWS", A_GLASS_SHADOWS), ("A_MEDIA_SHADOWS", A_MEDIA_SHADOWS), ("A_CUTOUT_PATHS", A_CUTOUT_PATHS), ("A_CUTOUT_EMITTERS", A_CUTOUT_EMITTERS), ("A_FAR_EMITTERS", A_FAR_EMITTERS), ("A_CUTOUT_DEEP", A_CUTOUT_DEEP)];assert_eq!(approx.iter().fold(0, |all, a| { assert!(a.1.is_power_of_two() && all & a.1 == 0, "{} = {}", a.0, a.1); all | a.1 }), A_LIVE);let declared: Vec<&str> = wgsl.lines().filter(|l| l.starts_with("const A_")).collect();assert_eq!(declared.len(), approx.len());@@ -4363,7 +4364,7 @@ mod tests {}// (The render tests' names for them: tests/render/lib.ts `APPROX`.)let lib = include_str!("../../tests/render/lib.ts");- for (name, bit) in [("glassShadows", A_GLASS_SHADOWS), ("mediaShadows", A_MEDIA_SHADOWS), ("cutoutPaths", A_CUTOUT_PATHS), ("cutoutEmitters", A_CUTOUT_EMITTERS), ("farEmitters", A_FAR_EMITTERS)] {+ for (name, bit) in [("glassShadows", A_GLASS_SHADOWS), ("mediaShadows", A_MEDIA_SHADOWS), ("cutoutPaths", A_CUTOUT_PATHS), ("cutoutEmitters", A_CUTOUT_EMITTERS), ("farEmitters", A_FAR_EMITTERS), ("cutoutDeep", A_CUTOUT_DEEP)] {assert!(lib.contains(&format!("{name}: {bit},")), "{name}: tests/render/lib.ts and gpu.rs differ");}assert!(lib.contains(&format!("all: {A_LIVE},")));diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rsindex e8b9ac4..dc453e9 100644--- a/renderer/src/live/frame.rs+++ b/renderer/src/live/frame.rs@@ -143,6 +143,24 @@ pub(super) struct Profile {pub(super) grid: (wgpu::QuerySet, wgpu::Buffer, wgpu::Buffer),pub(super) grid_sum: f64,pub(super) media_sum: f64,+ /// The trace's parts (`KERNEL_STAGES`): while profiling, each of the kernel's dispatches of a frame's first sample+ /// is a pass of its own with a pair of stamps, and the trace's time is from the first one's begin to the last+ /// one's end. Their queries, the resolve and read buffers, the sums.+ pub(super) kernel: (wgpu::QuerySet, wgpu::Buffer, wgpu::Buffer),+ pub(super) kernel_sums: [f64; KERNEL_STAGES.len()],+}++/// The kernel's dispatches a profile times apart, in the order a frame runs them: the output's guides, the camera+/// hits, the paths, the radiance cache's ends (`finish`), the lights a camera hit resamples, and what else the+/// trace's pass holds (the surface guides of a reconstruction that asks for them, the media's training).+pub(super) const KERNEL_STAGES: [&str; 6] = ["guides", "first_hit", "paths", "finish", "direct", "rest"];++/// A compute pass of the kernel's: its two bind groups set.+fn kernel_compute_pass<'e>(e: &'e mut wgpu::CommandEncoder, label: &str, tw: Option<wgpu::ComputePassTimestampWrites>, scene: &wgpu::BindGroup, targets: &wgpu::BindGroup) -> wgpu::ComputePass<'e> {+ let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some(label), timestamp_writes: tw });+ pass.set_bind_group(0, scene, &[]);+ pass.set_bind_group(1, targets, &[]);+ pass}/// Whether pass `name` runs: the passes that compose the output from its own guides only where it is (`decoupled`), and@@ -379,6 +397,8 @@ impl LiveCore {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;+ // (The trace's parts a profile timed this frame: a bit a stage of KERNEL_STAGES.)+ let mut staged = 0u32;for k in 0..spp.max(1) {let mut p = self.sc.base;p.motion[1] = reconstruction.raw_signal() as u32 as f32;@@ -482,17 +502,19 @@ impl LiveCore {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);}+ // Profiled, the first sample's dispatches are a pass each, with a pair of stamps (KERNEL_STAGES).+ let stage = |i: usize| self.profile.as_ref().filter(|_| k == 0).map(|p| wgpu::ComputePassTimestampWrites { query_set: &p.kernel.0, beginning_of_pass_write_index: Some(i as u32 * 2), end_of_pass_write_index: Some(i as u32 * 2 + 1) });+ let split = self.profile.is_some() && k == 0;if gp.is_some() {{// (The trace's time begins here: its stamps' first, the paths' pass below writing the second.)let tw = match (&self.profile, &self.timer, timed) {- (Some(p), _, _) => Some(wgpu::ComputePassTimestampWrites { query_set: &p.queries, beginning_of_pass_write_index: Some(0), end_of_pass_write_index: None }),+ (Some(_), _, _) => stage(0),(None, Some(t), Some(slot)) => Some(wgpu::ComputePassTimestampWrites { query_set: &t.queries, beginning_of_pass_write_index: Some(slot as u32 * TIMER_QUERIES), end_of_pass_write_index: None }),_ => None,};- let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("live guides"), timestamp_writes: tw });- pass.set_bind_group(0, &self.sc.up.bg, &[]);- pass.set_bind_group(1, &self.kernel_bg, &[]);+ staged |= split as u32;+ let mut pass = kernel_compute_pass(&mut e, "live guides", tw, &self.sc.up.bg, &self.kernel_bg);pass.set_pipeline(&out_guides);pass.dispatch_workgroups(w.div_ceil(8), h.div_ceil(8), 1);}@@ -503,29 +525,44 @@ impl LiveCore {{let begin = |i: u32| (!decoupled).then_some(i);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: begin(0), end_of_pass_write_index: Some(1) }),+ (Some(_), _, _) => stage(1),(None, Some(t), Some(slot)) if k == 0 => Some(wgpu::ComputePassTimestampWrites { query_set: &t.queries, beginning_of_pass_write_index: begin(slot as u32 * TIMER_QUERIES), end_of_pass_write_index: Some(slot as u32 * TIMER_QUERIES + 1) }),_ => None,};if let Some((_, d)) = &finish {e.clear_buffer(&d.buffer, d.offset, Some(4));}- let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("live trace"), timestamp_writes: tw });- pass.set_bind_group(0, &self.sc.up.bg, &[]);- pass.set_bind_group(1, &self.kernel_bg, &[]);+ let (scene, targets) = (&self.sc.up.bg, &self.kernel_bg);+ let mut pass = kernel_compute_pass(&mut e, "live trace", tw, scene, targets);// (The frame's samples share its camera hits.)if k == 0 {+ staged |= (split as u32) << 1;pass.set_pipeline(&first);pass.dispatch_workgroups(iw.div_ceil(8), ih.div_ceil(8), 1);}+ if split {+ drop(pass);+ staged |= 1 << 2;+ pass = kernel_compute_pass(&mut e, "paths", stage(2), scene, targets);+ }pass.set_pipeline(&pipeline);pass.dispatch_workgroups(iw.div_ceil(8), ih.div_ceil(8), 1);// (Rows over every traced pixel: the invocations past the records' count leave at once.)if let Some((f, _)) = &finish {+ if split {+ drop(pass);+ staged |= 1 << 3;+ pass = kernel_compute_pass(&mut e, "finish", stage(3), scene, targets);+ }pass.set_pipeline(f);pass.dispatch_workgroups(gpu::DEFERRED_ROW / 64, (iw * ih).div_ceil(gpu::DEFERRED_ROW), 1);}if apart {+ if split {+ drop(pass);+ staged |= 1 << 4;+ pass = kernel_compute_pass(&mut e, "direct", stage(4), scene, targets);+ }pass.set_pipeline(&direct);pass.dispatch_workgroups(iw.div_ceil(8), ih.div_ceil(8), 1);}@@ -535,9 +572,11 @@ impl LiveCore {let last = k + 1 == spp.max(1);if let (Some(p), true, true) = (&self.profile, last, media_composite.is_some()) {drop(pass);- pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("media"), timestamp_writes: Some(wgpu::ComputePassTimestampWrites { query_set: &p.grid.0, beginning_of_pass_write_index: Some(4), end_of_pass_write_index: Some(5) }) });- pass.set_bind_group(0, &self.sc.up.bg, &[]);- pass.set_bind_group(1, &self.kernel_bg, &[]);+ pass = kernel_compute_pass(&mut e, "media", Some(wgpu::ComputePassTimestampWrites { query_set: &p.grid.0, beginning_of_pass_write_index: Some(4), end_of_pass_write_index: Some(5) }), scene, targets);+ } else if split && ((guides.is_some() && last) || media_train.is_some()) {+ drop(pass);+ staged |= 1 << 5;+ pass = kernel_compute_pass(&mut e, "trace rest", stage(5), scene, targets);}if let (Some(guides), true) = (&guides, last) {pass.set_pipeline(guides);@@ -686,6 +725,8 @@ impl LiveCore {let n = self.passes.pipes.len() as u32 + 2 + self.profile_extra();e.resolve_query_set(&p.queries, 0..n * 2, &p.resolve, 0);e.copy_buffer_to_buffer(&p.resolve, 0, &p.read, 0, p.read.size());+ e.resolve_query_set(&p.kernel.0, 0..KERNEL_STAGES.len() as u32 * 2, &p.kernel.1, 0);+ e.copy_buffer_to_buffer(&p.kernel.1, 0, &p.kernel.2, 0, p.kernel.2.size());} else {// A pass is timed by a pair of stamps of its own: with a provider, the passes before it (the second pair)// and those after it (the fifth).@@ -763,9 +804,21 @@ impl LiveCore {// The particle, BLAS, translucency and volume training slots (the last four) are written only when the scene// has particles / translucent ones.let n = self.passes.pipes.len() + 2 + extra;- for (k, s) in p.sums.iter_mut().enumerate().take(n) {+ for (k, s) in p.sums.iter_mut().enumerate().take(n).skip(1) {*s += t[k * 2 + 1].saturating_sub(t[k * 2]) as f64 * period;}+ // The trace: its stages' own times, and from the first one's begin to the last one's end.+ p.kernel.2.slice(..).map_async(wgpu::MapMode::Read, |_| {});+ let _ = g.device.poll(wgpu::PollType::wait_indefinitely());+ let t: Vec<u64> = bytemuck::cast_slice::<u8, u64>(&p.kernel.2.slice(..).get_mapped_range().unwrap()).to_vec();+ p.kernel.2.unmap();+ let ran = (0..KERNEL_STAGES.len()).filter(|k| staged >> k & 1 != 0);+ for k in ran.clone() {+ p.kernel_sums[k] += t[k * 2 + 1].saturating_sub(t[k * 2]) as f64 * period;+ }+ if let (Some(begin), Some(end)) = (ran.clone().map(|k| t[k * 2]).min(), ran.map(|k| t[k * 2 + 1]).max()) {+ p.sums[0] += end.saturating_sub(begin) as f64 * period;+ }let (sim, media) = (gpu::Gpu::has_grid_sim(&self.sc.up), media_composite.is_some());if sim || media {p.grid.2.slice(..).map_async(wgpu::MapMode::Read, |_| {});@@ -783,6 +836,9 @@ impl LiveCore {if p.frames == 120 {let names: Vec<&str> = std::iter::once("trace").chain(self.passes.pipes.iter().map(|(n, ..)| *n)).chain(["cache", "particles", "blas", "translucent", "vtrain"]).collect();let mut rows: Vec<String> = names.iter().zip(&p.sums).map(|(n, s)| format!("{n} {:.2}", s / p.frames as f64)).collect();+ // (The trace's parts after it; they are within its time, not beside it.)+ rows.splice(1..1, KERNEL_STAGES.iter().zip(&p.kernel_sums).map(|(n, s)| format!("trace.{n} {:.2}", s / p.frames as f64)));+ p.kernel_sums = [0.0; KERNEL_STAGES.len()];rows.push(format!("gridsim {:.2}", p.grid_sum / p.frames as f64));rows.push(format!("media {:.2}", p.media_sum / p.frames as f64));rows.retain(|r| !r.ends_with(" 0.00"));diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rsindex f363f6a..445bc6d 100644--- a/renderer/src/live/mod.rs+++ b/renderer/src/live/mod.rs@@ -575,6 +575,15 @@ impl LiveCore {),grid_sum: 0.0,media_sum: 0.0,+ kernel: {+ let n = frame::KERNEL_STAGES.len() as u64 * 2;+ (+ g.device.create_query_set(&wgpu::QuerySetDescriptor { label: Some("profile kernel"), ty: wgpu::QueryType::Timestamp, count: n as u32 }),+ g.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: n * 8, usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }),+ g.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: n * 8, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }),+ )+ },+ kernel_sums: [0.0; frame::KERNEL_STAGES.len()],}});let timer = (g.timestamps && profile.is_none()).then(|| FrameTimer::new(&g.device));diff --git a/tests/render/cutout-deep-live-exact.ts b/tests/render/cutout-deep-live-exact.tsnew file mode 100644index 0000000..8d27ac9--- /dev/null+++ b/tests/render/cutout-deep-live-exact.ts@@ -0,0 +1,7 @@+// cutout/deep in the real-time renderer without `APPROX.cutoutDeep`: the ten cards are passed, as offline.+import def, { test as base } from "./cutout-deep.ts";+import { APPROX, type TestMeta } from "./lib.ts";++export const test: TestMeta = { ...base, id: "cutout/deep-live-exact", temporal: true, live: 120, approx: APPROX.all & ~APPROX.cutoutDeep };++export default def;diff --git a/tests/render/cutout-deep-live.ts b/tests/render/cutout-deep-live.tsnew file mode 100644index 0000000..1a8117c--- /dev/null+++ b/tests/render/cutout-deep-live.ts@@ -0,0 +1,9 @@+// cutout/deep in the real-time renderer as it ships: of the cutouts a ray that sees meets the eighth stands+// whole (`APPROX.cutoutDeep`), so behind ten cards the floor's glow is not seen: the eighth card, black, which no+// light reaches from above.+import def, { test as base } from "./cutout-deep.ts";+import type { TestMeta } from "./lib.ts";++export const test: TestMeta = { ...base, id: "cutout/deep-live", metric: { ...base.metric, expected: 0 }, temporal: true, live: 120 };++export default def;diff --git a/tests/render/cutout-deep.ts b/tests/render/cutout-deep.tsnew file mode 100644index 0000000..1bb40f3--- /dev/null+++ b/tests/render/cutout-deep.ts@@ -0,0 +1,27 @@+// What is seen through many alpha-tested cards: a glowing floor behind ten cards that are cut out everywhere reads as+// it does beside them. A ray that sees asks every card's alpha on its way (hardware traversal: a ray query for each,+// sixteen at most). The cards are black: one taken for solid shows nothing of the light around it.+import { camera, result, sceneWithSky, type TestMeta } from "./lib.ts";+import { Color, DataTexture, Mesh, MeshStandardMaterial, PlaneGeometry } from "@threert/scene";++export const test: TestMeta = {+ id: "cutout/deep", features: ["alpha-test", "emissive"], reference: "analytic", temporal: false,+ metric: { kind: "ratio", a: [0.2, 0.45, 0.3, 0.55], b: [0.7, 0.45, 0.8, 0.55], expected: 1, tolerance: 0.02 },+ note: "ten cards 4 x 4 m over the left of the view, 0.1 m apart; the floor glows at 10 nits",+};++export default function () {+ const scene = sceneWithSky(0);+ const floor = new Mesh(new PlaneGeometry(400, 400), new MeshStandardMaterial({ name: "floor", color: new Color(0, 0, 0), emissive: new Color(1, 1, 1), emissiveIntensity: 10, roughness: 1 }));+ floor.name = "floor";+ floor.rotation.x = -Math.PI / 2;+ const clear = new DataTexture(2, 2, new Uint8Array([255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0, 255, 255, 255, 0]));+ const cards = Array.from({ length: 10 }, (_, k) => {+ const card = new Mesh(new PlaneGeometry(4, 4), new MeshStandardMaterial({ name: "card", color: 0x000000, map: clear, alphaTest: 0.5, roughness: 1, side: "double" }));+ card.name = `card${k}`;+ card.rotation.x = -Math.PI / 2;+ card.position.set(-2.5, 0.1 * (k + 1), 0);+ return card;+ });+ return result(scene, camera(scene, [0, 6, 3], [0, 0, 0]), [floor, ...cards]);+}diff --git a/tests/render/lib.ts b/tests/render/lib.tsindex 6a55b01..b9b0e42 100644--- a/tests/render/lib.ts+++ b/tests/render/lib.ts@@ -46,7 +46,8 @@ export const APPROX = {cutoutPaths: 4,cutoutEmitters: 8,farEmitters: 16,- all: 31,+ cutoutDeep: 32,+ all: 63,};export const SIZE = { width: 160, height: 90 };