Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Local volumes: one shared refusal, early validation, reference scene (part of #710)

Nguyen Xuan An9ca443015d34
diff --git a/bench/reference/README.md b/bench/reference/README.md
index a5182c91..b0259e21 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -1868,3 +1868,7 @@ What it says (measured, causes marked):
- Not isolated: why the lit side of `-a` and `-b` is 25 to 30 percent dim. Candidates still to test, one each: fog in the beam taking light that Cycles keeps, the sun bounce lights (about 0.3 gain) lighting walls rather than the lit floor, and the unshadowed bounce lights lifting the shadow side.
No engine change was made and no frame cost changes. The megacity and mountain options were not re-measured in this pass. Box 2 stays open for `temple-hall-b`, `-c` and `-rose`.
+
+## Local volumes (issue #710)
+
+`node bench/reference/local-volumes.mjs gpu` (or `cpu` for SwiftShader) renders a smoky room with a glowing puff, with and without `environment.localVolumes`, writes `images/local-volumes.png` and `images/local-volumes-plain.png`, and prints the frame time. It is not scored against Blender: Cycles has no counterpart for these fields, so it sits outside the 23 scored scenes. Frame time on the RTX 3060 shared with other jobs (2026-11-10, 960 x 540, 4x MSAA, median of 200 frames, three alternating rounds): 1.34, 1.25 and 1.07 ms without volumes, 2.13, 2.11 and 1.54 ms with the haze box and the puff, so the two volumes cost about 0.5 to 0.9 ms (noisy).
diff --git a/bench/reference/images/local-volumes-plain.png b/bench/reference/images/local-volumes-plain.png
new file mode 100644
index 00000000..becbbf65
Binary files /dev/null and b/bench/reference/images/local-volumes-plain.png differ
diff --git a/bench/reference/images/local-volumes.png b/bench/reference/images/local-volumes.png
new file mode 100644
index 00000000..ac9568a0
Binary files /dev/null and b/bench/reference/images/local-volumes.png differ
diff --git a/bench/reference/local-volumes.mjs b/bench/reference/local-volumes.mjs
new file mode 100644
index 00000000..dd401272
--- /dev/null
+++ b/bench/reference/local-volumes.mjs
@@ -0,0 +1,101 @@
+// A smoky room with a glowing puff (issue #710): the picture and the frame time of the room with and without environment.localVolumes.
+// node bench/reference/local-volumes.mjs [gpu|cpu]
+// Writes bench/reference/images/local-volumes.png (with volumes) and local-volumes-plain.png (without), and prints the frame times.
+import { writeFileSync } from 'node:fs';
+import { constants, setPriority } from 'node:os';
+import { chromium } from 'playwright';
+import { createServer } from 'vite';
+
+const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+const BACKEND_ARGUMENTS = {
+ gpu: ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'],
+ cpu: ['--enable-webgl', '--ignore-gpu-blocklist', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'],
+};
+const [backend = 'gpu'] = process.argv.slice(2);
+const IMAGE_DIRECTORY = new URL('./images/', import.meta.url);
+
+// Runs in the page. Three rounds of 200 frames per side, the order alternating each round so a drifting machine load favors neither.
+async function measureSmokyRoom({ width, height, rounds, warmupFrames, measuredFrames }) {
+ const { box } = await import('/src/geometry.js');
+ const { Renderer67 } = await import('/src/renderer.js');
+ await import('/src/fog-shader.js');
+
+ const placed = (translation, scale, color) => ({
+ geometry: box(0, 1),
+ matrix: new Float32Array([scale[0], 0, 0, 0, 0, scale[1], 0, 0, 0, 0, scale[2], 0, translation[0], translation[1], translation[2], 1]),
+ material: { tag: 'surface', color, metallic: 0, roughness: 0.8, emission: 0 },
+ });
+ const room = [
+ placed([0, -0.1, 0], [8, 0.2, 8], [0.55, 0.5, 0.45]),
+ placed([0, 2, -4.1], [8, 4.2, 0.2], [0.6, 0.58, 0.55]),
+ placed([-4.1, 2, 0], [0.2, 4.2, 8], [0.5, 0.52, 0.6]),
+ placed([4.1, 2, 0], [0.2, 4.2, 8], [0.6, 0.5, 0.5]),
+ placed([1.8, 0.5, -1.5], [1, 1, 1], [0.3, 0.3, 0.35]),
+ ];
+ const smoke = { shape: 'box', center: [0, 1.6, -0.5], size: [7, 3, 7], density: 0.18, falloff: 0.6, absorption: [0.7, 0.8, 1], noiseAmount: 0.5, noiseScale: 0.8, steps: 24 };
+ const puff = { shape: 'sphere', center: [-0.4, 1.1, -1.2], radius: 0.7, density: 1.5, falloff: 0.5, emission: [1, 0.45, 0.12], emissionStrength: 6, noiseAmount: 0.6, noiseScale: 2, steps: 24 };
+ const camera = { eye: [0, 1.6, 3.6], target: [0, 1.1, -1], fov: 55, time: 0 };
+ const baseEnvironment = { keyIntensity: 1, fillIntensity: 0.3, ambientIntensity: 0.5 };
+
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ document.body.append(canvas);
+ const snapshot = document.createElement('canvas');
+ snapshot.width = width;
+ snapshot.height = height;
+
+ const pixel = new Uint8Array(4);
+ const runSide = (withVolumes, frames) => {
+ const renderer = new Renderer67(canvas, room, { hdr: true, depth: true, samples: 4, pixelRatio: 1, ground: false });
+ const environment = withVolumes ? { ...baseEnvironment, localVolumes: [smoke, puff] } : baseEnvironment;
+ const draw = () => {
+ renderer.render({ ...camera, environment });
+ renderer.context.readPixels(0, 0, 1, 1, renderer.context.RGBA, renderer.context.UNSIGNED_BYTE, pixel);
+ };
+ for (let index = 0; index < warmupFrames; index++) draw();
+ const milliseconds = [];
+ for (let index = 0; index < frames; index++) {
+ const started = performance.now();
+ draw();
+ milliseconds.push(performance.now() - started);
+ }
+ snapshot.getContext('2d').drawImage(canvas, 0, 0);
+ const glError = renderer.context.getError();
+ renderer.dispose();
+ milliseconds.sort((first, second) => first - second);
+ return { median: milliseconds[milliseconds.length >> 1], minimum: milliseconds[0], maximum: milliseconds[milliseconds.length - 1], glError };
+ };
+
+ const timings = { plain: [], volumes: [] };
+ for (let round = 0; round < rounds; round++) {
+ for (const withVolumes of round % 2 ? [true, false] : [false, true]) {
+ timings[withVolumes ? 'volumes' : 'plain'].push(runSide(withVolumes, measuredFrames));
+ }
+ }
+ runSide(false, 1);
+ const plainImage = snapshot.toDataURL('image/png').split(',')[1];
+ runSide(true, 1);
+ const volumesImage = snapshot.toDataURL('image/png').split(',')[1];
+ return { timings, plainImage, volumesImage };
+}
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
+await server.listen();
+const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: BACKEND_ARGUMENTS[backend] });
+try {
+ const options = { width: 960, height: 540, rounds: 3, warmupFrames: 20, measuredFrames: 200 };
+ const page = await browser.newPage({ viewport: { width: options.width, height: options.height } });
+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/`);
+ const result = await page.evaluate(measureSmokyRoom, options);
+ writeFileSync(new URL('local-volumes.png', IMAGE_DIRECTORY), Buffer.from(result.volumesImage, 'base64'));
+ writeFileSync(new URL('local-volumes-plain.png', IMAGE_DIRECTORY), Buffer.from(result.plainImage, 'base64'));
+ const summary = Object.fromEntries(Object.entries(result.timings).map(([side, rounds]) => [side, rounds.map(round => Number(round.median.toFixed(2)))]));
+ const glErrors = Object.values(result.timings).flat().filter(round => round.glError !== 0).length;
+ console.log(JSON.stringify({ backend, width: options.width, height: options.height, frames: options.measuredFrames, medianMillisecondsPerRound: summary, glErrors }, null, 1));
+ if (glErrors > 0) process.exitCode = 1;
+} finally {
+ await browser.close();
+ await server.close();
+}
diff --git a/docs/volumetric.md b/docs/volumetric.md
index bfe4d325..afc9108e 100644
--- a/docs/volumetric.md
+++ b/docs/volumetric.md
@@ -127,4 +127,12 @@ In a scene with an irradiance grid (`bake.irradianceGrid`) the bounce term is th
| `noiseAmount`, `noiseScale` | `0`, `1` | Raster only. `noiseAmount` `0` to `1` breaks the density up with the cloud noise at `noiseScale` cells per unit |
| `steps` | `16` | `4` to `32` samples through the volume |
-Each volume is marched on its own between its entry and its exit, cut at the first surface, and the volumes are composited nearest entry first. Overlapping volumes are therefore an approximation. Local volumes are drawn before `volumeFog`, so a fog in front of a puff also dims it. They need the same renderer as the fog (`hdr: true`, `depth: true`, an opaque canvas) and are drawn in the post pass, so they are not in the lightmap bake. The path tracer traces them on `backend: "cpu"` with the same fields except the noise, and refuses them on the GPU backends rather than leaving them out. Cost grows with the covered pixels times `steps` times the number of volumes that the pixel's ray crosses; a ray that misses every volume pays only the interval test.
+Each volume is marched on its own between its entry and its exit, cut at the first surface, and the volumes are composited nearest entry first. Overlapping volumes are therefore an approximation. Local volumes are drawn before `volumeFog`, so a fog in front of a puff also dims it. They need the same renderer as the fog (`hdr: true`, `depth: true`, an opaque canvas) and are drawn in the post pass, so they are not in the lightmap bake. The path tracer traces them on `backend: "cpu"` with the same fields except the noise, and every other tracer entry point (backends `gpu` and `native`, the progressive and realtime tracers, the GPU light bake) throws instead of leaving them out. Cost grows with the covered pixels times `steps` times the number of volumes that the pixel's ray crosses; a ray that misses every volume pays only the interval test.
+
+### Reference render and frame time
+
+`node bench/reference/local-volumes.mjs gpu` draws a smoky room (a haze box with noise and a glowing noisy puff, `bench/reference/images/local-volumes.png`) and the same room without volumes (`local-volumes-plain.png`), and times both: 960 x 540, 4x MSAA, median of 200 frames with readback, three rounds with the order alternating. On the RTX 3060 shared with other jobs (2026-11-10) the room without volumes took 1.34, 1.25 and 1.07 ms, and with the two volumes 2.13, 2.11 and 1.54 ms, so the pair costs about 0.5 to 0.9 ms at this size (noisy; treat it as a range).
+
+### Not covered yet
+
+Mesh bounds as a shape, the WebGPU and WebGL path tracers, the lightmap bake and path tracer noise are open work: mesh bounds #807, tracer noise and GPU tracers #808, the bake #809.
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index a3315dd9..26d3117f 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -881,12 +881,13 @@ window.__agentPreview = {
} else if (motionTime !== undefined) {
record.scene.sampleMotion(motionTime);
}
- const [{ createCamera, describeIgnoredFeatures }, { buildTraceScene }, pack, { buildNativeInput }] = await Promise.all([
+ const [{ createCamera, describeIgnoredFeatures }, { buildTraceScene, refuseLocalVolumes }, pack, { buildNativeInput }] = await Promise.all([
import('../src/path-tracer.js'), import('../src/path-tracer-scene.js'), import('../src/path-tracer-gpu-pack.js'),
import('../packages/render-native/pack-input.mjs'),
]);
const environment = { ...record.scene.environment, map: agentEnvironmentMap(record.scene.environment) };
const traceScene = buildTraceScene(record.scene.parts, environment);
+ refuseLocalVolumes(traceScene, 'the native path tracer');
const camera = createCamera(record.scene.camera, options.width, options.height);
const input = buildNativeInput(traceScene, camera, options, pack);
const tables = encodeNativeTables(input);
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index a1a02228..63c03939 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -270,7 +270,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
maxSpotLights: MAX_SPOT_LIGHTS, maxAreaLights: MAX_AREA_LIGHTS,
localShadows: Object.freeze({ lights: Object.freeze(['pointLights', 'spotLights']), atlasTiles: 24, pointLightTiles: 6, spotLightTiles: 1, tileSize: 512 }),
lightLinking: Object.freeze({ fields: Object.freeze(['environment.keyAffects', 'pointLights[].affects', 'spotLights[].affects', 'areaLights[].affects']), unlisted: 'a light without affects lights every node', unknownNode: 'rejected', bake: 'honoured', pathTracer: 'ignored, named in report.ignored' }),
- localVolumes: Object.freeze({ field: 'environment.localVolumes', maximum: 8, shapes: Object.freeze(['box', 'sphere']), fields: 'shape, center, size (box) or radius (sphere), density 0-100 (1), falloff 0-1 (0.5), absorption rgb 0-1 (1,1,1), emission rgb 0-1, emissionStrength 0-1000 (1), noiseAmount 0-1 (0), noiseScale (1), steps 4-32 (16)', note: 'Absorb and emit, no scattering; needs hdr and depth like volumeFog; noise is raster only; path tracer: backend cpu only.' }),
+ localVolumes: Object.freeze({ field: 'environment.localVolumes', maximum: 8, shapes: Object.freeze(['box', 'sphere']), fields: 'shape, center, size (box) or radius (sphere), density 0-100 (1), falloff 0-1 (0.5), absorption rgb 0-1 (1,1,1), emission rgb 0-1, emissionStrength 0-1000 (1), noiseAmount 0-1 (0), noiseScale (1), steps 4-32 (16)', note: 'Absorb and emit, no scattering; needs hdr and depth like volumeFog; noise is raster only; path tracer: backend cpu only (gpu and native throw).' }),
shadowCascades: Object.freeze({ field: 'environment.shadowCascades', counts: Object.freeze([0, 1, 2, 3, 4]), zero: 'one shadow map', automatic: 'three cascades when shadow.extent is above 40 and the field is unset', maximumDistance: 150, note: 'volume fog and water read the single map' }),
lineArt: Object.freeze({ field: 'environment.lines', fields: 'width px 0.25-16 (1.5), color, boundaries, creaseAngle deg (35), depthJump (0.08), toon steps 0-8, polylines [{points [x,y,z] 2-256, color, width, depthTest, closed}] max 64; {} turns on, null clears; material toon 0-8', note: 'docs/line-art.md' }),
viewTransform: Object.freeze({
diff --git a/src/fog-shader.js b/src/fog-shader.js
index 8701956d..c2c76ad2 100644
--- a/src/fog-shader.js
+++ b/src/fog-shader.js
@@ -74,13 +74,21 @@ function bindFieldAndLights(renderer, post, volume) {
context.uniform4fv(post.uniforms['volumeLightCones[0]'], lights.cones);
}
-// The local volumes of the frame (environment.localVolumes): validated, packed and bound. Their uniforms exist only in a program
-// with the local step compiled in, and a program without it never reaches this function.
-function bindLocalVolumes(renderer, post, volumes, frame) {
- const context = renderer.context;
+// The local volumes of the frame (environment.localVolumes), checked and packed once before the post program is chosen, so a bad
+// field or a renderer without depth or HDR throws before any program is bound. Returns the count packed, or 0 for an empty list.
+function prepareLocalVolumes(renderer, input) {
+ const volumes = resolveLocalVolumes(input, 'environment.localVolumes');
+ if (volumes.length === 0) return 0;
if (!renderer.depth || !renderer.hdr || renderer.transparent || renderer.benchmark) throw new Error('Local volumes require depth:true, active HDR and an opaque canvas');
const buffers = (renderer.localVolumeBuffers ??= createLocalVolumeBuffers());
- packLocalVolumes(resolveLocalVolumes(volumes, 'environment.localVolumes'), buffers);
+ packLocalVolumes(volumes, buffers);
+ return buffers.count;
+}
+
+// Uploads the packed volumes. Their uniforms exist only in a program with the local step compiled in.
+function bindLocalVolumes(renderer, post, frame) {
+ const context = renderer.context;
+ const buffers = renderer.localVolumeBuffers;
const locate = name => (post.uniforms[name] ??= context.getUniformLocation(post.program, name));
context.uniform1i(locate('localVolumeCount'), buffers.count);
context.uniform1f(locate('localOrthographic'), frame.projection === 'orthographic' ? 1 : 0);
@@ -200,8 +208,8 @@ function packLights(renderer) {
}
registerShaderFeatureCode('volumeFog', {
- // The JavaScript halfSize, which the renderer calls for a frame that draws a volume fog.
- support: { packLights, bindUniforms, usesDetail: fogUsesDetail, bindLocalVolumes },
+ // The JavaScript half, which the renderer calls for a frame that draws a volume fog.
+ support: { packLights, bindUniforms, usesDetail: fogUsesDetail, prepareLocalVolumes, bindLocalVolumes },
localDeclarations: LOCAL_VOLUME_DECLARATIONS,
localFunctions: LOCAL_VOLUME_FUNCTIONS,
postDeclarations: `
@@ -354,7 +362,7 @@ float sunOpticalDepth(vec3 position, vec3 towardSun) {
return volumeDensity * sum * exitDistance / 3.0;
}
// The sun's in-scatter at a point. The octave sum approximates multiple scattering (Wrenninge et al. 2015, "Oz: the great and
-// volumetric"): octave n scatters multiScatter^n as much, sees halfSize^n of the extinction and has halfSize^n of the anisotropy.
+// volumetric"): octave n scatters multiScatter^n as much, sees half^n of the extinction and has half^n of the anisotropy.
float keyInScatter(float cosine, float opticalDepth) {
float total = 0.0;
float weight = 1.0;
diff --git a/src/light-bake-gpu.js b/src/light-bake-gpu.js
index fb820fc9..7658c165 100644
--- a/src/light-bake-gpu.js
+++ b/src/light-bake-gpu.js
@@ -1,4 +1,4 @@
-import { buildTraceScene } from './path-tracer-scene.js';
+import { buildTraceScene, refuseLocalVolumes } from './path-tracer-scene.js';
import { checkBudget, checkedBakeSize, finishLightmaps, planLightmaps, rasterizeEntries, traceLightmaps } from './light-bake.js';
// The GPU side of the light bake: the texels of every part go to the path tracer's kernel in one batch, which starts a
@@ -59,6 +59,7 @@ async function gatherOnGpu(plan, settings, rasterized, shouldStop) {
const environment = traceEnvironment(plan);
const texels = packCoveredTexels(rasterized);
const scene = buildTraceScene(plan.parts, environment);
+ refuseLocalVolumes(scene, 'the GPU light bake');
const traceTexels = settings.texelTracer ?? await loadTexelTracer(settings.backend);
const traced = await traceTexels(scene, texels, { samples: settings.samples, bounces: settings.bounces, seed: BAKE_SEED, fireflyClamp: NO_FIREFLY_CLAMP }, shouldStop);
let next = 0;
diff --git a/src/path-tracer-progressive.js b/src/path-tracer-progressive.js
index c0aeb301..d87fae82 100644
--- a/src/path-tracer-progressive.js
+++ b/src/path-tracer-progressive.js
@@ -1,4 +1,4 @@
-import { buildTraceScene } from './path-tracer-scene.js';
+import { buildTraceScene, refuseLocalVolumes } from './path-tracer-scene.js';
import { denoiseRadiance } from './path-tracer-denoise.js';
import { resolveLightSelection } from './path-tracer-light-tree.js';
import { createCamera, normalizePathTracerOptions, toneMapToRgba8 } from './path-tracer.js';
@@ -43,6 +43,7 @@ export async function createProgressiveTracer(scene, rawOptions = {}, { resoluti
const loadScene = (parts, environment) => {
releaseResources(gl);
traceScene = buildTraceScene(parts, environment);
+ refuseLocalVolumes(traceScene, 'the progressive path tracer');
sceneOptions = { ...options, lightSelection: resolveLightSelection(options.lightSelection, traceScene.lights) };
const kernel = getKernel(sceneUsesSubsurface(traceScene.materials), false, sceneOptions);
program = kernel.program;
diff --git a/src/path-tracer-realtime-webgpu.js b/src/path-tracer-realtime-webgpu.js
index 86428153..aa59a1db 100644
--- a/src/path-tracer-realtime-webgpu.js
+++ b/src/path-tracer-realtime-webgpu.js
@@ -1,4 +1,4 @@
-import { buildTraceScene } from './path-tracer-scene.js';
+import { buildTraceScene, refuseLocalVolumes } from './path-tracer-scene.js';
import { createCamera } from './path-tracer.js';
import { prepareRealtimeKernel } from './path-tracer-webgpu.js';
import { REALTIME_KERNEL_PIECES } from './path-tracer-realtime-webgpu-kernel.js';
@@ -70,6 +70,7 @@ export async function createWebGpuRealtimeTracer(scene, resolved, suppliedCanvas
currentParts = parts;
currentEnvironment = environment;
traceScene = buildTraceScene(parts, environment);
+ refuseLocalVolumes(traceScene, 'the WebGPU realtime path tracer');
const next = await prepareRealtimeKernel(traceScene, options, REALTIME_KERNEL_PIECES);
const previousKernel = kernel;
kernel = next;
diff --git a/src/path-tracer-realtime.js b/src/path-tracer-realtime.js
index 26878dac..c68b39e1 100644
--- a/src/path-tracer-realtime.js
+++ b/src/path-tracer-realtime.js
@@ -1,4 +1,4 @@
-import { buildTraceScene } from './path-tracer-scene.js';
+import { buildTraceScene, refuseLocalVolumes } from './path-tracer-scene.js';
import { createCamera } from './path-tracer.js';
import { getContext, getKernel, releaseResources, setSceneUniforms, uploadScene } from './path-tracer-gpu.js';
import { sceneUsesSubsurface } from './path-tracer-gpu-pack.js';
@@ -66,6 +66,7 @@ export async function createRealtimeTracer(scene, rawOptions = {}) {
const loadScene = (parts, environment) => {
releaseResources(gl);
traceScene = buildTraceScene(parts, environment);
+ refuseLocalVolumes(traceScene, 'the WebGL realtime path tracer');
const kernel = getKernel(sceneUsesSubsurface(traceScene.materials), false, options);
program = kernel.program;
compileSeconds = kernel.compileSeconds;
diff --git a/src/path-tracer-scene.js b/src/path-tracer-scene.js
index 3cdc55f2..d9dc833d 100644
--- a/src/path-tracer-scene.js
+++ b/src/path-tracer-scene.js
@@ -303,6 +303,12 @@ export function attachTracer(scene) {
return { ...scene, tracer: createTracer({ positions: scene.positions, indices: scene.indices, bvh: scene.bvh }) };
}
+/** Local volumes are traced by the CPU path tracer only. Every other tracer entry point calls this so none drops them silently. */
+export function refuseLocalVolumes(scene, tracerName) {
+ if (!scene.localVolumes) return;
+ throw new RangeError(`environment.localVolumes is traced by the CPU path tracer only; ${tracerName} cannot draw them. Use backend "cpu" or remove the volumes.`);
+}
+
export function buildTraceScene(parts, environment = {}) {
if (!Array.isArray(parts) || parts.length < 1 || parts.length > MAX_TRACE_PARTS) throw new RangeError(`A path trace takes 1 to ${MAX_TRACE_PARTS} parts.`);
const geometry = flattenParts(parts);
diff --git a/src/path-tracer.js b/src/path-tracer.js
index 73c3d2dd..0125af4e 100644
--- a/src/path-tracer.js
+++ b/src/path-tracer.js
@@ -1,7 +1,7 @@
import { cameraFieldOfView } from './camera.js';
import { pointLightFalloff } from './ray-query.js';
import { profileGain } from './light-profile.js';
-import { buildTraceScene, SUN_ANGULAR_RADIUS } from './path-tracer-scene.js';
+import { buildTraceScene, refuseLocalVolumes, SUN_ANGULAR_RADIUS } from './path-tracer-scene.js';
import { denoiseRadiance } from './path-tracer-denoise.js';
import { acesChannel, displayColor } from './view-transform.js';
import { VIEW_TRANSFORM_NAMES } from './view-transform-names.js';
@@ -1120,9 +1120,7 @@ export async function renderPathTracedImage({ parts, environment = {}, camera },
const { width, height } = options;
const view = createCamera(camera, width, height);
const scene = buildTraceScene(parts, environment);
- if (scene.localVolumes && options.backend !== 'cpu') {
- throw new RangeError(`environment.localVolumes is traced by the CPU path tracer only; use backend "cpu" or remove the volumes (backend "${options.backend}" was asked for).`);
- }
+ if (options.backend !== 'cpu') refuseLocalVolumes(scene, `backend "${options.backend}"`);
const pixelCount = width * height;
const buffers = {
color: new Float32Array(pixelCount * 3), albedo: new Float32Array(pixelCount * 3), normal: new Float32Array(pixelCount * 3),
diff --git a/src/renderer.js b/src/renderer.js
index b5a21e59..1ce35068 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -1849,6 +1849,12 @@ export class Renderer67 {
context.drawArrays(context.TRIANGLES, 0, 3);
}
+ // True when the frame draws local volumes. An empty list costs nothing; anything else is checked here, before a program is bound.
+ prepareLocalVolumes(input) {
+ if (input === undefined || (Array.isArray(input) && input.length === 0)) return false;
+ return requireFeatureCode('volumeFog').support.prepareLocalVolumes(this, input) > 0;
+ }
+
// The post steps this frame uses. A step that is off costs nothing in a program that has it compiled out.
postStepsOf(frame, effects, volume, occluded, fogSky, localVolumes) {
const steps = [];
@@ -1918,7 +1924,7 @@ export class Renderer67 {
context.bindVertexArray(null);
const fogSky = this.fogSkyVisibility?.(this.sceneParts, volume, context, environment);
const fogSupport = volume.density > 0 ? requireFeatureCode('volumeFog').support : null;
- const localVolumes = environment.localVolumes?.length ? environment.localVolumes : null;
+ const localVolumes = this.prepareLocalVolumes(environment.localVolumes);
if (fogSupport) fogSupport.packLights(this);
else if (this.fogLightBuffers) this.fogLightBuffers.count = 0;
const post = this.selectPostProgram(this.postStepsOf(frame, effects, volume, occluded, fogSky, localVolumes));
@@ -1940,7 +1946,7 @@ export class Renderer67 {
context.bindTexture(context.TEXTURE_2D, this.depthTexture ?? this.whiteTexture);
context.uniform1i(post.uniforms.sceneDepth, 1);
fogSupport?.bindUniforms(this, post, volume, environment, frame);
- if (localVolumes) requireFeatureCode('volumeFog').support.bindLocalVolumes(this, post, localVolumes, frame);
+ if (localVolumes) requireFeatureCode('volumeFog').support.bindLocalVolumes(this, post, frame);
context.activeTexture(context.TEXTURE2);
context.bindTexture(context.TEXTURE_2D, effects.bloom.strength > 0 ? this.bloomTargets[1].texture : this.whiteTexture);
context.uniform1i(post.uniforms.bloomTexture, 2);
diff --git a/tests/local-volumes-entry-points.test.js b/tests/local-volumes-entry-points.test.js
new file mode 100644
index 00000000..2396fb17
--- /dev/null
+++ b/tests/local-volumes-entry-points.test.js
@@ -0,0 +1,121 @@
+// Local volumes (issue 710): the tracers that cannot draw them refuse them through one shared check, and the renderer rejects a bad
+// environment.localVolumes before it binds a post program. The browser test uses headless Chrome on SwiftShader and skips when
+// Chrome cannot start.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { freePort } from './helpers/free-port.js';
+import { buildTraceScene, refuseLocalVolumes } from '../src/path-tracer-scene.js';
+
+const GROUND = [{
+ name: 'ground',
+ geometry: {
+ positions: new Float32Array([-5, 0, 5, 5, 0, 5, 5, 0, -5, -5, 0, -5]),
+ normals: new Float32Array([0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]),
+ uvs: new Float32Array([0, 1, 1, 1, 1, 0, 0, 0]),
+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
+ },
+ material: { tag: 'surface', metallic: 0, roughness: 1, color: [0, 0, 0], ior: 1, emission: 1, emissiveColor: [1, 1, 1] },
+}];
+
+test('every tracer entry point refuses local volumes through one shared check', () => {
+ const withVolumes = buildTraceScene(GROUND, { localVolumes: [{ shape: 'sphere', center: [0, 1, 0], radius: 1 }] });
+ assert.throws(() => refuseLocalVolumes(withVolumes, 'the progressive path tracer'), /CPU path tracer only; the progressive path tracer cannot draw them/);
+ assert.doesNotThrow(() => refuseLocalVolumes(buildTraceScene(GROUND, {}), 'the progressive path tracer'));
+ assert.doesNotThrow(() => refuseLocalVolumes(buildTraceScene(GROUND, { localVolumes: [] }), 'the progressive path tracer'));
+});
+
+async function startServer(port) {
+ const server = spawn(process.execPath, ['node_modules/vite/bin/vite.js', '--host', '127.0.0.1', '--port', String(port), '--strictPort'], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
+ await new Promise((resolve, reject) => {
+ const timeout = setTimeout(() => reject(new Error('The dev server did not start.')), 30000);
+ server.stdout.on('data', (data) => {
+ if (/ready in/.test(data.toString())) {
+ clearTimeout(timeout);
+ resolve();
+ }
+ });
+ server.on('exit', (code) => {
+ clearTimeout(timeout);
+ reject(new Error(`The dev server exited ${code}.`));
+ });
+ });
+ return server;
+}
+
+async function probeInPage(page) {
+ const { box } = await import('/src/geometry.js');
+ const { Renderer67 } = await import('/src/renderer.js');
+ const { createProgressiveTracer } = await import('/src/path-tracer-progressive.js');
+ await import('/src/fog-shader.js');
+ const wall = { geometry: box(0, 1), matrix: new Float32Array([4, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0.2, 0, 0, 0, -0.1, 1]), material: { tag: 'unlit', color: [0.4, 0.4, 0.4], metallic: 0, roughness: 1, emission: 0 } };
+ const volume = [{ shape: 'sphere', center: [0, 0, 1], radius: 1 }];
+
+ const drawWith = (rendererOptions, localVolumes) => {
+ const canvas = document.createElement('canvas');
+ canvas.width = 32;
+ canvas.height = 32;
+ const renderer = new Renderer67(canvas, [wall], { samples: 1, pixelRatio: 1, ground: false, ...rendererOptions });
+ let choseProgram = false;
+ const originalSelect = renderer.selectPostProgram.bind(renderer);
+ renderer.selectPostProgram = (steps) => {
+ choseProgram = true;
+ return originalSelect(steps);
+ };
+ try {
+ renderer.render({ eye: [0, 0, 5], target: [0, 0, 0], fov: 40, time: 0, environment: { localVolumes } });
+ return { message: null, choseProgram };
+ } catch (failure) {
+ return { message: failure.message, choseProgram };
+ }
+ };
+
+ const result = {
+ objectWithoutLength: drawWith({ hdr: true, depth: true }, {}),
+ noHdr: drawWith({ hdr: false, depth: true }, volume),
+ noDepth: drawWith({ hdr: true, depth: false }, volume),
+ valid: drawWith({ hdr: true, depth: true }, volume),
+ };
+ try {
+ await createProgressiveTracer({ parts: [wall], environment: { localVolumes: volume } }, { width: 16, height: 16, maxSeconds: 60 });
+ result.progressive = null;
+ } catch (failure) {
+ result.progressive = failure.message;
+ }
+ return result;
+}
+
+test('the renderer rejects a bad localVolumes value before it binds a post program, and the progressive tracer refuses volumes', async (context) => {
+ let chromium;
+ try {
+ ({ chromium } = await import('playwright'));
+ } catch {
+ context.skip('playwright is not installed');
+ return;
+ }
+ const port = await freePort();
+ const server = await startServer(port);
+ let browser;
+ try {
+ try {
+ browser = await chromium.launch({ headless: true, args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'] });
+ } catch (error) {
+ context.skip(`Chrome did not start: ${error.message.split('\n')[0]}`);
+ return;
+ }
+ const page = await browser.newPage({ viewport: { width: 32, height: 32 } });
+ await page.goto(`http://127.0.0.1:${port}/`);
+ const outcome = await page.evaluate(probeInPage);
+ assert.match(outcome.objectWithoutLength.message, /environment\.localVolumes must be an array of volumes/);
+ assert.equal(outcome.objectWithoutLength.choseProgram, false, 'the throw comes before the post program is chosen');
+ assert.match(outcome.noHdr.message, /Local volumes require depth:true, active HDR/);
+ assert.match(outcome.noDepth.message, /Local volumes require depth:true, active HDR/);
+ assert.equal(outcome.noHdr.choseProgram, false);
+ assert.equal(outcome.noDepth.choseProgram, false);
+ assert.equal(outcome.valid.message, null);
+ assert.match(outcome.progressive, /CPU path tracer only; the progressive path tracer cannot draw them/);
+ } finally {
+ await browser?.close();
+ server.kill();
+ }
+});