Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Light local volumes with the key light and the sky through a scatter field (#855)

Nguyen Xuan Anc13a8d7f293b
diff --git a/changes/855-lit-local-volumes.md b/changes/855-lit-local-volumes.md
new file mode 100644
index 00000000..09972f23
--- /dev/null
+++ b/changes/855-lit-local-volumes.md
@@ -0,0 +1 @@
+- `environment.localVolumes[].scatter` (0 to 1, default 0 draws as before) lights a local volume with the key light (shadow map, phase function and the volume's own depth toward the sun) and the sky, in the rasterizer and the CPU path tracer (#855)
diff --git a/changes/855-lit-local-volumes.size.md b/changes/855-lit-local-volumes.size.md
new file mode 100644
index 00000000..dc450b42
--- /dev/null
+++ b/changes/855-lit-local-volumes.size.md
@@ -0,0 +1,9 @@
+- entry:fog-shader: smoke and haze in sun drew as a dark stain; the lit local volume step (sun depth, in-scatter, key light binding) shares the fog's shadow lookup and phase function instead of copying them.
+- scene:agent-scene: the `scatter` field check and the capabilities text run where the recipe is checked, an agent-facing capability.
+- scene:agent-scene+lazy: the same field plus the CPU path tracer's lit volume step (sky mean, shadow ray, sun depth), counted in the lazy bundle.
+- scene:lit-box: a few core lines (the key light block in the post program, the shadow flag, the environment passed to the volume bind), counted in this scene.
+- scene:gltf-box: the same core lines, counted in this scene.
+- scene:gltf-box+lazy: the same core lines, counted in this scene.
+- goal:lit-box: growth is a few core lines for a visible fix whose shader code lives in the fog addon.
+- goal:gltf-box: growth is a few core lines for a visible fix whose shader code lives in the fog addon.
+- goal:agent-scene: the scene is already over its goal; the `scatter` check must run where the recipe is checked.
diff --git a/docs/volumetric.md b/docs/volumetric.md
index 97641a72..77c16dd4 100644
--- a/docs/volumetric.md
+++ b/docs/volumetric.md
@@ -108,7 +108,7 @@ In a scene with an irradiance grid (`bake.irradianceGrid`) the bounce term is th
## Local volumes
-`environment.localVolumes` holds up to 8 boxes, spheres or parts that absorb and emit light: candle haze, a smoke puff, a glowing cloud in one place. They need no `volumeFog` and do not scatter, so a lamp does not light them; they only dim what is behind them and add their own glow. A scene without `localVolumes` draws exactly as before and compiles nothing extra.
+`environment.localVolumes` holds up to 8 boxes, spheres or parts that absorb and emit light: candle haze, a smoke puff, a glowing cloud in one place. They need no `volumeFog`. With `scatter` at its default `0` they do not scatter, so the sun and the sky do not light them; they only dim what is behind them and add their own glow. Raise `scatter` to light them (see "Lit volumes"). A scene without `localVolumes` draws exactly as before and compiles nothing extra.
```json
{ "environment": { "localVolumes": [
@@ -125,11 +125,22 @@ In a scene with an irradiance grid (`bake.irradianceGrid`) the bounce term is th
| `absorption` | `[1, 1, 1]` | Per colour channel share of the density, `0` to `1`. A larger value dims that channel more, so `[0.1, 0.6, 1]` removes blue first and leaves a warm tint |
| `emission`, `emissionStrength` | `[0, 0, 0]`, `1` | Glow colour and its radiance per unit length at the core, `0` to `1000`. Emission does not depend on `density`, so `density: 0` is a pure glow |
| `falloff` | `0.5` | `0` to `1`. The outer share of the volume over which the density fades to zero (`0` is a hard edge) |
+| `scatter` | `0` | `0` to `1`. The share of the light the volume extinguishes that it scatters back instead of absorbing, lit by the key light and the sky (see "Lit volumes"). `0` draws exactly as before. Not allowed with `fit: "mesh"` |
| `noiseAmount`, `noiseScale` | `0`, `1` | `noiseAmount` `0` to `1` breaks the density up with value noise at `noiseScale` cells per unit: the profile is multiplied by `mix(1, 2 * noise, noiseAmount)`. The rasterizer and the CPU path tracer read the same field. A `fit: "mesh"` volume ignores it |
| `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: a scene bake (`bake` in a recipe) leaves them out, an emissive volume lights no baked surface and no volume dims the baked light, and the bake report names them in `skippedLocalVolumes` (index, shape, whether emissive) with a `warnings` line. A scene without local volumes bakes and reports exactly as before. Add a point light or an emissive part where the volume's glow should reach a wall. The path tracer traces them on `backend: "cpu"` with the same fields, noise included, and every other tracer entry point (backends `gpu`, `webgpu` and `native`, the progressive and both realtime tracers, the GPU light bake) throws `environment.localVolumes is traced by the CPU path tracer only` instead of leaving them out. The GPU tracers are refused, not ported: each would need a second march loop in its kernel and a volume table in every pack, for a feature the CPU tracer already draws. 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.
+### Lit volumes
+
+A volume with `scatter` above `0` returns, in each step, `scatter * (1 - exp(-extinction * step))` of the light it dims, per colour channel, times the light that arrives at that point: the sky term plus the key light. Smoke or haze in sun then reads bright on the side toward the sun and grey in shade, where a `scatter: 0` volume draws as a dark stain.
+
+- The key light uses the same shadow map lookup (`keyVisibility`) and phase function (`henyeyGreenstein`, isotropic here) as `volumeFog`, times `exp(-depth)` where `depth` is the volume's own optical depth between the point and the volume's far side toward the sun (three midpoint taps of its profile, noise included). That depth is what makes the sunward side brighter than the shaded side. Only the key light and the sky light a volume: point, spot and area lights do not.
+- The sky term is the mean of `skyTop` and `skyBottom` times `ambientIntensity` in the rasterizer, and the mean radiance of `environment.map` in the CPU path tracer. It is not occluded. With an environment map the rasterizer still reads `skyTop` and `skyBottom`.
+- The CPU path tracer uses the same model on `backend: "cpu"`: the sky term, a shadow ray toward the sun, and the same three taps. The sun's colour is `keyColor` there.
+- A scene with a lit volume draws the key light's shadow map for the post pass, as a fog does. A volume with `scatter: 0` pays nothing extra per step.
+- Measured (`tests/local-volume-scatter.test.js`, a density 1.2 smoke box under a side sun over an even grey sky, seen from above; 64 px rasterizer on SwiftShader against the 32 px, 16 sample CPU tracer): the worst of 64 regions differed by 0.0003 of linear radiance and the whole frame matched to four places (0.4141 both), inside the 0.05 and 0.02 tolerances. The half toward the sun read 0.424 and the shaded half 0.404 in both renderers.
+
### Mesh volumes
`shape: "mesh"` takes its place and size from a part, so smoke can fill a room or a modelled shape without writing its numbers twice.
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 08677bed..c667d267 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -271,7 +271,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', 'mesh']), fields: 'shape, center, size (box) or radius (sphere) or part + fit bounds|mesh (mesh: the named part, bounds by default; fit mesh fills a closed part, ignoring falloff, noise and steps), 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 the same field in the rasterizer and the CPU path tracer; path tracer: backend cpu only (gpu, webgpu and native throw); a bake leaves them out, so an emissive volume lights no baked surface (bake report: skippedLocalVolumes, warnings).' }),
+ localVolumes: Object.freeze({ field: 'environment.localVolumes', maximum: 8, shapes: Object.freeze(['box', 'sphere', 'mesh']), fields: 'shape, center, size (box) or radius (sphere) or part + fit bounds|mesh (mesh: the named part, bounds by default; fit mesh fills a closed part, ignoring falloff, noise and steps), density 0-100 (1), falloff 0-1 (0.5), absorption rgb 0-1 (1,1,1), emission rgb 0-1, emissionStrength 0-1000 (1), scatter 0-1 (0; lit by the key light and the sky, not with fit mesh), noiseAmount 0-1 (0), noiseScale (1), steps 4-32 (16)', note: 'Absorb and emit; scatter above 0 lights the volume with the key light (shadow map, own depth toward the sun) and the sky term, 0 draws as before; needs hdr and depth like volumeFog; noise is the same field in the rasterizer and the CPU path tracer; path tracer: backend cpu only (gpu, webgpu and native throw); a bake leaves them out, so an emissive volume lights no baked surface (bake report: skippedLocalVolumes, warnings).' }),
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 46f726da..7ed0db82 100644
--- a/src/fog-shader.js
+++ b/src/fog-shader.js
@@ -89,10 +89,11 @@ function prepareLocalVolumes(renderer, input, frame) {
}
// Uploads the packed volumes. Their uniforms exist only in a program with the local step compiled in.
-function bindLocalVolumes(renderer, post, frame) {
+function bindLocalVolumes(renderer, post, frame, environment) {
const context = renderer.context;
const buffers = renderer.localVolumeBuffers;
const locate = name => (post.uniforms[name] ??= context.getUniformLocation(post.program, name));
+ bindKeyLight(renderer, locate, environment);
context.uniform1i(locate('localVolumeCount'), buffers.count);
context.uniform1f(locate('localOrthographic'), frame.projection === 'orthographic' ? 1 : 0);
context.uniform4fv(locate('localVolumeCenters[0]'), buffers.centers);
@@ -107,6 +108,32 @@ function bindLocalVolumes(renderer, post, frame) {
context.uniform1i(locate('localMeshVolumes'), 7);
}
+// The renderer's own sky gradient when a scene names none; drawSky in renderer.js holds the same two colours.
+const DEFAULT_SKY_TOP = [0.20, 0.38, 0.52];
+const DEFAULT_SKY_BOTTOM = [0.62, 0.70, 0.67];
+
+// The sky term of a scattering local volume: the mean of the sky gradient times the ambient intensity.
+function localSkyAmbient(renderer, environment) {
+ const top = environment.skyTop ?? DEFAULT_SKY_TOP;
+ const bottom = environment.skyBottom ?? DEFAULT_SKY_BOTTOM;
+ return [0, 1, 2].map(channel => 0.5 * (top[channel] + bottom[channel]) * renderer.lighting.ambientIntensity);
+}
+
+// The key light's shadow map, direction and colour, and the sky term, for volumes that scatter. The sampler always has the shadow map
+// on its unit, so the program is valid in a frame where no volume scatters.
+function bindKeyLight(renderer, locate, environment) {
+ const context = renderer.context;
+ if (renderer.shadowTexture) {
+ context.activeTexture(context.TEXTURE3);
+ context.bindTexture(context.TEXTURE_2D, renderer.shadowTexture);
+ }
+ context.uniform1i(locate('volumeShadowMap'), 3);
+ context.uniformMatrix4fv(locate('volumeLightProjection'), false, renderer.lightProjection);
+ context.uniform3fv(locate('volumeLightDirection'), environment.lightDirection);
+ context.uniform3fv(locate('volumeLightColor'), renderer.lighting.keyColor);
+ context.uniform3fv(locate('localSkyAmbient'), localSkyAmbient(renderer, environment));
+}
+
const LOCAL_VOLUME_DECLARATIONS = `
uniform int localVolumeCount;
uniform float localOrthographic;
@@ -116,6 +143,7 @@ uniform vec4 localVolumeAbsorption[8];
uniform vec4 localVolumeEmission[8];
uniform vec4 localVolumeSteps[8];
uniform vec4 localVolumeAxes[24];
+uniform vec3 localSkyAmbient;
uniform highp sampler2D localMeshVolumes;
`;
@@ -179,6 +207,21 @@ float localVolumeProfile(int index, vec3 position) {
if (noiseAmount > 0.0) profile *= mix(1.0, localVolumeNoise(position * localVolumeEmission[index].w) * 2.0, noiseAmount);
return profile;
}
+// The optical depth of a volume between a point inside it and its far side toward the sun, from three midpoint taps of its profile.
+vec3 localVolumeSunDepth(int index, vec3 position, vec3 towardSun) {
+ float exitDistance = max(localVolumeInterval(index, position, towardSun).y, 0.0);
+ float profileSum = 0.0;
+ for (int tap = 0; tap < 3; tap++) profileSum += localVolumeProfile(index, position + towardSun * (exitDistance * (float(tap) + 0.5) / 3.0));
+ return localVolumeAbsorption[index].rgb * (profileSum * exitDistance / 3.0);
+}
+// The light a scattering volume receives at a point: the sky term plus the key light through the shadow map and the volume's own depth.
+vec3 localVolumeInScatter(int index, vec3 position, vec3 direction) {
+ vec3 towardSun = normalize(volumeLightDirection);
+ float visibility = keyVisibility(position);
+ vec3 sunLight = vec3(0.0);
+ if (visibility > 0.001) sunLight = volumeLightColor * (henyeyGreenstein(dot(direction, towardSun), 0.0) * visibility) * exp(-localVolumeSunDepth(index, position, towardSun));
+ return localSkyAmbient + sunLight;
+}
vec3 localVolumes(vec3 background) {
vec2 clipXY = textureCoordinate * 2.0 - 1.0;
vec4 farPoint = inverseViewProjection * vec4(clipXY, 1.0, 1.0);
@@ -243,18 +286,45 @@ vec3 localVolumes(vec3 background) {
int steps = int(localVolumeSteps[nearest].x);
float stepSize = (exitDistance - entry) / float(steps);
float jitter = hash(vec3(gl_FragCoord.xy, float(nearest) + 1.0));
+ float scatterAlbedo = localVolumeSteps[nearest].z;
for (int step = 0; step < 32; step++) {
if (step >= steps) break;
vec3 position = origin + direction * (entry + (float(step) + jitter) * stepSize);
float profile = localVolumeProfile(nearest, position);
radiance += transmittance * localVolumeEmission[nearest].rgb * (profile * stepSize);
- transmittance *= exp(-localVolumeAbsorption[nearest].rgb * (profile * stepSize));
+ vec3 extinction = localVolumeAbsorption[nearest].rgb * (profile * stepSize);
+ if (scatterAlbedo > 0.0 && profile > 0.0) radiance += transmittance * (scatterAlbedo * (1.0 - exp(-extinction))) * localVolumeInScatter(nearest, position, direction);
+ transmittance *= exp(-extinction);
}
}
return background * transmittance + radiance;
}
`;
+// The key light's side of the fog and of a scattering local volume: the shadow map, the light and the phase function. Both steps read these,
+// so post.js compiles this block in whenever either is on.
+const KEY_LIGHT_DECLARATIONS = `
+uniform highp sampler2DShadow volumeShadowMap;
+uniform mat4 volumeLightProjection;
+uniform vec3 volumeLightDirection;
+uniform vec3 volumeLightColor;
+`;
+
+const KEY_LIGHT_FUNCTIONS = `
+float henyeyGreenstein(float cosine, float anisotropy) {
+ return (1.0 - anisotropy * anisotropy) / (12.5663706 * pow(1.0 + anisotropy * anisotropy - 2.0 * anisotropy * cosine, 1.5));
+}
+// The share of the key light that reaches a point: the shadow map.
+float keyVisibility(vec3 position) {
+ vec4 lightPosition = volumeLightProjection * vec4(position, 1);
+ vec3 shadow = lightPosition.xyz / lightPosition.w * 0.5 + 0.5;
+ if (all(greaterThanEqual(shadow, vec3(0))) && all(lessThanEqual(shadow, vec3(1)))) {
+ return texture(volumeShadowMap, vec3(shadow.xy, shadow.z - 0.0008));
+ }
+ return 1.0;
+}
+`;
+
function packLights(renderer) {
renderer.fogLightBuffers ??= createFogLightBuffers();
packFogLights(renderer.lighting, renderer.fogLightBuffers);
@@ -263,13 +333,11 @@ function packLights(renderer) {
registerShaderFeatureCode('volumeFog', {
// The JavaScript half, which the renderer calls for a frame that draws a volume fog.
support: { packLights, bindUniforms, usesDetail: fogUsesDetail, prepareLocalVolumes, bindLocalVolumes },
+ keyDeclarations: KEY_LIGHT_DECLARATIONS,
+ keyFunctions: KEY_LIGHT_FUNCTIONS,
localDeclarations: LOCAL_VOLUME_DECLARATIONS,
localFunctions: LOCAL_VOLUME_FUNCTIONS,
postDeclarations: `
-uniform highp sampler2DShadow volumeShadowMap;
-uniform mat4 volumeLightProjection;
-uniform vec3 volumeLightDirection;
-uniform vec3 volumeLightColor;
uniform float volumeDensity;
uniform vec3 volumeMinimum;
uniform vec3 volumeMaximum;
@@ -309,9 +377,6 @@ uniform float orthographic;
uniform highp sampler3D fogSkyVisibility;
`,
postFunctions: `
-float henyeyGreenstein(float cosine, float anisotropy) {
- return (1.0 - anisotropy * anisotropy) / (12.5663706 * pow(1.0 + anisotropy * anisotropy - 2.0 * anisotropy * cosine, 1.5));
-}
float fogLightAttenuation(float distanceSquared, float range, float radius) {
float cutoff = 1.0;
if (range > 0.0) {
@@ -391,15 +456,6 @@ float fogDensityFactor(vec3 position) {
else if (volumeHeightFalloff > 0.0) noise *= exp((volumeMinimum.y - position.y) / volumeHeightFalloff);
return noise;
}
-// The share of the key light that reaches a point: the shadow map.
-float keyVisibility(vec3 position) {
- vec4 lightPosition = volumeLightProjection * vec4(position, 1);
- vec3 shadow = lightPosition.xyz / lightPosition.w * 0.5 + 0.5;
- if (all(greaterThanEqual(shadow, vec3(0))) && all(lessThanEqual(shadow, vec3(1)))) {
- return texture(volumeShadowMap, vec3(shadow.xy, shadow.z - 0.0008));
- }
- return 1.0;
-}
// The optical depth of the fog between a point and the sun, from three taps along the light direction up to the box exit.
float sunOpticalDepth(vec3 position, vec3 towardSun) {
float exitDistance = volumeMaxDistance;
diff --git a/src/local-volumes.js b/src/local-volumes.js
index d4daae01..3d8e2e3d 100644
--- a/src/local-volumes.js
+++ b/src/local-volumes.js
@@ -1,14 +1,14 @@
import { finiteRange } from './volumetric.js';
import { localVolumeNoiseFactor } from './local-volume-noise.js';
-// Local volumes: up to MAX_LOCAL_VOLUMES boxes, spheres or parts (shape "mesh") that absorb and emit light, for candle haze, smoke puffs and glowing
-// fog in one place. They sit beside environment.volumeFog (the one scattering volume) and need no fog. The post pass marches
+// Local volumes: up to MAX_LOCAL_VOLUMES boxes, spheres or parts (shape "mesh") that absorb and emit light and, with `scatter`, scatter
+// the key light and the sky, for candle haze, smoke puffs and glowing fog in one place. They sit beside environment.volumeFog (the one scattering volume) and need no fog. The post pass marches
// each one separately and composites them from the nearest entry to the farthest, so overlapping volumes are an approximation.
export const MAX_LOCAL_VOLUMES = 8;
export const LOCAL_VOLUME_SHAPES = Object.freeze(['box', 'sphere', 'mesh']);
export const LOCAL_VOLUME_FIT = Object.freeze(['bounds', 'mesh']);
-export const LOCAL_VOLUME_FIELDS = Object.freeze(['shape', 'part', 'fit', 'center', 'size', 'radius', 'density', 'falloff', 'absorption', 'emission', 'emissionStrength', 'noiseAmount', 'noiseScale', 'steps']);
+export const LOCAL_VOLUME_FIELDS = Object.freeze(['shape', 'part', 'fit', 'center', 'size', 'radius', 'density', 'falloff', 'absorption', 'emission', 'emissionStrength', 'scatter', 'noiseAmount', 'noiseScale', 'steps']);
export const LOCAL_VOLUME_MAXIMUM_STEPS = 32;
function vectorField(value, minimum, maximum, label) {
@@ -31,6 +31,7 @@ function resolveLocalVolume(input, label) {
absorption: vectorField(input.absorption ?? [1, 1, 1], 0, 1, `${label}.absorption`),
emission: vectorField(input.emission ?? [0, 0, 0], 0, 1, `${label}.emission`),
emissionStrength: finiteRange(input.emissionStrength ?? 1, 0, 1000, `${label}.emissionStrength`),
+ scatter: finiteRange(input.scatter ?? 0, 0, 1, `${label}.scatter`),
noiseAmount: finiteRange(input.noiseAmount ?? 0, 0, 1, `${label}.noiseAmount`),
noiseScale: finiteRange(input.noiseScale ?? 1, 0.001, 100, `${label}.noiseScale`),
steps: finiteRange(input.steps ?? 16, 4, LOCAL_VOLUME_MAXIMUM_STEPS, `${label}.steps`),
@@ -41,6 +42,7 @@ function resolveLocalVolume(input, label) {
for (const field of ['center', 'size', 'radius']) {
if (input[field] !== undefined) throw new TypeError(`${label}.${field} belongs to a box or a sphere; a mesh volume takes its place and size from the part named in ${label}.part`);
}
+ if (resolved.scatter > 0 && (input.fit ?? 'bounds') === 'mesh') throw new RangeError(`${label}.scatter is not drawn inside a volume that fits the closed mesh; use fit "bounds" or scatter 0`);
resolved.part = input.part;
resolved.fit = input.fit ?? 'bounds';
if (!LOCAL_VOLUME_FIT.includes(resolved.fit)) throw new RangeError(`${label}.fit must be one of ${LOCAL_VOLUME_FIT.join(', ')}`);
@@ -87,7 +89,7 @@ export function packLocalVolumes(volumes, buffers) {
buffers.extents.set([...half, volume.falloff], at);
buffers.absorption.set([...volume.absorption.map(channel => channel * volume.density), volume.noiseAmount], at);
buffers.emission.set([...volume.emission.map(channel => channel * volume.emissionStrength), volume.noiseScale], at);
- buffers.steps.set([volume.steps, packedShape === PACKED_SHAPE_MESH ? buffers.meshParts.length : 0, 0, 0], at);
+ buffers.steps.set([volume.steps, packedShape === PACKED_SHAPE_MESH ? buffers.meshParts.length : 0, volume.scatter ?? 0, 0], at);
if (packedShape === PACKED_SHAPE_MESH) buffers.meshParts.push({ part: volume.part, label: `environment.localVolumes[${index}]` });
const axes = volume.axes ?? IDENTITY_AXES;
for (let axis = 0; axis < 3; axis++) buffers.axes.set([axes[axis * 3], axes[axis * 3 + 1], axes[axis * 3 + 2], 0], (index * 3 + axis) * 4);
diff --git a/src/path-tracer-volume.js b/src/path-tracer-volume.js
index 865408d2..ee95dab6 100644
--- a/src/path-tracer-volume.js
+++ b/src/path-tracer-volume.js
@@ -150,18 +150,72 @@ function marchMeshVolume(volume, spans, originX, originY, originZ, directionX, d
}
}
+/** The mean radiance of an environment map over the sphere (rows weighted by their solid angle), the sky term of a scattering local volume. */
+export function meanEnvironmentRadiance(environment) {
+ const mean = [0, 0, 0];
+ if (!environment) return mean;
+ const { width, height, channels, data, intensity } = environment;
+ let weightTotal = 0;
+ for (let row = 0; row < height; row++) {
+ const rowWeight = Math.sin(Math.PI * (row + 0.5) / height);
+ for (let column = 0; column < width; column++) {
+ for (let channel = 0; channel < 3; channel++) mean[channel] += data[(row * width + column) * channels + channel] * rowWeight;
+ }
+ weightTotal += rowWeight * width;
+ }
+ return mean.map(total => total * intensity / weightTotal);
+}
+
+const SUN_DEPTH_TAPS = 3;
+
+/**
+ * The optical depth per colour channel between a point inside a volume and the volume's far side toward the sun, from three
+ * midpoint taps of its profile: the rasterizer's `localVolumeSunDepth`, so the lit side of a volume is brighter than the shaded side.
+ */
+function writeSunOpticalDepth(volume, x, y, z, toward, span, out) {
+ const exitDistance = localVolumeInterval(volume, x, y, z, toward[0], toward[1], toward[2], Infinity, span) ? Math.max(span[1], 0) : 0;
+ let profileSum = 0;
+ for (let tap = 0; tap < SUN_DEPTH_TAPS; tap++) {
+ const distance = exitDistance * (tap + 0.5) / SUN_DEPTH_TAPS;
+ profileSum += localVolumeProfile(volume, x + toward[0] * distance, y + toward[1] * distance, z + toward[2] * distance);
+ }
+ for (let channel = 0; channel < 3; channel++) out[channel] = volume.absorption[channel] * volume.density * profileSum * exitDistance / SUN_DEPTH_TAPS;
+}
+
/**
* Builds the function that carries a ray through the scene's local volumes (environment.localVolumes). Each volume is marched with
* its own step count between its entry and exit, nearest entry first: the emitted light is added in proportion to the throughput
- * so far, then the throughput is dimmed by exp(-absorption * profile * step). Emission and absorption do not scatter, so no light
- * sample is taken. A volume's `noiseAmount` modulates the profile with the rasterizer's own noise field. `jitter` (0 to 1) offsets the samples within a step.
+ * so far, then the throughput is dimmed by exp(-absorption * profile * step). A volume with `scatter` above 0 also returns that share
+ * of the light it extinguishes in the step, lit by the sky term and by the sun (phase function, shadow ray, and the volume's own
+ * optical depth toward the sun); `lighting` is `{ sun: { direction, color } | null, ambient: [red, green, blue], sunVisibility(x, y, z) }`,
+ * where sunVisibility is 1 or 0 for a shadow ray toward the sun. A volume's `noiseAmount` modulates the profile with the rasterizer's
+ * own noise field. `jitter` (0 to 1) offsets the samples within a step.
* The returned function writes the emitted light into `emitted` and scales `throughput` in place.
*/
-export function createLocalVolumeCrossing(volumes) {
+export function createLocalVolumeCrossing(volumes, lighting = null) {
const entries = new Float64Array(volumes.length);
const exits = new Float64Array(volumes.length);
const order = new Int32Array(volumes.length);
const span = new Float64Array(2);
+ const sunDepth = new Float64Array(3);
+ const sunLight = new Float64Array(3);
+
+ // Adds the light one step of a scattering volume sends back along the ray: scatter * (1 - exp(-extinction * width)) * (sky + sun).
+ function addScatteredLight(volume, x, y, z, directionX, directionY, directionZ, width, throughput, emitted) {
+ sunLight.fill(0);
+ const sun = lighting.sun;
+ if (sun && lighting.sunVisibility(x, y, z) > 0) {
+ writeSunOpticalDepth(volume, x, y, z, sun.direction, span, sunDepth);
+ const cosine = sun.direction[0] * directionX + sun.direction[1] * directionY + sun.direction[2] * directionZ;
+ const phase = henyeyGreensteinPhase(0, cosine);
+ for (let channel = 0; channel < 3; channel++) sunLight[channel] = sun.color[channel] * phase * Math.exp(-sunDepth[channel]);
+ }
+ for (let channel = 0; channel < 3; channel++) {
+ const scattered = volume.scatter * (1 - Math.exp(-volume.absorption[channel] * volume.density * width));
+ emitted[channel] += throughput[channel] * scattered * (lighting.ambient[channel] + sunLight[channel]);
+ }
+ }
+
const meshScratch = new Float64Array(MAXIMUM_MESH_SEGMENTS * 2);
const meshSpans = new Array(volumes.length);
return function crossLocalVolumes(originX, originY, originZ, directionX, directionY, directionZ, length, jitter, throughput, emitted) {
@@ -199,6 +253,9 @@ export function createLocalVolumeCrossing(volumes) {
const profile = localVolumeProfile(volume, originX + directionX * distance, originY + directionY * distance, originZ + directionZ * distance);
if (profile <= 0) continue;
const width = profile * stepLength;
+ if (volume.scatter > 0 && lighting) {
+ addScatteredLight(volume, originX + directionX * distance, originY + directionY * distance, originZ + directionZ * distance, directionX, directionY, directionZ, width, throughput, emitted);
+ }
for (let channel = 0; channel < 3; channel++) {
emitted[channel] += throughput[channel] * volume.emission[channel] * volume.emissionStrength * width;
throughput[channel] *= Math.exp(-volume.absorption[channel] * volume.density * width);
diff --git a/src/path-tracer.js b/src/path-tracer.js
index 3467721e..c0e0f166 100644
--- a/src/path-tracer.js
+++ b/src/path-tracer.js
@@ -11,7 +11,7 @@ import {
} from './path-tracer-shading.js';
import { buildLightTree, chooseLightFromTree, LIGHT_TREE_FIRST_HIT_LIGHTS, resolveLightSelection } from './path-tracer-light-tree.js';
import { createRandomWalk, WALK_OUTCOME } from './path-tracer-subsurface.js';
-import { henyeyGreensteinPhase, sampleHenyeyGreensteinCosine, volumeInterval, createLocalVolumeCrossing } from './path-tracer-volume.js';
+import { henyeyGreensteinPhase, sampleHenyeyGreensteinCosine, volumeInterval, createLocalVolumeCrossing, meanEnvironmentRadiance } from './path-tracer-volume.js';
// Offline still renderer: unidirectional path tracing on the CPU with next-event estimation for every light, the
// environment map drawn by importance, and a wavelet denoiser. It reads the same parts, materials, lights and camera
@@ -798,7 +798,15 @@ function createPathTracer(scene, options) {
return henyeyGreensteinPhase(volume.anisotropy, cosine);
}
- const crossLocalVolumes = scene.localVolumes ? createLocalVolumeCrossing(scene.localVolumes) : null;
+ // A scattering local volume is lit by the sky's mean radiance and by the sun through a shadow ray, as the rasterizer lights it.
+ const localVolumeLighting = scene.localVolumes?.some(volume => volume.scatter > 0)
+ ? {
+ sun: lights.sun,
+ ambient: meanEnvironmentRadiance(environment),
+ sunVisibility: (pointX, pointY, pointZ) => (occluded(scene, pointX, pointY, pointZ, lights.sun.direction[0], lights.sun.direction[1], lights.sun.direction[2], scene.farDistance, shadowHit) ? 0 : 1),
+ }
+ : null;
+ const crossLocalVolumes = scene.localVolumes ? createLocalVolumeCrossing(scene.localVolumes, localVolumeLighting) : null;
const localEmitted = new Float64Array(3);
const walkSubsurface = createRandomWalk(scene, random, intersect);
diff --git a/src/post.js b/src/post.js
index 3878fc66..ee1c2d12 100644
--- a/src/post.js
+++ b/src/post.js
@@ -191,6 +191,11 @@ function explosionFunctionFor(enabledSteps) {
function fogCodeFor(enabledSteps) {
let declarations = '';
let functions = '';
+ if (enabledSteps.has('volume') || enabledSteps.has('local')) {
+ const code = requireFeatureCode('volumeFog');
+ declarations += code.keyDeclarations;
+ functions += code.keyFunctions;
+ }
if (enabledSteps.has('volume')) {
const code = requireFeatureCode('volumeFog');
declarations += code.postDeclarations;
diff --git a/src/renderer.js b/src/renderer.js
index 8c305be8..258f0d0a 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -2190,7 +2190,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, frame);
+ if (localVolumes) requireFeatureCode('volumeFog').support.bindLocalVolumes(this, post, frame, environment);
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);
@@ -2550,7 +2550,7 @@ export class Renderer67 {
this.requireFeatureNames(shaderFeaturesOfLighting(this.lighting));
const passMode = this.preparePass(frame);
this.renderingPass = passMode > 0;
- this.volumeShadowWanted = volume.density > 0;
+ this.volumeShadowWanted = volume.density > 0 || (Array.isArray(environment.localVolumes) && environment.localVolumes.some(localVolume => localVolume?.scatter > 0));
if (casterChanged || this.shadowMapSizeWanted() !== this.shadowMapSize) {
this.assemblyAmount = assemblyAmount;
this.createShadowMap();
diff --git a/tests/local-volume-scatter.test.js b/tests/local-volume-scatter.test.js
new file mode 100644
index 00000000..25373424
--- /dev/null
+++ b/tests/local-volume-scatter.test.js
@@ -0,0 +1,308 @@
+// Scattering local volumes (issue 855): `scatter` lets a volume return a share of the light it extinguishes, lit by the sky and by the
+// key light. The pure tests check the field, the packing and the CPU path tracer's lit and shaded sides; the browser test draws one
+// smoke box in the rasterizer (headless Chrome on SwiftShader, from the Vite dev server) and in the CPU path tracer and compares the
+// radiance per region. It skips when Chrome cannot start. Set LOCAL_VOLUME_SCATTER_ARTIFACTS to a folder to also write the compare still
+// and the per-region numbers there.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { freePort } from './helpers/free-port.js';
+import { renderPathTracedImage } from '../src/path-tracer.js';
+import { applyViewTransform } from '../src/view-transform.js';
+import { encodePng } from '../src/export-png.js';
+import { resolveLocalVolumes, createLocalVolumeBuffers, packLocalVolumes } from '../src/local-volumes.js';
+import { createLocalVolumeCrossing, meanEnvironmentRadiance } from '../src/path-tracer-volume.js';
+
+const REGION_TOLERANCE = 0.05;
+const MEAN_TOLERANCE = 0.02;
+const SMOKE_BOX = { shape: 'box', center: [0, 1.5, 0], size: [3, 1.5, 3], density: 1.2, falloff: 0.3, absorption: [0.7, 0.8, 1], scatter: 0.8, steps: 32 };
+const SUN_DIRECTION = [1, 0.1, 0];
+const SUN_COLOR = [3, 3, 3];
+const SKY_LEVEL = 0.15;
+
+test('scatter is a number from 0 to 1 that defaults to 0 and an error names the field and the range', () => {
+ const [plain] = resolveLocalVolumes([{ shape: 'box', center: [0, 0, 0], size: [1, 1, 1] }]);
+ assert.equal(plain.scatter, 0);
+ const [lit] = resolveLocalVolumes([{ shape: 'sphere', center: [0, 0, 0], radius: 1, scatter: 0.8 }]);
+ assert.equal(lit.scatter, 0.8);
+ for (const bad of [-0.1, 1.5, Number.NaN, '0.5']) {
+ assert.throws(() => resolveLocalVolumes([{ shape: 'box', center: [0, 0, 0], size: [1, 1, 1], scatter: bad }], 'environment.localVolumes'), /environment\.localVolumes\[0\]\.scatter/);
+ }
+});
+
+test('a volume that fits a closed mesh refuses scatter and a bounds fit accepts it', () => {
+ assert.throws(() => resolveLocalVolumes([{ shape: 'mesh', part: 'room', fit: 'mesh', scatter: 0.5 }], 'environment.localVolumes'), /localVolumes\[0\]\.scatter.*fit "bounds"/);
+ const [bounded] = resolveLocalVolumes([{ shape: 'mesh', part: 'room', scatter: 0.5 }]);
+ assert.equal(bounded.scatter, 0.5);
+});
+
+test('the packed steps carry the scatter in their third component and leave the other packed arrays alone', () => {
+ const buffers = createLocalVolumeBuffers();
+ const volumes = resolveLocalVolumes([{ shape: 'box', center: [0, 0, 0], size: [1, 1, 1], steps: 12 }, { shape: 'box', center: [0, 0, 0], size: [1, 1, 1], steps: 12, scatter: 0.4 }]);
+ packLocalVolumes(volumes, buffers);
+ assert.equal(buffers.steps[2], 0);
+ assert.ok(Math.abs(buffers.steps[6] - 0.4) < 1e-6);
+ assert.equal(buffers.steps[0], 12);
+});
+
+const SUN_TOWARD = (() => {
+ const length = Math.hypot(...SUN_DIRECTION);
+ return SUN_DIRECTION.map(component => component / length);
+})();
+
+// Sends one ray straight down through the box at the given x and returns the light it returns, with the throughput left behind.
+function downRay(volume, lighting, x) {
+ const crossing = createLocalVolumeCrossing(resolveLocalVolumes([volume]), lighting);
+ const throughput = new Float64Array([1, 1, 1]);
+ const emitted = new Float64Array(3);
+ crossing(x, 4, 0, 0, -1, 0, 8, 0.5, throughput, emitted);
+ return { emitted: Array.from(emitted), throughput: Array.from(throughput) };
+}
+
+const FULL_SUN = { sun: { direction: SUN_TOWARD, color: SUN_COLOR }, ambient: [0, 0, 0], sunVisibility: () => 1 };
+
+test('in sun a scattering box returns more light on its lit side than on its shaded side', () => {
+ const lit = downRay(SMOKE_BOX, FULL_SUN, 1.2).emitted[1];
+ const shaded = downRay(SMOKE_BOX, FULL_SUN, -1.2).emitted[1];
+ assert.ok(lit > 0 && shaded > 0);
+ assert.ok(lit > shaded * 1.3, `lit side ${lit} against shaded side ${shaded}`);
+});
+
+test('a volume with scatter 0 draws exactly as it did: no light is added and the throughput is the absorbed share', () => {
+ const absorbOnly = { ...SMOKE_BOX, scatter: 0 };
+ const { scatter, ...withoutField } = SMOKE_BOX;
+ const withLighting = downRay(absorbOnly, FULL_SUN, 0.3);
+ const withoutLighting = downRay(withoutField, null, 0.3);
+ assert.deepEqual(withLighting.emitted, [0, 0, 0]);
+ assert.deepEqual(withLighting, withoutLighting);
+ assert.ok(withLighting.throughput[0] < 1);
+});
+
+test('a shaded volume with only the sky around it returns the sky colour scaled by what it extinguishes', () => {
+ const sky = { sun: null, ambient: [SKY_LEVEL, SKY_LEVEL, SKY_LEVEL], sunVisibility: () => 1 };
+ const result = downRay({ ...SMOKE_BOX, falloff: 0 }, sky, 0);
+ const extinguished = 1 - result.throughput[1];
+ assert.ok(Math.abs(result.emitted[1] - 0.8 * extinguished * SKY_LEVEL) < 1e-9, `${result.emitted[1]} against ${0.8 * extinguished * SKY_LEVEL}`);
+ const blocked = downRay(SMOKE_BOX, { ...FULL_SUN, sunVisibility: () => 0 }, 1.2);
+ assert.deepEqual(blocked.emitted, [0, 0, 0]);
+});
+
+test('the mean of an environment map weights each row by its solid angle', () => {
+ const data = new Float32Array(4 * 2 * 3).fill(0.5);
+ assert.deepEqual(meanEnvironmentRadiance({ width: 4, height: 2, channels: 3, data, intensity: 2 }).map(value => +value.toFixed(6)), [1, 1, 1]);
+ assert.deepEqual(meanEnvironmentRadiance(null), [0, 0, 0]);
+});
+
+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;
+}
+
+const SIZE = 64;
+const CPU_SIZE = 32;
+const CPU_SAMPLES = 16;
+const LOOKING_DOWN = { eye: [0, 3, 0], target: [0, 0, 0], up: [0, 0, -1], fov: 40 };
+const LIGHT = { keyColor: SUN_COLOR, lightDirection: SUN_DIRECTION, keyIntensity: 1, fillIntensity: 0, skyTop: [SKY_LEVEL, SKY_LEVEL, SKY_LEVEL], skyBottom: [SKY_LEVEL, SKY_LEVEL, SKY_LEVEL] };
+
+// The rasterizer's frame for each list of volumes, as floats (RGBA, rows bottom to top).
+async function rasterFrames(page, volumeLists) {
+ const task = async ({ size, lists, camera, light }) => {
+ const { box } = await import('/src/geometry.js');
+ const { Renderer67 } = await import('/src/renderer.js');
+ const { createFloatOutput, readFloatPixels } = await import('/src/float-output.js');
+ await import('/src/fog-shader.js');
+ const canvas = document.createElement('canvas');
+ canvas.width = size;
+ canvas.height = size;
+ canvas.style.width = size + 'px';
+ canvas.style.height = size + 'px';
+ document.body.append(canvas);
+ const material = { tag: 'unlit', color: [1, 1, 1], metallic: 0, roughness: 1, emission: 0 };
+ const ground = { name: 'ground', geometry: box(0, 1), matrix: new Float32Array([40, 0, 0, 0, 0, 0.2, 0, 0, 0, 0, 40, 0, 0, -0.1, 0, 1]), material };
+ const renderer = new Renderer67(canvas, [ground], { hdr: true, depth: true, samples: 1, pixelRatio: 1, ground: false });
+ const output = createFloatOutput(renderer.context, size, size);
+ const frames = lists.map((localVolumes) => {
+ renderer.render({ ...camera, time: 0, environment: { ...light, localVolumes }, outputFramebuffer: output.framebuffer });
+ return Array.from(readFloatPixels(renderer.context, output.framebuffer, size, size));
+ });
+ const glError = renderer.context.getError();
+ output.dispose();
+ renderer.dispose?.();
+ return { frames, glError };
+ };
+ return page.evaluate(task, { size: SIZE, lists: volumeLists, camera: LOOKING_DOWN, light: LIGHT });
+}
+
+// The display shows aces(light) ^ (1 / 2.2); this undoes both for a channel.
+function lightOf(displayed) {
+ let low = 0;
+ let high = 64;
+ for (let round = 0; round < 40; round++) {
+ const middle = (low + high) / 2;
+ if (applyViewTransform('aces', [middle, middle, middle])[0] ** (1 / 2.2) < displayed) low = middle;
+ else high = middle;
+ }
+ return low;
+}
+
+// One linear value per pixel (the green channel), top row first.
+function rasterRadiance(frame) {
+ const result = new Float64Array(SIZE * SIZE);
+ for (let row = 0; row < SIZE; row++) {
+ for (let column = 0; column < SIZE; column++) result[row * SIZE + column] = lightOf(frame[((SIZE - 1 - row) * SIZE + column) * 4 + 1]);
+ }
+ return result;
+}
+
+async function cpuRadiance(volume) {
+ const material = { tag: 'surface', metallic: 0, roughness: 1, color: [0, 0, 0], ior: 1, emission: 1, emissiveColor: [1, 1, 1] };
+ const half = 20;
+ const geometry = {
+ positions: new Float32Array([-half, 0, half, half, 0, half, half, 0, -half, -half, 0, -half]),
+ 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]),
+ };
+ const map = { width: 4, height: 2, channels: 3, data: new Float32Array(4 * 2 * 3).fill(SKY_LEVEL), intensity: 1, rotation: 0 };
+ const { linear } = await renderPathTracedImage(
+ { parts: [{ name: 'ground', geometry, material }], environment: { localVolumes: volume ? [volume] : [], keyColor: SUN_COLOR, lightDirection: SUN_DIRECTION, map }, camera: LOOKING_DOWN },
+ { width: CPU_SIZE, height: CPU_SIZE, denoise: false, threads: 1, bounces: 1, samples: CPU_SAMPLES },
+ );
+ const result = new Float64Array(CPU_SIZE * CPU_SIZE);
+ for (let pixel = 0; pixel < result.length; pixel++) result[pixel] = linear[pixel * 3 + 1];
+ return result;
+}
+
+// The mean over a square cell of a square image of `size` pixels, the cell given in the units of a 64 pixel frame.
+function cellMean(values, size, column, row, cell) {
+ const scale = size / SIZE;
+ let total = 0;
+ let count = 0;
+ for (let y = Math.floor(row * cell * scale); y < Math.floor((row + 1) * cell * scale); y++) {
+ for (let x = Math.floor(column * cell * scale); x < Math.floor((column + 1) * cell * scale); x++) {
+ total += values[y * size + x];
+ count++;
+ }
+ }
+ return total / count;
+}
+
+function writeArtifacts(folder, raster, cpu, summary) {
+ mkdirSync(folder, { recursive: true });
+ const scale = 4;
+ const panel = SIZE * scale;
+ const width = panel * 3;
+ const pixels = new Uint8Array(width * panel * 4);
+ for (let y = 0; y < panel; y++) {
+ for (let x = 0; x < panel; x++) {
+ const rasterValue = raster[Math.floor(y / scale) * SIZE + Math.floor(x / scale)];
+ const cpuValue = cpu[Math.floor(y * CPU_SIZE / panel) * CPU_SIZE + Math.floor(x * CPU_SIZE / panel)];
+ const displayOf = value => applyViewTransform('aces', [value, value, value])[0] ** (1 / 2.2);
+ const difference = Math.min(1, Math.abs(rasterValue - cpuValue) * 4);
+ [displayOf(rasterValue), displayOf(cpuValue), difference].forEach((value, index) => {
+ const at = (y * width + index * panel + x) * 4;
+ pixels.fill(Math.round(Math.max(0, Math.min(1, value)) * 255), at, at + 3);
+ pixels[at + 3] = 255;
+ });
+ }
+ }
+ writeFileSync(join(folder, 'scatter-raster-cpu-difference.png'), encodePng(pixels, width, panel));
+ writeFileSync(join(folder, 'scatter-radiance.json'), `${JSON.stringify({
+ volume: SMOKE_BOX,
+ note: 'Left to right in the still: rasterizer, CPU path tracer (16 samples, 32 px), absolute difference times 4. Linear radiance (green) of a sunlit smoke box seen from above, sun from +x (the right half) over an even grey sky.',
+ regionTolerance: REGION_TOLERANCE,
+ meanTolerance: MEAN_TOLERANCE,
+ ...summary,
+ }, null, 2)}\n`);
+}
+
+test('the rasterizer and the CPU path tracer light a smoke box alike, and the side toward the sun is brighter', 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 {
+ const launchArguments = ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--enable-webgl', '--ignore-gpu-blocklist'];
+ browser = await chromium.launch({ headless: true, args: launchArguments }).catch(() => chromium.launch({ headless: true, channel: 'chrome', args: launchArguments }));
+ } catch (error) {
+ context.skip(`Chrome did not start: ${error.message.split('\n')[0]}`);
+ return;
+ }
+ const page = await browser.newPage({ viewport: { width: SIZE, height: SIZE } });
+ await page.goto(`http://127.0.0.1:${port}/`);
+ const { frames: [clear, scatteringOff, scattering], glError } = await rasterFrames(page, [[], [{ ...SMOKE_BOX, scatter: 0 }], [SMOKE_BOX]]);
+ assert.equal(glError, 0);
+ const { scatter, ...withoutField } = SMOKE_BOX;
+ const { frames: [omitted] } = await rasterFrames(page, [[withoutField]]);
+ assert.deepEqual(scatteringOff, omitted, 'scatter 0 must draw exactly as a volume with no scatter field');
+ assert.notDeepEqual(scatteringOff, scattering);
+
+ const raster = rasterRadiance(scattering);
+ const rasterClear = rasterRadiance(clear);
+ const cpu = await cpuRadiance(SMOKE_BOX);
+ const cpuClear = await cpuRadiance(null);
+ const cells = 8;
+ const cellSize = SIZE / cells;
+ const regions = [];
+ for (let row = 0; row < cells; row++) {
+ for (let column = 0; column < cells; column++) {
+ const rasterMean = cellMean(raster, SIZE, column, row, cellSize);
+ const cpuMean = cellMean(cpu, CPU_SIZE, column, row, cellSize);
+ regions.push({ column, row, raster: +rasterMean.toFixed(4), cpu: +cpuMean.toFixed(4), difference: +Math.abs(rasterMean - cpuMean).toFixed(4) });
+ }
+ }
+ const meanOf = values => values.reduce((total, value) => total + value, 0) / values.length;
+ const rasterMean = meanOf(Array.from(raster));
+ const cpuMean = meanOf(Array.from(cpu));
+ const worst = regions.reduce((a, b) => (b.difference > a.difference ? b : a));
+ const halfMean = (values, size, right) => {
+ let total = 0;
+ let count = 0;
+ for (let y = 0; y < size; y++) {
+ for (let x = right ? size / 2 : 0; x < (right ? size : size / 2); x++) {
+ total += values[y * size + x];
+ count++;
+ }
+ }
+ return total / count;
+ };
+ const summary = {
+ whole: { raster: +rasterMean.toFixed(4), cpu: +cpuMean.toFixed(4) },
+ clearGround: { raster: +meanOf(Array.from(rasterClear)).toFixed(4), cpu: +meanOf(Array.from(cpuClear)).toFixed(4) },
+ litHalf: { raster: +halfMean(raster, SIZE, true).toFixed(4), cpu: +halfMean(cpu, CPU_SIZE, true).toFixed(4) },
+ shadedHalf: { raster: +halfMean(raster, SIZE, false).toFixed(4), cpu: +halfMean(cpu, CPU_SIZE, false).toFixed(4) },
+ worstRegion: worst,
+ cells: regions,
+ };
+ if (process.env.LOCAL_VOLUME_SCATTER_ARTIFACTS) writeArtifacts(process.env.LOCAL_VOLUME_SCATTER_ARTIFACTS, raster, cpu, summary);
+ assert.ok(Math.abs(rasterMean - cpuMean) < MEAN_TOLERANCE, `whole frame: raster ${rasterMean} against CPU ${cpuMean}`);
+ assert.ok(worst.difference < REGION_TOLERANCE, `worst region ${JSON.stringify(worst)}`);
+ assert.ok(summary.litHalf.raster > summary.shadedHalf.raster + 0.01, `rasterizer: lit half ${summary.litHalf.raster}, shaded half ${summary.shadedHalf.raster}`);
+ assert.ok(summary.litHalf.cpu > summary.shadedHalf.cpu + 0.01, `CPU: lit half ${summary.litHalf.cpu}, shaded half ${summary.shadedHalf.cpu}`);
+ } finally {
+ await browser?.close();
+ server.kill();
+ }
+});
diff --git a/tests/local-volumes.test.js b/tests/local-volumes.test.js
index d1c4aaf4..46de93eb 100644
--- a/tests/local-volumes.test.js
+++ b/tests/local-volumes.test.js
@@ -58,6 +58,8 @@ test('the post program carries the local step only when asked, and a recipe name
assert.equal(normalizeAgentLook({ environment }).environment.localVolumes[0].steps, 16);
assert.equal('localVolumes' in normalizeAgentLook({}).environment, false);
assert.throws(() => normalizeAgentLook({ environment: { localVolumes: [{ center: [0, 0, 0], size: [1, 1, -1] }] } }), /environment\.localVolumes\[0\]\.size/);
+ assert.equal(normalizeAgentLook({ environment: { localVolumes: [{ center: [0, 0, 0], size: [1, 1, 1], scatter: 0.6 }] } }).environment.localVolumes[0].scatter, 0.6);
+ assert.throws(() => normalizeAgentLook({ environment: { localVolumes: [{ center: [0, 0, 0], size: [1, 1, 1], scatter: 2 }] } }), /environment\.localVolumes\[0\]\.scatter/);
assert.ok(agentSceneModulesNeeded({ environment }).includes('fogShader'));
});