diff --git a/src/app/features/scene/terrain/Terrain.test.ts b/src/app/features/scene/terrain/Terrain.test.ts index 8338721e..4578a58a 100644 --- a/src/app/features/scene/terrain/Terrain.test.ts +++ b/src/app/features/scene/terrain/Terrain.test.ts @@ -233,3 +233,87 @@ describe("startBackgroundScene style 'terrain'", () => { expect(c2.getContext).not.toHaveBeenCalledWith('webgl2', expect.anything()); }); }); + +describe('stars in the terrain scene', () => { + let overlays: any[]; + let arcs: number; + const withOverlays = () => { + overlays = []; + arcs = 0; + (document as any).createElement = () => { + const el: any = { + style: {}, + remove: vi.fn(), + setAttribute() {}, + getContext: () => ({ + clearRect() {}, + beginPath() {}, + fill() {}, + arc: () => (arcs += 1), + }), + }; + overlays.push(el); + return el; + }; + }; + const scene = (sky: 'midnight' | 'noonday', tier: 'still' | 'low' = 'low') => { + withOverlays(); + const canvas = canvasWith(fakeGl().gl); + const s = createTerrainScene({ canvas, tier, sky })!; + return { s, canvas }; + }; + + it('a midnight sky gets one star overlay beside the canvas, painted with the terrain', () => { + const { s, canvas } = scene('midnight'); + expect(overlays).toHaveLength(1); + expect(canvas.parentElement.appendChild).toHaveBeenCalledWith(overlays[0]); + rafQueue.shift()!(16); + expect(arcs).toBeGreaterThan(0); + s.dispose(); + expect(overlays[0].remove).toHaveBeenCalledOnce(); + }); + + it('a noonday sky gets no overlay and paints no stars', () => { + const { s } = scene('noonday'); + expect(overlays).toHaveLength(0); + expect(arcs).toBe(0); + s.dispose(); + }); + + it("'still' paints the stars once at base and queues nothing", () => { + const { s } = scene('midnight', 'still'); + expect(arcs).toBeGreaterThan(0); + expect(rafQueue).toHaveLength(0); + s.dispose(); + }); + + it('a hidden tab or reduced motion paints no more stars than the first frame', () => { + visibility = 'hidden'; + const { s } = scene('midnight'); + const n = arcs; + expect(n).toBeGreaterThan(0); + expect(rafQueue).toHaveLength(0); // the terrain loop never starts, so nothing repaints the stars + s.dispose(); + visibility = 'visible'; + (window as any).matchMedia = () => ({ + matches: true, + addEventListener() {}, + removeEventListener() {}, + }); + const r = scene('midnight'); + expect(rafQueue).toHaveLength(0); + expect(arcs).toBe(n); + r.s.dispose(); + }); + + it('stars turn with the terrain: a later frame is painted at a later heading', () => { + let clock = 0; + vi.stubGlobal('performance', { now: () => (clock += 1000) }); + const { s } = scene('midnight'); + rafQueue.shift()!(16); + const first = arcs; + rafQueue.shift()!(1000); + expect(arcs).toBeGreaterThan(first); + s.dispose(); + }); +}); diff --git a/src/app/features/scene/terrain/Terrain.ts b/src/app/features/scene/terrain/Terrain.ts index 2a81aa56..94fd554a 100644 --- a/src/app/features/scene/terrain/Terrain.ts +++ b/src/app/features/scene/terrain/Terrain.ts @@ -21,6 +21,7 @@ import { heightFragmentSource, SKY_FRAG, } from './terrainShaders'; +import { createTerrainStars } from './terrainStars'; export type TerrainOptions = Pick< SceneOptions, @@ -172,6 +173,7 @@ export function createTerrainScene(opts: TerrainOptions): Scene | null { const haze = [...hazeColour(sky)]; const triangles = triangleCount(spec.grid); + const stars = createTerrainStars(canvas, sky); const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)'); const sampler = new FrameSampler(); let still = tier === 'still'; @@ -224,6 +226,7 @@ export function createTerrainScene(opts: TerrainOptions): Scene | null { gl.bindVertexArray(vao); gl.drawElements(gl.TRIANGLES, g.indices.length, gl.UNSIGNED_INT, 0); gl.bindVertexArray(null); + stars?.draw(turns % 1, moving() ? performance.now() / 1000 : undefined); }; const moving = () => @@ -331,6 +334,7 @@ export function createTerrainScene(opts: TerrainOptions): Scene | null { resizeTimer = window.setTimeout(() => { if (disposed || lost) return; size(); + stars?.resize(); draw(turnsNow(performance.now())); sampler.reset(); }, 250); @@ -353,6 +357,7 @@ export function createTerrainScene(opts: TerrainOptions): Scene | null { reducedMotion?.removeEventListener?.('change', onVisibility); canvas.removeEventListener('webglcontextlost', onLost); readout?.remove(); + stars?.dispose(); release(); }, }; diff --git a/src/app/features/scene/terrain/terrainStars.test.ts b/src/app/features/scene/terrain/terrainStars.test.ts new file mode 100644 index 00000000..40020186 --- /dev/null +++ b/src/app/features/scene/terrain/terrainStars.test.ts @@ -0,0 +1,207 @@ +/* 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 { + createTerrainStars, + elevationOf, + ELEVATION_TOP, + FRAME_MS, + horizonY, + PERIOD, + project, + skyColoursOf, +} from './terrainStars'; +import { CAMERA, view } from './terrainWorld'; +import { isNight } from '../ridge/stars'; +import { skyNameFor } from './terrainSky'; + +/** A 2D context that only counts: arcs painted and clears since the last reset. */ +function fakeCtx() { + const c = { + arcs: [] as Array<[number, number, number]>, + clears: 0, + alpha: 1, + alphas: [] as number[], + }; + const ctx: any = { + clearRect: () => { + c.clears += 1; + c.arcs = []; + c.alphas = []; + }, + beginPath() {}, + fill() { + c.alphas.push(ctx.globalAlpha); + }, + arc: (x: number, y: number, r: number) => c.arcs.push([x, y, r]), + globalAlpha: 1, + fillStyle: '', + }; + return { c, ctx }; +} + +let overlay: any; +let ctx2d: ReturnType; +let parent: any; +beforeEach(() => { + ctx2d = fakeCtx(); + overlay = { + style: {}, + width: 0, + height: 0, + setAttribute: vi.fn(), + getContext: vi.fn(() => ctx2d.ctx), + remove: vi.fn(), + }; + parent = { appendChild: vi.fn() }; + vi.stubGlobal('document', { createElement: () => overlay }); + vi.stubGlobal('window', { devicePixelRatio: 1, innerWidth: 390, innerHeight: 844 }); +}); +afterEach(() => vi.unstubAllGlobals()); + +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('noonday gets no layer and no element', () => { + expect(createTerrainStars(glCanvas(), SKY.noonday)).toBeNull(); + expect(parent.appendChild).not.toHaveBeenCalled(); + }); + + it('midnight adds one overlay to the canvas parent; dispose removes it', () => { + const s = createTerrainStars(glCanvas(), SKY.midnight)!; + expect(parent.appendChild).toHaveBeenCalledWith(overlay); + s.dispose(); + expect(overlay.remove).toHaveBeenCalledOnce(); + }); + + it('is absent without a parent or a 2D context', () => { + expect( + createTerrainStars({ ...glCanvas(), parentElement: null } as any, SKY.midnight) + ).toBeNull(); + overlay.getContext = () => null; + expect(createTerrainStars(glCanvas(), SKY.midnight)).toBeNull(); + expect(parent.appendChild).not.toHaveBeenCalled(); + }); +}); + +describe('sky only', () => { + it('the overlay is as tall as the horizon line is low, never the whole screen', () => { + createTerrainStars(glCanvas(), SKY.midnight); + expect(overlay.height).toBe(Math.ceil(horizonY(844))); + expect(overlay.height).toBeLessThan(844 / 2); + expect(overlay.style.pointerEvents).toBe('none'); + }); + + it('a star at the horizon lands on the horizon line, one above it lands above', () => { + for (const aspect of [0.46, 1.78]) { + const h = 800; + const w = h * aspect; + const onLine = project(0.2, 0, w, h)!; + expect(onLine.y).toBeCloseTo(horizonY(h), 5); + expect(project(0.2, 0.05, w, h)!.y).toBeLessThan(horizonY(h)); + } + }); + + it('the camera eye clears the peaks, so the horizon line bounds the terrain', () => { + expect(CAMERA.eye).toBeGreaterThan(256); + }); + + it('every painted star is above the horizon line, at any heading', () => { + const s = createTerrainStars(glCanvas(), SKY.midnight)!; + for (let k = 0; k < 40; k += 1) { + s.draw(k / 40); + for (const [, y] of ctx2d.c.arcs) expect(y).toBeLessThanOrEqual(overlay.height); + } + }); + + it('agrees with the camera the terrain draws: the projection matches view()', () => { + const w = 390; + const h = 844; + const turns = 0.137; + const v = view(w / h, turns); + const yaw = 2 * Math.PI * turns; + const az = yaw + 0.1; + const e = 0.15; + const d = [Math.sin(az) * Math.cos(e), Math.sin(e), -Math.cos(az) * Math.cos(e)]; + const dot = (a: number[], b: readonly number[]) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + const t = Math.tan(CAMERA.fov / 2); + const f = dot(d, v.forward); + const nx = dot(d, v.right) / f / (t * (w / h)); + const ny = dot(d, v.up) / f / t; + const at = project(0.1, e, w, h)!; + expect(at.x).toBeCloseTo(((nx + 1) / 2) * w, 6); + expect(at.y).toBeCloseTo(((1 - ny) / 2) * h, 6); + }); +}); + +describe('turning with the camera', () => { + it('stars are on screen, and slide sideways as the camera turns', () => { + const s = createTerrainStars(glCanvas(), SKY.midnight)!; + s.draw(0); + const first = ctx2d.c.arcs.slice(); + expect(first.length).toBeGreaterThan(10); + s.draw(0.002); + const later = ctx2d.c.arcs; + expect(later).not.toEqual(first); + const m = (a: number[][]) => a.reduce((t, p) => t + p[0], 0) / a.length; + expect(m(later)).not.toBeCloseTo(m(first), 1); + }); + + it('repeats every PERIOD of heading', () => { + const s = createTerrainStars(glCanvas(), SKY.midnight)!; + s.draw(0.1); + const a = ctx2d.c.arcs.map((p) => p.map((n) => Math.round(n * 1e3))); + s.draw(0.1 + PERIOD / (2 * Math.PI)); + expect(ctx2d.c.arcs.map((p) => p.map((n) => Math.round(n * 1e3)))).toEqual(a); + }); + + it('the field fills the screen top and thins toward the horizon, inside the elevation band', () => { + expect(elevationOf(0)).toBeCloseTo(ELEVATION_TOP, 9); + expect(elevationOf(0.78)).toBeCloseTo(0, 9); + }); +}); + +describe('motion', () => { + it('with no clock every star is at base and a repeat draw repaints; no twinkle', () => { + const s = createTerrainStars(glCanvas(), SKY.midnight)!; + s.draw(0.3); + const alphas = ctx2d.c.alphas.slice(); + s.draw(0.3); + expect(ctx2d.c.alphas).toEqual(alphas); + }); + + it('with the clock the twinklers swing away from base, and the repaint is throttled', () => { + const s = createTerrainStars(glCanvas(), SKY.midnight)!; + s.draw(0.3); + const still = ctx2d.c.alphas.slice(); + let moved = false; + for (let t = 1; t < 60 && !moved; t += 1.7) { + s.draw(0.3, t); + moved = ctx2d.c.alphas.some((a, i) => a !== still[i]); + } + expect(moved).toBe(true); + const clears = ctx2d.c.clears; + s.draw(0.3, 100); + s.draw(0.3, 100 + FRAME_MS / 4000); + expect(ctx2d.c.clears).toBe(clears + 1); + }); + + it('resize refits the canvas and the next draw repaints at once', () => { + const c = glCanvas(); + const s = createTerrainStars(c, SKY.midnight)!; + s.draw(0.1, 5); + c.clientHeight = 400; + s.resize(); + expect(overlay.height).toBe(Math.ceil(horizonY(400))); + const clears = ctx2d.c.clears; + s.draw(0.1, 5.001); + expect(ctx2d.c.clears).toBe(clears + 1); + }); +}); diff --git a/src/app/features/scene/terrain/terrainStars.ts b/src/app/features/scene/terrain/terrainStars.ts new file mode 100644 index 00000000..e568418f --- /dev/null +++ b/src/app/features/scene/terrain/terrainStars.ts @@ -0,0 +1,157 @@ +// 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. +// +// 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 +// (TERRAIN.hmax), so terrain never rises above that line and a star above the horizon is never over terrain. +// +// Stars turn with the camera, as sky does: the ridge field's x becomes azimuth, repeated every PERIOD (so 400 +// stars fill a sky that only ever shows 55 deg to ~120 deg of it), and y becomes elevation from the horizon +// up to ELEVATION_TOP, the top of the screen. Placement is projected with the terrain's own camera (CAMERA, +// the yaw the terrain draws at), nothing is baked, and the whole overlay is redrawn at most every FRAME_MS: a +// visible star is a few arcs on a canvas a quarter of the screen tall. The stars stop when the terrain stops: +// 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 type { SkyColours, Srgb } from '../ridge/skyColour'; +import { activeAt, isNight, makeStars, SKY_STOPS, Star } from '../ridge/stars'; +import { SkyData } from './skyData'; +import { CAMERA } from './terrainWorld'; + +/** Azimuth the star field repeats at (radians); wider than any horizontal field of view the layer is shown at. */ +export const PERIOD = (2 * Math.PI) / 3; +/** Elevation of the field's top, radians: a little above the top edge of the screen at the camera's pitch. */ +export const ELEVATION_TOP = (16 * Math.PI) / 180; +/** The overlay repaints at most this often while the terrain turns (12 px/s on a phone: under half a pixel a step). */ +export const FRAME_MS = 33; +/** The twinkle schedule is re-read this often; the swings are 2 to 7 s. */ +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; + return { + top: hex(g[0]), + mid: hex(g[Math.floor(g.length / 2)]), + horizon: hex(g[g.length - 1]), + ground: [0, 0, 0], + }; +} + +/** Screen height in px below which there is no sky: where the horizon plane meets the image, a straight line. */ +export const horizonY = (height: number): number => + height * (0.5 - Math.tan(CAMERA.pitch) / Math.tan(CAMERA.fov / 2) / 2); + +export interface Placed { + x: number; + y: number; +} + +/** + * Where a star at azimuth `da` from the camera's heading and elevation `e` (radians) lands in a `w` x `h` px + * viewport, or null if it is behind or off the screen. The same camera as `view()` in terrainWorld.ts + * (forward, right and up are its basis written out for a camera with yaw and pitch only). + */ +export function project(da: number, e: number, w: number, h: number): Placed | null { + const p = CAMERA.pitch; + const ce = Math.cos(e); + const front = ce * Math.cos(p) * Math.cos(da) - Math.sin(e) * Math.sin(p); + if (front <= 0.01) return null; + const tanHalf = Math.tan(CAMERA.fov / 2); + const nx = (ce * Math.sin(da)) / front / (tanHalf * (w / h)); + const ny = (ce * Math.sin(p) * Math.cos(da) + Math.sin(e) * Math.cos(p)) / front / tanHalf; + if (Math.abs(nx) > 1.05) return null; + return { x: ((nx + 1) / 2) * w, y: ((1 - ny) / 2) * h }; +} + +/** Elevation in radians for a ridge-field height fraction y (0 zenith side .. SKY_STOPS.horizon at the horizon). */ +export const elevationOf = (y: number): number => ELEVATION_TOP * (1 - y / SKY_STOPS.horizon); + +const wrap = (a: number): number => a - PERIOD * Math.round(a / PERIOD); + +export interface TerrainStars { + /** Paint for the camera `turns` into its turn (0..1). `seconds` is the clock while the terrain moves; absent: every star at base. */ + draw(turns: number, seconds?: number): void; + /** Re-fit the overlay to the canvas's current size; the next draw repaints. */ + resize(): void; + dispose(): void; +} + +/** The layer for `canvas`'s parent, or null: a day sky, no parent, no 2D context. */ +export function createTerrainStars(canvas: HTMLCanvasElement, sky: SkyData): TerrainStars | null { + const colours = skyColoursOf(sky); + const parent = canvas.parentElement; + if (!parent || !isNight(colours)) return null; + const el = document.createElement('canvas'); + const ctx = el.getContext?.('2d'); + if (!ctx) return null; + el.setAttribute?.('aria-hidden', 'true'); + Object.assign(el.style, { position: 'absolute', left: '0', top: '0', pointerEvents: 'none' }); + parent.appendChild(el); + + let w = 1; + let h = 1; + let scale = 1; + let field: Star[] = []; + let lit: Array<{ star: Star; az: number; e: number }> = []; + let gains = new Map(); + let gainsAt = -Infinity; + let last = -Infinity; + + const fit = () => { + w = canvas.clientWidth || window.innerWidth; + h = canvas.clientHeight || window.innerHeight; + scale = Math.min(window.devicePixelRatio || 1, 2); + const sky = Math.max(1, Math.ceil(horizonY(h))); + el.width = Math.max(1, Math.round(w * scale)); + el.height = Math.max(1, Math.round(sky * scale)); + el.style.width = `${w}px`; + el.style.height = `${sky}px`; + field = makeStars(colours, w, h); + lit = field.map((star) => ({ star, az: star.x * PERIOD, e: elevationOf(star.y) })); + gains = new Map(); + gainsAt = -Infinity; + }; + + const paint = (turns: number, seconds: number | undefined) => { + ctx.clearRect(0, 0, el.width, el.height); + if (seconds !== undefined && seconds * 1000 - gainsAt >= TWINKLE_MS) { + gains = new Map(activeAt(field.length, seconds).map((a) => [a.star, a.gain])); + gainsAt = seconds * 1000; + } + 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); + ctx.fillStyle = star.fill; + [da, da > 0 ? da - PERIOD : da + PERIOD].forEach((d) => { + const at = project(d, e, w, h); + if (!at || at.y < 0 || at.y > el.height / scale) return; + ctx.beginPath(); + ctx.arc(at.x * scale, at.y * scale, star.r * scale, 0, 2 * Math.PI); + ctx.fill(); + }); + }); + ctx.globalAlpha = 1; + }; + + fit(); + return { + draw(turns, seconds) { + if (seconds !== undefined && seconds * 1000 - last < FRAME_MS) return; + last = seconds === undefined ? -Infinity : seconds * 1000; + paint(turns, seconds); + }, + resize() { + fit(); + last = -Infinity; + }, + dispose() { + el.remove(); + }, + }; +}