3D engine that AI agents drive
Add volume fog detail controls: octaves, warp, contrast, layer top, key scattering
Nguyen Xuan An95c4ca66430e
diff --git a/bench/reference/harness.js b/bench/reference/harness.jsindex c5ff2bf2..3399dfa5 100644--- a/bench/reference/harness.js+++ b/bench/reference/harness.js@@ -234,7 +234,7 @@ async function probeScene(scene, id, drawnParts, mode) {return { parts: placed.parts, report: placed.report, seconds: (performance.now() - started) / 1000 };}-async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambientOcclusionRadius = 0.5, bake = null, cascades = 0, backgroundOnly = false, probes = false, ambient = null, fill = null, key = null, viewTransform = null, bloom = null }) {+async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambientOcclusionRadius = 0.5, bake = null, cascades = 0, backgroundOnly = false, probes = false, ambient = null, fill = null, key = null, viewTransform = null, bloom = null, volumeFog = null }) {const scene = await SCENES[id]();if (GLOSSY_OFF) removeGlossy(scene);// A view transform (agx, neutral) replaces the ACES fit in the shaders, as environment.viewTransform does in a recipe.@@ -243,6 +243,8 @@ async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambienif (ambient !== null) scene.environment = { ...scene.environment, ambientIntensity: ambient };if (fill !== null) scene.environment = { ...scene.environment, fillIntensity: fill };if (key !== null) scene.environment = { ...scene.environment, keyIntensity: key };+ // Fields merged into the scene's volumeFog, to compare fog controls on the same scene.+ if (volumeFog) scene.environment = { ...scene.environment, volumeFog: { ...scene.environment.volumeFog, ...volumeFog } };const baked = bake ? await bakeScene(scene, bake) : null;const probed = probes ? await probeScene(scene, id, baked ? baked.parts : scene.parts, probes) : null;scene.environment = withDerivedGroundBounce(scene, probed ? probed.parts : baked ? baked.parts : scene.parts);diff --git a/bench/reference/render-gpu.mjs b/bench/reference/render-gpu.mjsindex 8539ba4b..a4a78144 100644--- a/bench/reference/render-gpu.mjs+++ b/bench/reference/render-gpu.mjs@@ -42,6 +42,12 @@ const sunBounce = numberAfter('--sun-bounce');const sunBounceRange = numberAfter('--sun-bounce-range');const sunBounceGain = numberAfter('--sun-bounce-gain');+// --fog '<json>' merges those fields into the scene's volumeFog, for example --fog '{"noiseAmount":1,"warp":0.8}'.+function fogOption() {+ const index = argumentsGiven.indexOf('--fog');+ return index >= 0 ? JSON.parse(argumentsGiven[index + 1]) : null;+}+const options = {ambient: numberAfter('--ambient'),fill: numberAfter('--fill'),@@ -49,6 +55,7 @@ const options = {ambientOcclusion: numberAfter('--ambient-occlusion') ?? 0,ambientOcclusionRadius: numberAfter('--ambient-occlusion-radius') ?? 0.5,bloom: bloomOption(),+ volumeFog: fogOption(),bake: bakePresetOption(),};diff --git a/changes/586-fog-detail.md b/changes/586-fog-detail.mdnew file mode 100644index 00000000..9504ebe8--- /dev/null+++ b/changes/586-fog-detail.md@@ -0,0 +1 @@+- Volume fog takes `detailOctaves`, `detailAmount`, `warp` and `contrast` for wispier mist, `profileSoftness` for where a layer top starts to fade, and `keyScattering` to scale only the key light shafts (#586)diff --git a/changes/586-fog-detail.size.md b/changes/586-fog-detail.size.mdnew file mode 100644index 00000000..49034672--- /dev/null+++ b/changes/586-fog-detail.size.md@@ -0,0 +1,10 @@+- entry:core: the six volumeFog detail fields are validated in resolveVolumeFog, their uniform names join the post uniform list and the renderer adds the detail step.+- entry:fog-shader: the warp, extra octave, contrast, layer top and key scattering GLSL, which a detail-free fog compiles out.+- scene:lit-box: the same core validation and uniform names.+- goal:lit-box: 256 bytes for fog detail controls an agent-facing look needs; core growth accepted under the trade-off rule.+- scene:gltf-box: the same core validation and uniform names.+- scene:gltf-box+lazy: the same core code as scene:gltf-box.+- goal:gltf-box: 266 bytes for the same fog detail controls; accepted on the same grounds.+- scene:agent-scene: the same core code plus the recipe field names and the MCP-facing ranges.+- goal:agent-scene: 272 bytes for the same fog detail controls; accepted on the same grounds.+- scene:agent-scene+lazy: the same core code plus the fog shader addon the recipe loads.diff --git a/docs/agent-look.md b/docs/agent-look.mdindex 32feeb55..4367b94c 100644--- a/docs/agent-look.md+++ b/docs/agent-look.md@@ -211,6 +211,7 @@ These controls reuse `resolveVolumeFog` and its existing domain rules.| `noiseScale` | `0.3` | `0.001` to `100` || `maxDistance` | `100` | `0.01` to `10000` || `shadowAmbient` | derived from the scene: 0.15 in a closed room, 1 under open sky | `0` to `1` |+| `detailOctaves`, `detailAmount`, `warp`, `contrast`, `profileSoftness`, `keyScattering` | `1`, `0.5`, `0`, `1`, `0.5`, `1` | Integer `1` to `3`, `0` to `1`, `0` to `4`, `0` to `4`, `0` to `0.95`, `0` to `10`; see [volume fog](https://67js.codepawl.com/volumetric.md) |Fog bounds reject dimensions that collapse after Float32 rounding.The current volume supports one directional scattering source.diff --git a/docs/volumetric.md b/docs/volumetric.mdindex 9b436289..d8faf39c 100644--- a/docs/volumetric.md+++ b/docs/volumetric.md@@ -48,6 +48,12 @@ renderer.render({ eye: [0, 2, 5], target: [0, 1, 0], time: 0 });| `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 |+| `detailOctaves` | `1` | Integer `1…3`; noise octaves at 1x, 2x and 4x `noiseScale`. Above 1 the frame compiles the detail step in |+| `detailAmount` | `0.5` | `0…1`; weight of the extra octaves against the base noise, which keeps its own weight |+| `warp` | `0` | `0…4`; domain warp strength in noise cells, for wisps and curls |+| `contrast` | `1` | `0…4`; stretches the noise around its middle, so thin gaps sit next to thick patches |+| `profileSoftness` | `0.5` | `0…0.95`; where the `'smoothstep'` layer top starts to fade, as a share of the layer height. Lower tapers from nearer the floor |+| `keyScattering` | `1` | `0…10`; scales the key light's in-scattering (the shadow-mapped god rays) and leaves `ambient` alone |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.diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex c78266a0..bda69213 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -173,6 +173,12 @@ const volumeFog = z.strictObject({noiseScale: bounded(0.001, 100).optional(),maxDistance: bounded(0.01, 1e4).optional(),shadowAmbient: unit.optional(),+ detailOctaves: z.number().int().min(1).max(3).optional(),+ detailAmount: unit.optional(),+ warp: bounded(0, 4).optional(),+ contrast: bounded(0, 4).optional(),+ profileSoftness: bounded(0, 0.95).optional(),+ keyScattering: bounded(0, 10).optional(),});const affects = z.array(z.string()).optional();const lines = z.record(z.string(), z.unknown()).describe('Outlines, toon light and polylines as plain JSON; fields and limits in scene_capabilities lineArt. null clears.');diff --git a/src/agent-look.js b/src/agent-look.jsindex a9e504f8..e8f82f8a 100644--- a/src/agent-look.js+++ b/src/agent-look.js@@ -21,7 +21,7 @@ const POINT_LIGHT_FIELDS = ['position', 'color', 'intensity', 'radius', 'range',const SPOT_LIGHT_FIELDS = ['position', 'direction', 'angle', 'penumbra', 'color', 'intensity', 'radius', 'range', 'castShadow', 'affects'];const AREA_LIGHT_FIELDS = ['position', 'direction', 'up', 'width', 'height', 'color', 'intensity', 'affects'];const VOLUME_VECTOR_FIELDS = ['minimum', 'maximum', 'color', 'ambient', 'drift'];-const VOLUME_NUMBER_FIELDS = ['density', 'steps', 'anisotropy', 'noiseAmount', 'noiseScale', 'maxDistance', 'shadowAmbient', 'heightFalloff'];+const VOLUME_NUMBER_FIELDS = ['density', 'steps', 'anisotropy', 'noiseAmount', 'noiseScale', 'maxDistance', 'shadowAmbient', 'heightFalloff', 'detailOctaves', 'detailAmount', 'warp', 'contrast', 'profileSoftness', 'keyScattering'];const BLOOM_FIELDS = ['strength', 'threshold', 'radius'];const DEPTH_OF_FIELD_FIELDS = ['blur', 'focusDistance'];const MOTION_BLUR_FIELDS = ['shutter'];diff --git a/src/fog-field.js b/src/fog-field.jsindex 0dc57494..e9690607 100644--- a/src/fog-field.js+++ b/src/fog-field.js@@ -4,6 +4,8 @@ import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS } from './light-limits.js';export const FOG_LIGHT_LIMIT = 8;export const DEFAULT_FLOW_STRENGTH = 1;export const DEFAULT_FLOW_PERIOD = 2;+// What a fog without detail controls uses: one octave, no warp, the noise as is, the layer top fading from half its height.+export const DEFAULT_DETAIL = Object.freeze({ detailOctaves: 1, detailAmount: 0.5, warp: 0, contrast: 1, profileSoftness: 0.5, keyScattering: 1 });// 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;diff --git a/src/fog-shader.js b/src/fog-shader.jsindex 608207b7..8d00eee9 100644--- a/src/fog-shader.js+++ b/src/fog-shader.js@@ -1,5 +1,5 @@import { registerShaderFeatureCode } from './shader-registry.js';-import { FogFieldTexture, createFogLightBuffers, packFogLights, volumeShadowAmbient, DEFAULT_FLOW_STRENGTH, DEFAULT_FLOW_PERIOD } from './fog-field.js';+import { FogFieldTexture, createFogLightBuffers, packFogLights, volumeShadowAmbient, DEFAULT_FLOW_STRENGTH, DEFAULT_FLOW_PERIOD, DEFAULT_DETAIL } from './fog-field.js';// The volume fog step of the post pass: its uniforms and the march that scatters light through the fog box. Only a renderer that// draws a frame with environment.volumeFog needs this module; post.js gives every other post program a stub. It reads hash and@@ -27,11 +27,23 @@ function bindUniforms(renderer, post, volume, environment, frame) {context.uniform1f(post.uniforms.volumeMaxDistance, volume.maxDistance);context.uniform1f(post.uniforms.volumeHeightFalloff, volume.heightFalloff);bindFieldAndLights(renderer, post, volume);+ bindDetail(context, post, volume);context.uniform1f(post.uniforms.orthographic, frame.projection === 'orthographic' ? 1 : 0);context.uniform1i(post.uniforms.fogSkyVisibility, 5);context.uniform1f(post.uniforms.volumeGridFog, renderer.sceneParts.some(part => part.material?.irradianceGrid) ? 1 : 0);}+// Detail, layer top and key light controls. The detail ones only act in a program with the detail step compiled in (fogUsesDetail).+function bindDetail(context, post, volume) {+ const detail = { ...DEFAULT_DETAIL, ...volume };+ context.uniform1i(post.uniforms.volumeDetailOctaves, detail.detailOctaves);+ context.uniform1f(post.uniforms.volumeDetailAmount, detail.detailAmount);+ context.uniform1f(post.uniforms.volumeWarp, detail.warp);+ context.uniform1f(post.uniforms.volumeContrast, detail.contrast);+ context.uniform1f(post.uniforms.volumeProfileStart, detail.profileSoftness);+ context.uniform1f(post.uniforms.volumeKeyScattering, detail.keyScattering);+}+// The fog's field texture and light buffers; a program without those steps has no such uniforms, and a null location is ignored.function bindFieldAndLights(renderer, post, volume) {const context = renderer.context;@@ -84,6 +96,12 @@ uniform sampler2D volumeField;uniform float volumeProfile;uniform float volumeFlowStrength;uniform float volumeFlowPeriod;+uniform int volumeDetailOctaves;+uniform float volumeDetailAmount;+uniform float volumeWarp;+uniform float volumeContrast;+uniform float volumeProfileStart;+uniform float volumeKeyScattering;uniform int volumeLightCount;uniform vec4 volumeLightPositions[8];uniform vec4 volumeLightColors[8];@@ -121,16 +139,47 @@ vec3 fogLightScattering(vec3 position, vec3 direction) {}return total;}-float flowedNoise(vec3 samplePosition, vec2 velocity) {+float flowedNoise(vec3 samplePosition, vec2 velocity, float noiseScale) {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);+ float first = cloudNoise((samplePosition - travel * firstPhase) * noiseScale);+ float second = cloudNoise((samplePosition - travel * secondPhase) * noiseScale);return mix(first, second, abs(2.0 * firstPhase - 1.0));}+float noiseAt(vec3 samplePosition, vec2 velocity, float noiseScale) {+ return POST_FIELD ? flowedNoise(samplePosition, velocity, noiseScale) : cloudNoise(samplePosition * noiseScale);+}+// The density noise in 0..1. With the detail step compiled out this is the single lookup. With it, the position is warped by+// three low-frequency lookups (warp counts noise cells), up to two octaves at 2x and 4x frequency join in (weights 0.5 and 0.25+// times detailAmount, renormalised so the mean stays), and contrast stretches the result around its middle.+float densityNoise(vec3 samplePosition, vec2 velocity) {+ vec3 warped = samplePosition;+ if (POST_DETAIL && volumeWarp > 0.0) {+ vec3 seed = samplePosition * volumeNoiseScale * 0.5;+ vec3 offset = vec3(cloudNoise(seed + 17.0), cloudNoise(seed + 43.0), cloudNoise(seed + 71.0)) - 0.5;+ warped += offset * (2.0 * volumeWarp / volumeNoiseScale);+ }+ float lookup = noiseAt(warped, velocity, volumeNoiseScale);+ if (POST_DETAIL) {+ float total = 1.0;+ float sum = lookup;+ if (volumeDetailOctaves > 1) {+ float weight = 0.5 * volumeDetailAmount;+ sum += weight * noiseAt(warped, velocity, volumeNoiseScale * 2.0);+ total += weight;+ }+ if (volumeDetailOctaves > 2) {+ float weight = 0.25 * volumeDetailAmount;+ sum += weight * noiseAt(warped, velocity, volumeNoiseScale * 4.0);+ total += weight;+ }+ lookup = clamp(0.5 + (sum / total - 0.5) * volumeContrast, 0.0, 1.0);+ }+ return lookup;+}float layerProfile(float relativeHeight) {- return volumeProfile > 0.5 ? 1.0 - smoothstep(0.5, 1.0, relativeHeight) : exp(-relativeHeight);+ return volumeProfile > 0.5 ? 1.0 - smoothstep(volumeProfileStart, 1.0, relativeHeight) : exp(-relativeHeight);}vec3 volumeFog(vec3 background) {vec2 clipXY = textureCoordinate * 2.0 - 1.0;@@ -169,7 +218,7 @@ vec3 volumeFog(vec3 background) {float noise = 1.0;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);+ float lookup = densityNoise(position - volumeDrift * time, field.zw);noise = mix(1.0, lookup * 2.0, volumeNoiseAmount);}if (POST_FIELD) noise *= field.r * layerProfile((position.y - volumeMinimum.y) / max(field.g, 0.0001));@@ -185,7 +234,7 @@ vec3 volumeFog(vec3 background) {float shadowShare = POST_SKY ? 0.1 + 0.9 * min(1.0, 30.0 * skyCell.r) : volumeShadowAmbient;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);+ vec3 scattering = volumeColor * (volumeAmbient * ambientShare + volumeLightColor * (phase * visibility * volumeKeyScattering) + 0.6 * skyCell.gba);if (POST_LIGHTS) scattering += volumeColor * fogLightScattering(position, direction);accumulated += transmittance * opacity * scattering;transmittance *= 1.0 - opacity;diff --git a/src/post.js b/src/post.jsindex 4990efa7..68dcfdcc 100644--- a/src/post.js+++ b/src/post.js@@ -163,6 +163,7 @@ const POST_STEP_CONDITIONS = {volume: ['POST_VOLUME', 'volumeDensity > 0.0'],sky: ['POST_SKY', 'true'],field: ['POST_FIELD', 'true'],+ detail: ['POST_DETAIL', 'true'],lights: ['POST_LIGHTS', 'volumeLightCount > 0'],explosion: ['POST_EXPLOSION', 'volumeExplosion > 0.5'],finish: ['POST_FINISH', 'true'],@@ -171,7 +172,7 @@ const POST_STEP_CONDITIONS = {// The program with every step is the one a frame draws while a variant builds. It leaves out the steps below: the fog sky grid,// field and lights exist only inside a fog, and the volume fog and explosion code load from fog-shader.js and explosion-shader.js// only for a renderer that draws them.-export const POST_STEPS_WITH_OPTIONAL_CODE = Object.freeze(['volume', 'sky', 'field', 'lights', 'explosion']);+export const POST_STEPS_WITH_OPTIONAL_CODE = Object.freeze(['volume', 'sky', 'field', 'detail', 'lights', 'explosion']);export const POST_STEPS = Object.freeze(Object.keys(POST_STEP_CONDITIONS).filter(step => !POST_STEPS_WITH_OPTIONAL_CODE.includes(step)));const EXPLOSION_STUB = 'vec3 explosion(vec3 background) { return background; }';diff --git a/src/renderer.js b/src/renderer.jsindex 857509e4..64296da4 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -12,7 +12,7 @@ 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, validateFogField } from './volumetric.js';+import { resolveVolumeFog, validateFogField, fogUsesDetail } from './volumetric.js';import { requireEnvironmentSupport } from './environment-shading.js';import { materialLayerState, materialLayerValue } from './material-layers.js';import { MaterialSnapshot } from './material-snapshot.js';@@ -46,7 +46,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', 'volumeField', 'volumeProfile', 'volumeFlowStrength', 'volumeFlowPeriod', 'volumeLightCount', 'volumeLightPositions[0]', 'volumeLightColors[0]', 'volumeLightDirections[0]', 'volumeLightCones[0]', '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', 'volumeDetailOctaves', 'volumeDetailAmount', 'volumeWarp', 'volumeContrast', 'volumeProfileStart', 'volumeKeyScattering', '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)]));@@ -1740,6 +1740,7 @@ export class Renderer67 {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 && fogUsesDetail(volume)) steps.push('detail');if (volume.density > 0 && this.fogLightBuffers?.count > 0) steps.push('lights');if (fogSky) steps.push('sky');if (frame.volumeExplosion) steps.push('explosion');diff --git a/src/volumetric.js b/src/volumetric.jsindex f77a6419..7638833a 100644--- a/src/volumetric.js+++ b/src/volumetric.js@@ -66,5 +66,19 @@ export function resolveVolumeFog(input = {}) {if (!FOG_PROFILES.includes(input.profile)) throw new RangeError(`Volume profile must be one of ${FOG_PROFILES.join(', ')}`);resolved.profile = input.profile;}+ if (input.detailOctaves !== undefined) {+ resolved.detailOctaves = finiteRange(input.detailOctaves, 1, 3, 'Volume detail octaves');+ if (!Number.isInteger(resolved.detailOctaves)) throw new RangeError('Volume detail octaves must be an integer');+ }+ if (input.detailAmount !== undefined) resolved.detailAmount = finiteRange(input.detailAmount, 0, 1, 'Volume detail amount');+ if (input.warp !== undefined) resolved.warp = finiteRange(input.warp, 0, 4, 'Volume warp');+ if (input.contrast !== undefined) resolved.contrast = finiteRange(input.contrast, 0, 4, 'Volume contrast');+ if (input.profileSoftness !== undefined) resolved.profileSoftness = finiteRange(input.profileSoftness, 0, 0.95, 'Volume profile softness');+ if (input.keyScattering !== undefined) resolved.keyScattering = finiteRange(input.keyScattering, 0, 10, 'Volume key scattering');return resolved;}++/** True when the density noise differs from the plain single lookup, so the frame needs the post program with the detail step. */+export function fogUsesDetail(volume) {+ return (volume.detailOctaves ?? 1) > 1 || (volume.warp ?? 0) > 0 || (volume.contrast ?? 1) !== 1;+}diff --git a/tests/fog-field.test.js b/tests/fog-field.test.jsindex ccccbc94..acf92a32 100644--- a/tests/fog-field.test.js+++ b/tests/fog-field.test.js@@ -1,7 +1,8 @@import test from 'node:test';import assert from 'node:assert/strict';-import { resolveVolumeFog, validateFogField } from '../src/volumetric.js';+import { resolveVolumeFog, validateFogField, fogUsesDetail } from '../src/volumetric.js';import { createLightingState, updateLightingState } from '../src/lighting.js';+import { normalizeAgentLook } from '../src/agent-look.js';import { FOG_LIGHT_LIMIT, createFogLightBuffers, packFogLights, FogFieldTexture } from '../src/fog-field.js';import { createPostFragment, POST_STEPS } from '../src/post.js';@@ -77,3 +78,39 @@ test('the field texture allocates once per size and writes into it afterwards',texture.dispose();assert.equal(calls.at(-1), 'delete');});++const DETAIL_FIELDS = ['detailOctaves', 'detailAmount', 'warp', 'contrast', 'profileSoftness', 'keyScattering'];++test('a fog without detail controls resolves without them and needs no detail step', () => {+ const resolved = resolveVolumeFog({ density: 0.1 });+ for (const key of DETAIL_FIELDS) assert.equal(Object.hasOwn(resolved, key), false, key);+ assert.equal(fogUsesDetail(resolved), false);+ assert.equal(fogUsesDetail(resolveVolumeFog({ density: 0.1, detailOctaves: 1, warp: 0, contrast: 1, profileSoftness: 0.2, keyScattering: 3 })), false, 'profile and key scattering are plain uniforms');+});++test('detail controls are kept, bounded and typed', () => {+ const resolved = resolveVolumeFog({ detailOctaves: 3, detailAmount: 0.6, warp: 0.8, contrast: 1.6, profileSoftness: 0.1, keyScattering: 2 });+ assert.deepEqual(DETAIL_FIELDS.map(key => resolved[key]), [3, 0.6, 0.8, 1.6, 0.1, 2]);+ assert.equal(fogUsesDetail(resolved), true);+ for (const bounds of [{ detailOctaves: 4 }, { detailOctaves: 0 }, { detailAmount: 1.1 }, { warp: -1 }, { warp: 5 }, { contrast: 4.5 }, { profileSoftness: 1 }, { keyScattering: 11 }, { keyScattering: -1 }]) {+ assert.throws(() => resolveVolumeFog(bounds), RangeError, JSON.stringify(bounds));+ }+ assert.throws(() => resolveVolumeFog({ detailOctaves: 2.5 }), /integer/);+ for (const field of DETAIL_FIELDS) {+ for (const bad of ['1', null, NaN, Infinity]) assert.throws(() => resolveVolumeFog({ [field]: bad }), /must be between/, `${field} ${bad}`);+ }+});++test('the recipe look accepts the detail controls and rejects bad ones', () => {+ const look = normalizeAgentLook({ environment: { volumeFog: { density: 0.5, detailOctaves: 2, detailAmount: 0.4, warp: 1, contrast: 1.2, profileSoftness: 0.3, keyScattering: 1.5 } } });+ assert.equal(look.environment.volumeFog.detailOctaves, 2);+ assert.equal(look.environment.volumeFog.keyScattering, 1.5);+ assert.throws(() => normalizeAgentLook({ environment: { volumeFog: { detailOctaves: 1.5 } } }));+ assert.throws(() => normalizeAgentLook({ environment: { volumeFog: { warp: 9 } } }));+});++test('the detail step is compiled in only on request', () => {+ assert.equal(POST_STEPS.includes('detail'), false);+ assert.match(createPostFragment(), /#define POST_DETAIL false/);+ assert.match(createPostFragment([...POST_STEPS, 'detail']), /#define POST_DETAIL \(true\)/);+});