Skip to content

3D engine that AI agents drive

Keep the real-time tracer's scene and GL objects when a scene is refused (#2576)

Nguyen Xuan And9d2f6d70abd
diff --git a/changes/2576.md b/changes/2576.md
new file mode 100644
index 00000000..d87e2943
--- /dev/null
+++ b/changes/2576.md
@@ -0,0 +1 @@
+- The real-time path tracer keeps its GL objects when a scene or kernel is refused at creation and keeps the working scene when `update` refuses a new one (#2576, #2577)
diff --git a/changes/2578.md b/changes/2578.md
new file mode 100644
index 00000000..735e9fe9
--- /dev/null
+++ b/changes/2578.md
@@ -0,0 +1 @@
+- A traced subsurface block with a radius that is not three numbers in range, or a NaN weight or scale, is refused with the field name (#2578)
diff --git a/docs/path-tracer.md b/docs/path-tracer.md
index d4d882b1..c197b144 100644
--- a/docs/path-tracer.md
+++ b/docs/path-tracer.md
@@ -59,7 +59,7 @@ The sunlit floor patch agrees to within a stop (158.8, 127.2, 82.1 against 134.2
## Subsurface
-A part with a material `subsurface` weight above 0 sends that share of its diffuse light through a bounded random walk, after the Random Walk model of Blender's Principled BSDF (issue #283). The walk starts inward from the hit with a cosine-weighted direction, scatters isotropically with a per-channel mean free path of radius times scale in metres (one channel draws the distance and the other two are weighted by the mean density, so every channel stays unbiased), and leaves where it meets the part's own surface; there the path continues as white diffuse light with the walk's throughput, lit by every light. The colour is the block's `color`, or the base colour, mapped to a single scattering albedo with the fit Cycles uses, so a colour of 1 gives an albedo of 1 and gains no energy. A walk ends after 32 scattering events (`SUBSURFACE_WALK_STEPS`) or when it meets another part, and then its path ends. A point with no surface of its own behind it is a card: half of the colour is reflected on the near side and half is transmitted through it. The specular lobe and clear coat stay as they are, and a weight of 0 takes the unchanged code path (the same samples and pixels). The GPU tracer traces the block too (`src/path-tracer-gpu-subsurface.js`): the walk is compiled into its kernel only for a scene with a part above weight 0, the block sits in its own table of two texels per material, and a scene without one compiles and draws the kernel it always did (foliage and glass drawn by the kernel before and after this change are byte identical). On the `subsurface` reference scene (960 by 540, 64 samples, FLIP against the Cycles render with subsurface on) the GPU tracer scores 0.0795 with weight 1 and 0.0876 with weight 0, the CPU tracer 0.0795 and 0.0875, and GPU against CPU is 0.0029 and 0.0014 (measured 2026-11-04). The kernel with the walk compiled in cold in 42.8 s against 7.2 s for the plain one, since a second place that traces rays is inlined again.
+A part with a material `subsurface` weight above 0 sends that share of its diffuse light through a bounded random walk, after the Random Walk model of Blender's Principled BSDF (issue #283). The walk starts inward from the hit with a cosine-weighted direction, scatters isotropically with a per-channel mean free path of radius times scale in metres (one channel draws the distance and the other two are weighted by the mean density, so every channel stays unbiased), and leaves where it meets the part's own surface; there the path continues as white diffuse light with the walk's throughput, lit by every light. The colour is the block's `color`, or the base colour, mapped to a single scattering albedo with the fit Cycles uses, so a colour of 1 gives an albedo of 1 and gains no energy. A walk ends after 32 scattering events (`SUBSURFACE_WALK_STEPS`) or when it meets another part, and then its path ends. A point with no surface of its own behind it is a card: half of the colour is reflected on the near side and half is transmitted through it. The specular lobe and clear coat stay as they are, and a weight of 0 takes the unchanged code path (the same samples and pixels). The GPU tracer traces the block too (`src/path-tracer-gpu-subsurface.js`): the walk is compiled into its kernel only for a scene with a part above weight 0, the block sits in its own table of two texels per material, and a scene without one compiles and draws the kernel it always did (foliage and glass drawn by the kernel before and after this change are byte identical). On the `subsurface` reference scene (960 by 540, 64 samples, FLIP against the Cycles render with subsurface on) the GPU tracer scores 0.0795 with weight 1 and 0.0876 with weight 0, the CPU tracer 0.0795 and 0.0875, and GPU against CPU is 0.0029 and 0.0014 (measured 2026-11-04). The kernel with the walk compiled in cold in 42.8 s against 7.2 s for the plain one, since a second place that traces rays is inlined again. The block is checked with `validateSubsurface` when the scene is built, so a radius that is not three numbers in range throws and names the field.
## Dispersion (issue #1714)
@@ -348,7 +348,7 @@ Proof of the three checks of issue #623 on 2026-11-11 (`node bench/reference/pro
## Real-time hybrid view (issue #624)
-`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:
+`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: A scene it refuses (no parts, over the part cap, local volumes) is checked before any GL object is made or released, so a refused `update({ parts })` keeps the scene the tracer had and a refused first scene leaves nothing allocated.
- **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.
- **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.
diff --git a/src/path-tracer-realtime.js b/src/path-tracer-realtime.js
index f02fdcac..81d01fd3 100644
--- a/src/path-tracer-realtime.js
+++ b/src/path-tracer-realtime.js
@@ -14,6 +14,13 @@ import { cacheCellSizes, noteIgnoredClipStart, resolveRealtimeOptions, viewsMatc
// static). It shares the WebGL2 context of `traceOnGpu`, so one render at a time owns it. The pieces:
// path-tracer-radiance-cache.js, path-tracer-temporal-denoise.js, path-tracer-reprojection.js.
+// Builds and checks a scene before any GL object is made or released, so a refused scene leaves the tracer as it was.
+function prepareTraceScene(parts, environment) {
+ const traceScene = buildTraceScene(parts, environment, { gpuTriangleLimit: gpuTriangleLimit() });
+ refuseLocalVolumes(traceScene, 'the WebGL realtime path tracer');
+ return traceScene;
+}
+
/**
* `scene` is `{ parts, environment, camera }` as `renderPathTracedImage` takes them. `options`: `width` and `height` of the
* output, `bounces` (2), `resolutionDivisor` (2: the tracing size is half the output), `seed`, `lightSelection`
@@ -40,6 +47,7 @@ export async function createRealtimeTracer(scene, rawOptions = {}) {
gl.canvas.width = outputWidth;
gl.canvas.height = outputHeight;
+ const firstTraceScene = prepareTraceScene(scene.parts, scene.environment ?? {});
const radianceTextures = [createFloatTexture(gl, traceWidth, traceHeight), createFloatTexture(gl, traceWidth, traceHeight)];
const normalTextures = [createFloatTexture(gl, traceWidth, traceHeight), createFloatTexture(gl, traceWidth, traceHeight)];
const albedoTexture = createFloatTexture(gl, traceWidth, traceHeight);
@@ -63,10 +71,9 @@ export async function createRealtimeTracer(scene, rawOptions = {}) {
let resetHistory = true;
let disposed = false;
- const loadScene = (parts, environment) => {
+ const loadScene = nextTraceScene => {
releaseResources(gl);
- traceScene = buildTraceScene(parts, environment, { gpuTriangleLimit: gpuTriangleLimit() });
- refuseLocalVolumes(traceScene, 'the WebGL realtime path tracer');
+ traceScene = nextTraceScene;
const kernel = getKernel(sceneUsesSubsurface(traceScene.materials), false, options);
program = kernel.program;
compileSeconds = kernel.compileSeconds;
@@ -83,7 +90,21 @@ export async function createRealtimeTracer(scene, rawOptions = {}) {
resetHistory = true;
};
- loadScene(scene.parts, scene.environment ?? {});
+ const dispose = () => {
+ disposed = true;
+ cache.dispose();
+ denoiser.dispose();
+ for (const texture of [...radianceTextures, ...normalTextures, albedoTexture, recordTexture]) gl.deleteTexture(texture);
+ for (const framebuffer of traceFramebuffers) gl.deleteFramebuffer(framebuffer);
+ releaseResources(gl);
+ };
+
+ try {
+ loadScene(firstTraceScene);
+ } catch (error) {
+ dispose();
+ throw error;
+ }
const traceOneSample = () => {
gl.useProgram(program);
@@ -113,7 +134,7 @@ export async function createRealtimeTracer(scene, rawOptions = {}) {
/** A new scene: the radiance cache and the denoiser's history start over. */
update({ parts, environment }) {
- if (parts) loadScene(parts, environment ?? {});
+ if (parts) loadScene(prepareTraceScene(parts, environment ?? {}));
},
/** Forgets the denoiser's history (the cache stays: it only depends on the scene). */
@@ -158,13 +179,6 @@ export async function createRealtimeTracer(scene, rawOptions = {}) {
return { width: outputWidth, height: outputHeight, rgba };
},
- dispose() {
- disposed = true;
- cache.dispose();
- denoiser.dispose();
- for (const texture of [...radianceTextures, ...normalTextures, albedoTexture, recordTexture]) gl.deleteTexture(texture);
- for (const framebuffer of traceFramebuffers) gl.deleteFramebuffer(framebuffer);
- releaseResources(gl);
- },
+ dispose,
};
}
diff --git a/src/path-tracer-subsurface.js b/src/path-tracer-subsurface.js
index 997df63f..8a0776cc 100644
--- a/src/path-tracer-subsurface.js
+++ b/src/path-tracer-subsurface.js
@@ -1,5 +1,5 @@
import { buildFrame } from './path-tracer-shading.js';
-import { subsurfaceUniformValues } from './subsurface-limits.js';
+import { subsurfaceUniformValues, validateSubsurface } from './subsurface-limits.js';
// Subsurface scattering for the path tracer, after the Random Walk model of Blender's Principled BSDF: light that enters
// a part walks through it with an isotropic phase function and per-channel mean free path (radius times scale, in metres),
@@ -14,7 +14,9 @@ export const WALK_OUTCOME = Object.freeze({ exit: 0, thin: 1, lost: 2 });
/** The traced form of a material's subsurface block: null when the weight is 0, so those parts take the unchanged code path. */
export function resolveTraceSubsurface(block) {
- if (!block || !(block.weight > 0)) return null;
+ if (!block) return null;
+ validateSubsurface(block);
+ if (!(block.weight > 0)) return null;
const [weight, ...rest] = subsurfaceUniformValues(block);
const meanFreePath = rest.slice(0, CHANNELS).map(length => Math.max(length, MINIMUM_FREE_PATH));
const color = rest[CHANNELS] < 0 ? null : rest.slice(CHANNELS, CHANNELS * 2);
diff --git a/tests/path-tracer-realtime-setup.test.js b/tests/path-tracer-realtime-setup.test.js
new file mode 100644
index 00000000..5b2d6f68
--- /dev/null
+++ b/tests/path-tracer-realtime-setup.test.js
@@ -0,0 +1,87 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { box } from '../src/geometry.js';
+import { resolveTraceSubsurface } from '../src/path-tracer-subsurface.js';
+
+// A stand-in WebGL2 context that accepts every call and counts the GL objects it hands out and takes back.
+function createFakeContext() {
+ class FakeFramebuffer {}
+ globalThis.WebGLFramebuffer = FakeFramebuffer;
+ const counts = { texture: 0, framebuffer: 0, program: 0, deleted: { texture: 0, framebuffer: 0, program: 0 } };
+ const constants = new Map();
+ const handlers = {
+ createTexture: () => { counts.texture++; return {}; },
+ createFramebuffer: () => { counts.framebuffer++; return new FakeFramebuffer(); },
+ createProgram: () => { counts.program++; return { index: counts.program }; },
+ deleteTexture: () => { counts.deleted.texture++; },
+ deleteFramebuffer: () => { counts.deleted.framebuffer++; },
+ deleteProgram: () => { counts.deleted.program++; },
+ getParameter: () => 16384,
+ getShaderParameter: () => true,
+ getProgramParameter: program => program.index !== counts.failingProgram,
+ getUniformLocation: () => ({}),
+ getExtension: () => ({}),
+ getShaderInfoLog: () => '',
+ getProgramInfoLog: () => '',
+ checkFramebufferStatus: () => gl.FRAMEBUFFER_COMPLETE,
+ };
+ const gl = new Proxy({ canvas: {} }, {
+ get(target, name) {
+ if (name in target) return target[name];
+ if (name in handlers) return handlers[name];
+ if (/^[A-Z0-9_]+$/.test(name)) {
+ if (!constants.has(name)) constants.set(name, constants.size + 1);
+ return constants.get(name);
+ }
+ return () => ({});
+ },
+ });
+ globalThis.OffscreenCanvas = class { getContext() { return gl; } };
+ return counts;
+}
+
+const counts = createFakeContext();
+const { createRealtimeTracer } = await import('../src/path-tracer-realtime.js');
+const WALL = { name: 'wall', geometry: box(), material: { color: [1, 1, 1], roughness: 1, metallic: 0 } };
+const CAMERA = { eye: [0, 0, 3], target: [0, 0, 0], up: [0, 1, 0], fov: 30 };
+
+const TEXTURES_AND_FRAMEBUFFERS = ['texture', 'framebuffer'];
+
+function liveObjects(kinds = ['texture', 'framebuffer', 'program']) {
+ return kinds.map(kind => counts[kind] - counts.deleted[kind]);
+}
+
+test('a real-time tracer that cannot load its scene gives back the GL objects it made', async () => {
+ const before = liveObjects();
+ await assert.rejects(createRealtimeTracer({ parts: [] }), /1 to 1024 parts/);
+ assert.deepEqual(liveObjects(), before);
+});
+
+test('a real-time tracer whose kernel does not build gives back the GL objects it made', async () => {
+ const before = liveObjects(TEXTURES_AND_FRAMEBUFFERS);
+ const passProgramCount = 5;
+ counts.failingProgram = counts.program + passProgramCount + 1;
+ await assert.rejects(createRealtimeTracer({ parts: [WALL] }));
+ counts.failingProgram = null;
+ assert.deepEqual(liveObjects(TEXTURES_AND_FRAMEBUFFERS), before);
+});
+
+test('a refused scene update keeps the scene the tracer already has', async () => {
+ const tracer = await createRealtimeTracer({ parts: [WALL] });
+ const deletedBefore = counts.deleted.texture;
+ assert.throws(() => tracer.update({ parts: [] }), /1 to 1024 parts/);
+ assert.equal(counts.deleted.texture, deletedBefore, 'the textures of the working scene were deleted');
+ assert.doesNotThrow(() => tracer.frame(CAMERA));
+ tracer.dispose();
+});
+
+test('a traced subsurface block that is not three radii in range is refused with the field name', () => {
+ assert.throws(() => resolveTraceSubsurface({ weight: 1, radius: 1 }), /subsurface\.radius must be three numbers/);
+ assert.throws(() => resolveTraceSubsurface({ weight: 1, radius: [NaN, 1, 1] }), /subsurface\.radius must be three numbers/);
+ assert.throws(() => resolveTraceSubsurface({ weight: 1, scale: Infinity }), /subsurface\.scale must be between/);
+ assert.throws(() => resolveTraceSubsurface({ weight: NaN }), /subsurface\.weight must be between/);
+ assert.deepEqual(resolveTraceSubsurface({ weight: 1, radius: [1, 0.2, 0.1], scale: 0.05 }).meanFreePath.map(value => +value.toFixed(6)), [0.05, 0.01, 0.005]);
+ assert.equal(resolveTraceSubsurface({ weight: 0 }), null);
+ assert.equal(resolveTraceSubsurface(undefined), null);
+});