Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Shade the far side of a lit local volume: smooth light depth, key gain and shadow strength (#855)

Nguyen Xuan An341bf97551a9
diff --git a/changes/855-sun-shadow-strength.md b/changes/855-sun-shadow-strength.md
new file mode 100644
index 00000000..33458a64
--- /dev/null
+++ b/changes/855-sun-shadow-strength.md
@@ -0,0 +1 @@
+- A scattering local volume lights its key term through the smooth depth toward the sun (counted four times, scaled by a key gain of 4) and its sky term through the smooth depth in five directions, so the sunward side is brighter than the shaded side and the core of a thick smoke is darker than its rim; the depth taps skip the noise, which cuts the cost of a lit volume by more than half; `scatter: 0` is unchanged (#855)
diff --git a/changes/855-sun-shadow-strength.size.md b/changes/855-sun-shadow-strength.size.md
new file mode 100644
index 00000000..0cb998f7
--- /dev/null
+++ b/changes/855-sun-shadow-strength.size.md
@@ -0,0 +1,3 @@
+- entry:fog-shader: a noise-free profile form for the light taps, and the key gain and shadow strength constants in the lit local volume step, so the sunward side of a smoke is clearly brighter than its shade and the lit step costs less than half as much.
+- scene:agent-scene+lazy: the same key gain and shadow strength in the CPU path tracer's lit volume step, counted in the lazy bundle.
+- entry:path-tracer: the key gain and shadow strength in the CPU path tracer's lit volume step, a few dozen bytes to match the rasterizer.
diff --git a/docs/volumetric.md b/docs/volumetric.md
index 5cd39a94..90784b81 100644
--- a/docs/volumetric.md
+++ b/docs/volumetric.md
@@ -135,11 +135,11 @@ Each volume is marched on its own between its entry and its exit, cut at the fir
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. With an environment map the rasterizer still reads `skyTop` and `skyBottom`. It passes through the volume's own depth too: the mean of `exp(-depth)` over the up direction and the four horizontal directions, one midpoint tap each, so the middle of a thick smoke is darker than its rim instead of glowing as evenly as the edge.
+- The key light uses the same shadow map lookup (`keyVisibility`) and phase function (`henyeyGreenstein`, isotropic here) as `volumeFog`, times `exp(-depth * 4)` 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 smooth profile, without the noise, so the noise does not speckle the shading). The factor 4 (`LOCAL_VOLUME_SHADOW_STRENGTH` in `src/local-volumes.js`) is there because a sun in front of the smoke reaches it through its near face, so the plain depth differs little across the frame; the key light is also scaled by `LOCAL_VOLUME_KEY_GAIN` (4), the many scatters of a thick smoke that one isotropic scatter leaves a dozen times dimmer than the sky term. Together they make the sunward side clearly 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. With an environment map the rasterizer still reads `skyTop` and `skyBottom`. It passes through the volume's own depth too: the mean of `exp(-depth)` over the up direction and the four horizontal directions, one midpoint tap each of the smooth profile, so the middle of a thick smoke is darker than its rim instead of glowing as evenly as the edge.
- 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.
+- 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.0001 of linear radiance and the whole frame matched to four places (0.3351 both), inside the 0.01 and 0.005 tolerances. The half toward the sun read 0.341 and the shaded half 0.329 in both renderers. On the 960 x 540 smoke still (sun from the right, a 3.2 x 2.4 x 3.2 box) the right third of the smoke is about 14 to 17 percent brighter than the left third in displayed luma; the sun sits in front of the box, so no setting of the two factors takes that far past 20 percent without clipping the sunlit side. The volume pass costs about 2 ms a frame at scatter 0.8 against 0.7 ms at scatter 0.
### Mesh volumes
diff --git a/src/fog-shader.js b/src/fog-shader.js
index 3daf0681..654632b9 100644
--- a/src/fog-shader.js
+++ b/src/fog-shader.js
@@ -1,5 +1,5 @@
import { registerShaderFeatureCode } from './shader-registry.js';
-import { resolveLocalVolumes, createLocalVolumeBuffers, packLocalVolumes } from './local-volumes.js';
+import { resolveLocalVolumes, createLocalVolumeBuffers, packLocalVolumes, LOCAL_VOLUME_KEY_GAIN, LOCAL_VOLUME_SHADOW_STRENGTH } from './local-volumes.js';
import { bindLocalVolumeParts } from './local-volume-parts.js';
import { drawMeshVolumes } from './mesh-volume-pass.js';
import { FogFieldTexture, createFogLightBuffers, packFogLights, volumeShadowAmbient, DEFAULT_FLOW_STRENGTH, DEFAULT_FLOW_PERIOD, resolveFogDetail, fogUsesDetail } from './fog-field.js';
@@ -196,7 +196,7 @@ vec2 localVolumeInterval(int index, vec3 origin, vec3 direction) {
}
return vec2(entry, exitDistance);
}
-float localVolumeProfile(int index, vec3 position) {
+float localVolumeProfile(int index, vec3 position, bool withNoise) {
vec3 offset = position - localVolumeCenters[index].xyz;
if (localVolumeCenters[index].w < 0.5) offset = localVolumeLocal(index, offset);
vec3 halfSize = localVolumeExtents[index].xyz;
@@ -204,7 +204,7 @@ float localVolumeProfile(int index, vec3 position) {
float falloff = localVolumeExtents[index].w;
float profile = falloff > 0.0 ? 1.0 - smoothstep(1.0 - falloff, 1.0, distanceRatio) : 1.0 - step(1.0, distanceRatio);
float noiseAmount = localVolumeAbsorption[index].w;
- if (noiseAmount > 0.0) profile *= mix(1.0, localVolumeNoise(position * localVolumeEmission[index].w) * 2.0, noiseAmount);
+ if (withNoise && 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 along a direction, from midpoint taps of its profile.
@@ -213,7 +213,7 @@ vec3 localVolumeDepth(int index, vec3 position, vec3 direction, int taps) {
float profileSum = 0.0;
for (int tap = 0; tap < 3; tap++) {
if (tap >= taps) break;
- profileSum += localVolumeProfile(index, position + direction * (exitDistance * (float(tap) + 0.5) / float(taps)));
+ profileSum += localVolumeProfile(index, position + direction * (exitDistance * (float(tap) + 0.5) / float(taps)), false);
}
return localVolumeAbsorption[index].rgb * (profileSum * exitDistance / float(taps));
}
@@ -232,7 +232,7 @@ 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(-localVolumeDepth(index, position, towardSun, 3));
+ if (visibility > 0.001) sunLight = volumeLightColor * (henyeyGreenstein(dot(direction, towardSun), 0.0) * visibility * ${LOCAL_VOLUME_KEY_GAIN.toFixed(1)}) * exp(-localVolumeDepth(index, position, towardSun, 3) * ${LOCAL_VOLUME_SHADOW_STRENGTH.toFixed(1)});
return localVolumeSkyLight(index, position) + sunLight;
}
vec3 localVolumes(vec3 background) {
@@ -303,7 +303,7 @@ vec3 localVolumes(vec3 background) {
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);
+ float profile = localVolumeProfile(nearest, position, true);
radiance += transmittance * localVolumeEmission[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);
diff --git a/src/local-volumes.js b/src/local-volumes.js
index 3d8e2e3d..8bcd723a 100644
--- a/src/local-volumes.js
+++ b/src/local-volumes.js
@@ -97,8 +97,22 @@ export function packLocalVolumes(volumes, buffers) {
return buffers;
}
+/**
+ * How much the key light of a scattering volume is scaled over the single-scatter estimate. A smoke thick enough to show form scatters the sun many times
+ * and reads about as bright as a surface in the same sun, which one isotropic scatter (1 / 4 pi of the key colour) leaves about a dozen times too dark
+ * beside the sky term; the gain keeps the sunlit side clearly above the shaded side. The rasterizer and the CPU path tracer both apply it.
+ */
+export const LOCAL_VOLUME_KEY_GAIN = 4;
+
+/**
+ * How many times the volume's own depth toward the sun counts in the key light's attenuation. The sun of a scene seen from the front reaches a
+ * smoke through its near face, so the optical depth toward it differs little across the frame; counting the depth more than once keeps the shaded
+ * side of the smoke visibly darker than the sunlit side, the way the many scatters of a real smoke take the light from its shade.
+ */
+export const LOCAL_VOLUME_SHADOW_STRENGTH = 4;
+
/** The density factor of a volume at a point: 1 at the core, fading over the outer `falloff` share, times the noise factor (up to 2) when `noiseAmount` is above 0, as the post shader does. */
-export function localVolumeProfile(volume, x, y, z) {
+export function localVolumeProfile(volume, x, y, z, withNoise = true) {
if (volume.shape === 'mesh') return 1;
let offsetX = x - volume.center[0];
let offsetY = y - volume.center[1];
@@ -120,7 +134,7 @@ export function localVolumeProfile(volume, x, y, z) {
const ratio = Math.min(1, Math.max(0, (distance - (1 - volume.falloff)) / volume.falloff));
profile = 1 - ratio * ratio * (3 - 2 * ratio);
}
- if (volume.noiseAmount > 0) profile *= localVolumeNoiseFactor(volume, x, y, z);
+ if (withNoise && volume.noiseAmount > 0) profile *= localVolumeNoiseFactor(volume, x, y, z);
return profile;
}
diff --git a/src/path-tracer-volume.js b/src/path-tracer-volume.js
index 1face12d..ca0d2cca 100644
--- a/src/path-tracer-volume.js
+++ b/src/path-tracer-volume.js
@@ -1,5 +1,5 @@
import { resolveVolumeFog } from './volumetric.js';
-import { localVolumeInterval, localVolumeProfile } from './local-volumes.js';
+import { localVolumeInterval, localVolumeProfile, LOCAL_VOLUME_KEY_GAIN, LOCAL_VOLUME_SHADOW_STRENGTH } from './local-volumes.js';
import { countOpenEdges } from './local-volume-parts.js';
import { buildTriangleBvh } from './triangle-bvh.js';
import { createTracer } from './ray-query.js';
@@ -180,7 +180,7 @@ function writeOpticalDepth(volume, x, y, z, direction, taps, span, out) {
let profileSum = 0;
for (let tap = 0; tap < taps; tap++) {
const distance = exitDistance * (tap + 0.5) / taps;
- profileSum += localVolumeProfile(volume, x + direction[0] * distance, y + direction[1] * distance, z + direction[2] * distance);
+ profileSum += localVolumeProfile(volume, x + direction[0] * distance, y + direction[1] * distance, z + direction[2] * distance, false);
}
for (let channel = 0; channel < 3; channel++) out[channel] = volume.absorption[channel] * volume.density * profileSum * exitDistance / taps;
}
@@ -223,7 +223,7 @@ export function createLocalVolumeCrossing(volumes, lighting = null) {
writeOpticalDepth(volume, x, y, z, sun.direction, SUN_DEPTH_TAPS, 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++) sunLight[channel] = sun.color[channel] * phase * LOCAL_VOLUME_KEY_GAIN * Math.exp(-sunDepth[channel] * LOCAL_VOLUME_SHADOW_STRENGTH);
}
for (let channel = 0; channel < 3; channel++) {
const scattered = volume.scatter * (1 - Math.exp(-volume.absorption[channel] * volume.density * width));
diff --git a/tests/local-volume-scatter.test.js b/tests/local-volume-scatter.test.js
index 6479b160..312ae636 100644
--- a/tests/local-volume-scatter.test.js
+++ b/tests/local-volume-scatter.test.js
@@ -12,7 +12,7 @@ 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 { resolveLocalVolumes, createLocalVolumeBuffers, packLocalVolumes, localVolumeProfile, LOCAL_VOLUME_KEY_GAIN, LOCAL_VOLUME_SHADOW_STRENGTH } from '../src/local-volumes.js';
import { createLocalVolumeCrossing, meanEnvironmentRadiance } from '../src/path-tracer-volume.js';
const REGION_TOLERANCE = 0.01;
@@ -80,6 +80,27 @@ test('a volume with scatter 0 draws exactly as it did: no light is added and the
assert.ok(withLighting.throughput[0] < 1);
});
+test('the key light of a thin volume is the phase function times the key gain, and a thick box shades its far side by the shadow strength', () => {
+ const thin = downRay({ ...SMOKE_BOX, size: [0.05, 0.05, 0.05], falloff: 0 }, FULL_SUN, 0);
+ const extinguished = 1 - thin.throughput[1];
+ const expected = SMOKE_BOX.scatter * SUN_COLOR[1] * LOCAL_VOLUME_KEY_GAIN / (4 * Math.PI);
+ const returned = thin.emitted[1] / extinguished;
+ // The thin box still shades itself a little (its own depth toward the sun), so the open value is an upper bound.
+ assert.ok(returned < expected && returned > 0.85 * expected, `thin volume returns ${returned}, expected up to ${expected}`);
+ const lit = downRay(SMOKE_BOX, FULL_SUN, 1.2).emitted[1];
+ const shaded = downRay(SMOKE_BOX, FULL_SUN, -1.2).emitted[1];
+ assert.ok(LOCAL_VOLUME_SHADOW_STRENGTH > 1);
+ assert.ok(lit > shaded * 2.5, `lit side ${lit} against shaded side ${shaded}`);
+});
+
+test('the light depth of a noisy volume is its smooth envelope, so the noise does not speckle the shading', () => {
+ const [noisy] = resolveLocalVolumes([{ ...SMOKE_BOX, noiseAmount: 0.9, noiseScale: 2.2 }]);
+ const [smooth] = resolveLocalVolumes([{ ...SMOKE_BOX }]);
+ const point = [0.4, 1.3, 0.2];
+ assert.equal(localVolumeProfile(noisy, ...point, false), localVolumeProfile(smooth, ...point));
+ assert.notEqual(localVolumeProfile(noisy, ...point), localVolumeProfile(smooth, ...point));
+});
+
// The sky light per unit of what a ray extinguishes, as a share of the open-sky value (scatter times the sky level).
function skyShare(volume) {
const sky = { sun: null, ambient: [SKY_LEVEL, SKY_LEVEL, SKY_LEVEL], sunVisibility: () => 1 };