Skip to content

3D engine that AI agents drive

Add a stylized colour ramp to water materials (#2033)

Nguyen Xuan Anbbae20641e76
diff --git a/changes/2033.md b/changes/2033.md
new file mode 100644
index 00000000..5d135be1
--- /dev/null
+++ b/changes/2033.md
@@ -0,0 +1 @@
+- Water: `waterRamp` paints a sea in 3 to 5 flat tones picked by wave height, facing and the sun, with a crest tint, off by default (#2033)
diff --git a/changes/2033.size.md b/changes/2033.size.md
new file mode 100644
index 00000000..b2294a6c
--- /dev/null
+++ b/changes/2033.size.md
@@ -0,0 +1,9 @@
+- entry:world-material-shader: the ramp shader function, its uniforms, the bind and the validation (1566 bytes gzip) give agents a stylized water look that no other field gives.
+- entry:nature: the same world material code ships inside this entry (801 bytes gzip).
+- entry:vegetation: the same world material code ships inside this entry (826 bytes gzip).
+- entry:terrain: the same world material code ships inside this entry (798 bytes gzip).
+- entry:grass: the same world material code ships inside this entry (806 bytes gzip).
+- entry:clutter: the same world material code ships inside this entry (801 bytes gzip).
+- scene:agent-scene: the waterRamp field name and its module trigger (135 bytes gzip).
+- scene:agent-scene+lazy: the ramp validation that loads with the world materials module (1713 bytes gzip).
+- goal:agent-scene: the agent-facing capability is a new field on the water material, 135 bytes gzip.
diff --git a/docs/agent-scene.md b/docs/agent-scene.md
index 1c8765ec..e135e9ab 100644
--- a/docs/agent-scene.md
+++ b/docs/agent-scene.md
@@ -107,6 +107,7 @@ The defaults are `surface`, `[0.5, 0.5, 0.5]`, `0`, `0.5`, `0`, opacity `1`, `op
The tag can be `surface`, `unlit`, `liquid`, `foam`, `water`, `foliage` or `grass` (the last two sway in `environment.wind`) and remains fixed during editing.
`liquid` refracts and tints what lies behind it: its color is the light one metre lets through, so `[0.56, 0.84, 0.88]` is clear water. `foam` draws soft blended droplets.
`water` is a flat mirror sheet (a plane or thin box). The largest one sets the water level: everything below it fades by `exp(-absorption * depth)` per colour channel (`absorption` is RGB per metre), and its shadows are lifted and softened with depth times `turbidity` (0 clear to 1 murky). `waterPreset` fills both: `lake` (default), `sea` or `river`. A shadow on the surface is faint and never darkens the reflection; give the sheet an `opacity` below one when the bed should show. The sun's leg to a bed is bent at n = 1.33 and absorbed over `depth / cos(theta_t)`, so a clear lake keeps little shadow contrast on a bed 4 m down, and a murky river keeps about a quarter.
+`waterRamp` (off by default) paints the sea in flat anime tones: `{ colors: [3 to 5 RGB, deep to bright], drivers: { height, facing, sun } (weights 0 to 1, default height 1), heightRange: [low, high] (world y, default -1 to 1), steps: hard (default) or soft, crestTint: { color, strength } }`. A weighted mix of the drivers picks the tone: `height` is world y across `heightRange`, `facing` rises toward the horizon, `sun` is how squarely a wave face meets the key light. The ramp owns the colour, so the sky reflection and the lit shading are not drawn; foam and the sun glint still add on top. `crestTint` colours the folded crests the `foam` group marks, wider than the foam itself. It needs the water tag; depth and a shallow and deep pair are not drivers yet.
Any `opacity` below one draws the material blended after opaque geometry, which suits glass, windows and visors. `alphaMode` accepts `opaque`, `blend` or `add` (additive light for sparks, trails and glow); cutout masking needs a texture and is not available in procedural recipes.
`doubleSided` draws and lights both faces of thin sheets.
Changing the tag, opacity, blending, sidedness or pattern replaces the affected parts in the renderer; color, metallic, roughness and emission edits keep them.
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 3901be31..29a88175 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -159,6 +159,7 @@ const waterFields = {
waterPreset: z.enum(['lake', 'sea', 'river']).optional().describe('Water tag.'),
absorption: z.array(z.number().min(0).max(20)).length(3).optional().describe('Water tag: RGB per metre.'),
turbidity: unit.optional().describe('Water tag: 0 clear to 1 murky.'),
+ waterRamp: z.record(z.string(), z.unknown()).optional().describe('Water tag: flat colour ramp, see scene_capabilities water.'),
};
const subsurfaceTriple = ([minimum, maximum]) => z.tuple([0, 1, 2].map(() => z.number().min(minimum).max(maximum)));
const subsurface = z.strictObject({
@@ -193,7 +194,7 @@ const materialFields = {
};
const materialTag = z.enum(['surface', 'unlit', 'liquid', 'foam', 'foliage', 'grass', 'water']).optional().describe('Surface kind; liquid, foam, foliage, grass and water change how it renders: see scene_capabilities materialTags and water.');
const materialCore = coreOf(materialFields, ['color', 'metallic', 'roughness', 'emission', 'opacity']);
-const materialMore = 'More fields: tag, alphaMode, doubleSided, emissiveColor, map, pattern, subsurface, snippet, wear, retro, waterPreset, absorption, turbidity and the layers clearcoat, clearcoatRoughness, transmission, thickness, ior, attenuationColor, attenuationDistance, sheenColor, sheenRoughness, specular, specularColor, anisotropy, anisotropyRotation, iridescence, iridescenceIor, iridescenceThickness, toon; see scene_capabilities materialFields.';
+const materialMore = 'More fields: tag, alphaMode, doubleSided, emissiveColor, map, pattern, subsurface, snippet, wear, retro, waterPreset, absorption, turbidity, waterRamp and the layers clearcoat, clearcoatRoughness, transmission, thickness, ior, attenuationColor, attenuationDistance, sheenColor, sheenRoughness, specular, specularColor, anisotropy, anisotropyRotation, iridescence, iridescenceIor, iridescenceThickness, toon; see scene_capabilities materialFields.';
const materialListed = (strictSchema, description, extraCore) => listed('materialFields', strictSchema, `${description} ${materialMore}`, { ...extraCore, ...materialCore });
const liquidOptics = z.strictObject({
thickness: z.number().min(0).max(100).optional().describe('Metres of liquid where it faces the camera.'),
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 3835587d..0020e575 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -265,7 +265,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
]),
materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam', 'foliage', 'grass', 'water']),
// A flat water sheet; the largest sets the level. A bed d metres down keeps exp(-absorption * d) per channel (RGB per metre).
- water: Object.freeze({ presets: WATER_PRESETS_SUMMARY, default: 'lake', note: 'absorption 0..20, turbidity 0..1 softens shadows below; opacity under 1 shows the bed.' }),
+ water: Object.freeze({ presets: WATER_PRESETS_SUMMARY, default: 'lake', note: 'absorption 0..20, turbidity 0..1 softens shadows below; opacity under 1 shows the bed. waterRamp {colors [3-5 rgb, deep to bright], drivers {height, facing, sun: weights 0-1; default height 1}, heightRange [low, high] world y (-1, 1), steps hard|soft (hard), crestTint {color, strength 0-1}} paints flat tones that own the colour (no sky reflection; foam and glint stay), off by default.' }),
materialLayers: Object.freeze(Object.fromEntries(MATERIAL_LAYER_FIELDS.map(field => [field, Object.freeze({
range: MATERIAL_LAYER_SCALAR_RANGES[field] ?? MATERIAL_LAYER_COLOR_RANGES[field] ?? 'above 0',
note: MATERIAL_LAYER_NOTES[field],
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index b09e8e65..ace5029d 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -85,7 +85,7 @@ const MODULE_MARKERS = {
retroShader: ['"retro"'],
// Any mention loads it, because an edit can set the density through a path or the environment of an operation.
fogShader: ['volumeFog', 'localVolumes', '"add-explosion"'],
- worldMaterials: ['"tag":"water"', '"waterPreset"', '"absorption"', '"turbidity"', '"vegetation":{', '"tag":"foliage"', '"tag":"grass"', '"tag":"terrain"', '"tag":"fire"', '"tag":"smoke"', '"moss"'],
+ worldMaterials: ['"tag":"water"', '"waterPreset"', '"absorption"', '"turbidity"', '"waterRamp"', '"vegetation":{', '"tag":"foliage"', '"tag":"grass"', '"tag":"terrain"', '"tag":"fire"', '"tag":"smoke"', '"moss"'],
terrain: ['"type":"terrain"'],
// No recipe text asks for it, only the path option of scene_inspect does, so a host loads it with loadAllAgentSceneModules.
navigation: [],
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 70258db9..2fa91e3f 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -61,7 +61,7 @@ const CAMERA_DEFAULTS = Object.freeze({ eye: [4, 3, 5], target: [0, 0, 0], up: [
const RENDER_FLAG_FIELDS = ['visible', 'castShadow', 'receiveShadow', 'holdout', 'shadowCatcher', 'shadowOnly'];
const PART_FLAG_FIELDS = RENDER_FLAG_FIELDS.slice(1);
const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material', 'skin', 'relations', 'asset', 'vegetation', 'decal', 'depthLayer', 'blend', 'rayVisibility', ...RENDER_FLAG_FIELDS];
-const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', 'map', 'subsurface', 'snippet', 'waterPreset', 'absorption', 'turbidity', 'aov', 'wear', 'retro', 'emissionMask', ...MATERIAL_LAYER_FIELDS];
+const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', 'map', 'subsurface', 'snippet', 'waterPreset', 'absorption', 'turbidity', 'waterRamp', 'aov', 'wear', 'retro', 'emissionMask', ...MATERIAL_LAYER_FIELDS];
const PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'emissiveMap', 'layerMaps', 'transmissionMap', 'aovMap', 'emissionFresnel', 'boxMapScale', 'boxMapAxis'];
const CAMERA_FIELDS = [...Object.keys(CAMERA_DEFAULTS), ...CAMERA_LENS_FIELDS];
const LOOK_OPERATION_FIELDS = Object.freeze({
@@ -340,6 +340,7 @@ function materialFrom(value) {
if (value.retro !== undefined && value.retro !== null) result.retro = agentSceneModule('retroShader').normalizeMaterialRetro(value.retro);
if (agentSceneModuleLoaded('worldMaterials')) {
agentSceneModule('worldMaterials').copyWaterFields(value, result, vector);
+ agentSceneModule('worldMaterials').copyWaterRamp(value, result, vector);
}
const emissiveColor = result.emissiveColor ?? result.color;
for (const component of emissiveColor) {
diff --git a/src/renderer.js b/src/renderer.js
index 2a3cdec3..963f62a2 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -228,7 +228,7 @@ function materialMapState(material) {
const occlusionStrength = material.occlusionStrength ?? 1;
if (material.layers || material.splat) requireSplatSupport().validate(material);
if (material.layers && PROCEDURAL_MATERIAL_TAGS.has(material.tag)) throw new Error('Splat layers require a standard PBR material tag.');
- return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength, ...mossState(material), material.boxMapScale ?? 0, material.boxMapAxis ?? 1, ...lightMapState(material), material.layers ?? null, material.splat ?? null, material.layerMaps ?? null, material.environmentProbe ?? null, material.waterReflection ?? null, material.irradianceGrid ?? null, material.wear ?? null];
+ return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength, ...mossState(material), material.boxMapScale ?? 0, material.boxMapAxis ?? 1, ...lightMapState(material), material.layers ?? null, material.splat ?? null, material.layerMaps ?? null, material.environmentProbe ?? null, material.waterReflection ?? null, material.irradianceGrid ?? null, material.wear ?? null, material.waterRamp ?? null];
}
// A baked light map reads the second UV set, so it is only drawn for parts that cannot be skinned or morphed.
diff --git a/src/world-material-shader.js b/src/world-material-shader.js
index a635da6f..489a716d 100644
--- a/src/world-material-shader.js
+++ b/src/world-material-shader.js
@@ -48,6 +48,80 @@ export function copyWaterFields(value, result, toVector) {
Object.assign(result, resolveWaterMaterial({ ...value, absorption }));
}
+export const WATER_RAMP_COLOR_COUNT = Object.freeze([3, 5]);
+const WATER_RAMP_DRIVERS = Object.freeze(['height', 'facing', 'sun']);
+const WATER_RAMP_FIELDS = Object.freeze(['colors', 'drivers', 'heightRange', 'steps', 'crestTint']);
+const WATER_RAMP_STEPS = Object.freeze(['hard', 'soft']);
+const WATER_RAMP_DEFAULT_HEIGHT_RANGE = Object.freeze([-1, 1]);
+
+function rampColor(value, name, toVector) {
+ const color = toVector(value, 3, name);
+ if (color.some(component => !Number.isFinite(component) || component < 0 || component > 16)) {
+ throw new RangeError(`${name} must be three numbers from 0 to 16, such as [0.1, 0.5, 0.6].`);
+ }
+ return Object.freeze([...color]);
+}
+
+function rampDrivers(drivers) {
+ const given = drivers ?? { height: 1 };
+ const unknown = Object.keys(given).filter(name => !WATER_RAMP_DRIVERS.includes(name));
+ if (unknown.length > 0) {
+ throw new RangeError(`waterRamp.drivers has no ${unknown.join(', ')}; pass weights for ${WATER_RAMP_DRIVERS.join(', ')}, such as { "height": 1, "sun": 0.5 }.`);
+ }
+ const weights = WATER_RAMP_DRIVERS.map(name => given[name] ?? 0);
+ if (weights.some(weight => !Number.isFinite(weight) || weight < 0 || weight > 1) || weights.every(weight => weight === 0)) {
+ throw new RangeError('waterRamp.drivers weights must be numbers from 0 to 1 with at least one above 0, such as { "height": 1, "sun": 0.5 }.');
+ }
+ return Object.freeze(Object.fromEntries(WATER_RAMP_DRIVERS.map((name, index) => [name, weights[index]])));
+}
+
+/**
+ * The stylized colour ramp of a water material. `colors` (3 to 5, deep to bright) are picked by a weighted mix of drivers: `height`
+ * (world y across `heightRange`, default -1 to 1), `facing` (grazing view, 1 at the horizon) and `sun` (how squarely the wave face meets
+ * the sun). `steps` hard (default) keeps flat tones, soft blends them. `crestTint` { color, strength 0-1 } colours the folded crests.
+ */
+export function resolveWaterRamp(ramp, toVector) {
+ if (typeof ramp !== 'object' || ramp === null || Array.isArray(ramp)) {
+ throw new RangeError('waterRamp must be an object such as { "colors": [[0.02, 0.2, 0.3], [0.1, 0.6, 0.7], [0.5, 0.95, 0.95]] }.');
+ }
+ const unknown = Object.keys(ramp).filter(name => !WATER_RAMP_FIELDS.includes(name));
+ if (unknown.length > 0) {
+ throw new RangeError(`waterRamp has no ${unknown.join(', ')}; use ${WATER_RAMP_FIELDS.join(', ')}.`);
+ }
+ const [minimumColors, maximumColors] = WATER_RAMP_COLOR_COUNT;
+ if (!Array.isArray(ramp.colors) || ramp.colors.length < minimumColors || ramp.colors.length > maximumColors) {
+ throw new RangeError(`waterRamp.colors must list ${minimumColors} to ${maximumColors} colours from deep to bright, such as [[0.02, 0.2, 0.3], [0.1, 0.6, 0.7], [0.5, 0.95, 0.95]].`);
+ }
+ const steps = ramp.steps ?? 'hard';
+ if (!WATER_RAMP_STEPS.includes(steps)) {
+ throw new RangeError(`waterRamp.steps must be one of ${WATER_RAMP_STEPS.join(', ')}, such as hard.`);
+ }
+ const heightRange = ramp.heightRange ?? WATER_RAMP_DEFAULT_HEIGHT_RANGE;
+ if (!Array.isArray(heightRange) || heightRange.length !== 2 || !heightRange.every(Number.isFinite) || heightRange[0] >= heightRange[1]) {
+ throw new RangeError('waterRamp.heightRange must be [low, high] world heights with low below high, such as [-1, 1].');
+ }
+ const resolved = { colors: Object.freeze(ramp.colors.map((color, index) => rampColor(color, `waterRamp.colors[${index}]`, toVector))), drivers: rampDrivers(ramp.drivers), heightRange: Object.freeze([...heightRange]), steps };
+ if (ramp.crestTint !== undefined) {
+ const { color, strength = 1, ...extra } = ramp.crestTint ?? {};
+ if (color === undefined || Object.keys(extra).length > 0 || !Number.isFinite(strength) || strength < 0 || strength > 1) {
+ throw new RangeError('waterRamp.crestTint must be { "color": [r, g, b], "strength": 0 to 1 }, such as { "color": [0.7, 1, 0.9], "strength": 0.8 }.');
+ }
+ resolved.crestTint = Object.freeze({ color: rampColor(color, 'waterRamp.crestTint.color', toVector), strength });
+ }
+ return Object.freeze(resolved);
+}
+
+/** Copies a recipe material's `waterRamp`: it needs the water tag. */
+export function copyWaterRamp(value, result, toVector) {
+ if (value.waterRamp === undefined) {
+ return;
+ }
+ if (result.tag !== 'water') {
+ throw new RangeError('waterRamp needs the water tag.');
+ }
+ result.waterRamp = resolveWaterRamp(value.waterRamp, toVector);
+}
+
function partBounds(part) {
const { positions } = part.geometry;
const { matrix } = part;
@@ -168,10 +242,32 @@ export const worldMaterialSlots = {
// Shadow of a surface under murky water: the classic shadow map read over a wider disc. A cascaded map is read through
// its own macro and keeps its filter.
declarations: `uniform vec4 waterBody;
+uniform vec4 waterRampHead;
+uniform vec3 waterRampWeights;
+uniform vec2 waterRampHeightRange;
+uniform vec4 waterRampCrest;
+uniform vec3 waterRampColors[5];
uniform vec3 waterAbsorption;
uniform sampler2D waterScene;
uniform mat4 viewProjection;
// The frame texture holds the picture as it leaves the shader: scaled by exposure and, outside HDR, tone mapped and encoded.
+// The stylized ramp: waterRampHead is (colour count, 1 for soft steps, 0, 0) and waterRampWeights the height, facing and sun weights.
+// A hard ramp has a one pixel edge (fwidth) so a band does not crawl.
+vec3 waterRampTone(float height, float facing, float sun) {
+ float count = waterRampHead.x;
+ float heightFraction = clamp((height - waterRampHeightRange.x) / (waterRampHeightRange.y - waterRampHeightRange.x), 0.0, 1.0);
+ float driven = dot(waterRampWeights, vec3(heightFraction, facing, sun)) / dot(waterRampWeights, vec3(1.0));
+ if (waterRampHead.y > 0.5) {
+ float blendPosition = clamp(driven, 0.0, 1.0) * (count - 1.0);
+ int lower = int(floor(min(blendPosition, count - 1.001)));
+ return mix(waterRampColors[lower], waterRampColors[lower + 1], blendPosition - float(lower));
+ }
+ float position = clamp(driven, 0.0, 0.9999) * count;
+ int band = int(floor(position));
+ float edge = smoothstep(0.0, max(fwidth(position), 0.0001), fract(position));
+ return band == 0 ? waterRampColors[0] : mix(waterRampColors[band - 1], waterRampColors[band], edge);
+}
+
vec3 waterDecode(vec3 encoded) {
vec3 linear = encoded;
if (hdrEnabled < 0.5) {
@@ -359,6 +455,8 @@ void mossMasks(vec3 normal, float amount, out float sharpMask, out float softMas
`,
worldSurface: ` float waterFoam = 0.0;
+ vec3 waterRampRadiance = vec3(0.0);
+ float waterRampOwns = 0.0;
float waterLostVariance = 0.0;
if (TAG_WATER) {
// Small ripples tilt the surface's own normal, so a sea mesh keeps its waves; a flat sheet (normal up) gets the same ripples as before.
@@ -393,6 +491,14 @@ void mossMasks(vec3 normal, float amount, out float sharpMask, out float softMas
color = mix(color, vec3(0.0137, 0.147, 0.195), grazing * 0.85);
color = mix(color, vec3(0.92, 0.95, 0.97) * (0.68 + 0.32 * (fineLace * 0.5 + midLace * 0.5)), waterFoam);
roughness = mix(0.16, 0.8, waterFoam);
+ if (waterRampHead.x > 0.5) {
+ float rampSun = clamp(dot(normal, normalize(lightDirection)), 0.0, 1.0);
+ vec3 rampTone = waterRampTone(worldPosition.y, 1.0 - max(dot(normal, viewDirection), 0.0), rampSun);
+ float crestEdge = waterRampHead.y > 0.5 ? 0.15 : max(1.5 * fwidth(foamMask), 0.0001);
+ float crestAmount = waterRampCrest.w * smoothstep(0.2 - crestEdge, 0.2 + crestEdge, foamMask);
+ waterRampRadiance = mix(rampTone, waterRampCrest.rgb, crestAmount);
+ waterRampOwns = 1.0;
+ }
}
if (CANOPY_TAG) {
float leaves = sin(worldPosition.x * 13.0 + sin(worldPosition.y * 9.0)) * sin(worldPosition.z * 11.0 - worldPosition.y * 5.0);
@@ -457,6 +563,8 @@ void mossMasks(vec3 normal, float amount, out float sharpMask, out float softMas
mirrorDirection.y = max(mirrorDirection.y, 0.02);
vec3 skyColor = ENVIRONMENT_ENABLED ? surroundingsColor(mirrorDirection, 0.05) : mix(vec3(0.12, 0.24, 0.28), vec3(0.40, 0.63, 0.78), clamp(mirrorDirection.y, 0.0, 1.0)) * daylight;
radiance = mix(radiance * 0.6 + color * ambientIntensity * daylight * 1.7, skyColor * ambientIntensity, clamp(reflectivity, 0.0, 1.0));
+ // A ramp owns the colour: no sky reflection, so the tones stay flat; foam and the sun glint still add on top.
+ if (waterRampOwns > 0.5) radiance = waterRampRadiance * (1.0 - waterFoam);
// Sun glint: a narrow lobe around the mirror direction, the width of open water slopes, bright enough to bloom.
vec3 halfVector = normalize(normalize(lightDirection) + viewDirection);
float glintSharpness = 1.0 / (1.0 / 500.0 + 0.35 * waterLostVariance);
@@ -502,3 +610,34 @@ export function applyWindHeading(renderer, radians) {
if (renderer.windHeading !== radians) renderer.shadowsDirty = true;
renderer.windHeading = radians;
}
+
+const waterRampLocations = new WeakMap();
+const NO_RAMP = Object.freeze({ colors: [], drivers: { height: 1, facing: 0, sun: 0 }, heightRange: [-1, 1], steps: 'hard' });
+const RAMP_COLOR_SLOTS = WATER_RAMP_COLOR_COUNT[1];
+
+/** Sends the ramp of a water batch; a batch without one sends a colour count of 0, which leaves the water as it was. */
+function bindWaterRamp(renderer, batch) {
+ if (!renderer.shaderFeatures?.has('water')) {
+ return;
+ }
+ let locations = waterRampLocations.get(renderer);
+ if (locations?.program !== renderer.program) {
+ const locate = name => renderer.context.getUniformLocation(renderer.program, name);
+ locations = { program: renderer.program, head: locate('waterRampHead'), weights: locate('waterRampWeights'), heightRange: locate('waterRampHeightRange'), crest: locate('waterRampCrest'), colors: locate('waterRampColors') };
+ waterRampLocations.set(renderer, locations);
+ }
+ const ramp = batch.parts[0].material.waterRamp ?? NO_RAMP;
+ const context = renderer.context;
+ context.uniform4f(locations.head, ramp.colors.length, ramp.steps === 'soft' ? 1 : 0, 0, 0);
+ context.uniform3f(locations.weights, ramp.drivers.height, ramp.drivers.facing, ramp.drivers.sun);
+ context.uniform2f(locations.heightRange, ...ramp.heightRange);
+ context.uniform4f(locations.crest, ...(ramp.crestTint?.color ?? [0, 0, 0]), ramp.crestTint?.strength ?? 0);
+ const padding = Array.from({ length: RAMP_COLOR_SLOTS - ramp.colors.length }, () => [0, 0, 0]);
+ context.uniform3fv(locations.colors, new Float32Array([...ramp.colors, ...padding].flat()));
+}
+
+const bindBeforeRamp = layerTextureSupport.bind;
+layerTextureSupport.bind = (renderer, mapState, layerState, batch) => {
+ bindBeforeRamp?.(renderer, mapState, layerState, batch);
+ bindWaterRamp(renderer, batch);
+};
diff --git a/tests/water-ramp.test.js b/tests/water-ramp.test.js
new file mode 100644
index 00000000..3ed40f5c
--- /dev/null
+++ b/tests/water-ramp.test.js
@@ -0,0 +1,94 @@
+import './support/load-agent-scene-modules.mjs';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createAgentScene } from '../src/agent-scene.js';
+import { createFragmentShader, layerTextureSupport } from '../src/shaders.js';
+import '../src/world-material-shader.js';
+
+const COLORS = [[0.01, 0.12, 0.2], [0.04, 0.4, 0.5], [0.3, 0.85, 0.9]];
+
+function sceneWith(material) {
+ return createAgentScene({
+ format: 'crucible.scene', schemaVersion: 1,
+ geometries: [{ id: 'sheet', type: 'box' }],
+ materials: [{ id: 'sea', ...material }],
+ nodes: [{ id: 'sea', geometry: 'sheet', material: 'sea' }],
+ });
+}
+
+function rampOf(waterRamp) {
+ return sceneWith({ tag: 'water', waterRamp }).parts[0].material.waterRamp;
+}
+
+test('a water ramp keeps its colours and fills the defaults', () => {
+ const ramp = rampOf({ colors: COLORS });
+ assert.deepEqual(ramp.colors, COLORS);
+ assert.deepEqual(ramp.drivers, { height: 1, facing: 0, sun: 0 });
+ assert.deepEqual(ramp.heightRange, [-1, 1]);
+ assert.equal(ramp.steps, 'hard');
+ assert.equal(ramp.crestTint, undefined);
+});
+
+test('a water ramp keeps drivers, steps and the crest tint', () => {
+ const ramp = rampOf({ colors: COLORS, drivers: { height: 0.7, sun: 0.3 }, heightRange: [-2, 3], steps: 'soft', crestTint: { color: [0.7, 1, 0.9], strength: 0.5 } });
+ assert.deepEqual(ramp.drivers, { height: 0.7, facing: 0, sun: 0.3 });
+ assert.deepEqual(ramp.heightRange, [-2, 3]);
+ assert.equal(ramp.steps, 'soft');
+ assert.deepEqual(ramp.crestTint, { color: [0.7, 1, 0.9], strength: 0.5 });
+});
+
+test('the stored ramp is accepted again, so a render job can rebuild the scene from its snapshot', () => {
+ const first = rampOf({ colors: COLORS, drivers: { facing: 1 }, crestTint: { color: [1, 1, 1] } });
+ assert.deepEqual(rampOf(JSON.parse(JSON.stringify(first))), first);
+});
+
+test('a bad water ramp is refused with what to pass instead', () => {
+ assert.throws(() => rampOf({ colors: COLORS.slice(0, 2) }), /3 to 5 colours from deep to bright/);
+ assert.throws(() => rampOf({ colors: [...COLORS, ...COLORS] }), /3 to 5 colours/);
+ assert.throws(() => rampOf({ colors: COLORS, steps: 'smooth' }), /steps must be one of hard, soft/);
+ assert.throws(() => rampOf({ colors: COLORS, drivers: { depth: 1 } }), /no depth; pass weights for height, facing, sun/);
+ assert.throws(() => rampOf({ colors: COLORS, drivers: { height: 0 } }), /at least one above 0/);
+ assert.throws(() => rampOf({ colors: COLORS, heightRange: [2, 2] }), /low below high/);
+ assert.throws(() => rampOf({ colors: COLORS, crestTint: { strength: 0.5 } }), /crestTint must be/);
+ assert.throws(() => rampOf({ colors: COLORS, speed: 2 }), /no speed/);
+ assert.throws(() => rampOf({ colors: [[0, 0, -1], COLORS[1], COLORS[2]] }), /colors\[0\] must be three numbers from 0 to 16/);
+});
+
+test('a ramp needs the water tag', () => {
+ assert.throws(() => sceneWith({ waterRamp: { colors: COLORS } }), /waterRamp needs the water tag/);
+ assert.equal(sceneWith({ tag: 'water' }).parts[0].material.waterRamp, undefined);
+});
+
+test('the water shader draws the ramp over the sky reflection only when a ramp is bound', () => {
+ const shader = createFragmentShader(['water', 'vertexColors']);
+ assert.match(shader, /vec3 waterRampTone\(float height, float facing, float sun\)/);
+ assert.match(shader, /if \(waterRampHead\.x > 0\.5\)/);
+ assert.match(shader, /if \(waterRampOwns > 0\.5\) radiance = waterRampRadiance \* \(1\.0 - waterFoam\)/);
+});
+
+function recordingRenderer() {
+ const calls = [];
+ const names = ['uniform4f', 'uniform3f', 'uniform2f', 'uniform3fv', 'uniform1i', 'uniform1f'];
+ const context = { getUniformLocation: (program, name) => name, isEnabled: () => false, BLEND: 3042 };
+ for (const name of names) {
+ context[name] = (location, ...values) => calls.push([name, location, values.flatMap(value => (value?.length === undefined ? [value] : [...value]))]);
+ }
+ return { calls, renderer: { shaderFeatures: new Set(['water']), program: {}, context, batches: [] } };
+}
+
+function sentUniforms(material) {
+ const { calls, renderer } = recordingRenderer();
+ layerTextureSupport.bind(renderer, [], [], { parts: [{ material }] });
+ return Object.fromEntries(calls.filter(([, location]) => String(location).startsWith('waterRamp')).map(([, location, values]) => [location, values]));
+}
+
+test('a batch with a ramp sends it and a batch without one turns it off', () => {
+ const ramp = rampOf({ colors: COLORS, drivers: { height: 0.7, sun: 0.3 }, steps: 'soft', crestTint: { color: [0.5, 1, 0.5], strength: 0.4 } });
+ const sent = sentUniforms({ tag: 'water', waterRamp: ramp });
+ assert.deepEqual(sent.waterRampHead, [3, 1, 0, 0]);
+ assert.deepEqual(sent.waterRampWeights, [0.7, 0, 0.3]);
+ assert.deepEqual(sent.waterRampCrest, [0.5, 1, 0.5, 0.4]);
+ assert.deepEqual(sent.waterRampColors.slice(0, 9), COLORS.flat().map(Math.fround));
+ assert.deepEqual(sent.waterRampColors.slice(9), new Array(6).fill(0));
+ assert.deepEqual(sentUniforms({ tag: 'water' }).waterRampHead, [0, 0, 0, 0]);
+});