Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Shade moss as its own material and add near-ground parallax

Nguyen Xuan Ana03ba41715e0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dccce65d..f3f3f25b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,8 @@
- Break up grass fields with `patchiness` (short, thin and dense patches), seed `stalks` and folded blades, and let sunlight glow through backlit blades
- Add `67js/addons/clutter`: pebbles, chipped rocks with moss, twigs and fallen leaves scattered over terrain in streamed tiles, with four presets
- Share one tile and level-of-detail system between grass and clutter
+- Add a `moss` layer to standard materials: its own rough, sheened, light-wrapping material with a sharp shading mask and a blurred cushion mask; clutter rocks use it
+- Add splat `parallax` (default 0.03 m) for near-ground relief from the layer height maps
- Add splat `variation` (brightness and hue drift at three scales that grows with distance) and `edgeNoise` (ragged layer borders), both on by default
## 0.10.0
diff --git a/docs/clutter.md b/docs/clutter.md
index d2aced2d..54d92f7d 100644
--- a/docs/clutter.md
+++ b/docs/clutter.md
@@ -24,10 +24,11 @@ if (clutter.update(eye)) renderer.replaceParts([...terrain.parts, ...grass.parts
- A stone is a sphere displaced by smooth noise. Rocks are also cut by four random planes, which gives them flat, chipped faces. Pebbles stay round.
- A stone sinks a third to a half of its height into the ground and tilts with the terrain.
-- Vertex colours give each stone its own tone and hue, from blue-grey to rust. Blotches follow the stone's own space. The underside is darker, soil clings near the ground line, and rocks gather moss on top.
+- Vertex colours give each stone its own tone and hue, from blue-grey to rust. Blotches follow the stone's own space. The underside is darker and soil clings near the ground line.
+- Rocks carry the renderer's [moss layer](/material-maps.md): rough, sheened cushions on their tops, shaded as moss rather than painted on. Pebbles stay bare.
- Twigs are tapered tubes that lie on the ground and follow it. Leaves are small cupped strips in a palette of dry browns.
- Items gather into patches of about 7 m (`clumping`), so the ground does not read as an even sprinkle.
-- Everything is vertex-coloured and untextured. Each tile has at most two parts, stones and litter, and both stream through `renderer.replaceParts`.
+- Everything is vertex-coloured and untextured. Each tile has at most three parts, rocks, pebbles and litter, and all stream through `renderer.replaceParts`.
Clutter shows best on paths, clearings, riverbanks and forest floor. Under a dense meadow most of it hides in the grass. To fill a path, pass the inverse of the grass mask as the clutter `mask`.
@@ -41,7 +42,7 @@ Clutter shows best on paths, clearings, riverbanks and forest floor. Under a den
| `mask` | none | Coverage at `(x, z)` from 0 to 1. |
| `pebbles`, `rocks`, `twigs`, `leaves` | from preset | Items per square metre. |
| `pebbleSize`, `rockSize` | `[0.012, 0.05]`, `[0.08, 0.38]` | Radius range in metres. Most stones fall near the small end. |
-| `moss` | from preset | Moss on rock tops, 0 to 1. |
+| `moss` | from preset | Moss cover on rocks, 0 to 1. It sets the rock material's `moss`. |
| `clumping` | `0.6` | How strongly items gather into patches, 0 to 1. |
| `stoneColor`, `mossColor`, `soilColor`, `twigColor` | earth tones | Linear RGB. |
| `leafColors` | four dry browns | A list of linear RGB colours. Each leaf picks one. |
diff --git a/docs/material-maps.md b/docs/material-maps.md
index 3c28460b..3fedb43f 100644
--- a/docs/material-maps.md
+++ b/docs/material-maps.md
@@ -55,7 +55,7 @@ Descriptor identity determines GPU texture reuse. Repeated parts can share descr
Different descriptors allocate separately even when they reference the same decoded image.
Every channel and its mipmaps contributes to `textureBytes` and the render memory plan.
-A batch groups geometry identity, all five map identities, `normalScale` values, and `occlusionStrength`.
+A batch groups geometry identity, all five map identities, `normalScale` values, `occlusionStrength`, `moss` and `mossColor`.
The renderer uses batch uniforms for scale and strength because its instance attributes already occupy 16 vertex locations.
Changing any of these batch fields requires a new renderer. `updateParts()` rejects changes before uploading instance data.
Color, metallic, roughness, emission, emissive color, and transforms retain their existing update behavior.
@@ -97,6 +97,16 @@ Final alpha is the base map alpha (when `material.map` is set) times `opacity`.
glTF import maps `alphaMode` MASK and BLEND, `alphaCutoff`, `doubleSided` and `baseColorFactor[3]` (to `opacity`) onto these fields, and keeps the base color texture alpha. `exportGlb` writes them back.
+## Moss layer
+
+A standard-tag material can grow moss: `moss` (0 to 1, default 0) sets how much of the up-facing surface it covers, and `mossColor` (linear RGB, default `[0.05, 0.085, 0.02]`) its colour.
+
+```js
+const rock = { color: [0.3, 0.29, 0.27], roughness: 0.85, moss: 0.6 };
+```
+
+Moss is shaded as its own material, not as a tint. Where it grows, roughness becomes 1 and metal 0, a soft sheen shows at grazing angles, and sunlight wraps through it. Two masks decide it: a sharp one for where moss is shaded, and a blurred one that lifts it into small cushions, so its relief never turns into needles. Coverage follows world position, so moss slides across an object that moves. Use it on static parts. Moss works with or without maps, costs nothing on materials without it, and is part of the batch state: parts with different `moss` or `mossColor` draw separately, and changing either needs a new renderer. Procedural tags reject it.
+
## Splat layers
A standard-tag material can carry `layers` (up to four `{ color, normal, roughness, height, scale, tint, triplanar }` entries built from `loadTextureSet`) and a `splat` rule object instead of these single maps. The layers are blended by slope, height and a weight mask, sampled in world space and packed into texture arrays on units 11 to 14. They replace `map`, `normalMap`, `metallicRoughnessMap` and `occlusionMap`, which must be absent, and parts batch only when `layers` and `splat` are the same objects. See [Terrain](/terrain.md).
diff --git a/docs/terrain.md b/docs/terrain.md
index f11acd69..cea24596 100644
--- a/docs/terrain.md
+++ b/docs/terrain.md
@@ -67,6 +67,8 @@ Other `splat` options: `heightBlend` (0.22) and `heightInfluence` (1) control ho
Two options keep large ground from looking flat. `variation` (0 to 2, default 1) drifts brightness and hue at three scales, about 120 m, 20 m and 3 m, with dry and lush patches. The 3 m octave grows with distance, where texture detail averages out. `edgeNoise` (0 to 2, default 1) jitters the slope and height that the rules see, by up to 9 degrees and 1.6 m, so a mud flat or a rock band gets a ragged border instead of a contour line. Set either to 0 to turn it off.
+`parallax` (0 to 0.15 m, default 0.03) gives near ground relief: the top-down texture slides along each layer's height map toward where the view ray meets it, refined in three steps. It runs only on pixels close to the camera and is capped, because deep parallax stretches the height map into spikes at grazing angles. At the default it measured within noise of off (about 10.5 ms a frame either way, 1280 × 720, RTX 3060). It reads best in motion and from above; at a grazing eye height it mostly flattens the texture. Set it to 0 to turn it off.
+
Shading: world-space XZ UVs, a second rotated sample at 0.58 times the scale mixed by low-frequency noise (with contrast restored) so repetition is not visible from afar, normal tilts added in world space, roughness from the maps, and a slow macro brightness and dryness variation.
Materials batch together only when they share the same `layers` array and `splat` object, so build them once and assign them to every chunk.
diff --git a/src/clutter.js b/src/clutter.js
index e9888ec9..da40a57c 100644
--- a/src/clutter.js
+++ b/src/clutter.js
@@ -1,6 +1,7 @@
// Ground clutter: pebbles, rocks, twigs and fallen leaves scattered over terrain in streamable tiles.
// Stones are noise-displaced spheres cut by a few random planes, so rocks get flat chipped faces while pebbles stay
-// round. They sink into the ground, darken underneath and near the soil line, and rocks gather moss on top.
+// round. They sink into the ground and darken underneath and near the soil line. Rocks carry the renderer's moss layer
+// (its own rough, sheened material with cushion relief), so moss is shaded as moss rather than painted on.
// Everything is vertex-coloured and untextured, so tiles stream with `renderer.replaceParts`.
import {
@@ -121,8 +122,6 @@ function stoneColor(normal, localPoint, heightAboveGround, stone, vertexIndex, s
const blotch = valueNoise(localPoint[0] * stone.grain + localPoint[1] * 0.7 * stone.grain, localPoint[2] * stone.grain, stone.colorSeed);
const stain = lerp(0.6, 1.25, blotch);
let color = stone.base.map(channel => channel * underside * speckle * stain);
- const moss = stone.moss * smoothstep(0.35, 0.85, normal[1]) * smoothstep(0.3, 0.6, valueNoise(normal[0] * 3 + stone.phases[0], normal[2] * 3, stone.colorSeed));
- color = lerpVectors(color, settings.mossColor, moss);
// Soil clings to the stone where it meets the ground.
const soil = 1 - smoothstep(0, stone.height * 0.35, heightAboveGround);
return lerpVectors(color, settings.soilColor, soil * 0.7);
@@ -140,7 +139,6 @@ function addStone(builder, item, tileOrigin, settings, detail) {
roughness: isRock ? 0.16 : 0.08,
phases: [random() * FULL_TURN, random() * FULL_TURN, random() * FULL_TURN, random() * FULL_TURN],
planes: [],
- moss: isRock ? settings.moss : settings.moss * 0.2,
colorSeed: hashTile(settings.seed + 17, Math.floor(item.x * 977), Math.floor(item.z * 977)),
height: radius * lerp(0.45, 0.75, rolls[1]),
};
@@ -316,7 +314,8 @@ function resolveSettings(options) {
export function createClutter(options = {}) {
const settings = resolveSettings(options);
const materials = {
- stone: { color: [1, 1, 1], roughness: 0.88, metallic: 0, emission: 0 },
+ rock: { color: [1, 1, 1], roughness: 0.88, metallic: 0, emission: 0, moss: settings.moss, mossColor: settings.mossColor },
+ pebble: { color: [1, 1, 1], roughness: 0.8, metallic: 0, emission: 0 },
litter: { color: [1, 1, 1], roughness: 0.8, metallic: 0, emission: 0, doubleSided: true },
};
@@ -324,17 +323,20 @@ export function createClutter(options = {}) {
const level = settings.levels[levelIndex];
tile.cache.items ??= planTileItems(tile, settings);
const tileOrigin = [tile.tileX, tile.tileZ];
- const stones = createMeshBuilder({ withColors: true });
+ const rocks = createMeshBuilder({ withColors: true });
+ const pebbles = createMeshBuilder({ withColors: true });
const litter = createMeshBuilder({ withColors: true });
for (const item of tile.cache.items) {
if (item.keepKey >= level.keep) continue;
- if (item.kind === 'pebbles' || item.kind === 'rocks') addStone(stones, item, tileOrigin, settings, level.detail);
+ if (item.kind === 'rocks') addStone(rocks, item, tileOrigin, settings, level.detail);
+ else if (item.kind === 'pebbles') addStone(pebbles, item, tileOrigin, settings, level.detail);
else if (item.kind === 'twigs') addTwig(litter, item, tileOrigin, settings, level.detail);
else addLeaf(litter, item, tileOrigin, settings, level.detail);
}
const parts = [];
const matrix = tileMatrix(tile);
- if (stones.vertexCount > 0) parts.push({ name: `Clutter stones ${tile.column},${tile.row}`, geometry: stones.build(), matrix, material: materials.stone, castShadow: settings.castShadow });
+ if (rocks.vertexCount > 0) parts.push({ name: `Clutter rocks ${tile.column},${tile.row}`, geometry: rocks.build(), matrix, material: materials.rock, castShadow: settings.castShadow });
+ if (pebbles.vertexCount > 0) parts.push({ name: `Clutter pebbles ${tile.column},${tile.row}`, geometry: pebbles.build(), matrix, material: materials.pebble, castShadow: settings.castShadow });
if (litter.vertexCount > 0) parts.push({ name: `Clutter litter ${tile.column},${tile.row}`, geometry: litter.build(), matrix, material: materials.litter, castShadow: false });
return parts;
}
diff --git a/src/renderer.js b/src/renderer.js
index 2d68f36f..72c013ac 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -76,6 +76,22 @@ function validateMaterialMaps(material) {
if (normalScale.length !== 2 || !Number.isFinite(normalScale[0]) || !Number.isFinite(normalScale[1]) || !Number.isFinite(Math.fround(normalScale[0])) || !Number.isFinite(Math.fround(normalScale[1]))) throw new Error('normalScale must contain two finite floats.');
const occlusionStrength = material.occlusionStrength ?? 1;
if (!Number.isFinite(occlusionStrength) || occlusionStrength < 0 || occlusionStrength > 1) throw new Error('occlusionStrength must be within zero and one.');
+ validateMoss(material);
+}
+
+const DEFAULT_MOSS_COLOR = Object.freeze([0.05, 0.085, 0.02]);
+
+function validateMoss(material) {
+ if (material.moss === undefined) return;
+ if (typeof material.moss !== 'number' || !(material.moss >= 0 && material.moss <= 1)) throw new Error('moss must be within zero and one.');
+ if (material.moss > 0 && PROCEDURAL_MATERIAL_TAGS.has(material.tag)) throw new Error('Moss needs a standard PBR material tag.');
+ const color = material.mossColor ?? DEFAULT_MOSS_COLOR;
+ if (!Array.isArray(color) || color.length !== 3 || !color.every(Number.isFinite)) throw new Error('mossColor must be three linear RGB numbers.');
+}
+
+/** Moss amount and linear colour, as the shader's materialMoss uniform. */
+function mossState(material) {
+ return [material.moss ?? 0, ...(material.mossColor ?? DEFAULT_MOSS_COLOR)];
}
function materialMapState(material) {
@@ -84,7 +100,7 @@ function materialMapState(material) {
const occlusionStrength = material.occlusionStrength ?? 1;
validateSplatMaterial(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, ...splatBatchState(material)];
+ return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength, ...mossState(material), ...splatBatchState(material)];
}
function validateAlphaMaterial(material) {
@@ -388,7 +404,7 @@ export class Renderer67 {
this.inverseViewProjection = mat4.create();
this.program = compileProgram(this.context, benchmark ? benchmarkVertexShader : vertexShader, benchmark ? benchmarkFragmentShader : fragmentShader);
this.depthProgram = compileProgram(this.context, depthVertexShader, depthFragmentShader);
- this.uniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
+ this.uniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
for (const name of ['pointLightCount', 'pointLightPositions[0]', 'pointLightColors[0]', 'pointLightRadii[0]', 'keyColor', 'fillIntensity', 'ambientIntensity']) {
this.uniforms[name] = this.context.getUniformLocation(this.program, name);
}
@@ -845,7 +861,7 @@ export class Renderer67 {
for (let index = 0; index < MATERIAL_MAPS.length; index++) {
if ((part.material[MATERIAL_MAPS[index]] ?? null) !== mapState[index]) throw new Error(`Material map or scale changes require a new renderer: ${part.name}`);
}
- if (normalScale[0] !== mapState[5] || normalScale[1] !== mapState[6] || (part.material.occlusionStrength ?? 1) !== mapState[7]) throw new Error(`Material map or scale changes require a new renderer: ${part.name}`);
+ if (normalScale[0] !== mapState[5] || normalScale[1] !== mapState[6] || (part.material.occlusionStrength ?? 1) !== mapState[7] || mossState(part.material).some((value, index) => value !== mapState[8 + index])) throw new Error(`Material map or scale changes require a new renderer: ${part.name}`);
validateTransform(part, location.normalMatrix);
}
// A palette upload also changes consumers absent from the submitted part list.
@@ -1397,6 +1413,7 @@ export class Renderer67 {
}
this.context.uniform2f(this.uniforms.normalScale, batch.mapState[5], batch.mapState[6]);
this.context.uniform1f(this.uniforms.occlusionStrength, batch.mapState[7]);
+ this.context.uniform4f(this.uniforms.materialMoss, batch.mapState[8], batch.mapState[9], batch.mapState[10], batch.mapState[11]);
this.bindSplat(batch.splat);
}
this.context.bindVertexArray(batch.vertexArray);
diff --git a/src/shaders.js b/src/shaders.js
index ec7a2e38..45ce7db6 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -369,6 +369,7 @@ uniform float hasOcclusionMap;
uniform float hasEmissiveMap;
uniform vec2 normalScale;
uniform float occlusionStrength;
+uniform vec4 materialMoss;
uniform float hdrEnabled;
uniform float alphaMode;
uniform float alphaCutoff;
@@ -495,6 +496,18 @@ vec3 mappedNormal(vec3 normal) {
${splatGlsl}
+// Moss is its own material over the base, not a tint: fully rough, a soft sheen at grazing angles and light that wraps
+// through it. Two masks, as in offline moss shading: a sharp one decides where moss is shaded, and a blurred one lifts
+// it into cushions, so its relief never turns into needles. Coverage favours up-facing surfaces.
+void mossMasks(vec3 normal, float amount, out float sharpMask, out float softMask) {
+ float facing = smoothstep(0.1, 0.7, normal.y);
+ vec2 position = worldPosition.xz * 6.0 + worldPosition.y * vec2(2.3, -1.7);
+ float patches = terrainNoise(position).x * 0.6 + terrainNoise(position * 2.7 + 5.1).x * 0.4;
+ float threshold = 1.0 - amount;
+ sharpMask = facing * smoothstep(threshold - 0.035, threshold + 0.035, patches);
+ softMask = facing * smoothstep(threshold - 0.22, threshold + 0.18, patches);
+}
+
// Opaque draws 1, mask resolves to a cutout (smooth coverage with MSAA) and blend keeps the fraction.
float surfaceAlpha(float textureAlpha) {
if (alphaMode < 0.5) return 1.0;
@@ -580,6 +593,21 @@ void main() {
normal = normalize(normal + perturbation - normal * dot(perturbation, normal));
roughness = clamp(roughness + (grains.x - 0.5) * 0.06 * grainWeight, 0.075, 1.0);
}
+ float mossCover = 0.0;
+ vec3 mossTone = vec3(0.0);
+ if (materialMoss.x > 0.0) {
+ float mossSoft;
+ mossMasks(normal, materialMoss.x, mossCover, mossSoft);
+ float mossFootprint = length(fwidth(worldPosition));
+ vec3 cushion = terrainNoise(worldPosition.xz * 40.0 + worldPosition.y * 13.0);
+ float cushionDetail = 1.0 - smoothstep(0.004, 0.03, mossFootprint);
+ vec3 cushionTilt = vec3(-cushion.y, 0.0, -cushion.z) * 0.07 * mossSoft * cushionDetail;
+ normal = normalize(normal + cushionTilt - normal * dot(cushionTilt, normal));
+ mossTone = materialMoss.yzw * (0.7 + 0.6 * cushion.x);
+ color = mix(color, mossTone, mossCover);
+ roughness = mix(roughness, 1.0, mossCover);
+ metallic = mix(metallic, 0.0, mossCover);
+ }
float visibility = shadowVisibility(normal);
vec3 radiance = illuminate(normal, viewDirection, normalize(lightDirection), keyColor * visibility, color, metallic, roughness);
radiance += illuminate(normal, viewDirection, normalize(vec3(4.0, 2.0, -3.0)), mix(vec3(0.8, 2.0, 1.8), vec3(0.12, 0.17, 0.20) * daylight, worldMode) * fillIntensity, color, metallic, roughness);
@@ -620,6 +648,11 @@ void main() {
vec3 keyResponse = keyColor / mix(vec3(5.2, 4.7, 4.1), vec3(3.7, 3.4, 2.9), worldMode);
keyResponse *= mix(daylight, 1.0, worldMode);
if (surface.w == 4.0 || surface.w == 7.0) radiance += color * max(dot(-normal, normalize(lightDirection)), 0.0) * 0.3 * keyResponse;
+ if (mossCover > 0.001) {
+ float sheen = pow(1.0 - max(dot(normal, viewDirection), 0.0), 4.0);
+ float wrap = max(dot(normal, normalize(lightDirection)) + 0.5, 0.0) / 1.5;
+ radiance += mossTone * (sheen * 0.8 + wrap * 0.35) * keyResponse * visibility * mossCover;
+ }
if (surface.w == 7.0) {
// Sun through thin blades: they glow yellow-green when the camera looks toward the light, most at the thin tips
// (uv.y runs 1 at the root to 0 at the tip; grass without UVs gets a middle value).
diff --git a/src/splat-shader.js b/src/splat-shader.js
index 32e70400..2dd52332 100644
--- a/src/splat-shader.js
+++ b/src/splat-shader.js
@@ -99,6 +99,17 @@ vec3 splatNormalTwoScale(SplatPlane plane, float layer, float blend) {
return mixed;
}
+// Parallax with offset limiting: the top-down uv slides toward where the view ray meets the layer's height map, refined
+// in three steps. It only runs on pixels near the camera, where the relief is visible.
+vec2 splatParallaxOffset(SplatPlane top, float layer, vec2 viewSlope, float depthInUv) {
+ vec2 offset = vec2(0.0);
+ for (int refinement = 0; refinement < 3; refinement++) {
+ float height = textureGrad(splatPacked, vec3(top.uv + offset, layer), top.dx, top.dy).y;
+ offset = -viewSlope * depthInUv * (1.0 - height);
+ }
+ return offset;
+}
+
SplatPlane splatPlane(vec2 worldCoordinates, vec2 worldDx, vec2 worldDy, float scale, vec3 tangent, vec3 bitangent, vec3 face) {
return SplatPlane(worldCoordinates / scale, worldDx / scale, worldDy / scale, tangent, bitangent, face);
}
@@ -190,6 +201,10 @@ void applySplat(inout vec3 color, inout vec3 normal, inout float roughness, inou
vec2 sideShare = pow(abs(geometric.xz), vec2(4.0));
sideShare /= max(sideShare.x + sideShare.y, 0.0001);
+ vec3 toEye = normalize(eye - worldPosition);
+ vec2 viewSlope = toEye.xz / max(toEye.y, 0.35);
+ float parallaxFade = 1.0 - smoothstep(0.004, 0.03, length(fwidth(worldPosition.xz)));
+ vec2 topOffsets[4] = vec2[4](vec2(0.0), vec2(0.0), vec2(0.0), vec2(0.0));
vec2 packedSamples[4] = vec2[4](vec2(0.5), vec2(0.5), vec2(0.5), vec2(0.5));
vec3 projections[4] = vec3[4](vec3(0.0, 1.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 1.0, 0.0));
float scores[4] = float[4](-1.0, -1.0, -1.0, -1.0);
@@ -203,6 +218,9 @@ void applySplat(inout vec3 color, inout vec3 normal, inout float roughness, inou
SplatPlane top = splatPlane(topCoordinates, topDx, topDy, scale, topTangent, topBitangent, up);
SplatPlane sideX = splatPlane(sideXCoordinates, sideXDx, sideXDy, scale, sideXTangent, sideUp, vec3(xSign, 0.0, 0.0));
SplatPlane sideZ = splatPlane(sideZCoordinates, sideZDx, sideZDy, scale, sideZTangent, sideUp, vec3(0.0, 0.0, zSign));
+ float parallaxDepth = splatVariation.z * parallaxFade * projection.y / scale;
+ if (parallaxDepth > 0.0001) topOffsets[index] = splatParallaxOffset(top, float(index), viewSlope, parallaxDepth);
+ top.uv += topOffsets[index];
projections[index] = projection;
packedSamples[index] = splatPackedSample(index, top, sideX, sideZ, projection, blend);
scores[index] = weights[index] + packedSamples[index].y * splatBlend.y;
@@ -230,6 +248,7 @@ void applySplat(inout vec3 color, inout vec3 normal, inout float roughness, inou
SplatPlane top = splatPlane(topCoordinates, topDx, topDy, scale, topTangent, topBitangent, up);
SplatPlane sideX = splatPlane(sideXCoordinates, sideXDx, sideXDy, scale, sideXTangent, sideUp, vec3(xSign, 0.0, 0.0));
SplatPlane sideZ = splatPlane(sideZCoordinates, sideZDx, sideZDy, scale, sideZTangent, sideUp, vec3(0.0, 0.0, zSign));
+ top.uv += topOffsets[index];
vec3 layerColor;
vec3 layerTilt;
splatColorSample(index, top, sideX, sideZ, projections[index], blend, layerColor, layerTilt);
diff --git a/src/splat.js b/src/splat.js
index 5614ddcf..36b7e3f7 100644
--- a/src/splat.js
+++ b/src/splat.js
@@ -15,6 +15,7 @@ const DEFAULT_SPLAT = Object.freeze({
cavity: 0.55,
variation: 1,
edgeNoise: 1,
+ parallax: 0.03,
});
const DEFAULT_RULE_SOFTNESS = Object.freeze({ slope: 4, height: 1.5 });
@@ -93,6 +94,8 @@ export function validateSplatMaterial(material) {
}
if (splat.antiTiling > 1 || splat.cavity > 1) throw new RangeError('splat.antiTiling and splat.cavity must be at most 1.');
if (splat.variation > 2 || splat.edgeNoise > 2) throw new RangeError('splat.variation and splat.edgeNoise must be at most 2.');
+ // Deeper parallax stretches the height map into spikes at grazing angles, so it is capped.
+ if (splat.parallax !== undefined && !(requireFiniteNumber(splat.parallax, 'splat.parallax') >= 0 && splat.parallax <= 0.15)) throw new RangeError('splat.parallax must be between 0 and 0.15 metres.');
for (const field of ['triplanarStart', 'triplanarEnd']) {
if (splat[field] !== undefined) requireRange([splat[field], splat[field]], `splat.${field}`, 0, 90);
}
@@ -150,7 +153,7 @@ export function packSplatParameters(material) {
blend: new Float32Array([splat.heightBlend, splat.heightInfluence, splat.triplanarStart, splat.triplanarEnd]),
options: new Float32Array([splat.antiTiling, splat.maskMap ? 1 : 0, layerCount, splat.cavity]),
maskBounds: new Float32Array(splat.maskBounds ?? [0, 0, 1, 1]),
- variation: new Float32Array([splat.variation, splat.edgeNoise, 0, 0]),
+ variation: new Float32Array([splat.variation, splat.edgeNoise, splat.parallax, 0]),
};
material.layers.forEach((layer, index) => writeRule(material.splat?.rules?.[index], index, parameters, layer));
return parameters;
diff --git a/tests/clutter.test.js b/tests/clutter.test.js
index ee49c979..6e69d132 100644
--- a/tests/clutter.test.js
+++ b/tests/clutter.test.js
@@ -30,7 +30,7 @@ test('the same options and seed build identical clutter', () => {
test('stones face outward and stand on the ground they sink into', () => {
const terrainHeight = (x, z) => 1 + x * 0.05 + Math.sin(z);
const clutter = createClutter({ ...near, preset: 'scree', twigs: 0, leaves: 0, terrainHeight });
- const stones = clutter.parts.filter(part => part.name.startsWith('Clutter stones'));
+ const stones = clutter.parts.filter(part => part.name.match(/^Clutter (rocks|pebbles)/));
assert.ok(stones.length > 0);
for (const part of stones) {
assert.ok(triangleFacesAgreeWithNormals(part.geometry), 'winding and normals agree, so stones are not inside out');
diff --git a/tests/morph-renderer.test.js b/tests/morph-renderer.test.js
index e1727016..a19bde9e 100644
--- a/tests/morph-renderer.test.js
+++ b/tests/morph-renderer.test.js
@@ -40,7 +40,7 @@ function retainedRenderer(parts) {
group.forEach((part, index) => renderer.partLocations.set(part, {
batch, index, geometry: part.geometry, morph: part.morph,
morphWeights: part.morph.weights, morphTargets: part.geometry.morphTargets,
- skin: null, map: null, mapState: [null, null, null, null, null, 1, 1, 1],
+ skin: null, map: null, mapState: [null, null, null, null, null, 1, 1, 1, 0, 0.05, 0.085, 0.02],
normalMatrix: mat3.create(),
}));
return batch;
diff --git a/tests/renderer.test.js b/tests/renderer.test.js
index 1eff848e..c770c332 100644
--- a/tests/renderer.test.js
+++ b/tests/renderer.test.js
@@ -16,7 +16,7 @@ function retainedRenderer(parts) {
renderer.partLocations = new Map(parts.map((item, index) => [item, {
batch, index, geometry: item.geometry, map: item.material.map ?? null, normalMatrix: mat3.create(), skin: item.skin ?? null,
jointMatrices: item.skin?.jointMatrices, skinIndices: item.geometry.skinIndices, skinWeights: item.geometry.skinWeights,
- mapState: ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'].map(field => item.material[field] ?? null).concat(item.material.normalScale ?? [1, 1], item.material.occlusionStrength ?? 1),
+ mapState: ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'].map(field => item.material[field] ?? null).concat(item.material.normalScale ?? [1, 1], item.material.occlusionStrength ?? 1, item.material.moss ?? 0, item.material.mossColor ?? [0.05, 0.085, 0.02]),
}]));
renderer.updateBatches = new Set();
renderer.updateSkins = new Set();
@@ -233,17 +233,24 @@ test('all material map identities and fixed scale values partition instance batc
});
test('map and scale changes reject atomically before retained data uploads', () => {
- for (const field of ['normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap', 'normalScale', 'occlusionStrength']) {
+ for (const field of ['normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap', 'normalScale', 'occlusionStrength', 'moss']) {
const parts = [part('moving'), part('changed')];
const { renderer, batch, writes } = retainedRenderer(parts);
parts[0].matrix[12] = 4;
- parts[1].material[field] = field === 'normalScale' ? [0.5, 1] : field === 'occlusionStrength' ? 0.2 : {};
+ const changedValues = { normalScale: [0.5, 1], occlusionStrength: 0.2, moss: 0.5 };
+ parts[1].material[field] = changedValues[field] ?? {};
assert.throws(() => renderer.updateParts(parts), /map or scale changes/);
assert.ok(batch.instanceData.every(value => value === 7));
assert.equal(writes.length, 0);
}
assert.throws(() => groupParts([{ ...part('invalid'), material: { ...part('invalid').material, normalScale: [Infinity, 1] } }]), /normalScale/);
assert.throws(() => groupParts([{ ...part('invalid'), material: { ...part('invalid').material, occlusionStrength: 2 } }]), /occlusionStrength/);
+ assert.throws(() => groupParts([{ ...part('invalid'), material: { ...part('invalid').material, moss: 1.5 } }]), /moss/);
+ assert.throws(() => groupParts([{ ...part('invalid'), material: { ...part('invalid').material, moss: 0.5, mossColor: [1, 1] } }]), /mossColor/);
+ assert.throws(() => groupParts([{ ...part('invalid'), material: { ...part('invalid').material, tag: 'water', moss: 0.5 } }]), /Moss needs a standard/);
+ const mossy = part('mossy');
+ mossy.material.moss = 0.6;
+ assert.equal(groupParts([part('bare'), mossy]).length, 2, 'moss splits batches');
const procedural = part('procedural');
procedural.material.tag = 'water';
procedural.material.metallicRoughnessMap = {};
@@ -319,20 +326,22 @@ test('draw batches bind all channels with their flags and scalar uniforms', () =
const renderer = Object.create(Renderer67.prototype);
const bindings = [];
const uniforms = [];
- renderer.uniforms = Object.fromEntries(['baseMap', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap', 'hasBaseMap', 'hasNormalMap', 'hasMetallicRoughnessMap', 'hasOcclusionMap', 'hasEmissiveMap', 'normalScale', 'occlusionStrength'].map(name => [name, name]));
+ renderer.uniforms = Object.fromEntries(['baseMap', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap', 'hasBaseMap', 'hasNormalMap', 'hasMetallicRoughnessMap', 'hasOcclusionMap', 'hasEmissiveMap', 'normalScale', 'occlusionStrength', 'materialMoss'].map(name => [name, name]));
renderer.context = {
TEXTURE0: 33984,
activeTexture(unit) { bindings.push(unit); }, bindTexture() {}, bindVertexArray() {}, drawElementsInstanced() {},
uniform1i(name, value) { uniforms.push([name, value]); },
uniform1f(name, value) { uniforms.push([name, value]); },
uniform2f(name, first, second) { uniforms.push([name, first, second]); },
+ uniform4f(name, ...values) { uniforms.push([name, ...values]); },
};
- renderer.drawBatch({ textures: [{}, {}, {}, {}, {}], mapState: [{}, {}, {}, null, {}, 0.5, -1, 0.4] }, true);
+ renderer.drawBatch({ textures: [{}, {}, {}, {}, {}], mapState: [{}, {}, {}, null, {}, 0.5, -1, 0.4, 0.6, 0.1, 0.2, 0.05] }, true);
assert.deepEqual(bindings, [33985, 33986, 33987, 33988, 33989]);
assert.ok(uniforms.some(values => values[0] === 'hasOcclusionMap' && values[1] === 0));
assert.ok(uniforms.some(values => values[0] === 'metallicRoughnessMap' && values[1] === 3));
assert.ok(uniforms.some(values => values[0] === 'normalScale' && values[1] === 0.5 && values[2] === -1));
assert.ok(uniforms.some(values => values[0] === 'occlusionStrength' && values[1] === 0.4));
+ assert.ok(uniforms.some(values => values[0] === 'materialMoss' && values[1] === 0.6 && values[4] === 0.05));
});
function skinGeometry(vertexCount = 3) {
diff --git a/tests/splat.test.js b/tests/splat.test.js
index fc437e34..5953df71 100644
--- a/tests/splat.test.js
+++ b/tests/splat.test.js
@@ -63,8 +63,9 @@ test('packs per-layer rules for the shader', () => {
});
test('variation and edge noise default on, can be switched off and are bounded', () => {
- assert.deepEqual([...packSplatParameters({ layers: [layer()] }).variation], [1, 1, 0, 0]);
- assert.deepEqual([...packSplatParameters({ layers: [layer()], splat: { variation: 0, edgeNoise: 0.5 } }).variation], [0, 0.5, 0, 0]);
+ assert.deepEqual([...packSplatParameters({ layers: [layer()] }).variation], [1, 1, Math.fround(0.03), 0]);
+ assert.deepEqual([...packSplatParameters({ layers: [layer()], splat: { variation: 0, edgeNoise: 0.5, parallax: 0 } }).variation], [0, 0.5, 0, 0]);
+ assert.throws(() => validateSplatMaterial({ layers: [layer()], splat: { parallax: 0.4 } }), /parallax/);
assert.throws(() => validateSplatMaterial({ layers: [layer()], splat: { variation: 3 } }), /at most 2/);
assert.throws(() => validateSplatMaterial({ layers: [layer()], splat: { edgeNoise: -1 } }), /negative/);
});
@@ -74,6 +75,7 @@ test('the splat shader drifts colour at several scales and jitters rule edges',
assert.match(splatGlsl, /vec3 splatVariationTint\(float footprint\)/);
assert.match(splatGlsl, /ruleSlope = slope \+ edgeJitter/);
assert.match(splatGlsl, /splatRange\(ruleHeight,/);
+ assert.match(splatGlsl, /topOffsets\[index\] = splatParallaxOffset\(top, float\(index\), viewSlope, parallaxDepth\)/, 'near pixels slide along the height map');
});
test('resizes layers to a common size and counts the texture bytes', () => {