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.

A camera hit's resampled lights have a pass of their own (#297)

YX844381b8c6a2
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 064b27e..11c1f73 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -1791,7 +1791,8 @@ pipeline. The real-time pipeline moves toward Lumen's structure — split signal
- It also covers the rest of the way to 16.7 ms on the district, about 2.7 ms. Geometry LOD does not change
the GPU time: 19.23 ms with the outer blocks gone entirely vs 19.38 with only their light sources gone.
5. Streaming (§ 5 item 5): first frame ≤ 3 s, no frame over 50 ms. The first frame is met without it (§ 5).
- - Tried 2026-11-07, not merged.
+ - Tried 2026-11-07, not merged. (The split was taken up again on 2026-11-30 for the resampled lights alone:
+ § 1a, "The samples' noise that is left is direct light".)
- The split itself (branch `direct-pass`):
- What it does: the trace leaves each camera hit's surface in a buffer and skips direct_light there; a pass of
its own (`direct`) lights it with the same estimators.
@@ -2357,6 +2358,47 @@ over larger regions would find a change that is slow and everywhere (that aftern
history only contains. Test: `a_noisy_picture_holds_from_frame_to_frame` (thirty-six lamps a centimetre wide before a
wall, the camera drifting: the 4 × 4 means change 1.45 steps a frame before, 1.10 now). Not checked on Vulkan.
+**The samples' noise that is left is direct light; a camera hit's resampled lights in a pass of their own
+(2026-11-30).** What the two night clips' change still holds was located by switches that take one part of a path
+sixteen times over and leave the rest (in a clone, none of them merged; the measure and the conditions above; one
+keyframe pair, which another random sequence alone moves by about 5 %):
+
+| | as it is | the camera hit's direct light (its sampled lights, the emitters its BSDF ray finds) | the sampled lights of the vertices past it | whole paths | the scene |
+|---|---|---|---|---|---|
+| the street with its crowd | 1.02 | 0.66 | 0.99 | 0.62 | 0.54 |
+| the hall | 0.85 | 0.89 | 0.68 | 0.64 | 0.52 |
+| the still room | 0.033 | 0.033 | 0.022 | 0.029 | |
+
+It is direct light in both: the street's at the camera hit, the hall's at the vertices after it (what a reflection
+shows, the radiance cache's points). Light of more bounces is a few percent of either. Two ways of asking that do
+not answer, tried first: the denoised signals taken apart before the upscaler (under sixteen paths a pixel their
+own change falls 5 to 13 %, the picture's 25 to 39 %: before the upscaler the change is mostly the jitter's), and
+tracing at full resolution for the camera ray's share (the filters are then narrower in the picture: the hall and
+the room read more).
+
+- **Not merged: more of the light tree's candidates at the vertices past the camera hit**, which take one draw
+ where a camera hit resamples 8. With 4 / 8 / 16 there and the one shadow ray the hall reads 0.76 / 0.69 / 0.67,
+ all that sixteen shadow rays gave, and its ΔE goes 3.24 → 3.00. But with 8 a city into the night, a room of neon
+ tubes and a colour lab pay 6.3 / 6.2 / 4.4 % of a frame for pictures that do not change: a candidate is a descent
+ of the tree, a triangle read and a BSDF. At the cache's points alone the hall reads 0.74 for 2.2 to 2.5 % of
+ those frames; at a reflection's hit alone 0.80 for 2.3 to 4.5 %. More candidates there have to cost less than a
+ descent each.
+- **The camera hit's resampled lights in a pass of their own** (`direct`; docs/RUNTIME.md "The live architecture"):
+ the emitters and the local lights past those summed exactly, lit after the paths at the surface they leave, by
+ the same estimators. The pictures as before on twelve clips; a frame's GPU time: a night street with its crowd
+ −14.3 %, a city into the night −7.2 %, a hall of small emitters, a room of neon tubes, a colour lab and a gallery
+ −4.1 to −4.2 %, a jeweller's window −1.3 %, a still room of 768 lamps +1.4 %; four without such lights, or with
+ theirs off by day, 0.0 to +1.5 %. It is the split that was left on 2026-11-07 (§ 1 "Tried 2026-11-07, not
+ merged": a district +4 %), taken now only where a scene has something to resample: with every sampled light in it
+ a sunlit garden paid 8.8 %, a house by day 8.6 %, a softbox over glass 5.8 %. It is also where samples kept from
+ frame to frame and shared between pixels would run. Whether those earn their place is not measured: the sixteen-
+ times figures are ceilings, and the one experiment of the kind here (2026-11-06, removed 2026-11-13) gained
+ nothing by its measures, before the light tree. Unit suite 292, render suite 273; `bench-ghosting --quick
+ --check`, `bench-object-ghosting` and `bench-temporal --shot edit` as before. Test:
+ `a_camera_hits_lights_in_their_own_pass_are_the_paths` (a wall under thirty-six small lamps and fifteen point
+ lights: the pass's picture 0.02 steps of 255 from the paths' own, at the view's size and at half of it, under
+ both traversals). Not checked on Vulkan, nor in a browser.
+
**The live passes from one place (2026-11-14, after it).** A buffer and a pass more (the locks' carry, above) took
seven edits that had to agree: the declaration in live.wgsl, the bind group layout's entries, the pass list, the
buffers' 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.md
index 1e7b6b6..3fa7bac 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -1776,15 +1776,36 @@ particles are lit from the cache's voxels; past a camera hit's own decisions the
signal, unfiltered: as the surface's light it was divided by the surface's albedo and filtered with it), as the
aerial haze is; its attenuation and its sampled scattering from lights are still the path's.
-A live frame is two passes of the kernel. `first_hit` traces every pixel's camera ray, once a frame (one jitter,
-no lens: the frame's samples share it), and leaves the hit (`first_hits`, 32 bytes a traced pixel: distance,
-barycentrics, triangle, instance, part) and its motion vector, which needs no material. `main` starts each path
-from that record and evaluates the surface there once; the guides that need the material (albedo, normal,
+A live frame's paths are two passes of the kernel. `first_hit` traces every pixel's camera ray, once a frame (one
+jitter, no lens: the frame's samples share it), and leaves the hit (`first_hits`, 32 bytes a traced pixel:
+distance, barycentrics, triangle, instance, part) and its motion vector, which needs no material. `main` starts
+each path from that record and evaluates the surface there once; the guides that need the material (albedo, normal,
roughness) stay its to write. What needs this frame's depth and motion before the lighting has its place between
the two. Both layouts; an offline render is one pass. Measured before it was written, twelve heavy clips: the
split alone +0.4 % of a frame's GPU time, within the runs' spread (two of them +2 %, not explained); with the
first pass evaluating the surface too, for the guides, +5 %.
+The lights a camera hit resamples have a pass of their own after the paths, `direct`: the emitters, and the local
+lights past those a camera hit sums exactly (more than eight that cast shadows). `main` leaves the surface it
+evaluated there in the first pass's buffer, after the hits and the chains (`surf_store`, 64 bytes a traced pixel:
+its place, its colour and the path's weight as they are, its normals and its material's numbers in fewer bits), and
+takes the rest of the hit's direct light itself: the directional lights, the local lights summed exactly, the sky.
+The pass lights that surface with the same estimators and the sample's own numbers, and adds the diffuse and the
+specular part to the pixel's signals. The frame says when it runs (`Params::jitter.w`): in a scene that has such
+lights; and while none of them is on, the paths leave no surface and the pass returns at once. Both layouts, no
+buffer more. `THREERT_DIRECT_PASS=0`: the paths light the hit themselves (A/B).
+
+Measured on twelve clips against the build before, the two alternated (an M4, 960 × 540): the pictures as they were
+(ΔE against offline, the change from a frame to the next and the detail the same on each), and a frame's GPU time:
+a night street with its crowd −14.3 %, a city into the night −7.2 %, a hall of small emitters, a room of neon
+tubes, a colour lab and a gallery −4.1 to −4.2 %, a jeweller's window −1.3 %, a still room of 768 lamps +1.4 %;
+four without such lights, or with theirs off by day, 0.0 to +1.5 %. With many such lights a frame is shorter for
+the pass (why was not measured); what the split costs is the surface written and read and a dispatch, so it is
+taken only where there is something to resample. Every sampled light in the pass, tried first with the surface as 112
+bytes, cost a sunlit garden 8.8 % of its frame (no such light at all), a house by day 8.6 % (its lamps off) and a
+softbox over glass 5.8 % (one light, summed exactly, its shadow ray through the glass). The same split of all of a
+camera hit's direct light was tried and left on 2026-11-07, when it cost a district of signs 4 % (docs/ROADMAP.md).
+
A pixel on a mirror has the surface the mirror shows. Where the camera hit has a mirror's lobe alone (roughness
under 0.025, metalness 1, no glass, no coat), `first_hit` follows the reflection, through 8 mirrors at most and all
but one of a path's bounces (the surface shown is lit and has its bounce), and records the chain (`Chain`, 96 bytes more a traced pixel in a scene with a
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index a736e3d..6eff489 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -1276,6 +1276,15 @@ var<private> shadow_hole: bool = false;
// of a uniform sky on a Lambert surface, ln 17 / 16 = 18 %.
var<private> nee_alone: bool = false;
+// Which of a vertex's direct light `direct_light` takes: all of it; or, where a live frame's camera hit has the lights
+// it resamples (one of many chosen, then its shadow ray: the emitters, and the local lights past those summed
+// exactly, `local_lights`) in a pass of their own (`direct`), all but those (`main`: the directional lights, the
+// local lights summed exactly, the sky) or those alone (the pass).
+const DL_ALL: u32 = 0u;
+const DL_REST: u32 = 1u;
+const DL_SAMPLED: u32 = 2u;
+var<private> dl_part: u32 = 0u;
+
// `direct_light` without the sky: a surface seen in a reflection lights itself from the lights, the sky's light
// there is the radiance cache's.
var<private> lights_only: bool = false;
@@ -2168,7 +2177,8 @@ fn local_lights(s: Surface, lb: Lobes, v: vec3<f32>, o: vec3<f32>, x: vec3<f32>,
let end = select(ns, P.counts.x, n_sh <= RIS_EXACT || nl <= RIS_EXACT);
// In groups of LIGHT_GROUP (spatially sorted; a sphere holding all their light per group: lib.rs
// light_groups): a group x is outside of is skipped whole.
- var i = nd;
+ // (Not for the pass that takes the resampled lights alone: `dl_part`.)
+ var i = select(nd, end, dl_part == DL_SAMPLED);
loop {
if (i >= end) { break; }
let gs = light_group_at((i - nd) / LIGHT_GROUP);
@@ -2202,6 +2212,7 @@ fn local_lights(s: Surface, lb: Lobes, v: vec3<f32>, o: vec3<f32>, x: vec3<f32>,
first = ns;
count = n_sh;
}
+ if (dl_part == DL_REST) { return sum; }
// Target: unshadowed intensity x cosine (cheap; the full BSDF / phase is applied to the chosen light only).
let m_cand = select(3u, RIS_M, seen_directly());
// With the pixel's list (light tiles), `nt` candidates more come from it, one in each `step` of its lights, and
@@ -2446,7 +2457,7 @@ fn direct_light(s: Surface, lb: Lobes, v: vec3<f32>) -> vec3<f32> {
dl_spec = vec3<f32>(0.0);
let o = offset_origin(s.p, s.ng);
// Directional lights: uniformly sampled cone (soft shadows), MIS against BSDF sampling.
- for (var i = 0u; i < P.counts2.x; i++) {
+ for (var i = 0u; i < select(P.counts2.x, 0u, dl_part == DL_SAMPLED); i++) {
let li = light_at(i);
let cos_max = li.dir.w;
let to_light = -li.dir.xyz;
@@ -2506,6 +2517,7 @@ fn direct_light(s: Surface, lb: Lobes, v: vec3<f32>) -> vec3<f32> {
mis_n = ne;
var emitters = select(0u, P.counts.y, emitters_on());
@if(light_pick) if (!take_emit) { emitters = 0u; }
+ if (dl_part == DL_REST) { emitters = 0u; }
if (emitters > 0u) {
var es: ES;
// With the light tree its candidates are already near the point: P.ltree.y of them at camera hits, one elsewhere.
@@ -2524,8 +2536,8 @@ fn direct_light(s: Surface, lb: Lobes, v: vec3<f32>) -> vec3<f32> {
}
}
// Environment
- var env_on = env_sampled() && !lights_only;
- @if(light_pick) env_on = take_env && has_env && !lights_only;
+ var env_on = env_sampled() && !lights_only && dl_part != DL_SAMPLED;
+ @if(light_pick) env_on = take_env && has_env && !lights_only && dl_part != DL_SAMPLED;
if (env_on) {
// (`split_frac` is the sky sample's where its BSDF was not 0; where it was, e is 0.)
let e = env_light(s, lb, v, o);
@@ -3370,6 +3382,100 @@ fn chain_load(pix: u32, chain: u32) -> Chain {
// The longest chain (and all but one of a path's bounces at most: the surface it shows is lit and has its bounce).
const MIRROR_CHAIN: u32 = 8u;
+// The surface a live path's camera hit has (the one a mirror chain shows), as `main` evaluated it, with what a pass
+// after needs to light it without reading its material again: four vec4s a traced pixel after the hits and the
+// chains (gpu.rs `SURFACE_BYTES`; a scene with F_MIRROR has the chains' room before them).
+// - (place, shading normal) (base colour, geometric normal) (`thr`, the pixel's list of the light tiles and its
+// length) (roughness and metalness, specular and transmission, coat's roughness and coat, flags and the index of
+// refraction);
+// - `thr`: what reaches the camera of the light it reflects (a chain's weight, the fog's and the haze's
+// attenuation);
+// - the place, the colour and `thr` as they are; a normal as an octahedral pair of 12 bits a side; the material's
+// numbers in the bits a float's whole number keeps (24): a roughness 16, the index of refraction 16 over 1..5,
+// the others 8 or 12;
+// - not its emission, which no light sample asks for, nor the way to the viewer, which the pass has from the
+// pixel's camera ray (and a chain's turns: `SURF_CHAIN`, `SURF_ODD`).
+// `lit`: `main` reached the hit's lighting this frame (not a pixel of sky, an emitter's card, a path without a bounce).
+struct Lit { s: Surface, thr: vec3<f32>, list: u32, list_n: u32, chain: bool, odd: bool, lit: bool };
+const SURF_VECS: u32 = 4u;
+const SURF_LIT: u32 = 1u;
+const SURF_FRONT: u32 = 2u;
+const SURF_ANIM: u32 = 4u;
+const SURF_CHAIN: u32 = 8u;
+const SURF_ODD: u32 = 16u;
+fn surf_at(pix: u32) -> u32 { return (2u + select(0u, CHAIN_VECS, has(F_MIRROR))) * P.size.x * P.size.y + pix * SURF_VECS; }
+// (Where the frame says it runs the pass, `P.jitter.w`, and there are such lights now: emitters that are on, more
+// shadow-casting local lights than a camera hit sums exactly. Else the paths leave no surface and the pass has
+// nothing to do: a sunlit garden paid 9 % of its frame for both, a softbox over glass 4 % for a light it sums
+// exactly, a house by day 3 % for lamps that are off. The buffer's length alone does not say that the pass runs: a
+// view traced at half its size has the room whatever was asked for.)
+fn surf_room() -> bool {
+ if (!LIVE || P.jitter.w < 0.5 || !(emitters_on() || min(P.counts.x - P.counts2.x, P.counts.x - P.counts2.w) > RIS_EXACT)) { return false; }
+ return first_len() >= (2u + select(0u, CHAIN_VECS, has(F_MIRROR)) + SURF_VECS) * P.size.x * P.size.y;
+}
+// Two numbers of 0..1 as one whole number a float keeps: `bits` of the 24 for the second.
+fn pair_pack(a: f32, b: f32, bits: u32) -> f32 {
+ let nb = f32(1u << bits);
+ return round(saturate(a) * (f32(1u << (24u - bits)) - 1.0)) * nb + round(saturate(b) * (nb - 1.0));
+}
+fn pair_unpack(v: f32, bits: u32) -> vec2<f32> {
+ let nb = f32(1u << bits);
+ let hi = floor(v / nb);
+ return vec2<f32>(hi / (f32(1u << (24u - bits)) - 1.0), (v - hi * nb) / (nb - 1.0));
+}
+fn dir_pack(n: vec3<f32>) -> f32 {
+ let p = n.xy / (abs(n.x) + abs(n.y) + abs(n.z));
+ let q = select(p, (1.0 - abs(p.yx)) * select(vec2<f32>(-1.0), vec2<f32>(1.0), p >= vec2<f32>(0.0)), n.z < 0.0);
+ return pair_pack(q.x * 0.5 + 0.5, q.y * 0.5 + 0.5, 12u);
+}
+fn dir_unpack(v: f32) -> vec3<f32> {
+ let q = pair_unpack(v, 12u) * 2.0 - 1.0;
+ let z = 1.0 - abs(q.x) - abs(q.y);
+ let t = max(-z, 0.0);
+ return normalize(vec3<f32>(q - select(vec2<f32>(-t), vec2<f32>(t), q >= vec2<f32>(0.0)), z));
+}
+fn surf_none(pix: u32) { first_vec_store(surf_at(pix) + 3u, vec4<f32>(0.0)); }
+fn surf_store(pix: u32, s: Surface, thr: vec3<f32>, chain: u32) {
+ let at = surf_at(pix);
+ first_vec_store(at, vec4<f32>(s.p, dir_pack(s.n)));
+ first_vec_store(at + 1u, vec4<f32>(s.base, dir_pack(s.ng)));
+ // (The list's first entry is a multiple of LT_LIST, its length under it: one number, as `finish`'s record has it.)
+ first_vec_store(at + 2u, vec4<f32>(thr, f32(lt_list + lt_list_n)));
+ let fl = SURF_LIT | select(0u, SURF_FRONT, s.front) | select(0u, SURF_ANIM, s.anim) | select(0u, SURF_CHAIN, chain > 0u) | select(0u, SURF_ODD, (chain & 1u) == 1u);
+ first_vec_store(at + 3u, vec4<f32>(pair_pack(s.roughness, s.metallic, 8u), pair_pack(s.specular, s.transmission, 12u), pair_pack(s.coat_rough, s.coat, 8u),
+ f32(fl) * 65536.0 + round(saturate((s.ior - 1.0) * 0.25) * 65535.0)));
+}
+fn surf_load(pix: u32) -> Lit {
+ let at = surf_at(pix);
+ let d = first_vec_load(at + 3u);
+ let fl = u32(d.w / 65536.0);
+ var s: Surface;
+ if ((fl & SURF_LIT) == 0u) { return Lit(s, vec3<f32>(0.0), 0u, 0u, false, false, false); }
+ let a = first_vec_load(at);
+ let b = first_vec_load(at + 1u);
+ let c = first_vec_load(at + 2u);
+ let rm = pair_unpack(d.x, 8u);
+ let st = pair_unpack(d.y, 12u);
+ let cc = pair_unpack(d.z, 8u);
+ s.p = a.xyz;
+ s.n = dir_unpack(a.w);
+ s.base = b.xyz;
+ s.ng = dir_unpack(b.w);
+ s.roughness = rm.x;
+ s.metallic = rm.y;
+ s.specular = st.x;
+ s.transmission = st.y;
+ s.coat_rough = cc.x;
+ s.coat = cc.y;
+ s.ior = 1.0 + 4.0 * (d.w - f32(fl) * 65536.0) / 65535.0;
+ s.emissive = vec3<f32>(0.0);
+ s.front = (fl & SURF_FRONT) != 0u;
+ s.card = false;
+ s.anim = (fl & SURF_ANIM) != 0u;
+ let list = u32(c.w);
+ return Lit(s, c.xyz, list & ~(LT_LIST - 1u), list & (LT_LIST - 1u), (fl & SURF_CHAIN) != 0u, (fl & SURF_ODD) != 0u, true);
+}
+
// The loop guard (gpu.rs `loop_guard_of`; docs/RUNTIME.md "The engine in a browser"): every loop of the kernel, the
// scene's functions' too, begins with `if (loop_guard()) { break; }` (gpu.rs `guard_loops`, a pass over the variant's
// syntax tree). The kernel's traversals follow indices they read from buffers and end only on sound data; with the
@@ -3743,6 +3849,44 @@ fn finish(@builtin(global_invocation_id) gid: vec3<u32>) {
accum[pix] = px;
}
+// Live, after each sample's paths: the lights a camera hit resamples (the emitters, the local lights past those
+// summed exactly; `DL_SAMPLED`), at the surface `main` left (`surf_store`), added to the pixel's signals as `main`'s
+// epilogue splits them. The sample's own numbers at the camera hit: what `main` drew there. Both layouts.
+@compute @workgroup_size(8, 8, 1)
+fn direct(@builtin(global_invocation_id) gid: vec3<u32>) {
+ let w = P.size.x;
+ let h = P.size.y;
+ if (gid.x >= w || gid.y >= h || !surf_room()) { return; }
+ let pix = gid.y * w + gid.x;
+ let at = surf_load(pix);
+ if (!at.lit) { return; }
+ rng_start(gid.xy, P.size.z, P.size.w, 0u);
+ cur_depth = 0u;
+ mirror_path = false;
+ rays_off = LIVE && P.jitter.z > 0.5;
+ lt_list = at.list;
+ lt_list_n = at.list_n;
+ if (has(F_LISTS)) { lt_fb = LT_NONE; }
+ // The way to the viewer, as `main` had it: against the pixel's camera ray, turned back through a mirror chain.
+ var v = -camera_ray(gid.xy, vec4<f32>(0.0)).d;
+ if (at.chain) {
+ let x = first_vec_load(chain_at(pix) + 3u).xyz;
+ let y = first_vec_load(chain_at(pix) + 4u).xyz;
+ v = transpose(mat3x3<f32>(x, y, cross(x, y) * select(1.0, -1.0, at.odd))) * v;
+ }
+ dl_part = DL_SAMPLED;
+ let c = at.thr * direct_light(at.s, lobes(at.s, max(dot(at.s.n, v), 1e-4)), v);
+ let cs = at.thr * dl_spec;
+ // The light tiles' report, beside the deterministic light `main` wrote there.
+ if (has(F_LISTS) && P.misc.w < 0.5 && direct_len() >= w * h) { direct_store(pix, vec4<f32>(direct_load(pix).rgb, f32(lt_fb))); }
+ // (The two signals alone are read and written, not the pixel's whole record, and neither where no light was found.)
+ if (non_finite(c) || non_finite(cs) || all(c == vec3<f32>(0.0))) { return; }
+ let diffuse = accum[pix].color;
+ accum[pix].color = vec4<f32>(diffuse.rgb + max(c - cs, vec3<f32>(0.0)), diffuse.w);
+ let specular = accum[pix].spec;
+ accum[pix].spec = vec4<f32>(specular.rgb + cs, specular.w);
+}
+
// Deterministic reconstruction guides at smooth reflectors. Using the random BSDF sample makes
// glass alternate between two different materials and leaves a hole wherever a diffuse lobe was drawn.
struct GuideHit { albedo: vec3<f32>, normal: vec3<f32>, rough: f32, distance: f32 };
@@ -4112,6 +4256,10 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
// turned to sky must not keep what a surface left there.
if (LIVE && P.misc.w < 0.5 && direct_len() >= w * h) { direct_store(pix, vec4<f32>(0.0, 0.0, 0.0, select(0.0, f32(LT_NONE), has(F_LISTS)))); }
if (has(F_LISTS)) { lt_fb = LT_NONE; }
+ // A live frame's camera hit has the lights it resamples in a pass of their own (`direct`), which lights the
+ // surface left for it below (`surf_store`): none, unless the path reaches the hit's lighting.
+ let apart = surf_room();
+ if (apart && P.misc.w < 0.5) { surf_none(pix); }
rng_start(gid.xy, P.size.z, P.size.w, 0u);
cur_depth = 0u;
let cr = camera_ray(gid.xy, rng4(rng_dim(D_CAMERA)));
@@ -4395,7 +4543,12 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let v = -d;
let nov = max(dot(s.n, v), 1e-4);
let lb = lobes(s, nov);
+ if (apart && depth == 0u) {
+ dl_part = DL_REST;
+ if (P.misc.w < 0.5) { surf_store(pix, s, thr, chain); }
+ }
var dl = thr * direct_light(s, lb, v);
+ dl_part = DL_ALL;
if (depth > 0u && !straight) {
let lum = luminance(dl);
if (lum > clamp_v) { dl *= clamp_v / lum; }
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index 93e8898..c7cee56 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -142,7 +142,7 @@ pub struct Params {
pub fog_color: [f32; 4], // ambient inscattering radiance rgb, max opacity
pub vol: [f32; 4], // volumetric scattering albedo (0 = off), phase anisotropy, extinction scale in range, -
pub vol2: [f32; 4], // volumetric albedo tint rgb, range (m, 0 = unlimited)
- pub jitter: [f32; 4], // live: this frame's sub-pixel jitter x, y (every camera ray's); ray tracing off (1); -
+ pub jitter: [f32; 4], // live: this frame's sub-pixel jitter x, y (every camera ray's); ray tracing off (1); the lights a camera hit resamples in a pass of their own (1: `direct`)
pub cache: [f32; 4], // live radiance cache (1 = on), history cap in samples, history cap in frames, -
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).
@@ -1583,6 +1583,10 @@ impl CacheBuffers {
/// The kernel's group-1 buffers: the radiance cache, what the live passes read of a trace (live/targets.rs
/// `Targets`: the specular-lobe rays, the motion vectors, the directional lights' direct light) and the light tiles'
/// lists. In the merged layout they are the sections of one buffer (`heap::Live`).
+/// A camera hit's surface as the paths leave it for the passes that light it (pathtrace.wgsl `surf_store`, `SURF_VECS`
+/// vec4s): its place, its normals, its material's numbers, what reaches the camera of its light.
+pub const SURFACE_BYTES: u64 = 64;
+
pub struct KernelBufs {
pub cache: CacheBuffers,
pub refl: Buf,
@@ -1590,8 +1594,10 @@ pub struct KernelBufs {
pub direct: Buf,
pub lists: Buf,
/// A live frame's camera hits, 32 bytes a traced pixel (pathtrace.wgsl `first_store`), and in a scene with a
- /// mirror 96 more for a mirror chain (`Chain`): its first pass writes them, its paths start from them. Of the
- /// view's size at 32 bytes until a frame makes it for what it traces (`with_first`).
+ /// mirror 96 more for a mirror chain (`Chain`): its first pass writes them, its paths start from them. After
+ /// them the surface each path found there, `SURFACE_BYTES` a traced pixel (`surf_store`): the paths write it,
+ /// the pass that lights it reads it (`direct`). Of the view's size at 32 bytes until a frame makes it for what
+ /// it traces (`with_first`).
pub first: Buf,
/// The pixels a sample's trace leaves for `finish` (their count, then `DEFERRED_BYTES` each): the layout as
/// written only. Of one record until a live view makes it for its traced size (`deferred_buffer`).
@@ -4666,7 +4672,7 @@ mod tests {
let sun = v(hwrt, KernelSwitches { last_sun: true, ..Default::default() });
assert_eq!((sun.matches("radiance += dz;").count(), sun.matches("fn sun_light(").count(), sun.matches("sun_light(s, lobes(").count()), (1, 1, 1));
assert!(!plain.contains("sun_light"));
- assert_eq!(lit.matches("env_on = take_env && has_env && !lights_only;").count(), 1);
+ assert_eq!(lit.matches("env_on = take_env && has_env && !lights_only && dl_part != DL_SAMPLED;").count(), 1);
assert_eq!(lit.contains("let steps = 4u;"), hwrt);
assert_eq!(v(hwrt, KernelSwitches { cutout_lite: 2, ..Default::default() }) == plain, !hwrt);
}
diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rs
index 7183100..f6cad9a 100644
--- a/renderer/src/live/frame.rs
+++ b/renderer/src/live/frame.rs
@@ -158,7 +158,7 @@ impl LiveCore {
return;
}
// (What a frame asks: as the load makes them, and the guides and the translucency pass where it has them.)
- let mut passes: Vec<&'static str> = vec!["first_hit"];
+ let mut passes: Vec<&'static str> = vec!["first_hit", "direct"];
if !self.g.merged {
passes.push("finish");
}
@@ -328,6 +328,8 @@ impl LiveCore {
let finish = self.targets.kernel.deferred.as_ref().filter(|_| self.cache.is_some()).map(|d| (g.kernel_pass(kernel, "finish"), d));
// The frame's camera rays, before its paths (pathtrace.wgsl `first_hit`).
let first = g.kernel_pass(kernel, "first_hit");
+ // The lights a camera hit resamples, after a sample's paths (pathtrace.wgsl `direct`).
+ let direct = g.kernel_pass(kernel, "direct");
// This frame's sub-pixel jitter (Halton 2, 3), every camera ray's: 8 phases at
// full resolution, as many more as an output pixel has fewer traced ones (8 / scale^2: the upscaler needs each
// output pixel visited), in the 12 bits a side the samples carry it in.
@@ -362,7 +364,12 @@ impl LiveCore {
if let Some(u) = &self.sc.up.units {
(p.motion[2], p.motion[3]) = (f32::from_bits(u.layout.top_first), f32::from_bits(u.count));
}
- p.jitter = [jitter.0, jitter.1, if self.rays { 0.0 } else { 1.0 }, 0.0];
+ // The lights a camera hit resamples, in a pass of their own after the paths: where the scene has such
+ // lights (emitters; more shadow-casting local lights than a camera hit sums exactly: pathtrace.wgsl
+ // `local_lights`). The kernel's paths leave their surfaces for it when told so.
+ let (local, casting) = (p.counts[0] - p.counts2[0], p.counts[0] - p.counts2[3]);
+ let apart = self.direct_pass && (p.counts[1] > 0 || local.min(casting) as usize > gpu::RIS_EXACT);
+ p.jitter = [jitter.0, jitter.1, if self.rays { 0.0 } else { 1.0 }, apart as u32 as f32];
if moving {
p.motion[0] = 1.0;
}
@@ -458,6 +465,10 @@ impl LiveCore {
pass.set_pipeline(f);
pass.dispatch_workgroups(gpu::DEFERRED_ROW / 64, (iw * ih).div_ceil(gpu::DEFERRED_ROW), 1);
}
+ if apart {
+ pass.set_pipeline(&direct);
+ pass.dispatch_workgroups(iw.div_ceil(8), ih.div_ceil(8), 1);
+ }
// Participating media: their volume voxels trained after the trace (pathtrace.wgsl media_train), and
// camera rays through media once the frame's samples are traced (media_composite). In the trace's pass
// and timing; profiled, the frame's last sample's media passes are a pass of their own (`media`).
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index d38370c..a428ca3 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -5473,3 +5473,53 @@ fn a_noisy_picture_holds_from_frame_to_frame() {
assert!(lit > 10.0, "the lamps light the wall: the picture's mean is {lit:.1}");
assert!(change < 1.25, "the picture's 4 x 4 means change {change:.3} steps from a frame to the next");
}
+
+/// The lights a camera hit resamples, in a pass of their own after the paths (pathtrace.wgsl `direct`, from the
+/// surface the paths leave there), light it as the paths did themselves: a wall under thirty-six lamps a centimetre
+/// wide and fifteen point lights (twelve cast shadows, more than are summed exactly: resampled), the same picture
+/// either way, at the view's size and at half of it. The two take the same samples; the pass has the surface's
+/// normals and its material's numbers in fewer bits (0.02 steps of 255 here).
+#[test]
+fn a_camera_hits_lights_in_their_own_pass_are_the_paths() {
+ let presets = crate::default_presets_dir();
+ let shot = |apart: bool, scale: f32| -> Option<(Vec<u8>, u64, bool)> {
+ let mut w = world();
+ w.set_visible(20, false).unwrap();
+ w.set_material(6, serde_json::from_value(serde_json::json!({ "name": "spark", "color": [0.0, 0.0, 0.0], "opacity": 1, "metalness": 0, "roughness": 1, "emissive": [1, 0.8, 0.6], "emissiveIntensity": 4000.0, "doubleSided": true })).unwrap());
+ w.set_geometry(7, Geometry { positions: vec![-0.005, -0.005, 0.0, 0.005, -0.005, 0.0, 0.005, 0.005, 0.0, -0.005, 0.005, 0.0], normals: [0.0, 0.0, 1.0].repeat(4), uvs: vec![0.0; 8], indices: vec![0, 1, 2, 0, 2, 3], groups: vec![], colors: vec![] }).unwrap();
+ for i in 0..36u32 {
+ w.set_object(100 + i, format!("spark {i}"), None, Kind::Mesh { geometry: 7, material: 6, own_blas: false, materials: vec![] }, true, false).unwrap();
+ w.set_transform(100 + i, Vec3::new(-0.75 + 0.3 * (i % 6) as f32, -0.75 + 0.3 * (i / 6) as f32, 0.15), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ }
+ // (Twelve that cast shadows: resampled, the pass's. Three that cast none: summed exactly, the paths' still.)
+ for i in 0..15u32 {
+ let lamp = serde_json::from_value(serde_json::json!({ "type": "point", "color": [0.6, 0.8, 1.0], "castShadow": i < 12, "intensity": 40.0, "radius": 0.02, "range": 0.0 })).unwrap();
+ w.set_object(200 + i, format!("lamp {i}"), None, Kind::Light(lamp), true, false).unwrap();
+ w.set_transform(200 + i, Vec3::new(-0.8 + 0.5 * (i % 4) as f32, -0.6 + 0.6 * (i / 4) as f32, 0.6), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ }
+ let mut live = match gpu::Gpu::new().and_then(|g| LiveCore::new(g, &w, Path::new("."), &presets, 96, 54)) {
+ Ok(c) => c,
+ Err(e) => {
+ eprintln!("skipped: {e}");
+ return None;
+ }
+ };
+ live.direct_pass = apart;
+ live.set_scale(scale);
+ let p = picture(&mut live, 32);
+ let made = live.g.kernel_passes_made().contains(&"direct");
+ Some((p, live.targets.kernel.first.size, made))
+ };
+ // (At half the size too: the first pass's buffer, of the view's size at first, has the room there unasked.)
+ for scale in [1.0, 0.5] {
+ let Some((own, room, made)) = shot(true, scale) else { return };
+ let Some((paths, room_paths, _)) = shot(false, scale) else { return };
+ let Some((again, _, _)) = shot(true, scale) else { return };
+ let (lit, d, run) = (region_mean(&own, [0, 0, 96, 54]), apart(&own, &paths), apart(&own, &again));
+ eprintln!("OWN PASS at {scale}: the picture's mean {lit:.1}; {d:.3} steps from the paths' own, {run:.3} from another run of itself; the first pass's buffer {room} bytes for {room_paths}");
+ assert!(made, "the pass was made");
+ assert!(room >= room_paths, "the surfaces' room");
+ assert!(lit > 20.0, "the lamps light the wall: the picture's mean is {lit:.1}");
+ assert!(d < run + 0.1, "at {scale} the pass's picture is {d:.3} steps from the paths' own ({run:.3} between two runs of the pass)");
+ }
+}
diff --git a/renderer/src/live/load.rs b/renderer/src/live/load.rs
index 1ebe924..e1b11a8 100644
--- a/renderer/src/live/load.rs
+++ b/renderer/src/live/load.rs
@@ -163,6 +163,7 @@ pub(super) fn load_scene(g: &gpu::Gpu, world: &World, assets: &Path, presets: &P
let up = g.upload(&sc, &targets.accum, bytemuck::cast_slice(&prep.nodes), &prep.emitters, &prep.gpu_emitter_tris, &prep.emitter_runs, crate::ltree::nodes_of(tables.light_tree.as_ref()), &prep.env, &prep.env_cdf, &prep.energy, &mut timings)?;
let _ = g.pipeline(&up.kernel, true); // compile the scene's kernel variant now, not in the first frame
let _ = g.kernel_pass(&up.kernel, "first_hit");
+ let _ = g.kernel_pass(&up.kernel, "direct");
if !g.merged {
let _ = g.kernel_pass(&up.kernel, "finish");
}
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index 0ab32c2..7012558 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -308,6 +308,10 @@ pub struct LiveCore {
/// fallback for GPUs that trace too slowly (no hardware ray queries), and the "what tracing adds" comparison on
/// those that do: the same scene, materials, exposure and post either way.
rays: bool,
+ /// The lights a camera hit resamples (emitters, the local lights past those summed exactly) in a pass of their
+ /// own, after the paths (true; pathtrace.wgsl `direct`). THREERT_DIRECT_PASS=0, for A/B: the paths light the
+ /// hit themselves, as they do in a scene without such lights.
+ direct_pass: bool,
/// 0 lit, 1 base color, 2 world normal, 3 lit without denoiser, 4 raw sample, 5 history length, 6 diffuse,
/// 7 specular, 8 deterministic direct light (THREERT_VIEW_MODE at start: e.g. bench-temporal per signal).
pub view_mode: u32,
@@ -586,7 +590,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![], 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 };
+ 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, direct_pass: std::env::var("THREERT_DIRECT_PASS").map_or(true, |v| v != "0"), 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)
@@ -832,11 +836,12 @@ impl LiveCore {
(self.kernel_bg, self.tl_kernel_bg) = kernel_bind_groups(&self.g, &self.targets);
}
- /// Room for a frame's camera hits at `pixels` traced pixels: 32 bytes each, and 96 more for a mirror chain in a
+ /// Room for a frame's camera hits at `pixels` traced pixels: 32 bytes each, 96 more for a mirror chain in a
/// scene that has a mirror (`gpu::F_MIRROR`; pathtrace.wgsl `Chain`: without the room the first pass follows no
- /// mirror). The buffer follows the traced size, a quarter larger than asked, as `finish`'s records do.
+ /// mirror), and the surface the paths find there (`gpu::SURFACE_BYTES`: without the room the paths light it
+ /// themselves). The buffer follows the traced size, a quarter larger than asked, as `finish`'s records do.
pub(super) fn ensure_first(&mut self, pixels: u64) {
- let each = if self.sc.up.kernel.features & gpu::F_MIRROR != 0 { 128 } else { 32 };
+ let each = if self.sc.up.kernel.features & gpu::F_MIRROR != 0 { 128 } else { 32 } + if self.direct_pass { gpu::SURFACE_BYTES } else { 0 };
if self.targets.kernel.first.size >= pixels * each {
return;
}