3D engine that AI agents drive
Volume fog: density/velocity field, flow-advected noise and point-light scattering
Nguyen Xuan An474508cc6688
diff --git a/changes/573.md b/changes/573.mdnew file mode 100644index 00000000..ecac55a7--- /dev/null+++ b/changes/573.md@@ -0,0 +1 @@+- Add a per-frame density and velocity `field` to volume fog (also `renderer.setFogField`), flow-advected noise (`flowStrength`, `flowPeriod`), a `profile` choice, and scattering from up to 8 point and spot lights in the fog (issue #573). A fog without a field or lights draws exactly as before.diff --git a/changes/573.size.md b/changes/573.size.mdnew file mode 100644index 00000000..6f60c1c6--- /dev/null+++ b/changes/573.size.md@@ -0,0 +1,11 @@+- entry:core: the fog field upload, flow-advected noise and point/spot scattering are new agent-facing capability (fog that reacts and torches that light it); the fog shader and field code live in the core post pass, 1.8 KB gzip for the whole feature.+- entry:replace-textured-parts: the same renderer and post shader growth, in a bundle that carries the core.+- entry:texture-update: the same renderer and post shader growth, in a bundle that carries the core.+- scene:lit-box: the same core growth; the fog code is in the post pass every scene carries.+- scene:gltf-box: the same core growth.+- scene:gltf-box+lazy: the same core growth.+- scene:agent-scene: the same core growth.+- scene:agent-scene+lazy: the same core growth.+- goal:lit-box: functional fog capability from #573 (field, flow, local lights); moving the fog pass out of the core is a separate change.+- goal:gltf-box: functional fog capability from #573; moving the fog pass out of the core is a separate change.+- goal:agent-scene: functional fog capability from #573; moving the fog pass out of the core is a separate change.diff --git a/docs/volumetric.md b/docs/volumetric.mdindex e03f139b..5fae19df 100644--- a/docs/volumetric.md+++ b/docs/volumetric.md@@ -42,9 +42,34 @@ renderer.render({ eye: [0, 2, 5], target: [0, 1, 0], time: 0 });| `drift` | `[0.03, 0, 0]` | Three components within ±100, scene units per second || `maxDistance` | `100` | `0.01…10,000`, ray distance in scene units || `shadowAmbient` | derived | `0…1`; the share of `ambient` the fog keeps where the sun's shadow covers it. Left unset, 32 upward rays from the middle of the fog box decide: a closed room keeps 0.15, open ground under a sky keeps 1, and a partly covered scene lands between. Set it to override |+| `field` | none | A fog field, see below |+| `profile` | `'exponential'` | `'exponential'` or `'smoothstep'`; the vertical shape of a layer when a `field` is set |+| `flowStrength` | `1` | `0…100`; how far the noise travels along the field's velocity, as a share of velocity times `flowPeriod` |+| `flowPeriod` | `2` | `0.01…1,000` seconds; how often a noise lookup restarts |Values must be finite numbers. Active volume fog accepts finite frame time within ±1,000,000 seconds and a nonzero light direction with components within ±1,000,000. Noise samples absolute time, so backward seeks reproduce earlier density.+## Fog field: density and velocity per footprint cell++`volumeFog.field` is a 2D texture over the box's x/z footprint that the caller fills each frame, for fog that reacts to things (a character walks through it, a slam pushes it away). 67js only samples it; the simulation is the caller's.++```js+const data = new Float32Array(160 * 160 * 4); // RGBA, row 0 at the box's minimum z, column 0 at its minimum x+// r: density multiplier (1 = the fog as is, 0 = a hole), g: layer height in metres, b: velocity x, a: velocity z (metres per second)+renderer.setFogField({ width: 160, height: 160, data }); // stays until replaced; setFogField(null) clears it+// or per frame: environment: { volumeFog: { density: 1.2, minimum, maximum, profile: 'smoothstep', field: { width: 160, height: 160, data } } }+```++- Density at a point is `density * field.r * profile(y / field.g) * noise`, with `y` measured from `minimum[1]`. `profile` is `exp(-y / g)` for `'exponential'` and `1 - smoothstep(0.5, 1, y / g)` for `'smoothstep'`, a flat body with a soft, readable top. With a field, `heightFalloff` is not used: the field's layer height replaces it.+- The texture is RGBA16F, linear filtered and clamped at the edges, so the field may be coarse. `data` is a `Float32Array` of `width * height * 4` finite values; `width` and `height` are integers within `1…2048`. Anything else throws and names what it wanted.+- A frame with a field uploads it, so rewriting the same `Float32Array` between frames is enough. The same size writes into the existing texture (`texSubImage2D`); a new size allocates a new one. `setFogField` wins over a `field` in the frame or constructor environment.+- Flow: the noise lookup is carried along the field's velocity by two lookups that restart half a `flowPeriod` apart and cross-fade (Vlachos, "Water Flow in Portal 2", 2010), so detail swirls with the flow instead of drifting one way. It depends on frame time and the field only, so the same time and field give the same pixels after any seek. The constant `drift` still applies. Noise contrast dips slightly mid-fade, as in any flow map.+- A fog without a field is drawn by the program it had before, pixel for pixel. The first frame with a field or a light compiles its program before drawing.++## Point and spot lights in the fog++Every point and spot light of the frame (`environment.pointLights`, `spotLights`) scatters in the march: points first, then spots, at most 8. Each uses the light's range window and inverse square (the same as lit surfaces, with the light's radius floored at 0.1 m so the glow has no spike), the spot cone, its colour times intensity and the fog's Henyey-Greenstein phase. There are no shadows and no light linking in the fog. Light beyond the eighth is left out.+## Sky visibility of the fogPass `fogSkyVisibility` from `src/fog-sky-visibility.js` to `Renderer67` (the agent preview and the reference harness do) and the fog's ambient follows a per-point sky visibility instead of one share for the whole box. `skyVisibilityGrid` in `src/closed-room.js` shoots 24 fixed upward rays from the centre of each cell of a grid over the fog box (at most 2,048 cells and 32 along an axis), once per scene and fog box, and the result is uploaded as one 8-bit 3D texture. The post shader samples it with trilinear filtering in the shadowed fog: a point that sees any sky keeps all of the ambient, a point that sees none keeps 0.1 of it, and fog the sun reaches keeps all of it as before. Without the option, or when volume fog is off, the sampling is compiled out of the post shader and the frame is drawn by the program it had before. A scene of more than 150,000 triangles has no grid and draws as before. The rays run on the CPU: 0.03 s for `dark-shaft` (1,120 triangles) and 1.7 s for `temple-hall` (11,892 triangles) at scene build. A recipe that sets `shadowAmbient` keeps it and gets no grid.@@ -61,7 +86,9 @@ The fullscreen march clips against resolved opaque depth, supports perspective aResolved depth adds four estimated bytes per rendered pixel, or 2,073,600 bytes at 960 × 540. The planner reduces render dimensions when needed. The target is allocated at construction/resize, reused across frames and released by `dispose()`. The march adds no additional volume textures or geometry, but shading cost grows with covered pixels and step count.-This implements one bounded medium and one directional scattering source. Point-light scattering, multiple scattering, attenuation toward the source, transparent depth, volume grids, particles, temporal accumulation and half-resolution rendering remain unfinished. The legacy film explosion is separate and does not use this depth-clipped medium. Fog runs after bloom extraction, so scattering itself does not feed bloom.+This implements one bounded medium, a directional source with shadows and up to 8 unshadowed point and spot lights. Multiple scattering, attenuation toward the source, transparent depth, volume grids, particles, temporal accumulation and half-resolution rendering remain unfinished. The legacy film explosion is separate and does not use this depth-clipped medium. Fog runs after bloom extraction, so scattering itself does not feed bloom.++Measured at 1920 × 1080 with 24 steps on an RTX 3060 shared with other jobs, whole frame (a small scene, fog and read-back): the fog as before 3.6 to 3.7 ms; with a field 4.8 to 5.1 ms (about 1.3 ms more); with 8 point lights 7.3 to 7.4 ms (about 0.46 ms per light); both 8.6 to 8.8 ms. Numbers move with other jobs on the card.Run `node scripts/smoke-volumetric.mjs` with the development server running for native GPU extinction, foreground clipping, directional shadow, long-distance ray, resource reuse and disposal checks. Run `node scripts/benchmark-volumetric.mjs` for a fixed laboratory comparison and deterministic noise seeking. These fixtures establish behavior, not cinematic trailer quality.diff --git a/src/fog-field.js b/src/fog-field.jsnew file mode 100644index 00000000..e761d6f4--- /dev/null+++ b/src/fog-field.js@@ -0,0 +1,98 @@+import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS } from './light-limits.js';++// What the fog march takes from the scene's local lights. Points come first, then spots.+export const FOG_LIGHT_LIMIT = 8;+// A light's own radius is a few centimetres, and inside fog that would put a spike of glow around it.+const FOG_LIGHT_MINIMUM_RADIUS = 0.1;++export function createFogLightBuffers() {+ return {+ count: 0,+ positions: new Float32Array(FOG_LIGHT_LIMIT * 4),+ colors: new Float32Array(FOG_LIGHT_LIMIT * 4),+ directions: new Float32Array(FOG_LIGHT_LIMIT * 4),+ cones: new Float32Array(FOG_LIGHT_LIMIT * 4),+ };+}++function writePoint(buffers, slot, lighting, index) {+ const offset = slot * 4;+ const source = index * 4;+ buffers.positions.set(lighting.positions.subarray(source, source + 4), offset);+ const intensity = lighting.colors[source + 3];+ for (let channel = 0; channel < 3; channel++) buffers.colors[offset + channel] = lighting.colors[source + channel] * intensity;+ buffers.colors[offset + 3] = Math.max(lighting.radii[index], FOG_LIGHT_MINIMUM_RADIUS);+ buffers.directions.fill(0, offset, offset + 4);+ buffers.cones.fill(0, offset, offset + 4);+}++function writeSpot(buffers, slot, lighting, index) {+ const offset = slot * 4;+ const source = index * 4;+ buffers.positions.set(lighting.spotPositions.subarray(source, source + 4), offset);+ const intensity = lighting.spotColors[source + 3];+ for (let channel = 0; channel < 3; channel++) buffers.colors[offset + channel] = lighting.spotColors[source + channel] * intensity;+ buffers.colors[offset + 3] = Math.max(lighting.spotParameters[source], FOG_LIGHT_MINIMUM_RADIUS);+ buffers.directions.set(lighting.spotDirections.subarray(source, source + 4), offset);+ buffers.cones[offset] = lighting.spotParameters[source + 1];+ buffers.cones[offset + 1] = 1;+ buffers.cones[offset + 2] = 0;+ buffers.cones[offset + 3] = 0;+}++/** Copies up to FOG_LIGHT_LIMIT point and spot lights from the lighting state into the fog's uniform buffers. */+export function packFogLights(lighting, buffers) {+ let slot = 0;+ for (let index = 0; index < Math.min(lighting.pointCount, MAX_POINT_LIGHTS) && slot < FOG_LIGHT_LIMIT; index++) {+ if (lighting.colors[index * 4 + 3] === 0) continue;+ writePoint(buffers, slot++, lighting, index);+ }+ for (let index = 0; index < Math.min(lighting.spotCount, MAX_SPOT_LIGHTS) && slot < FOG_LIGHT_LIMIT; index++) {+ if (lighting.spotColors[index * 4 + 3] === 0) continue;+ writeSpot(buffers, slot++, lighting, index);+ }+ buffers.count = slot;+ return slot;+}++/**+ * The fog field as one RGBA16F texture, linear filtered and clamped at the edges. The same size writes into the texture it+ * has (texSubImage2D); a new size allocates new storage. The caller may rewrite the Float32Array between frames, so every+ * frame that carries a field uploads it.+ */+export class FogFieldTexture {+ constructor(context) {+ this.context = context;+ this.texture = null;+ this.width = 0;+ this.height = 0;+ }++ upload(field) {+ const context = this.context;+ if (!this.texture) {+ this.texture = context.createTexture();+ context.bindTexture(context.TEXTURE_2D, this.texture);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.LINEAR);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.LINEAR);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);+ } else {+ context.bindTexture(context.TEXTURE_2D, this.texture);+ }+ if (field.width === this.width && field.height === this.height) {+ context.texSubImage2D(context.TEXTURE_2D, 0, 0, 0, field.width, field.height, context.RGBA, context.FLOAT, field.data);+ return;+ }+ context.texImage2D(context.TEXTURE_2D, 0, context.RGBA16F, field.width, field.height, 0, context.RGBA, context.FLOAT, field.data);+ this.width = field.width;+ this.height = field.height;+ }++ dispose() {+ if (this.texture) this.context.deleteTexture(this.texture);+ this.texture = null;+ this.width = 0;+ this.height = 0;+ }+}diff --git a/src/post.js b/src/post.jsindex 75b0c4d8..1a06711a 100644--- a/src/post.js+++ b/src/post.js@@ -43,6 +43,15 @@ uniform float volumeNoiseAmount;uniform float volumeNoiseScale;uniform float volumeMaxDistance;uniform float volumeHeightFalloff;+uniform sampler2D volumeField;+uniform float volumeProfile;+uniform float volumeFlowStrength;+uniform float volumeFlowPeriod;+uniform int volumeLightCount;+uniform vec4 volumeLightPositions[8];+uniform vec4 volumeLightColors[8];+uniform vec4 volumeLightDirections[8];+uniform vec4 volumeLightCones[8];uniform float orthographic;uniform highp sampler3D fogSkyVisibility;uniform sampler2D occlusionTexture;@@ -60,6 +69,45 @@ float cloudNoise(vec3 position) {return mix(lower, upper, fraction.z);}${explosionFunction}+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) {+ float squaredRatio = distanceSquared / (range * range);+ float fade = max(1.0 - squaredRatio * squaredRatio, 0.0);+ cutoff = fade * fade;+ }+ return cutoff / max(distanceSquared, radius * radius);+}+vec3 fogLightScattering(vec3 position, vec3 direction) {+ vec3 total = vec3(0);+ for (int index = 0; index < 8; index++) {+ if (index >= volumeLightCount) break;+ vec3 offset = volumeLightPositions[index].xyz - position;+ float distanceSquared = dot(offset, offset);+ if (distanceSquared < 1e-12) continue;+ vec3 toLight = offset * inversesqrt(distanceSquared);+ float attenuation = fogLightAttenuation(distanceSquared, volumeLightPositions[index].w, volumeLightColors[index].w);+ if (volumeLightCones[index].y > 0.5) attenuation *= smoothstep(volumeLightDirections[index].w, volumeLightCones[index].x, dot(-toLight, volumeLightDirections[index].xyz));+ if (attenuation <= 0.0) continue;+ float denominator = 1.0 + volumeAnisotropy * volumeAnisotropy - 2.0 * volumeAnisotropy * dot(direction, toLight);+ total += volumeLightColors[index].rgb * (attenuation * (1.0 - volumeAnisotropy * volumeAnisotropy) / (12.5663706 * denominator * sqrt(denominator)));+ }+ return total;+}+float flowedNoise(vec3 samplePosition, vec2 velocity) {+ float firstPhase = fract(time / volumeFlowPeriod);+ float secondPhase = fract(time / volumeFlowPeriod + 0.5);+ vec3 travel = vec3(velocity.x, 0.0, velocity.y) * volumeFlowStrength * volumeFlowPeriod;+ float first = cloudNoise((samplePosition - travel * firstPhase) * volumeNoiseScale);+ float second = cloudNoise((samplePosition - travel * secondPhase) * volumeNoiseScale);+ return mix(first, second, abs(2.0 * firstPhase - 1.0));+}+float layerProfile(float relativeHeight) {+ return volumeProfile > 0.5 ? 1.0 - smoothstep(0.5, 1.0, relativeHeight) : exp(-relativeHeight);+}vec3 volumeFog(vec3 background) {vec2 clipXY = textureCoordinate * 2.0 - 1.0;vec4 farPoint = inverseViewProjection * vec4(clipXY, 1.0, 1.0);@@ -87,7 +135,7 @@ vec3 volumeFog(vec3 background) {vec3 lightDirection = normalize(volumeLightDirection);float cosine = dot(direction, lightDirection);float anisotropy = volumeAnisotropy;- float phase = (1.0 - anisotropy * anisotropy) / (12.5663706 * pow(1.0 + anisotropy * anisotropy - 2.0 * anisotropy * cosine, 1.5));+ float phase = henyeyGreenstein(cosine, anisotropy);float jitter = hash(vec3(gl_FragCoord.xy, 0));float transmittance = 1.0;vec3 accumulated = vec3(0);@@ -95,8 +143,13 @@ vec3 volumeFog(vec3 background) {if (index >= volumeSteps) break;vec3 position = origin + direction * (entry + (float(index) + jitter) * stepSize);float noise = 1.0;- if (volumeNoiseAmount > 0.0) noise = mix(1.0, cloudNoise((position - volumeDrift * time) * volumeNoiseScale) * 2.0, volumeNoiseAmount);- if (volumeHeightFalloff > 0.0) noise *= exp((volumeMinimum.y - position.y) / volumeHeightFalloff);+ vec4 field = POST_FIELD ? texture(volumeField, (position.xz - volumeMinimum.xz) / (volumeMaximum.xz - volumeMinimum.xz)) : vec4(1);+ if (volumeNoiseAmount > 0.0) {+ float lookup = POST_FIELD ? flowedNoise(position - volumeDrift * time, field.zw) : cloudNoise((position - volumeDrift * time) * volumeNoiseScale);+ noise = mix(1.0, lookup * 2.0, volumeNoiseAmount);+ }+ if (POST_FIELD) noise *= field.r * layerProfile((position.y - volumeMinimum.y) / max(field.g, 0.0001));+ else if (volumeHeightFalloff > 0.0) noise *= exp((volumeMinimum.y - position.y) / volumeHeightFalloff);float opacity = 1.0 - exp(-volumeDensity * noise * stepSize);vec4 lightPosition = volumeLightProjection * vec4(position, 1);vec3 shadow = lightPosition.xyz / lightPosition.w * 0.5 + 0.5;@@ -109,6 +162,7 @@ vec3 volumeFog(vec3 background) {float ambientShare = mix(shadowShare, 1.0, visibility);if (volumeGridFog > 0.5) ambientShare = min(1.0, 30.0 * skyCell.r);vec3 scattering = volumeColor * (volumeAmbient * ambientShare + volumeLightColor * phase * visibility + 0.6 * skyCell.gba);+ if (POST_LIGHTS) scattering += volumeColor * fogLightScattering(position, direction);accumulated += transmittance * opacity * scattering;transmittance *= 1.0 - opacity;if (transmittance < 0.001) break;@@ -241,13 +295,16 @@ const POST_STEP_CONDITIONS = {bloom: ['POST_BLOOM', 'bloomStrength > 0.0'],volume: ['POST_VOLUME', 'volumeDensity > 0.0'],sky: ['POST_SKY', 'true'],+ field: ['POST_FIELD', 'true'],+ lights: ['POST_LIGHTS', 'volumeLightCount > 0'],explosion: ['POST_EXPLOSION', 'volumeExplosion > 0.5'],finish: ['POST_FINISH', 'true'],};-// The sky step is left out: the program with every step is the one a frame draws while a variant builds, and it has no fog sky grid.+// The sky, field and lights steps are left out: the program with every step is the one a frame draws while a variant builds,+// and it has no fog sky grid, no fog field and no fog lights.// The explosion step is left out too, because its code loads from explosion-shader.js only for a renderer that draws it.-export const POST_STEPS = Object.freeze(Object.keys(POST_STEP_CONDITIONS).filter(step => step !== 'sky' && step !== 'explosion'));+export const POST_STEPS = Object.freeze(Object.keys(POST_STEP_CONDITIONS).filter(step => !['sky', 'field', 'lights', 'explosion'].includes(step)));const EXPLOSION_STUB = 'vec3 explosion(vec3 background) { return background; }';diff --git a/src/renderer.js b/src/renderer.jsindex 3458a744..7cbc8c92 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -12,7 +12,8 @@ import { depthLayerOf } from './depth-layer.js';import { createLightingState, updateLightingState } from './lighting.js';import { RenderTargetLedger } from './render-target-ledger.js';import { SHADOW_ATLAS_WIDTH, SHADOW_TILE_SIZE, SHADOW_TILES_PER_ROW, tileViewport, writeShadowTile } from './local-shadows.js';-import { resolveVolumeFog, volumeShadowAmbient } from './volumetric.js';+import { resolveVolumeFog, volumeShadowAmbient, validateFogField, DEFAULT_FLOW_STRENGTH, DEFAULT_FLOW_PERIOD } from './volumetric.js';+import { FogFieldTexture, createFogLightBuffers, packFogLights } from './fog-field.js';import { requireEnvironmentSupport } from './environment-shading.js';import { materialLayerState, materialLayerValue } from './material-layers.js';import { MaterialSnapshot } from './material-snapshot.js';@@ -46,7 +47,7 @@ const DEFORMING_TAGS = new Set(['foliage', 'grass', 'water', 'fire', 'smoke']);// strength, so they can be culled and given levels like rigid parts.const SWAY_REACH_PER_STRENGTH = 0.56;-const POST_UNIFORMS = ['transparent', 'frameTexture', 'bloomTexture', 'bloomStrength', 'hdrEnabled', 'grade', 'vignette', 'grainAmount', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye', 'sceneDepth', 'volumeShadowMap', 'volumeLightProjection', 'volumeLightDirection', 'volumeLightColor', 'volumeDensity', 'volumeMinimum', 'volumeMaximum', 'volumeColor', 'volumeAmbient', 'volumeDrift', 'volumeSteps', 'volumeAnisotropy', 'volumeShadowAmbient', 'volumeGridFog', 'volumeNoiseAmount', 'volumeNoiseScale', 'volumeHeightFalloff', 'volumeMaxDistance', 'fogSkyVisibility', 'orthographic', 'occlusionTexture', 'occlusionStrength', 'occlusionTexel'];+const POST_UNIFORMS = ['transparent', 'frameTexture', 'bloomTexture', 'bloomStrength', 'hdrEnabled', 'grade', 'vignette', 'grainAmount', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye', 'sceneDepth', 'volumeShadowMap', 'volumeLightProjection', 'volumeLightDirection', 'volumeLightColor', 'volumeDensity', 'volumeMinimum', 'volumeMaximum', 'volumeColor', 'volumeAmbient', 'volumeDrift', 'volumeSteps', 'volumeAnisotropy', 'volumeShadowAmbient', 'volumeGridFog', 'volumeNoiseAmount', 'volumeNoiseScale', 'volumeHeightFalloff', 'volumeMaxDistance', 'volumeField', 'volumeProfile', 'volumeFlowStrength', 'volumeFlowPeriod', 'volumeLightCount', 'volumeLightPositions[0]', 'volumeLightColors[0]', 'volumeLightDirections[0]', 'volumeLightCones[0]', 'fogSkyVisibility', 'orthographic', 'occlusionTexture', 'occlusionStrength', 'occlusionTexel'];function postUniformLocations(context, program) {return Object.fromEntries(POST_UNIFORMS.map(name => [name, context.getUniformLocation(program, name)]));@@ -485,6 +486,9 @@ export class Renderer67 {this.skyOpenness = skyOpenness;// `fogSkyVisibility` from fog-sky-visibility.js is passed in for the same reason; without it the post shader has no grid.this.fogSkyVisibility = fogSkyVisibility;+ this.fogFieldOverride = null;+ this.fogFieldTexture = null;+ this.fogLightBuffers = createFogLightBuffers();// `createGpuTimer` from adaptive-quality.js is passed in, which keeps the timer code out of scenes that do not time frames.this.createGpuTimer = createGpuTimer;this.gpuTimer = undefined;@@ -1729,6 +1733,8 @@ export class Renderer67 {if (occluded) steps.push('occlusion');if (effects.bloom.strength > 0) steps.push('bloom');if (volume.density > 0) steps.push('volume');+ if (volume.density > 0 && volume.field) steps.push('field');+ if (volume.density > 0 && this.fogLightBuffers.count > 0) steps.push('lights');if (fogSky) steps.push('sky');if (frame.volumeExplosion) steps.push('explosion');const gradesColor = effects.saturation !== 1 || effects.contrast !== 1 || effects.temperature !== 0;@@ -1749,7 +1755,7 @@ export class Renderer67 {}if (variant.pending) {const parallelCompile = this.context.getExtension('KHR_parallel_shader_compile');- const building = parallelCompile && !steps.includes('sky') && !steps.includes('explosion') && !this.context.getProgramParameter(variant.pending.program, parallelCompile.COMPLETION_STATUS_KHR);+ const building = parallelCompile && !['sky', 'field', 'lights', 'explosion'].some(step => steps.includes(step)) && !this.context.getProgramParameter(variant.pending.program, parallelCompile.COMPLETION_STATUS_KHR);if (building) return { program: this.postProgram, uniforms: this.postUniforms };variant.program = finishProgram(this.context, variant.pending);variant.uniforms = postUniformLocations(this.context, variant.program);@@ -1774,6 +1780,8 @@ export class Renderer67 {context.disable(context.CULL_FACE);context.bindVertexArray(null);const fogSky = this.fogSkyVisibility?.(this.sceneParts, volume, context, environment);+ if (volume.density > 0) packFogLights(this.lighting, this.fogLightBuffers);+ else this.fogLightBuffers.count = 0;const post = this.selectPostProgram(this.postStepsOf(frame, effects, volume, occluded, fogSky));context.useProgram(post.program);if (this.look) viewTransformShader.bindLook(this, post.program);@@ -1811,6 +1819,7 @@ export class Renderer67 {context.uniform1f(post.uniforms.volumeNoiseScale, volume.noiseScale);context.uniform1f(post.uniforms.volumeMaxDistance, volume.maxDistance);context.uniform1f(post.uniforms.volumeHeightFalloff, volume.heightFalloff);+ this.bindFogExtras(post, volume);context.uniform1f(post.uniforms.orthographic, frame.projection === 'orthographic' ? 1 : 0);context.uniform1i(post.uniforms.fogSkyVisibility, 5);context.uniform1f(post.uniforms.volumeGridFog, this.sceneParts.some(part => part.material?.irradianceGrid) ? 1 : 0);@@ -1840,6 +1849,27 @@ export class Renderer67 {context.drawArrays(context.TRIANGLES, 0, 3);}+ // The fog's field texture and light buffers; a program without those steps has no such uniforms, and a null location is ignored.+ bindFogExtras(post, volume) {+ const context = this.context;+ if (volume.density > 0 && volume.field) {+ this.fogFieldTexture ??= new FogFieldTexture(context);+ context.activeTexture(context.TEXTURE6);+ this.fogFieldTexture.upload(volume.field);+ context.uniform1i(post.uniforms.volumeField, 6);+ context.uniform1f(post.uniforms.volumeProfile, volume.profile === 'smoothstep' ? 1 : 0);+ context.uniform1f(post.uniforms.volumeFlowStrength, volume.flowStrength ?? DEFAULT_FLOW_STRENGTH);+ context.uniform1f(post.uniforms.volumeFlowPeriod, volume.flowPeriod ?? DEFAULT_FLOW_PERIOD);+ }+ const lights = this.fogLightBuffers;+ context.uniform1i(post.uniforms.volumeLightCount, lights.count);+ if (lights.count === 0) return;+ context.uniform4fv(post.uniforms['volumeLightPositions[0]'], lights.positions);+ context.uniform4fv(post.uniforms['volumeLightColors[0]'], lights.colors);+ context.uniform4fv(post.uniforms['volumeLightDirections[0]'], lights.directions);+ context.uniform4fv(post.uniforms['volumeLightCones[0]'], lights.cones);+ }+drawTranslucent(frame, environment, assemblyAmount, environmentMap) {this.activateEnvironment(environmentMap);const liquids = this.batches.filter(batch => batchPass(batch) === 'liquid');@@ -2092,12 +2122,21 @@ export class Renderer67 {return this.passSupport.prepare(frame);}+ /**+ * Sets the fog's density and velocity field (see docs/volumetric.md) until it is replaced or cleared with null. It wins over+ * a field in the constructor's or the frame's volumeFog. The same size is written into the existing texture on the next frame.+ */+ setFogField(field) {+ this.fogFieldOverride = field === null ? null : validateFogField(field);+ }+render(frame) {const { eye, target = [0, 1.2, 0], armorColor = [0.53, 0.39, 0.24], armorSurface = [0.88, 0.32], exposure = 1, inspection = false } = frame;const effects = resolveEffects(frame.effects);const environment = { lightDirection: [-3, 6, 4], fogColor: [0.35, 0.43, 0.43], fogDensity: 0.006, daylight: 1, explosionCenter: [0, 0, 0], ...this.environment, ...frame.environment };environment.fogDensity ??= this.fittedFogDensity ?? 0.006;const volume = resolveVolumeFog(environment.volumeFog);+ if (this.fogFieldOverride) volume.field = this.fogFieldOverride;if (volume.density > 0) {if (!this.depth || !this.hdr || this.transparent || this.benchmark) throw new Error('Volume fog requires depth:true, active HDR and an opaque canvas');if (!Number.isFinite(frame.time ?? 0) || Math.abs(frame.time ?? 0) > 1e6) throw new RangeError('Volume time must be finite and within ±1000000 seconds');@@ -2266,6 +2305,7 @@ export class Renderer67 {}dispose() {+ this.fogFieldTexture?.dispose();this.releaseFrameTargets();this.shadowCascades?.dispose(this.context, this.renderTargets);viewTransformShader.dispose?.(this);diff --git a/src/volumetric.js b/src/volumetric.jsindex 7402b469..a776b8f7 100644--- a/src/volumetric.js+++ b/src/volumetric.js@@ -17,6 +17,26 @@ function vector(value, minimum, maximum, label) {return value;}+export const FOG_FIELD_MAXIMUM_SIZE = 2048;+export const FOG_PROFILES = Object.freeze(['exponential', 'smoothstep']);+export const DEFAULT_FLOW_STRENGTH = 1;+export const DEFAULT_FLOW_PERIOD = 2;++/** Checks a fog field and returns it unchanged: { width, height, data } with RGBA floats, row 0 at the box's minimum z. */+export function validateFogField(field) {+ if (!field || typeof field !== 'object' || Array.isArray(field)) throw new TypeError('Fog field must be an object with width, height and data');+ for (const label of ['width', 'height']) {+ const size = field[label];+ if (!Number.isInteger(size) || size < 1 || size > FOG_FIELD_MAXIMUM_SIZE) throw new RangeError(`Fog field ${label} must be an integer between 1 and ${FOG_FIELD_MAXIMUM_SIZE}`);+ }+ if (!(field.data instanceof Float32Array)) throw new TypeError('Fog field data must be a Float32Array of RGBA values');+ if (field.data.length !== field.width * field.height * 4) throw new RangeError(`Fog field data must hold width * height * 4 = ${field.width * field.height * 4} values, got ${field.data.length}`);+ for (let index = 0; index < field.data.length; index++) {+ if (!Number.isFinite(field.data[index])) throw new RangeError(`Fog field data must be finite; index ${index} is not`);+ }+ return field;+}+export function resolveVolumeFog(input = {}) {if (!input || typeof input !== 'object' || Array.isArray(input)) throw new TypeError('volumeFog must be an object');const density = finiteRange(input.density ?? 0, 0, 10, 'Volume density');@@ -40,6 +60,14 @@ export function resolveVolumeFog(input = {}) {if (input.shadowAmbient !== undefined) {resolved.shadowAmbient = finiteRange(input.shadowAmbient, 0, 1, 'Volume shadow ambient');}+ if (input.field !== undefined) resolved.field = validateFogField(input.field);+ // Left out when unset, like shadowAmbient: the renderer applies the defaults, and a fog without them resolves as before.+ if (input.flowStrength !== undefined) resolved.flowStrength = finiteRange(input.flowStrength, 0, 100, 'Volume flow strength');+ if (input.flowPeriod !== undefined) resolved.flowPeriod = finiteRange(input.flowPeriod, 0.01, 1000, 'Volume flow period');+ if (input.profile !== undefined) {+ if (!FOG_PROFILES.includes(input.profile)) throw new RangeError(`Volume profile must be one of ${FOG_PROFILES.join(', ')}`);+ resolved.profile = input.profile;+ }return resolved;}diff --git a/tests/fog-field.test.js b/tests/fog-field.test.jsnew file mode 100644index 00000000..ccccbc94--- /dev/null+++ b/tests/fog-field.test.js@@ -0,0 +1,79 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { resolveVolumeFog, validateFogField } from '../src/volumetric.js';+import { createLightingState, updateLightingState } from '../src/lighting.js';+import { FOG_LIGHT_LIMIT, createFogLightBuffers, packFogLights, FogFieldTexture } from '../src/fog-field.js';+import { createPostFragment, POST_STEPS } from '../src/post.js';++function fieldOf(width, height) {+ return { width, height, data: new Float32Array(width * height * 4).fill(1) };+}++test('a volume fog without field, flow or profile resolves to the same keys as before', () => {+ const resolved = resolveVolumeFog({ density: 0.1 });+ for (const key of ['field', 'flowStrength', 'flowPeriod', 'profile']) assert.equal(Object.hasOwn(resolved, key), false, key);+});++test('a fog field is kept by reference with its flow knobs and profile', () => {+ const field = fieldOf(4, 3);+ const resolved = resolveVolumeFog({ density: 0.1, field, flowStrength: 0.5, flowPeriod: 3, profile: 'smoothstep' });+ assert.equal(resolved.field, field);+ assert.equal(resolved.flowStrength, 0.5);+ assert.equal(resolved.flowPeriod, 3);+ assert.equal(resolved.profile, 'smoothstep');+});++test('fog field validation names the problem', () => {+ assert.throws(() => validateFogField(null), /object/);+ assert.throws(() => validateFogField({ width: 0, height: 2, data: new Float32Array(0) }), /width/);+ assert.throws(() => validateFogField({ width: 2, height: 2.5, data: new Float32Array(10) }), /height/);+ assert.throws(() => validateFogField({ width: 2, height: 2, data: [1, 2, 3] }), /Float32Array/);+ assert.throws(() => validateFogField({ width: 2, height: 2, data: new Float32Array(15) }), /16 values, got 15/);+ const withNaN = fieldOf(2, 2);+ withNaN.data[5] = NaN;+ assert.throws(() => validateFogField(withNaN), /finite/);+ assert.throws(() => resolveVolumeFog({ flowStrength: -1 }), RangeError);+ assert.throws(() => resolveVolumeFog({ flowPeriod: 0 }), RangeError);+ assert.throws(() => resolveVolumeFog({ profile: 'linear' }), /exponential, smoothstep/);+});++test('the post program has the field and light steps only when asked, and the default program has neither', () => {+ assert.equal(POST_STEPS.includes('field'), false);+ assert.equal(POST_STEPS.includes('lights'), false);+ const defaultSource = createPostFragment();+ assert.match(defaultSource, /#define POST_FIELD false/);+ assert.match(defaultSource, /#define POST_LIGHTS false/);+ const fogSource = createPostFragment([...POST_STEPS, 'field', 'lights']);+ assert.match(fogSource, /#define POST_FIELD \(true\)/);+ assert.match(fogSource, /#define POST_LIGHTS \(volumeLightCount > 0\)/);+});++test('fog lights take points then spots, premultiplied by intensity, up to the limit', () => {+ const lighting = createLightingState();+ const pointLights = Array.from({ length: 6 }, (_, index) => ({ position: [index, 1, 0], color: [1, 0.5, 0.25], intensity: 4, range: 5 }));+ const spotLights = Array.from({ length: 4 }, () => ({ position: [0, 3, 0], direction: [0, -1, 0], color: [1, 1, 1], intensity: 2, range: 8, angle: 0.5 }));+ updateLightingState(lighting, { pointLights, spotLights });+ const buffers = createFogLightBuffers();+ assert.equal(packFogLights(lighting, buffers), FOG_LIGHT_LIMIT);+ assert.deepEqual(Array.from(buffers.colors.subarray(0, 3)), [4, 2, 1]);+ assert.equal(buffers.positions[3], 5);+ assert.equal(buffers.cones[1], 0, 'a point light has no cone');+ assert.equal(buffers.cones[6 * 4 + 1], 1, 'the seventh light is the first spot');+ assert.ok(buffers.colors[3] >= 0.1, 'the radius has a floor');+ updateLightingState(lighting, {});+ assert.equal(packFogLights(lighting, buffers), 0);+});++test('the field texture allocates once per size and writes into it afterwards', () => {+ const calls = [];+ const context = new Proxy({ TEXTURE_2D: 1, RGBA: 2, FLOAT: 3, RGBA16F: 4, createTexture: () => ({}), deleteTexture: () => calls.push('delete') }, {+ get: (target, name) => target[name] ?? ((...args) => { calls.push(String(name)); return args; }),+ });+ const texture = new FogFieldTexture(context);+ texture.upload(fieldOf(8, 8));+ texture.upload(fieldOf(8, 8));+ texture.upload(fieldOf(4, 4));+ assert.deepEqual(calls.filter(name => name.startsWith('tex') && name.endsWith('2D')), ['texImage2D', 'texSubImage2D', 'texImage2D']);+ texture.dispose();+ assert.equal(calls.at(-1), 'delete');+});