Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Ripple the faded edge of a local volume with its noise, soften the lit rim and blur thin smoke further (#855)

Nguyen Xuan Anf869e080dfb7
diff --git a/changes/855-edge-warp.md b/changes/855-edge-warp.md
new file mode 100644
index 00000000..5fd9ab74
--- /dev/null
+++ b/changes/855-edge-warp.md
@@ -0,0 +1 @@
+- The noise of a local volume also ripples its faded edge, so a wide-falloff box or sphere reads as a cloud and not as a rounded rectangle; the blur behind a thin volume reaches 24 px of a 540 row frame and no longer carries the edge of an object in front into it; the sun's shadow depth is 1.2 and the fringe saturates at profile 1/6 so the lit side of a smoke has no bright rim around a dark body (#855)
diff --git a/docs/volumetric.md b/docs/volumetric.md
index 6b06b7d9..51994a9f 100644
--- a/docs/volumetric.md
+++ b/docs/volumetric.md
@@ -127,7 +127,7 @@ In a scene with an irradiance grid (`bake.irradianceGrid`) the bounce term is th
| `falloff` | `0.5` | `0` to `1`. The outer share of the volume over which the density fades to zero (`0` is a hard edge) |
| `blur` | `1` | `0` to `1`. How much the light seen through the volume is blurred, by its optical depth (see Thick smoke and thin haze). `0` keeps it sharp |
| `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 |
+| `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)`, and the noise also pushes the faded edge in and out (by up to half the fade width times `noiseAmount`, zero at the core and at the outer face), so a box or a sphere with a wide `falloff` such as 0.85 reads as a cloud and not as a rounded rectangle. 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. With `noiseAmount` above 0 the count is raised to two samples per noise cell along the ray (`ceil(length * noiseScale * 2)`, at most 32), because fewer samples than that skip whole cells and a fine pixel-pitch dither of the start offset shows in dense smoke (8 steps measured); a volume without noise takes exactly `steps` |
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.
@@ -144,7 +144,7 @@ Each volume is marched on its own between its entry and its exit, cut at the fir
Measured on the 2.4 m high, 3.2 m wide box of the smoke still, from rays through its middle (noise 0.5): density 0.3 let 50 to 64 percent of the green channel through, 1.5 let 6 to 25 percent and 3 let 0.2 to 2.7 percent. A uniform slab of 1 m (`falloff: 0`) of density 3.5 let 0.0303 through in the rasterizer and 0.0302 in the tracer against exp(-3.5) = 0.0302; density 0.7 gave 0.4978 and 0.4965 against 0.4966 (`tests/local-volume-blur.test.js`; worst 8 by 8 region differed by 0.0013).
-Thin smoke also blurs what is behind it. The rasterizer averages 12 taps of the frame over a disc of radius `14 * (1 - exp(-opticalDepth))` pixels of a 540 row frame (it scales with the frame height), where the optical depth is the mean of the extinction along the ray, times `blur`. It is zero at zero depth and never passes 14 px, only runs on pixels whose ray meets a volume, and a tap counts only where its surface lies at or past the ray's first volume entry, so an object in front of the volume is not smeared into it. It reads the frame's mip chain, so a frame with a blurring volume generates mips like a frame with `volumeFog`. The CPU path tracer marches straight through a local volume and does not scatter the background, so it draws the same dimming but no blur: set `blur: 0` to compare the two.
+Thin smoke also blurs what is behind it. The rasterizer averages 12 taps of the frame over a disc of radius `24 * (1 - exp(-1.5 * opticalDepth))` pixels of a 540 row frame (it scales with the frame height), where the optical depth is the mean of the extinction along the ray, times `blur`. It is zero at zero depth and never passes 24 px, only runs on pixels whose ray meets a volume, and a tap counts only where its surface lies at or past the ray's first volume entry, so an object in front of the volume is not smeared into it (the depth is also read one filter footprint to each side of the tap, so the filter does not carry the colour of an object's edge into the volume). It reads the frame's mip chain, so a frame with a blurring volume generates mips like a frame with `volumeFog`. The CPU path tracer marches straight through a local volume and does not scatter the background, so it draws the same dimming but no blur: set `blur: 0` to compare the two.
### Lit volumes
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 158de1fd..4cf21fc6 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -272,7 +272,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), scatter 0-1 (0; lit by the key light and the sky, not with fit mesh), blur 0-1 (1; softens the light behind it by optical depth, max 14 px at 540 rows), 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; density is extinction per metre times absorption, light behind = exp(-density * absorption * metres): about 0.3 is a thin haze (half shows through), 3 is thick smoke (under 3 percent); 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), blur 0-1 (1; softens the light behind it by optical depth, max 24 px at 540 rows), noiseAmount 0-1 (0; also ripples the faded edge, so use falloff 0.8 to 0.9 for a round cloud), 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; density is extinction per metre times absorption, light behind = exp(-density * absorption * metres): about 0.3 is a thin haze (half shows through), 3 is thick smoke (under 3 percent); 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 b59f5a4d..4455c8b7 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, LOCAL_VOLUME_MAXIMUM_STEPS, LOCAL_VOLUME_STEPS_PER_NOISE_CELL, LOCAL_VOLUME_BLUR_PIXELS, LOCAL_VOLUME_KEY_GAIN, LOCAL_VOLUME_LIGHT_DEPTH_SATURATION, LOCAL_VOLUME_SHADOW_STRENGTH, LOCAL_VOLUME_SKY_GAIN, LOCAL_VOLUME_SUN_FLATTEN } from './local-volumes.js';
+import { resolveLocalVolumes, createLocalVolumeBuffers, packLocalVolumes, LOCAL_VOLUME_MAXIMUM_STEPS, LOCAL_VOLUME_STEPS_PER_NOISE_CELL, LOCAL_VOLUME_BLUR_PIXELS, LOCAL_VOLUME_BLUR_RATE, LOCAL_VOLUME_EDGE_WARP, LOCAL_VOLUME_KEY_GAIN, LOCAL_VOLUME_LIGHT_DEPTH_SATURATION, LOCAL_VOLUME_SHADOW_STRENGTH, LOCAL_VOLUME_SKY_GAIN, LOCAL_VOLUME_SUN_FLATTEN } 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';
@@ -201,24 +201,33 @@ vec2 localVolumeInterval(int index, vec3 origin, vec3 direction) {
}
return vec2(entry, exitDistance);
}
+// Where a fade position (0 at the core, 1 at the outer face) lands once the noise has pushed the edge in and out, most at the middle of the fade (local-volumes.js repeats it).
+float localVolumeWarpedFade(float position, float noiseAmount, float noise) {
+ float clamped = clamp(position, 0.0, 1.0);
+ return clamped + (0.5 - noise) * noiseAmount * ${LOCAL_VOLUME_EDGE_WARP.toFixed(3)} * 4.0 * clamped * (1.0 - clamped);
+}
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;
float falloff = localVolumeExtents[index].w;
+ float noiseAmount = withNoise ? localVolumeAbsorption[index].w : 0.0;
+ float noise = noiseAmount > 0.0 ? localVolumeNoise(position * localVolumeEmission[index].w) : 0.5;
float profile;
if (localVolumeCenters[index].w > 0.5) {
float distanceRatio = length(offset) / halfSize.x;
- profile = falloff > 0.0 ? 1.0 - smoothstep(1.0 - falloff, 1.0, distanceRatio) : 1.0 - step(1.0, distanceRatio);
+ float fade = localVolumeWarpedFade((distanceRatio - (1.0 - falloff)) / max(falloff, 1e-6), noiseAmount, noise);
+ profile = falloff > 0.0 ? 1.0 - smoothstep(0.0, 1.0, fade) : 1.0 - step(1.0, distanceRatio);
+ if (distanceRatio >= 1.0) profile = 0.0;
} else {
vec3 ratios = abs(offset) / halfSize;
// The distance past the core box is round at the corners; the plain largest ratio fades along boxes with mitred creases (local-volumes.js repeats it).
float fadeDistance = length(max(ratios - (1.0 - falloff), 0.0));
- profile = falloff > 0.0 ? 1.0 - smoothstep(0.0, 1.0, fadeDistance / falloff) : 1.0 - step(1.0, max(max(ratios.x, ratios.y), ratios.z));
+ float fade = localVolumeWarpedFade(fadeDistance / max(falloff, 1e-6), noiseAmount, noise);
+ profile = falloff > 0.0 ? 1.0 - smoothstep(0.0, 1.0, fade) : 1.0 - step(1.0, max(max(ratios.x, ratios.y), ratios.z));
if (max(max(ratios.x, ratios.y), ratios.z) >= 1.0) profile = 0.0;
}
- float noiseAmount = localVolumeAbsorption[index].w;
- if (withNoise && noiseAmount > 0.0) profile *= mix(1.0, localVolumeNoise(position * localVolumeEmission[index].w) * 2.0, noiseAmount);
+ if (noiseAmount > 0.0) profile *= mix(1.0, noise * 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.
@@ -256,18 +265,25 @@ vec3 localVolumeInScatter(int index, vec3 position, vec3 direction) {
// The light behind a volume, blurred by the optical depth in front of it: taps of the frame spread over a disc whose radius grows with the depth,
// each counted only where its surface lies at or past the ray's first volume entry, so an object in front of the volume is never smeared into it.
vec3 localVolumeBlurred(vec3 background, float opticalDepth, float firstEntry, vec3 origin, vec3 direction) {
- float radiusPixels = ${LOCAL_VOLUME_BLUR_PIXELS.toFixed(1)} * (resolution.y / 540.0) * (1.0 - exp(-opticalDepth));
+ float radiusPixels = ${LOCAL_VOLUME_BLUR_PIXELS.toFixed(1)} * (resolution.y / 540.0) * (1.0 - exp(-${LOCAL_VOLUME_BLUR_RATE.toFixed(2)} * opticalDepth));
if (radiusPixels < 0.05) return background;
- float lod = max(0.0, log2(radiusPixels * 0.5));
+ float lod = max(0.0, log2(radiusPixels * 0.5) - 1.0);
+ float footprint = exp2(lod) + 1.0;
vec3 sum = background;
float weight = 1.0;
for (int tap = 0; tap < 12; tap++) {
float index = float(tap) + 0.5;
vec2 offsetPixels = vec2(cos(index * 2.4), sin(index * 2.4)) * (radiusPixels * sqrt(index / 12.0));
vec2 coordinate = textureCoordinate + offsetPixels / resolution;
- vec4 tapPoint = inverseViewProjection * vec4(coordinate * 2.0 - 1.0, texture(sceneDepth, coordinate).r * 2.0 - 1.0, 1.0);
- float tapDistance = tapPoint.w > 0.0 ? dot(tapPoint.xyz - origin * tapPoint.w, direction) / tapPoint.w : 1e30;
- if (tapDistance < firstEntry) continue;
+ // The surface at the tap and one filter footprint to each side of it: the filter blends the colour of an object in front of the volume into a tap whose own depth is still the far one.
+ float nearestTap = 1e30;
+ for (int side = 0; side < 5; side++) {
+ vec2 shift = side == 0 ? vec2(0.0) : (side == 1 ? vec2(footprint, 0.0) : (side == 2 ? vec2(-footprint, 0.0) : (side == 3 ? vec2(0.0, footprint) : vec2(0.0, -footprint))));
+ vec2 sideCoordinate = coordinate + shift / resolution;
+ vec4 sidePoint = inverseViewProjection * vec4(sideCoordinate * 2.0 - 1.0, texture(sceneDepth, sideCoordinate).r * 2.0 - 1.0, 1.0);
+ nearestTap = min(nearestTap, sidePoint.w > 0.0 ? dot(sidePoint.xyz - origin * sidePoint.w, direction) / sidePoint.w : 1e30);
+ }
+ if (nearestTap < firstEntry) continue;
sum += textureLod(frameTexture, coordinate, lod).rgb;
weight += 1.0;
}
diff --git a/src/local-volumes.js b/src/local-volumes.js
index 77658b2b..a77044bd 100644
--- a/src/local-volumes.js
+++ b/src/local-volumes.js
@@ -1,5 +1,5 @@
import { finiteRange } from './volumetric.js';
-import { localVolumeNoiseFactor } from './local-volume-noise.js';
+import { localVolumeNoise } from './local-volume-noise.js';
// 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
@@ -112,23 +112,26 @@ export const LOCAL_VOLUME_KEY_GAIN = 3;
* ray running along the faded top or side skin is shaded by the whole volume, not by the skin's low density. With the plain profile that
* skin is lit far above the core and reads as a bright rim around the form.
*/
-export const LOCAL_VOLUME_LIGHT_DEPTH_SATURATION = 3;
+export const LOCAL_VOLUME_LIGHT_DEPTH_SATURATION = 6;
/**
* How many times the volume's own depth toward the sun counts in the key light's attenuation. Counting it more than once keeps the shaded
* side of the smoke clearly 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 = 3;
+export const LOCAL_VOLUME_SHADOW_STRENGTH = 1.2;
/** The share of the mean sky radiance the sky term of a scattering volume keeps. The sky lights the whole volume evenly, so a high share flattens the form the sun gives it. */
export const LOCAL_VOLUME_SKY_GAIN = 0.5;
/**
* The widest blur, in pixels of a 540 row frame (it scales with the frame height), that the light behind a volume gets: the radius grows as
- * `cap * (1 - exp(-opticalDepth))`, so none at zero depth, most of the cap by an optical depth of 2, and it never passes the cap. A thick volume hides the
+ * `cap * (1 - exp(-LOCAL_VOLUME_BLUR_RATE * opticalDepth))`, so none at zero depth, most of the cap by an optical depth of 1.5, and it never passes the cap. A thick volume hides the
* background anyway, a thin one shows it blurred (#855).
*/
-export const LOCAL_VOLUME_BLUR_PIXELS = 14;
+export const LOCAL_VOLUME_BLUR_PIXELS = 24;
+
+/** How fast the blur grows with optical depth: a thin wisp of optical depth 0.7 already blurs by about 15 px, so a haze visibly softens the horizon behind it (#855). */
+export const LOCAL_VOLUME_BLUR_RATE = 1.5;
/** Samples the march takes per cell of the density noise at least: fewer step over whole cells and the dither of the start offset shows as pixel-pitch grain (#855). */
export const LOCAL_VOLUME_STEPS_PER_NOISE_CELL = 2;
@@ -156,7 +159,20 @@ function fadeProfile(ratio) {
return 1 - clamped * clamped * (3 - 2 * clamped);
}
-/** 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. */
+/**
+ * How far the noise pushes the faded edge of a volume in and out, as a share of the fade width, at its largest (#855). The fade is a smooth
+ * ramp from the core to the edge of the form, so without this a box or a sphere keeps a flat top and flat sides under the noise and reads as
+ * a rounded rectangle, not a cloud. The push is zero at the core and at the outer face, so the core stays as thick and no step shows where the form ends.
+ */
+export const LOCAL_VOLUME_EDGE_WARP = 1;
+
+/** The fade position (0 at the core, 1 at the outer face) after the noise has pushed the edge: `position` moved by the noise, most at the middle of the fade. */
+export function warpedFadePosition(position, noiseAmount, noise) {
+ const clamped = Math.min(1, Math.max(0, position));
+ return clamped + (0.5 - noise) * noiseAmount * LOCAL_VOLUME_EDGE_WARP * 4 * clamped * (1 - clamped);
+}
+
+/** 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. With noise the fade edge is also pushed in and out (LOCAL_VOLUME_EDGE_WARP). */
export function localVolumeProfile(volume, x, y, z, withNoise = true) {
if (volume.shape === 'mesh') return 1;
let offsetX = x - volume.center[0];
@@ -170,11 +186,13 @@ export function localVolumeProfile(volume, x, y, z, withNoise = true) {
offsetX = alongX;
offsetY = alongY;
}
+ const noisy = withNoise && volume.noiseAmount > 0;
+ const noise = noisy ? localVolumeNoise(x * volume.noiseScale, y * volume.noiseScale, z * volume.noiseScale) : 0.5;
let profile = 1;
if (volume.shape === 'sphere') {
const distance = Math.hypot(offsetX, offsetY, offsetZ) / volume.radius;
if (distance >= 1) return 0;
- if (volume.falloff > 0) profile = fadeProfile((distance - (1 - volume.falloff)) / volume.falloff);
+ if (volume.falloff > 0) profile = fadeProfile(warpedFadePosition((distance - (1 - volume.falloff)) / volume.falloff, noisy ? volume.noiseAmount : 0, noise));
} else {
const ratioX = Math.abs(offsetX) / (volume.size[0] / 2);
const ratioY = Math.abs(offsetY) / (volume.size[1] / 2);
@@ -184,10 +202,10 @@ export function localVolumeProfile(volume, x, y, z, withNoise = true) {
// The distance past the core box, which is round at the corners: the plain largest ratio fades along boxes with mitred creases.
const core = 1 - volume.falloff;
const fadeDistance = Math.hypot(Math.max(ratioX - core, 0), Math.max(ratioY - core, 0), Math.max(ratioZ - core, 0));
- profile = fadeProfile(fadeDistance / volume.falloff);
+ profile = fadeProfile(warpedFadePosition(fadeDistance / volume.falloff, noisy ? volume.noiseAmount : 0, noise));
}
}
- if (withNoise && volume.noiseAmount > 0) profile *= localVolumeNoiseFactor(volume, x, y, z);
+ if (noisy) profile *= 1 + (2 * noise - 1) * volume.noiseAmount;
return profile;
}
diff --git a/tests/local-volume-blur.test.js b/tests/local-volume-blur.test.js
index 8a1e9d61..f9eb394b 100644
--- a/tests/local-volume-blur.test.js
+++ b/tests/local-volume-blur.test.js
@@ -210,7 +210,7 @@ test('density is extinction per metre: a slab of density d and thickness t lets
const withoutBlur = await drawRaster(page, [occluder], [{ ...haze, blur: 0 }]);
const withBlur = await drawRaster(page, [occluder], [haze]);
let smear = 0;
- for (let offset = 14; offset <= 16; offset++) smear = Math.max(smear, Math.abs(withBlur[(SIZE / 2) * SIZE + SIZE / 2 + offset] - withoutBlur[(SIZE / 2) * SIZE + SIZE / 2 + offset]));
+ for (let offset = 13; offset <= 16; offset++) smear = Math.max(smear, Math.abs(withBlur[(SIZE / 2) * SIZE + SIZE / 2 + offset] - withoutBlur[(SIZE / 2) * SIZE + SIZE / 2 + offset]));
numbers.smearNextToObjectInFront = +smear.toFixed(5);
assert.ok(smear < 0.005, `an object in front smeared into the volume by ${smear}`);
if (process.env.LOCAL_VOLUME_BLUR_ARTIFACTS) {
diff --git a/tests/local-volume-edge-warp.test.js b/tests/local-volume-edge-warp.test.js
new file mode 100644
index 00000000..15de365b
--- /dev/null
+++ b/tests/local-volume-edge-warp.test.js
@@ -0,0 +1,49 @@
+// The noise pushes the faded edge of a local volume in and out (issue 855), so a box or a sphere reads as a cloud and not as a rounded rectangle.
+// The rasterizer's post shader repeats this rule and tests/local-volume-noise.test.js compares the two renderers on a noisy volume.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { resolveLocalVolumes, localVolumeProfile, warpedFadePosition, LOCAL_VOLUME_EDGE_WARP } from '../src/local-volumes.js';
+
+test('the warp leaves the core and the outer face where they are and moves the middle of the fade by the noise', () => {
+ for (const noise of [0, 0.3, 0.5, 0.9, 1]) {
+ assert.equal(warpedFadePosition(0, 0.5, noise), 0);
+ assert.equal(warpedFadePosition(1, 0.5, noise), 1);
+ }
+ assert.equal(warpedFadePosition(0.5, 0.5, 0.5), 0.5, 'a noise of one half is neutral');
+ assert.equal(warpedFadePosition(0.5, 0, 0), 0.5, 'noiseAmount 0 is neutral');
+ assert.ok(warpedFadePosition(0.5, 0.5, 0) > 0.5, 'low noise pushes the edge in');
+ assert.ok(warpedFadePosition(0.5, 0.5, 1) < 0.5, 'high noise pushes the edge out');
+ const largest = Math.abs(warpedFadePosition(0.5, 1, 0) - 0.5);
+ assert.ok(Math.abs(largest - 0.5 * LOCAL_VOLUME_EDGE_WARP) < 1e-12, 'at most half of the fade width times the warp');
+});
+
+function topEdgeHeights(noiseAmount) {
+ const [volume] = resolveLocalVolumes([{ shape: 'box', center: [0, 0, 0], size: [4, 4, 4], falloff: 0.85, noiseAmount, noiseScale: 1.5 }]);
+ const heights = [];
+ for (let x = -1; x <= 1; x += 0.1) {
+ let height = 0;
+ for (let y = 0; y < 2; y += 0.01) if (localVolumeProfile(volume, x, y, 0, true) > 0.3) height = y;
+ heights.push(height);
+ }
+ return heights;
+}
+
+test('with noise the top edge of a box wanders away from the smooth dome the plain fade draws', () => {
+ const noisy = topEdgeHeights(0.6);
+ const plain = topEdgeHeights(0);
+ const wander = Math.max(...noisy.map((height, index) => Math.abs(height - plain[index])));
+ assert.ok(wander > 0.15, `the top edge moves by only ${wander} m from the plain dome`);
+});
+
+test('the warp never lets density past the outer face of the volume', () => {
+ const [box, sphere] = resolveLocalVolumes([
+ { shape: 'box', center: [0, 0, 0], size: [2, 2, 2], falloff: 0.9, noiseAmount: 1, noiseScale: 3 },
+ { shape: 'sphere', center: [0, 0, 0], radius: 1, falloff: 0.9, noiseAmount: 1, noiseScale: 3 },
+ ]);
+ for (let step = 0; step < 200; step++) {
+ const x = 1 + step * 0.001;
+ assert.equal(localVolumeProfile(box, x, 0.1 * step % 1, 0.3), 0);
+ assert.equal(localVolumeProfile(sphere, x, 0.1, 0.2), 0);
+ }
+ for (let step = 0; step < 100; step++) assert.ok(localVolumeProfile(box, 0.99999, step * 0.01, 0) < 1e-3, 'density fades to nothing at the face');
+});