scene: terrain steep faces without streaks, smoother normals and silhouettes

- albedo wobble, grain and strata are triplanar (weights |n|^4 over yz, xz, xy), so a cliff is not the floor pattern smeared down it
- normals from bilinear height at a continuous position, stencil 1.5 texels each side
- the grid is packed toward the camera at the patch centre (warpUv), 192 low / 256 full, vertex heights bilinear: near ridge silhouettes no longer step in 23 m blocks

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Nibu 2026-11-08 18:10:21 +00:00
commit 685abbb19b
5 changed files with 162 additions and 57 deletions

View file

@ -1,7 +1,15 @@
/* eslint-disable no-restricted-syntax -- tests loop over skies, heights and slopes */
import { describe, expect, it } from 'vitest';
import { SKY } from './terrainSky';
import { ALBEDO, albedoAt, albedoPalette, grainAt, wobble } from './terrainAlbedo';
import {
ALBEDO,
albedoAt,
albedoPalette,
grainAt,
triWeights,
wobble,
wobbleAt,
} from './terrainAlbedo';
import { GRID_FRAG } from './terrainShaders';
const near = (a: readonly number[], b: readonly number[], eps = 1e-6) =>
@ -9,8 +17,10 @@ const near = (a: readonly number[], b: readonly number[], eps = 1e-6) =>
const luma = (c: readonly number[]) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
// A point where the wobble is zero, so band edges sit exactly where the palette says.
const FLAT_X = Math.PI / 0.043;
// A normal for the xz plane alone (all the weight on it), carrying `ny` for the slope bands.
const facing = (ny: number) => [0, ny, 0] as const;
const at = (sky: keyof typeof SKY, h: number, ny: number) =>
albedoAt(albedoPalette(SKY[sky]), h, ny, FLAT_X, 0);
albedoAt(albedoPalette(SKY[sky]), h, facing(ny), FLAT_X, 0);
describe('albedo by slope and height', () => {
it('the test point really has no wobble', () => {
@ -50,7 +60,7 @@ describe('albedo by slope and height', () => {
for (const sky of ['midnight', 'noonday'] as const)
for (let h = -20; h < 300; h += 7)
for (let ny = 0; ny <= 1; ny += 0.1)
for (const v of albedoAt(albedoPalette(SKY[sky]), h, ny, h * 3, ny * 91)) {
for (const v of albedoAt(albedoPalette(SKY[sky]), h, facing(ny), h * 3, ny * 91)) {
expect(v).toBeGreaterThanOrEqual(0);
expect(v).toBeLessThanOrEqual(1);
}
@ -105,9 +115,14 @@ describe('shader agrees with the pure function on its numbers', () => {
});
});
const UP = [0, 1, 0] as const;
const EAST = [1, 0, 0] as const;
describe('grain', () => {
const samples = (rock: number, distance: number) =>
Array.from({ length: 400 }, (_, i) => grainAt(i * 1.7, i * 0.9, 100 + i * 0.3, rock, distance));
Array.from({ length: 400 }, (_, i) =>
grainAt(i * 1.7, 100 + i * 0.3, i * 0.9, UP, rock, distance)
);
const spread = (v: number[]) => Math.max(...v) - Math.min(...v);
it('varies the surface near the eye, never goes negative, and averages about 1', () => {
@ -119,14 +134,41 @@ describe('grain', () => {
it('drops its fine octave with distance, so far ground does not shimmer', () => {
const rangeOf = (d: number) =>
spread(Array.from({ length: 400 }, (_, i) => grainAt(i * 0.37, i * 0.21, 100, 0, d)));
spread(Array.from({ length: 400 }, (_, i) => grainAt(i * 0.37, 100, i * 0.21, UP, 0, d)));
expect(rangeOf(900)).toBeLessThan(rangeOf(50));
});
it('layers the rock: strata show only where the face is rock', () => {
const height = (rock: number) =>
spread(Array.from({ length: 400 }, (_, i) => grainAt(0, 0, 100 + i * 0.05, rock, 2000)));
spread(Array.from({ length: 400 }, (_, i) => grainAt(0, 100 + i * 0.05, 0, UP, rock, 2000)));
expect(height(1)).toBeGreaterThan(0.2);
expect(height(0)).toBeLessThan(1e-9);
});
});
describe('triplanar projection', () => {
it('weights sum to 1 and go to the plane the face looks along', () => {
for (const n of [UP, EAST, [0.6, 0.6, 0.529], [0, 0, 1]] as const) {
const w = triWeights(n);
expect(w[0] + w[1] + w[2]).toBeCloseTo(1, 9);
}
expect(triWeights(UP)).toEqual([0, 1, 0]);
expect(triWeights(EAST)).toEqual([1, 0, 0]);
expect(triWeights([0.8, 0.5, 0.33])[0]).toBeGreaterThan(0.7);
});
it('a cliff facing east takes its pattern over (z, y), so it varies with height and not with x: no vertical smear', () => {
const col = (x: number, y: number) => grainAt(x, y, 40, EAST, 0, 50);
const alongY = Array.from({ length: 200 }, (_, i) => col(10, 50 + i * 0.7));
const alongX = Array.from({ length: 200 }, (_, i) => col(i * 0.7, 50));
expect(Math.max(...alongY) - Math.min(...alongY)).toBeGreaterThan(0.3);
expect(Math.max(...alongX) - Math.min(...alongX)).toBeLessThan(1e-9);
expect(wobbleAt(5, 80, 40, EAST)).toBeCloseTo(wobbleAt(500, 80, 40, EAST), 12);
expect(wobbleAt(5, 80, 40, EAST)).not.toBeCloseTo(wobbleAt(5, 120, 40, EAST), 3);
});
it('level ground takes its pattern over (x, z) alone, as before', () => {
expect(grainAt(12, 10, 30, UP, 0, 50)).toBeCloseTo(grainAt(12, 900, 30, UP, 0, 50), 12);
expect(wobbleAt(12, 10, 30, UP)).toBeCloseTo(wobble(12, 30), 12);
});
});

View file

@ -79,19 +79,36 @@ export function albedoPalette(d: SkyData): AlbedoPalette {
};
}
/** Cheap two-sine value in -1..1 from world position; stands in for noise so no texture or hash is read. */
/** Cheap two-sine value in -1..1 from a 2D world position; stands in for noise so no texture or hash is read. */
export const wobble = (x: number, z: number): number =>
Math.sin(x * 0.043 + z * 0.017) * Math.sin(z * 0.051 - x * 0.023);
/**
* Linear albedo at a surface point. `height` in metres, `ny` the unit normal's y, `x`/`z` world metres.
* How much each axis-aligned projection plane counts at a surface with unit normal `n`: weights for (yz, xz, xy), summing
* to 1, sharply favouring the plane the face looks along. Procedural patterns are evaluated on all three and blended by
* these (triplanar), so a cliff is not the floor pattern smeared down it.
*/
export function triWeights(n: Vec3): Vec3 {
const w = n.map((c) => Math.abs(c) ** 4);
const sum = w[0] + w[1] + w[2] || 1;
return [w[0] / sum, w[1] / sum, w[2] / sum];
}
/** `wobble` blended over the three projection planes, at a surface point with unit normal `n`. */
export function wobbleAt(x: number, y: number, z: number, n: Vec3): number {
const w = triWeights(n);
return w[0] * wobble(z, y) + w[1] * wobble(x, z) + w[2] * wobble(x, y);
}
/**
* Linear albedo at a surface point. `y` the height in metres, `n` the unit normal, `x`/`z` world metres.
* Rock takes the steep faces at any height; on the rest, soil to scree by height, then snow above the snow
* line, thinning to nothing as the face steepens.
*/
export function albedoAt(p: AlbedoPalette, height: number, ny: number, x: number, z: number): Vec3 {
const w = wobble(x, z);
const h = height + ALBEDO.wobbleHeight * w;
const flat = ny + ALBEDO.wobbleSlope * w;
export function albedoAt(p: AlbedoPalette, y: number, n: Vec3, x: number, z: number): Vec3 {
const w = wobbleAt(x, y, z, n);
const h = y + ALBEDO.wobbleHeight * w;
const flat = n[1] + ALBEDO.wobbleSlope * w;
const ground = (i: number) =>
mix(p.soil[i], p.scree[i], smooth(ALBEDO.screeFrom, ALBEDO.screeTo, h));
const snow =
@ -103,33 +120,39 @@ export function albedoAt(p: AlbedoPalette, height: number, ny: number, x: number
) as unknown as Vec3;
}
const COARSE = [
[0.31, 0.27],
[-0.22, 0.35],
[0.38, -0.12],
] as const;
const FINE = [
[1.1, 0.7],
[-0.8, 1.2],
[1.3, -0.6],
] as const;
const waves = (k: ReadonlyArray<readonly [number, number]>, a: number, b: number) =>
k.reduce((sum, [ka, kb]) => sum + Math.sin(a * ka + b * kb), 0) / 3;
/**
* The multiplier on albedo that gives the surface grain and the rock its layers, from world position (metres),
* height, `rock` (0..1, how much of the face is rock) and the distance from the eye. The shader's `ALB_GRAIN_*` block does the same arithmetic.
* The cavity term beside it in the shader reads the height map and has no twin here.
* The multiplier on albedo that gives the surface grain and the rock its layers, at a surface point (metres) with unit
* normal `n`, `rock` (0..1, how much of the face is rock) and the distance from the eye. Grain is triplanar like the
* wobble. The shader's `ALB_GRAIN_*` block does the same arithmetic. The cavity term beside it in the shader reads the
* height map and has no twin here.
*/
export function grainAt(
x: number,
y: number,
z: number,
height: number,
n: Vec3,
rock: number,
distance: number
): number {
const waves = (k: ReadonlyArray<readonly [number, number]>) =>
k.reduce((sum, [kx, kz]) => sum + Math.sin(x * kx + z * kz), 0) / 3;
const coarse = waves([
[0.31, 0.27],
[-0.22, 0.35],
[0.38, -0.12],
]);
const fine =
waves([
[1.1, 0.7],
[-0.8, 1.2],
[1.3, -0.6],
]) *
(1 - smooth(ALBEDO.fineNear, ALBEDO.fineFar, distance));
const layers = Math.sin(height * 0.9 + wobble(x, z) * 3);
const w = triWeights(n);
const over = (k: ReadonlyArray<readonly [number, number]>) =>
w[0] * waves(k, z, y) + w[1] * waves(k, x, z) + w[2] * waves(k, x, y);
const coarse = over(COARSE);
const fine = over(FINE) * (1 - smooth(ALBEDO.fineNear, ALBEDO.fineFar, distance));
const layers = Math.sin(y * 0.9 + wobbleAt(x, y, z, n) * 3);
return Math.max(
0,
1 + ALBEDO.grainCoarse * coarse + ALBEDO.grainFine * fine + ALBEDO.strata * rock * layers

View file

@ -90,6 +90,12 @@ float hAt(ivec2 t) {
return (floor(s.r * 255.0 + 0.5) * 256.0 + floor(s.g * 255.0 + 0.5)) / 65535.0 * ${f1(
TERRAIN.hmax
)};
}
// The height at a point in texel units, bilinear over the four texels around it (the packed texture cannot be filtered by the GPU).
float hBil(vec2 p) {
ivec2 i = ivec2(floor(p));
vec2 f = fract(p);
return mix(mix(hAt(i), hAt(i + ivec2(1, 0)), f.x), mix(hAt(i + ivec2(0, 1)), hAt(i + ivec2(1, 1)), f.x), f.y);
}`;
export const GRID_VERT = `${HEADER}
@ -100,12 +106,14 @@ out vec2 v_uv;
out vec3 v_world;
${FETCH}
void main() {
ivec2 t = ivec2(a_uv * float(uTex - 1) + 0.5);
// The grid is packed toward the centre, where the camera stands (terrainWorld.warpUv): s = 2u - 1, 0.5 + 0.5 (0.5 s + 0.5 s |s|).
vec2 s = a_uv * 2.0 - 1.0;
vec2 uv = 0.5 + 0.5 * (0.5 * s + 0.5 * s * abs(s));
// The patch's rim sinks to zero so the grid has no cliff edge to show through the haze.
float rim = 1.0 - smoothstep(0.78, 1.0, 2.0 * max(abs(a_uv.x - 0.5), abs(a_uv.y - 0.5)));
float h = hAt(t) * rim;
v_uv = a_uv;
v_world = vec3((a_uv.x - 0.5) * uSpan, h, (a_uv.y - 0.5) * uSpan);
float rim = 1.0 - smoothstep(0.78, 1.0, 2.0 * max(abs(uv.x - 0.5), abs(uv.y - 0.5)));
float h = hBil(uv * float(uTex - 1)) * rim;
v_uv = uv;
v_world = vec3((uv.x - 0.5) * uSpan, h, (uv.y - 0.5) * uSpan);
gl_Position = uViewProj * vec4(v_world, 1.0);
}`;
@ -145,23 +153,21 @@ uniform vec3 uCamera, uLightDir, uLight, uAmbient, uSoil, uScree, uRock, uSnow;
uniform float uSpan, uHazeK, uSnowLine;
out vec4 o;
${FETCH}
// Unnormalised normal at one texel, central differences over its neighbours.
vec3 nAt(ivec2 t, float texel) {
float dx = hAt(t + ivec2(1, 0)) - hAt(t - ivec2(1, 0));
float dz = hAt(t + ivec2(0, 1)) - hAt(t - ivec2(0, 1));
return normalize(vec3(-dx, 2.0 * texel, -dz));
}
// Triplanar patterns: each projection plane's value, blended by the weights of the face's normal (terrainAlbedo.triWeights).
float wob2(vec2 q) { return sin(q.x * 0.043 + q.y * 0.017) * sin(q.y * 0.051 - q.x * 0.023); }
float waves3(vec2 q, vec2 a, vec2 b, vec2 c) { return (sin(dot(q, a)) + sin(dot(q, b)) + sin(dot(q, c))) / 3.0; }
void main() {
// The four texels around this fragment, blended, so the shading is continuous and not one flat square per texel.
// Normal from the bilinear height at a continuous position, a stencil 1.5 texels each side: smooth across texel borders.
vec2 p = v_uv * float(uTex - 1);
ivec2 t = ivec2(floor(p));
vec2 f = fract(p);
float texel = uSpan / float(uTex - 1);
vec3 n = normalize(mix(
mix(nAt(t, texel), nAt(t + ivec2(1, 0), texel), f.x),
mix(nAt(t + ivec2(0, 1), texel), nAt(t + ivec2(1, 1), texel), f.x), f.y));
float dx = hBil(p + vec2(1.5, 0.0)) - hBil(p - vec2(1.5, 0.0));
float dz = hBil(p + vec2(0.0, 1.5)) - hBil(p - vec2(0.0, 1.5));
vec3 n = normalize(vec3(-dx, 3.0 * texel, -dz));
vec3 tw = pow(abs(n), vec3(4.0));
tw /= tw.x + tw.y + tw.z;
vec2 qx = v_world.zy, qy = v_world.xz, qz = v_world.xy;
// Procedural albedo, no texture reads; the same arithmetic as terrainAlbedo.albedoAt().
float w = sin(v_world.x * 0.043 + v_world.z * 0.017) * sin(v_world.z * 0.051 - v_world.x * 0.023);
float w = tw.x * wob2(qx) + tw.y * wob2(qy) + tw.z * wob2(qz);
float h = v_world.y + ALB_WOBBLE_H * w;
float flat_ = n.y + ALB_WOBBLE_S * w;
vec3 ground = mix(uSoil, uScree, smoothstep(ALB_SCREE_FROM, ALB_SCREE_TO, h));
@ -169,15 +175,14 @@ void main() {
float rockW = 1.0 - smoothstep(ALB_ROCK_LO, ALB_ROCK_HI, flat_);
vec3 albedo = mix(mix(ground, uSnow, snow), uRock, rockW);
// Surface grain and rock strata, the same arithmetic as terrainAlbedo.grainAt().
vec2 q = v_world.xz;
float coarse = (sin(dot(q, vec2(0.31, 0.27))) + sin(dot(q, vec2(-0.22, 0.35))) + sin(dot(q, vec2(0.38, -0.12)))) / 3.0;
float fine = (sin(dot(q, vec2(1.1, 0.7))) + sin(dot(q, vec2(-0.8, 1.2))) + sin(dot(q, vec2(1.3, -0.6)))) / 3.0;
float coarse = tw.x * waves3(qx, vec2(0.31, 0.27), vec2(-0.22, 0.35), vec2(0.38, -0.12)) + tw.y * waves3(qy, vec2(0.31, 0.27), vec2(-0.22, 0.35), vec2(0.38, -0.12)) + tw.z * waves3(qz, vec2(0.31, 0.27), vec2(-0.22, 0.35), vec2(0.38, -0.12));
float fine = tw.x * waves3(qx, vec2(1.1, 0.7), vec2(-0.8, 1.2), vec2(1.3, -0.6)) + tw.y * waves3(qy, vec2(1.1, 0.7), vec2(-0.8, 1.2), vec2(1.3, -0.6)) + tw.z * waves3(qz, vec2(1.1, 0.7), vec2(-0.8, 1.2), vec2(1.3, -0.6));
float near = 1.0 - smoothstep(ALB_FINE_NEAR, ALB_FINE_FAR, length(v_world - uCamera));
float layers = sin(v_world.y * 0.9 + w * 3.0);
albedo *= max(0.0, 1.0 + ALB_GRAIN_COARSE * coarse + ALB_GRAIN_FINE * near * fine + ALB_STRATA * rockW * layers);
// Cavity: a point lower than its surroundings sits in shade, one higher catches light. Shader-only, from the height map.
int r = max(1, int(12.0 / texel));
ivec2 c = ivec2(p + 0.5);
ivec2 c = ivec2(floor(p + 0.5));
float curv = 0.25 * (hAt(c + ivec2(r, 0)) + hAt(c - ivec2(r, 0)) + hAt(c + ivec2(0, r)) + hAt(c - ivec2(0, r))) - hAt(c);
float cavity = 1.0 - 0.55 * clamp(curv / 12.0, 0.0, 1.0) + 0.3 * clamp(-curv / 12.0, 0.0, 1.0);
vec3 lit = albedo * cavity * (uLight * max(dot(n, uLightDir), 0.0) + uAmbient * (0.5 + 0.5 * n.y));

View file

@ -1,6 +1,15 @@
/* eslint-disable no-restricted-syntax -- tests loop over skies, normals and distances */
import { describe, expect, it } from 'vitest';
import { buildGrid, CAMERA, GRID, seedOffset, TERRAIN, triangleCount, view } from './terrainWorld';
import {
buildGrid,
CAMERA,
GRID,
seedOffset,
TERRAIN,
triangleCount,
view,
warpUv,
} from './terrainWorld';
import { heightFragmentSource } from './terrainShaders';
describe('seed', () => {
@ -32,7 +41,7 @@ describe('grid', () => {
});
it('each tier fits a 32-bit index and the cheap tiers stay cheap', () => {
expect(triangleCount(GRID.low.grid)).toBeLessThan(40000);
expect(triangleCount(GRID.low.grid)).toBeLessThan(80000);
expect(GRID.full.grid).toBeGreaterThan(GRID.low.grid);
expect(GRID.still.tex).toBeLessThanOrEqual(GRID.low.tex);
});
@ -79,3 +88,19 @@ describe('camera', () => {
expect(Math.hypot(...v.up)).toBeCloseTo(1, 9);
});
});
describe('warpUv', () => {
it('maps the patch onto itself, monotonic, centre fixed', () => {
expect(warpUv(0)).toBe(0);
expect(warpUv(1)).toBe(1);
expect(warpUv(0.5)).toBe(0.5);
for (let i = 0; i < 100; i += 1) expect(warpUv((i + 1) / 100)).toBeGreaterThan(warpUv(i / 100));
});
it('packs the vertices toward the camera at the centre: finer there, coarser at the rim, than a plain grid', () => {
const plain = 1 / 192;
const step = (u: number) => warpUv(u + 1 / 192) - warpUv(u);
expect(step(0.5)).toBeLessThan(0.6 * plain);
expect(step(0.99)).toBeGreaterThan(1.3 * plain);
});
});

View file

@ -8,8 +8,8 @@ export const TERRAIN = { span: 3000, hmax: 256 };
/** Grid quads per side and height-map texels per side, by tier. 'still' draws one frame, so it takes the cheap pair. */
export const GRID = {
still: { grid: 128, tex: 512 },
low: { grid: 128, tex: 1024 },
full: { grid: 192, tex: 1024 },
low: { grid: 192, tex: 1024 },
full: { grid: 256, tex: 1024 },
} as const;
/** The camera: at the patch centre, above the highest peak, turning slowly and looking a little down. */
@ -29,6 +29,16 @@ export function seedOffset(seed: number): [number, number] {
return [(s * 7919) % 65536, (s * 104729) % 65536];
}
/**
* Where grid coordinate `u` (0..1 across the patch) lands in the patch, 0..1. The camera stands at the centre, so the
* grid is packed toward it: with s = 2u - 1 the spacing grows as 0.5 + |s| of the plain grid's, about half of it at the
* centre and half again as much at the rim. The vertex shader does the same arithmetic (terrainShaders.ts GRID_VERT).
*/
export const warpUv = (u: number): number => {
const s = 2 * u - 1;
return 0.5 + 0.5 * (0.5 * s + 0.5 * s * Math.abs(s));
};
export const triangleCount = (grid: number): number => 2 * grid * grid;
/** Vertex grid in unit uv: (grid + 1)^2 positions, then the two-triangle-per-quad index list. */