scene: procedural terrain albedo by normal and height, per baked sky

Rock on steep faces, soil to scree to snow by height, snow only on gentle
faces; no texture reads. Pure albedoAt()/albedoPalette() mirror the grid
fragment shader; the palette is read from the baked sky (snow line and tint
by sun elevation: cool haze at night, warm sun by day).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Nibu 2026-11-07 20:44:54 +00:00
commit 931f84fcd1
4 changed files with 232 additions and 7 deletions

View file

@ -2,6 +2,7 @@ import type { Scene, SceneOptions } from '../Scene';
import { FrameSampler, FrameStats } from '../ridge/probe';
import { skyColours } from '../ridge/skyColour';
import { SkyName } from './skyData';
import { albedoPalette } from './terrainAlbedo';
import {
ambientColour,
hazeColour,
@ -170,6 +171,7 @@ export function createTerrainScene(opts: TerrainOptions): Scene | null {
const sunLight = [...sunColour(sky)];
const ambient = [...ambientColour(sky)];
const haze = [...hazeColour(sky)];
const palette = albedoPalette(sky);
const triangles = triangleCount(spec.grid);
const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)');
@ -218,6 +220,11 @@ export function createTerrainScene(opts: TerrainOptions): Scene | null {
gl.uniform3fv(u('uAmbient'), ambient);
gl.uniform3fv(u('uHaze'), haze);
gl.uniform1f(u('uHazeK'), HAZE_K);
gl.uniform3fv(u('uSoil'), palette.soil);
gl.uniform3fv(u('uScree'), palette.scree);
gl.uniform3fv(u('uRock'), palette.rock);
gl.uniform3fv(u('uSnow'), palette.snow);
gl.uniform1f(u('uSnowLine'), palette.snowLine);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, heightTex);
gl.uniform1i(u('uHeight'), 0);

View file

@ -0,0 +1,103 @@
/* eslint-disable no-restricted-syntax -- tests loop over skies, heights and slopes */
import { describe, expect, it } from 'vitest';
import { SKY } from './skyData';
import { ALBEDO, albedoAt, albedoPalette, wobble } from './terrainAlbedo';
import { GRID_FRAG } from './terrainShaders';
const near = (a: readonly number[], b: readonly number[], eps = 1e-6) =>
a.every((v, i) => Math.abs(v - b[i]) < eps);
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;
const at = (sky: keyof typeof SKY, h: number, ny: number) =>
albedoAt(albedoPalette(SKY[sky]), h, ny, FLAT_X, 0);
describe('albedo by slope and height', () => {
it('the test point really has no wobble', () => {
expect(Math.abs(wobble(FLAT_X, 0))).toBeLessThan(1e-9);
});
it('steep faces are rock at every height, gentle low ones are soil, gentle high ones are snow', () => {
const p = albedoPalette(SKY.noonday);
for (const h of [10, 90, 160, 220]) expect(near(at('noonday', h, 0.3), p.rock)).toBe(true);
expect(near(at('noonday', 10, 1), p.soil)).toBe(true);
expect(near(at('noonday', 220, 1), p.snow)).toBe(true);
});
it('scree sits between soil and the snow line on gentle ground', () => {
const p = albedoPalette(SKY.noonday);
expect(near(at('noonday', ALBEDO.screeTo + 1, 1), p.scree)).toBe(true);
});
it('snow is shed as the face steepens: the same height goes snow, then mixed, then rock', () => {
const l = [1, 0.8, 0.5].map((ny) => luma(at('noonday', 220, ny)));
expect(l[0]).toBeGreaterThan(l[1]);
expect(l[1]).toBeGreaterThan(l[2]);
});
it('is continuous: a small step in height or slope never jumps a channel by more than a tenth', () => {
for (const sky of ['midnight', 'noonday'] as const)
for (let h = 0; h < 250; h += 1)
for (let ny = 0.3; ny <= 1; ny += 0.05) {
const a = at(sky, h, ny);
const b = at(sky, h + 1, ny + 0.01);
a.forEach((v, i) => expect(Math.abs(v - b[i])).toBeLessThan(0.1));
}
});
it('never returns a negative or a super-white channel', () => {
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)) {
expect(v).toBeGreaterThanOrEqual(0);
expect(v).toBeLessThanOrEqual(1);
}
});
it('the wobble moves band edges but stays inside its stated amplitude', () => {
for (let i = 0; i < 400; i += 1)
expect(Math.abs(wobble(i * 13.7, i * -9.1))).toBeLessThanOrEqual(1);
});
});
describe('per-sky palette', () => {
const mid = albedoPalette(SKY.midnight);
const noon = albedoPalette(SKY.noonday);
it('midnight snows lower than noonday', () => {
expect(mid.snowLine).toBeLessThan(noon.snowLine);
});
it('midnight is tinted toward the cool horizon haze, noonday toward the warm sun', () => {
// blue share of the same material is higher at night
const blueShare = (c: readonly number[]) => c[2] / (c[0] + c[1] + c[2]);
expect(blueShare(mid.scree)).toBeGreaterThan(blueShare(noon.scree));
expect(blueShare(mid.snow)).toBeGreaterThan(blueShare(noon.snow));
});
it('a sun at the horizon lands between the two palettes', () => {
const dusk = albedoPalette({ ...SKY.noonday, elevation: 2 });
expect(dusk.snowLine).toBeLessThan(noon.snowLine);
expect(dusk.snowLine).toBeGreaterThan(mid.snowLine);
});
it('keeps every material in 0..1', () => {
for (const p of [mid, noon])
for (const c of [p.soil, p.scree, p.rock, p.snow])
c.forEach((v) => {
expect(v).toBeGreaterThan(0);
expect(v).toBeLessThanOrEqual(1);
});
});
});
describe('shader agrees with the pure function on its numbers', () => {
it('takes every band number from ALBEDO, and reads no texture for colour', () => {
expect(GRID_FRAG).toContain(`#define ALB_SNOW_BAND ${ALBEDO.snowBand.toFixed(1)}`);
expect(GRID_FRAG).toContain(`#define ALB_ROCK_LO ${ALBEDO.rockLo}`);
expect(GRID_FRAG).toContain(`#define ALB_WOBBLE_S ${ALBEDO.wobbleSlope}`);
// the only fetch in the fragment shader is the height map's
expect(GRID_FRAG.match(/texelFetch|texture\(/g)).toHaveLength(1);
});
});

View file

@ -0,0 +1,98 @@
// Terrain surface colour as a pure function of height, slope and world position, no texture reads: the shader
// (terrainShaders.ts GRID_FRAG) does the same arithmetic with these numbers as uniforms and #defines. No DOM, no GL.
// Rock where the face is steep, then by height soil, scree and snow; snow only settles on gentle faces. The per-sky
// part reads the baked sky (./skyData.ts): the snow line drops and every material is tinted toward the sky's colour
// as the sun goes down, warm by the sun's own colour by day and cool by the horizon haze at night.
import { SkyData, Vec3 } from './skyData';
import { hazeColour, sunColour } from './terrainSky';
const clamp01 = (x: number) => Math.min(1, Math.max(0, x));
const smooth = (a: number, b: number, x: number) => {
const t = clamp01((x - a) / (b - a));
return t * t * (3 - 2 * t);
};
const mix = (a: number, b: number, t: number) => a + (b - a) * t;
/** Every number the shader shares: band edges in metres, slope edges as the normal's y (cosine of the slope angle). */
export const ALBEDO = {
/** soil fades to scree across these heights. */
screeFrom: 55,
screeTo: 115,
/** half-width in metres of the snow line's fade. */
snowBand: 30,
/** n.y edges: faces with n.y below `rockLo` are all rock, above `rockHi` none. */
rockLo: 0.62,
rockHi: 0.88,
/** n.y edges: snow is shed entirely below `snowLo` and settles fully above `snowHi`. */
snowLo: 0.68,
snowHi: 0.9,
/** world-position wobble of the height edges (metres) and the slope edges, so bands are not contour lines. */
wobbleHeight: 14,
wobbleSlope: 0.05,
} as const;
export interface AlbedoPalette {
soil: Vec3;
scree: Vec3;
rock: Vec3;
snow: Vec3;
/** Metres where snow is half in. */
snowLine: number;
}
const BASE = {
soil: [0.055, 0.06, 0.03],
scree: [0.2, 0.18, 0.155],
rock: [0.1, 0.09, 0.085],
snow: [0.72, 0.75, 0.8],
} as const;
const SNOW_LINE_DAY = 150;
const SNOW_LINE_NIGHT = 105;
const unit = (c: Vec3): Vec3 => {
const m = Math.max(c[0], c[1], c[2], 1e-6);
return [c[0] / m, c[1] / m, c[2] / m];
};
/** The palette one baked sky gives: base reflectances tinted toward the sky's colour, and its snow line. */
export function albedoPalette(d: SkyData): AlbedoPalette {
const cold = 1 - smooth(-6, 25, d.elevation);
const sun = unit(sunColour(d));
const haze = unit(hazeColour(d));
const tint = [0, 1, 2].map((i) => mix(sun[i], haze[i], cold));
const k = mix(0.15, 0.5, cold);
const tinted = (c: Vec3): Vec3 =>
[0, 1, 2].map((i) => c[i] * mix(1, tint[i], k)) as unknown as Vec3;
return {
soil: tinted(BASE.soil),
scree: tinted(BASE.scree),
rock: tinted(BASE.rock),
snow: tinted(BASE.snow),
snowLine: mix(SNOW_LINE_DAY, SNOW_LINE_NIGHT, cold),
};
}
/** Cheap two-sine value in -1..1 from 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.
* 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;
const ground = (i: number) =>
mix(p.soil[i], p.scree[i], smooth(ALBEDO.screeFrom, ALBEDO.screeTo, h));
const snow =
smooth(p.snowLine - ALBEDO.snowBand, p.snowLine + ALBEDO.snowBand, h) *
smooth(ALBEDO.snowLo, ALBEDO.snowHi, flat);
const rock = 1 - smooth(ALBEDO.rockLo, ALBEDO.rockHi, flat);
return [0, 1, 2].map((i) =>
mix(mix(ground(i), p.snow[i], snow), p.rock[i], rock)
) as unknown as Vec3;
}

View file

@ -7,11 +7,13 @@
import cultmath from '../shaders/CultMath.glsl?raw';
import phacelle from '../shaders/CultMath.Phacelle.glsl?raw';
import { trimGlsl } from '../cultmathTrim';
import { ALBEDO } from './terrainAlbedo';
import { TERRAIN } from './terrainWorld';
const HEADER =
'#version 300 es\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\n';
const f1 = (x: number) => x.toFixed(1);
const lit = (x: number) => (Number.isInteger(x) ? x.toFixed(1) : String(x));
export const FULLSCREEN_VERT = `${HEADER}
void main() {
@ -107,11 +109,22 @@ void main() {
// Lit by the baked sky: uSun (direction), uSunColour (linear, zero when the sun is down), uAmbient, uHaze (linear).
// The same arithmetic as terrainSky.shade(); the normal comes from the height map so shading carries detail finer than the mesh.
export const GRID_FRAG = `${HEADER}
const ALBEDO_DEFINES = `
#define ALB_SCREE_FROM ${lit(ALBEDO.screeFrom)}
#define ALB_SCREE_TO ${lit(ALBEDO.screeTo)}
#define ALB_SNOW_BAND ${lit(ALBEDO.snowBand)}
#define ALB_ROCK_HI ${lit(ALBEDO.rockHi)}
#define ALB_ROCK_LO ${lit(ALBEDO.rockLo)}
#define ALB_SNOW_HI ${lit(ALBEDO.snowHi)}
#define ALB_SNOW_LO ${lit(ALBEDO.snowLo)}
#define ALB_WOBBLE_H ${lit(ALBEDO.wobbleHeight)}
#define ALB_WOBBLE_S ${lit(ALBEDO.wobbleSlope)}
`;
export const GRID_FRAG = `${HEADER}${ALBEDO_DEFINES}
in vec2 v_uv;
in vec3 v_world;
uniform vec3 uCamera, uSun, uSunColour, uAmbient, uHaze;
uniform float uSpan, uHazeK;
uniform vec3 uCamera, uSun, uSunColour, uAmbient, uHaze, uSoil, uScree, uRock, uSnow;
uniform float uSpan, uHazeK, uSnowLine;
out vec4 o;
${FETCH}
// Unnormalised normal at one texel, central differences over its neighbours.
@ -129,10 +142,14 @@ void main() {
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 alt = clamp(v_world.y / 200.0, 0.0, 1.0);
vec3 rock = mix(vec3(0.07, 0.06, 0.05), vec3(0.28, 0.26, 0.22), alt);
vec3 grass = mix(vec3(0.03, 0.07, 0.025), vec3(0.14, 0.15, 0.07), alt);
vec3 albedo = mix(rock, grass, smoothstep(0.55, 0.9, n.y));
// 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 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));
float snow = smoothstep(uSnowLine - ALB_SNOW_BAND, uSnowLine + ALB_SNOW_BAND, h) * smoothstep(ALB_SNOW_LO, ALB_SNOW_HI, flat_);
float rockW = 1.0 - smoothstep(ALB_ROCK_LO, ALB_ROCK_HI, flat_);
vec3 albedo = mix(mix(ground, uSnow, snow), uRock, rockW);
vec3 lit = albedo * (uSunColour * max(dot(n, uSun), 0.0) + uAmbient * (0.5 + 0.5 * n.y));
float T = exp(-uHazeK * length(v_world - uCamera));
o = vec4(pow(mix(uHaze, lit, T), vec3(1.0 / 2.2)), 1.0);