3D engine that AI agents drive
Path tracer: the light tree respects light linking
Nguyen Xuan An3b2df0621a81
diff --git a/changes/814.md b/changes/814.mdnew file mode 100644index 00000000..d0bf55a4--- /dev/null+++ b/changes/814.md@@ -0,0 +1 @@+- Path tracer: `lightSelection: "tree"` (and `auto` past 8 lights) now draws only the lights a linked part can see, uniformly among them, instead of walking a tree that counts every light, on the CPU, WebGL2 and WebGPU tracers (#814)diff --git a/docs/path-tracer.md b/docs/path-tracer.mdindex 27721086..e9232dcf 100644--- a/docs/path-tracer.md+++ b/docs/path-tracer.md@@ -140,7 +140,7 @@ Three options (`samplingPattern: "blue-noise-first"` and `lightSelection: "impor- `samplingPattern: "blue-noise-first"` uses a 64 by 64 void-and-cluster tile (`src/path-tracer-blue-noise.js`, same bytes for the same seed) for the pixel jitter and the first two random numbers of sample 0, as `SAMPLING_PATTERN_BLUE_NOISE_FIRST` does in Cycles. Later samples are random.- `lightSelection: "importance"` replaces the uniform light draw past the first hit: the sun and the sky keep their uniform share, and the local lights split theirs by power over squared distance, surface cosine and spot cone, mixed 10 percent with a uniform part. It ignores shadows and is a flat sum over the lights, not a tree (that is `lightSelection: "tree"`) nor ReSTIR; a scene with one local light or none draws the same pixels as before.-- `lightSelection: "tree"` is the light tree of Conty and Kulla (2018) as Cycles builds it (`src/kernel/light/tree.h`), in `src/path-tracer-light-tree.js`, the same code and table on the CPU reference and in the GLSL kernel. The point, spot and area lights are leaves of a binary tree built with the surface area orientation heuristic of the paper (12 buckets per axis, cost = energy times box area times orientation measure of both sides, as Cycles builds it). Each node keeps its box, an orientation cone (merged as in the paper) and the sum of its energy. A shading point walks down from the root and picks a child at each step by the importance of its box and cone: energy times the cosine of the best angle the box and cone allow, times the surface cosine, over the squared distance to the nearest point of the box. The step takes the chance 0.9 of the child's share of the maximum measure plus 0.1 of its share of a minimum measure (energy over the squared farthest distance, no angles; Cycles mixes them half and half), so a node the angle test culls keeps a chance and the image stays unbiased while little of the draw goes to lights that cannot reach the point; the chance of the whole path is divided out. The sun and the sky are the distant emitters and keep their uniform share of the emitter draw. It ignores shadows, light linking and spot blend. With more than 16 local lights the first hit draws one light by the tree too, where every other selection traces a shadow ray to each light there. A scene with one local light or none draws the same pixels as the uniform choice.+- `lightSelection: "tree"` is the light tree of Conty and Kulla (2018) as Cycles builds it (`src/kernel/light/tree.h`), in `src/path-tracer-light-tree.js`, the same code and table on the CPU reference and in the GLSL kernel. The point, spot and area lights are leaves of a binary tree built with the surface area orientation heuristic of the paper (12 buckets per axis, cost = energy times box area times orientation measure of both sides, as Cycles builds it). Each node keeps its box, an orientation cone (merged as in the paper) and the sum of its energy. A shading point walks down from the root and picks a child at each step by the importance of its box and cone: energy times the cosine of the best angle the box and cone allow, times the surface cosine, over the squared distance to the nearest point of the box. The step takes the chance 0.9 of the child's share of the maximum measure plus 0.1 of its share of a minimum measure (energy over the squared farthest distance, no angles; Cycles mixes them half and half), so a node the angle test culls keeps a chance and the image stays unbiased while little of the draw goes to lights that cannot reach the point; the chance of the whole path is divided out. The sun and the sky are the distant emitters and keep their uniform share of the emitter draw. It ignores shadows and spot blend. On a part with light linking that leaves some local light out, the tree is skipped and the draw is uniform among the lights the part is linked to (the tree weighs a node by every light under it, so it would spend draws on lights the part cannot see). With more than 16 local lights the first hit draws one light by the tree too, where every other selection traces a shadow ray to each light there. A scene with one local light or none draws the same pixels as the uniform choice.Measured on the RTX 3060, 960 by 540, FLIP against Cycles of the denoised image, machine shared with other jobs (times are ranges of repeated runs: GPU steps only, without the first step's kernel compile and without the read back, which took 1.8 to 2.6 s with the filter):diff --git a/src/path-tracer-gpu-shader.js b/src/path-tracer-gpu-shader.jsindex 8fd7c156..8d0847e1 100644--- a/src/path-tracer-gpu-shader.js+++ b/src/path-tracer-gpu-shader.js@@ -104,6 +104,22 @@ int chooseEmitterByTree(vec3 normal, out float probability) {probability = uniformShare;int lightIndex = emitter - firstLightEmitter;if (lightIndex < 0 || lightIndex >= uLightCount) return emitter;+ // The tree weighs a node by every light under it, linked or not, so a receiver with light linking draws uniformly among the lights it can see.+ int linkedCount = 0;+ for (int index = 0; index < uLightCount; index++) {+ if (reaches(int(fetchData(uLights, index * LIGHT_TEXELS + 1).w))) linkedCount++;+ }+ if (linkedCount < uLightCount) {+ if (linkedCount == 0) return -1;+ int skip = min(int(floor(nextRandom() * float(linkedCount))), linkedCount - 1);+ probability = float(uLightCount) * uniformShare / float(linkedCount);+ for (int index = 0; index < uLightCount; index++) {+ if (!reaches(int(fetchData(uLights, index * LIGHT_TEXELS + 1).w))) continue;+ if (skip == 0) return firstLightEmitter + index;+ skip--;+ }+ return -1;+ }int node = 0;float pathProbability = 1.0;for (int step = 0; step < 64; step++) {diff --git a/src/path-tracer-webgpu-kernel.js b/src/path-tracer-webgpu-kernel.jsindex 0fccc74e..ee99d374 100644--- a/src/path-tracer-webgpu-kernel.js+++ b/src/path-tracer-webgpu-kernel.js@@ -836,6 +836,22 @@ fn chooseEmitter(normal: vec3<f32>) -> i32 {let lightIndex = emitter - firstLightEmitter;let lightCount = params.sizeBouncesLights.w;if (lightIndex < 0 || lightIndex >= lightCount) { return emitter; }+ // The tree weighs a node by every light under it, linked or not, so a receiver with light linking draws uniformly among the lights it can see.+ var linkedCount = 0;+ for (var index = 0; index < lightCount; index++) {+ if (reaches(i32(lights[index * LIGHT_TEXELS + 1].w))) { linkedCount++; }+ }+ if (linkedCount < lightCount) {+ if (linkedCount == 0) { return -1; }+ var skip = min(i32(floor(nextRandom() * f32(linkedCount))), linkedCount - 1);+ selectionProbability = f32(lightCount) * uniformShare / f32(linkedCount);+ for (var index = 0; index < lightCount; index++) {+ if (!reaches(i32(lights[index * LIGHT_TEXELS + 1].w))) { continue; }+ if (skip == 0) { return firstLightEmitter + index; }+ skip--;+ }+ return -1;+ }var node = 0;var pathProbability = 1.0;for (var step = 0; step < 64; step++) {diff --git a/src/path-tracer.js b/src/path-tracer.jsindex 0125af4e..3467721e 100644--- a/src/path-tracer.js+++ b/src/path-tracer.js@@ -663,6 +663,22 @@ function createPathTracer(scene, options) {return sampleAreaLight(depth, normal, lights.areas[index - lights.spots.length]);}+ const linkedLightsByMask = new Map();+ const allLights = () => [...lights.points, ...lights.spots, ...lights.areas];+ /** The sampling-order indices of the local lights the hit part is lit by; every light inside a medium. */+ function linkedLights() {+ const mask = inMedium ? -1 : hit.material.lightMask;+ let linked = linkedLightsByMask.get(mask);+ if (!linked) {+ linked = [];+ allLights().forEach((light, index) => {+ if ((mask >> light.bit & 1) === 1) linked.push(index);+ });+ linkedLightsByMask.set(mask, linked);+ }+ return linked;+ }+/** One emitter by the light tree: the sun and the sky keep a uniform share, the local lights share theirs down the tree. */function addOneLightByTree(depth, normal) {const lightsShare = lightCount / emitterCount;@@ -678,6 +694,16 @@ function createPathTracer(scene, options) {selectionProbability = 1 / emitterCount;return sampleEnvironmentLight(depth, normal);}+ const linked = linkedLights();+ if (linked.length < lightCount) {+ // The tree weighs a node by every light under it, linked or not, so a receiver with light linking draws uniformly among the lights it can see.+ selectionProbability = 1 / emitterCount;+ if (linked.length === 0) return;+ selectionProbability = lightsShare / linked.length;+ sampleLightByIndex(depth, normal, linked[Math.floor(random.next() * linked.length)]);+ selectionProbability = 1 / emitterCount;+ return;+ }const picked = chooseLightFromTree(lightTree, hit.point[0], hit.point[1], hit.point[2], normal[0], normal[1], normal[2], drawRandom);selectionProbability = 1 / emitterCount;if (picked.lightIndex < 0) return;diff --git a/tests/path-tracer-light-tree.test.js b/tests/path-tracer-light-tree.test.jsindex 04089f6e..8e86741f 100644--- a/tests/path-tracer-light-tree.test.js+++ b/tests/path-tracer-light-tree.test.js@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';import test from 'node:test';import { box } from '../src/geometry.js';+import { POINT_FIRST_BIT } from '../src/light-link-bits.js';import { renderPathTracedImage } from '../src/path-tracer.js';import { packLightTree } from '../src/path-tracer-gpu-pack.js';import { buildFragmentSource } from '../src/path-tracer-gpu-shader.js';@@ -169,3 +170,38 @@ test('the WebGPU kernels carry the tree walk', async () => {assert.ok(source.includes('lightsFromEveryEmitter'));}});++// Twenty point lights, only the first of which reaches the floor: the other nineteen hang close above it, so a walk that ignores+// the link set spends nearly every draw on a light the floor cannot see.+function linkedReceiverScene() {+ const farLight = pointLight([0, 4, 0], 40);+ const nearLights = Array.from({ length: 19 }, (_, index) => pointLight([(index % 5) * 1.4 - 2.8, 0.6, Math.floor(index / 5) * 1.4 - 2], 3));+ const scene = manyLightScene(1);+ scene.environment.pointLights = [farLight, ...nearLights];+ scene.parts[0].material.lightMask = 1 << POINT_FIRST_BIT;+ return scene;+}++function rootMeanSquareError(linear, reference) {+ let sum = 0;+ for (let index = 0; index < linear.length; index++) sum += (linear[index] - reference[index]) ** 2;+ return Math.sqrt(sum / linear.length);+}++test('the light tree draws only the lights a linked receiver can see, with the mean of the uniform draw and no more noise', async () => {+ const base = { width: 24, height: 18, bounces: 1, denoise: false, threads: 1 };+ const reference = await renderPathTracedImage(linkedReceiverScene(), { ...base, samples: 256, seed: 99 });+ const uniform = await renderPathTracedImage(linkedReceiverScene(), { ...base, samples: 8, lightSelection: 'uniform' });+ const tree = await renderPathTracedImage(linkedReceiverScene(), { ...base, samples: 8, lightSelection: 'tree' });+ const treeError = rootMeanSquareError(tree.linear, reference.linear);+ const uniformError = rootMeanSquareError(uniform.linear, reference.linear);+ assert.ok(treeError <= uniformError * 1.1, `tree error ${treeError} against uniform error ${uniformError}`);+ const ratio = meanRadiance(tree.linear) / meanRadiance(reference.linear);+ assert.ok(Math.abs(ratio - 1) < 0.05, `mean ratio ${ratio}`);+});++test('the GPU kernels limit the tree walk to the lights the hit part is linked to', async () => {+ assert.ok(buildFragmentSource({ lightTree: true }).includes('linkedCount'));+ const { buildMegakernelSource, WAVEFRONT_SOURCE } = await import('../src/path-tracer-webgpu-kernel.js');+ for (const source of [buildMegakernelSource(), WAVEFRONT_SOURCE]) assert.ok(source.includes('linkedCount'));+});