Add Morning Flight meditation with chase-camera Cessna landing scene

- New 5-minute "Morning Flight" meditation: fly behind a small Cessna over farmland and past a city, then descend and land at daybreak as the sun rises over the mountains
- Scene rendered per-pixel from world-space geometry: ray-traced building boxes with lit windows, procedurally filtered ground (fields, suburbs, runway), two cloud decks, dawn sky with stars, sun glow and rays, plus airport details like the tower beacon and windsock
- Chase camera follows an integrated speed/distance profile so altitude, propeller spin and lighting all stay pure functions of time
- Extend AmbientLoop with optional `until`/`fadeOut` so the engine drone can stop at the prop-down moment instead of running to the end; wire it through the Meditation type and Player
This commit is contained in:
Brian Fertig 2026-10-31 14:24:42 -06:00
parent 080321938d
commit e6da313b61
19 changed files with 2196 additions and 6 deletions

Binary file not shown.

BIN
public/audio/fx-plane.mp3 Normal file

Binary file not shown.

Binary file not shown.

View File

@ -49,7 +49,7 @@ export class Music {
/** /**
* A gapless looping ambient sound (Web Audio), locked to the meditation clock: at time t it plays * A gapless looping ambient sound (Web Audio), locked to the meditation clock: at time t it plays
* from (t - from) mod loopLength, so visuals keyed to the loop (e.g. waves) stay in sync with what * from (t - from) mod loopLength, so visuals keyed to the loop (e.g. waves) stay in sync with what
* is heard. Before `from` it is silent. * is heard. Before `from` it is silent, and it fades out to end at `until` (default: the meditation's end).
*/ */
export class AmbientLoop { export class AmbientLoop {
private ctx?: AudioContext; private ctx?: AudioContext;
@ -66,6 +66,7 @@ export class AmbientLoop {
private readonly fadeIn = 4, private readonly fadeIn = 4,
private readonly fadeOut = 10, private readonly fadeOut = 10,
private readonly from = 0, private readonly from = 0,
private readonly until?: number,
) {} ) {}
/** Position in the file at meditation time t. */ /** Position in the file at meditation time t. */
@ -103,7 +104,8 @@ export class AmbientLoop {
update(t: number, duration: number): void { update(t: number, duration: number): void {
this.lastT = t; this.lastT = t;
if (!this.ctx || !this.master) return; if (!this.ctx || !this.master) return;
const k = Math.max(0, Math.min(1, (t - this.from) / this.fadeIn, (duration - t) / this.fadeOut)); const end = this.until ?? duration;
const k = Math.max(0, Math.min(1, (t - this.from) / this.fadeIn, (end - t) / this.fadeOut));
this.master.gain.setTargetAtTime(k * this.volume, this.ctx.currentTime, 0.1); this.master.gain.setTargetAtTime(k * this.volume, this.ctx.currentTime, 0.1);
if (!this.playing || !this.source || !this.buffer) return; if (!this.playing || !this.source || !this.buffer) return;
const len = this.buffer.duration; const len = this.buffer.duration;

View File

@ -0,0 +1,74 @@
import { hex, mix } from '../../engine/color';
import type { Surface } from '../../engine/Surface';
import type { Box } from './city';
import { lamp } from './lights';
import type { Frame } from './timeline';
import { APRON, project, STOP_Z } from './world';
/** Hangars, a small terminal and the control tower along the apron, west of the runway. */
const HANGAR = hex('#8c949c');
const HANGAR_ROOF = hex('#6c7278');
const TERMINAL = hex('#b8b0a0');
const TOWER = { x: -262, z: STOP_Z + 860, h: 22 };
export const AIRPORT_BOXES: readonly Box[] = [
...[0, 1, 2].map(
(i): Box => ({
x0: APRON.x0 - 44,
x1: APRON.x0,
z0: APRON.z0 + 150 + i * 80,
z1: APRON.z0 + 210 + i * 80,
y0: 0,
h: 13 + (i % 2) * 2,
wall: HANGAR,
roof: HANGAR_ROOF,
door: { open: i === 1 ? 0.45 : 0 },
}),
),
{ x0: APRON.x0 - 30, x1: APRON.x0 - 4, z0: APRON.z0 + 420, z1: APRON.z0 + 480, y0: 0, h: 7, wall: TERMINAL, roof: HANGAR_ROOF, windows: { lit: 0.6, seed: 5 } },
{ x0: TOWER.x - 4, x1: TOWER.x + 4, z0: TOWER.z - 4, z1: TOWER.z + 4, y0: 0, h: TOWER.h, wall: TERMINAL, roof: HANGAR_ROOF },
{ x0: TOWER.x - 6, x1: TOWER.x + 6, z0: TOWER.z - 6, z1: TOWER.z + 6, y0: TOWER.h, h: TOWER.h + 5, wall: HANGAR_ROOF, roof: HANGAR_ROOF, glass: hex('#9affc8') },
];
const GREEN = hex('#6aff9a');
const WHITE = hex('#ffffff');
const POLE = hex('#c8c8c8');
const SOCK = hex('#ff7a2a');
const SOCK_BAND = hex('#f4f0e8');
const SOCK_AT = { x: -32, z: STOP_Z + 180 };
/** The rotating beacon atop the tower: alternating green and white sweeps, visible from miles out. */
function drawBeacon(s: Surface, f: Frame): void {
const u = (f.t / 1.6) % 1;
const sweep = Math.max(0, 1 - Math.abs(u - 0.25) / 0.08) + Math.max(0, 1 - Math.abs(u - 0.75) / 0.08);
if (sweep <= 0) return;
lamp(s, f.cam, TOWER.x, TOWER.h + 7, TOWER.z, u < 0.5 ? GREEN : WHITE, 1.4 * sweep, 2.2);
}
/** A windsock beside the runway, filled by the light morning breeze. */
function drawWindsock(s: Surface, f: Frame): void {
const cam = f.cam;
const base = project(cam, SOCK_AT.x, 0, SOCK_AT.z);
const top = project(cam, SOCK_AT.x, 6, SOCK_AT.z);
if (!base || !top || base.d > 3000) return;
const pole = mix([POLE[0] * f.amb[0], POLE[1] * f.amb[1], POLE[2] * f.amb[2]], f.fog, 0.2);
for (let y = Math.round(top.y); y <= Math.round(base.y); y++) s.set(Math.round(top.x), y, pole);
const sway = Math.sin(f.t * 0.7) * 0.4;
const n = 10;
for (let i = 0; i <= n; i++) {
const k = i / n;
const p = project(cam, SOCK_AT.x + 3.4 * k, 6 - 0.6 * k * k, SOCK_AT.z + sway * k);
if (!p) continue;
const c = Math.floor(k * 5) % 2 ? SOCK_BAND : SOCK;
const lc = mix([c[0] * f.amb[0], c[1] * f.amb[1], c[2] * f.amb[2]], f.fog, 0.15);
const r = Math.max(0, ((1 - 0.5 * k) * 0.45 * 220) / p.d);
for (let dy = -Math.round(r); dy <= Math.round(r); dy++) s.set(Math.round(p.x), Math.round(p.y) + dy, lc);
}
}
export function drawAirportDetails(s: Surface, f: Frame): void {
drawWindsock(s, f);
drawBeacon(s, f);
}

View File

@ -0,0 +1,229 @@
import { hex, mix, type RGB } from '../../engine/color';
import { hash, Rng } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import type { Frame } from './timeline';
import { BLOCK, clarity, CX, DOWNTOWN, F, H, HORIZON, project, STREET_W, urbanAt, URBAN_BOUNDS, W } from './world';
/**
* Buildings as boxes, ray traced per pixel: a ray from the camera through each pixel of the box's
* screen bounds finds which face it enters (front, side or roof) and where, so lit windows land on
* a proper grid of floors and bays. Boxes are drawn far to near.
*/
export interface Box {
x0: number;
x1: number;
z0: number;
z1: number;
/** Base and top heights, m. */
y0: number;
h: number;
wall: RGB;
roof: RGB;
/** Office windows: share lit at night, and the seed for which ones. */
windows?: { lit: number; seed: number };
/** Every wall is glass, glowing with this interior light (a control tower cab). */
glass?: RGB;
/** A big hangar door on the right (+x) face, facing the runway; `open` 0–1 shows the lit interior. */
door?: { open: number };
/** Red aviation light on the roof. */
beacon?: boolean;
}
const WALLS: readonly RGB[] = ['#9a968e', '#4c5e78', '#8a5e4a', '#3e4658', '#b0a084', '#7c8088'].map(hex);
const ROOF = hex('#5c5c62');
const GLASS = hex('#26303e');
const WARM = hex('#ffd890');
const COOL = hex('#d8e6ff');
const DOOR = hex('#6e7278');
const INSIDE = hex('#ffe0a8');
const AVIATION = hex('#ff3226');
const BUILDINGS: Box[] = (() => {
const r = new Rng(71);
const out: Box[] = [];
const add = (b: Box): void => {
if (out.some((o) => b.x0 < o.x1 + 6 && b.x1 > o.x0 - 6 && b.z0 < o.z1 + 6 && b.z1 > o.z0 - 6)) return;
out.push(b);
};
// Inside a block, clear of the streets.
const inBlock = (x: number, z: number, w: number, d: number): [number, number] => {
const bx = Math.floor(x / BLOCK) * BLOCK + STREET_W / 2 + 4;
const bz = Math.floor(z / BLOCK) * BLOCK + STREET_W / 2 + 4;
const room = BLOCK - STREET_W - 8;
return [bx + r.range(0, Math.max(0, room - w)), bz + r.range(0, Math.max(0, room - d))];
};
for (let i = 0; i < 220 && out.length < 40; i++) {
const a = r.range(0, Math.PI * 2);
const rr = DOWNTOWN.r * Math.sqrt(r.next());
const w = r.range(26, 50);
const d = r.range(26, 50);
const [x0, z0] = inBlock(DOWNTOWN.x + Math.cos(a) * rr * 1.15, DOWNTOWN.z + Math.sin(a) * rr, w, d);
const h = 30 + 200 * Math.exp(-((rr / 280) ** 2)) * r.range(0.4, 1);
add({
x0,
x1: x0 + w,
z0,
z1: z0 + d,
y0: 0,
h,
wall: WALLS[r.int(0, WALLS.length - 1)],
roof: ROOF,
windows: { lit: r.range(0.15, 0.45), seed: r.int(0, 9999) },
beacon: h > 120,
});
}
const B = URBAN_BOUNDS;
for (let i = 0; i < 900 && out.length < 150; i++) {
const x = r.range(B.x0, B.x1);
const z = r.range(B.z0, B.z1);
if (urbanAt(x, z) < 0.6 + 0.3 * r.next()) continue;
const w = r.range(18, 42);
const d = r.range(18, 42);
const [x0, z0] = inBlock(x, z, w, d);
add({
x0,
x1: x0 + w,
z0,
z1: z0 + d,
y0: 0,
h: r.range(9, 34),
wall: WALLS[r.int(0, WALLS.length - 1)],
roof: ROOF,
windows: { lit: r.range(0.1, 0.35), seed: r.int(0, 9999) },
});
}
return out;
})();
const FLOOR = 3.6;
const BAY = 3.2;
/** Sun direction for the low morning sun, just right of straight ahead. */
const SUN_X = 0.135;
function windowAt(f: Frame, b: Box, face: number, u: number, v: number): RGB | undefined {
const w = b.windows!;
const fu = u / BAY;
const fv = (v - b.y0) / FLOOR;
const wi = Math.floor(fu);
const fl = Math.floor(fv);
if (fl < 1 || fu - wi < 0.2 || fu - wi > 0.8 || fv - fl < 0.3 || fv - fl > 0.8) return undefined;
// Lights go on and off now and then, each window on its own slow schedule.
const epoch = Math.floor((f.t + hash(wi, fl, w.seed + face) * 120) / 120);
if (hash(wi + face * 977, fl + epoch * 131, w.seed) < w.lit) return hash(wi, fl, w.seed + 7) < 0.25 ? COOL : WARM;
return GLASS;
}
export function drawBox(s: Surface, f: Frame, b: Box): void {
const cam = f.cam;
if (b.z0 < cam.z + 15) return;
let bx0 = W;
let bx1 = -1;
let by0 = H;
let by1 = -1;
for (const X of [b.x0, b.x1]) {
for (const Y of [b.y0, b.h]) {
for (const Z of [b.z0, b.z1]) {
const p = project(cam, X, Y, Z)!;
bx0 = Math.min(bx0, Math.floor(p.x));
bx1 = Math.max(bx1, Math.ceil(p.x));
by0 = Math.min(by0, Math.floor(p.y));
by1 = Math.max(by1, Math.ceil(p.y));
}
}
}
bx0 = Math.max(0, bx0);
bx1 = Math.min(W - 1, bx1);
by0 = Math.max(0, by0);
by1 = Math.min(H - 1, by1);
if (bx0 > bx1 || by0 > by1) return;
const amb = f.amb;
const sunK = f.sun * 0.55;
const lightK = 0.55 + 0.45 * f.lights;
for (let y = by0; y <= by1; y++) {
const dy = -(y + 0.5 - HORIZON) / F;
for (let x = bx0; x <= bx1; x++) {
const dx = (x + 0.5 - CX) / F;
// Slab test; the ray advances one meter of depth per unit t.
let tmin = b.z0 - cam.z;
let tmax = b.z1 - cam.z;
let face = 0;
if (dx !== 0) {
let ta = (b.x0 - cam.x) / dx;
let tb = (b.x1 - cam.x) / dx;
if (ta > tb) [ta, tb] = [tb, ta];
if (ta > tmin) {
tmin = ta;
face = dx > 0 ? 1 : 2;
}
tmax = Math.min(tmax, tb);
} else if (cam.x < b.x0 || cam.x > b.x1) continue;
if (dy !== 0) {
let ta = (b.y0 - cam.y) / dy;
let tb = (b.h - cam.y) / dy;
if (ta > tb) [ta, tb] = [tb, ta];
if (ta > tmin) {
tmin = ta;
face = 3;
}
tmax = Math.min(tmax, tb);
}
if (tmin > tmax || tmin <= 0) continue;
const X = cam.x + dx * tmin;
const Y = cam.y + dy * tmin;
const Z = cam.z + tmin;
const fp = tmin / F;
let c: RGB;
if (face === 3) {
const k = 0.95 + sunK * 0.2;
c = [b.roof[0] * amb[0] * k, b.roof[1] * amb[1] * k, b.roof[2] * amb[2] * k];
if (fp < 2 && hash(Math.floor(X / 4), Math.floor(Z / 4), 72) < 0.12) c = [c[0] * 0.75, c[1] * 0.75, c[2] * 0.75];
} else {
// 0 = front (facing the camera), 1 = left (-x) side, 2 = right (+x) side, which catches the low sun.
const k = (face === 0 ? 0.72 : 0.58) + (face === 2 ? sunK * SUN_X * 4 : 0);
c = [b.wall[0] * amb[0] * k, b.wall[1] * amb[1] * k, b.wall[2] * amb[2] * k];
const u = face === 0 ? X : Z;
if (b.glass) {
const band = Y > b.y0 + 0.6 && Y < b.h - 0.8;
if (band) c = mix(mix(GLASS, f.horizonColor, 0.35), b.glass, 0.5 * lightK);
} else if (b.door && face === 2 && Z > b.z0 + 3 && Z < b.z1 - 3 && Y < b.y0 + (b.h - b.y0) * 0.78) {
const open = (Z - b.z0) / (b.z1 - b.z0) < b.door.open;
c = open ? [INSIDE[0] * lightK * 0.8, INSIDE[1] * lightK * 0.8, INSIDE[2] * lightK * 0.8] : [DOOR[0] * amb[0] * k, DOOR[1] * amb[1] * k, DOOR[2] * amb[2] * k];
if (!open && fp < 1 && (Z - b.z0) % 4 < 0.4) c = [c[0] * 0.7, c[1] * 0.7, c[2] * 0.7];
} else if (b.windows) {
const win = windowAt(f, b, face, u, Y);
let wc: RGB = c;
if (win === GLASS) wc = mix(mix(GLASS, f.horizonColor, 0.3), c, 0.2);
else if (win) wc = [win[0] * lightK, win[1] * lightK, win[2] * lightK];
// Far away, a wall averages out to a faint glow of its lit windows, with a little sparkle left.
const avgK = Math.min(1, Math.max(0, (fp - 0.9) / 2));
if (avgK > 0) {
const avg = mix(mix(c, GLASS, 0.3), WARM, b.windows.lit * 0.22 * lightK);
wc = mix(wc, avg, avgK * 0.7);
}
c = wc;
}
}
s.set(x, y, mix(c, f.fog, 1 - clarity(tmin)));
}
}
if (b.beacon && (f.t * 0.6 + b.x0 * 0.01) % 1 < 0.5) {
const p = project(cam, (b.x0 + b.x1) / 2, b.h + 2, (b.z0 + b.z1) / 2);
if (p) {
const k = Math.sqrt(clarity(p.d)) * (0.6 + 0.4 * f.lights);
s.light(p.x, p.y, AVIATION, k);
s.light(p.x - 1, p.y, AVIATION, k * 0.3);
s.light(p.x + 1, p.y, AVIATION, k * 0.3);
s.light(p.x, p.y - 1, AVIATION, k * 0.3);
}
}
}
/** Draw the city's buildings and any others (the airport's) together, far to near. */
export function drawBuildings(s: Surface, f: Frame, extra: readonly Box[]): void {
const cam = f.cam;
const dist = (b: Box) => Math.hypot((b.x0 + b.x1) / 2 - cam.x, (b.z0 + b.z1) / 2 - cam.z);
const list = [...BUILDINGS, ...extra].filter((b) => b.z0 > cam.z + 15).sort((a, b) => dist(b) - dist(a));
for (const b of list) drawBox(s, f, b);
}

View File

@ -0,0 +1,147 @@
import { ditherStep, hex, mix, type RGB } from '../../engine/color';
import { progress } from '../../engine/Timeline';
import { noise2 } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import { frameAt, HIGH_EDGE, HIGH_LIT, HIGH_SHADE, LOW_EDGE, LOW_LIT, LOW_SHADE, type Frame } from './timeline';
import { clarity, CX, F, HORIZON, smoothstep, urbanAt, W } from './world';
/**
* Two broken cloud decks overhead, seen from below: a high, thin one that catches the first pink of
* dawn, and a patchier low one. Each is a sheet of noise in world coordinates, so it streams
* overhead from the horizon as the plane flies on, and it is filtered by how much ground each pixel
* spans so the far rows don't shimmer.
*/
interface Deck {
alt: number;
/** Size of the big cloud masses, m. */
size: number;
/** Density above which a pixel is cloud. */
th: number;
/** Wind drift across the path, m/s. */
wind: number;
seed: number;
shade: (t: number) => RGB;
lit: (t: number) => RGB;
edge: (t: number) => RGB;
glow: (f: Frame) => number;
}
const HIGH: Deck = {
alt: 2600,
size: 1100,
th: 0.55,
wind: 5,
seed: 80,
shade: HIGH_SHADE,
lit: HIGH_LIT,
edge: HIGH_EDGE,
glow: (f) => f.highGlow,
};
const LOW: Deck = {
alt: 1100,
size: 620,
th: 0.6,
wind: 3,
seed: 90,
shade: LOW_SHADE,
lit: LOW_LIT,
edge: LOW_EDGE,
glow: (f) => f.lowGlow,
};
const CITY_UNDERLIGHT = hex('#a8643e');
function density(d: Deck, X: number, Z: number, fp: number, th: number): number {
const s = d.size;
// Detail that would be smaller than a pixel is faded to its average.
const k2 = smoothstep(s * 0.5, s * 0.15, fp);
const k3 = smoothstep(s * 0.16, s * 0.05, fp);
const base = 0.5 + 0.62 * (noise2(X / (s * 1.7), Z / s, d.seed) - 0.5);
// Clear sky that the finer octaves can't push over the threshold needs nothing more.
if (base + 0.15 * k2 + 0.07 * k3 < th - 0.02) return 0;
let v = base;
if (k2 > 0) v += 0.3 * k2 * (noise2(X / (s * 0.6) + 11, Z / (s * 0.38), d.seed + 1) - 0.5);
if (k3 > 0) v += 0.14 * k3 * (noise2(X / (s * 0.17), Z / (s * 0.12), d.seed + 2) - 0.5);
return v;
}
/** The cloud layer over the sky: color and coverage per pixel, both decks combined. */
const LAYER_C = new Float32Array(W * HORIZON * 3);
const LAYER_A = new Float32Array(W * HORIZON);
function computeDeck(f: Frame, d: Deck): void {
const cam = f.cam;
const h = d.alt - cam.y;
const shade = d.shade(f.t);
const litC = d.lit(f.t);
const edgeC = d.edge(f.t);
const glow = d.glow(f);
const city = d === LOW ? f.lights * (1 - progress(f.t, 150, 225)) : 0;
const drift = f.t * d.wind;
for (let y = 0; y < HORIZON; y++) {
const r = HORIZON - (y + 0.5);
const dist = (h * F) / r;
const far = smoothstep(30000, 12000, dist);
if (far <= 0) continue;
const fp = Math.max(dist / F, dist / r);
const Z = cam.z + dist;
const haze = 1 - clarity(dist * 0.6);
const low = y / HORIZON;
for (let x = 0; x < W; x++) {
const X = cam.x + ((x + 0.5 - CX) * dist) / F + drift;
const e = density(d, X, Z, fp, d.th) - d.th;
if (e <= -0.02) continue;
const a = ditherStep(Math.min(1, (e + 0.02) / 0.07) * far, x, y, 5);
if (a <= 0) continue;
// Dawn light from the east reaches under the clouds, warmest near the sun and the horizon.
const sunward = Math.exp(-(((x - f.sunX) / 120) ** 2)) * (0.45 + 0.55 * low);
const g = glow * (0.4 + 0.6 * sunward);
let c = mix(shade, litC, g);
c = mix(c, edgeC, (1 - Math.min(1, Math.max(0, e) / 0.08)) * (0.3 + 0.5 * glow));
const thick = Math.min(1, Math.max(0, e) / 0.24);
c = mix(c, shade, thick * 0.45 * (1 - g));
if (city > 0) {
const u = urbanAt(X - drift, Z);
if (u > 0) c = mix(c, CITY_UNDERLIGHT, u * city * 0.45);
}
c = mix(c, f.horizonColor, haze * 0.7);
// Lay this deck over what the decks above have left in the layer.
const j = y * W + x;
const below = LAYER_A[j];
const out = a + below * (1 - a);
const kb = (below * (1 - a)) / out;
LAYER_C[j * 3] = c[0] * (1 - kb) + LAYER_C[j * 3] * kb;
LAYER_C[j * 3 + 1] = c[1] * (1 - kb) + LAYER_C[j * 3 + 1] * kb;
LAYER_C[j * 3 + 2] = c[2] * (1 - kb) + LAYER_C[j * 3 + 2] * kb;
LAYER_A[j] = out;
}
}
}
/**
* The decks move at most a couple of pixels a second, so the layer is recomputed only every 1/12 s
* of scene time. Keying the cache on quantized time keeps the scene a pure function of t.
*/
const STEP = 1 / 12;
let cachedKey = NaN;
export function drawClouds(s: Surface, f: Frame): void {
const key = Math.round(f.t / STEP);
if (key !== cachedKey) {
cachedKey = key;
LAYER_A.fill(0);
const ft = key * STEP === f.t ? f : frameAt(key * STEP);
computeDeck(ft, HIGH);
computeDeck(ft, LOW);
}
const col: [number, number, number] = [0, 0, 0];
for (let j = 0; j < W * HORIZON; j++) {
const a = LAYER_A[j];
if (a <= 0) continue;
col[0] = LAYER_C[j * 3];
col[1] = LAYER_C[j * 3 + 1];
col[2] = LAYER_C[j * 3 + 2];
s.blend(j % W, (j / W) | 0, col, a);
}
}

View File

@ -0,0 +1,48 @@
import { track } from '../../engine/Timeline';
/** All timings for the Morning Flight meditation, in seconds. */
export const DURATION = 300;
export const TIMES = {
fadeIn: [0, 6],
fadeOut: [295, 300],
/** Downtown slides past on the right. */
cityPass: 150,
/** The glide from cruise altitude down to the wheels touching. */
descent: [172, 270],
touchdown: 270,
/** Rolled to a stop on the runway. */
stop: 290,
/** Engine cut: the propeller winds down and stops, and the engine sound fades with it. */
propDown: [284, 292],
} as const;
/** Ground speed in m/s: cruise, slowing on approach, then braking to a stop on the runway. */
export const speedAt = track([
[0, 55],
[160, 55],
[215, 44],
[255, 36],
[TIMES.touchdown, 32],
[279, 18],
[286, 5],
[TIMES.stop, 0],
]);
/**
* Distance flown since t = 0, in meters. Integrated from a table so the ground never jumps when
* the speed changes, while staying a pure function of t.
*/
const DT = 0.05;
const TRAVEL: Float64Array = (() => {
const n = Math.ceil(DURATION / DT) + 2;
const out = new Float64Array(n);
for (let i = 1; i < n; i++) out[i] = out[i - 1] + speedAt((i - 0.5) * DT) * DT;
return out;
})();
export function travelAt(t: number): number {
const u = Math.max(0, t) / DT;
const i = Math.min(TRAVEL.length - 2, Math.floor(u));
return TRAVEL[i] + (TRAVEL[i + 1] - TRAVEL[i]) * (u - i);
}

View File

@ -0,0 +1,281 @@
import { hex, mix, type RGB } from '../../engine/color';
import { hash } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import type { Frame } from './timeline';
import {
AIRPORT,
APPROACH,
APRON,
BLOCK,
clarity,
CONNECTORS,
cover,
CX,
F,
FARM_ROADS_X,
farmstead,
FIELD_D,
FIELD_W,
fieldShift,
gridDist,
H,
HORIZON,
HWY_X,
RUNWAY,
SECTION,
smoothstep,
STREET_W,
tex2,
TAXI_X,
urbanAt,
W,
} from './world';
/**
* The ground, rendered per pixel by tracing each row back onto the ground plane: farm fields, the
* suburbs and city, and the airport. Every pattern is filtered by how many meters a pixel spans
* (across and in depth), so details resolve as the plane comes down instead of crawling.
*/
const CROPS: readonly RGB[] = ['#4f7a36', '#6a9442', '#b8a45a', '#7c5c3c', '#8c8a52', '#3e6a32', '#a08a5a', '#5e8240'].map(hex);
/** Crops planted in rows that run along the flight path. */
const ROWED = [true, true, false, true, false, true, false, true];
const HEDGE = hex('#2c4628');
const GRAVEL = hex('#8a826e');
const YARD = hex('#7a7058');
const FARMHOUSE = hex('#d8d2c4');
const BARN = hex('#8a3a2e');
const TREE = hex('#2a4424');
const STREET = hex('#3c3c40');
const LAWN = hex('#56763e');
const ROOFS: readonly RGB[] = ['#8a5040', '#6a6a72', '#9a8a70', '#5a4a44', '#7c7c80'].map(hex);
const FLAT_ROOF = hex('#76767a');
const SUBURB_AVG = hex('#626a50');
const DENSE_AVG = hex('#6a6a6c');
const HIGHWAY = hex('#48484c');
const STREET_GLOW = hex('#ffa050');
const GRASS = hex('#5e8444');
const GRASS_MOWN = hex('#6a9050');
const ASPHALT = hex('#58585c');
const RUBBER = hex('#2e2e32');
const PAINT = hex('#dcdcd2');
const TAXI_LINE = hex('#d8b030');
const CONCRETE = hex('#86868a');
const MIST = hex('#f0e0e6');
/** Emission from street lighting at the last sampled point, added after the ambient light. */
let emit = 0;
// Per-field values, cached while consecutive pixels stay in the same field.
let cellX = NaN;
let cellZ = NaN;
let rowShift = 0;
let cellKind = 0;
let cellSplit = Infinity;
let cellHedge = false;
let cellFarm: { x: number; z: number } | undefined;
function farm(X: number, Z: number, fpx: number, fpz: number): RGB {
const cz = Math.floor(Z / FIELD_D);
if (cz !== cellZ) {
cellZ = cz;
cellX = NaN;
rowShift = fieldShift(cz);
}
const xs = X + rowShift;
const cx = Math.floor(xs / FIELD_W);
if (cx !== cellX) {
cellX = cx;
cellKind = Math.floor(hash(cx, cz, 22) * CROPS.length);
// Some fields are split in two.
cellSplit = hash(cx, cz, 23) < 0.35 ? FIELD_W * (0.35 + 0.3 * hash(cx, cz, 24)) : Infinity;
cellHedge = hash(cx, cz, 26) < 0.55;
cellFarm = farmstead(cx, cz);
}
const u = xs - cx * FIELD_W;
const v = Z - cz * FIELD_D;
const kind = u > cellSplit ? (cellKind + 3) % CROPS.length : cellKind;
let tex = 0.9 + 0.2 * tex2(X / 70, Z / 70);
if (ROWED[kind]) tex *= 1 - 0.16 * cover(gridDist(X, 3), 1.2, fpx);
let c: RGB = [CROPS[kind][0] * tex, CROPS[kind][1] * tex, CROPS[kind][2] * tex];
if (cellHedge) {
const hedge = Math.max(cover(Math.min(u, FIELD_W - u), 5, fpx), cover(Math.min(v, FIELD_D - v), 5, fpz));
if (hedge > 0) c = mix(c, HEDGE, hedge * (0.75 + 0.25 * tex2(X / 7 + 17, Z / 7)));
}
let road = cover(gridDist(Z, SECTION.period, SECTION.offset), 7, fpz);
for (const rx of FARM_ROADS_X) road = Math.max(road, cover(Math.abs(X - rx), 7, fpx));
if (road > 0) c = mix(c, GRAVEL, road);
const fs = cellFarm;
if (fs) {
const du = X - fs.x;
const dv = Z - fs.z;
const yard = cover(Math.abs(du), 50, fpx) * cover(Math.abs(dv), 40, fpz);
if (yard > 0) c = mix(c, YARD, yard * 0.8);
const house = cover(Math.abs(du - 9), 12, fpx) * cover(Math.abs(dv + 4), 9, fpz);
if (house > 0) c = mix(c, FARMHOUSE, house);
const barn = cover(Math.abs(du + 10), 20, fpx) * cover(Math.abs(dv - 6), 12, fpz);
if (barn > 0) c = mix(c, BARN, barn);
// Shelter trees on the north side of the yard.
const trees = cover(Math.abs(du), 64, fpx) * cover(Math.abs(dv + 26), 10, fpz) * (tex2(X / 5 + 31, Z / 5) > 0.45 || fpx > 4 ? 0.8 : 0);
if (trees > 0) c = mix(c, TREE, trees);
}
return c;
}
function urban(X: number, Z: number, fpx: number, fpz: number, dens: number): RGB {
const street = Math.max(cover(gridDist(X, BLOCK), STREET_W, fpx), cover(gridDist(Z, BLOCK), STREET_W, fpz)) * (dens > 0.12 ? 1 : 0);
const LOT = 22;
const lx = Math.floor(X / LOT);
const lz = Math.floor(Z / LOT);
const built = hash(lx, lz, 32) < dens * 1.6;
let c: RGB;
if (!built) c = farm(X, Z, fpx, fpz);
else if (Math.max(fpx, fpz) > 8) c = mix(SUBURB_AVG, DENSE_AVG, dens);
else if (hash(lx, lz, 33) < dens * 0.7) {
// Dense blocks: flat roofs and car parks.
c = mix(FLAT_ROOF, STREET, hash(lx, lz, 34) * 0.6);
} else {
const du = X - (lx + 0.5) * LOT;
const dv = Z - (lz + 0.5) * LOT;
const roof = cover(Math.abs(du), 12, fpx) * cover(Math.abs(dv), 10, fpz);
const tree = tex2(X / 6 + 35, Z / 6) > 0.62 ? 0.8 : 0;
c = mix(mix(LAWN, TREE, tree), ROOFS[Math.floor(hash(lx, lz, 36) * ROOFS.length)], roof);
}
emit = (street * 0.8 + 0.12) * dens;
return street > 0 ? mix(c, STREET, street) : c;
}
function runway(X: number, Z: number, fpx: number, fpz: number): RGB {
const ax = Math.abs(X);
const dz = Z - RUNWAY.z0;
const len = RUNWAY.z1 - RUNWAY.z0;
let c = mix(ASPHALT, RUBBER, 0.2 * tex2(X / 3 + 40, Z / 20));
// Tire marks where everyone touches down.
const marks = cover(Math.abs(ax - 4), 5, fpx) * cover(Math.abs(dz - 420), 260, fpz);
if (marks > 0) c = mix(c, RUBBER, marks * 0.6 * tex2(X + 41, Z / 6));
let m = cover(Math.abs(ax - 14.2), 0.9, fpx);
// Threshold bars at both ends.
for (const at of [21, len - 21]) {
const keys = ax > 3 && ax < 14 ? cover(gridDist(ax - 3.9, 1.8), 1.2, fpx) : 0;
m = Math.max(m, keys * cover(Math.abs(dz - at), 30, fpz));
}
// Centerline dashes, aiming point and touchdown zone markings.
if (dz > 60 && dz < len - 60) m = Math.max(m, cover(ax, 0.9, fpx) * (fpz < 30 ? ((dz - 60) % 60 < 36 ? 1 : 0) : 0.6));
m = Math.max(m, cover(Math.abs(ax - 7.2), 4.5, fpx) * cover(Math.abs(dz - 322), 45, fpz));
for (const at of [160, 470, 620]) m = Math.max(m, cover(Math.abs(ax - 6.4), 3, fpx) * cover(Math.abs(dz - at), 22, fpz));
return m > 0 ? mix(c, PAINT, m * 0.85) : c;
}
function airport(X: number, Z: number, fpx: number, fpz: number): RGB {
if (Math.abs(X) < RUNWAY.half && Z > RUNWAY.z0 && Z < RUNWAY.z1) return runway(X, Z, fpx, fpz);
let c = mix(GRASS, GRASS_MOWN, cover(gridDist(X, 24), 12, fpx) * 0.4);
c = mix(c, GRASS, 0.3 * tex2(X / 40 + 42, Z / 40));
const inField = Z > RUNWAY.z0 - 10 && Z < RUNWAY.z1 + 10;
let pave = inField ? cover(Math.abs(X - TAXI_X), 15, fpx) : 0;
let line = inField ? cover(Math.abs(X - TAXI_X), 0.5, fpx) : 0;
if (X > TAXI_X && X < -RUNWAY.half) {
for (const cz of CONNECTORS) {
pave = Math.max(pave, cover(Math.abs(Z - cz), 18, fpz));
line = Math.max(line, cover(Math.abs(Z - cz), 0.5, fpz));
}
}
const apron = cover(Math.abs(X - (APRON.x0 + APRON.x1) / 2), APRON.x1 - APRON.x0, fpx) * cover(Math.abs(Z - (APRON.z0 + APRON.z1) / 2), APRON.z1 - APRON.z0, fpz);
if (apron > 0) c = mix(c, CONCRETE, apron);
if (pave > 0) c = mix(c, ASPHALT, pave);
if (line > 0 && pave > 0) c = mix(c, TAXI_LINE, line * 0.8);
return c;
}
function sample(X: number, Z: number, fpx: number, fpz: number): RGB {
emit = 0;
if (X > AIRPORT.x0 && X < AIRPORT.x1 && Z > AIRPORT.z0 && Z < AIRPORT.z1) return airport(X, Z, fpx, fpz);
if (Math.abs(X) < APPROACH.half && Z > APPROACH.z0 && Z < AIRPORT.z0) return airport(X, Z, fpx, fpz);
const dens = urbanAt(X, Z);
let c = dens > 0.02 ? urban(X, Z, fpx, fpz, dens) : farm(X, Z, fpx, fpz);
const hwy = cover(Math.abs(X - HWY_X), 26, fpx);
if (hwy > 0) {
c = mix(c, HIGHWAY, hwy);
emit = Math.max(emit, hwy * 0.9 * Math.min(1, dens * 3));
}
return c;
}
/** Soft edge falloff: 1 well inside half-width `half`, 0 beyond it by `soft`. */
const inside = (v: number, half: number, soft: number): number => smoothstep(half + soft, half - soft, Math.abs(v));
/** Fraction of sky light the landing or parked plane blocks from a ground point beneath it. */
function planeShadow(f: Frame, X: number, Z: number): number {
if (f.agl > 30) return 0;
const p = f.plane;
const dx = X - p.x;
const dz = Z - p.z;
if (Math.abs(dx) > 9 || Math.abs(dz) > 7) return 0;
const soft = 0.8 + f.agl * 0.3;
const wing = inside(dx, 5.5, soft) * inside(dz, 0.8, soft);
const body = inside(dx, 0.6, soft) * inside(dz - 0.2, 4.3, soft);
const tail = inside(dx, 1.7, soft) * inside(dz + 3.9, 0.4, soft);
return 0.32 * Math.max(wing, body, tail) * (1 - f.agl / 30);
}
/** Light from the landing light in the left wing, a cone reaching ahead of the plane. */
function landingLight(f: Frame, X: number, Z: number): number {
if (f.landing <= 0 || f.agl > 140) return 0;
const p = f.plane;
const ahead = Z - p.z - 1;
if (ahead < 2) return 0;
const h = p.y + 1.1;
const lat = (X - p.x + 2.2) / ahead;
const down = h / ahead - (0.07 + p.pitch * -0.9);
const beam = Math.exp(-((lat / 0.11) ** 2) - (down / 0.06) ** 2);
return (f.landing * 1.6 * beam * 900) / (ahead * ahead + h * h + 400);
}
export function drawGround(s: Surface, f: Frame): void {
const cam = f.cam;
const glowK = f.lights * 0.25;
const [ar, ag, ab] = f.amb;
const [fr, fg, fb] = f.fog;
const mistC = mix(f.fog, MIST, 0.4);
const out: [number, number, number] = [0, 0, 0];
const nearPlane = f.agl < 30 || (f.landing > 0 && f.agl < 140);
for (let y = HORIZON; y < H; y++) {
const r = y + 0.5 - HORIZON;
const d = (cam.y * F) / r;
const fpx = d / F;
const fpz = d / r;
const Z = cam.z + d;
const fog = 1 - clarity(d);
const keep = 1 - fog;
const mistRow = f.mist * Math.min(1, d / 3000);
for (let x = 0; x < W; x++) {
const X = cam.x + (x + 0.5 - CX) * fpx;
const base = sample(X, Z, fpx, fpz);
const light = nearPlane ? 1 - planeShadow(f, X, Z) + landingLight(f, X, Z) : 1;
let cr = base[0] * ar * light;
let cg = base[1] * ag * light;
let cb = base[2] * ab * light;
if (emit > 0) {
const e = emit * glowK;
cr += STREET_GLOW[0] * e;
cg += STREET_GLOW[1] * e;
cb += STREET_GLOW[2] * e;
}
if (mistRow > 0) {
const m = Math.min(0.7, mistRow * Math.max(0, tex2(X / 700 + 43, Z / 450) - 0.35) * 1.6);
if (m > 0) {
cr += (mistC[0] - cr) * m;
cg += (mistC[1] - cg) * m;
cb += (mistC[2] - cb) * m;
}
}
out[0] = cr * keep + fr * fog;
out[1] = cg * keep + fg * fog;
out[2] = cb * keep + fb * fog;
s.set(x, y, out);
}
}
}

View File

@ -0,0 +1,41 @@
import type { Meditation, Scene } from '../types';
import { AIRPORT_BOXES, drawAirportDetails } from './airport';
import { drawBuildings } from './city';
import { drawClouds } from './clouds';
import { drawGround } from './ground';
import { drawGroundLights } from './lights';
import { drawMountains } from './mountains';
import { drawPlane } from './plane';
import { drawCityGlow, drawSky, drawSunRays } from './sky';
import { DURATION, frameAt, TIMES } from './timeline';
const scene: Scene = {
render(s, t) {
const f = frameAt(t);
drawSky(s, f);
drawMountains(s, f);
drawCityGlow(s, f);
drawClouds(s, f);
drawSunRays(s, f);
drawGround(s, f);
drawGroundLights(s, f);
drawBuildings(s, f, AIRPORT_BOXES);
drawAirportDetails(s, f);
drawPlane(s, f);
s.darken(f.fade);
},
};
export const morningFlight: Meditation = {
id: 'morning-flight',
title: 'Morning Flight',
subtitle: 'A small plane flies home at daybreak',
description:
'Ride along behind a little Cessna in the last dark of the night. Fly over sleeping farmland and past a city of streetlights and early traffic, toward the runway lights blinking under the mountains. Then glide down and land as the sun clears the ridge and the sky fills with morning color.',
music: 'audio/morning-flight.mp3',
// The engine drone loops from the start and fades out as the propeller winds down after landing.
ambience: { src: 'audio/fx-plane.mp3', volume: 0.45, fadeIn: 5, until: TIMES.propDown[1], fadeOut: TIMES.propDown[1] - TIMES.propDown[0] },
duration: DURATION,
previewTime: 255,
createScene: () => scene,
};

View File

@ -0,0 +1,224 @@
import { hex, type RGB } from '../../engine/color';
import { hash, Rng } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import type { Frame } from './timeline';
import {
APRON,
BLOCK,
clarity,
CONNECTORS,
FARM_ROADS_X,
farmstead,
HWY_X,
project,
RUNWAY,
TAXI_X,
urbanAt,
URBAN_BOUNDS,
W,
type Cam,
} from './world';
/** Points of light on the ground: farmhouses, streetlights, traffic and the airfield. */
const SODIUM = hex('#ffaa58');
const LED = hex('#e4ecff');
const WINDOW = hex('#ffcc80');
const YARD = hex('#d8e4ff');
const HEAD = hex('#fff4d8');
const TAIL = hex('#ff3a30');
const WHITE = hex('#fff8e8');
const YELLOW = hex('#ffd870');
const GREEN = hex('#5aff8a');
const RED = hex('#ff4a3a');
const BLUE = hex('#5a7cff');
const STROBE = hex('#ffffff');
/**
* Add one light at a world point. It falls off with distance (but never below a faint speck, so
* far towns still sparkle), dims in the haze, and grows a small halo up close. Lights in a row
* `sz` meters apart in depth (or `sx` across) dim where they crowd into the same pixels, so a far
* runway stays a line of points instead of piling up into a white bar.
*/
export function lamp(s: Surface, cam: Cam, X: number, Y: number, Z: number, c: RGB, k: number, size = 1, sz = 0, sx = 0): void {
const p = project(cam, X, Y, Z);
if (!p || p.d > 40000 || p.x < -4 || p.x > W + 4 || p.y < 0) return;
let a = k * Math.pow(Math.min(1, 500 / p.d), 0.55) * Math.sqrt(clarity(p.d));
if (sz > 0) a *= Math.min(1, Math.max(0.08, (sz * (Math.abs(cam.y - Y) + Math.abs(X - cam.x) * 0.5) * 220) / (p.d * p.d)));
if (sx > 0) a *= Math.min(1, Math.max(0.15, (sx * 220) / p.d));
if (a < 0.01) return;
const x = Math.floor(p.x);
const y = Math.floor(p.y);
s.light(x, y, c, a);
const r = Math.min(4, (size * 90) / p.d);
if (r < 0.6) return;
const R = Math.ceil(r);
for (let dy = -R; dy <= R; dy++) {
for (let dx = -R; dx <= R; dx++) {
if (!dx && !dy) continue;
const d = Math.hypot(dx, dy);
if (d > r + 0.5) continue;
s.light(x + dx, y + dy, c, a * 0.45 * (1 - d / (r + 0.6)));
}
}
}
interface Fixed {
x: number;
y: number;
z: number;
c: RGB;
k: number;
}
const STREETLIGHTS: Fixed[] = (() => {
const out: Fixed[] = [];
const B = URBAN_BOUNDS;
for (let z = Math.floor(B.z0 / BLOCK) * BLOCK; z < B.z1; z += BLOCK) {
for (let x = Math.floor(B.x0 / BLOCK) * BLOCK; x < B.x1; x += BLOCK) {
const d = urbanAt(x, z);
if (d < 0.18 + 0.3 * hash(x, z, 50)) continue;
const c = hash(x, z, 51) < 0.25 ? LED : SODIUM;
out.push({ x: x + 7, y: 8, z: z + 7, c, k: 0.75 });
if (d > 0.45) {
out.push({ x: x + 55, y: 8, z: z + 7, c, k: 0.6 });
out.push({ x: x + 7, y: 8, z: z + 55, c, k: 0.6 });
}
}
}
// The highway is lit through town.
for (let z = B.z0; z < B.z1; z += 55) {
if (urbanAt(HWY_X, z) < 0.08) continue;
out.push({ x: HWY_X - 14, y: 10, z, c: SODIUM, k: 0.8 });
out.push({ x: HWY_X + 14, y: 10, z: z + 27, c: SODIUM, k: 0.8 });
}
return out;
})();
const FARM_LIGHTS: Fixed[] = (() => {
const out: Fixed[] = [];
for (let cz = -8; cz < 110; cz++) {
for (let cx = -18; cx < 26; cx++) {
const fs = farmstead(cx, cz);
if (!fs) continue;
out.push({ x: fs.x + 9, y: 2, z: fs.z - 4, c: WINDOW, k: 0.55 + 0.3 * hash(cx, cz, 52) });
if (hash(cx, cz, 53) < 0.55) out.push({ x: fs.x - 2, y: 6, z: fs.z + 2, c: YARD, k: 0.8 });
}
}
return out;
})();
interface Car {
/** Lane runs along z (true) or x. */
alongZ: boolean;
lane: number;
from: number;
len: number;
speed: number;
phase: number;
dir: 1 | -1;
}
const CARS: Car[] = (() => {
const r = new Rng(57);
const out: Car[] = [];
const B = URBAN_BOUNDS;
// Town traffic on the avenues, every fourth street.
for (let i = 0; i < 70; i++) {
const alongZ = r.next() < 0.6;
const dir = r.next() < 0.5 ? 1 : -1;
const span = alongZ ? [B.x0, B.x1] : [B.z0, B.z1];
const lane = Math.round(r.range(span[0], span[1]) / (BLOCK * 4)) * BLOCK * 4 + dir * 3;
const from = alongZ ? B.z0 : B.x0;
out.push({ alongZ, lane, from, len: alongZ ? B.z1 - B.z0 : B.x1 - B.x0, speed: r.range(9, 15), phase: r.next(), dir });
}
// The highway, northbound on the right.
for (let i = 0; i < 46; i++) {
const dir = r.next() < 0.5 ? 1 : -1;
const lane = HWY_X + dir * r.int(1, 2) * 4.5;
out.push({ alongZ: true, lane, from: -2000, len: 20000, speed: r.range(25, 32), phase: r.next(), dir });
}
// A few early risers on the farm roads.
for (let i = 0; i < 6; i++) {
const dir = r.next() < 0.5 ? 1 : -1;
out.push({ alongZ: true, lane: FARM_ROADS_X[i % 2] + dir * 2, from: -1000, len: 16000, speed: r.range(14, 20), phase: r.next(), dir });
}
return out;
})();
function drawCars(s: Surface, f: Frame): void {
const k = 0.55 + 0.45 * f.lights;
for (const car of CARS) {
const along = car.from + ((((car.phase * car.len + f.t * car.speed * car.dir) % car.len) + car.len) % car.len);
const X = car.alongZ ? car.lane : along;
const Z = car.alongZ ? along : car.lane;
if (car.alongZ && urbanAt(X, Z) < 0.1 && Math.abs(X - HWY_X) > 20 && !FARM_ROADS_X.some((rx) => Math.abs(X - rx) < 4)) continue;
if (!car.alongZ && urbanAt(X, Z) < 0.25) continue;
// Driving away shows tail lights, toward us headlights; crossing traffic shows a bit of both.
const c = !car.alongZ ? (hash(Math.floor(along / 400), car.lane, 58) < 0.5 ? HEAD : TAIL) : car.dir > 0 ? TAIL : HEAD;
lamp(s, f.cam, X, 0.8, Z, c, (c === HEAD ? 0.9 : 0.7) * k, 0.5);
}
}
function drawFixed(s: Surface, f: Frame, list: Fixed[], k: number): void {
const cam = f.cam;
for (const l of list) {
if (l.z < cam.z + 5) continue;
lamp(s, cam, l.x, l.y, l.z, l.c, l.k * k);
}
}
/** Strobe flash, 0–1: a short double pulse every period seconds. */
const flash = (t: number, period: number, offset = 0): number => {
const u = (((t + offset) % period) + period) % period;
return u < 0.06 || (u > 0.16 && u < 0.21) ? 1 : 0;
};
function drawAirfield(s: Surface, f: Frame): void {
const cam = f.cam;
const t = f.t;
const k = 0.7 + 0.3 * f.lights;
// Approach lights: steady white bars, with the "rabbit" racing toward the runway twice a second.
const N = 30;
const rabbit = (t * 2) % 1;
for (let i = 0; i < N; i++) {
const z = RUNWAY.z0 - 30 * (i + 1);
if (i < 12) for (let x = -6; x <= 6; x += 3) lamp(s, cam, x, 0.6, z, WHITE, 0.45 * k, 1, 30, 3);
if (Math.abs(rabbit - (N - 1 - i) / N) < 0.02) lamp(s, cam, 0, 0.8, z, STROBE, 1.1, 1.6);
}
for (let x = -RUNWAY.half; x <= RUNWAY.half; x += 2.5) {
lamp(s, cam, x, 0.4, RUNWAY.z0 - 2, GREEN, 0.75 * k, 1, 0, 2.5);
lamp(s, cam, x, 0.4, RUNWAY.z1 + 2, RED, 0.6 * k, 1, 0, 2.5);
}
// Edge lights turn yellow over the last 600 m.
for (let z = RUNWAY.z0 + 30; z < RUNWAY.z1; z += 60) {
const c = z > RUNWAY.z1 - 600 ? YELLOW : WHITE;
lamp(s, cam, -RUNWAY.half - 1, 0.5, z, c, 0.65 * k, 1, 60);
lamp(s, cam, RUNWAY.half + 1, 0.5, z, c, 0.65 * k, 1, 60);
}
for (let z = RUNWAY.z0 + 15; z < RUNWAY.z1; z += 30) lamp(s, cam, 0, 0.05, z, WHITE, 0.22 * k, 0.4, 30);
for (let z = RUNWAY.z0; z < RUNWAY.z1; z += 50) {
lamp(s, cam, TAXI_X - 8.5, 0.4, z, BLUE, 0.5 * k, 0.7, 50);
lamp(s, cam, TAXI_X + 8.5, 0.4, z + 25, BLUE, 0.5 * k, 0.7, 50);
}
for (const cz of CONNECTORS) {
for (let x = TAXI_X + 15; x < -RUNWAY.half - 5; x += 20) {
lamp(s, cam, x, 0.4, cz - 10, BLUE, 0.5 * k, 0.7, 0, 20);
lamp(s, cam, x, 0.4, cz + 10, BLUE, 0.5 * k, 0.7, 0, 20);
}
}
// Floodlights over the apron.
for (let z = APRON.z0 + 40; z < APRON.z1; z += 140) lamp(s, cam, APRON.x1 - 6, 14, z, SODIUM, 0.8 * f.lights, 1.4);
// Runway end identifier lights, flashing in sync.
if (flash(t, 1, 0.5)) {
lamp(s, cam, -RUNWAY.half - 12, 1, RUNWAY.z0, STROBE, 1, 1.2);
lamp(s, cam, RUNWAY.half + 12, 1, RUNWAY.z0, STROBE, 1, 1.2);
}
}
export function drawGroundLights(s: Surface, f: Frame): void {
drawFixed(s, f, FARM_LIGHTS, f.lights);
drawFixed(s, f, STREETLIGHTS, f.lights);
drawCars(s, f);
drawAirfield(s, f);
}

View File

@ -0,0 +1,81 @@
import { hex, mix } from '../../engine/color';
import { progress } from '../../engine/Timeline';
import { hash, noise1 } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import { MOUNTAIN_FAR, MOUNTAIN_NEAR, type Frame } from './timeline';
import { HORIZON, W } from './world';
/**
* Ridgelines far beyond the airport, so distant they sit on the horizon without parallax. The far
* range dips into a saddle just right of the runway, where the sun comes up.
*/
function ridge(peaks: readonly (readonly [number, number, number])[], wobble: number, seed: number): Int16Array {
return Int16Array.from({ length: W }, (_, x) => {
let best = Infinity;
for (const [cx, cy, k] of peaks) best = Math.min(best, cy + Math.abs(x - cx) * k);
const y = best + (noise1(x / 3, seed) - 0.5) * wobble + (noise1(x / 11, seed + 1) - 0.5) * wobble * 1.8;
return Math.min(HORIZON, Math.round(y));
});
}
const FAR = ridge(
[
[18, 77, 0.32],
[66, 80, 0.3],
[116, 73, 0.38],
[160, 79, 0.3],
[218, 75, 0.36],
[262, 71, 0.4],
[306, 77, 0.3],
],
1.6,
61,
);
const NEAR = ridge(
[
[-10, 85, 0.16],
[86, 85, 0.14],
[134, 87, 0.12],
[250, 86, 0.16],
[330, 84, 0.18],
],
1.2,
65,
);
/** A radio mast on one of the western peaks, with its slow red light. */
const MAST_X = 116;
const MAST_RED = hex('#ff3a2a');
export function drawMountains(s: Surface, f: Frame): void {
const far = MOUNTAIN_FAR(f.t);
const near = MOUNTAIN_NEAR(f.t);
const rimK = progress(f.t, 225, 285);
for (let x = 0; x < W; x++) {
// Backlit by the dawn: a rim of light along the ridge, strongest near the sun.
const rim = rimK * Math.exp(-(((x - f.sunX) / 46) ** 2));
for (let y = FAR[x]; y < HORIZON; y++) {
const depth = (y - FAR[x]) / Math.max(1, HORIZON - FAR[x]);
let c = mix(far, f.fog, 0.25 + 0.5 * depth);
// Faint gullies of old snow catching the sky light.
if (y - FAR[x] > 1 && noise1(x / 2.3, 70 + ((y - FAR[x]) >> 1)) > 0.78 && hash(x, y, 71) > 0.4) c = mix(c, f.horizonColor, 0.2);
if (y === FAR[x]) c = mix(mix(c, f.horizonColor, 0.25), f.sunColor, 0.7 * rim);
else if (y === FAR[x] + 1) c = mix(c, f.sunColor, 0.3 * rim);
s.set(x, y, c);
}
for (let y = NEAR[x]; y < HORIZON; y++) {
let c = mix(near, f.fog, 0.15 + 0.35 * ((y - NEAR[x]) / Math.max(1, HORIZON - NEAR[x])));
if (y === NEAR[x]) c = mix(c, f.sunColor, 0.25 * rim);
s.set(x, y, c);
}
}
const my = FAR[MAST_X];
for (let y = my - 3; y < my; y++) s.set(MAST_X, y, mix(far, [0, 0, 0], 0.3));
if ((f.t * 0.7) % 1 < 0.45) {
const k = 0.9 * f.lights;
s.blend(MAST_X, my - 4, MAST_RED, k);
s.light(MAST_X - 1, my - 4, MAST_RED, k * 0.25);
s.light(MAST_X + 1, my - 4, MAST_RED, k * 0.25);
}
}

View File

@ -0,0 +1,478 @@
import { ditherStep, hex, mix, type RGB } from '../../engine/color';
import { clamp01, progress } from '../../engine/Timeline';
import type { Surface } from '../../engine/Surface';
import type { Frame } from './timeline';
import { CX, F, H, HORIZON, project, W } from './world';
/**
* The Cessna: a small high-wing four-seater with fixed gear, white with a navy stripe. The model is
* a set of flat faces and rods in meters (x right, y up, z toward the nose, origin under the wing),
* turned by the plane's pitch and bank each frame and rasterized into a depth buffer, so the wing,
* struts and tail overlap correctly from the chase camera's angle. It gets a pixel outline when
* composited, then its navigation lights, beacon and strobes are added on top.
*/
type V3 = [number, number, number];
const enum Mat {
White,
Belly,
Stripe,
Accent,
Glass,
Strut,
Spinner,
Tire,
Blade,
}
const COLORS: readonly RGB[] = ['#eeeef2', '#c8c8d0', '#22346e', '#b8323a', '#1e2a3a', '#b4b4bc', '#d8d8dc', '#2a2a2e', '#34343a'].map(hex);
interface Face {
pts: V3[];
mat: Mat;
twoSided?: boolean;
/** Flaps: rotated down about their hinge line as they extend. */
flap?: -1 | 1;
}
interface Rod {
a: V3;
b: V3;
mat: Mat;
}
const FACES: Face[] = [];
const RODS: Rod[] = [];
function quad(a: V3, b: V3, c: V3, d: V3, mat: Mat, twoSided = false): void {
FACES.push({ pts: [a, b, c, d], mat, twoSided });
}
/** An axis-aligned box as six outward faces. */
function box(x0: number, x1: number, y0: number, y1: number, z0: number, z1: number, mat: Mat, top = mat): void {
quad([x0, y1, z0], [x1, y1, z0], [x1, y1, z1], [x0, y1, z1], top);
quad([x0, y0, z0], [x0, y0, z1], [x1, y0, z1], [x1, y0, z0], mat);
quad([x0, y0, z0], [x1, y0, z0], [x1, y1, z0], [x0, y1, z0], mat);
quad([x0, y0, z1], [x0, y1, z1], [x1, y1, z1], [x1, y0, z1], mat);
quad([x0, y0, z0], [x0, y1, z0], [x0, y1, z1], [x0, y0, z1], mat);
quad([x1, y0, z0], [x1, y0, z1], [x1, y1, z1], [x1, y1, z0], mat);
}
/** Wing surface height at a span position: high on the cabin roof, with a little dihedral. */
const wingY = (x: number): number => 1.3 + Math.abs(x) * 0.03;
const WING_T = 0.13;
export const SPAN = 5.5;
(function build() {
// Fuselage: 16-sided rings from the cowling back to the tail, squared off a little.
const STATIONS: readonly (readonly [number, number, number, number])[] = [
[4.2, 0.05, 0.32, 0.3],
[3.7, 0.08, 0.52, 0.52],
[2.6, 0.2, 0.58, 0.72],
[1.5, 0.38, 0.6, 0.92],
[0.0, 0.4, 0.58, 0.9],
[-1.0, 0.45, 0.5, 0.75],
[-2.6, 0.55, 0.3, 0.42],
[-4.35, 0.7, 0.09, 0.15],
];
const N = 16;
const ring = (st: readonly number[]): V3[] =>
Array.from({ length: N }, (_, k) => {
const a = ((k + 0.5) / N) * Math.PI * 2;
const c = Math.cos(a);
const s = Math.sin(a);
return [st[2] * Math.sign(c) * Math.abs(c) ** 0.75, st[1] + st[3] * Math.sign(s) * Math.abs(s) ** 0.75, st[0]] as V3;
});
const rings = STATIONS.map(ring);
for (let i = 0; i < rings.length - 1; i++) {
for (let k = 0; k < N; k++) {
const k2 = (k + 1) % N;
// Face k is centered at angle (k + 1) / N turns: 0 = right side, 4 = top, 8 = left, 12 = belly.
const at = k + 1;
let mat = at > 9 && at < 15 ? Mat.Belly : Mat.White;
if ((at === 16 || at === 8) && i >= 1 && i <= 5) mat = Mat.Stripe;
if ((at === 15 || at === 9) && i >= 2 && i <= 5) mat = Mat.Accent;
// Cabin windows on the upper sides, the windshield and the rear window.
if ((at === 1 || at === 2 || at === 6 || at === 7) && (i === 3 || i === 4)) mat = Mat.Glass;
if (at >= 2 && at <= 6 && i === 2) mat = Mat.Glass;
if (at >= 3 && at <= 5 && i === 4) mat = Mat.Glass;
quad(rings[i][k], rings[i + 1][k], rings[i + 1][k2], rings[i][k2], mat);
}
}
// Tail cap and spinner.
const tail = rings[rings.length - 1];
for (let k = 1; k < N - 1; k++) FACES.push({ pts: [tail[0], tail[k + 1], tail[k]], mat: Mat.White });
const tip: V3 = [0, 0.05, 4.6];
for (let k = 0; k < N; k++) FACES.push({ pts: [rings[0][(k + 1) % N], rings[0][k], tip], mat: Mat.Spinner });
// Wings, each a tapered slab, with flaps along the inner trailing edge.
for (const side of [-1, 1] as const) {
const r0 = 0.45 * side;
const r1 = SPAN * side;
const lr = 1.05;
const tr = -0.6;
const lt = 0.85;
const tt = -0.35;
const y0 = wingY(0);
const y1 = wingY(SPAN);
const top0: V3[] = [
[r0, y0, lr],
[r1, y1, lt],
[r1, y1, tt],
[r0, y0, tr],
];
const pts = side > 0 ? top0 : [...top0].reverse();
FACES.push({ pts, mat: Mat.White });
FACES.push({ pts: [...pts].reverse().map((p) => [p[0], p[1] - WING_T, p[2]] as V3), mat: Mat.Belly });
// Trailing edge, leading edge and tip.
const te: V3[] = [
[r0, y0, tr],
[r1, y1, tt],
[r1, y1 - WING_T, tt],
[r0, y0 - WING_T, tr],
];
FACES.push({ pts: side > 0 ? te : [...te].reverse(), mat: Mat.Belly });
const le: V3[] = [
[r0, y0 - WING_T, lr],
[r1, y1 - WING_T, lt],
[r1, y1, lt],
[r0, y0, lr],
];
FACES.push({ pts: side > 0 ? le : [...le].reverse(), mat: Mat.White });
const tipF: V3[] = [
[r1, y1, lt],
[r1, y1 - WING_T, lt],
[r1, y1 - WING_T, tt],
[r1, y1, tt],
];
FACES.push({ pts: side > 0 ? tipF : [...tipF].reverse(), mat: Mat.White });
const fx0 = 0.55 * side;
const fx1 = 2.9 * side;
FACES.push({
pts: [
[fx0, wingY(0.55) - 0.04, tr + 0.02],
[fx1, wingY(2.9) - 0.04, tr + 0.13],
[fx1, wingY(2.9) - 0.04, tr - 0.33],
[fx0, wingY(0.55) - 0.04, tr - 0.42],
],
mat: Mat.Belly,
twoSided: true,
flap: side,
});
// Strut from the lower fuselage up to the wing.
RODS.push({ a: [0.5 * side, -0.15, 0.45], b: [2.55 * side, wingY(2.55) - WING_T, 0.35], mat: Mat.Strut });
// Main gear leg and wheel fairing.
RODS.push({ a: [0.42 * side, -0.3, 0.3], b: [1.15 * side, -1.1, 0.15], mat: Mat.Strut });
const wx = 1.2 * side;
box(wx - 0.11, wx + 0.11, -1.55, -1.05, -0.3, 0.5, Mat.White);
box(wx - 0.08, wx + 0.08, -1.6, -1.45, -0.05, 0.25, Mat.Tire);
}
// Nose gear.
RODS.push({ a: [0, -0.25, 3.3], b: [0, -1.1, 3.4], mat: Mat.Strut });
box(-0.1, 0.1, -1.55, -1.05, 3.1, 3.75, Mat.White);
box(-0.07, 0.07, -1.6, -1.45, 3.3, 3.55, Mat.Tire);
// Horizontal stabilizer and the fin, with a navy band near the top.
for (const side of [-1, 1] as const) {
const pts: V3[] = [
[0.08 * side, 0.68, -3.45],
[1.75 * side, 0.7, -3.8],
[1.75 * side, 0.7, -4.3],
[0.08 * side, 0.68, -4.4],
];
FACES.push({ pts: side > 0 ? pts : [...pts].reverse(), mat: Mat.White });
FACES.push({ pts: (side > 0 ? [...pts].reverse() : pts).map((p) => [p[0], p[1] - 0.07, p[2]] as V3), mat: Mat.Belly });
}
FACES.push({
pts: [
[0, 0.78, -2.85],
[0, 1.75, -3.6],
[0, 1.75, -4.4],
[0, 0.75, -4.45],
],
mat: Mat.White,
twoSided: true,
});
FACES.push({
pts: [
[0, 1.75, -3.6],
[0, 2.15, -3.92],
[0, 2.15, -4.32],
[0, 1.75, -4.4],
],
mat: Mat.Stripe,
twoSided: true,
});
})();
// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------
const ZB = new Float32Array(W * H).fill(Infinity);
const CB = new Uint8ClampedArray(W * H * 3);
let bx0 = W;
let bx1 = -1;
let by0 = H;
let by1 = -1;
interface Pose {
f: Frame;
cp: number;
sp: number;
cr: number;
sr: number;
/** Flap angle, radians. */
flaps: number;
}
function toWorld(p: Pose, v: V3): V3 {
const { plane } = p.f;
// Pitch about x (nose up), then bank about z (right wing down).
const y1 = v[1] * p.cp + v[2] * p.sp;
const z1 = v[2] * p.cp - v[1] * p.sp;
const x2 = v[0] * p.cr + y1 * p.sr;
const y2 = y1 * p.cr - v[0] * p.sr;
return [plane.x + x2, plane.y + y2, plane.z + z1];
}
/** Rotate a flap point down about its hinge on the wing's trailing edge. */
function flapPoint(v: V3, a: number): V3 {
const hz = -0.58;
const dz = v[2] - hz;
return [v[0], v[1] + dz * Math.sin(a), hz + dz * Math.cos(a)];
}
function shade(p: Pose, mat: Mat, n: V3): RGB {
const f = p.f;
const base = COLORS[mat];
// Sky light from above, a little bounce from below, and the low sun just right of ahead.
const sky = 0.62 + 0.38 * n[1];
const k = mat === Mat.Glass ? 1 : sky;
const amb = f.amb;
let c: RGB = [base[0] * (amb[0] * 1.25 + 0.05) * k, base[1] * (amb[1] * 1.25 + 0.05) * k, base[2] * (amb[2] * 1.25 + 0.07) * k];
if (mat === Mat.Glass) c = mix(c, f.horizonColor, 0.25 + 0.2 * Math.max(0, n[1]));
const sun = f.sun * Math.max(0, n[0] * 0.135 + n[1] * 0.1 + n[2] * 0.985);
if (sun > 0) c = [c[0] + base[0] * (f.sunColor[0] / 255) * sun * 0.6, c[1] + base[1] * (f.sunColor[1] / 255) * sun * 0.6, c[2] + base[2] * (f.sunColor[2] / 255) * sun * 0.6];
return c;
}
function rasterFace(p: Pose, face: Face): void {
const f = p.f;
const cam = f.cam;
const w = face.pts.map((v) => toWorld(p, face.flap ? flapPoint(v, p.flaps) : v));
// Newell normal.
let nx = 0;
let ny = 0;
let nz = 0;
for (let i = 0; i < w.length; i++) {
const a = w[i];
const b = w[(i + 1) % w.length];
nx += (a[1] - b[1]) * (a[2] + b[2]);
ny += (a[2] - b[2]) * (a[0] + b[0]);
nz += (a[0] - b[0]) * (a[1] + b[1]);
}
const nl = Math.hypot(nx, ny, nz) || 1;
let n: V3 = [nx / nl, ny / nl, nz / nl];
const toCam = n[0] * (cam.x - w[0][0]) + n[1] * (cam.y - w[0][1]) + n[2] * (cam.z - w[0][2]);
if (toCam <= 0) {
if (!face.twoSided) return;
n = [-n[0], -n[1], -n[2]];
}
const sp = w.map((v) => project(cam, v[0], v[1], v[2]));
if (sp.some((q) => !q)) return;
const pts = sp as { x: number; y: number }[];
let minX = W;
let maxX = -1;
let minY = H;
let maxY = -1;
for (const q of pts) {
minX = Math.min(minX, q.x);
maxX = Math.max(maxX, q.x);
minY = Math.min(minY, q.y);
maxY = Math.max(maxY, q.y);
}
const xa = Math.max(0, Math.floor(minX));
const xb = Math.min(W - 1, Math.ceil(maxX));
const ya = Math.max(0, Math.floor(minY));
const yb = Math.min(H - 1, Math.ceil(maxY));
if (xa > xb || ya > yb) return;
// Signed area gives the winding, so inside means every edge function has that sign.
let area = 0;
for (let i = 0; i < pts.length; i++) {
const a = pts[i];
const b = pts[(i + 1) % pts.length];
area += a.x * b.y - b.x * a.y;
}
const sgn = area >= 0 ? 1 : -1;
const col = shade(p, face.mat, n);
const p0 = w[0];
const num = n[0] * (p0[0] - cam.x) + n[1] * (p0[1] - cam.y) + n[2] * (p0[2] - cam.z);
for (let y = ya; y <= yb; y++) {
const py = y + 0.5;
for (let x = xa; x <= xb; x++) {
const px = x + 0.5;
let inside = true;
for (let i = 0; i < pts.length; i++) {
const a = pts[i];
const b = pts[(i + 1) % pts.length];
if (((b.x - a.x) * (py - a.y) - (b.y - a.y) * (px - a.x)) * sgn < 0) {
inside = false;
break;
}
}
if (!inside) continue;
// Exact depth: where this pixel's ray meets the face's plane.
const dx = (px - CX) / F;
const dy = -(py - HORIZON) / F;
const den = n[0] * dx + n[1] * dy + n[2];
const t = Math.abs(den) > 1e-6 ? num / den : 1e9;
write(x, y, t, col);
}
}
}
function write(x: number, y: number, depth: number, c: RGB): void {
const j = y * W + x;
if (depth >= ZB[j]) return;
ZB[j] = depth;
CB[j * 3] = c[0];
CB[j * 3 + 1] = c[1];
CB[j * 3 + 2] = c[2];
if (x < bx0) bx0 = x;
if (x > bx1) bx1 = x;
if (y < by0) by0 = y;
if (y > by1) by1 = y;
}
function rasterRod(p: Pose, a: V3, b: V3, col: RGB): void {
const cam = p.f.cam;
const wa = toWorld(p, a);
const wb = toWorld(p, b);
const pa = project(cam, wa[0], wa[1], wa[2]);
const pb = project(cam, wb[0], wb[1], wb[2]);
if (!pa || !pb) return;
const n = Math.ceil(Math.hypot(pb.x - pa.x, pb.y - pa.y) * 2) + 1;
for (let i = 0; i <= n; i++) {
const k = i / n;
const x = Math.floor(pa.x + (pb.x - pa.x) * k);
const y = Math.floor(pa.y + (pb.y - pa.y) * k);
if (x < 0 || y < 0 || x >= W || y >= H) continue;
write(x, y, pa.d + (pb.d - pa.d) * k - 0.05, col);
}
}
const PROP_C: V3 = [0, 0.05, 4.62];
const PROP_R = 0.95;
const BLUR = hex('#a0a0a8');
const PROP_TIP = hex('#e8c040');
/** The propeller seen from behind while it spins: a faint disc with a ring of yellow tips. */
function drawPropDisc(s: Surface, p: Pose): void {
const f = p.f;
const blur = clamp01((f.propRate - 4) / 10);
if (blur <= 0) return;
const c = toWorld(p, PROP_C);
const pc = project(f.cam, c[0], c[1], c[2]);
if (!pc) return;
const rpx = (PROP_R * F) / pc.d;
const R = Math.ceil(rpx) + 1;
const col = mix([BLUR[0] * f.amb[0], BLUR[1] * f.amb[1], BLUR[2] * f.amb[2]], f.horizonColor, 0.25);
const tip: RGB = [PROP_TIP[0] * f.amb[0] * 1.2, PROP_TIP[1] * f.amb[1] * 1.2, PROP_TIP[2] * f.amb[2] * 1.2];
for (let y = Math.floor(pc.y - R); y <= pc.y + R; y++) {
for (let x = Math.floor(pc.x - R); x <= pc.x + R; x++) {
const dx = (x + 0.5 - pc.x) / rpx;
const dy = (y + 0.5 - pc.y) / rpx;
const r = Math.hypot(dx, dy);
if (r > 1) continue;
const flicker = 0.7 + 0.3 * Math.sin(f.propAngle * 3 + Math.atan2(dy, dx) * 2);
s.blend(x, y, r > 0.86 ? tip : col, ditherStep(blur * (r > 0.86 ? 0.45 : 0.2) * flicker, x, y, 6));
}
}
}
/** Once it has slowed enough to follow, the two blades themselves, turning to a stop. */
function drawPropBlades(p: Pose): void {
const f = p.f;
if (f.propRate > 9) return;
const a = f.propAngle;
const col = shade(p, Mat.Blade, [0, 0, -1]);
for (const dir of [1, -1]) {
const e: V3 = [PROP_C[0] + Math.cos(a) * PROP_R * dir, PROP_C[1] + Math.sin(a) * PROP_R * dir, PROP_C[2]];
rasterRod(p, PROP_C, e, col);
// The blades are wide near the hub.
const e2: V3 = [PROP_C[0] + Math.cos(a) * PROP_R * 0.6 * dir, PROP_C[1] + Math.sin(a) * PROP_R * 0.6 * dir + 0.06, PROP_C[2]];
rasterRod(p, [PROP_C[0], PROP_C[1] + 0.06, PROP_C[2]], e2, col);
}
}
/** A light on the airframe: hidden when the plane itself is in front of it. */
function navLight(s: Surface, p: Pose, v: V3, c: RGB, k: number, halo: number): void {
if (k <= 0) return;
const w = toWorld(p, v);
const q = project(p.f.cam, w[0], w[1], w[2]);
if (!q) return;
const x = Math.floor(q.x);
const y = Math.floor(q.y);
if (x < 0 || y < 0 || x >= W || y >= H) return;
if (ZB[y * W + x] < q.d - 0.4) return;
const R = Math.ceil(halo);
for (let dy = -R; dy <= R; dy++) {
for (let dx = -R; dx <= R; dx++) {
const d = Math.hypot(dx, dy);
if (d > halo + 0.3) continue;
s.light(x + dx, y + dy, c, k * (d < 0.5 ? 1 : 0.5 * (1 - d / (halo + 0.6)) ** 1.5));
}
}
}
const RED = hex('#ff3628');
const GREEN = hex('#40ff70');
const WHITE = hex('#ffffff');
export function drawPlane(s: Surface, f: Frame): void {
const pose: Pose = {
f,
cp: Math.cos(f.plane.pitch),
sp: Math.sin(f.plane.pitch),
cr: Math.cos(f.plane.roll),
sr: Math.sin(f.plane.roll),
flaps: 0.35 * progress(f.t, 222, 232) + 0.2 * progress(f.t, 248, 256) - 0.55 * progress(f.t, 280, 286),
};
drawPropDisc(s, pose);
bx0 = W;
bx1 = -1;
by0 = H;
by1 = -1;
for (const face of FACES) rasterFace(pose, face);
for (const r of RODS) rasterRod(pose, r.a, r.b, shade(pose, r.mat, [0, 1, 0]));
drawPropBlades(pose);
const empty = (x: number, y: number) => x < 0 || y < 0 || x >= W || y >= H || ZB[y * W + x] === Infinity;
const col: [number, number, number] = [0, 0, 0];
for (let y = by0; y <= by1; y++) {
for (let x = bx0; x <= bx1; x++) {
const j = y * W + x;
if (ZB[j] === Infinity) continue;
const m = empty(x - 1, y) || empty(x + 1, y) || empty(x, y - 1) || empty(x, y + 1) ? 0.6 : 1;
col[0] = CB[j * 3] * m;
col[1] = CB[j * 3 + 1] * m;
col[2] = CB[j * 3 + 2] * m;
s.set(x, y, col);
}
}
const t = f.t;
const tipY = wingY(SPAN) - WING_T / 2;
navLight(s, pose, [-SPAN - 0.05, tipY, 0.5], RED, 0.95, 2.2);
navLight(s, pose, [SPAN + 0.05, tipY, 0.5], GREEN, 0.95, 2.2);
navLight(s, pose, [0, 0.72, -4.47], WHITE, 0.8, 1.6);
const beacon = f.beacon * Math.max(0, Math.sin(t * Math.PI * 1.8)) ** 6;
navLight(s, pose, [0, 2.2, -4.12], RED, beacon, 3);
const u = t % 1.3;
const strobe = f.strobes * (u < 0.05 || (u > 0.15 && u < 0.2) ? 1 : 0);
navLight(s, pose, [-SPAN - 0.05, tipY, 0.1], WHITE, strobe * 1.2, 5);
navLight(s, pose, [SPAN + 0.05, tipY, 0.1], WHITE, strobe * 1.2, 5);
for (let y = by0; y <= by1; y++) ZB.fill(Infinity, y * W + bx0, y * W + bx1 + 1);
}

View File

@ -0,0 +1,191 @@
import { bayer, ditherStep, hex, mix, type RGB } from '../../engine/color';
import { progress } from '../../engine/Timeline';
import { Rng } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import { SKY_BANDS, SUN_R, type Frame } from './timeline';
import { CX, DOWNTOWN, F, HORIZON, W } from './world';
/** Which gradient band each sky pixel uses, with dithered seams; fixed by the layout. */
const BAND_MAP: Uint8Array = (() => {
const map = new Uint8Array(W * HORIZON);
for (let y = 0; y < HORIZON; y++) {
for (let x = 0; x < W; x++) {
const v = (y / (HORIZON - 1)) ** 1.15 * (SKY_BANDS - 1) + (bayer(x, y) - 0.5) * 0.95;
map[y * W + x] = Math.max(0, Math.min(SKY_BANDS - 1, Math.round(v)));
}
}
return map;
})();
interface Star {
x: number;
y: number;
mag: number;
twinkle: number;
phase: number;
tint: RGB;
}
const STARS: Star[] = (() => {
const r = new Rng(23);
const out: Star[] = [];
for (let i = 0; i < 230; i++) {
const y = Math.floor(Math.pow(r.next(), 1.3) * (HORIZON - 14));
out.push({
x: r.int(0, W - 1),
y,
mag: Math.pow(r.next(), 2.4),
twinkle: r.range(0.6, 2.4),
phase: r.range(0, Math.PI * 2),
tint: r.next() < 0.2 ? hex('#cad8ff') : r.next() < 0.2 ? hex('#ffe4c0') : hex('#ffffff'),
});
}
return out;
})();
function drawStars(s: Surface, f: Frame): void {
if (f.stars <= 0) return;
for (const st of STARS) {
// The faint ones go first, and the ones low in the east before those overhead.
const vis = f.stars * (0.35 + 0.65 * st.mag) * (1 - 0.6 * (st.y / HORIZON) * (1 - f.stars));
const tw = 0.7 + 0.3 * Math.sin(f.t * st.twinkle + st.phase);
const a = vis * tw;
s.blend(st.x, st.y, st.tint, a);
if (st.mag > 0.82) {
const arm = a * 0.3;
s.blend(st.x - 1, st.y, st.tint, arm);
s.blend(st.x + 1, st.y, st.tint, arm);
s.blend(st.x, st.y - 1, st.tint, arm);
s.blend(st.x, st.y + 1, st.tint, arm);
}
}
}
const CITY_GLOW = hex('#d08a58');
/** Sodium light from the city glowing in the haze above it, gone by dawn. */
export function drawCityGlow(s: Surface, f: Frame): void {
const dz = DOWNTOWN.z - f.cam.z;
const k = f.lights * (1 - progress(f.t, 140, 230)) * Math.min(1, dz / 1500);
if (k <= 0 || dz <= 0) return;
const cx = CX + ((DOWNTOWN.x - f.cam.x) * F) / Math.max(dz, 1200);
const spread = 34 + 50000 / dz;
for (let x = Math.max(0, Math.floor(cx - spread * 2.2)); x < Math.min(W, cx + spread * 2.2); x++) {
const across = Math.exp(-(((x - cx) / spread) ** 2));
for (let y = HORIZON - 26; y < HORIZON; y++) {
const a = k * 0.32 * across * Math.exp(-(HORIZON - y) / 8);
s.light(x, y, CITY_GLOW, a);
}
}
}
const GLOW_ROSE = hex('#ff8a9a');
const GLOW_WARM = hex('#ffb070');
const HALO = hex('#fff2cc');
/**
* Shapes centered on the sun, which only rises (its column is fixed), so each is built once per
* whole-pixel sun height and reused.
*/
function cachedBySunY(build: (cy: number) => Float32Array): (cy: number) => Float32Array {
const cache = new Map<number, Float32Array>();
return (cy) => {
const key = Math.round(cy);
let shape = cache.get(key);
if (!shape) cache.set(key, (shape = build(key)));
return shape;
};
}
const GLOW_R = 170;
const glowShape = (sunX: number) =>
cachedBySunY((cy) => {
const out = new Float32Array(W * HORIZON);
for (let y = 0; y < HORIZON; y++) {
for (let x = 0; x < W; x++) {
const d = Math.hypot((x - sunX) * 0.75, (y - cy) * 1.9);
const q = Math.max(0, 1 - d / GLOW_R);
out[y * W + x] = q * q * Math.sqrt(q);
}
}
return out;
});
let glowFor: ((cy: number) => Float32Array) | undefined;
function drawDawnGlow(s: Surface, f: Frame): void {
if (f.glow <= 0) return;
const col = mix(GLOW_ROSE, GLOW_WARM, progress(f.t, 170, 270));
glowFor ??= glowShape(f.sunX);
const shape = glowFor(Math.max(f.sunY, HORIZON - 6));
const k = f.glow * 0.5;
for (let y = 0; y < HORIZON; y++) {
for (let x = 0; x < W; x++) {
const q = shape[y * W + x];
if (q > 0) s.blend(x, y, col, ditherStep(k * q, x, y, 16));
}
}
}
function drawSun(s: Surface, f: Frame): void {
if (f.sunY > HORIZON + 10) return;
const cx = Math.round(f.sunX);
const cy = Math.round(f.sunY);
const glowR = 30 + 16 * f.sun;
const halo = mix(f.sunColor, HALO, 0.35);
for (let y = Math.max(0, cy - glowR); y < Math.min(HORIZON, cy + glowR); y++) {
for (let x = cx - glowR; x <= cx + glowR; x++) {
const d = Math.hypot(x - cx, y - cy);
if (d > glowR) continue;
s.blend(x, y, halo, ditherStep(Math.pow(1 - d / glowR, 2) * (0.35 + 0.3 * f.glow), x, y, 12));
}
}
const core = mix(f.sunColor, [255, 255, 255], 0.7);
for (let y = -SUN_R; y <= SUN_R; y++) {
for (let x = -SUN_R; x <= SUN_R; x++) {
const d2 = x * x + y * y;
if (d2 > SUN_R * SUN_R + SUN_R * 0.8 || cy + y >= HORIZON) continue;
s.set(cx + x, cy + y, d2 > (SUN_R - 1.5) ** 2 ? mix(core, f.sunColor, 0.5) : core);
}
}
}
export function drawSky(s: Surface, f: Frame): void {
for (let y = 0; y < HORIZON; y++) {
for (let x = 0; x < W; x++) s.set(x, y, f.skyBands[BAND_MAP[y * W + x]]);
}
drawStars(s, f);
drawDawnGlow(s, f);
drawSun(s, f);
}
const rayShape = (sunX: number) =>
cachedBySunY((sy) => {
const out = new Float32Array(W * HORIZON);
for (let y = 0; y < HORIZON; y++) {
for (let x = 0; x < W; x++) {
const dx = x - sunX;
const dy = sy - y;
if (dy < 2) continue;
const a = Math.atan2(dx, dy);
const streak = 0.5 + 0.5 * Math.sin(a * 11 + 1.3) * Math.sin(a * 5 - 0.4);
out[y * W + x] = streak * Math.exp(-Math.hypot(dx, dy) / 60) * Math.max(0, 1 - Math.abs(a) / 1.5);
}
}
return out;
});
let raysFor: ((sy: number) => Float32Array) | undefined;
/** Rays fanning up from the sun once it clears the ridge, over the clouds. */
export function drawSunRays(s: Surface, f: Frame): void {
if (f.sun <= 0) return;
const col = mix(f.sunColor, HALO, 0.5);
raysFor ??= rayShape(f.sunX);
const shape = raysFor(f.sunY);
const k = f.sun * 0.1;
for (let y = 0; y < HORIZON; y++) {
for (let x = 0; x < W; x++) {
const v = shape[y * W + x] * k;
if (v > 0.004) s.light(x, y, col, v);
}
}
}

View File

@ -0,0 +1,221 @@
import { gradient, hex, mix, scale, type RGB } from '../../engine/color';
import { colorTrack, ease, progress, track } from '../../engine/Timeline';
import { noise1 } from '../../engine/rng';
import { DURATION, speedAt, TIMES, travelAt } from './flight';
import { CHASE, CRUISE_ALT, GEAR_H, type Cam } from './world';
export { DURATION, TIMES };
/** Light phases: deep pre-dawn navy → blue hour → first pink → rose and orange → sunrise. */
const P = [0, 90, 180, 250, 300] as const;
const phase = (...c: string[]) => colorTrack(P.map((t, i) => [t, hex(c[i])] as const));
/** Sky gradient stops from zenith to horizon. */
const SKY = [
phase('#03071a', '#060e2a', '#12245a', '#2a4a8a', '#3a68ae'),
phase('#060c26', '#0c1a40', '#1e3672', '#4268a4', '#5e8ec6'),
phase('#0b1434', '#152654', '#3c4e8c', '#7c88b8', '#9cb2d8'),
phase('#121c42', '#243262', '#7a6c9e', '#d89aa6', '#f2bfae'),
phase('#1c2550', '#3a3c6c', '#c88a96', '#ffb27e', '#ffd290'),
];
/** Light falling on everything in the scene, as a per-channel multiplier. */
const AMBIENT = phase('#262c4c', '#30385e', '#58588a', '#a28ca8', '#f0d8c6');
/** Haze that swallows the far ground. */
const FOG = phase('#141c40', '#26305a', '#7c6c94', '#d0a0a8', '#f0c8b0');
/** Cloud colors for the high and low decks: shaded underside, underlit by the dawn, bright thin edges. */
export const HIGH_SHADE = phase('#0a1230', '#16204a', '#4a4a7c', '#a06c8c', '#c0909e');
export const HIGH_LIT = phase('#121a3e', '#262c5c', '#b07890', '#ff9c84', '#ffc8a0');
export const HIGH_EDGE = phase('#1a2450', '#343e72', '#d8a0b4', '#ffc4aa', '#fff0e0');
export const LOW_SHADE = phase('#080e26', '#121a3a', '#383a64', '#6c5678', '#9a8292');
export const LOW_LIT = phase('#0e153a', '#20284e', '#76628a', '#ec8a7a', '#ffb488');
export const LOW_EDGE = phase('#182044', '#2c3460', '#a08aa8', '#ffb09a', '#ffe0c8');
export const MOUNTAIN_FAR = phase('#0c1230', '#161e44', '#3e3e6c', '#7a5c84', '#8c76a0');
export const MOUNTAIN_NEAR = phase('#070b20', '#0e1432', '#2a2a52', '#4c3c62', '#5c4c72');
/** The sun rises behind the mountains just right of the runway, cresting the ridge around touchdown. */
export const SUN_R = 6;
/** Rows from the top of the sun's center: it rises steadily through the saddle at x = SUN_X. */
const sunY = track(
[
[150, 128],
[DURATION, 78],
],
ease.linear,
);
const SUN_X = 185;
const sunColor = colorTrack([
[200, hex('#ff5a3a')],
[TIMES.touchdown, hex('#ff8a44')],
[DURATION, hex('#ffb864')],
]);
/** Warm glow on the horizon around the sun. */
const glow = track([
[50, 0],
[150, 0.3],
[220, 0.7],
[TIMES.touchdown, 1],
]);
const stars = track([
[0, 1],
[90, 0.75],
[175, 0],
]);
/** Windows and streetlights stay on but count for less as the sky brightens. */
const lights = track([
[0, 1],
[180, 0.9],
[250, 0.6],
[DURATION, 0.35],
]);
/** How strongly the dawn underlights each cloud deck; the high one catches it first. */
const highGlow = track([
[110, 0],
[200, 0.6],
[260, 1],
]);
const lowGlow = track([
[160, 0],
[240, 0.6],
[285, 1],
]);
/** Pale ground mist gathering in the fields at sunrise. */
const mist = track([
[180, 0],
[260, 0.45],
[DURATION, 0.55],
]);
const pitch = track([
[0, 0],
[TIMES.descent[0], 0],
[190, -0.035],
[255, -0.03],
[264, 0.05],
[TIMES.touchdown, 0.07],
[273, 0.065],
[277, 0],
]);
/** Engine power, 0–1; the propeller turns at 38 rev/s at full. */
const rpm = track([
[0, 1],
[250, 0.9],
[268, 0.6],
[TIMES.propDown[0], 0.55],
[TIMES.propDown[1], 0],
]);
const REV = 38;
const PROP_DT = 0.02;
const PROP: Float64Array = (() => {
const n = Math.ceil(DURATION / PROP_DT) + 2;
const out = new Float64Array(n);
for (let i = 1; i < n; i++) out[i] = out[i - 1] + rpm((i - 0.5) * PROP_DT) * REV * PROP_DT;
return out;
})();
function propTurns(t: number): number {
const u = Math.max(0, t) / PROP_DT;
const i = Math.min(PROP.length - 2, Math.floor(u));
return PROP[i] + (PROP[i + 1] - PROP[i]) * (u - i);
}
export const SKY_BANDS = 24;
export interface Plane {
x: number;
y: number;
z: number;
/** Nose-up angle and right-wing-down bank, radians. */
pitch: number;
roll: number;
}
export interface Frame {
t: number;
cam: Cam;
plane: Plane;
/** Height of the wheels above the ground, m. */
agl: number;
speed: number;
/** Propeller angle (radians) and speed (rev/s). */
propAngle: number;
propRate: number;
skyBands: RGB[];
horizonColor: RGB;
/** Ambient light multiplier, 0–1 per channel. */
amb: RGB;
fog: RGB;
sunX: number;
sunY: number;
sunColor: RGB;
/** Direct sunlight on the scene once the sun is up, 0–1. */
sun: number;
glow: number;
stars: number;
lights: number;
highGlow: number;
lowGlow: number;
mist: number;
/** Landing light, 0–1. */
landing: number;
/** Strobes and beacon still running (they're switched off after landing). */
strobes: number;
beacon: number;
/** Overall brightness for the fade in/out. */
fade: number;
}
export function frameAt(t: number): Frame {
const sky = SKY.map((c) => c(t));
const z = travelAt(t);
const alt = GEAR_H + (CRUISE_ALT - GEAR_H) * (1 - progress(t, TIMES.descent[0], TIMES.descent[1]));
// Light turbulence aloft, smoothing out on short final.
const calm = 1 - progress(t, 236, 262);
const plane: Plane = {
x: 0.8 * (noise1(t * 0.06, 1) - 0.5) * calm,
y: alt + 1.1 * (noise1(t * 0.22, 2) - 0.5) * calm,
z,
pitch: pitch(t) + 0.02 * (noise1(t * 0.3, 3) - 0.5) * calm,
roll: (0.1 * (noise1(t * 0.08, 4) - 0.5) + 0.02 * (noise1(t * 0.5, 5) - 0.5)) * calm,
};
const cam: Cam = {
x: CHASE.right + 0.9 * (noise1(t * 0.035, 11) - 0.5),
y: alt + CHASE.up + 0.7 * (noise1(t * 0.045, 12) - 0.5),
z: z - CHASE.back - 1.6 * (noise1(t * 0.03, 13) - 0.5),
};
const amb = scale(AMBIENT(t), 1 / 255);
return {
t,
cam,
plane,
agl: alt - GEAR_H,
speed: speedAt(t),
propAngle: (propTurns(t) % 1) * Math.PI * 2,
propRate: rpm(t) * REV,
skyBands: Array.from({ length: SKY_BANDS }, (_, i) => gradient(sky, i / (SKY_BANDS - 1))),
horizonColor: sky[4],
amb,
fog: mix(FOG(t), sky[4], 0.3),
sunX: SUN_X,
sunY: sunY(t),
sunColor: sunColor(t),
sun: progress(t, 266, 292),
glow: glow(t),
stars: stars(t),
lights: lights(t),
highGlow: highGlow(t),
lowGlow: lowGlow(t),
mist: mist(t),
landing: progress(t, 200, 206) * (1 - progress(t, 293, 295)),
strobes: t < 279 ? 1 : 0,
beacon: t < 294 ? 1 : 0,
fade: progress(t, TIMES.fadeIn[0], TIMES.fadeIn[1]) * (1 - progress(t, TIMES.fadeOut[0], TIMES.fadeOut[1])),
};
}
/** Apply the frame's ambient light to a base (daylight) color. */
export function lit(f: Frame, base: RGB): RGB {
return [base[0] * f.amb[0], base[1] * f.amb[1], base[2] * f.amb[2]];
}

View File

@ -0,0 +1,171 @@
import { hash, noise2 } from '../../engine/rng';
import { TIMES, travelAt } from './flight';
/**
* Fixed layout of the scene, in meters: x to the right, y up, z forward along the flight path
* (heading east, into the sunrise). The plane flies along x = 0 and the chase camera keeps level,
* so the horizon always sits across the middle of the 320x180 canvas.
*/
export const W = 320;
export const H = 180;
export const HORIZON = 90;
export const CX = W / 2;
/** Focal length in pixels: a ground point d meters ahead and h below the camera sits h·F/d rows under the horizon. */
export const F = 220;
/** Where the chase camera rides relative to the plane: behind, to the right and a little above. */
export const CHASE = { back: 26, right: 4.5, up: 4.5 };
export const CRUISE_ALT = 260;
/** Height of the plane's origin above the ground when it sits on its wheels. */
export const GEAR_H = 1.55;
export interface Cam {
x: number;
y: number;
z: number;
}
export interface Pt {
x: number;
y: number;
/** Distance ahead of the camera. */
d: number;
}
export function project(c: Cam, X: number, Y: number, Z: number): Pt | undefined {
const d = Z - c.z;
if (d < 0.5) return undefined;
const k = F / d;
return { x: CX + (X - c.x) * k, y: HORIZON - (Y - c.y) * k, d };
}
/** How much of a surface d meters away shows through the morning haze. */
export const clarity = (d: number): number => Math.exp(-d / 11000);
export const smoothstep = (a: number, b: number, x: number): number => {
const u = Math.max(0, Math.min(1, (x - a) / (b - a)));
return u * u * (3 - 2 * u);
};
/** Distance from v to the nearest of a set of lines spaced `period` apart. */
export const gridDist = (v: number, period: number, offset = 0): number => {
const u = v - offset;
return Math.abs(u - Math.round(u / period) * period);
};
/**
* Share of a pixel `fp` meters across covered by a stripe `w` wide whose center is `m` away. Box
* filtered, so thin far-off features fade into their surroundings instead of flickering.
*/
export const cover = (m: number, w: number, fp: number): number => {
if (fp <= w) return m < w / 2 ? 1 : 0;
return m < fp / 2 ? w / fp : 0;
};
// ---------------------------------------------------------------------------
// The airport, lined up with the flight path
// ---------------------------------------------------------------------------
export const TOUCH_Z = travelAt(TIMES.touchdown);
export const STOP_Z = travelAt(TIMES.stop);
export const RUNWAY = { z0: TOUCH_Z - 320, z1: TOUCH_Z + 1500, half: 15 };
/** Parallel taxiway on the left, its connectors, and the apron in front of the hangars. */
export const TAXI_X = -130;
export const CONNECTORS: readonly number[] = [RUNWAY.z0 + 40, TOUCH_Z + 560, RUNWAY.z1 - 40];
export const APRON = { x0: -330, x1: -150, z0: STOP_Z + 300, z1: STOP_Z + 950 };
/** Mown grass around the field, and the cleared strip under the approach lights reaching out over the farms. */
export const AIRPORT = { x0: -480, x1: 300, z0: RUNWAY.z0 - 120, z1: RUNWAY.z1 + 260 };
export const APPROACH = { half: 40, z0: RUNWAY.z0 - 950 };
// ---------------------------------------------------------------------------
// The city, passed on the right at two and a half minutes
// ---------------------------------------------------------------------------
export const DOWNTOWN = { x: 900, z: travelAt(TIMES.cityPass) + 1600, r: 520 };
const URBAN = { x: 700, z: DOWNTOWN.z - 500, rx: 2300, rz: 2900 };
export const URBAN_BOUNDS = { x0: URBAN.x - URBAN.rx * 1.2, x1: URBAN.x + URBAN.rx * 1.2, z0: URBAN.z - URBAN.rz * 1.2, z1: URBAN.z + URBAN.rz * 1.2 };
export const BLOCK = 110;
export const STREET_W = 12;
/** A divided highway running beside the flight path all the way to the airport. */
export const HWY_X = 420;
function urbanExact(X: number, Z: number): number {
const dx = (X - URBAN.x) / URBAN.rx;
const dz = (Z - URBAN.z) / URBAN.rz;
const r2 = dx * dx + dz * dz;
if (r2 > 1.6) return 0;
const r = Math.sqrt(r2) + (noise2(X / 700, Z / 700, 5) - 0.5) * 0.4;
return smoothstep(1.02, 0.55, r) * smoothstep(APPROACH.z0 - 200, APPROACH.z0 - 900, Z);
}
/** urbanExact sampled every 40 m, since the ground looks it up for most pixels of every frame. */
const UG = 40;
const UW = Math.ceil((URBAN_BOUNDS.x1 - URBAN_BOUNDS.x0) / UG) + 1;
const UH = Math.ceil((URBAN_BOUNDS.z1 - URBAN_BOUNDS.z0) / UG) + 1;
const URBAN_GRID: Float32Array = (() => {
const g = new Float32Array(UW * UH);
for (let j = 0; j < UH; j++) for (let i = 0; i < UW; i++) g[j * UW + i] = urbanExact(URBAN_BOUNDS.x0 + i * UG, URBAN_BOUNDS.z0 + j * UG);
return g;
})();
/** How built up the land is, from 0 (farmland) to 1 (dense city), with a ragged suburban edge. */
export function urbanAt(X: number, Z: number): number {
const u = (X - URBAN_BOUNDS.x0) / UG;
const v = (Z - URBAN_BOUNDS.z0) / UG;
if (u < 0 || v < 0 || u >= UW - 1 || v >= UH - 1) return 0;
const i = Math.floor(u);
const j = Math.floor(v);
const fu = u - i;
const fv = v - j;
const k = j * UW + i;
const a = URBAN_GRID[k];
const b = URBAN_GRID[k + 1];
const c = URBAN_GRID[k + UW];
const d = URBAN_GRID[k + UW + 1];
return a + (b - a) * fu + (c - a) * fv + (a - b - c + d) * fu * fv;
}
/** Cheap smooth value noise in [0, 1) from a small repeating table, for subtle ground texture. */
const TN = 64;
const TEX: Float32Array = Float32Array.from({ length: TN * TN }, (_, i) => hash(i % TN, (i / TN) | 0, 99));
export function tex2(x: number, z: number): number {
const ix = Math.floor(x);
const iz = Math.floor(z);
let fx = x - ix;
let fz = z - iz;
fx = fx * fx * (3 - 2 * fx);
fz = fz * fz * (3 - 2 * fz);
const x0 = ix & (TN - 1);
const x1 = (ix + 1) & (TN - 1);
const z0 = (iz & (TN - 1)) * TN;
const z1 = ((iz + 1) & (TN - 1)) * TN;
const a = TEX[z0 + x0];
const b = TEX[z0 + x1];
const c = TEX[z1 + x0];
const d = TEX[z1 + x1];
return a + (b - a) * fx + (c - a) * fz + (a - b - c + d) * fx * fz;
}
// ---------------------------------------------------------------------------
// Farmland: a patchwork of fields, with a farmstead here and there
// ---------------------------------------------------------------------------
export const FIELD_W = 190;
export const FIELD_D = 150;
/** Gravel roads running east, and section roads across them. */
export const FARM_ROADS_X: readonly number[] = [-760, 1480];
export const SECTION = { period: 1750, offset: 400 };
/** Each row of fields is offset sideways so the patchwork doesn't line up. */
export const fieldShift = (cz: number): number => hash(cz, 0, 21) * FIELD_W;
/** The farmyard in a field cell, if it has one: its center in world meters. */
export function farmstead(cx: number, cz: number): { x: number; z: number } | undefined {
if (hash(cx, cz, 27) > 0.11) return undefined;
const x = cx * FIELD_W - fieldShift(cz) + FIELD_W * (0.25 + 0.5 * hash(cx, cz, 28));
const z = cz * FIELD_D + FIELD_D * (0.3 + 0.4 * hash(cx, cz, 29));
if (urbanAt(x, z) > 0.05 || (x > AIRPORT.x0 - 40 && x < AIRPORT.x1 + 40 && z > AIRPORT.z0 - 40 && z < AIRPORT.z1 + 40)) return undefined;
if (Math.abs(x - HWY_X) < 60) return undefined;
return { x, z };
}

View File

@ -1,13 +1,14 @@
import type { Meditation } from './types'; import type { Meditation } from './types';
import { desertSunrise } from './desert-sunrise'; import { desertSunrise } from './desert-sunrise';
import { mediterraneanCoast } from './mediterranean-coast'; import { mediterraneanCoast } from './mediterranean-coast';
import { morningFlight } from './morning-flight';
import { northernCabin } from './northern-cabin'; import { northernCabin } from './northern-cabin';
import { ringedPlanet } from './ringed-planet'; import { ringedPlanet } from './ringed-planet';
import { theReef } from './the-reef'; import { theReef } from './the-reef';
import { tibetanMonastery } from './tibetan-monastery'; import { tibetanMonastery } from './tibetan-monastery';
/** Every meditation listed on the main menu, in display order. Add new ones here. */ /** Every meditation listed on the main menu, in display order. Add new ones here. */
export const meditations: readonly Meditation[] = [northernCabin, mediterraneanCoast, theReef, ringedPlanet, desertSunrise, tibetanMonastery]; export const meditations: readonly Meditation[] = [northernCabin, mediterraneanCoast, theReef, ringedPlanet, desertSunrise, tibetanMonastery, morningFlight];
export function findMeditation(id: string): Meditation | undefined { export function findMeditation(id: string): Meditation | undefined {
return meditations.find((m) => m.id === id); return meditations.find((m) => m.id === id);

View File

@ -22,8 +22,9 @@ export interface Meditation {
/** /**
* Optional ambient sound that loops seamlessly, kept in step with the scene clock. By default it * Optional ambient sound that loops seamlessly, kept in step with the scene clock. By default it
* plays for the whole meditation; with `from` it stays silent until then and fades in over `fadeIn` * plays for the whole meditation; with `from` it stays silent until then and fades in over `fadeIn`
* seconds, starting from the beginning of the file. * seconds, starting from the beginning of the file. With `until` it fades to silence over `fadeOut`
* seconds ending at that moment, instead of at the end of the meditation.
*/ */
ambience?: { src: string; volume?: number; from?: number; fadeIn?: number }; ambience?: { src: string; volume?: number; from?: number; fadeIn?: number; until?: number; fadeOut?: number };
createScene(): Scene; createScene(): Scene;
} }

View File

@ -30,7 +30,7 @@ class Soundtrack {
constructor(m: Meditation, enabled: boolean) { constructor(m: Meditation, enabled: boolean) {
this.music = new Music(enabled ? m.music : undefined, 0.75); this.music = new Music(enabled ? m.music : undefined, 0.75);
const a = m.ambience; const a = m.ambience;
this.ambience = new AmbientLoop(enabled ? a?.src : undefined, a?.volume, a?.fadeIn, undefined, a?.from); this.ambience = new AmbientLoop(enabled ? a?.src : undefined, a?.volume, a?.fadeIn, a?.fadeOut, a?.from, a?.until);
} }
play(t: number): void { play(t: number): void {