scene: terrain sky and haze from Void's baked scattering table

Drops the vendored terrain/skyData.ts and the computed azimuth. terrainSky.ts reads src/sky/baked.ts:
sun {elevation_deg, azimuth_deg, color_linear}, ambient_linear, horizon_hex. terrainScatter.ts decodes
baked.scatter and uploads sky_view as an RGB16F 3D texture; SKY_FRAG and GRID_FRAG sample it (README
sampler), the sky for the view ray, the haze for the horizon in the fragment's azimuth.

- Sky: 1 - exp(-exposure * radiance) + night glow (midnight horizon colour, off as the sun nears the
  horizon) + sun disc; +-0.5/255 dither on the 8-bit output.
- Stars fade by sun elevation (starGain: 1 below -12, 0 above -6) instead of a dark-sky gate; the
  field is placed against the midnight gradient.
- ?sun=<deg>&az=<deg> (or the sun option) lights between the two bakes for dusk (skyAtSun).
- Changed numbers, noted in scene/README.md: haze colour is the scattered sky (was the gradient's
  horizon stop), ambient is ambient_linear as baked (was gradient zenith x 0.25 x night lift up to 4),
  HAZE_K unchanged at 0.0004.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Nibu 2026-11-07 23:40:43 +00:00
commit c2858452e7
13 changed files with 642 additions and 210 deletions

View file

@ -38,6 +38,31 @@ Integration (a canvas under the app, `startBackgroundScene`, `login()` when the
are later cuts. This PR is the render core plus the contract the host needs: flag, tier, failure
callbacks and the creature sizing rule. Nothing has drawn a creature.
## Terrain scene (`style: 'terrain'`): the baked sky
`terrain/` draws a Phacelle-displaced grid under a sky read from Void's bake (`src/sky/baked.ts`, layout in
`src/sky/README.md`); nothing is vendored. `terrainSky.ts` reads each moment's `sun.{elevation_deg, azimuth_deg,
color_linear}`, `ambient_linear` and `horizon_hex`; `terrainScatter.ts` decodes `baked.scatter` and uploads `sky_view` as an
RGB16F 3D texture (the transmittance table stays on the CPU, for the sun's colour at an elevation the bake does not hold).
Both fragment shaders sample it: `SKY_FRAG` for the sky, `GRID_FRAG` for the haze, which is the sky's colour at the horizon in the
fragment's azimuth, so far ground fades into the sky behind it at dusk too.
Page URL: `?sky=midnight|noonday` picks a bake; `?sun=<elevation deg>&az=<deg from north>` puts the sun anywhere between them
(`skyAtSun`: baked transmittance for the sun's colour, ambient and horizon blended from the midnight bake to the noonday one as
the sun climbs from -8 to 25 degrees). `?sun=` wins over `?sky=`.
- Sky: `1 - exp(-SKY_EXPOSURE * radiance)` plus a night glow (the midnight horizon colour, `nightness` 1 below -4 degrees, 0 above 4), a
sun disc from the sun's colour, and a +-0.5/255 dither on the 8-bit output. The table is single scattering only (no ground bounce,
no multiple scattering), so the noon horizon is pale yellow-green and a sun just under the horizon colours the whole sky orange,
where the real one keeps a blue-violet zenith. Within `HORIZON_FLOOR` (1.5 degrees) of the horizon the sky takes one flat colour,
because the table dips toward the ground there and would draw a seam against the haze.
- Stars: faded by the sun's elevation, `starGain` 1 below -12 degrees (where the table goes dark), 0 above -6, smooth between;
the field is placed against the midnight gradient and no longer gated on the sky being dark. At a baked sky that is the same as
before (midnight shows, noonday does not).
- Changed numbers: haze colour (was the gradient's horizon stop; now the scattered sky), ambient (was the gradient's zenith stop
x `AMBIENT_GAIN` 0.25 x `NIGHT_LIFT` up to 4; now `ambient_linear` as baked, so midnight's fill is about 2.5 to 3.5 times darker than
the lifted one). `HAZE_K` (0.0004 per metre) is unchanged.
## Entry points
- `index.ts` `startBackgroundScene(config.backgroundScene, capabilities, options)` is the host's

View file

@ -2,8 +2,9 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createTerrainScene } from './Terrain';
import { GRID, triangleCount } from './terrainWorld';
import { SKY } from './skyData';
import { ambientColour } from './terrainSky';
import { SKY, skyAtSun } from './terrainSky';
import { SKY_VIEW, skyViewWords } from './terrainScatter';
import { SKY_FRAG } from './terrainShaders';
import { startBackgroundScene } from '../index';
/** A GL context that accepts every call, remembers them, reports success for compile, link and framebuffer. */
@ -134,26 +135,58 @@ describe('createTerrainScene', () => {
});
it('lights with the sky chosen: option, then ?sky=, then the night default', () => {
const ambientUploaded = (opts: { sky?: 'midnight' | 'noonday' }) => {
const uploaded = (opts: { sky?: 'midnight' | 'noonday' }) => {
const { gl, calls } = fakeGl();
createTerrainScene({ canvas: canvasWith(gl), tier: 'still', ...opts })!.dispose();
const hit = calls.uniform3fv.filter((a) => (a[1] as ArrayLike<number>).length === 3);
// uniform3fv order in draw(): right, up, forward, then sun, sunColour, ambient, haze (+ camera)
return hit.map((a) => Array.from(a[1] as ArrayLike<number>));
// every vec3 uniform draw() sets: right, up, forward, sun, sunColour, glow, ambient, camera, soil...
return calls.uniform3fv
.filter((a) => (a[1] as ArrayLike<number>).length === 3)
.map((a) => Array.from(a[1] as ArrayLike<number>));
};
const night = ambientUploaded({});
const day = ambientUploaded({ sky: 'noonday' });
const nightA = Array.from(ambientColour(SKY.midnight));
const dayA = Array.from(ambientColour(SKY.noonday));
const night = uploaded({});
const day = uploaded({ sky: 'noonday' });
const nightA = Array.from(SKY.midnight.ambient);
const dayA = Array.from(SKY.noonday.ambient);
const has = (all: number[][], v: number[]) =>
all.some((a) => a.every((x, i) => Math.abs(x - v[i]) < 1e-6));
expect(has(night, nightA)).toBe(true);
expect(has(night, dayA)).toBe(false);
expect(has(day, dayA)).toBe(true);
search = '?sky=noonday';
expect(has(ambientUploaded({}), dayA)).toBe(true);
expect(has(uploaded({}), dayA)).toBe(true);
search = '?sky=garbage';
expect(has(ambientUploaded({}), nightA)).toBe(true);
expect(has(uploaded({}), nightA)).toBe(true);
});
it('a sun elevation (option or ?sun=&az=) lights between the bakes, and wins over ?sky=', () => {
const ambients = (opts: Record<string, unknown>) => {
const { gl, calls } = fakeGl();
createTerrainScene({ canvas: canvasWith(gl), tier: 'still', ...opts })!.dispose();
return calls.uniform3fv.map((a) => Array.from(a[1] as ArrayLike<number>));
};
const dusk = skyAtSun(-1, 300);
const has = (all: number[][], v: readonly number[]) =>
all.some((a) => a.length === 3 && a.every((x, i) => Math.abs(x - v[i]) < 1e-6));
expect(has(ambients({ sun: { elevation: -1, azimuth: 300 } }), dusk.ambient)).toBe(true);
search = '?sky=noonday&sun=-1&az=300';
expect(has(ambients({}), dusk.ambient)).toBe(true);
search = '?sun=garbage';
expect(has(ambients({}), SKY.midnight.ambient)).toBe(true);
});
it('uploads the baked scattering table once, as half floats, to a 3D texture', () => {
const { gl, calls } = fakeGl();
createTerrainScene({ canvas: canvasWith(gl), tier: 'full' })!.dispose();
expect(calls.texImage3D).toHaveLength(1);
const a = calls.texImage3D[0];
expect([a[3], a[4], a[5]]).toEqual([SKY_VIEW.width, SKY_VIEW.height, SKY_VIEW.depth]);
expect(a[9]).toEqual(skyViewWords());
expect(calls.deleteTexture).toHaveLength(2);
});
it('dithers the sky output by half an 8-bit step either way, and the terrain not at all', () => {
expect(SKY_FRAG).toContain('- 0.5');
expect(SKY_FRAG).toContain('dither / 255.0');
});
it('falls back to a still frame when the measured p95 is over 33 ms', () => {
@ -208,7 +241,7 @@ describe('createTerrainScene', () => {
createTerrainScene({ canvas: canvasWith(gl), tier: 'full' })!.dispose();
expect(calls.deleteProgram).toHaveLength(3);
expect(calls.deleteBuffer).toHaveLength(2);
expect(calls.deleteTexture).toHaveLength(1);
expect(calls.deleteTexture).toHaveLength(2);
expect(rafQueue).toHaveLength(0);
});
});

View file

@ -1,17 +1,18 @@
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 { sunIndex } from '../../../../sky/scatter.js';
import { SKY_VIEW, skyViewWords } from './terrainScatter';
import {
ambientColour,
hazeColour,
glowColour,
HAZE_K,
hexToLinear,
isSkyName,
skyAtSun,
SkyData,
skyData,
SkyName,
skyNameFor,
sunColour,
sunDirection,
} from './terrainSky';
import { buildGrid, CAMERA, GRID, seedOffset, TERRAIN, triangleCount, view } from './terrainWorld';
@ -30,6 +31,8 @@ export type TerrainOptions = Pick<
> & {
/** Which baked sky lights and hazes the terrain. Default: `?sky=` in the page URL, else the night notion of `skyColours()`. */
sky?: SkyName;
/** Put the sun at this elevation (degrees) and azimuth (clockwise from north; default: noonday's) instead of at the baked sky's: `?sun=` and `?az=` in the page URL. Lights between the two bakes, for dusk. */
sun?: { elevation: number; azimuth?: number };
/** Terrain seed: the height map is sampled at an offset taken from it. Default 0. */
seed?: number;
/** Show the rAF median/p95 readout (plus triangle count). Default: the page URL has `?probe=1`. */
@ -74,18 +77,25 @@ function program(gl: WebGL2RenderingContext, name: string, vs: string, fs: strin
return p;
}
/** The sky to use: the option, then `?sky=midnight|noonday`, then the night notion of `skyColours()`. */
function chooseSky(opt: SkyName | undefined): SkyName {
if (opt) return opt;
const q = new URLSearchParams(window.location.search).get('sky');
return isSkyName(q) ? q : skyNameFor(skyColours());
/** The sky to use: a sun elevation from the option or `?sun=` (with `?az=`), else the baked sky from the option, then `?sky=midnight|noonday`, then the night notion of `skyColours()`. */
function chooseSky(opts: Pick<TerrainOptions, 'sky' | 'sun'>): SkyData {
const q = new URLSearchParams(window.location.search);
const number = (key: string) => (q.get(key)?.trim() ? Number(q.get(key)) : NaN);
const elevation = opts.sun?.elevation ?? number('sun');
if (Number.isFinite(elevation)) {
const azimuth = opts.sun?.azimuth ?? number('az');
return skyAtSun(elevation, Number.isFinite(azimuth) ? azimuth : undefined);
}
if (opts.sky) return skyData(opts.sky);
const name = q.get('sky');
return skyData(isSkyName(name) ? name : skyNameFor(skyColours()));
}
/**
* The terrain scene: same contract as `createRidgeScene`/`createScene` ({ login, dispose }, null for "keep the
* CSS ground"). WebGL2 only. The height map is baked once on the GPU (Phacelle, see terrainShaders.ts) into an
* RGBA8 texture; each frame is two draws: the baked gradient sky, then a displaced grid lit by the baked sun and
* ambient and hazed toward the baked horizon colour. Cadence guard, pauses and the `?probe=1` readout match the
* RGBA8 texture; each frame is two draws: the sky from the baked scattering table, then a displaced grid lit by the
* baked sun and ambient and hazed toward that sky at the horizon. Cadence guard, pauses and the `?probe=1` readout match the
* ridge scene.
*/
export function createTerrainScene(opts: TerrainOptions): Scene | null {
@ -101,7 +111,7 @@ export function createTerrainScene(opts: TerrainOptions): Scene | null {
const units = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
if (typeof units === 'number' && units < 1) return null;
const sky = skyData(chooseSky(opts.sky));
const sky = chooseSky(opts);
const spec = GRID[tier];
let skyProg: WebGLProgram;
@ -123,6 +133,29 @@ export function createTerrainScene(opts: TerrainOptions): Scene | null {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, spec.tex, spec.tex, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
// The baked scattering table, RGB16F, uploaded as it is stored (half floats); the shader divides by the store scale.
const skyTex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_3D, skyTex);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
gl.texImage3D(
gl.TEXTURE_3D,
0,
gl.RGB16F,
SKY_VIEW.width,
SKY_VIEW.height,
SKY_VIEW.depth,
0,
gl.RGB,
gl.HALF_FLOAT,
skyViewWords()
);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
[gl.TEXTURE_WRAP_S, gl.TEXTURE_WRAP_T, gl.TEXTURE_WRAP_R].forEach((w) =>
gl.texParameteri(gl.TEXTURE_3D, w, gl.CLAMP_TO_EDGE)
);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
gl.bindTexture(gl.TEXTURE_2D, heightTex);
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, heightTex, 0);
const complete = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE;
@ -130,6 +163,7 @@ export function createTerrainScene(opts: TerrainOptions): Scene | null {
const release = () => {
free.forEach((f) => f());
gl.deleteTexture(heightTex);
gl.deleteTexture(skyTex);
gl.deleteFramebuffer(fbo);
gl.deleteProgram(bakeProg);
gl.deleteProgram(skyProg);
@ -167,11 +201,11 @@ export function createTerrainScene(opts: TerrainOptions): Scene | null {
() => gl.deleteBuffer(ibuf)
);
const gradient = new Float32Array(sky.gradient.flatMap((h) => [...hexToLinear(h)]));
const sun = [...sunDirection(sky)];
const sunLight = [...sunColour(sky)];
const ambient = [...ambientColour(sky)];
const haze = [...hazeColour(sky)];
const sunLight = [...sky.direct];
const ambient = [...sky.ambient];
const glow = [...glowColour(sky)];
const sunTexel = sunIndex(sky.elevation);
const palette = albedoPalette(sky);
const triangles = triangleCount(spec.grid);
@ -201,7 +235,13 @@ export function createTerrainScene(opts: TerrainOptions): Scene | null {
gl.disable(gl.DEPTH_TEST);
gl.useProgram(skyProg);
const us = (n: string) => gl.getUniformLocation(skyProg, n);
gl.uniform3fv(us('uGrad'), gradient);
gl.uniform3fv(us('uSun'), sun);
gl.uniform3fv(us('uSunColour'), sunLight);
gl.uniform3fv(us('uGlow'), glow);
gl.uniform1f(us('uSunIndex'), sunTexel);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_3D, skyTex);
gl.uniform1i(us('uSky'), 1);
gl.uniform3fv(us('uRight'), v.right);
gl.uniform3fv(us('uUp'), v.up);
gl.uniform3fv(us('uForward'), v.forward);
@ -220,7 +260,11 @@ export function createTerrainScene(opts: TerrainOptions): Scene | null {
gl.uniform3fv(u('uSun'), sun);
gl.uniform3fv(u('uSunColour'), sunLight);
gl.uniform3fv(u('uAmbient'), ambient);
gl.uniform3fv(u('uHaze'), haze);
gl.uniform3fv(u('uGlow'), glow);
gl.uniform1f(u('uSunIndex'), sunTexel);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_3D, skyTex);
gl.uniform1i(u('uSky'), 1);
gl.uniform1f(u('uHazeK'), HAZE_K);
gl.uniform3fv(u('uSoil'), palette.soil);
gl.uniform3fv(u('uScree'), palette.scree);

View file

@ -1,44 +0,0 @@
// The sky numbers the terrain scene lights and hazes with, vendored from Void's baked sky (GameCult/Void
// PR #22, branch void/sky-tokens, revision 7b4aa2f): `src/sky/baked.ts` (generated by scripts/bake-sky.mjs
// from src/sky/sun.js and src/sky/skyTokens.js) and `light()` in `src/sky/sun.js`. Both moments are
// 2026-09-22 at lat 45, lon 0.
//
// elevation, gradient copied from baked.ts (`baked.midnight` / `baked.noonday`).
// direct `light({time, lat, lon}).direct` from sun.js at that moment: sun colour at normal
// incidence, linear RGB, clear zenith sun ~ 1. baked.ts does not carry it.
// azimuth NOT in #22. Computed here from the same NOAA/Meeus series sun.js uses for the
// elevation (hour angle and declination), degrees clockwise from north. It is the
// one number in this file Void's bake does not produce; see the report on the table shape.
//
// These are copies, not a link: #22 is not in this tree, so nothing fails if Void re-bakes. When #22 lands,
// replace this module's literals with an import of `baked` (plus the fields above, if the bake adds them) and
// keep the exports.
export type SkyName = 'midnight' | 'noonday';
export type Vec3 = readonly [number, number, number];
export interface SkyData {
/** Degrees above the horizon, no refraction. Negative: the sun is down. */
elevation: number;
/** Degrees clockwise from north. */
azimuth: number;
/** Sun colour at normal incidence, linear RGB. Black when the sun is down. */
direct: Vec3;
/** Seven sRGB hex stops, zenith first, horizon last. */
gradient: readonly string[];
}
export const SKY: Record<SkyName, SkyData> = {
midnight: {
elevation: -44.579021600011224,
azimuth: 2.4988773054640205,
direct: [0, 0, 0],
gradient: ['#37446a', '#38456a', '#3b4669', '#3d4868', '#414a67', '#444c66', '#484e64'],
},
noonday: {
elevation: 45.16994813502928,
azimuth: 182.58737070473097,
direct: [0.9189659216820631, 0.8444983652129638, 0.6933684802959983],
gradient: ['#95c6ff', '#9ac9ff', '#a5cfff', '#b3d6ff', '#c2dfff', '#d2e9ff', '#e2f4ff'],
},
};

View file

@ -1,6 +1,6 @@
/* eslint-disable no-restricted-syntax -- tests loop over skies, heights and slopes */
import { describe, expect, it } from 'vitest';
import { SKY } from './skyData';
import { SKY } from './terrainSky';
import { ALBEDO, albedoAt, albedoPalette, wobble } from './terrainAlbedo';
import { GRID_FRAG } from './terrainShaders';
@ -98,7 +98,7 @@ describe('shader agrees with the pure function on its numbers', () => {
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);
// the only fetch for colour-by-material would be a texture; the height map's texelFetch is the only other read, and the sky lookup is the baked scattering table's
expect(GRID_FRAG.match(/texelFetch|texture\((?!uSky)/g)).toHaveLength(1);
});
});

View file

@ -1,10 +1,9 @@
// 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
// part reads the baked sky (./terrainSky.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 { coldness, hazeColour, sunColour } from './terrainSky';
import { coldness, hazeColour, SkyData, Vec3 } from './terrainSky';
const clamp01 = (x: number) => Math.min(1, Math.max(0, x));
const smooth = (a: number, b: number, x: number) => {
@ -58,7 +57,7 @@ const unit = (c: Vec3): Vec3 => {
/** 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 = coldness(d);
const sun = unit(sunColour(d));
const sun = unit(d.direct);
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);

View file

@ -0,0 +1,88 @@
/* eslint-disable no-restricted-syntax -- tests walk table texels */
import { describe, expect, it } from 'vitest';
import { baked } from '../../../../sky/baked';
import { decode, viewElevation } from '../../../../sky/scatter.js';
import {
SCATTER_GLSL,
scatterRadiance,
skyViewWords,
SKY_VIEW,
tableWords,
transmittanceAt,
} from './terrainScatter';
const S = baked.scatter.sky_view;
describe('the table upload', () => {
it('decodes the baked base64 to one half-float word per channel per texel', () => {
const w = skyViewWords();
expect(w.length).toBe(S.width * S.height * S.depth * S.channels);
expect(SKY_VIEW).toEqual({ width: S.width, height: S.height, depth: S.depth });
expect(tableWords(baked.scatter.transmittance.data)).toHaveLength(32 * 3);
});
it('words are little-endian: the base64 bytes lo, hi make a word hi << 8 | lo', () => {
expect(Array.from(tableWords(btoa(String.fromCharCode(0x34, 0x12, 0xff, 0x7b))))).toEqual([
0x1234, 0x7bff,
]);
});
});
describe('scatterRadiance (the CPU twin of the sampler)', () => {
it('returns the stored texel exactly at a texel centre: layout x azimuth, y view, z sun', () => {
const w = skyViewWords();
for (const [z, y, x] of [
[10, 31, 0],
[8, 5, 3],
[5, 20, 6],
[11, 0, 2],
]) {
const base = ((z * S.height + y) * S.width + x) * 3;
const got = scatterRadiance(
S.sun_elevations_deg[z],
viewElevation(y),
x * S.azimuth_step_deg
);
got.forEach((v, c) => expect(v).toBeCloseTo(decode(w[base + c]), 9));
}
});
it('interpolates between texels and clamps beyond the table', () => {
const a = scatterRadiance(25, 10, 0)[2];
const b = scatterRadiance(45, 10, 0)[2];
const mid = scatterRadiance(35, 10, 0)[2]; // 35 is halfway between 25 and 45 on the sun axis
expect(mid).toBeCloseTo((a + b) / 2, 9);
expect(scatterRadiance(500, 10, 400)).toEqual(scatterRadiance(90, 10, 180));
expect(scatterRadiance(30, 10, -90)).toEqual(scatterRadiance(30, 10, 90));
});
it('is black under the planet’s shadow limit and blue at a high noon zenith', () => {
scatterRadiance(-18, 30, 0).forEach((v) => expect(v).toBeLessThan(1e-6));
const noon = scatterRadiance(45, 85, 90);
expect(noon[2]).toBeGreaterThan(1.5 * noon[0]);
});
});
describe('transmittanceAt', () => {
it('is the zenith transmittance exp(-TAU) overhead and redder at the horizon', () => {
const z = transmittanceAt(90);
[0.06, 0.12, 0.26].forEach((tau, i) => expect(z[i]).toBeCloseTo(Math.exp(-tau), 2));
const h = transmittanceAt(2);
expect(h[2] / h[0]).toBeLessThan(0.5 * (z[2] / z[0]));
});
it('is zero where the ground is in the way', () => {
expect(transmittanceAt(-4)).toEqual([0, 0, 0]);
});
});
describe('the GLSL sampler', () => {
it('uses the layout the README documents: texel-centre coordinates over a 7 x 32 x 12 texture, decoded by the store scale', () => {
expect(SCATTER_GLSL).toContain('(x + 0.5) / 7.0');
expect(SCATTER_GLSL).toContain('(y + 0.5) / 32.0');
expect(SCATTER_GLSL).toContain('(uSunIndex + 0.5) / 12.0');
expect(SCATTER_GLSL).toContain('/ 64.0');
expect(SCATTER_GLSL).toContain('sqrt(clamp((el - (-4.0)) / 94.0, 0.0, 1.0)) * 31.0');
expect(SCATTER_GLSL).toContain('* 6.0');
});
});

View file

@ -0,0 +1,94 @@
// The baked scattering tables (src/sky/baked.ts `scatter`, layout in src/sky/README.md) as the terrain scene
// uses them: decoded to half-float words for the GPU, a CPU twin of the shader's sky lookup for tests and
// for the sun's colour at an arbitrary elevation, and the GLSL both shaders share. No DOM, no GL.
import { baked } from '../../../../sky/baked';
import { decode, sunIndex, viewIndex } from '../../../../sky/scatter.js';
import type { Vec3 } from './terrainSky';
const S = baked.scatter;
const SKY = S.sky_view;
const VIEW = S.view_elevation_deg;
/** Raw little-endian half-float words of a base64 table, ready for `texImage3D(..., HALF_FLOAT, words)`. */
export function tableWords(b64: string): Uint16Array {
const bytes = atob(b64);
return Uint16Array.from(
{ length: bytes.length / 2 },
(_, i) => bytes.charCodeAt(2 * i) + 256 * bytes.charCodeAt(2 * i + 1)
);
}
export const SKY_VIEW = { width: SKY.width, height: SKY.height, depth: SKY.depth } as const;
export const STORE_SCALE = S.store_scale;
export const skyViewWords = (): Uint16Array => tableWords(SKY.data);
/** Decode a stored table to values, once. */
const decoded = (data: string) => {
let values: Float32Array | undefined;
return (): Float32Array => {
if (!values) values = Float32Array.from(tableWords(data), decode);
return values;
};
};
const transmittanceTable = decoded(S.transmittance.data);
const skyTable = decoded(SKY.data);
/** Sun colour at normal incidence for a sun at `elevationDeg`: the baked transmittance, per channel. Zero under the horizon. */
export function transmittanceAt(elevationDeg: number): Vec3 {
const t = transmittanceTable();
const f = Math.min(viewIndex(elevationDeg), VIEW.samples - 1);
const i = Math.min(Math.floor(f), VIEW.samples - 2);
const k = f - i;
return [0, 1, 2].map((c) => t[i * 3 + c] * (1 - k) + t[(i + 1) * 3 + c] * k) as unknown as Vec3;
}
/**
* Sky radiance per steradian for a sun of unit irradiance, trilinear in (azimuth from the sun, view
* elevation, sun elevation) on texel centres, clamped at the edges: what the GPU's LINEAR sampler returns.
*/
export function scatterRadiance(sunElDeg: number, viewElDeg: number, azFromSunDeg: number): Vec3 {
const t = skyTable();
const at = [
Math.min(Math.abs(azFromSunDeg) / 180, 1) * (SKY.width - 1),
viewIndex(viewElDeg),
sunIndex(sunElDeg),
];
const lo = at.map((v, a) => Math.min(Math.floor(v), [SKY.width, SKY.height, SKY.depth][a] - 2));
const f = at.map((v, a) => v - lo[a]);
const out = [0, 0, 0];
for (let corner = 0; corner < 8; corner += 1) {
const dx = corner % 2;
const dy = Math.floor(corner / 2) % 2;
const dz = Math.floor(corner / 4);
const w = (dx ? f[0] : 1 - f[0]) * (dy ? f[1] : 1 - f[1]) * (dz ? f[2] : 1 - f[2]);
const base = (((lo[2] + dz) * SKY.height + lo[1] + dy) * SKY.width + lo[0] + dx) * 3;
for (let c = 0; c < 3; c += 1) out[c] += w * t[base + c];
}
return [out[0], out[1], out[2]];
}
/**
* The lowest view elevation the sky is sampled at, degrees. The table dips toward the ground over its last degree
* (its rows below the horizon are for an observer who would hit the ground), so at and below this the sky and the
* terrain's haze both take the colour here, flat to the horizon, and meet without a seam.
*/
export const HORIZON_FLOOR = 1.5;
/** The sky shader's lookup, in GLSL: `skyScatter(viewDirection)` is unit-sun radiance, needs uSky, uSunIndex, uSun. */
export const SCATTER_GLSL = `
uniform highp sampler3D uSky;
uniform float uSunIndex;
uniform vec3 uSun;
vec3 skyScatter(vec3 d) {
float el = max(degrees(asin(clamp(d.y, -1.0, 1.0))), ${HORIZON_FLOOR.toFixed(1)});
vec2 h = d.xz, s = uSun.xz;
float az = (length(h) < 1e-4 || length(s) < 1e-4) ? 0.0
: degrees(acos(clamp(dot(normalize(h), normalize(s)), -1.0, 1.0)));
float y = sqrt(clamp((el - (${VIEW.min.toFixed(1)})) / ${(VIEW.max - VIEW.min).toFixed(
1
)}, 0.0, 1.0)) * ${(VIEW.samples - 1).toFixed(1)};
float x = clamp(az / 180.0, 0.0, 1.0) * ${(SKY.width - 1).toFixed(1)};
return texture(uSky, vec3((x + 0.5) / ${SKY.width}.0, (y + 0.5) / ${
SKY.height
}.0, (uSunIndex + 0.5) / ${SKY.depth}.0)).rgb / ${S.store_scale.toFixed(1)};
}`;

View file

@ -8,6 +8,8 @@ import cultmath from '../shaders/CultMath.glsl?raw';
import phacelle from '../shaders/CultMath.Phacelle.glsl?raw';
import { trimGlsl } from '../cultmathTrim';
import { ALBEDO } from './terrainAlbedo';
import { SCATTER_GLSL } from './terrainScatter';
import { GLOW_ZENITH, SKY_EXPOSURE } from './terrainSky';
import { TERRAIN } from './terrainWorld';
const HEADER =
@ -107,7 +109,8 @@ void main() {
gl_Position = uViewProj * vec4(v_world, 1.0);
}`;
// Lit by the baked sky: uSun (direction), uSunColour (linear, zero when the sun is down), uAmbient, uHaze (linear).
// Lit by the baked sky: uSun (direction), uSunColour (linear, zero when the sun is down), uAmbient; hazed toward the
// scattered sky at the horizon in the ray's azimuth (SKY_COLOUR_GLSL).
// The same arithmetic as terrainSky.shade(); the normal comes from the height map so shading carries detail finer than the mesh.
const ALBEDO_DEFINES = `
#define ALB_SCREE_FROM ${lit(ALBEDO.screeFrom)}
@ -120,10 +123,20 @@ const ALBEDO_DEFINES = `
#define ALB_WOBBLE_H ${lit(ALBEDO.wobbleHeight)}
#define ALB_WOBBLE_S ${lit(ALBEDO.wobbleSlope)}
`;
export const GRID_FRAG = `${HEADER}${ALBEDO_DEFINES}
// The sky colour along a unit direction: scattering lifted by the exposure, tone-mapped, plus the night glow. The
// same arithmetic as terrainSky.skyColour(). uGlow is the baked horizon colour already scaled by how dark the sun is.
const SKY_COLOUR_GLSL = `${SCATTER_GLSL}
uniform vec3 uGlow;
vec3 skyColour(vec3 d) {
return 1.0 - exp(-${lit(SKY_EXPOSURE)} * skyScatter(d)) + uGlow * mix(1.0, ${lit(
GLOW_ZENITH
)}, sqrt(clamp(d.y, 0.0, 1.0)));
}`;
export const GRID_FRAG = `${HEADER}${ALBEDO_DEFINES}${SKY_COLOUR_GLSL}
in vec2 v_uv;
in vec3 v_world;
uniform vec3 uCamera, uSun, uSunColour, uAmbient, uHaze, uSoil, uScree, uRock, uSnow;
uniform vec3 uCamera, uSunColour, uAmbient, uSoil, uScree, uRock, uSnow;
uniform float uSpan, uHazeK, uSnowLine;
out vec4 o;
${FETCH}
@ -151,13 +164,21 @@ void main() {
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);
vec3 toSurface = v_world - uCamera;
float T = exp(-uHazeK * length(toSurface));
vec3 haze = skyColour(normalize(vec3(toSurface.x, 0.0, toSurface.z)));
o = vec4(pow(mix(haze, lit, T), vec3(1.0 / 2.2)), 1.0);
}`;
// The sky behind: the gradient's seven stops, zenith first, by the view ray's elevation (horizon stop at and below the horizon).
export const SKY_FRAG = `${HEADER}
uniform vec3 uGrad[7];
// The sky behind: the baked scattering tables by the view ray's elevation and azimuth from the sun, a sun disc, and a
// dither of +-0.5/255 on the 8-bit output so the dusk glow does not band.
const DISC = {
inner: Math.cos((0.5 * Math.PI) / 180),
outer: Math.cos((1.1 * Math.PI) / 180),
gain: 6.0,
};
export const SKY_FRAG = `${HEADER}${SKY_COLOUR_GLSL}
uniform vec3 uSunColour;
uniform vec3 uRight, uUp, uForward;
uniform vec2 uSize;
uniform float uTanHalf;
@ -165,8 +186,9 @@ out vec4 o;
void main() {
vec2 ndc = gl_FragCoord.xy / uSize * 2.0 - 1.0;
vec3 d = normalize(uForward + ndc.x * uTanHalf * uSize.x / uSize.y * uRight + ndc.y * uTanHalf * uUp);
float s = (1.0 - sqrt(smoothstep(-0.15, 1.0, d.y))) * 6.0;
int i = int(min(floor(s), 5.0));
vec3 c = mix(uGrad[i], uGrad[i + 1], s - float(i));
o = vec4(pow(c, vec3(1.0 / 2.2)), 1.0);
vec3 c = skyColour(d) + uSunColour * ${lit(DISC.gain)} * smoothstep(${DISC.outer}, ${
DISC.inner
}, dot(d, uSun));
float dither = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))) - 0.5;
o = vec4(pow(c, vec3(1.0 / 2.2)) + dither / 255.0, 1.0);
}`;

View file

@ -1,29 +1,47 @@
/* eslint-disable no-restricted-syntax -- tests loop over skies, normals and distances */
import { describe, expect, it } from 'vitest';
import { SKY } from './skyData';
import { baked } from '../../../../sky/baked';
import {
AMBIENT_GAIN,
NIGHT_LIFT,
ambientColour,
coldness,
glowColour,
hazeColour,
hexToLinear,
nightness,
shade,
SKY,
skyAtSun,
skyColour,
skyNameFor,
sunColour,
sunDirection,
transmittance,
Vec3,
} from './terrainSky';
import { skyColours } from '../ridge/skyColour';
const UP = [0, 1, 0] as const;
const luma = (c: readonly number[]) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
/** Unit view direction at an elevation (degrees) and an azimuth clockwise from north. */
const look = (el: number, az: number): Vec3 => {
const e = (el * Math.PI) / 180;
const a = (az * Math.PI) / 180;
return [Math.sin(a) * Math.cos(e), Math.sin(e), -Math.cos(a) * Math.cos(e)];
};
describe('baked sky numbers', () => {
it('keep the two moments apart: night sun below the horizon, noon sun well above', () => {
describe('the baked sky is read, not copied', () => {
it('SKY carries Void’s numbers: sun, ambient, horizon', () => {
for (const name of ['midnight', 'noonday'] as const) {
const b = baked[name];
expect(SKY[name].elevation).toBe(b.sun.elevation_deg);
expect(SKY[name].azimuth).toBe(b.sun.azimuth_deg);
expect(SKY[name].direct).toEqual(b.sun.color_linear);
expect(SKY[name].ambient).toEqual(b.ambient_linear);
expect(SKY[name].horizon).toEqual(hexToLinear(b.horizon_hex));
}
});
it('keeps the two moments apart: night sun below the horizon, noon sun well above', () => {
expect(SKY.midnight.elevation).toBeLessThan(0);
expect(SKY.noonday.elevation).toBeGreaterThan(30);
expect(SKY.midnight.gradient).toHaveLength(7);
expect(SKY.noonday.gradient).toHaveLength(7);
});
it('sunDirection is a unit vector with y = sin(elevation), north at -z, south at +z', () => {
@ -48,67 +66,118 @@ describe('baked sky numbers', () => {
});
});
describe('night fill', () => {
it('lifts ambient at night by NIGHT_LIFT and leaves a high sun at the plain gain', () => {
const z = (d: typeof SKY.midnight) => hexToLinear(d.gradient[0]);
ambientColour(SKY.midnight).forEach((v, i) => expect(v).toBeCloseTo(z(SKY.midnight)[i] * AMBIENT_GAIN * NIGHT_LIFT, 9));
ambientColour(SKY.noonday).forEach((v, i) => expect(v).toBeCloseTo(z(SKY.noonday)[i] * AMBIENT_GAIN, 9));
describe('a sun at any elevation (skyAtSun)', () => {
it('lights nothing under the horizon and fades in across the last degrees, as sun.js does', () => {
expect(skyAtSun(-2).direct).toEqual([0, 0, 0]);
expect(skyAtSun(-30).direct).toEqual([0, 0, 0]);
const at = (e: number) => luma(skyAtSun(e).direct);
expect(at(0.3)).toBeGreaterThan(0);
expect(at(0.3)).toBeLessThan(at(1.5));
expect(at(1.5)).toBeLessThan(at(60));
});
it('agrees with the baked noon sun colour where they overlap, to a couple of percent', () => {
const want = SKY.noonday.direct;
const got = skyAtSun(SKY.noonday.elevation).direct;
got.forEach((v, i) => expect(Math.abs(v / want[i] - 1)).toBeLessThan(0.02));
});
it('the sun goes red as it sets: less blue left in the direct light at 2 degrees than at 45', () => {
const lo = skyAtSun(2).direct;
const hi = skyAtSun(45).direct;
expect(lo[2] / lo[0]).toBeLessThan(0.6 * (hi[2] / hi[0]));
});
it('ambient and horizon run from the midnight bake to the noonday one as the sun climbs', () => {
expect(luma(skyAtSun(-30).ambient)).toBeCloseTo(luma(SKY.midnight.ambient), 9);
expect(luma(skyAtSun(60).ambient)).toBeCloseTo(luma(SKY.noonday.ambient), 9);
expect(luma(skyAtSun(5).ambient)).toBeGreaterThan(luma(SKY.midnight.ambient));
expect(luma(skyAtSun(5).ambient)).toBeLessThan(luma(SKY.noonday.ambient));
expect(skyAtSun(10, 270).azimuth).toBe(270);
});
});
describe('lighting', () => {
it('noonday lights an upward face with the sun; midnight has none', () => {
expect(luma(sunColour(SKY.noonday))).toBeGreaterThan(0.5);
expect(sunColour(SKY.midnight)).toEqual([0, 0, 0]);
});
it('a sun below the horizon gives no negative or sun light on any normal, even with a lit colour', () => {
const forcedDown = { ...SKY.noonday, elevation: -30 };
expect(sunColour(forcedDown)).toEqual([0, 0, 0]);
for (const n of [UP, [1, 0, 0], [0, -1, 0], [0, 0.6, -0.8]] as const) {
const c = shade(forcedDown, [1, 1, 1], n, 0);
for (const ch of c) expect(ch).toBeGreaterThanOrEqual(0);
}
});
it('the sun fades out through the horizon instead of switching', () => {
const at = (elevation: number) => luma(sunColour({ ...SKY.noonday, elevation }));
expect(at(-2)).toBe(0);
expect(at(0.3)).toBeGreaterThan(0);
expect(at(0.3)).toBeLessThan(at(1.5));
expect(at(1.5)).toBeCloseTo(at(60), 9);
expect(luma(SKY.noonday.direct)).toBeGreaterThan(0.5);
expect(SKY.midnight.direct).toEqual([0, 0, 0]);
});
it('shade never goes negative on any normal at either sky, at any distance', () => {
for (const d of Object.values(SKY))
for (const d of [...Object.values(SKY), skyAtSun(-3), skyAtSun(1)])
for (const n of [UP, [0, -1, 0], [1, 0, 0], [-0.6, 0.0, 0.8]] as const)
for (const dist of [0, 100, 5000])
for (const ch of shade(d, [0.3, 0.3, 0.3], n, dist)) expect(ch).toBeGreaterThanOrEqual(0);
for (const ch of shade(d, [0.3, 0.3, 0.3], n, dist, look(-5, 40)))
expect(ch).toBeGreaterThanOrEqual(0);
});
it('a face turned to the noon sun is brighter than one turned away; at midnight the two match to ambient', () => {
const toSun = sunDirection(SKY.noonday);
const away = [-toSun[0], 0, -toSun[2]] as const;
const lit = luma(shade(SKY.noonday, [0.5, 0.5, 0.5], toSun, 0));
const dark = luma(shade(SKY.noonday, [0.5, 0.5, 0.5], away, 0));
const view = look(-5, 0);
const lit = luma(shade(SKY.noonday, [0.5, 0.5, 0.5], toSun, 0, view));
const dark = luma(shade(SKY.noonday, [0.5, 0.5, 0.5], away, 0, view));
expect(lit).toBeGreaterThan(3 * dark);
const m = (n: readonly [number, number, number]) => shade(SKY.midnight, [0.5, 0.5, 0.5], n, 0);
const m = (n: readonly [number, number, number]) =>
shade(SKY.midnight, [0.5, 0.5, 0.5], n, 0, view);
expect(luma(m(UP))).toBeGreaterThan(0); // moonlit fill, not black
expect(luma(m(UP))).toBeLessThan(0.05);
});
it('noon is much brighter than midnight, ambient included', () => {
expect(luma(ambientColour(SKY.noonday))).toBeGreaterThan(2 * luma(ambientColour(SKY.midnight)));
expect(luma(shade(SKY.noonday, [0.4, 0.4, 0.4], UP, 0))).toBeGreaterThan(
10 * luma(shade(SKY.midnight, [0.4, 0.4, 0.4], UP, 0))
expect(luma(SKY.noonday.ambient)).toBeGreaterThan(2 * luma(SKY.midnight.ambient));
const view = look(-5, 0);
expect(luma(shade(SKY.noonday, [0.4, 0.4, 0.4], UP, 0, view))).toBeGreaterThan(
10 * luma(shade(SKY.midnight, [0.4, 0.4, 0.4], UP, 0, view))
);
});
it('noon ambient matches sun.js diffuse at that moment to within a few percent (the gain)', () => {
const a = ambientColour(SKY.noonday);
const diffuse = [0.07, 0.132, 0.27]; // light() at 2026-09-22T12:00Z, 45N 0E, revision 7b4aa2f
for (let i = 0; i < 3; i += 1) expect(a[i] / diffuse[i]).toBeGreaterThan(0.85);
for (let i = 0; i < 3; i += 1) expect(a[i] / diffuse[i]).toBeLessThan(1.2);
it('the cold tint (albedo) is 0 with the sun up and 1 once it is below -6', () => {
expect(coldness(SKY.noonday)).toBe(0);
expect(coldness(SKY.midnight)).toBe(1);
expect(hazeColour(SKY.noonday)).toEqual(SKY.noonday.horizon);
});
});
describe('the scattered sky', () => {
it('noon is blue overhead: more blue than red, much brighter than the night glow', () => {
const zenith = skyColour(SKY.noonday, [0, 1, 0]);
expect(zenith[2]).toBeGreaterThan(1.5 * zenith[0]);
expect(luma(zenith)).toBeGreaterThan(5 * luma(skyColour(SKY.midnight, [0, 1, 0])));
zenith.forEach((v) => expect(v).toBeLessThan(1));
});
it('a sun at the horizon reddens the sky toward it and darkens it away', () => {
const dusk = skyAtSun(-1, 270);
const toward = skyColour(dusk, look(3, 270));
const away = skyColour(dusk, look(3, 90));
const blueShare = (c: Vec3) => c[2] / (c[0] + c[1] + c[2]);
expect(blueShare(toward)).toBeLessThan(blueShare(away));
expect(luma(toward)).toBeGreaterThan(3 * luma(away));
});
it('under a deep night sun the tables are black and only the glow remains, brightest at the horizon', () => {
const d = SKY.midnight;
const horizon = skyColour(d, look(0, 180));
const zenith = skyColour(d, [0, 1, 0]);
horizon.forEach((v, i) => expect(v).toBeCloseTo(d.horizon[i], 6));
expect(luma(zenith)).toBeLessThan(luma(horizon));
expect(luma(zenith)).toBeGreaterThan(0.5 * luma(horizon));
});
it('the night glow fades out as the sun reaches the horizon', () => {
expect(nightness(-10)).toBe(1);
expect(nightness(5)).toBe(0);
expect(glowColour(SKY.noonday)).toEqual([0, 0, 0]);
expect(glowColour(SKY.midnight)).toEqual(SKY.midnight.horizon);
expect(luma(glowColour(skyAtSun(-2)))).toBeLessThan(luma(glowColour(skyAtSun(-6))));
});
it('is continuous in the sun’s elevation through dusk: no step between neighbours', () => {
const at = (e: number) => luma(skyColour(skyAtSun(e, 270), look(10, 200)));
for (let e = -20; e < 30; e += 0.5) {
expect(Math.abs(at(e + 0.5) - at(e))).toBeLessThan(0.05);
}
});
});
@ -124,24 +193,33 @@ describe('haze', () => {
}
});
it('far surfaces take the horizon colour of the baked gradient, at both skies', () => {
for (const d of Object.values(SKY)) {
const far = shade(d, [0.9, 0.2, 0.1], UP, 100000);
const h = hazeColour(d);
for (let i = 0; i < 3; i += 1) expect(far[i]).toBeCloseTo(h[i], 6);
it('far surfaces take the scattered sky at the horizon in their azimuth, at both skies', () => {
for (const d of [...Object.values(SKY), skyAtSun(2, 270)]) {
const far = shade(d, [0.9, 0.2, 0.1], UP, 100000, look(-3, 200));
const sky = skyColour(d, look(0, 200));
for (let i = 0; i < 3; i += 1) expect(far[i]).toBeCloseTo(sky[i], 6);
}
expect(hazeColour(SKY.noonday)).toEqual(hexToLinear('#e2f4ff'));
expect(hazeColour(SKY.midnight)).toEqual(hexToLinear('#484e64'));
});
it('haze toward the dusk sun is warmer and brighter than haze away from it', () => {
const dusk = skyAtSun(-1, 270);
const toward = shade(dusk, [0, 0, 0], UP, 100000, look(-3, 270));
const away = shade(dusk, [0, 0, 0], UP, 100000, look(-3, 90));
const blueShare = (c: Vec3) => c[2] / (c[0] + c[1] + c[2]);
expect(luma(toward)).toBeGreaterThan(3 * luma(away));
expect(blueShare(toward)).toBeLessThan(blueShare(away));
});
it('haze colour differs between the two skies: pale day horizon, dim night one', () => {
expect(luma(hazeColour(SKY.noonday))).toBeGreaterThan(5 * luma(hazeColour(SKY.midnight)));
const far = (d: typeof SKY.midnight) => luma(shade(d, [0, 0, 0], UP, 1e6, look(-3, 180)));
expect(far(SKY.noonday)).toBeGreaterThan(5 * far(SKY.midnight));
});
it('with distance a dark surface rises toward the haze and a bright one falls toward it', () => {
const d = SKY.noonday;
const h = luma(hazeColour(d));
const dark = (x: number) => luma(shade(d, [0.02, 0.02, 0.02], UP, x));
const view = look(-4, 200);
const h = luma(skyColour(d, look(0, 200)));
const dark = (x: number) => luma(shade(d, [0.02, 0.02, 0.02], UP, x, view));
expect(dark(2000)).toBeGreaterThan(dark(200));
expect(dark(2000)).toBeLessThan(h);
});

View file

@ -1,8 +1,25 @@
// Lighting and haze for the terrain scene, as pure functions of one sky's baked numbers (./skyData.ts).
// No DOM, no GL. The fragment shader does the same arithmetic with these results as uniforms.
// Lighting, haze and sky for the terrain scene, as pure functions of one sky's baked numbers (src/sky/baked.ts, Void's
// bake, GameCult/Void PR #22). No DOM, no GL. The fragment shaders do the same arithmetic with these results as uniforms.
import { baked } from '../../../../sky/baked';
import { isNight } from '../ridge/stars';
import type { SkyColours } from '../ridge/skyColour';
import { SKY, SkyData, SkyName, Vec3 } from './skyData';
import { HORIZON_FLOOR, scatterRadiance, transmittanceAt } from './terrainScatter';
export type SkyName = 'midnight' | 'noonday';
export type Vec3 = readonly [number, number, number];
export interface SkyData {
/** Degrees above the horizon, no refraction. Negative: the sun is down. */
elevation: number;
/** Degrees clockwise from north. */
azimuth: number;
/** Sun colour at normal incidence, linear RGB. Black when the sun is down. */
direct: Vec3;
/** Sky ambient on an upward surface, linear RGB; at night a moonlit floor, not black. */
ambient: Vec3;
/** The horizon, linear RGB: the baked `horizon_hex`. */
horizon: Vec3;
}
const RAD = Math.PI / 180;
const clamp01 = (x: number) => Math.min(1, Math.max(0, x));
@ -10,6 +27,8 @@ const smooth = (a: number, b: number, x: number) => {
const t = clamp01((x - a) / (b - a));
return t * t * (3 - 2 * t);
};
const mixVec = (a: Vec3, b: Vec3, t: number): Vec3 =>
[0, 1, 2].map((i) => a[i] + (b[i] - a[i]) * t) as unknown as Vec3;
/** Which baked sky a ridge-style `SkyColours` means: the night notion the stars use (`isNight`). */
export const skyNameFor = (sky: SkyColours): SkyName => (isNight(sky) ? 'midnight' : 'noonday');
@ -25,6 +44,39 @@ export function hexToLinear(hex: string): Vec3 {
return [ch(1), ch(3), ch(5)];
}
const fromBaked = (b: typeof baked.midnight | typeof baked.noonday): SkyData => ({
elevation: b.sun.elevation_deg,
azimuth: b.sun.azimuth_deg,
direct: b.sun.color_linear,
ambient: b.ambient_linear,
horizon: hexToLinear(b.horizon_hex),
});
export const SKY: Record<SkyName, SkyData> = {
midnight: fromBaked(baked.midnight),
noonday: fromBaked(baked.noonday),
};
export const skyData = (name: SkyName): SkyData => SKY[name];
/**
* A sky for a sun at any elevation, between the two baked ones. The sun's colour is the baked transmittance at
* that elevation, faded out across the disc's last degrees the way sun.js does (gone at -0.83, whole by 1.5);
* ambient and horizon blend from the midnight bake to the noonday one as the sun climbs from -8 to 25 degrees.
*/
export function skyAtSun(elevation: number, azimuth: number = SKY.noonday.azimuth): SkyData {
const day = smooth(-8, 25, elevation);
const fade = smooth(-0.83, 1.5, elevation);
const t = transmittanceAt(Math.max(elevation, -4));
return {
elevation,
azimuth,
direct: [t[0] * fade, t[1] * fade, t[2] * fade],
ambient: mixVec(SKY.midnight.ambient, SKY.noonday.ambient, day),
horizon: mixVec(SKY.midnight.horizon, SKY.noonday.horizon, day),
};
}
/** Unit vector toward the sun: x east, y up, z south (so azimuth 0, north, is -z). */
export function sunDirection(d: SkyData): Vec3 {
const el = d.elevation * RAD;
@ -32,59 +84,68 @@ export function sunDirection(d: SkyData): Vec3 {
return [Math.sin(az) * Math.cos(el), Math.sin(el), -Math.cos(az) * Math.cos(el)];
}
/**
* The sun's colour as the ground sees it: baked `direct`, off at the horizon the way sun.js fades the disc
* (gone at -0.83 degrees, soft to 1.5). A sun below the horizon lights nothing.
*/
export function sunColour(d: SkyData): Vec3 {
const k = smooth(-0.83, 1.5, d.elevation);
return [d.direct[0] * k, d.direct[1] * k, d.direct[2] * k];
}
/**
* Ambient light on an upward surface, from the baked gradient's zenith stop. The gain is chosen so the
* noonday value (0.075, 0.14, 0.25) matches sun.js's own `diffuse` there (0.07, 0.13, 0.27); at midnight
* the same gain turns the gradient's glow into a faint moonlit fill, where `diffuse` alone would be black.
*/
export const AMBIENT_GAIN = 0.25;
/** 0 with the sun well up, 1 once it is below -6 degrees (civil twilight over): the night notion the palette and fill share. */
/** 0 with the sun well up, 1 once it is below -6 degrees (civil twilight over): the night notion the palette shares. */
export const coldness = (d: SkyData): number => 1 - smooth(-6, 25, d.elevation);
/** Extra ambient at night, so a moonlit face is readable and not black on a phone: x4 at full night, 1 by day. */
export const NIGHT_LIFT = 4;
/** The colour distance fades to when the air has nothing to scatter: the baked horizon. Albedo tints toward it at night. */
export const hazeColour = (d: SkyData): Vec3 => d.horizon;
export function ambientColour(d: SkyData): Vec3 {
const z = hexToLinear(d.gradient[0]);
const k = AMBIENT_GAIN * (1 + (NIGHT_LIFT - 1) * coldness(d));
return [z[0] * k, z[1] * k, z[2] * k];
/** Sky radiance (see the sun's `skyScatter` in terrainScatter.ts) is for unit sun irradiance; this lifts it to the image. EYEBALLED. */
export const SKY_EXPOSURE = 45;
/** How far the night glow dims from the horizon to the zenith (1 at the horizon). EYEBALLED. */
export const GLOW_ZENITH = 0.75;
/** 1 with the sun below -4 degrees, 0 above 4: where the midnight horizon colour stands in for light the single-scattering tables lack. */
export const nightness = (elevation: number): number => 1 - smooth(-4, 4, elevation);
/** The night glow colour: the midnight bake's horizon, fading out as the sun nears the horizon (whatever horizon the day blend gives `d`). */
export const glowColour = (d: SkyData): Vec3 => {
const k = nightness(d.elevation);
const h = SKY.midnight.horizon;
return [h[0] * k, h[1] * k, h[2] * k];
};
/**
* Linear colour of the sky along a unit view direction (x east, y up, z south): the baked single-scattering
* radiance for this sun, lifted by SKY_EXPOSURE and tone-mapped `1 - exp(-x)`, plus the night glow, which sits
* brightest at the horizon; at and below the horizon, the horizon's colour. The fragment shader does the same.
*/
export function skyColour(d: SkyData, dir: Vec3): Vec3 {
const el = Math.max(HORIZON_FLOOR, Math.asin(Math.min(1, Math.max(-1, dir[1]))) / RAD);
const sun = sunDirection(d);
const h = Math.hypot(dir[0], dir[2]);
const s = Math.hypot(sun[0], sun[2]);
const az =
h < 1e-4 || s < 1e-4
? 0
: Math.acos(Math.min(1, Math.max(-1, (dir[0] * sun[0] + dir[2] * sun[2]) / (h * s)))) / RAD;
const r = scatterRadiance(d.elevation, el, az);
const glow = glowColour(d);
const shape = 1 + (GLOW_ZENITH - 1) * Math.sqrt(clamp01(dir[1]));
return [0, 1, 2].map(
(i) => 1 - Math.exp(-SKY_EXPOSURE * r[i]) + glow[i] * shape
) as unknown as Vec3;
}
/** The colour distance fades to: the gradient's horizon stop, linear. */
export const hazeColour = (d: SkyData): Vec3 => hexToLinear(d.gradient[d.gradient.length - 1]);
/** Haze: transmittance T = exp(-k d) at distance d metres. */
export const HAZE_K = 0.0004;
export const transmittance = (distance: number): number =>
Math.exp(-HAZE_K * Math.max(0, distance));
/**
* Linear colour of a surface: lambert from the sun plus ambient (full on an upward face, half on a
* vertical one, none on a downward one: `0.5 + 0.5 n.y`), then hazed toward the horizon colour by distance.
* `normal` is a unit vector. Never negative, whatever the sun does.
* Linear colour of a surface seen along the unit direction `view` (from the eye to the surface): lambert from
* the sun plus ambient (full on an upward face, half on a vertical one, none on a downward one: `0.5 + 0.5 n.y`),
* then hazed by distance toward the sky at the horizon in that direction. `normal` is a unit vector. Never negative.
*/
export function shade(d: SkyData, albedo: Vec3, normal: Vec3, distance: number): Vec3 {
export function shade(d: SkyData, albedo: Vec3, normal: Vec3, distance: number, view: Vec3): Vec3 {
const sun = sunDirection(d);
const lambert = Math.max(0, normal[0] * sun[0] + normal[1] * sun[1] + normal[2] * sun[2]);
const direct = sunColour(d);
const amb = ambientColour(d);
const hemi = 0.5 + 0.5 * normal[1];
const haze = hazeColour(d);
const flat = Math.hypot(view[0], view[2]) || 1;
const haze = skyColour(d, [view[0] / flat, 0, view[2] / flat]);
const t = transmittance(distance);
return [0, 1, 2].map((i) => {
const lit = albedo[i] * (direct[i] * lambert + amb[i] * Math.max(0, hemi));
const lit = albedo[i] * (d.direct[i] * lambert + d.ambient[i] * Math.max(0, hemi));
return lit * t + haze[i] * (1 - t);
}) as unknown as Vec3;
}
export const skyData = (name: SkyName): SkyData => SKY[name];

View file

@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-empty-function -- DOM stubs, as the other scene tests */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { SKY } from './skyData';
import { SKY, skyAtSun } from './terrainSky';
import {
BRIGHTEN,
createTerrainStars,
@ -9,12 +9,12 @@ import {
FRAME_MS,
horizonY,
PERIOD,
nightColours,
project,
skyColoursOf,
starGain,
} from './terrainStars';
import { CAMERA, view } from './terrainWorld';
import { isNight, makeStars } from '../ridge/stars';
import { skyNameFor } from './terrainSky';
/** A 2D context that only counts: arcs painted and clears since the last reset. */
function fakeCtx() {
@ -64,10 +64,21 @@ const glCanvas = (w = 390, h = 844) =>
({ clientWidth: w, clientHeight: h, parentElement: parent } as any);
describe('which skies get stars', () => {
it("midnight is dark, noonday is not, by the ridge module's own test", () => {
expect(isNight(skyColoursOf(SKY.midnight))).toBe(true);
expect(isNight(skyColoursOf(SKY.noonday))).toBe(false);
expect(skyNameFor(skyColoursOf(SKY.noonday))).toBe('noonday');
it('the field is placed against the baked night gradient, which the ridge module calls dark', () => {
expect(isNight(nightColours())).toBe(true);
});
it('starGain: full below -12 degrees, none above -6, smooth and monotone between', () => {
expect(starGain(-44.6)).toBe(1);
expect(starGain(-12)).toBe(1);
expect(starGain(-6)).toBe(0);
expect(starGain(45.2)).toBe(0);
expect(starGain(-9)).toBeCloseTo(0.5, 9);
let prev = 1;
for (let e = -12; e <= -6; e += 0.25) {
expect(starGain(e)).toBeLessThanOrEqual(prev);
prev = starGain(e);
}
});
it('noonday gets no layer and no element', () => {
@ -75,6 +86,17 @@ describe('which skies get stars', () => {
expect(parent.appendChild).not.toHaveBeenCalled();
});
it('twilight is a fade, not a gate: a sun at -9 degrees paints the stars at half alpha', () => {
createTerrainStars(glCanvas(), skyAtSun(-9))?.draw(0);
const half = Math.max(...ctx2d.c.alphas);
ctx2d.c.alphas = [];
createTerrainStars(glCanvas(), SKY.midnight)?.draw(0);
expect(half).toBeGreaterThan(0);
expect(half / Math.max(...ctx2d.c.alphas)).toBeCloseTo(0.5, 6);
expect(createTerrainStars(glCanvas(), skyAtSun(-6.5))).not.toBeNull();
expect(createTerrainStars(glCanvas(), skyAtSun(-6))).toBeNull();
});
it('midnight adds one overlay to the canvas parent; dispose removes it', () => {
const s = createTerrainStars(glCanvas(), SKY.midnight)!;
expect(parent.appendChild).toHaveBeenCalledWith(overlay);
@ -172,12 +194,10 @@ describe('turning with the camera', () => {
describe('brightness', () => {
it('draws every star at BRIGHTEN times its ridge-field alpha, capped at 1', () => {
createTerrainStars(glCanvas(), SKY.midnight)?.draw(0);
const want = makeStars(skyColoursOf(SKY.midnight), 390, 844).map((st) =>
Math.min(1, st.alpha * BRIGHTEN)
);
const want = makeStars(nightColours(), 390, 844).map((st) => Math.min(1, st.alpha * BRIGHTEN));
ctx2d.c.alphas.forEach((a) => expect(want.some((w) => Math.abs(w - a) < 1e-9)).toBe(true));
// and it is brighter than the ridge field's own top alpha
const top = Math.max(...makeStars(skyColoursOf(SKY.midnight), 390, 844).map((st) => st.alpha));
const top = Math.max(...makeStars(nightColours(), 390, 844).map((st) => st.alpha));
expect(Math.max(...ctx2d.c.alphas)).toBeGreaterThan(top * 1.5);
});
});

View file

@ -1,5 +1,5 @@
// The terrain scene's star layer: the ridge scene's starfield (ridge/stars.ts: placement, alpha, tint, the
// rolling twinkle schedule) on a 2D overlay canvas above the WebGL canvas, shown only when the baked sky is dark.
// rolling twinkle schedule) on a 2D overlay canvas above the WebGL canvas, faded by the sun's elevation (starGain).
//
// The WebGL canvas is opaque, so the overlay sits on top and is cut to the sky: it is only as tall as the
// horizon line is low on screen. The camera has no roll and the eye (CAMERA.eye) is above the highest peak
@ -13,9 +13,10 @@
// the layer only paints when Terrain.ts draws, and a draw with no clock (reduced motion, still tier, resize)
// paints every star at base brightness.
import { baked } from '../../../../sky/baked';
import type { SkyColours, Srgb } from '../ridge/skyColour';
import { activeAt, isNight, makeStars, SKY_STOPS, Star } from '../ridge/stars';
import { SkyData } from './skyData';
import { activeAt, makeStars, SKY_STOPS, Star } from '../ridge/stars';
import { SkyData } from './terrainSky';
import { CAMERA } from './terrainWorld';
/** Azimuth the star field repeats at (radians); wider than any horizontal field of view the layer is shown at. */
@ -30,9 +31,19 @@ const TWINKLE_MS = 50;
const hex = (h: string): Srgb =>
[1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16)) as unknown as Srgb;
/** The ridge star module's view of a baked terrain sky: zenith, the middle stop, and the horizon stop. */
export function skyColoursOf(d: SkyData): SkyColours {
const g = d.gradient;
/**
* How much of the starfield shows with the sun at `elevation` degrees: all of it below -12 (where the baked
* scattering goes dark: the planet's shadow covers every sunlit air path), none above -6 (civil twilight), a smooth
* fade between. Not a dark/day gate: a sun at -9 shows the stars at half.
*/
export function starGain(elevation: number): number {
const t = Math.min(1, Math.max(0, (elevation + 12) / 6));
return 1 - t * t * (3 - 2 * t);
}
/** The ridge star module's view of the night sky it places stars against: the baked midnight gradient's zenith, middle and horizon stops. */
export function nightColours(): SkyColours {
const g = baked.midnight.gradient;
return {
top: hex(g[0]),
mid: hex(g[Math.floor(g.length / 2)]),
@ -84,11 +95,12 @@ export interface TerrainStars {
dispose(): void;
}
/** The layer for `canvas`'s parent, or null: a day sky, no parent, no 2D context. */
/** The layer for `canvas`'s parent, or null: the sun is too high for any star, no parent, no 2D context. */
export function createTerrainStars(canvas: HTMLCanvasElement, sky: SkyData): TerrainStars | null {
const colours = skyColoursOf(sky);
const colours = nightColours();
const gain = starGain(sky.elevation);
const parent = canvas.parentElement;
if (!parent || !isNight(colours)) return null;
if (!parent || gain <= 0) return null;
const el = document.createElement('canvas');
const ctx = el.getContext?.('2d');
if (!ctx) return null;
@ -129,8 +141,8 @@ export function createTerrainStars(canvas: HTMLCanvasElement, sky: SkyData): Ter
const yaw = 2 * Math.PI * turns;
lit.forEach(({ star, az, e }, i) => {
const da = wrap(az - yaw);
const gain = seconds === undefined ? 1 : gains.get(i) ?? 1;
ctx.globalAlpha = Math.min(1, star.alpha * gain * BRIGHTEN);
const twinkle = seconds === undefined ? 1 : gains.get(i) ?? 1;
ctx.globalAlpha = Math.min(1, star.alpha * twinkle * BRIGHTEN) * gain;
ctx.fillStyle = star.fill;
[da, da > 0 ? da - PERIOD : da + PERIOD].forEach((d) => {
const at = project(d, e, w, h);