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 pixel on a mirror has the surface the mirror shows (frame structure, step 2) (#281)

Yujia0d15274a5e26
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index a57b066..d9ae8e0 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -2920,6 +2920,12 @@ 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.
+**A pixel on a mirror has the surface the mirror shows (2026-11-25, after it).** The second step of the frame's
+structure: the first pass follows a camera hit that is a mirror to what it shows, and that surface has the pixel's
+guides, motion vector and signals (docs/RUNTIME.md "The live architecture"). A mirror's picture changes: what it
+shows is filtered, reprojected and upscaled as a surface seen directly, where it was the mirror's specular signal.
+Glass is as it was. Tests: `a_pixel_on_a_mirror_has_the_surface_the_mirror_shows`.
+
**A live frame's camera rays in a pass of their own (2026-11-25).** The first step of the frame's structure: the
kernel's `first_hit` traces the camera rays and leaves each pixel's hit and motion vector, and `main` starts its
paths from the hits (docs/RUNTIME.md "The live architecture"). The pictures are the same. It is there for what
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 9829f49..8750d74 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -1655,8 +1655,9 @@ The kernel's read-only scene data other than triangles is two storage buffers, e
vertices; and a browser's kernel had seven tables as the sized arrays of a struct, a second copy of each made
every frame, and was compiled again when a table doubled. The count of bindings is as it was: 22 buffers and
acceleration structures a stage natively, 28 of Metal's 29 with the translucency pass (29 with the loop guard's).
- (`finish`'s records are the kernel's 23rd and a frame's camera hits its 24th; the translucency pass, which
- reads neither, binds group 1 without them, and stays at 29.)
+ (`finish`'s records are the kernel's 23rd and a frame's camera hits its 24th. The translucency pass binds of
+ group 1 what it reads, the radiance cache, the light tiles' lists and the camera hits: 26 buffers, 27 with the
+ loop guard's.)
(Hardware traversal no longer binds software traversal's trees, a placeholder there; the light tiles' lists took
the binding.)
@@ -1779,6 +1780,29 @@ the two. Both layouts; an offline render is one pass. Measured before it was wri
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 %.
+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
+mirror): the hit the last mirror shows and where its ray starts, the chain's transform, the way to its last
+mirror, what the mirrors and the segments that end at one leave of the light (the mirrors' Fresnel reflectance;
+the fog's and the haze's attenuation, water's between mirrors) and the light they add (a mirror's own emission,
+the fog's and the haze's ambient light). `main` starts its path at the surface shown, in the camera hit's place:
+the guides (its distance the whole way along the camera ray; its normal and its motion vector as the pixel sees
+them, turned by the chain; its albedo times the chain's weight), the light seen directly, the signals' split, the
+path's end in the cache a bounce later; each mirror takes one of the path's bounces. So the filters, the
+reprojection and the upscaler take a mirror as a window onto what it shows. The camera's own hit stays in the
+record: the translucency pass and the media read its distance, since a mirror hides what is behind it.
+
+The material decides: one whose own roughness and metalness say a mirror (`mirror_possible`; a scene with such a
+material has the feature `F_MIRROR`, and another scene's kernel none of this code). Only there does the first pass
+read a surface's textures and function; a material that is a mirror by its texture or its function alone is not
+followed, nor is procedural geometry. A curved mirror's motion vectors are a flat one's, and a mirror's own
+motion is not in them. The segment the last
+mirror shows is `main`'s first: a mirror pixel's sampled fog scattering is that segment's, and the camera's own
+segment has the fog's attenuation and ambient light alone. `main` reads the chain's record where it reads the
+camera hit and again after its loop, for the guides: on twelve heavy clips with the feature forced on that is
+0.9 % of a frame, where the record held through the loop was 5 % and `main` walking the chain itself 3 %.
+
Where a path ends in the cache, `main` takes only what a warm voxel holds. The pixels with more to trace there (a
training path, a cold voxel's estimate, a reflection hit's lights) leave a record of 96 bytes, and a second pass
of the kernel, `finish`, traces them after each sample and adds their light to the pixel, one invocation a record.
@@ -1903,8 +1927,9 @@ to step through every method this platform has. The title bar shows the method t
that handle keyboard input keep their key bindings. `tools/denoise-demo/live.sh` opens Kaleido (a mirror hall lit
only by hundreds of glowing orbs) for this comparison; `tools/denoise-demo/record.ts` and `video.ts` record it.
-For smooth mirrors and glass, secondary ray queries put the reflected and transmitted surfaces in the joint
-denoiser's guides (pathtrace.wgsl `surface_guides`). Directly visible sky and emission-dominated pixels are the
+For smooth surfaces and glass, secondary ray queries put the reflected and transmitted surfaces in the joint
+denoiser's guides (pathtrace.wgsl `surface_guides`); a mirror's pixel already has the surface it shows ("The live
+architecture"). Directly visible sky and emission-dominated pixels are the
overlay, with the bypass mask 1 on them. Exposure, bloom, depth of field and motion blur process the reconstructed
HDR image on the GPU.
diff --git a/renderer/shaders/live.wgsl b/renderer/shaders/live.wgsl
index 7758dec..3396688 100644
--- a/renderer/shaders/live.wgsl
+++ b/renderer/shaders/live.wgsl
@@ -40,7 +40,7 @@ struct LiveParams {
// (`Pixel`, a sample of the trace: records.wgsl, a part of this module. normal.w: `medium_tr`, `medium_share`.)
@group(0) @binding(0) var<uniform> L: LiveParams;
-@group(0) @binding(1) var<storage, read> sample_px: array<Pixel>; // color.w = first-hit distance (0 = sky)
+@group(0) @binding(1) var<storage, read> sample_px: array<Pixel>; // color.w = distance to the surface shown (0 = sky): the camera hit's, or the whole way to what a mirror chain shows
// ---- The live passes' buffers, by what they hold and how long.
//
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index c2bd65a..12b4140 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -75,6 +75,7 @@ const F_TEX: u32 = 256u;
const F_FUNC: u32 = 512u;
const F_GLASS: u32 = 2048u;
const F_COAT: u32 = 4096u;
+const F_MIRROR: u32 = 8192u; // a material that can be a mirror alone (`mirror_possible`): the first pass follows it
const F_INST: u32 = 16384u;
const F_MEDIA: u32 = 32768u;
const F_PEMIT: u32 = 65536u; // opaque particles' emitters (one not shown has no area)
@@ -3300,16 +3301,61 @@ fn sphere_hit(x: vec3<f32>, l: vec3<f32>, hit: Hit) -> vec3<f32> {
}
// A camera hit as the first-hit pass leaves it: (t, u, v, triangle low) (triangle high, instance low, instance high,
-// part). The integers as 16-bit halves: a float keeps those exactly, and its bits are not an integer's to keep.
-fn first_store(pix: u32, h: Hit) {
- first_vec_store(pix * 2u, vec4<f32>(h.t, h.u, h.v, f32(h.tri & 0xffffu)));
- first_vec_store(pix * 2u + 1u, vec4<f32>(f32(h.tri >> 16u), f32(h.inst & 0xffffu), f32(h.inst >> 16u), f32(h.part)));
-}
-fn first_load(pix: u32) -> Hit {
+// part + 65536 x its mirror chain). The integers as 16-bit halves: a float keeps those exactly, and its bits are not
+// an integer's to keep. The chain: how many mirrors the pixel's ray goes on through (`mirror_alone`); what the last
+// one shows is the surface the pixel has for the passes after (`Chain`).
+struct FirstHit { hit: Hit, chain: u32 };
+fn hit_store(at: u32, h: Hit, chain: u32) {
+ first_vec_store(at, vec4<f32>(h.t, h.u, h.v, f32(h.tri & 0xffffu)));
+ first_vec_store(at + 1u, vec4<f32>(f32(h.tri >> 16u), f32(h.inst & 0xffffu), f32(h.inst >> 16u), f32(h.part | (chain << 16u))));
+}
+fn hit_load(at: u32) -> FirstHit {
+ let a = first_vec_load(at);
+ let b = first_vec_load(at + 1u);
+ let pc = u32(b.w);
+ return FirstHit(Hit(a.x, u32(a.w) | (u32(b.x) << 16u), a.y, a.z, u32(b.y) | (u32(b.z) << 16u), pc & 0xffffu), pc >> 16u);
+}
+fn first_store(pix: u32, h: Hit, chain: u32) { hit_store(pix * 2u, h, chain); }
+fn first_load(pix: u32) -> FirstHit { return hit_load(pix * 2u); }
+// The distance to the camera hit itself (0: none), whatever its ray went on to: what stands before a mirror is nearer
+// than this.
+fn first_depth(pix: u32) -> f32 {
let a = first_vec_load(pix * 2u);
let b = first_vec_load(pix * 2u + 1u);
- return Hit(a.x, u32(a.w) | (u32(b.x) << 16u), a.y, a.z, u32(b.y) | (u32(b.z) << 16u), u32(b.w));
-}
+ return select(a.x, 0.0, a.w == 65535.0 && b.x == 65535.0);
+}
+// A mirror chain as the first pass leaves it where there is one, six vec4s a traced pixel after the hits (a scene with
+// F_MIRROR has the room): what the paths start from in the camera hit's place.
+// - `seen`, `o`: the hit the last mirror shows and where its ray starts; the ray's direction is the camera ray's
+// turned back through `xf`;
+// - `xf`: what takes a direction at the surface shown to where the pixel sees it, each mirror's reflection in turn
+// from the camera's (orthonormal: two columns kept, the third their cross product, turned for an odd chain);
+// - `way`: the distance to the last mirror, along the camera ray and from mirror to mirror;
+// - `weight`, `light`: what the mirrors and the segments that end at one leave of the light (the mirrors' Fresnel
+// reflectance; the fog's and the haze's attenuation, water's between mirrors), and the light those add on the way
+// (the mirrors' own emission, the fog's and the haze's ambient light). The segment the last mirror shows is
+// `main`'s first: it has there what a camera's segment has.
+struct Chain { seen: Hit, o: vec3<f32>, way: f32, xf: mat3x3<f32>, weight: vec3<f32>, light: vec3<f32> };
+const CHAIN_VECS: u32 = 6u;
+fn chain_at(pix: u32) -> u32 { return 2u * P.size.x * P.size.y + pix * CHAIN_VECS; }
+fn chain_store(pix: u32, c: Chain) {
+ let at = chain_at(pix);
+ hit_store(at, c.seen, 0u);
+ first_vec_store(at + 2u, vec4<f32>(c.o, c.way));
+ first_vec_store(at + 3u, vec4<f32>(c.xf[0], c.weight.x));
+ first_vec_store(at + 4u, vec4<f32>(c.xf[1], c.weight.y));
+ first_vec_store(at + 5u, vec4<f32>(c.light, c.weight.z));
+}
+fn chain_load(pix: u32, chain: u32) -> Chain {
+ let at = chain_at(pix);
+ let a = first_vec_load(at + 2u);
+ let b = first_vec_load(at + 3u);
+ let c = first_vec_load(at + 4u);
+ let d = first_vec_load(at + 5u);
+ return Chain(hit_load(at).hit, a.xyz, a.w, mat3x3<f32>(b.xyz, c.xyz, cross(b.xyz, c.xyz) * select(1.0, -1.0, (chain & 1u) == 1u)), vec3<f32>(b.w, c.w, d.w), d.xyz);
+}
+// 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 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
@@ -3730,7 +3776,8 @@ fn guide_hit(origin: vec3<f32>, dir: vec3<f32>, footprint: f32, through_glass: b
// Rough surfaces have no single reflected point. A stochastic second-bounce hit would move
// their guide even when both the object and camera stand still.
accum[q].spec.w = 0.0;
- if (px.color.w > 0.0 && rough < MIRROR_ROUGHNESS && P.jitter.z == 0.0 &&
+ // (Not behind a mirror chain: there the pixel's guides are already the surface shown.)
+ if (px.color.w > 0.0 && rough < MIRROR_ROUGHNESS && P.jitter.z == 0.0 && (!has(F_MIRROR) || first_load(q).chain == 0u) &&
(any(specular.rgb > vec3<f32>(0.005)) || diffuse.w > 0.0)) {
cur_depth = 1u;
mirror_path = true;
@@ -3783,7 +3830,7 @@ fn media_train(@builtin(global_invocation_id) gid: vec3<u32>) {
let ndc = vec2<f32>((f32(px) + r4.z) / f32(w) * 2.0 - 1.0, 1.0 - (f32(py) + r4.w) / f32(h) * 2.0);
let d = normalize(P.cam_fwd.xyz + P.cam_right.xyz * (ndc.x * P.cam_pos.w * P.cam_fwd.w) + P.cam_up.xyz * (ndc.y * P.cam_pos.w));
let o = P.cam_pos.xyz;
- let fd = accum[py * w + px].color.w;
+ let fd = first_depth(py * w + px);
let tmax = select(1.0e30, fd, fd > 0.0);
// Homogeneous media (water) lie behind the glass the camera sees them through: their points are taken along the
// straight ray up to the first opaque surface (stopped at the glass, the voxels learned the water's top layer
@@ -3840,7 +3887,7 @@ fn media_composite(@builtin(global_invocation_id) gid: vec3<u32>) {
var px = accum[pix];
let ndc = vec2<f32>((f32(gid.x) + P.jitter.x) / f32(w) * 2.0 - 1.0, 1.0 - (f32(gid.y) + P.jitter.y) / f32(h) * 2.0);
let d = normalize(P.cam_fwd.xyz + P.cam_right.xyz * (ndc.x * P.cam_pos.w * P.cam_fwd.w) + P.cam_up.xyz * (ndc.y * P.cam_pos.w));
- let ft = px.color.w;
+ let ft = first_depth(pix);
let mm = media_march(P.cam_pos.xyz, d, select(1.0e30, ft, ft > 0.0), true, rng_dim(D_MEDIA));
if (mm.tr >= 1.0 && all(mm.light == vec3<f32>(0.0))) { return; }
let samples = P.misc.w + 1.0; // this dispatch runs with the frame's last sample's parameters
@@ -3885,6 +3932,17 @@ fn cache_resolve(@builtin(global_invocation_id) gid: vec3<u32>) {
// ------------------------------------------------------------------------------------------------
+// What a live frame's first pass follows: a surface with a mirror's lobe alone (no diffuse lobe, no glass, no coat).
+fn mirror_alone(s: Surface) -> bool {
+ return s.roughness < DELTA_ROUGHNESS && s.metallic >= 1.0 && s.transmission <= 0.0 && s.coat <= 0.0 && !s.card;
+}
+// Whether a material's own numbers leave that possible (gpu.rs `mirror_possible`, which makes F_MIRROR of it): read
+// before its textures and its function are, which the surfaces of other materials so never are for this. A material
+// that is a mirror by its texture or its function alone is not followed.
+fn mirror_possible(m: Material) -> bool {
+ return m.params.y < DELTA_ROUGHNESS && m.params.x >= 1.0 && m.layer.x <= 0.0;
+}
+
// The camera hit's motion: from the hit point `p` to where that surface point was the previous frame (w = 1), zeros
// where it stands still.
fn first_motion(hit: Hit, p: vec3<f32>) -> vec4<f32> {
@@ -3966,10 +4024,68 @@ fn first_hit(@builtin(global_invocation_id) gid: vec3<u32>) {
let pix = gid.y * w + gid.x;
let cr = camera_ray(gid.xy, rng4(rng_dim(D_CAMERA)));
let hit = trace(cr.o, cr.d, INF, TRACE_CLOSEST);
- first_store(pix, hit);
+ // Through mirrors to the surface the pixel shows, which `main` starts its path from (`Chain`). The material is
+ // read only where its record says it can be a mirror. Not with ray tracing off; not procedural geometry.
+ var seen = hit;
+ var so = cr.o;
+ var sd = cr.d;
+ var chain = 0u;
+ var way = 0.0;
+ var weight = vec3<f32>(1.0);
+ var light = vec3<f32>(0.0);
+ var cone_w = 0.0;
+ var cone_a = 2.0 * P.cam_pos.w / lod_height();
+ var xf = mat3x3<f32>(vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(0.0, 0.0, 1.0));
+ let longest = select(min(MIRROR_CHAIN, max(P.counts.z, 1u) - 1u), 0u, !has(F_MIRROR) || P.jitter.z > 0.5 || first_len() < (2u + CHAIN_VECS) * w * h);
+ for (var b = 0u; b < longest; b++) {
+ if (seen.tri == 0xffffffffu || is_proc(seen) || !has(F_INST) || seen.inst == NO_INST) { break; }
+ if (!mirror_possible(material_at(row_word(instance_at(seen.inst).info.w, seen.part, 0u) & ROW_MATERIAL))) { break; }
+ let width = cone_w + cone_a * seen.t;
+ let s = surface(so, sd, seen, width);
+ if (!mirror_alone(s)) { break; }
+ // The segment that ends at this mirror (the camera's own first): its fog and haze as `main` has a segment's,
+ // less the camera segment's sampled scattering; water between mirrors.
+ if (has(F_FOG) && P.fog.x > 0.0) {
+ // (The fog's start distance and its volumetric range are the camera's: along a chain, what is left of
+ // them after the way so far.)
+ let t0 = max(P.fog.w - way, 0.0);
+ var od = fog_depth(so, sd, t0, seen.t);
+ if (has(F_VOLUME) && P.vol.x > 0.0) {
+ let tv = select(seen.t, min(seen.t, max(P.vol2.w - way, 0.0)), P.vol2.w > 0.0);
+ od += fog_depth(so, sd, t0, max(tv, t0)) * (P.vol.z - 1.0);
+ }
+ let tr = max(exp(-od), 1.0 - P.fog_color.w);
+ light += weight * (1.0 - tr) * P.fog_color.rgb;
+ weight *= tr;
+ }
+ if (has(F_AERIAL)) {
+ let ta = aerial_tr(so, sd, seen.t);
+ light += weight * (1.0 - ta) * aerial_light(sd);
+ weight *= ta;
+ }
+ if (has(F_HMEDIA) && chain > 0u) { weight *= media_homogeneous(so, sd, seen.t, false, 0u).tr; }
+ way += seen.t;
+ chain += 1u;
+ cone_w = width;
+ cone_a += 2.0 * s.roughness * s.roughness;
+ // The mirror: its own light, then its Fresnel reflectance (a metal's: its colour at F0); I - 2 n n^T.
+ light += weight * s.emissive;
+ weight *= f_schlick(s.base, vec3<f32>(1.0), max(dot(s.n, -sd), 1e-4));
+ xf = xf * mat3x3<f32>(vec3<f32>(1.0, 0.0, 0.0) - 2.0 * s.n * s.n.x, vec3<f32>(0.0, 1.0, 0.0) - 2.0 * s.n * s.n.y, vec3<f32>(0.0, 0.0, 1.0) - 2.0 * s.n * s.n.z);
+ let l = reflect(sd, s.n);
+ so = offset_origin(s.p, select(s.ng, -s.ng, dot(l, s.ng) < 0.0));
+ sd = l;
+ seen = trace(so, sd, INF, TRACE_CLOSEST);
+ }
+ first_store(pix, hit, chain);
+ // The motion of the surface shown, as the pixel sees it: through the chain.
var mv = vec4<f32>(0.0);
// (The hit point as `surface` has it.)
- if (hit.tri != 0xffffffffu) { mv = first_motion(hit, cr.o + cr.d * hit.t); }
+ if (seen.tri != 0xffffffffu) { mv = first_motion(seen, so + sd * seen.t); }
+ if (chain > 0u) {
+ mv = vec4<f32>(xf * mv.xyz, mv.w);
+ chain_store(pix, Chain(seen, so, way, xf, weight, light));
+ }
if (motion_len() >= w * h) { motion_store(pix, select(vec4<f32>(0.0), mv, !non_finite(mv.xyz))); }
}
@@ -4039,23 +4155,50 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
var cone_a = 2.0 * P.cam_pos.w / lod_height();
mirror_path = false;
- for (var depth = 0u; depth <= P.counts.z; depth++) {
+ // A live frame's mirror chain (`first_hit` followed it, `Chain`): `chain`, its mirrors, each taking one of the
+ // path's bounces; `way`, the distance to its last one.
+ var chain = 0u;
+ var way = 0.0;
+ var last = P.counts.z;
+ for (var depth = 0u; depth <= last; depth++) {
cur_depth = depth;
- // A live frame's camera hit is its first pass's (`first_hit`).
var hit = Hit(INF, 0xffffffffu, 0.0, 0.0, NO_INST, 0u);
- if (LIVE && depth == 0u) { hit = first_load(pix); } else { hit = trace(o, d, INF, TRACE_CLOSEST); }
+ if (LIVE && depth == 0u) {
+ // A live frame's camera hit is its first pass's (`first_hit`). Where a mirror chain follows it, the path
+ // starts at the surface the chain shows, with what the chain left of the light and added to it: that
+ // surface has what a camera hit has below (the guides, the light seen directly, the signals' split).
+ let f = first_load(pix);
+ hit = f.hit;
+ if (has(F_MIRROR) && f.chain > 0u) {
+ let c = chain_load(pix, f.chain);
+ chain = f.chain;
+ way = c.way;
+ last -= chain;
+ radiance += c.light;
+ e0 += c.light;
+ thr *= c.weight;
+ cone_w = cone_a * way;
+ o = c.o;
+ d = transpose(c.xf) * d;
+ hit = c.seen;
+ }
+ } else {
+ hit = trace(o, d, INF, TRACE_CLOSEST);
+ }
// Ray tracing off: the camera ray above was the last one traced for this pixel.
if (depth == 0u) { rays_off = LIVE && P.jitter.z > 0.5; }
if (has(F_FOG) && P.fog.x > 0.0) {
// Height fog on every segment (attenuation + ambient inscattering); lit volumetric scattering on camera rays.
- let t0 = select(0.0, P.fog.w, depth == 0u);
+ // (The fog's start distance and its volumetric range are the camera's: behind a mirror chain, what is
+ // left of them after the way to its last mirror.)
+ let t0 = select(0.0, max(P.fog.w - way, 0.0), depth == 0u);
let t1 = select(hit.t, 2.0e4, hit.tri == 0xffffffffu);
// Inside the volumetric range (camera rays) the medium is denser by the extinction scale (UE).
var od = fog_depth(o, d, t0, t1);
var tv = t1;
var trv = 1.0;
if (has(F_VOLUME) && depth == 0u && P.vol.x > 0.0) {
- tv = select(t1, min(t1, P.vol2.w), P.vol2.w > 0.0);
+ tv = select(t1, min(t1, max(P.vol2.w - way, 0.0)), P.vol2.w > 0.0);
let odv = fog_depth(o, d, t0, max(tv, t0));
od += odv * (P.vol.z - 1.0);
trv = exp(-odv * P.vol.z);
@@ -4085,7 +4228,8 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
}
// Live media are composited after the trace (media_composite); past the camera ray, homogeneous ones (water)
// attenuate and light the path here. Offline paths track every medium.
- if (LIVE && has(F_HMEDIA) && depth > 0u) {
+ // (The segment a mirror chain's last mirror shows is one of those.)
+ if (LIVE && has(F_HMEDIA) && (depth > 0u || (has(F_MIRROR) && chain > 0u))) {
let mh = media_homogeneous(o, d, select(hit.t, 1.0e30, hit.tri == 0xffffffffu), true, rng_sub(rng_dim(D_MEDIA), 1u));
radiance += thr * mh.light;
thr *= mh.tr;
@@ -4108,7 +4252,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
if (lum > clamp_v) { c *= clamp_v / lum; }
}
radiance += c;
- if (depth == P.counts.z) { break; }
+ if (depth == last) { break; }
let nd = sample_hg(d, tk.g);
last_pdf = hg_phase(tk.g, dot(nd, d));
specular_bounce = false;
@@ -4143,10 +4287,12 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let width = cone_w + cone_a * hit.t;
let s = surface(o, d, hit, width);
if (depth == 0u) {
- first_t = hit.t;
+ // (Behind mirrors: where the pixel sees it, the whole way along the camera ray, its normal turned.)
+ first_t = way + hit.t;
if (has(F_LISTS)) {
// (Where the hit was the previous frame: the first pass's motion vector.)
var before = s.p;
+ if (has(F_MIRROR) && chain > 0u) { before = cr.o + cr.d * first_t; }
if (LIVE && motion_len() >= w * h) { before += motion_load(pix).xyz; }
lt_list_start(before);
}
@@ -4172,10 +4318,11 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
radiance += c;
}
if (s.card) { break; }
- @if(!last_direct && !last_sun) if (depth == P.counts.z) { break; }
- @if(last_sun && !last_direct) if (depth == P.counts.z) {
+ @if(!last_direct && !last_sun) if (depth == last) { break; }
+ @if(last_sun && !last_direct) if (depth == last) {
// gpu.rs `KernelSwitches::last_sun`: the last vertex's light from the directional lights alone.
- if (depth > 0u) {
+ // (Or what a mirror chain shows, the chain having taken the path's bounces.)
+ if (depth > 0u || chain > 0u) {
var dz = thr * sun_light(s, lobes(s, max(dot(s.n, -d), 1e-4)), -d);
let lum = luminance(dz);
if (lum > clamp_v && !straight) { dz *= clamp_v / lum; }
@@ -4183,9 +4330,10 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
}
break;
}
- @if(last_direct) if (depth == P.counts.z) {
+ @if(last_direct) if (depth == last) {
// gpu.rs `KernelSwitches::last_direct`: the last vertex's direct light.
- if (depth > 0u) {
+ // (Or what a mirror chain shows, the chain having taken the path's bounces.)
+ if (depth > 0u || chain > 0u) {
var dz = thr * direct_light(s, lobes(s, max(dot(s.n, -d), 1e-4)), -d);
let lum = luminance(dz);
if (lum > clamp_v && !straight) { dz *= clamp_v / lum; }
@@ -4310,6 +4458,19 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
d = l;
}
+ if (has(F_MIRROR) && chain > 0u) {
+ // Behind a mirror chain, what the surface shown left for the passes after is as the pixel sees it: its
+ // normal and its specular ray turned by the chain, its albedo under the chain's weight. (Read again here:
+ // nothing of the chain is kept through the loop but its length and its way.)
+ let c = chain_load(pix, chain);
+ albedo *= c.weight;
+ normal = c.xf * normal;
+ refl_l = c.xf * refl_l;
+ if (P.motion.y > 0.5) {
+ guide_diffuse *= c.weight;
+ refl_e *= c.weight;
+ }
+ }
// Integer tests: Metal's fast-math folds `x != x` away, so float NaN checks are unreliable.
if (non_finite(radiance)) { radiance = vec3<f32>(0.0); }
if (non_finite(albedo)) { albedo = vec3<f32>(0.0); }
diff --git a/renderer/shaders/translucent.wgsl b/renderer/shaders/translucent.wgsl
index a214237..403266a 100644
--- a/renderer/shaders/translucent.wgsl
+++ b/renderer/shaders/translucent.wgsl
@@ -36,7 +36,8 @@
// Volume voxels (cache_point, point_radiance): pathtrace.wgsl, shared with participating media.
// Live: the nearest opaque first hit around output pixel (x, y): of the 2 x 2 traced pixels under it, the nearest
-// (sky = none), so nothing shows through at an edge.
+// (sky = none), so nothing shows through at an edge. The camera's own hits (`first_depth`): a mirror hides what is
+// behind it, whatever it shows.
@if(hwrt) fn opaque_depth(x: u32, y: u32) -> f32 {
let iw = TPS.view.x;
let ih = TPS.view.y;
@@ -49,7 +50,7 @@
var t = INF;
for (var k = 0u; k < 4u; k++) {
let q = select(y0, y1, k >= 2u) * iw + select(x0, x1, (k & 1u) == 1u);
- let d = accum[q].color.w;
+ let d = first_depth(q);
if (d > 0.0) { t = min(t, d); }
}
return t;
@@ -107,7 +108,7 @@ fn translucent(@builtin(global_invocation_id) gid: vec3<u32>) {
let o = P.cam_pos.xyz;
var tmax = INF;
if (low) {
- let od = accum[pix].color.w;
+ let od = first_depth(pix);
if (od > 0.0) { tmax = od; }
} else if (live) {
tmax = opaque_depth(gid.x, gid.y);
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index 7ea1317..c149bdc 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -1576,8 +1576,9 @@ pub struct KernelBufs {
pub motion: Buf,
pub direct: Buf,
pub lists: Buf,
- /// A live frame's camera hits, 32 bytes a traced pixel (pathtrace.wgsl `first_store`): its first pass writes them,
- /// its paths start from them.
+ /// 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`).
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`).
@@ -1606,6 +1607,26 @@ impl KernelBufs {
}
}
+ /// These with the camera hits' buffer of `bytes`. As written that buffer alone is another; the merged layout's
+ /// are one buffer, all of it made again (the cache, as long, empty).
+ pub fn with_first(&self, d: &wgpu::Device, bytes: u64) -> KernelBufs {
+ let view = [self.refl.size, self.motion.size, self.direct.size, self.lists.size, bytes];
+ match self.merged {
+ Some(_) => KernelBufs::new(d, true, true, self.cache.val.size / 32, view),
+ None => KernelBufs {
+ cache: self.cache.clone(),
+ refl: self.refl.clone(),
+ motion: self.motion.clone(),
+ direct: self.direct.clone(),
+ lists: self.lists.clone(),
+ first: Buf::whole(d.create_buffer(&wgpu::BufferDescriptor { label: Some(VIEW_BUFFERS[4]), size: bytes, usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false })),
+ deferred: self.deferred.clone(),
+ guard: self.guard.clone(),
+ merged: None,
+ },
+ }
+ }
+
/// For a cache of `entries` and a view's five of these bytes (`VIEW_BUFFERS`).
/// `guard`: the layout as written has the guard's count (`Gpu::guard_room`).
pub fn new(d: &wgpu::Device, merged: bool, guard: bool, entries: u64, view: [u64; 5]) -> KernelBufs {
@@ -1649,18 +1670,20 @@ pub(crate) fn live_sizes(entries: u64, view: [u64; 5]) -> [u64; 9] {
/// Group-1 bind group of the kernel: the radiance cache and the reflection resolve's inputs (`KernelBufs`); in the
/// merged layout, the one buffer.
-/// `paths`: with what the paths' passes alone use, `finish`'s records and the camera hits (`live_layout`; the
-/// translucency pass's `tl_live_layout` is without).
-pub fn live_bind_group(d: &wgpu::Device, layout: &wgpu::BindGroupLayout, b: &KernelBufs, paths: bool) -> wgpu::BindGroup {
+/// `translucent`: for the translucency pass's layout (`tl_live_layout`), which has what that pass reads alone: the
+/// radiance cache, the light tiles' lists and the camera hits.
+pub fn live_bind_group(d: &wgpu::Device, layout: &wgpu::BindGroupLayout, b: &KernelBufs, translucent: bool) -> wgpu::BindGroup {
fn e(binding: u32, b: &Buf) -> wgpu::BindGroupEntry<'_> {
wgpu::BindGroupEntry { binding, resource: b.binding() }
}
match &b.merged {
Some(heap) => d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("live"), layout, entries: &[wgpu::BindGroupEntry { binding: crate::merged::LIVE_BINDING, resource: heap.buffer.as_entire_binding() }] }),
None => {
- let mut entries = vec![e(1, &b.cache.keys), e(2, &b.cache.acc), e(3, &b.cache.val), e(crate::merged::LISTS_BINDING, &b.lists), e(5, &b.refl), e(6, &b.motion), e(7, &b.direct)];
- entries.extend(b.deferred.as_ref().filter(|_| paths).map(|r| e(crate::merged::DEFERRED_BINDING, r)));
- entries.extend(paths.then(|| e(crate::merged::FIRST_BINDING, &b.first)));
+ let mut entries = vec![e(1, &b.cache.keys), e(2, &b.cache.acc), e(3, &b.cache.val), e(crate::merged::LISTS_BINDING, &b.lists), e(crate::merged::FIRST_BINDING, &b.first)];
+ if !translucent {
+ entries.extend([e(5, &b.refl), e(6, &b.motion), e(7, &b.direct)]);
+ entries.extend(b.deferred.as_ref().map(|r| e(crate::merged::DEFERRED_BINDING, r)));
+ }
entries.extend(b.guard.as_ref().map(|g| e(crate::merged::GUARD_BINDING, g)));
d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("live"), layout, entries: &entries })
}
@@ -1857,7 +1880,9 @@ pub const F_FUNC: u32 = 512;
// (1024: the emitter-reservoir experiment, removed 2026-11-13.)
pub const F_GLASS: u32 = 2048;
pub const F_COAT: u32 = 4096;
-// (8192: free.)
+/// A material that can be a mirror alone (`mirror_possible`; pathtrace.wgsl's of the name): a live frame's first
+/// pass follows what it shows, and the kernel has the code for it.
+pub const F_MIRROR: u32 = 8192;
/// The scene has instances (scene::Instance): TLAS instances with their record as custom data, shaded from
/// model-space triangles through their `instances` record.
pub const F_INST: u32 = 16384;
@@ -1974,6 +1999,12 @@ pub fn instance_features(scene: &Scene) -> u32 {
media | particles | ifunc | iglass | deform | part | F_INST | if masked { F_MASKED } else { 0 } | if scene.units.is_some() { F_UNITS } else { 0 }
}
+/// Whether a material's own numbers leave a mirror alone possible (pathtrace.wgsl `mirror_possible`, `mirror_alone`):
+/// its roughness under the kernel's `DELTA_ROUGHNESS`, metal whole, no glass. (Its textures can only lower them.)
+pub fn mirror_possible(m: &crate::scene::GpuMaterial) -> bool {
+ m.params[1] < 0.025 && m.params[0] >= 1.0 && m.layer[0] <= 0.0
+}
+
/// `features` from the parts parameter edits change (the materials; `environment`: `environment_features`), and the
/// scene's structure (`instances`: `instance_features`).
pub fn features_of(ms: &[crate::scene::GpuMaterial], environment: u32, textures: bool, functions: bool, instances: u32) -> u32 {
@@ -1993,6 +2024,9 @@ pub fn features_of(ms: &[crate::scene::GpuMaterial], environment: u32, textures:
if ms.iter().any(|m| m.tex1[2] == crate::scene::MAT_UNLIT) {
f |= F_UNLIT;
}
+ if ms.iter().any(mirror_possible) {
+ f |= F_MIRROR;
+ }
if let Some(mask) = std::env::var("THREERT_FEATURES").ok().and_then(|v| v.parse::<u32>().ok()) {
f &= mask | F_INST | F_PROC | F_TINT; // not optional: they say what the instances' records / the object table hold
}
@@ -2178,14 +2212,15 @@ impl Gpu {
],
});
let no_live_bufs = KernelBufs::new(&device, merged, guard_room(hwrt), 1, [64; 5]);
- let no_live = live_bind_group(&device, &live_layout, &no_live_bufs, true);
+ let no_live = live_bind_group(&device, &live_layout, &no_live_bufs, false);
let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&layout), Some(&live_layout)], immediate_size: 0 });
let (tl_layout, tl_pipeline_layout, tl_live_layout, no_live_tl) = if hwrt {
let l = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("translucent"), entries: &tl_entries });
- let tl_vis: Vec<_> = live_entries.iter().filter(|e| merged || ![crate::merged::DEFERRED_BINDING, crate::merged::FIRST_BINDING].contains(&e.binding)).copied().collect();
+ // (What the pass reads of group 1: the radiance cache, the light tiles' lists, the camera hits, the loop guard's count. A stage's buffers are counted against Metal's limit.)
+ let tl_vis: Vec<_> = live_entries.iter().filter(|e| merged || [1, 2, 3, crate::merged::LISTS_BINDING, crate::merged::FIRST_BINDING, crate::merged::GUARD_BINDING].contains(&e.binding)).copied().collect();
let vl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("live, translucent"), entries: &tl_vis });
let tpl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("translucent"), bind_group_layouts: &[Some(&layout), Some(&vl), Some(&l)], immediate_size: 0 });
- let nv = live_bind_group(&device, &vl, &no_live_bufs, false);
+ let nv = live_bind_group(&device, &vl, &no_live_bufs, true);
(Some(l), Some(tpl), Some(vl), Some(nv))
} else {
(None, None, None, None)
@@ -4150,7 +4185,7 @@ mod tests {
("F_GLASS", F_GLASS), ("F_COAT", F_COAT), ("F_INST", F_INST), ("F_MEDIA", F_MEDIA), ("F_PEMIT", F_PEMIT),
("F_HMEDIA", F_HMEDIA), ("F_PROC", F_PROC), ("F_TINT", F_TINT), ("F_UNLIT", F_UNLIT), ("F_BACKGROUND", F_BACKGROUND),
("F_VCOLOR", F_VCOLOR), ("F_AERIAL", F_AERIAL), ("F_GRID", F_GRID), ("F_LISTS", F_LISTS), ("F_IFUNC", F_IFUNC), ("F_IGLASS", F_IGLASS),
- ("F_DEFORM", F_DEFORM), ("F_PART", F_PART),
+ ("F_DEFORM", F_DEFORM), ("F_PART", F_PART), ("F_MIRROR", F_MIRROR),
];
let mut seen = 0u32;
for (name, bit) in all {
diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rs
index cf55470..8c8040f 100644
--- a/renderer/src/live/frame.rs
+++ b/renderer/src/live/frame.rs
@@ -194,6 +194,7 @@ impl LiveCore {
let size = ReconstructionSize { input: [iw, ih], output: [w, h], dynamic: self.dynamic_res };
self.reset |= self.reconstructor.prepare(&self.g, &self.targets, size, self.view_mode != 0);
let reconstruction = self.reconstructor.active;
+ self.ensure_first(iw as u64 * ih as u64);
self.ensure_deferred(iw as u64 * ih as u64);
if self.sc.up.translucent.is_some() {
self.targets.translucent_low(&self.g);
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 0c72b9c..a263980 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -5033,6 +5033,134 @@ fn the_first_pass_leaves_the_camera_hits() {
assert!(missed > 200 && hits.iter().filter(|h| tri(h) == u32::MAX).all(|h| inst(h) == u32::MAX), "{missed} pixels of nothing, each a miss whole");
}
+/// A pixel on a mirror has the surface the mirror shows. A mirror at 45 degrees before the camera shows a wall to the
+/// side: on the mirror's pixels the distance is the whole way to the wall (the camera hit's own stays in its record),
+/// the normal is the wall's as the pixel sees it, the albedo the wall's under the mirror's tint, the light the
+/// mirror's tint times a white mirror's, and the mirror's own glow is light seen directly. A lamp just before the
+/// wall lights what the mirror shows (the path starts where the wall is). A chain leaves the surface it shows a
+/// bounce: with one bounce a path no mirror is followed. The wall moved along the view, its motion vectors go
+/// sideways: the motion of what the pixel sees. A translucent particle before the mirror is drawn, one behind it is
+/// not.
+#[test]
+fn a_pixel_on_a_mirror_has_the_surface_the_mirror_shows() {
+ // (A faint glow: the card below is told by the centre's colour.)
+ let (tint, shade, glow) = ([1.0f32, 0.8, 0.6], [0.2f32, 0.6, 0.4], 0.05f32);
+ // (The wall a little off the square: its normal as the mirror shows it has every column of the chain's transform.)
+ let turned = glam::Quat::from_rotation_y(-110f32.to_radians());
+ let scene = |mirror: [f32; 3], card: Option<f32>, bulb: bool| -> World {
+ let mut w = world();
+ let mat = |color: [f32; 3], metalness: f32, roughness: f32, emissive: f32| serde_json::from_value(serde_json::json!({ "name": "m", "color": color, "opacity": 1, "metalness": metalness, "roughness": roughness, "emissive": [1, 1, 1], "emissiveIntensity": emissive, "doubleSided": true })).unwrap();
+ w.set_material(40, mat(mirror, 1.0, 0.0, glow));
+ w.set_material(41, mat(shade, 0.0, 1.0, 0.0));
+ let quad = |s: f32| Geometry { positions: vec![-s, -s, 0.0, s, -s, 0.0, s, s, 0.0, -s, s, 0.0], normals: [0.0, 0.0, 1.0].repeat(4), uvs: vec![0.0; 8], indices: vec![0, 1, 2, 0, 2, 3], groups: vec![], colors: vec![] };
+ w.set_geometry(40, quad(0.5)).unwrap();
+ w.set_geometry(41, quad(2.0)).unwrap();
+ let mesh = |geometry, material| Kind::Mesh { geometry, material, own_blas: false, materials: vec![] };
+ w.set_object(40, "mirror".into(), None, mesh(40, 40), true, false).unwrap();
+ w.set_transform(40, Vec3::new(0.0, 0.0, 2.0), glam::Quat::from_rotation_y(std::f32::consts::FRAC_PI_4), Vec3::ONE).unwrap();
+ // (Movable: what moves has motion vectors.)
+ w.set_object(41, "side wall".into(), None, mesh(41, 41), true, true).unwrap();
+ w.set_transform(41, Vec3::new(4.0, 0.0, 2.0), turned, Vec3::ONE).unwrap();
+ if let Some(z) = card {
+ // A translucent card that glows, on the view's axis at this z.
+ w.set_shader("glow", "fn mf_glow(i: MatIn, m: Material, base: MatOut) -> MatOut {\n var o = base;\n o.base = vec3<f32>(0.9, 0.05, 0.05);\n o.emissive = vec3<f32>(0.9, 0.05, 0.05) * 40.0;\n return o;\n}\n".into(), String::new());
+ w.set_material(50, serde_json::from_value(serde_json::json!({ "name": "glow", "color": [0.5, 0.5, 0.5], "opacity": 0.9, "transparent": true, "metalness": 0, "roughness": 1, "emissive": [0, 0, 0], "emissiveIntensity": 0, "doubleSided": true, "shader": { "id": "glow", "params": [], "textures": [] } })).unwrap());
+ w.set_particle_fn("card", format!("fn pf_card(i: PIn, p: array<vec4<f32>, 8>) -> POut {{ return POut(vec3<f32>(0.0, 0.0, {z:.2}), vec3<f32>(0.12, 0.0, 0.0), vec3<f32>(0.0, 0.12, 0.0), true, vec4<f32>(0.0)); }}"), String::new());
+ w.set_object(60, "card".into(), None, Kind::Particles { count: 1, emitter: "card".into(), params: vec![], material: 50, emitter_area: 0.0 }, true, false).unwrap();
+ }
+ if bulb {
+ // A point light 0.4 before the wall, where the mirror's centre shows it (and 3 from where a path that
+ // started at the camera would think the wall is).
+ let point = serde_json::from_value(serde_json::json!({ "type": "point", "color": [1.0, 1.0, 1.0], "castShadow": true, "intensity": 400.0, "radius": 0.02, "range": 0.0 })).unwrap();
+ w.set_object(61, "bulb".into(), None, Kind::Light(point), true, false).unwrap();
+ w.set_transform(61, Vec3::new(3.6, 0.0, 2.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
+ }
+ w
+ };
+ let presets = crate::default_presets_dir();
+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new("."), &presets, 96, 54));
+ let mut w = scene(tint, None, false);
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ assert_ne!(live.sc.up.kernel.features & gpu::F_MIRROR, 0, "a scene with a mirror has the feature");
+ live.fixed_dt = Some(1.0 / 60.0);
+ live.render(1, |_, _| {});
+ let (iw, ih) = live.internal_size();
+ let pixels = (iw * ih) as u64;
+ let read = |live: &LiveCore| -> (Vec<[f32; 8]>, Vec<[f32; 20]>, Vec<[f32; 4]>, Vec<[f32; 4]>) {
+ let (f, m, d) = (&live.targets.kernel.first, &live.targets.kernel.motion, &live.targets.kernel.direct);
+ (read_back(live, &f.buffer, f.offset, pixels * 32), read_back(live, &live.targets.accum, 0, pixels * gpu::SAMPLE_BYTES), read_back(live, &m.buffer, m.offset, pixels * 16), read_back(live, &d.buffer, d.offset, pixels * 16))
+ };
+ let (hits, samples, _, direct) = read(&live);
+ // (pathtrace.wgsl `first_store`: the chain rides above the part.)
+ let chain = |h: &[f32; 8]| h[7] as u32 >> 16;
+ let on: Vec<usize> = (0..pixels as usize).filter(|&k| chain(&hits[k]) > 0).collect();
+ let centre = (ih / 2 * iw + iw / 2) as usize;
+ assert!(on.len() > 100 && on.contains(&centre) && on.iter().all(|&k| chain(&hits[k]) == 1), "{} pixels on the mirror, each through one mirror", on.len());
+ assert!((hits[centre][0] - 3.0).abs() < 0.1 && (samples[centre][3] - 7.0).abs() < 0.1, "the centre: the mirror {} away, the wall it shows {} (3 and 3 + 4)", hits[centre][0], samples[centre][3]);
+ // (The wall's normal, towards -x turned 20 degrees, as the mirror shows it: x and z changed over, both turned.)
+ let (facing, seen) = (Vec3::new(20f32.to_radians().sin(), 0.0, 20f32.to_radians().cos()), Vec3::new(shade[0] * tint[0], shade[1] * tint[1], shade[2] * tint[2]));
+ for &k in &on {
+ let (s, own) = (&samples[k], hits[k][0]);
+ let (normal, albedo, emitted) = (Vec3::new(s[8], s[9], s[10]), Vec3::new(s[4], s[5], s[6]), Vec3::new(s[12], s[13], s[14]));
+ assert!(s[3] > own + 2.0 && (normal - facing).length() < 0.02 && (albedo - seen).length() < 0.03, "pixel {k}: the mirror {own} away; shown {} away, normal {normal}, albedo {albedo}", s[3]);
+ assert!((emitted - Vec3::splat(glow)).abs().max_element() < 1e-3, "pixel {k}: the mirror's own glow {glow} is seen directly: {emitted}");
+ }
+ assert!((0..pixels as usize).filter(|&k| chain(&hits[k]) == 0 && samples[k][3] > 0.0).all(|k| samples[k][3].to_bits() == hits[k][0].to_bits()), "off the mirror the distance is the camera hit's");
+ // The light of those pixels (the diffuse signal and the sun's direct light) against a white mirror's: the tint
+ // at most, and no less than twice the tint (the wall is partly lit by way of the mirror too).
+ let light = |samples: &[[f32; 20]], direct: &[[f32; 4]], of: &[usize]| of.iter().fold(Vec3::ZERO, |sum, &k| sum + Vec3::new(samples[k][0] + direct[k][0], samples[k][1] + direct[k][1], samples[k][2] + direct[k][2]));
+ let frame = |w: &World| -> Vec3 {
+ let mut c = open(w).unwrap();
+ c.fixed_dt = Some(1.0 / 60.0);
+ c.render(1, |_, _| {});
+ let (_, s, _, d) = read(&c);
+ light(&s, &d, &on)
+ };
+ let (lit, plain) = (light(&samples, &direct, &on), frame(&scene([1.0; 3], None, false)));
+ let (share, tint_v) = (lit / plain, Vec3::from(tint));
+ assert!(plain.min_element() > 0.0 && (share - tint_v).max_element() < 0.03 && (tint_v * tint_v - share).max_element() < 0.03, "the mirror's pixels hold {lit}, a white mirror's {plain}: {share} of it, the tint {tint:?}");
+ // A lamp just before the wall: what the mirror shows is lit by it as the wall is.
+ let lamped = frame(&scene(tint, None, true));
+ assert!(lamped.min_element() > 3.0 * lit.max_element(), "the mirror's pixels with a lamp before the wall hold {lamped}, without {lit}");
+ // A chain is all but one of a path's bounces at most, so the surface it shows is lit: with one bounce a path no
+ // mirror is followed, with two the mirror is and the wall it shows has light.
+ let bounces = std::mem::replace(&mut live.bounces, 1);
+ live.render(1, |_, _| {});
+ assert!(read(&live).0.iter().all(|h| chain(h) == 0), "with one bounce a path, no mirror is followed");
+ live.bounces = 2;
+ live.render(1, |_, _| {});
+ // (This frame's pixels: another jitter.)
+ let (h2, s2, _, d2) = read(&live);
+ let mirror: Vec<usize> = (0..pixels as usize).filter(|&k| chain(&h2[k]) > 0).collect();
+ assert!(mirror.len() > 100 && light(&s2, &d2, &mirror).min_element() > 0.1, "with two bounces the mirror's {} pixels show the wall lit: {}", mirror.len(), light(&s2, &d2, &mirror));
+ live.bounces = bounces;
+ // The wall goes 0.3 along the view (z): in the mirror it goes 0.3 sideways (x), and a motion vector is the way back.
+ w.set_transform(41, Vec3::new(4.0, 0.0, 2.3), turned, Vec3::ONE).unwrap();
+ assert!(!live.commit(&mut w).unwrap(), "the wall moved: in place ({:?})", live.fallback);
+ live.render(1, |_, _| {});
+ let (hits, _, motion, _) = read(&live);
+ let moved: Vec<Vec3> = (0..pixels as usize).filter(|&k| chain(&hits[k]) > 0 && motion[k][3] > 0.5).map(|k| Vec3::new(motion[k][0], motion[k][1], motion[k][2])).collect();
+ assert!(moved.len() > 100 && moved.iter().all(|v| (*v - Vec3::new(0.3, 0.0, 0.0)).length() < 2e-3), "{} mirror pixels moved, each by the wall's step as the mirror shows it (the first: {:?})", moved.len(), moved.first());
+ // A translucent card on the view's axis: before the mirror (3 away) it is drawn, behind it it is not, though the
+ // wall the mirror shows is further than both. (The translucency pass: hardware traversal.)
+ if live.g.hwrt {
+ let centre = |card: Option<f32>| -> [i32; 3] {
+ let mut c = open(&scene(tint, card, false)).unwrap();
+ assert_eq!(c.sc.up.translucent.is_some(), card.is_some(), "the card is the translucency pass's");
+ let p = picture(&mut c, 8);
+ let at = ((c.h / 2 * c.w + c.w / 2) * 4) as usize;
+ [p[at] as i32, p[at + 1] as i32, p[at + 2] as i32]
+ };
+ let (plain, before, behind) = (centre(None), centre(Some(3.5)), centre(Some(1.2)));
+ let apart = |a: [i32; 3], b: [i32; 3]| (0..3).map(|k| (a[k] - b[k]).abs()).max().unwrap();
+ assert!(apart(before, plain) > 60 && apart(behind, plain) < 12, "the centre without a card {plain:?}; with one before the mirror {before:?} (drawn), behind it {behind:?} (hidden)");
+ }
+}
+
/// A planet's altitude alone is not another sky: the world says so apart (`Changes::altitude`), and the view bakes
/// again only past its step (5 %, at least 250 m).
#[test]
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index e28597c..11c87ba 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -167,7 +167,7 @@ pub(super) const LIST_CANDIDATES: u32 = 2;
/// The kernel's group-1 bind groups over a view's targets: the trace's, and the translucency pass's where the device
/// has one (`gpu::Gpu::tl_live_layout`: without `finish`'s records).
fn kernel_bind_groups(g: &gpu::Gpu, targets: &Targets) -> (wgpu::BindGroup, Option<wgpu::BindGroup>) {
- (gpu::live_bind_group(&g.device, &g.live_layout, &targets.kernel, true), g.tl_live_layout.as_ref().map(|l| gpu::live_bind_group(&g.device, l, &targets.kernel, false)))
+ (gpu::live_bind_group(&g.device, &g.live_layout, &targets.kernel, false), g.tl_live_layout.as_ref().map(|l| gpu::live_bind_group(&g.device, l, &targets.kernel, true)))
}
#[derive(Clone, Copy, PartialEq, Debug)]
@@ -821,6 +821,26 @@ 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
+ /// 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.
+ pub(super) fn ensure_first(&mut self, pixels: u64) {
+ let each = if self.sc.up.kernel.features & gpu::F_MIRROR != 0 { 128 } else { 32 };
+ if self.targets.kernel.first.size >= pixels * each {
+ return;
+ }
+ self.targets.grow_first(&self.g, &self.passes, (pixels + pixels / 4).min(self.w as u64 * self.h as u64) * each);
+ // (The merged layout's cache is in the buffer made again: the view's cache is that one from here, empty, and
+ // nothing of the frames before stands.)
+ if self.g.merged {
+ if let Some(c) = &mut self.cache {
+ c.bufs = self.targets.kernel.cache.clone();
+ }
+ (self.reset, self.prev_isz) = (true, (0, 0));
+ }
+ (self.kernel_bg, self.tl_kernel_bg) = kernel_bind_groups(&self.g, &self.targets);
+ }
+
/// The view at another size (its host's window, in pixels): the targets that follow the size are made again
/// (`Targets::resize`) and bound, the scene with the new samples' buffer; the frames' histories start again. The
/// scene's data, the radiance cache (the world's), the view's camera, state and render scale stay. A size this
diff --git a/renderer/src/live/targets.rs b/renderer/src/live/targets.rs
index 8c401cb..35a6a2a 100644
--- a/renderer/src/live/targets.rs
+++ b/renderer/src/live/targets.rs
@@ -152,6 +152,13 @@ impl Targets {
t
}
+ /// The kernel's buffers with the camera hits' of `bytes` (`gpu::KernelBufs::with_first`), and the passes' bind
+ /// groups over them (the merged layout's sections are all in another buffer then).
+ pub(super) fn grow_first(&mut self, g: &gpu::Gpu, passes: &Passes, bytes: u64) {
+ self.kernel = self.kernel.with_first(&g.device, bytes);
+ self.bgs = self.bind_groups(&g.device, passes);
+ }
+
/// For another size: what follows it is made again (the samples, the passes' own buffers and the output, the
/// kernel's four, the translucent particles'), with the bind groups over them. The radiance cache, which is the
/// world's, the passes' parameters and the tone-map table stay. (The merged layout keeps the cache in one buffer