Skip to content

3D engine that AI agents drive

Refuse tracer options that blend past the new sample, give NaN sizes or read short buffers (#2543)

Nguyen Xuan An6d65a25cf737
diff --git a/changes/2543.md b/changes/2543.md
new file mode 100644
index 00000000..4da350f2
--- /dev/null
+++ b/changes/2543.md
@@ -0,0 +1 @@
+- The real-time tracer refuses a `historyLimit` below 1, `createProgressiveTracer` refuses `resolutionDivisors` that are empty, fractional or do not end with 1, and `denoiseRadiance` refuses a buffer shorter than width times height, instead of blending past the new sample or returning NaN.
diff --git a/docs/path-tracer.md b/docs/path-tracer.md
index d4d882b1..1e09c71c 100644
--- a/docs/path-tracer.md
+++ b/docs/path-tracer.md
@@ -296,7 +296,7 @@ The required `test` check builds no addon, so the tests that need it skip there.
## Progressive preview, blue noise and light choice (issue #623)
-`crucible/addons/path-tracer-progressive` (`createProgressiveTracer(scene, options)`) draws the GPU tracer one sample per pixel per `step()`. The first two steps draw at a quarter and a half of the size, one sample each, then every step adds a sample at full size; `update({ camera, parts, environment })` starts the image over, and `snapshot()` reads the image back (filtered unless `denoise` is off). It shares the WebGL2 context of the GPU still, so one render at a time owns it. The core bundle does not carry it.
+`crucible/addons/path-tracer-progressive` (`createProgressiveTracer(scene, options)`) draws the GPU tracer one sample per pixel per `step()`. The first two steps draw at a quarter and a half of the size, one sample each, then every step adds a sample at full size; `resolutionDivisors` (third argument, default `[4, 2, 1]`) lists the sizes drawn first as whole numbers from 1 and ends with 1; `update({ camera, parts, environment })` starts the image over, and `snapshot()` reads the image back (filtered unless `denoise` is off). It shares the WebGL2 context of the GPU still, so one render at a time owns it. The core bundle does not carry it.
Three options (`samplingPattern: "blue-noise-first"` and `lightSelection: "importance"` need the GPU backend, `lightSelection: "tree"` runs on the CPU reference, the WebGL2 GPU and the WebGPU tracer). `samplingPattern` and `importance` are off by default; `lightSelection` defaults to `"auto"`, which is `"tree"` for a scene with more than 8 local lights and `"uniform"` for the rest, so scenes with a handful of lights draw the same pixels as before:
@@ -350,7 +350,7 @@ Proof of the three checks of issue #623 on 2026-11-11 (`node bench/reference/pro
`crucible/addons/path-tracer-realtime` (`createRealtimeTracer(scene, { width, height, bounces, ... })`, then `frame(camera)` for every picture) draws the WebGL2 tracer fast enough to move the camera. It shares the WebGL2 context of the GPU still, so one render at a time owns it, and it draws to `canvas` (an `OffscreenCanvas` or a canvas element, 8 bit, ACES view transform). `readFrame()` returns the same picture as bytes. The pieces, each in its own module so they can move to the WebGPU backend:
-- **Half-size tracing.** One path per pixel and frame at half the output size (`resolutionDivisor`, 2), two bounces (`bounces`, 2). `resolutionDivisor`, `historyLimit` and `cacheCellSize` must be above 0 and `filterIterations` a whole number from 0 to 16, and `width` and `height` whole numbers whose traced size (over `resolutionDivisor`) stays from 16 to 4096, or the tracer refuses them. The first hit picks one light by importance instead of tracing a shadow ray to every light, which the denoiser averages over frames.
+- **Half-size tracing.** One path per pixel and frame at half the output size (`resolutionDivisor`, 2), two bounces (`bounces`, 2). `resolutionDivisor` and `cacheCellSize` must be above 0, `historyLimit` at least 1 and `filterIterations` a whole number from 0 to 16, and `width` and `height` whole numbers whose traced size (over `resolutionDivisor`) stays from 16 to 4096, or the tracer refuses them. The first hit picks one light by importance instead of tracing a shadow ray to every light, which the denoiser averages over frames.
- **Radiance cache** (`src/path-tracer-radiance-cache.js`, SHaRC style). A cell is the quantized position (cells double in size each time the distance from the eye doubles past 64 cells) and the quantized normal of a surface point, hashed into 2^20 slots with no collision check (about 0.4% of 7,500 test cells collided). The last hit of a path reads its cell instead of tracing on; the hit before it writes what the rest of the path brought back, and a point pass adds the records into the cells with additive blending (WebGL2 has no atomics), as a running average of up to 128 records. The cache reads as diffuse. It needs the scene to rest: a new scene empties it.
- **Temporal denoiser and upsampler** (`src/path-tracer-temporal-denoise.js`, `src/path-tracer-reprojection.js`, SVGF style). The light is divided by the albedo, reprojected history (bilinear, rejected where distance or normal differ) is blended in over up to 48 frames, the variance comes from the history of the luminance (from the 3 by 3 neighbours while the history is short), four a-trous passes filter with plane distance, normal and variance guided luminance weights, and a joint bilateral upsample to the output size multiplies the albedo history back in. A sample far above its neighbours is clamped while the history is short.
diff --git a/src/path-tracer-denoise.js b/src/path-tracer-denoise.js
index a56f753a..7399f0e9 100644
--- a/src/path-tracer-denoise.js
+++ b/src/path-tracer-denoise.js
@@ -162,6 +162,15 @@ function filterPass({ width, height, light, variance, normal, depth }, settings,
}
}
+const FLOATS_PER_PIXEL = { color: 3, albedo: 3, normal: 3, depth: 1, variance: 1 };
+
+function requireBufferSizes(pixelCount, buffers) {
+ for (const [name, buffer] of Object.entries(buffers)) {
+ const needed = pixelCount * FLOATS_PER_PIXEL[name];
+ if (!(buffer?.length >= needed)) throw new RangeError(`denoiseRadiance: ${name} has ${buffer?.length} values; pass ${needed} (${FLOATS_PER_PIXEL[name]} per pixel).`);
+ }
+}
+
/**
* Filters a radiance image with the features gathered at each pixel's first hit. All buffers are row-major; colour,
* albedo and normal hold three floats per pixel, depth and variance one. Returns a new colour buffer.
@@ -169,6 +178,7 @@ function filterPass({ width, height, light, variance, normal, depth }, settings,
export function denoiseRadiance({ width, height, color, albedo, normal, depth, variance }, overrides = {}) {
const settings = { ...DEFAULT_DENOISE_SETTINGS, ...overrides };
const pixelCount = width * height;
+ requireBufferSizes(pixelCount, { color, albedo, normal, depth, variance });
let light = demodulate(color, albedo, pixelCount);
let noise = smoothedVariance(variance, albedo, width, height);
let nextLight = new Float32Array(light.length);
diff --git a/src/path-tracer-progressive.js b/src/path-tracer-progressive.js
index 3fede120..3cb6322c 100644
--- a/src/path-tracer-progressive.js
+++ b/src/path-tracer-progressive.js
@@ -6,6 +6,7 @@ import {
averageBuffers, createBandState, createTargets, drawOneSample, getContext, gpuTriangleLimit, getKernel, releaseResources, setSceneUniforms, uploadScene, withBlueNoiseTile,
} from './path-tracer-gpu.js';
import { sceneUsesSubsurface } from './path-tracer-gpu-pack.js';
+import { requireFiniteInRange } from './modeling-limits.js';
// A progressive view of the GPU path tracer (issue #623). `step()` draws one sample for every pixel and adds it to the
// image; while the scene and camera rest the image gets cleaner with each step, and `update()` starts it over. Like the
@@ -13,6 +14,15 @@ import { sceneUsesSubsurface } from './path-tracer-gpu-pack.js';
// appears at once, then draws at full size. It shares the WebGL2 context of `traceOnGpu`, so one render at a time owns it.
const DEFAULT_RESOLUTION_DIVISORS = Object.freeze([4, 2, 1]);
+const MAXIMUM_RESOLUTION_DIVISOR = 64;
+
+// A level size is the output size over its divisor, so every divisor is a whole number from 1 and the last one, the full size, is 1.
+function requireResolutionDivisors(divisors) {
+ if (!Array.isArray(divisors) || divisors.length === 0 || divisors.at(-1) !== 1) {
+ throw new RangeError(`createProgressiveTracer: resolutionDivisors was ${JSON.stringify(divisors)}; pass a list of whole numbers that ends with 1, such as [4, 2, 1].`);
+ }
+ requireFiniteInRange('createProgressiveTracer', 'resolutionDivisors', divisors, 1, MAXIMUM_RESOLUTION_DIVISOR, true);
+}
/**
* `scene` is `{ parts, environment, camera }` as `renderPathTracedImage` takes them. `options` are the same options
@@ -20,6 +30,7 @@ const DEFAULT_RESOLUTION_DIVISORS = Object.freeze([4, 2, 1]);
* `backend` are not used. `resolutionDivisors` lists the sizes drawn first, one sample each, ending with 1.
*/
export async function createProgressiveTracer(scene, rawOptions = {}, { resolutionDivisors = DEFAULT_RESOLUTION_DIVISORS } = {}) {
+ requireResolutionDivisors(resolutionDivisors);
const options = await withBlueNoiseTile(normalizePathTracerOptions({ ...rawOptions, backend: 'gpu', samples: 1, maxSeconds: rawOptions.maxSeconds ?? 3600 }));
const { gl, gpu } = getContext();
const { width, height } = options;
diff --git a/src/path-tracer-realtime-options.js b/src/path-tracer-realtime-options.js
index d6650ccd..9068606b 100644
--- a/src/path-tracer-realtime-options.js
+++ b/src/path-tracer-realtime-options.js
@@ -10,10 +10,11 @@ const CACHE_LEVEL_CELLS = 64;
const SCENE_EXTENT_SCALE = 1e4;
const MAX_FILTER_ITERATIONS = 16;
-function requirePositiveNumber(value, name) {
+// The history blend is 1 over the history length, capped by historyLimit: below 1 the new sample would weigh more than 1.
+function requirePositiveNumber(value, name, minimum = 0) {
if (value === undefined) return;
- if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
- throw new RangeError(`The real-time path tracer option ${name} must be a finite number above 0, got ${value}. Pass a positive value or leave it out for the default.`);
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value < minimum) {
+ throw new RangeError(`The real-time path tracer option ${name} must be a finite number ${minimum > 0 ? `of at least ${minimum}` : 'above 0'}, got ${value}. Pass a larger value or leave it out for the default.`);
}
}
@@ -42,7 +43,7 @@ function requireTraceSizeInRange(traceSize, outputSize, name) {
/** The output and tracing sizes and the normalized tracer options of `createRealtimeTracer`'s raw options. */
export function resolveRealtimeOptions(rawOptions) {
requirePositiveNumber(rawOptions.resolutionDivisor, 'resolutionDivisor');
- requirePositiveNumber(rawOptions.historyLimit, 'historyLimit');
+ requirePositiveNumber(rawOptions.historyLimit, 'historyLimit', 1);
requirePositiveNumber(rawOptions.cacheCellSize, 'cacheCellSize');
requireFilterIterations(rawOptions.filterIterations);
requireOutputSize(rawOptions.width, 'width');
diff --git a/tests/path-tracer-option-limits.test.js b/tests/path-tracer-option-limits.test.js
new file mode 100644
index 00000000..37393ad4
--- /dev/null
+++ b/tests/path-tracer-option-limits.test.js
@@ -0,0 +1,34 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { denoiseRadiance } from '../src/path-tracer-denoise.js';
+import { resolveRealtimeOptions } from '../src/path-tracer-realtime-options.js';
+
+test('real-time options refuse a historyLimit below 1 and accept 1 (#2543)', () => {
+ for (const historyLimit of [0.5, 0.999]) {
+ assert.throws(() => resolveRealtimeOptions({ historyLimit }), /historyLimit.*at least 1/, `historyLimit ${historyLimit}`);
+ }
+ assert.equal(resolveRealtimeOptions({ historyLimit: 1 }).historyLimit, 1);
+});
+
+test('createProgressiveTracer refuses resolutionDivisors that give no full-size level (#2544)', async () => {
+ const { createProgressiveTracer } = await import('../src/path-tracer-progressive.js');
+ const scene = { parts: [], camera: { eye: [0, 0, 5], target: [0, 0, 0], fov: 50 } };
+ for (const resolutionDivisors of [[], [0, 1], [-2, 1], [2.5, 1], [4, 2], [Number.NaN, 1], 'x']) {
+ await assert.rejects(createProgressiveTracer(scene, {}, { resolutionDivisors }), /resolutionDivisors/, JSON.stringify(resolutionDivisors));
+ }
+});
+
+test('denoiseRadiance refuses a buffer shorter than width times height (#2545)', async () => {
+ const pixels = 16;
+ const full = () => ({
+ width: 4, height: 4, color: new Float32Array(pixels * 3).fill(0.5), albedo: new Float32Array(pixels * 3).fill(0.5),
+ normal: new Float32Array(pixels * 3).fill(0.5), depth: new Float32Array(pixels).fill(1), variance: new Float32Array(pixels).fill(0.1),
+ });
+ assert.equal(denoiseRadiance(full()).some(Number.isNaN), false);
+ for (const name of ['color', 'albedo', 'normal', 'depth', 'variance']) {
+ const inputs = full();
+ inputs[name] = inputs[name].subarray(0, 4);
+ assert.throws(() => denoiseRadiance(inputs), new RegExp(`denoiseRadiance: ${name} has 4 values`), name);
+ }
+});