Add Cyberpunk City meditation scene

- New 5-minute pixel scene: rain-soaked neon avenue with buildings, crowds, traffic, holograms, and wet-street reflections, drifting to a plaza screen that dissolves into a moonlit sea
- Generalize ambience to support layering multiple loops (rain + city noise) in types and Player
- Register the meditation and document it plus the new `ambience` list form
This commit is contained in:
Brian Fertig 2026-10-31 16:21:23 -06:00
parent cd6a945dca
commit 5e19f6e08e
22 changed files with 3000 additions and 15 deletions

View File

@ -40,6 +40,7 @@ so edits on the host reload in the browser; don't run it and `npm run dev` on th
| `ringed-planet` | The Ringed Planet — drifting in high orbit above a ringed giant | 5 min |
| `desert-sunrise` | Desert Sunrise — dawn breaks over a canyon stream | 5 min |
| `tibetan-monastery` | Monastery Above the Clouds — prayer flags and snowfall on a high summit | 5 min |
| `cyberpunk-city` | Cyberpunk City — drifting over a neon city in the rain | 5 min |
Each meditation lives in `src/meditations/<id>/` and is registered in `src/meditations/registry.ts`.
A scene is a pure function of time (`render(surface, t)`), drawn pixel by pixel into a 320×180 buffer
@ -55,6 +56,7 @@ Audio lives in `public/audio/` and is configured per meditation in its `index.ts
second and fades in over `fadeIn` (Monastery Above the Clouds uses this for `wind.mp3` over its last 90 s). Mediterranean Coast uses
`fx-waves.mp3`; its wave crashes are timed to the peaks listed in `mediterranean-coast/waves.ts`
(re-measure them if the file changes).
- `ambience: [{ … }, { … }]` — a list layers several loops at once (Cyberpunk City plays `fx-rain.mp3` and `fx-city.mp3` together).
With Docker, rebuild the `web` image (`docker compose up --build -d`) after adding audio so it's included.

Binary file not shown.

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

Binary file not shown.

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

Binary file not shown.

View File

@ -0,0 +1,107 @@
import { hex, mix, scale, type RGB } from '../../engine/color';
import { progress } from '../../engine/Timeline';
import type { Surface } from '../../engine/Surface';
import { screenColor, type Sign, CYAN, PINK, RED } from './neon';
import { haze, type Frame } from './timeline';
import { CX, DEPTH, F, glowClarity, H, HORIZON, MAT, M_SOLID, NEAR, W } from './world';
/**
* An advertising airship drifting slowly across the far end of the avenue, high over the plaza,
* a video screen along its flank and searchlights sweeping beneath it.
*/
const SHIP = { z: 730, y: 182, a: 62, b: 14, c: 14 };
const PATH = { t0: 50, t1: 240, x0: 340, x1: -340 };
const HULL = hex('#4a4658');
const HULL_LIT = hex('#a080b0');
const SCREEN: Sign = { face: 0, u0: 0, u1: 60, v0: 0, v1: 14, kind: 'screen', color: PINK, seed: 3131 };
const BEAM = hex('#c8d0ff');
function shipX(t: number): number {
return PATH.x0 + (PATH.x1 - PATH.x0) * progress(t, PATH.t0, PATH.t1, (x) => x);
}
export function drawAirship(s: Surface, f: Frame): void {
if (f.t < PATH.t0 - 1 || f.t > PATH.t1 + 1) return;
const cam = f.cam;
const cx = shipX(f.t);
const cy = SHIP.y + 2 * Math.sin(f.t * 0.2);
const cz = SHIP.z;
const d0 = cz - cam.z;
if (d0 < NEAR) return;
const k = F / d0;
const sx0 = Math.max(0, Math.floor(CX + (cx - SHIP.a * 1.1 - cam.x) * k));
const sx1 = Math.min(W - 1, Math.ceil(CX + (cx + SHIP.a * 1.1 - cam.x) * k));
const sy0 = Math.max(0, Math.floor(HORIZON - (cy + SHIP.b * 1.6 - cam.y) * k));
const sy1 = Math.min(H - 1, Math.ceil(HORIZON - (cy - SHIP.b * 1.6 - cam.y) * k));
const fog = (1 - glowClarity(d0)) * 0.6;
for (let y = sy0; y <= sy1; y++) {
const dy = -(y + 0.5 - HORIZON) / F;
for (let x = sx0; x <= sx1; x++) {
const dx = (x + 0.5 - CX) / F;
// Ray against the ellipsoid hull.
const ox = (cam.x - cx) / SHIP.a;
const oy = (cam.y - cy) / SHIP.b;
const oz = (cam.z - cz) / SHIP.c;
const vx = dx / SHIP.a;
const vy = dy / SHIP.b;
const vz = 1 / SHIP.c;
const A = vx * vx + vy * vy + vz * vz;
const B = 2 * (ox * vx + oy * vy + oz * vz);
const C = ox * ox + oy * oy + oz * oz - 1;
const disc = B * B - 4 * A * C;
let c: RGB | undefined;
let t = 0;
if (disc >= 0) {
t = (-B - Math.sqrt(disc)) / (2 * A);
const lx = cam.x + dx * t - cx;
const ly = cam.y + dy * t - cy;
// Lit from beneath by the city, darker on top.
const ny = ly / SHIP.b;
c = mix(HULL_LIT, HULL, (ny + 1) / 2);
if (Math.abs(lx) < 30 && Math.abs(ly) < 7) c = screenColor(SCREEN, (lx + 30) / 60, (ly + 7) / 14, f.t, t / F, 60);
else if (Math.abs((lx % 9) + 9) % 9 < 0.5) c = scale(c, 0.8);
} else {
// Tail fins and the gondola, as flat shapes.
const t2 = cz - cam.z;
const lx = cam.x + dx * t2 - cx;
const ly = cam.y + dy * t2 - cy;
const fin = lx > SHIP.a * 0.72 && lx < SHIP.a * 1.05 && Math.abs(ly) < (lx - SHIP.a * 0.72) * 1.1 + 1;
const gondola = Math.abs(lx + 4) < 8 && ly < -SHIP.b * 0.9 && ly > -SHIP.b - 3;
if (fin) c = HULL;
else if (gondola) c = ly > -SHIP.b - 1 ? CYAN : HULL;
t = t2;
}
if (!c) continue;
const kk = y * W + x;
if (DEPTH[kk] < t) continue;
DEPTH[kk] = t;
MAT[kk] = M_SOLID;
s.set(x, y, haze(c, fog));
}
}
// Blinking lights at nose and tail, and two searchlights sweeping slowly down into the rain.
if (f.t % 2 < 0.25) {
for (const lx of [-SHIP.a, SHIP.a * 1.02]) {
const px = CX + (cx + lx - cam.x) * k;
const py = HORIZON - (cy - cam.y) * k;
if (px >= 0 && px < W && py >= 0 && py < H && DEPTH[(py | 0) * W + (px | 0)] >= d0 - 30) s.light(px, py, RED, 0.9);
}
}
for (const side of [-1, 1]) {
const a = 0.35 * Math.sin(f.t * 0.13 + side);
const gx = CX + (cx - 4 - cam.x) * k;
const gy = HORIZON - (cy - SHIP.b - 3 - cam.y) * k;
for (let n = 4; n < 70; n++) {
const u = n / 70;
const bx = gx + (side * 8 + Math.sin(a) * 40) * u;
const by = gy + n * 0.9;
const wide = 0.5 + u * 3;
for (let o = -Math.ceil(wide); o <= Math.ceil(wide); o++) {
const xx = Math.floor(bx + o);
const yy = Math.floor(by);
if (xx < 0 || xx >= W || yy < 0 || yy >= H || DEPTH[yy * W + xx] < d0 - 20) continue;
s.light(xx, yy, BEAM, 0.06 * (1 - u) * (1 - Math.abs(o) / (wide + 1)) * (1 - fog));
}
}
}
}

View File

@ -0,0 +1,533 @@
import { hex, mix, scale, type RGB } from '../../engine/color';
import { hash, noise1, Rng } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import { AMBER, CYAN, moonSea, NEONS, PINK, RED, shopAt, SHOP_W, signColor, VIOLET, type Sign } from './neon';
import { FOG, haze, type Frame } from './timeline';
import { bindScreen, BOTTOM, FRONT, LEFT, RIGHT, SCREEN, TOP, traceBox, type Box3, type Raster, type Shader } from './trace';
import {
BACK_STREET,
BLOCK,
clarity,
CROSS_HALF,
DEPTH,
F,
FIRST_CROSS,
glowClarity,
gridDist,
H,
HORIZON,
LAST_CROSS,
LINE,
MAT,
M_ROAD,
M_WALK,
PLAZA,
project,
TOWER,
W,
WET,
type Cam,
} from './world';
export interface Building extends Box3 {
wall: RGB;
/** Neon light from the street spilling up the walls. */
spill: RGB;
win?: { lit: number; seed: number };
/** Faces fronting a street, which have shops at street level. */
shops: number[];
signs: Sign[];
/** A glass curtain wall with vertical light strips instead of windows. */
glass?: RGB;
beacon?: boolean;
/** Which side of the avenue: shops on it share lights with the pavement below. */
side: number;
/** Colors worked out once: the wall by height (neon spill fades going up), dark glass, a floor ledge, the far-off average. */
pal?: { wallY: RGB[]; glass: RGB; ledge: RGB; avg: RGB; roof: RGB; under: RGB };
/** Each face's windows, worked out once: a color index per window (0 for dark glass), and which ones switch on and off. */
windows?: { bays: number; floors: number; u0: number; col: Uint8Array; flip: Float32Array }[];
/** Signs sorted by face, and the lowest sign on each face, for a quick miss. */
byFace?: Sign[][];
lowest?: number[];
shopMask?: number;
}
/** Blade signs jutting out over the sidewalk, lettered on the face turned down the avenue. */
export interface Blade extends Box3 {
color: RGB;
seed: number;
}
/** A low roof with a holo-billboard projected above it. */
export interface Roof {
x: number;
z: number;
y: number;
seed: number;
}
const WALLS: readonly RGB[] = ['#1a1a28', '#211c2c', '#1a2230', '#24202a', '#1c1e26', '#2a2232', '#162028'].map(hex);
const SPILLS: readonly RGB[] = [PINK, CYAN, VIOLET, AMBER, PINK, CYAN];
const SHOP_H = 4.4;
export const BUILDINGS: Building[] = [];
export const BLADES: Blade[] = [];
export const ROOFS: Roof[] = [];
/** The glass tower a holographic koi circles, partway up the avenue on the right. */
export const KOI_TOWER = { x0: LINE, x1: LINE + 34, z0: 2 * BLOCK + CROSS_HALF + 12, z1: 2 * BLOCK + CROSS_HALF + 48, h: 150 };
const r = new Rng(2077);
const pick = <T>(a: readonly T[]): T => a[r.int(0, a.length - 1)];
/** Scatter neon signs over one face, between u = ua and ub, from vmin up to the top. */
function addSigns(b: Building, face: number, ua: number, ub: number, vmin: number, top: number, busy = 1): void {
const len = ub - ua;
const out = b.signs;
const add = (sg: Sign): void => {
if (sg.u0 < ua + 0.4 || sg.u1 > ub - 0.4 || sg.v1 > top - 0.8 || sg.v0 < vmin) return;
if (out.some((o) => o.face === face && sg.u0 < o.u1 + 0.8 && sg.u1 > o.u0 - 0.8 && sg.v0 < o.v1 + 0.8 && sg.v1 > o.v0 - 0.8)) return;
out.push(sg);
};
const seed = () => r.int(0, 99999);
if (top - vmin > 30 && len > 16 && r.next() < 0.4 * busy) {
const w = r.range(10, Math.min(len - 3, 22));
const h = w * r.range(0.55, 0.8);
const u0 = ua + r.range(1.5, len - w - 1.5);
const v0 = r.range(vmin + 4, Math.max(vmin + 4, Math.min(top - h - 3, vmin + 40)));
add({ face, u0, u1: u0 + w, v0, v1: v0 + h, kind: 'screen', color: pick(NEONS), seed: seed() });
}
if (top - vmin > 14 && r.next() < 0.3 * busy) {
const v0 = r.range(vmin + 1, Math.min(top - 3, vmin + 26));
add({ face, u0: ua + 0.5, u1: ub - 0.5, v0, v1: v0 + 1.3, kind: 'ticker', color: r.next() < 0.6 ? AMBER : RED, seed: seed() });
}
for (let n = r.int(1, 3) + (busy > 1 ? 2 : 0); n > 0; n--) {
const w = r.range(2.2, 3.4);
const h = r.range(8, Math.min(26, top - vmin - 2));
if (h < 6) break;
const u0 = ua + r.range(0.5, len - w - 0.5);
const v0 = r.range(vmin, Math.max(vmin, Math.min(top - h - 2, vmin + 34)));
add({ face, u0, u1: u0 + w, v0, v1: v0 + h, kind: 'glyph', color: pick(NEONS), seed: seed() });
}
if (r.next() < 0.6 * busy && len > 8) {
const w = r.range(6, Math.min(16, len - 2));
const h = r.range(1.8, 3);
const u0 = ua + r.range(1, len - w - 1);
const v0 = r.range(vmin, Math.max(vmin, Math.min(top - h - 1, vmin + 10)));
add({ face, u0, u1: u0 + w, v0, v1: v0 + h, kind: 'band', color: pick(NEONS), seed: seed() });
}
}
function addBlades(b: Building, side: number, top: number): void {
for (let n = r.int(0, 2); n > 0; n--) {
const z0 = r.range(b.z0 + 1, b.z1 - 2);
const y0 = r.range(5, 8);
const y1 = Math.min(top - 1, y0 + r.range(7, 15));
if (y1 - y0 < 5) continue;
const out = 2.6;
BLADES.push({ x0: side > 0 ? LINE - out : -LINE, x1: side > 0 ? LINE : -LINE + out, y0, y1, z0, z1: z0 + 0.45, color: pick(NEONS), seed: r.int(0, 99999) });
}
}
function building(x0: number, x1: number, z0: number, z1: number, h: number, side: number, shops: number[]): Building {
const b: Building = {
x0,
x1,
y0: 0,
y1: h,
z0,
z1,
wall: pick(WALLS),
spill: pick(SPILLS),
win: { lit: r.range(0.08, 0.28), seed: r.int(0, 9999) },
shops,
signs: [],
side,
beacon: h > 110,
};
BUILDINGS.push(b);
return b;
}
const frontHeight = (k: number): number => {
if (k === LAST_CROSS) return r.range(12, 22);
const p = r.next();
return p < 0.3 ? r.range(14, 32) : p < 0.82 ? r.range(40, 90) : r.range(100, 165);
};
// The avenue: a row of buildings along each sidewalk, block by block, and taller towers behind.
for (const side of [1, -1]) {
const street = side > 0 ? LEFT : RIGHT;
for (let k = FIRST_CROSS; k <= LAST_CROSS; k++) {
const zs = k * BLOCK + CROSS_HALF;
const ze = (k + 1) * BLOCK - CROSS_HALF;
const koi = side > 0 && k === 2;
const plan: [number, number][] = koi
? [
[KOI_TOWER.z0 - zs, 22],
[KOI_TOWER.z1 - KOI_TOWER.z0, KOI_TOWER.h],
[ze - KOI_TOWER.z1, 27],
]
: [];
if (!koi) {
let z = zs;
while (z < ze - 1) {
let len = r.range(15, 30);
if (ze - z - len < 12) len = ze - z;
plan.push([len, frontHeight(k)]);
z += len;
}
}
let z = zs;
for (const [len, h] of plan) {
const depth = koi && h === KOI_TOWER.h ? KOI_TOWER.x1 - KOI_TOWER.x0 : r.range(24, 44);
const x0 = side > 0 ? LINE : -LINE - depth;
const b = building(x0, x0 + depth, z, z + len, h, side, z === zs ? [street, FRONT] : [street]);
if (koi && h === KOI_TOWER.h) {
b.glass = CYAN;
b.win = undefined;
addSigns(b, street, z, z + len, SHOP_H + 0.6, 30);
} else {
addSigns(b, street, z, z + len, SHOP_H + 0.6, h);
if (z === zs) addSigns(b, FRONT, x0, x0 + depth, SHOP_H + 0.6, h, 0.7);
addBlades(b, side, h);
}
if (h < 36 && r.next() < (k === LAST_CROSS ? 0.8 : 0.55)) ROOFS.push({ x: x0 + depth / 2, z: z + len / 2, y: h, seed: r.int(0, 9999) });
z += len;
}
// Towers set back behind the front row, rising over it.
for (let n = r.int(1, 2); n > 0; n--) {
const w = r.range(24, 42);
const d = r.range(22, 50);
const off = LINE + 48 + r.range(0, 30);
const x0 = side > 0 ? off : -off - w;
const z0 = zs + r.range(0, Math.max(0, ze - zs - d));
const h = r.range(95, 250);
const b = building(x0, x0 + w, z0, z0 + d, h, side, []);
addSigns(b, street, z0, z0 + d, r.range(45, 90), h);
addSigns(b, FRONT, x0, x0 + w, r.range(45, 90), h, 0.6);
}
}
}
// The plaza: walls of screens on either side, like a crossroads of giant billboards.
for (const side of [1, -1]) {
const inner = side > 0 ? LEFT : RIGHT;
const segs: [number, number, number][] = [
[PLAZA.z0, 498, 86],
[498, 556, 118],
[556, BACK_STREET.z0, 96],
];
for (const [z0, z1, h] of segs) {
const x0 = side > 0 ? PLAZA.half : -PLAZA.half - 42;
const b = building(x0, x0 + 42, z0, z1, h, side * 2, z0 === PLAZA.z0 ? [inner, FRONT] : [inner]);
const v0 = 15;
const v1 = Math.min(h - 12, v0 + (z1 - z0 - 6) * 0.62);
b.signs.push({ face: inner, u0: z0 + 3, u1: z1 - 3, v0, v1, kind: 'screen', color: pick(NEONS), seed: r.int(0, 99999) });
b.signs.push({ face: inner, u0: z0 + 0.6, u1: z1 - 0.6, v0: 10.5, v1: 12, kind: 'ticker', color: AMBER, seed: r.int(0, 99999) });
addSigns(b, inner, z0, z1, v1 + 2, h, 1.5);
addSigns(b, inner, z0, z1, SHOP_H + 0.8, 10, 1.5);
if (z0 === PLAZA.z0) addSigns(b, FRONT, x0, x0 + 42, SHOP_H + 0.6, h, 2);
}
}
// The screen tower at the head of the plaza, the glow at the end of the avenue the whole way up.
export const MAIN_SCREEN: Sign = { face: FRONT, u0: TOWER.x0 + 4, u1: TOWER.x1 - 4, v0: 34, v1: 96, kind: 'main', color: CYAN, seed: 4242 };
{
const b = building(TOWER.x0, TOWER.x1, TOWER.z0, TOWER.z1, TOWER.h, 0, [FRONT]);
b.win = undefined;
b.signs.push(
MAIN_SCREEN,
{ face: FRONT, u0: TOWER.x0 + 0.5, u1: TOWER.x1 - 0.5, v0: 27, v1: 29.5, kind: 'ticker', color: AMBER, seed: 77 },
{ face: FRONT, u0: TOWER.x0 + 0.5, u1: TOWER.x1 - 0.5, v0: 101, v1: 103.5, kind: 'ticker', color: CYAN, seed: 78 },
{ face: FRONT, u0: TOWER.x0 + 0.6, u1: TOWER.x0 + 3.2, v0: 8, v1: 30, kind: 'glyph', color: PINK, seed: 79 },
{ face: FRONT, u0: TOWER.x1 - 3.2, u1: TOWER.x1 - 0.6, v0: 8, v1: 30, kind: 'glyph', color: VIOLET, seed: 80 },
{ face: FRONT, u0: TOWER.x0 + 6, u1: TOWER.x1 - 6, v0: 108, v1: 118, kind: 'screen', color: PINK, seed: 81 },
{ face: FRONT, u0: TOWER.x0 + 5, u1: TOWER.x0 + 21, v0: 10, v1: 24, kind: 'screen', color: AMBER, seed: 82 },
{ face: FRONT, u0: TOWER.x1 - 21, u1: TOWER.x1 - 5, v0: 10, v1: 24, kind: 'screen', color: CYAN, seed: 83 },
);
}
// A row of buildings closing off the view behind the tower.
for (let x = -230; x < 230; ) {
const w = r.range(40, 70);
const h = r.range(40, 95);
const b = building(x, x + w, BACK_STREET.z1 + 2, BACK_STREET.z1 + 50, h, 3, [FRONT]);
addSigns(b, FRONT, x, x + w, SHOP_H + 0.6, h, 1.5);
x += w;
}
// Megatowers far off in the haze, their signs and lights streaking up into the clouds.
for (let n = 0; n < 12; n++) {
const w = r.range(60, 140);
const z0 = r.range(850, 1900);
const off = r.range(-700, 700);
const h = r.range(220, 480);
const b = building(off - w / 2, off + w / 2, z0, z0 + w, h, 4, []);
b.win = { lit: r.range(0.08, 0.2), seed: r.int(0, 9999) };
for (let i = r.int(1, 3); i > 0; i--) {
const u0 = off - w / 2 + r.range(4, w - 14);
const v0 = r.range(40, h - 120);
b.signs.push({ face: FRONT, u0, u1: u0 + r.range(6, 10), v0, v1: v0 + r.range(50, 110), kind: 'glyph', color: pick(NEONS), seed: r.int(0, 99999) });
}
}
// ---------------------------------------------------------------------------
// Shading
// ---------------------------------------------------------------------------
const WIN_COLORS: readonly RGB[] = [hex('#8a6a48'), hex('#8a6a48'), hex('#56748e'), hex('#84567a'), hex('#5e8a7c')];
const SHUTTER = hex('#26242c');
const ROOF = hex('#18161f');
const ROOF_UNIT = hex('#262430');
const PARAPET = hex('#2e2a38');
const GLASS_DARK = hex('#101a24');
function roofColor(b: Building, X: number, Z: number, fp: number): RGB {
const edge = Math.min(X - b.x0, b.x1 - X, Z - b.z0, b.z1 - Z);
if (edge < 0.7) return PARAPET;
let c = b.pal!.roof;
if (fp < 1.2 && hash(Math.floor(X / 3.2), Math.floor(Z / 3.2), 91) < 0.2) c = ROOF_UNIT;
// Rain pooled on the flat roof, holding a little of the sky's glow.
if (hash(Math.floor(X / 5), Math.floor(Z / 5), 92) < 0.25) c = mix(c, FOG, 0.35);
return c;
}
function shopFront(b: Building, face: number, u: number, Y: number, fp: number): RGB {
const n = Math.floor(u / SHOP_W);
const key = face === FRONT ? b.side * 7 + 3 : b.side;
const col = shopAt(key, n);
if (Y < 0.3) return scale(b.wall, 0.6);
if (!col) return fp < 0.3 && Y % 0.5 < 0.08 ? scale(SHUTTER, 0.7) : SHUTTER;
if (Y > SHOP_H - 1) return fp < 0.4 && Math.floor((u - n * SHOP_W) / 0.6) % 2 === 0 ? col : scale(col, 0.8);
const lu = u - n * SHOP_W;
if (fp < 0.5 && (lu < 0.25 || lu % 1.25 < 0.12)) return scale(b.wall, 0.8);
return scale(col, Y < 1.1 ? 0.55 : 0.75);
}
const SCRATCH: [number, number, number] = [0, 0, 0];
const BAY = 2.2;
const FLOOR = 3.4;
/** Window table for one face: what each window shows, and when the ones that switch do so. */
function windowTable(b: Building, face: number): NonNullable<Building['windows']>[number] {
const w = b.win!;
const u0 = face === FRONT ? b.x0 : b.z0;
const len = face === FRONT ? b.x1 - b.x0 : b.z1 - b.z0;
const bays = Math.ceil(len / BAY) + 2;
const floors = Math.ceil(b.y1 / FLOOR) + 1;
const col = new Uint8Array(bays * floors);
const flip = new Float32Array(bays * floors).fill(Infinity);
for (let fl = 0; fl < floors; fl++) {
for (let wi = 0; wi < bays; wi++) {
const n = fl * bays + wi;
const h = hash(wi, fl, w.seed + face);
if (hash(wi + face * 977, fl, w.seed) < w.lit) col[n] = 1 + Math.floor(((h * 7919) % 1) * WIN_COLORS.length);
// One window in twelve switches on or off at some moment during the meditation.
if (h < 0.08) flip[n] = hash(wi, fl, w.seed + 31) * 300;
}
}
return { bays, floors, u0, col, flip };
}
function windowColor(b: Building, face: number, u: number, Y: number, t: number, wall: RGB, fp: number): RGB {
const pal = b.pal!;
if (fp > 2.1) return pal.avg;
const tab = b.windows![face];
const fu = (u - tab.u0) / BAY;
const fv = (Y - SHOP_H) / FLOOR;
const wi = Math.floor(fu);
const fl = Math.floor(fv);
let c = wall;
// A thin ledge at every floor slab.
if (fl >= 0 && fv - fl < 0.1 && fp < 0.5) return pal.ledge;
if (fl >= 0 && fl < tab.floors && wi >= 0 && wi < tab.bays && fu - wi > 0.25 && fu - wi < 0.75 && fv - fl > 0.35 && fv - fl < 0.8) {
const n = fl * tab.bays + wi;
let ci = tab.col[n];
if (t > tab.flip[n]) ci = ci ? 0 : 1 + (n % WIN_COLORS.length);
c = ci ? WIN_COLORS[ci - 1] : pal.glass;
}
// Far away, a wall averages out to a faint glow of its lit windows.
if (fp <= 0.6) return c;
const k = Math.min(1, (fp - 0.6) / 1.5) * 0.8;
const a = pal.avg;
SCRATCH[0] = c[0] + (a[0] - c[0]) * k;
SCRATCH[1] = c[1] + (a[1] - c[1]) * k;
SCRATCH[2] = c[2] + (a[2] - c[2]) * k;
return SCRATCH;
}
function palette(b: Building): NonNullable<Building['pal']> {
const glass = mix(scale(b.wall, 0.55), FOG, 0.22);
return {
wallY: Array.from({ length: 48 }, (_, y) => mix(b.wall, b.spill, 0.05 + 0.22 * Math.exp(-y / 16))),
glass,
ledge: scale(b.wall, 1.25),
avg: mix(mix(b.wall, glass, 0.3), WIN_COLORS[0], (b.win?.lit ?? 0) * 0.35),
roof: mix(ROOF, b.spill, 0.05),
under: scale(b.wall, 0.6),
};
}
for (const b of BUILDINGS) {
b.pal = palette(b);
if (b.win) b.windows = [0, 1, 2].map((face) => windowTable(b, face));
b.byFace = [0, 1, 2, 3, 4].map((face) => b.signs.filter((sg) => sg.face === face));
b.lowest = b.byFace.map((l) => Math.min(Infinity, ...l.map((sg) => sg.v0)));
b.shopMask = b.shops.reduce((m, face) => m | (1 << face), 0);
}
const NONE: Sign[] = [];
/** One frame's moment, for the shaders below. */
let frame: Frame;
function shade(b: Building, face: number, X: number, Y: number, Z: number, d: number): RGB {
const fp = d / F;
const fog = 1 - clarity(d);
if (face === TOP) return haze(roofColor(b, X, Z, fp), fog);
if (face === BOTTOM) return haze(b.pal!.under, fog);
const u = face === FRONT ? X : Z;
const signs = Y >= b.lowest![face] ? b.byFace![face] : NONE;
for (let n = 0; n < signs.length; n++) {
const sg = signs[n];
if (u < sg.u0 || u > sg.u1 || Y < sg.v0 || Y > sg.v1) continue;
let c: RGB | undefined;
if (sg.kind === 'main') {
const lu = u - sg.u0;
const lv = Y - sg.v0;
const w = sg.u1 - sg.u0;
const h = sg.v1 - sg.v0;
// The moon arrives LED by LED, scattered across the screen.
const moon = hash(Math.floor(lu / 0.6), Math.floor(lv / 0.6), 93) < frame.moon;
c = moon ? moonSea(lu / w, lv / h, frame.t, w / h) : signColor(sg, lu, lv, frame.t, fp);
} else c = signColor(sg, u - sg.u0, Y - sg.v0, frame.t, fp);
if (c) return haze(c, 1 - glowClarity(d));
}
if (Y < SHOP_H && (b.shopMask! >> face) & 1) return haze(shopFront(b, face, u, Y, fp), 1 - glowClarity(d));
// Neon from the street below washes up the lower walls.
const wy = b.pal!.wallY;
let c = wy[Math.min(wy.length - 1, Y | 0)];
if (b.glass) {
const strip = gridDist(u, 4.2) < 0.3;
c = strip ? mix(GLASS_DARK, b.glass, 0.35 + 0.15 * Math.sin(Y * 0.05 - frame.t * 0.4)) : mix(GLASS_DARK, FOG, 0.25 + 0.1 * Math.sin(Y * 0.3 + u));
} else if (b.win) c = windowColor(b, face, u, Y, frame.t, c, fp);
return haze(c, fog);
}
function shadeBlade(bl: Blade, face: number, X: number, Y: number, _Z: number, d: number): RGB {
const fp = d / F;
let c: RGB;
if (face === FRONT) {
const sg: Sign = { face, u0: bl.x0, u1: bl.x1, v0: bl.y0, v1: bl.y1, kind: 'glyph', color: bl.color, seed: bl.seed };
c = signColor(sg, X - bl.x0, Y - bl.y0, frame.t, fp) ?? scale(bl.color, 0.1);
} else if (face === TOP || face === BOTTOM) c = scale(bl.color, 0.2);
else c = scale(bl.color, 0.75);
return haze(c, 1 - glowClarity(d));
}
/** The box being traced, so one shader function serves them all (and the call stays cheap). */
let current: Building;
let currentBlade: Blade;
const shadeCurrent: Shader = (face, X, Y, Z, d) => shade(current, face, X, Y, Z, d);
const shadeCurrentBlade: Shader = (face, X, Y, Z, d) => shadeBlade(currentBlade, face, X, Y, Z, d);
function traceBuilding(r: Raster, cam: Cam, b: Building, mirror: boolean): void {
current = b;
traceBox(r, cam, b, shadeCurrent, mirror);
}
function traceBlade(r: Raster, cam: Cam, b: Blade, mirror: boolean): void {
currentBlade = b;
traceBox(r, cam, b, shadeCurrentBlade, mirror);
}
const AVIATION = hex('#ff3226');
const near = (b: Box3, cam: Cam): number => Math.max(0, b.z0 - cam.z) + 0.5 * Math.max(0, b.x0 - cam.x, cam.x - b.x1);
function byDistance(cam: Cam): Building[] {
return BUILDINGS.filter((b) => b.z1 > cam.z + 0.5).sort((a, b) => near(a, cam) - near(b, cam));
}
export function drawBuildings(s: Surface, f: Frame): void {
frame = f;
bindScreen(s);
const cam = f.cam;
// Nearest first, so the depth test turns away hidden pixels before they are shaded.
for (const b of BLADES) if (b.z1 > cam.z && b.z0 - cam.z < 700) traceBlade(SCREEN, cam, b, false);
for (const b of byDistance(cam)) traceBuilding(SCREEN, cam, b, false);
// Red aviation lights blinking slowly on the tallest roofs.
for (const b of BUILDINGS) {
if (!b.beacon || ((f.t * 0.5 + hash(b.x0 | 0, b.z0 | 0, 94)) % 1) > 0.45) continue;
const p = project(cam, (b.x0 + b.x1) / 2, b.y1 + 1.5, (b.z0 + b.z1) / 2);
if (!p || p.x < 0 || p.x >= W || p.y < 0 || p.y >= H) continue;
if (DEPTH[(p.y | 0) * W + (p.x | 0)] < p.d - 30) continue;
const k = Math.sqrt(glowClarity(p.d));
s.light(p.x, p.y, AVIATION, k);
s.light(p.x - 1, p.y, AVIATION, k * 0.35);
s.light(p.x + 1, p.y, AVIATION, k * 0.35);
}
}
// ---------------------------------------------------------------------------
// Reflections in the wet street
// ---------------------------------------------------------------------------
const RW = W / 2;
const RH = Math.ceil((H - HORIZON) / 2);
const REF = new Float32Array(RW * RH * 3);
const REF_DEPTH = new Float32Array(RW * RH);
/** Half-size buffer the mirrored city is traced into, from the horizon down. */
export const MIRROR: Raster = {
w: RW,
h: RH,
scale: 2,
row0: HORIZON,
depth: REF_DEPTH,
put(i, j, c) {
const k = (j * RW + i) * 3;
REF[k] = c[0];
REF[k + 1] = c[1];
REF[k + 2] = c[2];
},
};
/** Trace the city upside down beneath the street. Other layers may add to MIRROR before compositing. */
export function traceReflections(f: Frame): void {
frame = f;
const sky = scale(FOG, 0.8);
for (let k = 0; k < RW * RH; k++) {
REF[k * 3] = sky[0];
REF[k * 3 + 1] = sky[1];
REF[k * 3 + 2] = sky[2];
}
REF_DEPTH.fill(Infinity);
const cam = f.cam;
for (const b of BLADES) if (b.z1 > cam.z && b.z0 - cam.z < 300) traceBlade(MIRROR, cam, b, true);
for (const b of byDistance(cam)) if (b.z0 - cam.z < 650) traceBuilding(MIRROR, cam, b, true);
}
/** Lay the mirrored city over the wet street, smeared toward the viewer and rippled by the rain. */
export function compositeReflections(s: Surface, f: Frame): void {
const d = s.data;
for (let y = HORIZON; y < H; y++) {
const j = (y - HORIZON) >> 1;
const wob = Math.round((noise1(y * 0.85 + f.t * 1.2, 7) - 0.5) * 3.2 + (noise1(y * 0.23 - f.t * 0.4, 8) - 0.5) * 2);
for (let x = 0; x < W; x++) {
const k = y * W + x;
const m = MAT[k];
if (m !== M_ROAD && m !== M_WALK) continue;
const wet = WET[k];
const i = Math.max(0, Math.min(RW - 1, (x + wob) >> 1));
const r0 = (j * RW + i) * 3;
const r1 = (Math.max(0, j - 1) * RW + i) * 3;
const r2 = (Math.max(0, j - 2) * RW + i) * 3;
const p = k * 4;
for (let c = 0; c < 3; c++) {
const refl = REF[r0 + c] * 0.5 + REF[r1 + c] * 0.3 + REF[r2 + c] * 0.2;
d[p + c] = d[p + c] * (1 - wet * 0.4) + refl * wet;
}
}
}
}

View File

@ -0,0 +1,279 @@
import { hex, mix, scale, type RGB } from '../../engine/color';
import { hash, noise1, Rng } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import { ICE, NEONS } from './neon';
import { FOG, type Frame } from './timeline';
import {
BLOCK,
CROSS_HALF,
CX,
cycleIndex,
DEPTH,
F,
glowClarity,
H,
HORIZON,
LAST_CROSS,
LINE,
PLAZA,
ROAD_HALF,
signalPhase,
smoothstep,
splitAt,
stallAt,
STALL_SLOT,
W,
WALK_END,
YELLOW,
type Cam,
} from './world';
/**
* Everyone is a person standing at (x, z) with an umbrella or a hood. Most umbrellas are dark;
* many glow with LED rims, and some are clear plastic that catches the neon. Far off a person is
* one pixel, so the sidewalks become rivers of colored specks.
*/
interface Look {
coat: RGB;
/** Canopy and rim, or undefined for a hood instead of an umbrella. */
canopy?: RGB;
rim?: RGB;
clear?: boolean;
/** Umbrellas that glow light up whoever carries them. */
glow: boolean;
height: number;
}
const COATS: readonly RGB[] = ['#1e1e28', '#2a2232', '#30282c', '#222c38', '#3a2430', '#26303a', '#4a2a3a', '#2a3a4e'].map(hex);
const DARK_CANOPY = hex('#16161e');
const DARK_RIM = hex('#3c3a4c');
const HOOD = hex('#3a3440');
function makeLook(r: Rng): Look {
const coat = COATS[r.int(0, COATS.length - 1)];
const height = r.range(1.6, 1.85);
const p = r.next();
if (p < 0.4) {
const c = NEONS[r.int(0, NEONS.length - 1)];
return { coat, canopy: scale(c, 0.45), rim: c, glow: true, height };
}
if (p < 0.55) return { coat, canopy: ICE, rim: ICE, clear: true, glow: false, height };
if (p < 0.85) return { coat, canopy: DARK_CANOPY, rim: DARK_RIM, glow: false, height };
return { coat, glow: false, height };
}
/** Plot a solid pixel of a person if nothing nearer covers it, and claim its depth. */
function put(s: Surface, x: number, y: number, d: number, c: RGB, a = 1): void {
x |= 0;
y |= 0;
if (x < 0 || y < 0 || x >= W || y >= H) return;
const k = y * W + x;
if (DEPTH[k] < d) return;
if (a >= 1) DEPTH[k] = d;
s.blend(x, y, c, a);
}
function drawPerson(s: Surface, cam: Cam, X: number, Z: number, look: Look, t: number, walk: number, seed: number, fade = 1): void {
const d = Z - cam.z;
if (d < 40 || d > 650) return;
const k = F / d;
const sx = CX + (X - cam.x) * k;
if (sx < -4 || sx > W + 4) return;
const feet = HORIZON + cam.y * k;
const fog = 1 - glowClarity(d) * fade;
const tint = (c: RGB): RGB => mix(c, FOG, fog);
if (k < 1.1) {
// Too far for any shape: one pixel, bright for a glowing umbrella, a faint dark speck otherwise.
const y = feet - look.height * k;
if (look.glow) put(s, sx, y, d, tint(look.rim!), 0.9);
else if (hash(seed, 0, 130) < 0.5) put(s, sx, y, d, tint(scale(look.coat, 0.8)), 0.5);
return;
}
// Bodies bob a little as they walk.
const bob = walk > 0 ? Math.abs(Math.sin(t * 5.5 * walk + seed)) * 0.06 : 0;
const top = feet - (look.height + bob) * k;
const bw = Math.max(1, Math.round(0.45 * k));
const x0 = Math.round(sx - bw / 2);
const coat = tint(look.glow ? mix(look.coat, look.rim!, 0.25) : look.coat);
for (let y = Math.floor(top); y < Math.round(feet); y++) for (let x = x0; x < x0 + bw; x++) put(s, x, y, d, coat);
if (!look.canopy) {
put(s, sx, top - 0.6, d, tint(HOOD));
return;
}
// The umbrella: a disc seen from above, foreshortened by the drone's height over it.
const uy = feet - (look.height + 0.35 + bob) * k;
const rx = Math.max(1, 0.55 * k);
const ry = Math.max(0.8, rx * ((cam.y - 2) / d) * 1.2);
for (let oy = -Math.ceil(ry); oy <= Math.ceil(ry); oy++) {
for (let ox = -Math.ceil(rx); ox <= Math.ceil(rx); ox++) {
const e = (ox / rx) ** 2 + (oy / ry) ** 2;
if (e > 1.15) continue;
const rim = e > 0.55;
if (look.clear) put(s, sx + ox, uy + oy, d, tint(look.canopy), rim ? 0.45 : 0.18);
else put(s, sx + ox, uy + oy, d, tint(rim ? look.rim! : look.canopy));
}
}
}
// ---------------------------------------------------------------------------
// Sidewalk walkers, up and down both sides of the avenue and on into the plaza
// ---------------------------------------------------------------------------
interface Walker {
side: number;
x: number;
z0: number;
dir: number;
speed: number;
look: Look;
seed: number;
}
const WALK_LOW = -60;
const WALK_HIGH = PLAZA.z0 + 70;
const WALK_LEN = WALK_HIGH - WALK_LOW;
const WALKERS: Walker[] = (() => {
const r = new Rng(314);
return Array.from({ length: 1100 }, (_, i) => {
const side = r.next() < 0.5 ? -1 : 1;
// Most keep to the open middle of the sidewalk, clear of the stalls along the walls.
const x = r.next() < 0.75 ? r.range(ROAD_HALF + 0.9, LINE - 4.2) : r.range(LINE - 4.2, LINE - 0.6);
return { side, x, z0: r.range(0, WALK_LEN), dir: r.next() < 0.5 ? -1 : 1, speed: r.range(0.8, 1.5), look: makeLook(r), seed: i };
});
})();
function drawWalkers(s: Surface, f: Frame): void {
const cam = f.cam;
for (const w of WALKERS) {
const u = (((w.z0 + w.dir * w.speed * f.t) % WALK_LEN) + WALK_LEN) % WALK_LEN;
const z = WALK_LOW + u;
// People fade in and out at the ends of their stretch, out in the plaza and behind the drone.
const fade = Math.min(smoothstep(0, 12, u), smoothstep(WALK_LEN, WALK_LEN - 12, u));
if (fade <= 0) continue;
const spread = Math.max(0, z - PLAZA.z0) * 0.55 + (z > PLAZA.z0 ? splitAt(z) * 0.3 : 0);
const sway = 0.25 * (noise1(f.t * 0.1 + w.seed, 131) - 0.5);
drawPerson(s, cam, w.side * (w.x + spread) + sway, z, w.look, f.t, w.speed, w.seed, fade);
}
}
// ---------------------------------------------------------------------------
// The scramble: when the lights change, the corners empty across every crossing at once
// ---------------------------------------------------------------------------
interface Crosser {
k: number;
/** Two corners (0–3) this person shuttles between, one crossing per cycle. */
a: number;
b: number;
ox: number;
oz: number;
delay: number;
speed: number;
look: Look;
seed: number;
}
const CORNER_X = ROAD_HALF + 1.2;
const CORNER_Z = CROSS_HALF + 1.6;
const corner = (c: number): [number, number] => [c & 1 ? CORNER_X : -CORNER_X, c & 2 ? CORNER_Z : -CORNER_Z];
const CROSSERS: Crosser[] = (() => {
const r = new Rng(2718);
const out: Crosser[] = [];
// Across the avenue, diagonally, and across the side street.
const pairs = [
[0, 1],
[2, 3],
[0, 3],
[1, 2],
[0, 2],
[1, 3],
];
for (let k = 0; k <= LAST_CROSS; k++) {
for (let n = 0; n < 44; n++) {
const [a, b] = pairs[r.int(0, pairs.length - 1)];
out.push({ k, a, b, ox: r.range(0, 4), oz: r.range(-1.2, 1.2), delay: r.range(0, 4.5), speed: r.range(0.9, 1.4), look: makeLook(r), seed: 5000 + out.length });
}
}
return out;
})();
function crosserAt(c: Crosser, t: number): [number, number] {
const n = cycleIndex(c.k, t);
const ph = signalPhase(c.k, t);
const [from, to] = n % 2 ? [c.b, c.a] : [c.a, c.b];
// Each waits back from the curb on its own corner of the sidewalk.
const at = (q: number): [number, number] => {
const [x, z] = corner(q);
return [x + Math.sign(x) * c.ox, c.k * BLOCK + z + c.oz];
};
const p0 = at(from);
const p1 = at(to);
const dist = Math.hypot(p1[0] - p0[0], p1[1] - p0[1]);
const u = Math.max(0, Math.min(1, (ph - YELLOW - 0.5 - c.delay) / (dist / c.speed)));
// Anyone not across when the walk ends hurries the rest of the way.
const late = ph > WALK_END ? 1 : u;
return [p0[0] + (p1[0] - p0[0]) * late, p0[1] + (p1[1] - p0[1]) * late];
}
function drawCrossers(s: Surface, f: Frame): void {
const cam = f.cam;
for (const c of CROSSERS) {
const [x, z] = crosserAt(c, f.t);
const ph = signalPhase(c.k, f.t);
const walking = ph > YELLOW && ph < WALK_END ? c.speed : 0;
drawPerson(s, cam, x, z, c.look, f.t, walking, c.seed);
}
}
// ---------------------------------------------------------------------------
// Customers at the food stalls, and people milling in the plaza
// ---------------------------------------------------------------------------
interface Stander {
x: number;
z: number;
/** How far they drift around their spot, m. */
roam: number;
look: Look;
seed: number;
}
const STANDERS: Stander[] = (() => {
const r = new Rng(1618);
const out: Stander[] = [];
for (let slot = -8; slot < Math.ceil(PLAZA.z0 / STALL_SLOT); slot++) {
for (const side of [1, -1]) {
if (!stallAt(slot, side)) continue;
const zc = (slot + 0.5) * STALL_SLOT;
for (let n = r.int(1, 4); n > 0; n--) out.push({ x: side * (LINE - 3.8 - r.range(0, 0.6)), z: zc + r.range(-1.5, 1.5), roam: 0.15, look: makeLook(r), seed: 8000 + out.length });
}
}
// The plaza crowd keeps to the pavement either side of the two roadways.
for (let n = 0; n < 420; n++) {
const z = r.range(PLAZA.z0 + 4, PLAZA.z1 + 50);
const lane = 5 + splitAt(z);
const outer = r.next() < 0.55;
const side = r.next() < 0.5 ? -1 : 1;
const x = outer ? side * r.range(lane + 6.5, PLAZA.half - 2) : side * r.range(0, Math.max(0, lane - 6.5));
if (z > PLAZA.z1 && Math.abs(x) < 28) continue;
out.push({ x, z, roam: r.range(1.5, 5), look: makeLook(r), seed: 9000 + out.length });
}
return out;
})();
function drawStanders(s: Surface, f: Frame): void {
const cam = f.cam;
for (const p of STANDERS) {
const x = p.x + p.roam * (noise1(f.t * 0.05 + p.seed * 0.37, 132) - 0.5);
const z = p.z + p.roam * (noise1(f.t * 0.05 + p.seed * 0.61, 133) - 0.5);
drawPerson(s, cam, x, z, p.look, f.t, p.roam > 1 ? 0.4 : 0, p.seed);
}
}
export function drawCrowds(s: Surface, f: Frame): void {
drawWalkers(s, f);
drawCrossers(s, f);
drawStanders(s, f);
}

View File

@ -0,0 +1,55 @@
import { track } from '../../engine/Timeline';
/** All timings for the Cyberpunk City meditation, in seconds. */
export const DURATION = 300;
export const TIMES = {
fadeIn: [0, 6],
fadeOut: [294, 300],
/** A hover car rises out from under the camera and glides on ahead. */
flyby: 60,
/** Easing out of the cruise into a hover over the plaza. */
arrive: [244, 276],
/** The rain softens to a drizzle. */
drizzle: [256, 292],
/** The plaza's big screen dissolves into a moonlit sea. */
moon: [262, 274],
} as const;
/** Forward speed in m/s: a slow drift up the avenue that eases into a hover. */
export const speedAt = track([
[0, 0.9],
[18, 1.3],
[TIMES.arrive[0], 1.3],
[TIMES.arrive[1], 0],
]);
/**
* Distance travelled since t = 0, in meters. Integrated from a table so position 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);
}
/** Where the drone starts along the avenue, and where it comes to rest. */
export const START_Z = 30;
export const camZAt = (t: number): number => START_Z + travelAt(t);
export const END_Z = camZAt(DURATION);
/** Height above the street: steady, then settling a little lower for the hover. */
export const altitudeAt = track([
[0, 44],
[TIMES.arrive[0], 44],
[TIMES.arrive[1] + 6, 38],
]);

View File

@ -0,0 +1,274 @@
import { hex, mix, type RGB } from '../../engine/color';
import { hash, noise2 } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import { KOI_TOWER, ROOFS } from './buildings';
import { AMBER, CYAN, GREEN, PINK, VIOLET } from './neon';
import type { Frame } from './timeline';
import { CX, DEPTH, F, glowClarity, H, HORIZON, MAT, M_ROAD, M_WALK, NEAR, project, W, type Cam } from './world';
/**
* Holograms are light without substance: they go behind solid things but never hide anything, and
* where several layers of one overlap they don't pile up into a white blob. Each pixel keeps the
* strongest hologram light that reached it, added onto the frame at the end.
*/
const GA = new Float32Array(W * H);
const GC = new Float32Array(W * H * 3);
function clearGlow(): void {
GA.fill(0);
}
/** Scanlines roll slowly down every hologram. */
let scan = 0;
/** Plot one hologram point; `mirror` plots its reflection in the wet street instead. */
function plot(cam: Cam, X: number, Y: number, Z: number, c: RGB, a: number, mirror: boolean): void {
const pd = Z - cam.z;
if (pd < NEAR) return;
const kk = F / pd;
const x = Math.floor(CX + (X - cam.x) * kk);
const y = Math.floor(HORIZON - ((mirror ? -Y : Y) - cam.y) * kk);
if (x < 0 || y < 0 || x >= W || y >= H) return;
const k = y * W + x;
if (mirror) {
const m = MAT[k];
if (m !== M_ROAD && m !== M_WALK) return;
a *= 0.3;
} else if (DEPTH[k] < pd) return;
if ((y + scan) % 3 === 0) a *= 0.55;
a *= glowClarity(pd);
if (a <= GA[k]) return;
GA[k] = a;
GC[k * 3] = c[0];
GC[k * 3 + 1] = c[1];
GC[k * 3 + 2] = c[2];
}
function compositeGlow(s: Surface): void {
const d = s.data;
for (let k = 0; k < W * H; k++) {
const a = GA[k];
if (a <= 0) continue;
d[k * 4] += GC[k * 3] * a;
d[k * 4 + 1] += GC[k * 3 + 1] * a;
d[k * 4 + 2] += GC[k * 3 + 2] * a;
}
}
// ---------------------------------------------------------------------------
// Two holographic koi circling the glass tower, one chasing the other
// ---------------------------------------------------------------------------
/** The koi swim an oval that swings out over the avenue in front of the tower, then around behind it. */
const KOI_C = { x: KOI_TOWER.x0 + 4, z: (KOI_TOWER.z0 + KOI_TOWER.z1) / 2 };
const KOI_LAP = 52;
const KOI_L = 18;
interface Koi {
/** Radius across the avenue; the oval is a little shorter along it. */
r: number;
y: number;
phase: number;
base: RGB;
patch: RGB;
seed: number;
}
const KOI: readonly Koi[] = [
{ r: 32, y: 47, phase: 0, base: hex('#fff6f0'), patch: hex('#ff5a1e'), seed: 1 },
{ r: 35, y: 54, phase: Math.PI * 0.92, base: hex('#ffc848'), patch: hex('#ff3a6a'), seed: 2 },
];
/** Half-height of the body at a share p of the way from nose to tail. */
const bodyH = (p: number): number => (p < 0.22 ? 1.9 * Math.sqrt(p / 0.22) : 1.9 * (1 - 0.82 * Math.pow((p - 0.22) / 0.78, 1.2)));
function drawKoi(f: Frame, k: Koi, mirror: boolean): void {
const cam = f.cam;
if (KOI_C.z + k.r < cam.z) return;
const th = k.phase + (f.t / KOI_LAP) * Math.PI * 2;
const headY = k.y + 3 * Math.sin(th * 2 + k.seed);
const rz = k.r * 0.84;
const head = project(cam, KOI_C.x + k.r * Math.cos(th), headY, KOI_C.z + rz * Math.sin(th));
const dist = Math.max(20, head ? head.d : KOI_C.z - cam.z);
const step = Math.max(0.1, dist / F / 1.15);
const len = KOI_L * 1.22;
for (let s = 0; s < len; s += step) {
const p = s / KOI_L;
// The body bends in a travelling wave that grows toward the tail.
const wave = (0.25 + 1.3 * p * p) * Math.sin(p * 7.5 - f.t * 2.4 + k.seed);
const a = th - s / (k.r * 0.92);
const X = KOI_C.x + (k.r + wave) * Math.cos(a);
const Z = KOI_C.z + (rz + wave) * Math.sin(a);
const Y = headY - 0.6 * Math.sin(p * 3) + 0.3 * Math.sin(f.t * 0.7 + p * 4);
// Skip slices of the body that are off screen or behind the drone.
const pd = Z - cam.z;
if (pd < 2) continue;
const kk = F / pd;
const sx = CX + (X - cam.x) * kk;
const sy = mirror ? HORIZON + (Y + cam.y) * kk : HORIZON - (Y - cam.y) * kk;
if (sx < -6 * kk || sx > W + 6 * kk || sy < -6 * kk || sy > H + 6 * kk) continue;
const tail = p > 1;
const h = tail ? 0.5 + (p - 1) * 9 : bodyH(p) + (p > 0.3 && p < 0.7 ? 0.5 * Math.sin(((p - 0.3) / 0.4) * Math.PI) : 0);
const thick = tail ? 0.05 : h * 0.5;
// Radial direction, for the body's thickness.
const nx = Math.cos(a);
const nz = Math.sin(a);
for (let v = -h; v <= h; v += step) {
const q = v / h;
const lat = thick * Math.sqrt(Math.max(0, 1 - q * q));
const patch = noise2(s * 0.45 + k.seed * 9, q * 1.5 + 3, 75) > 0.55;
let c = patch ? k.patch : k.base;
const rim = Math.abs(q) > 0.82 || tail;
c = mix(c, CYAN, rim ? 0.6 : 0.12);
let al = tail ? 0.4 : rim ? 0.85 : 0.66;
if (!tail && p < 0.08 && Math.abs(q - 0.25) < 0.18) {
c = CYAN;
al = 0.9;
}
plot(cam, X + nx * lat, Y + v, Z + nz * lat, c, al, mirror);
if (lat > step) plot(cam, X - nx * lat, Y + v, Z - nz * lat, c, al, mirror);
}
// Pectoral fins, swept back below the body.
if (p > 0.2 && p < 0.34) {
const fin = (p - 0.2) / 0.14;
for (let o = 0; o < 1.8 * (1 - fin * 0.4); o += step) {
plot(cam, X + nx * (0.5 + o), Y - bodyH(p) * 0.6 - o * 0.5, Z + nz * (0.5 + o), mix(k.base, CYAN, 0.5), 0.35, mirror);
plot(cam, X - nx * (0.5 + o), Y - bodyH(p) * 0.6 - o * 0.5, Z - nz * (0.5 + o), mix(k.base, CYAN, 0.5), 0.35, mirror);
}
}
}
}
// ---------------------------------------------------------------------------
// Holo-billboards on the low roofs: turning rings, pyramids and cubes, and a dancer
// ---------------------------------------------------------------------------
const HOLO_COLORS: readonly RGB[] = [CYAN, PINK, VIOLET, AMBER, GREEN, CYAN];
function line(cam: Cam, a: readonly number[], b: readonly number[], c: RGB, al: number, step: number, mirror: boolean): void {
const n = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]) / step));
for (let i = 0; i <= n; i++) {
const u = i / n;
plot(cam, a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u, a[2] + (b[2] - a[2]) * u, c, al, mirror);
}
}
/** A dancer's pose: limbs as [x0, y0, x1, y1, radius] segments in meters, in a plane facing the camera. */
function dancer(t: number): [number, number, number, number, number][] {
const sway = Math.sin(t * 0.9) * 0.35;
const hip: [number, number] = [sway * 0.6, 3.4];
const neck: [number, number] = [sway, 6.1];
const armA = 0.9 + Math.sin(t * 0.9) * 0.8;
const armB = 2.1 + Math.sin(t * 0.9 + 1.4) * 0.7;
const elbow = (ang: number, dir: number): [number, number] => [neck[0] + dir * Math.cos(ang) * 1.4, neck[1] - 0.2 + Math.sin(ang) * 1.4];
const e1 = elbow(armA, 1);
const e2 = elbow(armB, -1);
const legA = Math.sin(t * 0.9) * 0.25;
return [
[hip[0], hip[1], neck[0], neck[1], 0.55],
[neck[0], neck[1] + 0.5, neck[0], neck[1] + 0.6, 0.55],
[neck[0], neck[1] - 0.2, e1[0], e1[1], 0.2],
[e1[0], e1[1], e1[0] + Math.cos(armA + 0.6) * 1.3, e1[1] + Math.sin(armA + 0.6) * 1.3, 0.16],
[neck[0], neck[1] - 0.2, e2[0], e2[1], 0.2],
[e2[0], e2[1], e2[0] - Math.cos(armB - 0.5) * 1.3, e2[1] + Math.sin(armB - 0.5) * 1.3, 0.16],
[hip[0] + 0.25, hip[1], 0.5 + legA, 0, 0.25],
[hip[0] - 0.25, hip[1], -0.6 + legA * 0.5, 0.1, 0.25],
];
}
function drawRoofHolo(f: Frame, roof: (typeof ROOFS)[number], mirror: boolean): void {
const cam = f.cam;
const d = roof.z - cam.z;
if (d < 6 || d > 320) return;
const kind = roof.seed % 5;
const c = HOLO_COLORS[roof.seed % HOLO_COLORS.length];
const size = 4 + (roof.seed % 7) * 0.6;
const cy = roof.y + size + 3;
const step = Math.max(0.08, d / F / 1.3);
const ang = f.t * (0.25 + (roof.seed % 3) * 0.08) + roof.seed;
const ca = Math.cos(ang);
const sa = Math.sin(ang);
const P = (x: number, y: number, z: number): number[] => [roof.x + x * ca - z * sa, cy + y, roof.z + x * sa + z * ca];
// A faint beam from the projector on the roof.
for (let i = 0; i < 4; i++) {
const a = (i / 4) * Math.PI * 2 + ang * 0.2;
line(cam, [roof.x, roof.y + 0.3, roof.z], [roof.x + Math.cos(a) * size * 0.6, cy - size * 0.7, roof.z + Math.sin(a) * size * 0.6], c, 0.12, step * 1.5, mirror);
}
if (kind === 0) {
// Two interlocked rings.
const n = Math.ceil((Math.PI * 2 * size) / step);
for (let i = 0; i < n; i++) {
const a = (i / n) * Math.PI * 2;
const pa = P(Math.cos(a) * size, Math.sin(a) * size, 0);
plot(cam, pa[0], pa[1], pa[2], c, 0.7, mirror);
const pb = P(0, Math.sin(a) * size * 0.8, Math.cos(a) * size * 0.8);
plot(cam, pb[0], pb[1], pb[2], PINK, 0.6, mirror);
}
} else if (kind === 1 || kind === 3) {
const v: number[][] =
kind === 1
? [P(-size, -size, -size), P(size, -size, -size), P(size, -size, size), P(-size, -size, size), P(0, size * 1.1, 0)]
: [P(-size, -size, -size), P(size, -size, -size), P(size, -size, size), P(-size, -size, size), P(-size, size, -size), P(size, size, -size), P(size, size, size), P(-size, size, size)];
const edges = kind === 1 ? [[0, 1], [1, 2], [2, 3], [3, 0], [0, 4], [1, 4], [2, 4], [3, 4]] : [[0, 1], [1, 2], [2, 3], [3, 0], [4, 5], [5, 6], [6, 7], [7, 4], [0, 4], [1, 5], [2, 6], [3, 7]];
for (const [a, b] of edges) line(cam, v[a], v[b], c, 0.75, step, mirror);
} else if (kind === 2) {
// A dancer, swaying slowly, drawn as a glowing figure facing the street: rasterized on screen,
// each pixel tested against the limbs.
const sc = size / 4;
const limbs = dancer(f.t + roof.seed);
const base = roof.y + 1;
const p0 = project(cam, roof.x, mirror ? -base : base, roof.z);
if (p0) {
const k = F / p0.d;
const ys = mirror ? -1 : 1;
const x0 = Math.max(0, Math.floor(p0.x - 3 * sc * k));
const x1 = Math.min(W - 1, Math.ceil(p0.x + 3 * sc * k));
const yTop = p0.y - ys * 8 * sc * k;
const y0 = Math.max(0, Math.floor(Math.min(p0.y, yTop)));
const y1 = Math.min(H - 1, Math.ceil(Math.max(p0.y, yTop)));
for (let y = y0; y <= y1; y++) {
const ly = (ys * (p0.y - (y + 0.5))) / (sc * k);
for (let x = x0; x <= x1; x++) {
const lx = (x + 0.5 - p0.x) / (sc * k);
for (const [ax, ay, bx, by, rad] of limbs) {
const vx = bx - ax;
const vy = by - ay;
const u = Math.max(0, Math.min(1, ((lx - ax) * vx + (ly - ay) * vy) / (vx * vx + vy * vy || 1)));
const ex = lx - ax - vx * u;
const ey = ly - ay - vy * u;
if (ex * ex + ey * ey > rad * rad) continue;
plot(cam, roof.x + lx * sc, base + ly * sc, roof.z, c, 0.55, mirror);
break;
}
}
}
}
} else {
// A turning disc with a glyph in it, like a spinning coin.
const n = Math.ceil((Math.PI * 2 * size) / step);
for (let i = 0; i < n; i++) {
const a = (i / n) * Math.PI * 2;
const pa = P(Math.cos(a) * size, Math.sin(a) * size, 0);
plot(cam, pa[0], pa[1], pa[2], c, 0.75, mirror);
}
for (let x = -size * 0.55; x <= size * 0.55; x += step) {
for (let y = -size * 0.55; y <= size * 0.55; y += step) {
const gx = Math.floor((x / size + 0.55) / 0.37);
const gy = Math.floor((0.55 - y / size) / 0.22);
if (hash(gx, gy, roof.seed) < 0.5) continue;
const p = P(x, y, 0);
plot(cam, p[0], p[1], p[2], AMBER, 0.5, mirror);
}
}
}
}
export function drawHolograms(s: Surface, f: Frame): void {
clearGlow();
scan = Math.floor(f.t * 5) % 3;
for (const mirror of [true, false]) {
for (const k of KOI) drawKoi(f, k, mirror);
for (const r of ROOFS) drawRoofHolo(f, r, mirror);
}
compositeGlow(s);
}

View File

@ -0,0 +1,49 @@
import type { Meditation, Scene } from '../types';
import { drawAirship } from './airship';
import { compositeReflections, drawBuildings, traceReflections } from './buildings';
import { drawCrowds } from './crowds';
import { drawHolograms } from './holo';
import { bloom } from './post';
import { drawRain } from './rain';
import { clearFrame, drawSky } from './sky';
import { drawGround, drawStalls, drawSteam } from './street';
import { DURATION, frameAt } from './timeline';
import { drawTraffic, traceTrafficReflections } from './traffic';
const scene: Scene = {
render(s, t) {
const f = frameAt(t);
clearFrame();
drawBuildings(s, f);
drawStalls(s, f);
drawGround(s, f);
drawSky(s, f);
drawAirship(s, f);
traceReflections(f);
traceTrafficReflections(f);
compositeReflections(s, f);
drawTraffic(s, f);
drawCrowds(s, f);
drawSteam(s, f);
drawHolograms(s, f);
drawRain(s, f);
bloom(s);
s.darken(f.fade);
},
};
export const cyberpunkCity: Meditation = {
id: 'cyberpunk-city',
title: 'Cyberpunk City',
subtitle: 'Drifting over a neon city in the rain',
description:
'Float above a rain-soaked avenue in a city of the far future. Crowds with glowing umbrellas fill the sidewalks, hover cars glide between the towers and a holographic koi circles a skyscraper, while neon signs shimmer in the wet streets below. Drift slowly up the avenue to the great plaza of screens, and rest there as the rain softens.',
music: 'audio/cyberpunk-city.mp3',
ambience: [
{ src: 'audio/fx-rain.mp3', volume: 0.5 },
{ src: 'audio/fx-city.mp3', volume: 0.4 },
],
duration: DURATION,
previewTime: 282,
createScene: () => scene,
};

View File

@ -0,0 +1,283 @@
import { hex, mix, scale, type RGB } from '../../engine/color';
import { hash, noise2, Rng } from '../../engine/rng';
/** The neon palette every sign, screen and hologram is drawn from. */
export const PINK = hex('#ff3ea8');
export const CYAN = hex('#30eeff');
export const AMBER = hex('#ffae34');
export const VIOLET = hex('#a35cff');
export const GREEN = hex('#56ffa4');
export const RED = hex('#ff4848');
export const ICE = hex('#d8ecff');
export const NEONS: readonly RGB[] = [PINK, CYAN, AMBER, VIOLET, PINK, CYAN, GREEN, RED, ICE];
export type SignKind = 'glyph' | 'band' | 'ticker' | 'screen' | 'main';
/** A sign or screen flat on a building face, in that face's (u, v) meters: u along the wall, v up. */
export interface Sign {
face: number;
u0: number;
u1: number;
v0: number;
v1: number;
kind: SignKind;
color: RGB;
seed: number;
/** Steady-state colors, worked out on first use. */
pal?: { bg: RGB; border: RGB; avg: RGB };
/** Per-frame state: the time it was worked out for, the flicker level, and the screen's program. */
at?: number;
k?: number;
program?: number;
ad?: number;
prevAd?: number;
into?: number;
}
/** Glyphs for the signs: 3 wide by 5 tall, made up but with the dense look of real lettering. */
const GLYPHS: readonly number[] = (() => {
const r = new Rng(808);
return Array.from({ length: 64 }, () => {
let g = 0;
// A spine plus random strokes reads as a character rather than noise.
const spine = r.int(0, 2);
for (let y = 0; y < 5; y++) for (let x = 0; x < 3; x++) if (x === spine ? r.next() < 0.8 : r.next() < 0.42) g |= 1 << (y * 3 + x);
g |= 7 << (r.int(0, 1) * 12); // a top or bottom bar
return g;
});
})();
export const glyphBit = (g: number, gx: number, gy: number): boolean => ((GLYPHS[g & 63] >> (gy * 3 + gx)) & 1) === 1;
/** Now and then a sign stutters off and on for a moment, then holds steady again for a long while. */
export function flicker(seed: number, t: number): number {
const per = 13;
const p = t / per + hash(seed, 0, 61);
if (hash(seed, Math.floor(p), 62) > 0.12) return 1;
if ((p % 1) * per > 1.5) return 1;
return hash(seed, Math.floor(t * 12), 63) < 0.5 ? 0.22 : 1;
}
const BORDER = 0.28;
/**
* A neon sign's color at (lu, lv) meters inside it, or undefined between letters where the wall
* shows through. `fp` is how many meters one pixel covers; far off, lettering blurs to an even glow.
*/
export function signColor(sg: Sign, lu: number, lv: number, t: number, fp: number): RGB | undefined {
const w = sg.u1 - sg.u0;
const h = sg.v1 - sg.v0;
switch (sg.kind) {
case 'screen':
case 'main':
return screenColor(sg, lu / w, lv / h, t, fp, w);
case 'ticker':
return tickerColor(sg, lu, lv, h, t, fp);
}
if (sg.at !== t) {
sg.at = t;
sg.k = flicker(sg.seed, t);
}
const k = sg.k!;
let col = sg.color;
let pal = (sg.pal ??= signPalette(sg.color, 1));
if (k !== 1) {
col = scale(sg.color, k);
pal = signPalette(sg.color, k);
}
const bg = pal.bg;
if (lu < BORDER || lu > w - BORDER || lv < BORDER || lv > h - BORDER) return fp > BORDER * 3 ? pal.border : col;
const pad = BORDER * 2;
const vertical = sg.kind === 'glyph';
const cw = vertical ? w - pad * 2 : (h - pad * 2) * 0.62;
const ch = vertical ? cw * 1.55 : h - pad * 2;
if (fp > cw / 3) return pal.avg;
const a = (vertical ? lv : lu) - pad;
const across = (vertical ? lu : lv) - pad;
const step = vertical ? ch * 1.2 : cw * 1.3;
const n = Math.floor(a / step);
const inA = a - n * step;
const along = vertical ? ch : cw;
if (inA > along || across < 0 || across > (vertical ? cw : ch)) return bg;
const gx = Math.min(2, Math.floor(((vertical ? across : inA) / cw) * 3));
const gyRaw = ((vertical ? inA : across) / ch) * 5;
const gy = Math.max(0, Math.min(4, Math.floor(5 - gyRaw)));
return glyphBit(Math.floor(hash(sg.seed, n, 64) * 64), gx, gy) ? col : bg;
}
function signPalette(c: RGB, k: number): NonNullable<Sign['pal']> {
const col = scale(c, k);
const bg = scale(c, 0.1 + 0.06 * k);
return { bg, border: mix(bg, col, 0.6), avg: mix(bg, col, 0.42) };
}
/** LED news ticker: amber characters crawling sideways across a black strip. */
function tickerColor(sg: Sign, lu: number, lv: number, h: number, t: number, fp: number): RGB {
const pal = (sg.pal ??= { bg: scale(sg.color, 0.08), border: sg.color, avg: mix(scale(sg.color, 0.08), sg.color, 0.35) });
const bg = pal.bg;
if (fp > h * 0.45) return pal.avg;
const ch = h * 0.8;
const cw = ch * 0.65;
const u = lu + t * 1.6;
const n = Math.floor(u / (cw * 1.35));
const inU = u - n * cw * 1.35;
const y = lv - h * 0.1;
if (inU > cw || y < 0 || y > ch) return bg;
// Some gaps between words.
if (hash(Math.floor(n / 5), 0, sg.seed) < 0.18 && n % 5 === 4) return bg;
const lit = glyphBit(Math.floor(hash(sg.seed, n, 65) * 64), Math.min(2, Math.floor((inU / cw) * 3)), Math.min(4, Math.floor((1 - y / ch) * 5)));
return lit ? sg.color : bg;
}
const SCREEN_INK = hex('#07060e');
const SEA_SKY_TOP = hex('#060a22');
const SEA_SKY_LOW = hex('#24305e');
const MOON = hex('#f4f0dc');
const SEA_DEEP = hex('#040818');
const SEA_GLINT = hex('#c8d4f0');
/**
* Animated content for a video screen at (u, v) in [0, 1] (v = 0 at the bottom). Each screen loops
* through a few slow, soft adverts; the big plaza screen ends on a moonlit sea.
*/
export function screenColor(sg: Sign, u: number, v: number, t: number, fp: number, w: number): RGB {
// A dark bezel round the edge.
const bez = 0.35 / w;
if (u < bez || u > 1 - bez || v < bez * 1.6 || v > 1 - bez * 1.6) return SCREEN_INK;
// Screens are made of big LED tiles, which show close up as a grid of fine dark lines.
const lu = u * w;
const lv = v * (sg.v1 - sg.v0);
const grid = fp < 0.45 && (lu % 0.5 < 0.07 || lv % 0.5 < 0.07);
if (fp < 0.45) {
u = (Math.floor(lu / 0.5) + 0.5) * (0.5 / w);
v = (Math.floor(lv / 0.5) + 0.5) * (0.5 / (sg.v1 - sg.v0));
}
if (sg.at !== t) {
sg.at = t;
const p = t / 24 + hash(sg.seed, 0, 66) * 5;
sg.program = Math.floor(p);
sg.ad = Math.floor(hash(sg.seed, sg.program, 67) * 6);
sg.prevAd = Math.floor(hash(sg.seed, sg.program - 1, 67) * 6);
sg.into = (p % 1) * 24;
}
const program = sg.program!;
// Programs cross-fade into each other over the first two seconds.
let c = adContent(sg.ad!, sg, u, v, t, program);
if (sg.into! < 2) c = mix(adContent(sg.prevAd!, sg, u, v, t, program - 1), c, sg.into! / 2);
return grid ? scale(c, 0.6) : c;
}
function adContent(kind: number, sg: Sign, u: number, v: number, t: number, program: number): RGB {
const a = NEONS[Math.floor(hash(sg.seed, program, 68) * NEONS.length)];
const b = NEONS[Math.floor(hash(sg.seed, program, 69) * NEONS.length)];
switch (kind) {
case 0: {
// Slow flowing color fields, in bands like a cheap LED wall.
const p = Math.sin(u * 6 + t * 0.4) + Math.sin(v * 5 - t * 0.3) + Math.sin((u + v) * 4 + t * 0.25);
return mix(scale(a, 0.3), b, Math.round((0.5 + p / 6) * 5) / 5);
}
case 1: {
// A glowing orb pulsing slowly, product-style, with rings.
const dx = (u - 0.5) * 1.5;
const dy = v - 0.5 - 0.04 * Math.sin(t * 0.5);
const r = Math.hypot(dx, dy);
const R = 0.26 + 0.02 * Math.sin(t * 0.8);
if (r < R) return mix(ICE, a, r / R);
const ring = Math.abs(((r - R) * 10 - t * 0.6) % 1);
return mix(scale(b, 0.12), scale(a, 0.5), ring < 0.12 ? 0.8 : 0.15 * (1 - r));
}
case 2: {
// A synthwave sun over a scrolling grid.
const hz = 0.38;
if (v > hz) {
const sr = Math.hypot((u - 0.5) * 1.6, v - hz - 0.12);
const bands = v < hz + 0.2 && Math.floor((v - hz) * 40) % 3 === 0;
if (sr < 0.28 && !bands) return mix(AMBER, PINK, (hz + 0.4 - v) * 2);
return mix(scale(VIOLET, 0.25), scale(PINK, 0.15), (v - hz) * 1.5);
}
const depth = hz - v + 0.02;
const gx = Math.abs((((u - 0.5) / depth) * 0.08) % 0.1);
const gz = Math.abs((0.05 / depth + t * 0.25) % 0.25);
return gx < 0.012 || gz < 0.03 ? CYAN : scale(VIOLET, 0.12);
}
case 3: {
// Large characters drifting up the screen.
const rows = 4;
const y = v * rows + t * 0.15;
const n = Math.floor(y);
const cols = 3;
const cx = Math.floor(u * cols);
const gx = Math.floor((u * cols - cx) * 3.6);
const gy = Math.floor((1 - (y - n)) * 6);
const on = gx < 3 && gy < 5 && glyphBit(Math.floor(hash(n, cx, sg.seed) * 64), gx, gy);
return on ? a : mix(scale(b, 0.18), scale(a, 0.06), v);
}
case 4: {
// A jellyfish pulsing slowly upward through deep water.
const pulse = 0.5 + 0.5 * Math.sin(t * 1.1);
const cx = 0.5 + 0.06 * Math.sin(t * 0.21);
const cy = 0.62 + 0.04 * Math.sin(t * 0.3);
const bw = 0.2 + 0.04 * pulse;
const bh = 0.16 - 0.03 * pulse;
const dx = (u - cx) / bw;
const dy = (v - cy) / bh;
const water = mix(hex('#04122a'), hex('#0a3050'), v);
if (dy > 0 && dx * dx + dy * dy < 1) return mix(a, ICE, (1 - dy) * 0.5 * (dx * dx + dy * dy));
if (v < cy && v > cy - 0.45 && Math.abs(dx) < 0.9) {
// Tentacles trailing beneath the bell.
const lane = Math.round(dx * 3) / 3;
const wav = lane + 0.08 * Math.sin((cy - v) * 18 - t * 1.6 + lane * 5);
if (Math.abs(dx - wav) < 0.05) return mix(a, water, (cy - v) * 1.6);
}
return water;
}
default: {
// Soft gradient with a slowly turning ribbon.
const ph = u * 3 + t * 0.2;
const ribbon = Math.abs(v - 0.5 - 0.25 * Math.sin(ph)) < 0.07 + 0.03 * Math.sin(ph * 2);
const n = noise2(u * 3 + t * 0.1, v * 3, 70);
return ribbon ? mix(ICE, a, 0.3) : mix(scale(b, 0.2), scale(a, 0.4), Math.round(n * 4) / 4);
}
}
}
/**
* The plaza's big screen at the end: a full moon over a quiet sea, its light broken into glints on
* the swell. `aspect` is the screen's width over its height, so the moon stays round.
*/
export function moonSea(u: number, v: number, t: number, aspect: number): RGB {
const hz = 0.34;
const mx = 0.5;
const my = 0.72;
if (v > hz) {
const r = Math.hypot((u - mx) * aspect, v - my);
if (r < 0.075) return mix(MOON, hex('#d0c8b0'), noise2(u * 40, v * 40, 71) * 0.6);
const halo = Math.max(0, 1 - (r - 0.075) / 0.25);
let c = mix(SEA_SKY_LOW, SEA_SKY_TOP, (v - hz) / (1 - hz));
c = mix(c, hex('#5a6aa0'), halo * halo * 0.6);
if (hash(Math.floor(u * 70), Math.floor(v * 90), 72) < 0.01) c = mix(c, MOON, 0.7);
return c;
}
const depth = (hz - v) / hz;
let c = mix(mix(SEA_SKY_LOW, SEA_DEEP, 0.35), SEA_DEEP, depth);
// Glints: short horizontal dashes on the swell, crowded into a path beneath the moon.
const row = Math.floor(v * 110);
const off = (u - mx) * aspect;
const seg = Math.floor(u * 26 + Math.sin(row * 1.7 + t * 0.5) * 0.6 + t * 0.15 * ((row % 2) * 2 - 1));
const spread = 0.04 + depth * 0.2;
const near = Math.max(0, 1 - Math.abs(off) / spread);
const tw = hash(row, seg, Math.floor(t * 0.8 + hash(row, seg, 76) * 4));
if (tw < 0.15 + near * 0.75) c = mix(c, SEA_GLINT, near * 0.85 + 0.08);
return c;
}
/**
* The shop under a stretch of building front: its window color, or undefined if it's shuttered for
* the night. Shared with the street so the pavement glows the same color as the shop above it.
*/
export const SHOP_W = 5;
const SHOP_COLORS: readonly RGB[] = ['#ffb46a', '#ff6ab8', '#6af0ff', '#b48aff', '#ffe0a0', '#7affc0', '#ff8a5a'].map(hex);
export function shopAt(side: number, n: number): RGB | undefined {
if (hash(n, side, 73) < 0.18) return undefined;
return SHOP_COLORS[Math.floor(hash(n, side, 74) * SHOP_COLORS.length)];
}

View File

@ -0,0 +1,93 @@
import type { Surface } from '../../engine/Surface';
import { H, W } from './world';
/**
* Bloom: light from the brightest pixels bleeds softly into their surroundings, the haze of neon
* in the rain. Worked at quarter size, blurred, and added back.
*/
const S = 4;
const BW = W / S;
const BH = H / S;
const A = new Float32Array(BW * BH * 3);
const B = new Float32Array(BW * BH * 3);
const THRESHOLD = 120;
const STRENGTH = 0.55;
/** A 5-tap tent blur along one axis, clamping at the edges. */
function blur(src: Float32Array, dst: Float32Array, horizontal: boolean): void {
const n = horizontal ? BW : BH;
const lines = horizontal ? BH : BW;
const step = horizontal ? 3 : BW * 3;
for (let l = 0; l < lines; l++) {
const base = horizontal ? l * BW * 3 : l * 3;
for (let i = 0; i < n; i++) {
const m2 = base + Math.max(0, i - 2) * step;
const m1 = base + Math.max(0, i - 1) * step;
const c0 = base + i * step;
const p1 = base + Math.min(n - 1, i + 1) * step;
const p2 = base + Math.min(n - 1, i + 2) * step;
for (let c = 0; c < 3; c++) dst[c0 + c] = (src[m2 + c] + 2 * src[m1 + c] + 3 * src[c0 + c] + 2 * src[p1 + c] + src[p2 + c]) / 9;
}
}
}
/** Bilinear sampling positions for upscaling, per column and per row. */
const axis = (n: number, cells: number) => {
const i0 = new Int32Array(n);
const f = new Float32Array(n);
for (let p = 0; p < n; p++) {
const v = Math.min(cells - 1.001, Math.max(0, (p + 0.5) / S - 0.5));
i0[p] = v | 0;
f[p] = v - (v | 0);
}
return { i0, f };
};
const XS = axis(W, BW);
const YS = axis(H, BH);
export function bloom(s: Surface): void {
const d = s.data;
A.fill(0);
for (let y = 0; y < H; y++) {
const row = ((y / S) | 0) * BW;
for (let x = 0; x < W; x++) {
const i = (y * W + x) * 4;
const r = d[i];
const g = d[i + 1];
const b = d[i + 2];
const lum = r > g ? (r > b ? r : b) : g > b ? g : b;
if (lum <= THRESHOLD) continue;
const k = (row + ((x / S) | 0)) * 3;
const e = (lum - THRESHOLD) / lum / (S * S);
A[k] += r * e;
A[k + 1] += g * e;
A[k + 2] += b * e;
}
}
blur(A, B, true);
blur(B, A, false);
for (let y = 0; y < H; y++) {
const y0 = YS.i0[y];
const ty = YS.f[y];
for (let x = 0; x < W; x++) {
const x0 = XS.i0[x];
const tx = XS.f[x];
const k00 = (y0 * BW + x0) * 3;
const k10 = k00 + 3;
const k01 = k00 + BW * 3;
const k11 = k01 + 3;
const w00 = (1 - tx) * (1 - ty) * STRENGTH;
const w10 = tx * (1 - ty) * STRENGTH;
const w01 = (1 - tx) * ty * STRENGTH;
const w11 = tx * ty * STRENGTH;
const r = A[k00] * w00 + A[k10] * w10 + A[k01] * w01 + A[k11] * w11;
const g = A[k00 + 1] * w00 + A[k10 + 1] * w10 + A[k01 + 1] * w01 + A[k11 + 1] * w11;
const b = A[k00 + 2] * w00 + A[k10 + 2] * w10 + A[k01 + 2] * w01 + A[k11 + 2] * w11;
if (r + g + b < 1) continue;
const i = (y * W + x) * 4;
d[i] += r;
d[i + 1] += g;
d[i + 2] += b;
}
}
}

View File

@ -0,0 +1,84 @@
import { hex } from '../../engine/color';
import { hash, Rng } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import type { Frame } from './timeline';
import { H, HORIZON, MAT, M_ROAD, M_SOLID, M_WALK, W } from './world';
/**
* Rain in three layers by distance: fine and slow far off, long bright streaks close to the lens.
* Each streak picks up the color of whatever is behind it, so rain in front of neon glows.
*/
interface Drop {
x0: number;
y0: number;
rank: number;
}
interface Layer {
drops: Drop[];
speed: number;
len: number;
alpha: number;
/** How strongly a streak takes on the light behind it. */
pick: number;
}
const SLANT = 0.16;
const BASE = hex('#46506a');
function layer(seed: number, n: number, speed: number, len: number, alpha: number, pick: number): Layer {
const r = new Rng(seed);
return { drops: Array.from({ length: n }, (_, i) => ({ x0: r.range(-40, W + 10), y0: r.range(0, H + 40), rank: i / n })), speed, len, alpha, pick };
}
const LAYERS: readonly Layer[] = [layer(11, 900, 150, 3, 0.17, 0.4), layer(12, 380, 240, 6, 0.26, 0.55), layer(13, 100, 420, 12, 0.34, 0.65)];
export function drawRain(s: Surface, f: Frame): void {
const d = s.data;
for (const L of LAYERS) {
const wrap = H + L.len + 20;
for (const dr of L.drops) {
if (dr.rank > f.rain) continue;
const y = ((dr.y0 + L.speed * f.t) % wrap) - L.len - 10;
const x = dr.x0 + y * SLANT;
for (let n = 0; n < L.len; n++) {
const yy = Math.floor(y + n);
const xx = Math.floor(x + n * SLANT);
if (yy < 0 || yy >= H || xx < 0 || xx >= W) continue;
const i = (yy * W + xx) * 4;
const a = L.alpha * (0.4 + 0.6 * (n / L.len));
d[i] += (BASE[0] + d[i] * L.pick) * a;
d[i + 1] += (BASE[1] + d[i + 1] * L.pick) * a;
d[i + 2] += (BASE[2] + d[i + 2] * L.pick) * a;
}
}
}
drawSplashes(s, f);
}
const SPLASH = hex('#9aa4c4');
const SPLASHES = 260;
const SPLASH_LIFE = 0.14;
/** Drops bursting on the wet street and the roofs: a bright fleck, with a tiny crown close up. */
function drawSplashes(s: Surface, f: Frame): void {
const n = Math.round(SPLASHES * f.rain);
for (let i = 0; i < n; i++) {
const period = 0.45 + hash(i, 0, 140) * 0.4;
const p = f.t / period + hash(i, 1, 140);
const cycle = Math.floor(p);
const age = (p - cycle) * period;
if (age > SPLASH_LIFE) continue;
const x = Math.floor(hash(i, cycle, 141) * W);
const y = Math.floor(HORIZON + 6 + hash(i, cycle, 142) * (H - HORIZON - 6));
const m = MAT[y * W + x];
if (m !== M_ROAD && m !== M_WALK && m !== M_SOLID) continue;
const near = (y - HORIZON) / (H - HORIZON);
const k = 0.5 * (1 - age / SPLASH_LIFE);
s.light(x, y, SPLASH, k);
if (near > 0.55 && m !== M_SOLID) {
s.light(x - 1, y - 1, SPLASH, k * 0.5);
s.light(x + 1, y - 1, SPLASH, k * 0.5);
}
}
}

View File

@ -0,0 +1,110 @@
import { hex, mix, type RGB } from '../../engine/color';
import { hash, noise2 } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import { FOG, type Frame } from './timeline';
import { CX, DEPTH, F, H, HORIZON, MAT, M_SKY, project, W } from './world';
/** A low ceiling of rain cloud hangs over the towers, lit from beneath by the city. */
const CLOUD_Y = 300;
const ZENITH = hex('#0a0818');
const HIGH = hex('#170f2c');
const CLOUD_DARK = hex('#1c1232');
const CLOUD_PINK = hex('#5e2a66');
const CLOUD_TEAL = hex('#1e4660');
const BEAM = hex('#a8b8ff');
/** Searchlights far off in the city, sweeping slowly back and forth across the clouds. */
const SEARCHLIGHTS = [
{ x: -520, z: 1500, rate: 0.05, phase: 0.3, spread: 0.55 },
{ x: 260, z: 1900, rate: 0.037, phase: 2.1, spread: 0.6 },
{ x: 900, z: 1300, rate: 0.043, phase: 4.0, spread: 0.45 },
{ x: -1100, z: 2100, rate: 0.031, phase: 1.2, spread: 0.5 },
] as const;
/** Start a frame: nothing drawn yet, everything at infinite depth. */
export function clearFrame(): void {
DEPTH.fill(Infinity);
MAT.fill(M_SKY);
}
const skyRow = new Float32Array(W * 3);
/** Fill whatever the city left uncovered with cloud, sampled every other pixel since it's soft anyway. */
export function drawSky(s: Surface, f: Frame): void {
const cam = f.cam;
const drift = f.t * 1.6;
const d = s.data;
for (let y = 0; y < H; y++) {
const dy = -(y + 0.5 - HORIZON) / F;
const up = Math.max(0, dy);
const base = mix(FOG, mix(HIGH, ZENITH, Math.min(1, up * 2.2)), Math.min(1, up * 4));
const tc = up > 0.01 ? (CLOUD_Y - cam.y) / up : Infinity;
let any = false;
for (let x = 0; x < W; x++) if (DEPTH[y * W + x] === Infinity) any = true;
if (!any) continue;
if ((y & 1) === 0 || y === 0) {
for (let x = 0; x < W; x += 2) {
let c: RGB = base;
if (tc < 6000) {
const X = cam.x + ((x + 1 - CX) / F) * tc;
const Z = cam.z + tc;
const n = noise2(X / 260 + drift / 260, Z / 200, 3) * 0.65 + noise2(X / 90, Z / 70 - drift / 140, 4) * 0.35;
const tint = noise2(X / 700, Z / 600, 5);
let cc = mix(CLOUD_DARK, tint > 0.55 ? CLOUD_TEAL : CLOUD_PINK, Math.max(0, n - 0.35) * 1.3);
// The clouds catch more of the city's glow the lower they sit over the horizon.
cc = mix(cc, FOG, Math.min(1, tc / 4500));
c = mix(base, cc, 0.85);
}
skyRow[x * 3] = skyRow[x * 3 + 3] = c[0];
skyRow[x * 3 + 1] = skyRow[x * 3 + 4] = c[1];
skyRow[x * 3 + 2] = skyRow[x * 3 + 5] = c[2];
}
}
for (let x = 0; x < W; x++) {
if (DEPTH[y * W + x] !== Infinity) continue;
const i = (y * W + x) * 4;
d[i] = skyRow[x * 3];
d[i + 1] = skyRow[x * 3 + 1];
d[i + 2] = skyRow[x * 3 + 2];
d[i + 3] = 255;
}
}
drawSearchlights(s, f);
}
function drawSearchlights(s: Surface, f: Frame): void {
const cam = f.cam;
for (const sl of SEARCHLIGHTS) {
const base = project(cam, sl.x, 0, sl.z);
if (!base) continue;
const a = Math.sin(f.t * sl.rate * Math.PI * 2 + sl.phase) * sl.spread;
// Where the beam meets the cloud ceiling.
const top = project(cam, sl.x + Math.sin(a) * CLOUD_Y * 0.9, CLOUD_Y, sl.z + Math.cos(a * 0.7) * 120);
if (!top) continue;
const steps = Math.ceil(Math.hypot(top.x - base.x, top.y - base.y));
for (let n = 0; n <= steps; n++) {
const u = n / steps;
const x = base.x + (top.x - base.x) * u;
const y = base.y + (top.y - base.y) * u;
if (y < 0 || y >= HORIZON + 2) continue;
const wHalf = 0.6 + u * 3.5;
const k = 0.07 * (1 - u * 0.5);
for (let o = -Math.ceil(wHalf); o <= Math.ceil(wHalf); o++) {
const xx = Math.floor(x + o);
if (xx < 0 || xx >= W || DEPTH[Math.floor(y) * W + xx] !== Infinity) continue;
const e = 1 - Math.abs(o) / (wHalf + 1);
s.light(xx, y, BEAM, k * e * e);
}
}
// A soft pool of light where it hits the clouds.
for (let oy = -3; oy <= 3; oy++) {
for (let ox = -8; ox <= 8; ox++) {
const e = 1 - Math.hypot(ox / 8, oy / 3);
const xx = Math.floor(top.x + ox);
const yy = Math.floor(top.y + oy);
if (e <= 0 || xx < 0 || xx >= W || yy < 0 || yy >= H || DEPTH[yy * W + xx] !== Infinity) continue;
s.light(xx, yy, BEAM, 0.1 * e * (0.85 + 0.15 * hash(ox, oy, 9)));
}
}
}
}

View File

@ -0,0 +1,297 @@
import { hex, mix, scale, type RGB } from '../../engine/color';
import { hash } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import { glyphBit, NEONS, shopAt, SHOP_W } from './neon';
import { FOG_LOW, haze, type Frame } from './timeline';
import { FRONT, LEFT, RIGHT, SCREEN, TOP, traceBox, type Box3 } from './trace';
import {
BACK_STREET,
BLOCK,
clarity,
CROSS_HALF,
crossAt,
CX,
DEPTH,
F,
glowClarity,
gridDist,
H,
HORIZON,
isRoad,
LANE_HALF,
LINE,
MAT,
M_ROAD,
M_WALK,
PLAZA,
project,
ROAD_HALF,
smoothstep,
splitAt,
stallAt,
STALL_SLOT,
ventAt,
VENT_SLOT,
W,
WET,
} from './world';
const ASPHALT = hex('#121119');
const MARKING = hex('#4a4858');
const CENTER = hex('#5a4422');
const CURB = hex('#2c2a36');
const PAVEMENT = hex('#1e1b26');
const SEAM = hex('#16141d');
const PAVING = hex('#221f2c');
const INLAY = hex('#3ad8ff');
const LANTERN = hex('#ff8a3a');
const STALL_LIGHT = hex('#ffb060');
/** Share of a pixel `fp` meters across covered by a stripe `w` wide whose center is `m` away. */
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 pavement and roadway at (X, Z), before any light falls on it; sets `gRoad` and `gWet` alongside. */
let gRoad = false;
let gWet = 0;
const ground = (c: RGB, road: boolean, wet: number): RGB => {
gRoad = road;
gWet = wet;
return c;
};
function groundColor(X: number, Z: number, fp: number): RGB {
const ax = Math.abs(X);
const k = crossAt(Z);
if (Z < PLAZA.z0) {
if (k !== undefined) {
const dz = Z - k * BLOCK;
let c = ASPHALT;
if (ax < ROAD_HALF) {
// The scramble: diagonal zebra crossings across the intersection.
const a = gridDist((X + dz * (ROAD_HALF / CROSS_HALF)) / 1.41, 1.3);
const b = gridDist((X - dz * (ROAD_HALF / CROSS_HALF)) / 1.41, 1.3);
const onA = Math.abs(X - dz * (ROAD_HALF / CROSS_HALF)) < 1.8;
const onB = Math.abs(X + dz * (ROAD_HALF / CROSS_HALF)) < 1.8;
const m = Math.max(onA ? cover(a, 0.55, fp) : 0, onB ? cover(b, 0.55, fp) : 0);
c = mix(c, MARKING, m);
} else if (ax < LINE - 1.5) {
// Crosswalks over the cross street, in line with the sidewalks.
c = mix(c, MARKING, cover(gridDist(dz, 1.3), 0.6, fp));
}
return ground(c, true, 0.6);
}
if (ax < ROAD_HALF) {
let c = ASPHALT;
const kk = Math.round(Z / BLOCK);
const dz = Z - kk * BLOCK;
const adz = Math.abs(dz);
if (adz > CROSS_HALF && adz < CROSS_HALF + 3.5) c = mix(c, MARKING, cover(gridDist(X, 1.2), 0.62, fp));
else if (Math.abs(adz - CROSS_HALF - 4.2) < 0.25 && Math.sign(dz) === -Math.sign(X)) c = mix(c, MARKING, 0.8);
else {
c = mix(c, CENTER, cover(Math.abs(ax - 0.18), 0.12, fp));
if (Z % 6 < 3) c = mix(c, MARKING, cover(Math.abs(ax - LANE_HALF), 0.14, fp) * 0.7);
c = mix(c, MARKING, cover(Math.abs(ax - ROAD_HALF + 0.3), 0.12, fp) * 0.5);
}
return ground(c, true, 0.6);
}
if (ax < ROAD_HALF + 0.3) return ground(CURB, false, 0.3);
let c = PAVEMENT;
c = mix(c, SEAM, Math.max(cover(gridDist(X, 1.5), 0.08, fp), cover(gridDist(Z, 1.5), 0.08, fp)));
return ground(c, false, 0.32);
}
if (isRoad(X, Z)) {
let c = ASPHALT;
if (Z < BACK_STREET.z0) c = mix(c, MARKING, cover(Math.abs(ax - LANE_HALF - splitAt(Z)), 0.12, fp) * 0.6);
return ground(c, true, 0.6);
}
// The plaza: big pavers with lines of light set into them.
let c = PAVING;
c = mix(c, SEAM, Math.max(cover(gridDist(X, 3), 0.1, fp), cover(gridDist(Z, 3), 0.1, fp)));
const inlay = Math.max(cover(gridDist(Z - PLAZA.z0, 12, 6), 0.25, fp), cover(gridDist(X, 24, 12), 0.25, fp));
c = mix(c, scale(INLAY, 0.55), inlay * 0.8);
return ground(c, false, 0.42);
}
export function drawGround(s: Surface, f: Frame): void {
const cam = f.cam;
const d = s.data;
for (let y = HORIZON; y < H; y++) {
const ry = (y + 0.5 - HORIZON) / F;
const tg = cam.y / ry;
if (tg > 2600) continue;
const Z = cam.z + tg;
const fp = tg / F;
const fog = 1 - clarity(tg);
const sheen = 0.7 + 0.3 * smoothstep(30, 220, tg);
for (let x = 0; x < W; x++) {
const k = y * W + x;
if (DEPTH[k] !== Infinity) continue;
const X = cam.x + ((x + 0.5 - CX) / F) * tg;
let c = groundColor(X, Z, fp);
const ax = Math.abs(X);
if (Z < PLAZA.z0 && ax > ROAD_HALF && ax < LINE && crossAt(Z) === undefined) {
// Shop windows and food stalls throw pools of light across the pavement.
const side = Math.sign(X);
const shop = shopAt(side, Math.floor(Z / SHOP_W));
if (shop) c = mix(c, shop, 0.32 * Math.exp(-(LINE - ax) / 2));
const slot = Math.floor(Z / STALL_SLOT);
if (stallAt(slot, side)) {
const dz = Z - (slot + 0.5) * STALL_SLOT;
const dx = ax - (LINE - 2.5);
c = mix(c, STALL_LIGHT, 0.4 * Math.exp(-(dx * dx + dz * dz) / 7));
}
}
// The haze lies thickest along the street, warmed by the neon.
c = mix(c, FOG_LOW, fog);
let wet = gWet;
if (hash(Math.floor(X / 2.6), Math.floor(Z / 2.6), 95) < 0.18) wet = Math.min(0.92, wet + 0.3);
DEPTH[k] = tg;
MAT[k] = gRoad ? M_ROAD : M_WALK;
WET[k] = wet * sheen;
const i = k * 4;
d[i] = c[0];
d[i + 1] = c[1];
d[i + 2] = c[2];
d[i + 3] = 255;
}
}
}
// ---------------------------------------------------------------------------
// Street-food stalls: a lit counter under a striped awning, lanterns hung along its edge
// ---------------------------------------------------------------------------
interface Stall {
side: number;
zc: number;
counter: Box3;
awning: Box3;
stripe: RGB;
sign: RGB;
seed: number;
}
const STRIPES: readonly RGB[] = ['#c83a3a', '#2a9ab0', '#c87a2a', '#8a3ac8'].map(hex);
const CREAM = hex('#d8ccb0');
const WOOD = hex('#3a2a22');
const STALLS: Stall[] = [];
for (let slot = -8; slot < Math.ceil(PLAZA.z0 / STALL_SLOT); slot++) {
for (const side of [1, -1]) {
if (!stallAt(slot, side)) continue;
const zc = (slot + 0.5) * STALL_SLOT;
const xa = side * (LINE - 2.4);
const xw = side * (LINE - 3.4);
STALLS.push({
side,
zc,
counter: { x0: Math.min(xa, side * LINE), x1: Math.max(xa, side * LINE), y0: 0, y1: 1.1, z0: zc - 1.6, z1: zc + 1.6 },
awning: { x0: Math.min(xw, side * LINE), x1: Math.max(xw, side * LINE), y0: 2.3, y1: 2.5, z0: zc - 1.9, z1: zc + 1.9 },
stripe: STRIPES[Math.floor(hash(slot, side, 96) * STRIPES.length)],
sign: NEONS[Math.floor(hash(slot, side, 97) * NEONS.length)],
seed: Math.floor(hash(slot, side, 98) * 9999),
});
}
}
export function drawStalls(s: Surface, f: Frame): void {
const cam = f.cam;
for (const st of STALLS) {
if (st.zc < cam.z || st.zc - cam.z > 320) continue;
const toRoad = st.side > 0 ? LEFT : RIGHT;
traceBox(SCREEN, cam, st.counter, (face, _X, Y, _Z, d) => {
let c: RGB = WOOD;
if (face === TOP) c = scale(STALL_LIGHT, 0.6);
else if (face === toRoad || face === FRONT) c = Y > 0.8 ? scale(STALL_LIGHT, 0.85) : mix(WOOD, STALL_LIGHT, 0.25);
return haze(c, 1 - glowClarity(d));
});
traceBox(SCREEN, cam, st.awning, (face, _X, Y, Z, d) => {
let c: RGB;
if (face === TOP) c = scale(Math.floor((Z - st.awning.z0) / 0.55) % 2 ? st.stripe : CREAM, 0.5);
else if (face === toRoad || face === FRONT) {
// The stall's name in neon along the awning's edge.
const lu = Z - st.awning.z0;
const gx = Math.floor(((lu % 0.42) / 0.42) * 3.5);
const gy = Math.floor((1 - (Y - st.awning.y0) / 0.2) * 5);
const on = d / F < 0.08 ? gx < 3 && glyphBit(Math.floor(hash(Math.floor(lu / 0.42), st.seed, 99) * 64), gx, Math.min(4, gy)) : true;
c = on || face === FRONT ? st.sign : scale(st.sign, 0.3);
} else c = scale(st.stripe, 0.4);
return haze(c, 1 - glowClarity(d));
});
// Paper lanterns along the front edge of the awning.
for (let n = -1; n <= 1; n++) {
const p = project(cam, st.side * (LINE - 3.3), 2.0 + 0.04 * Math.sin(f.t * 0.8 + n + st.seed), st.zc + n * 1.25);
if (!p || p.x < 0 || p.x >= W || p.y < 0 || p.y >= H) continue;
if (DEPTH[(p.y | 0) * W + (p.x | 0)] < p.d - 0.5) continue;
const k = glowClarity(p.d);
const r = Math.max(0.6, 0.32 * (F / p.d));
glowDot(s, p.x, p.y, r, LANTERN, k);
}
}
}
/** A small soft light: a bright core with a dim halo. */
export function glowDot(s: Surface, x: number, y: number, r: number, c: RGB, k: number): void {
const R = Math.ceil(r * 2.2);
for (let oy = -R; oy <= R; oy++) {
for (let ox = -R; ox <= R; ox++) {
const dd = Math.hypot(ox, oy) / r;
const a = dd < 1 ? 1 : Math.max(0, 0.35 * (1 - (dd - 1) / 1.2));
if (a > 0) s.light(x + ox, y + oy, c, a * k);
}
}
}
// ---------------------------------------------------------------------------
// Steam rising from the stalls and from manholes in the road
// ---------------------------------------------------------------------------
const STEAM_WARM = hex('#a89088');
const STEAM_COOL = hex('#8a84a4');
const PUFFS = 6;
const LIFE = 7.5;
function drawPlume(s: Surface, f: Frame, X: number, Y: number, Z: number, seed: number, color: RGB, size: number, rise: number): void {
const cam = f.cam;
for (let i = 0; i < PUFFS; i++) {
const ph = hash(seed, i, 100) * LIFE;
const age = (((f.t + ph + (i * LIFE) / PUFFS) % LIFE) + LIFE) % LIFE;
const u = age / LIFE;
const px = X + age * 0.22 + 0.4 * Math.sin(age * 0.7 + seed);
const py = Y + age * rise;
const pz = Z + 0.3 * Math.sin(age * 0.5 + i);
const p = project(cam, px, py, pz);
if (!p) continue;
const R = (0.35 + u * 1.6) * size * (F / p.d);
if (R < 0.6 || p.x + R < 0 || p.x - R > W || p.y + R < 0 || p.y - R > H) continue;
const a = 0.2 * Math.sin(Math.PI * u) * glowClarity(p.d);
const Ri = Math.ceil(R);
for (let oy = -Ri; oy <= Ri; oy++) {
const yy = Math.floor(p.y + oy);
if (yy < 0 || yy >= H) continue;
for (let ox = -Ri; ox <= Ri; ox++) {
const xx = Math.floor(p.x + ox);
if (xx < 0 || xx >= W) continue;
const e = 1 - Math.hypot(ox, oy) / R;
if (e <= 0 || DEPTH[yy * W + xx] < p.d - 1) continue;
s.blend(xx, yy, color, a * Math.min(1, e * 1.6));
}
}
}
}
export function drawSteam(s: Surface, f: Frame): void {
const cam = f.cam;
for (const st of STALLS) {
if (st.zc < cam.z + 5 || st.zc - cam.z > 260) continue;
drawPlume(s, f, st.side * (LINE - 1.6), 1.3, st.zc, st.seed, STEAM_WARM, 0.8, 0.45);
}
const s0 = Math.floor(cam.z / VENT_SLOT);
for (let n = s0; n < s0 + 14; n++) {
const v = ventAt(n);
if (!v || v.z < cam.z + 5) continue;
drawPlume(s, f, v.x, 0.1, v.z, n * 13 + 5, STEAM_COOL, 1.3, 0.6);
}
}

View File

@ -0,0 +1,60 @@
import { hex, type RGB } from '../../engine/color';
import { progress, track } from '../../engine/Timeline';
import { noise1 } from '../../engine/rng';
import { altitudeAt, camZAt, DURATION, TIMES } from './drone';
import type { Cam } from './world';
export { DURATION, TIMES };
/** The rain haze everything far away dissolves into: lit violet by the city below. */
export const FOG = hex('#2e1d44');
/** The haze where it meets the street, a little warmer and brighter. */
export const FOG_LOW = hex('#3c2448');
export interface Frame {
t: number;
cam: Cam;
/** Rain density, 0–1. */
rain: number;
/** How far the main plaza screen has dissolved into the moonlit sea, 0–1. */
moon: number;
/** Overall brightness for the fade in/out. */
fade: number;
}
const rain = track([
[0, 1],
[TIMES.drizzle[0], 1],
[TIMES.drizzle[1], 0.3],
]);
export function frameAt(t: number): Frame {
// The drone sways and bobs a little in the wind, settling as it comes to a hover.
const sway = 1 - 0.5 * progress(t, TIMES.arrive[0], TIMES.arrive[1]);
const cam: Cam = {
x: 1.2 * (noise1(t * 0.035, 11) - 0.5) * sway,
y: altitudeAt(t) + 0.8 * (noise1(t * 0.05, 12) - 0.5) * sway,
z: camZAt(t) + 0.8 * (noise1(t * 0.03, 13) - 0.5) * sway,
};
return {
t,
cam,
rain: rain(t),
moon: progress(t, TIMES.moon[0], TIMES.moon[1]),
fade: progress(t, TIMES.fadeIn[0], TIMES.fadeIn[1]) * (1 - progress(t, TIMES.fadeOut[0], TIMES.fadeOut[1])),
};
}
const HAZED: [number, number, number] = [0, 0, 0];
/**
* Fade a surface color into the haze by distance. Returns a shared scratch color, so it's only for
* handing straight to a raster, which copies it.
*/
export function haze(c: RGB, k: number): RGB {
HAZED[0] = c[0] + (FOG[0] - c[0]) * k;
HAZED[1] = c[1] + (FOG[1] - c[1]) * k;
HAZED[2] = c[2] + (FOG[2] - c[2]) * k;
return HAZED;
}

View File

@ -0,0 +1,180 @@
import type { RGB } from '../../engine/color';
import type { Surface } from '../../engine/Surface';
import { CX, DEPTH, F, H, HORIZON, MAT, M_SOLID, NEAR, W, type Cam } from './world';
/** An axis-aligned box in world meters. */
export interface Box3 {
x0: number;
x1: number;
y0: number;
y1: number;
z0: number;
z1: number;
}
/** Faces of a box as a ray enters it. */
export const FRONT = 0; // the z0 face, toward the camera
export const LEFT = 1; // the x0 face, looking toward -x
export const RIGHT = 2; // the x1 face, looking toward +x
export const TOP = 3;
export const BOTTOM = 4;
/** Beyond this depth (m, times the raster's pixel size) neighbouring pixels share shading. */
const LOD_D = 220;
/** Color of a box at a hit point, or undefined to let the ray pass (e.g. a gap in a sign). */
export type Shader = (face: number, X: number, Y: number, Z: number, d: number) => RGB | undefined;
/** Something boxes can be traced into: the frame itself, or the half-size reflection buffer. */
export interface Raster {
w: number;
h: number;
/** Screen pixels per raster pixel, and the screen row of the raster's first row. */
scale: number;
row0: number;
depth: Float32Array;
put(i: number, j: number, c: RGB): void;
}
let target: Surface | undefined;
/** Ray slope for each raster column, and its inverse, worked out once per raster size. */
const slopes = new Map<string, { dx: Float64Array; inv: Float64Array }>();
function columnSlopes(w: number, scale: number): { dx: Float64Array; inv: Float64Array } {
const key = `${w}x${scale}`;
let s = slopes.get(key);
if (!s) {
const dx = Float64Array.from({ length: w }, (_, i) => ((i + 0.5) * scale - CX) / F);
s = { dx, inv: dx.map((v) => (v === 0 ? Infinity : 1 / v)) };
slopes.set(key, s);
}
return s;
}
/** The full-size frame, writing solid pixels with their depth. */
export const SCREEN: Raster = {
w: W,
h: H,
scale: 1,
row0: 0,
depth: DEPTH,
put(i, j, c) {
target!.set(i, j, c);
MAT[j * W + i] = M_SOLID;
},
};
export function bindScreen(s: Surface): void {
target = s;
}
/**
* Ray trace a box into a raster: each pixel's ray finds the face it enters and where, and the
* shader colors it, with a depth test so boxes may be drawn in any order. With `mirror` the box is
* traced upside down beneath the street, which is exactly its reflection in the wet ground.
*/
export function traceBox(r: Raster, cam: Cam, b: Box3, shade: Shader, mirror = false): void {
const by0 = mirror ? -b.y1 : b.y0;
const by1 = mirror ? -b.y0 : b.y1;
const zn = Math.max(b.z0, cam.z + NEAR);
if (b.z1 <= zn) return;
let sx0 = Infinity;
let sx1 = -Infinity;
let sy0 = Infinity;
let sy1 = -Infinity;
for (let n = 0; n < 2; n++) {
const k = F / ((n ? b.z1 : zn) - cam.z);
const xa = CX + (b.x0 - cam.x) * k;
const xb = CX + (b.x1 - cam.x) * k;
const ya = HORIZON - (by1 - cam.y) * k;
const yb = HORIZON - (by0 - cam.y) * k;
sx0 = Math.min(sx0, xa);
sx1 = Math.max(sx1, xb);
sy0 = Math.min(sy0, ya);
sy1 = Math.max(sy1, yb);
}
const s = r.scale;
const i0 = Math.max(0, Math.floor(sx0 / s));
const i1 = Math.min(r.w - 1, Math.floor(sx1 / s));
const j0 = Math.max(0, Math.floor((sy0 - r.row0) / s));
const j1 = Math.min(r.h - 1, Math.floor((sy1 - r.row0) / s));
if (i0 > i1 || j0 > j1) return;
const tz0 = b.z0 - cam.z;
const tz1 = b.z1 - cam.z;
/** No ray can meet the box nearer than this, so pixels already showing something nearer are skipped outright. */
const tNear = Math.max(NEAR, tz0);
const depth = r.depth;
const { dx: DX, inv: INV } = columnSlopes(r.w, s);
const ax0 = b.x0 - cam.x;
const ax1 = b.x1 - cam.x;
for (let j = j0; j <= j1; j++) {
const dy = -(r.row0 + (j + 0.5) * s - HORIZON) / F;
let tyMin = -Infinity;
let tyMax = Infinity;
let yFace = TOP;
if (dy !== 0) {
const ta = (by0 - cam.y) / dy;
const tb = (by1 - cam.y) / dy;
if (ta < tb) {
tyMin = ta;
tyMax = tb;
yFace = BOTTOM;
} else {
tyMin = tb;
tyMax = ta;
}
} else if (cam.y < by0 || cam.y > by1) continue;
if (mirror) yFace = yFace === TOP ? BOTTOM : TOP;
const row = j * r.w;
let lastI = -2;
let lastFace = -1;
let lastC: [number, number, number] = [0, 0, 0];
for (let i = i0; i <= i1; i++) {
if (depth[row + i] <= tNear) continue;
const dx = DX[i];
let tmin = tz0;
let tmax = tz1;
let face = FRONT;
if (dx !== 0) {
let ta = ax0 * INV[i];
let tb = ax1 * INV[i];
let xFace = LEFT;
if (ta > tb) {
const tmp = ta;
ta = tb;
tb = tmp;
xFace = RIGHT;
}
if (ta > tmin) {
tmin = ta;
face = xFace;
}
if (tb < tmax) tmax = tb;
} else if (cam.x < b.x0 || cam.x > b.x1) continue;
if (tyMin > tmin) {
tmin = tyMin;
face = yFace;
}
if (tyMax < tmax) tmax = tyMax;
if (tmin > tmax || tmin < NEAR) continue;
const k = row + i;
if (tmin >= depth[k]) continue;
// Far off, detail is averaged away anyway, so every other pixel copies its neighbour on the same face.
if (tmin * r.scale > LOD_D && (i & 1) === 1 && lastI === i - 1 && lastFace === face) {
depth[k] = tmin;
r.put(i, j, lastC);
continue;
}
const Y = cam.y + dy * tmin;
const c = shade(face, cam.x + dx * tmin, mirror ? -Y : Y, cam.z + tmin, tmin);
if (!c) continue;
depth[k] = tmin;
r.put(i, j, c);
lastI = i;
lastFace = face;
lastC[0] = c[0];
lastC[1] = c[1];
lastC[2] = c[2];
}
}
}

View File

@ -0,0 +1,417 @@
import { hex, mix, scale, type RGB } from '../../engine/color';
import { hash, Rng } from '../../engine/rng';
import type { Surface } from '../../engine/Surface';
import { MIRROR } from './buildings';
import { camZAt, DURATION, TIMES } from './drone';
import { CYAN, ICE, PINK, RED, VIOLET } from './neon';
import { glowDot } from './street';
import { haze, type Frame } from './timeline';
import { BOTTOM, FRONT, SCREEN, TOP, traceBox, type Box3, type Raster } from './trace';
import {
BACK_STREET,
BLOCK,
CROSS_HALF,
DEPTH,
F,
glowClarity,
GREEN,
H,
LAST_CROSS,
LINE,
MAT,
M_ROAD,
PLAZA,
project,
roadwayX,
signalPhase,
smoothstep,
W,
YELLOW,
type Cam,
} from './world';
// ---------------------------------------------------------------------------
// Vehicles: little boxes with lights
// ---------------------------------------------------------------------------
interface Look {
body: RGB;
roof: RGB;
/** Neon trim along the sides and the glow it throws underneath. */
trim: RGB;
/** A lit roof sign, for taxis. */
sign?: RGB;
w: number;
len: number;
h: number;
}
const LOOKS: readonly Look[] = [
{ body: hex('#c89a2a'), roof: hex('#e0b440'), trim: hex('#ffcc44'), sign: hex('#fff0b0'), w: 2, len: 4.4, h: 1.3 },
{ body: hex('#c89a2a'), roof: hex('#e0b440'), trim: hex('#ffcc44'), sign: hex('#fff0b0'), w: 2, len: 4.4, h: 1.3 },
{ body: hex('#d8dce4'), roof: hex('#eef0f6'), trim: CYAN, w: 2, len: 4.2, h: 1.2 },
{ body: hex('#1c1c26'), roof: hex('#2a2a36'), trim: PINK, w: 2.1, len: 4.8, h: 1.25 },
{ body: hex('#2a3448'), roof: hex('#3a465e'), trim: VIOLET, w: 2.2, len: 6.5, h: 2.2 },
{ body: hex('#5a1c2a'), roof: hex('#7a2a3a'), trim: CYAN, w: 2, len: 4.4, h: 1.25 },
];
const GLASS = hex('#0c1018');
const TAIL = RED;
const HEAD = ICE;
/** A vehicle placed in the world for one frame: its box, which way it faces, and how it looks. */
interface Placed extends Box3 {
look: Look;
/** +1 heading up the avenue (we see its tail), -1 heading toward us (headlights); 0 crossing. */
dir: number;
/** How faded in it is, 0–1, at the ends of its route. */
alpha: number;
}
function shadeVehicle(v: Placed, face: number, X: number, Y: number, Z: number, d: number): RGB {
const L = v.look;
const y0 = v.y0;
const lv = (Y - y0) / (v.y1 - y0);
let c: RGB;
if (face === TOP) {
c = L.roof;
if (L.sign && Math.abs(X - (v.x0 + v.x1) / 2) < 0.4 && Math.abs(Z - (v.z0 + v.z1) / 2) < 0.4) c = L.sign;
// A glossy streak where the wet roof catches the neon.
else if (Math.abs(X - v.x0 - (v.x1 - v.x0) * 0.3) < 0.18) c = mix(c, ICE, 0.25);
} else if (face === BOTTOM) c = L.trim;
else if (face === FRONT) {
const lu = (X - v.x0) / (v.x1 - v.x0);
if (v.dir !== 0 && lv > 0.35 && lv < 0.7 && (lu < 0.22 || lu > 0.78)) c = v.dir > 0 ? TAIL : HEAD;
else if (lv > 0.7) c = GLASS;
else if (lv < 0.12) c = L.trim;
else c = scale(L.body, 0.7);
} else {
if (lv > 0.65) c = mix(GLASS, L.trim, 0.15);
else if (lv < 0.12) c = L.trim;
else c = scale(L.body, 0.8);
}
if (v.alpha < 1) c = scale(c, v.alpha);
return haze(c, 1 - glowClarity(d));
}
function drawVehicle(r: Raster, s: Surface | undefined, cam: Cam, v: Placed, mirror: boolean): void {
traceBox(r, cam, v, (face, X, Y, Z, d) => shadeVehicle(v, face, X, Y, Z, d), mirror);
if (!s || mirror) return;
// Head and tail lights, which carry far further than the car itself, and their streaks on the wet road.
const cx = (v.x0 + v.x1) / 2;
const half = (v.x1 - v.x0) * 0.38;
const y = v.y0 + (v.y1 - v.y0) * 0.5;
const col = v.dir > 0 ? TAIL : HEAD;
if (v.dir === 0) return;
for (const side of [-1, 1]) {
const p = project(cam, cx + side * half, y, v.z0 - 0.05);
if (!p || p.x < 0 || p.x >= W || p.y < 0 || p.y >= H) continue;
if (DEPTH[(p.y | 0) * W + (p.x | 0)] < p.d - 0.3) continue;
const k = glowClarity(p.d) * v.alpha * (v.dir > 0 ? 0.8 : 1);
glowDot(s, p.x, p.y, Math.max(0.5, 0.18 * (F / p.d)), col, k);
if (v.y0 < 3) streak(s, p.x, p.y, (v.y0 + y) * 2 * (F / p.d), col, k * 0.45);
}
}
/** A light's reflection drawn down the wet road beneath it. */
function streak(s: Surface, x: number, y: number, gap: number, c: RGB, k: number): void {
const xx = x | 0;
if (xx < 0 || xx >= W) return;
const top = Math.ceil(y + gap * 0.6);
const len = Math.max(3, gap * 2.5);
for (let n = 0; n < len; n++) {
const yy = top + n;
if (yy >= H) break;
if (yy < 0 || MAT[yy * W + xx] !== M_ROAD) continue;
s.light(xx, yy, c, k * (1 - n / len));
}
}
// ---------------------------------------------------------------------------
// Ground traffic: hover-taxis and pods, simulated once so they queue at red lights
// ---------------------------------------------------------------------------
interface Trip {
/** Lane: +1/+2 inner/outer heading up the avenue, -1/-2 heading down. */
lane: number;
look: Look;
t0: number;
/** Position along the route (m of z) every SIM_REC seconds from t0. */
zs: Float32Array;
}
const SIM_DT = 0.1;
const SIM_REC = 0.25;
const SIM_FROM = -150;
const ROUTE_LOW = -140;
const ROUTE_HIGH = BACK_STREET.z0 + 18;
/** The next intersection ahead with a light, and the stop line before its crosswalk. */
function stopLine(dir: number, z: number): { z: number; k: number } | undefined {
for (let n = 0; n <= LAST_CROSS; n++) {
const k = dir > 0 ? n : LAST_CROSS - n;
const zl = k * BLOCK - dir * (CROSS_HALF + 4.6);
if ((zl - z) * dir > -0.5) return { z: zl, k };
}
return undefined;
}
const TRIPS: Trip[] = (() => {
const r = new Rng(1999);
const out: Trip[] = [];
for (const lane of [1, 2, -1, -2]) {
const dir = Math.sign(lane);
const live: { trip: Trip; z: number; v: number; v0: number; rec: number[]; done: boolean }[] = [];
let nextSpawn = SIM_FROM + r.range(0, 4);
for (let t = SIM_FROM; t <= DURATION + 1; t += SIM_DT) {
if (t >= nextSpawn) {
const z = dir > 0 ? ROUTE_LOW : ROUTE_HIGH;
const last = live.filter((c) => !c.done).at(-1);
if (!last || Math.abs(last.z - z) > 14) {
const look = LOOKS[r.int(0, LOOKS.length - 1)];
const trip: Trip = { lane, look, t0: t, zs: new Float32Array(0) };
live.push({ trip, z, v: 6, v0: r.range(5, 8.5) * (Math.abs(lane) === 2 ? 0.85 : 1), rec: [], done: false });
nextSpawn = t + r.range(4, 10);
} else nextSpawn = t + 1;
}
let leader: (typeof live)[number] | undefined;
for (const c of live) {
if (c.done) continue;
let want = c.v0;
const sl = stopLine(dir, c.z);
if (sl) {
const ph = signalPhase(sl.k, t);
const dist = (sl.z - c.z) * dir;
const stop = ph >= YELLOW || (ph >= GREEN && dist > (c.v * c.v) / 5 + 1);
if (stop && dist < 40) want = Math.min(want, Math.sqrt(Math.max(0, 2 * 2.2 * (dist - 0.5))));
}
if (leader) {
const gap = (leader.z - c.z) * dir - leader.trip.look.len;
want = Math.min(want, Math.max(0, (gap - 2.5) * 0.9));
}
c.v += Math.max(-4, Math.min(1.6, (want - c.v) * 1.5)) * SIM_DT;
c.v = Math.max(0, c.v);
c.z += c.v * dir * SIM_DT;
const step = Math.round((t - c.trip.t0) / SIM_DT);
if (step % Math.round(SIM_REC / SIM_DT) === 0) c.rec.push(c.z);
if ((dir > 0 && c.z > ROUTE_HIGH) || (dir < 0 && c.z < ROUTE_LOW)) {
c.done = true;
c.rec.push(c.z);
}
leader = c;
}
}
for (const c of live) {
c.trip.zs = Float32Array.from(c.rec);
out.push(c.trip);
}
}
return out;
})();
function tripZ(tr: Trip, t: number): number | undefined {
const u = (t - tr.t0) / SIM_REC;
if (u < 0 || u >= tr.zs.length - 1) return undefined;
const i = Math.floor(u);
return tr.zs[i] + (tr.zs[i + 1] - tr.zs[i]) * (u - i);
}
function placeGround(tr: Trip, z: number): Placed {
const dir = Math.sign(tr.lane);
const L = tr.look;
const x = roadwayX(dir, z) + dir * (Math.abs(tr.lane) === 1 ? -2.5 : 2.5);
const hover = 0.45;
const alpha = smoothstep(ROUTE_HIGH, ROUTE_HIGH - 25, z);
return { x0: x - L.w / 2, x1: x + L.w / 2, y0: hover, y1: hover + L.h, z0: z - L.len / 2, z1: z + L.len / 2, look: L, dir, alpha };
}
// ---------------------------------------------------------------------------
// Air traffic: lanes of hover cars over the avenue and across it
// ---------------------------------------------------------------------------
interface AirLane {
x: number;
y: number;
dir: number;
speed: number;
n: number;
seed: number;
}
const AIR_LANES: readonly AirLane[] = [
{ x: 4.5, y: 27, dir: 1, speed: 9, n: 9, seed: 1 },
{ x: -4.5, y: 30, dir: -1, speed: 10, n: 9, seed: 2 },
{ x: 7, y: 62, dir: 1, speed: 12, n: 8, seed: 3 },
{ x: -7, y: 66, dir: -1, speed: 13, n: 8, seed: 4 },
];
const AIR_LOW = -200;
const AIR_LEN = 1500;
const AIR_LOOKS: readonly Look[] = [
{ body: hex('#262a36'), roof: hex('#3a3e4c'), trim: CYAN, w: 2.4, len: 5, h: 1.3 },
{ body: hex('#30222e'), roof: hex('#4a3442'), trim: PINK, w: 2.4, len: 5.2, h: 1.3 },
{ body: hex('#c8ccd4'), roof: hex('#e4e6ec'), trim: VIOLET, w: 2.2, len: 4.6, h: 1.2 },
{ body: hex('#c89a2a'), roof: hex('#e0b440'), trim: hex('#ffcc44'), sign: hex('#fff0b0'), w: 2.3, len: 4.8, h: 1.3 },
];
/** Air lanes climb over the plaza and its tower. */
const climb = (z: number): number => 115 * smoothstep(PLAZA.z0 - 10, PLAZA.z1, z);
function airCar(x: number, y: number, z: number, look: Look, dir: number): Placed {
const yy = y + climb(z);
return { x0: x - look.w / 2, x1: x + look.w / 2, y0: yy, y1: yy + look.h, z0: z - look.len / 2, z1: z + look.len / 2, look, dir, alpha: 1 };
}
/** Cross traffic high over each intersection, gliding left and right. */
function crossCars(t: number, out: Placed[]): void {
for (let k = 0; k <= LAST_CROSS; k++) {
for (let n = 0; n < 3; n++) {
const dir = (k + n) % 2 ? 1 : -1;
const speed = 11 + hash(k, n, 120) * 4;
const loop = 900;
const x = ((((hash(k, n, 121) * loop + t * speed * dir) % loop) + loop) % loop) - loop / 2;
const look = AIR_LOOKS[(k + n) % AIR_LOOKS.length];
const y = 78 + n * 9;
const z = k * BLOCK + (n - 1) * 3;
out.push({ x0: x - look.len / 2, x1: x + look.len / 2, y0: y, y1: y + look.h, z0: z - look.w / 2, z1: z + look.w / 2, look, dir: 0, alpha: 1 });
}
}
}
function placeAir(f: Frame): Placed[] {
const out: Placed[] = [];
const cam = f.cam;
for (const ln of AIR_LANES) {
for (let i = 0; i < ln.n; i++) {
const off = (i + hash(i, ln.seed, 122) * 0.6) * (AIR_LEN / ln.n);
const z = AIR_LOW + ((((off + f.t * ln.speed * ln.dir) % AIR_LEN) + AIR_LEN) % AIR_LEN);
if (z < cam.z + 2 || z - cam.z > 900) continue;
const bob = 0.4 * Math.sin(f.t * 0.6 + i * 1.7);
out.push(airCar(ln.x + 0.6 * Math.sin(i * 2.3), ln.y + bob, z, AIR_LOOKS[(i + ln.seed) % AIR_LOOKS.length], ln.dir));
}
}
crossCars(f.t, out);
// One hover car rises from under the drone and glides on ahead up the avenue.
if (f.t > TIMES.flyby) {
const z = camZAt(TIMES.flyby) - 28 + 8.5 * (f.t - TIMES.flyby);
if (z > cam.z + 2 && z < 1200) out.push(airCar(2.2, 35 + 0.3 * Math.sin(f.t * 0.7), z, AIR_LOOKS[1], 1));
}
return out;
}
// ---------------------------------------------------------------------------
// The maglev: an elevated track over cross street 3, and its trains gliding past
// ---------------------------------------------------------------------------
const MAG_Z = 3 * BLOCK;
const DECK: Box3 = { x0: -900, x1: 900, y0: 21.5, y1: 23, z0: MAG_Z - 3.5, z1: MAG_Z + 3.5 };
const PILLARS: Box3[] = [-1, 1].map((s) => ({ x0: s * (LINE + 4) - 1.2, x1: s * (LINE + 4) + 1.2, y0: 0, y1: 21.5, z0: MAG_Z - 1.2, z1: MAG_Z + 1.2 }));
const CONCRETE = hex('#2a2834');
const RAIL = hex('#6a6878');
const TRAIN_BODY = hex('#c4c8d4');
const TRAIN_WIN = hex('#ffd8a0');
const TRAIN_CARS = 5;
const CAR_LEN = 18;
const TRAIN_SPEED = 15;
/** When each train passes over the avenue, and which way. */
const TRAINS = [
{ t: 38, dir: -1 },
{ t: 104, dir: 1 },
{ t: 168, dir: -1 },
] as const;
function shadeDeck(face: number, X: number, Y: number, _Z: number, d: number): RGB {
let c: RGB = CONCRETE;
if (face === FRONT) c = Y < DECK.y0 + 0.35 ? CYAN : Y > DECK.y1 - 0.3 ? scale(CONCRETE, 1.3) : CONCRETE;
else if (face === TOP) c = Math.abs(((_Z - DECK.z0) % 3.5) - 1.75) < 0.25 ? RAIL : scale(CONCRETE, 0.9);
else if (face === BOTTOM) c = Math.abs(X % 12) < 0.6 ? scale(CYAN, 0.8) : scale(CONCRETE, 0.6);
return haze(c, 1 - glowClarity(d) * 0.9);
}
function shadePillar(face: number, _X: number, Y: number, _Z: number, d: number): RGB {
const c = face === FRONT && Y > 2 && Y < 20 && Math.abs(Y % 6 - 3) < 0.2 ? PINK : CONCRETE;
return haze(c, 1 - glowClarity(d) * 0.9);
}
function trainCars(t: number): Box3[] {
const out: Box3[] = [];
for (const tr of TRAINS) {
const head = tr.dir * TRAIN_SPEED * (t - tr.t);
if (Math.abs(head) > 700) continue;
for (let n = 0; n < TRAIN_CARS; n++) {
const x0 = head - tr.dir * n * (CAR_LEN + 0.8);
const xa = tr.dir > 0 ? x0 - CAR_LEN : x0;
out.push({ x0: xa, x1: xa + CAR_LEN, y0: DECK.y1 + 0.3, y1: DECK.y1 + 3.7, z0: MAG_Z - 1.8, z1: MAG_Z + 1.8 });
}
}
return out;
}
function shadeTrain(face: number, X: number, Y: number, _Z: number, d: number): RGB {
const lv = (Y - DECK.y1 - 0.3) / 3.4;
let c: RGB = TRAIN_BODY;
if (face === TOP) c = scale(TRAIN_BODY, 0.75);
else if (face === FRONT) {
if (lv > 0.45 && lv < 0.8) c = Math.abs((X % 2.4) - 1.2) < 0.95 ? TRAIN_WIN : scale(TRAIN_BODY, 0.5);
else if (lv < 0.18) c = PINK;
} else c = scale(TRAIN_BODY, 0.8);
return haze(c, 1 - glowClarity(d));
}
function drawMaglev(r: Raster, cam: Cam, t: number, mirror: boolean): void {
if (MAG_Z < cam.z) return;
traceBox(r, cam, DECK, shadeDeck, mirror);
for (const p of PILLARS) traceBox(r, cam, p, shadePillar, mirror);
for (const c of trainCars(t)) traceBox(r, cam, c, shadeTrain, mirror);
}
// ---------------------------------------------------------------------------
function placeAll(f: Frame): Placed[] {
const out: Placed[] = [];
const cam = f.cam;
for (const tr of TRIPS) {
const z = tripZ(tr, f.t);
if (z === undefined || z < cam.z + 3 || z - cam.z > 700) continue;
out.push(placeGround(tr, z));
}
out.push(...placeAir(f));
return out;
}
/** Trace traffic upside down into the street's reflection, before it's composited. */
export function traceTrafficReflections(f: Frame): void {
const cam = f.cam;
drawMaglev(MIRROR, cam, f.t, true);
for (const v of placeAll(f)) if (v.z0 - cam.z < 250) drawVehicle(MIRROR, undefined, cam, v, true);
}
export function drawTraffic(s: Surface, f: Frame): void {
const cam = f.cam;
drawMaglev(SCREEN, cam, f.t, false);
for (const v of placeAll(f)) {
drawVehicle(SCREEN, s, cam, v, false);
// Hover cars low over the road cast their neon trim onto it.
if (v.y0 < 1 && v.z0 - cam.z < 220) underglow(s, cam, v);
}
}
function underglow(s: Surface, cam: Cam, v: Placed): void {
const cx = (v.x0 + v.x1) / 2;
const cz = (v.z0 + v.z1) / 2;
const p = project(cam, cx, 0, cz);
if (!p) return;
const k = F / p.d;
const rx = Math.ceil(2.2 * k);
const ry = Math.ceil(rx * (cam.y / p.d) * 1.6 + 1);
const a = 0.35 * glowClarity(p.d) * v.alpha;
for (let oy = -ry; oy <= ry; oy++) {
const yy = Math.floor(p.y + oy);
if (yy < 0 || yy >= H) continue;
for (let ox = -rx; ox <= rx; ox++) {
const xx = Math.floor(p.x + ox);
if (xx < 0 || xx >= W || MAT[yy * W + xx] !== M_ROAD) continue;
const e = 1 - Math.hypot(ox / rx, oy / ry);
if (e > 0) s.light(xx, yy, v.look.trim, a * e);
}
}
}

View File

@ -0,0 +1,149 @@
import { hash } from '../../engine/rng';
/**
* Fixed layout of the city, in meters: x to the right, y up, z forward up the avenue. The drone
* flies along x = 0, and the view is a shifted lens: the camera looks level but the horizon sits
* high in the frame, so we look down into the street while the towers stay upright.
*/
export const W = 320;
export const H = 180;
export const HORIZON = 52;
export const CX = W / 2;
/** Focal length in pixels: a point d meters ahead and h below the camera sits h·F/d rows under the horizon. */
export const F = 150;
/** Nearest depth a ray may hit, m. */
export const NEAR = 0.5;
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 < NEAR) return undefined;
const k = F / d;
return { x: CX + (X - c.x) * k, y: HORIZON - (Y - c.y) * k, d };
}
/** Haze falloff tables, one entry per meter: Math.exp per pixel adds up. */
const FAR = 4000;
const CLEAR = Float32Array.from({ length: FAR + 1 }, (_, i) => Math.exp(-i / 420));
const GLOW_CLEAR = Float32Array.from({ length: FAR + 1 }, (_, i) => Math.exp(-i / 950));
/** How much of a surface d meters away shows through the rain haze. */
export const clarity = (d: number): number => CLEAR[Math.min(FAR, d | 0)];
/** Neon carries much further through the haze than unlit walls. */
export const glowClarity = (d: number): number => GLOW_CLEAR[Math.min(FAR, d | 0)];
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);
};
// ---------------------------------------------------------------------------
// Per-pixel depth and material, shared by every layer of the frame
// ---------------------------------------------------------------------------
/** Depth of what each pixel shows, m ahead of the camera (Infinity for sky). */
export const DEPTH = new Float32Array(W * H);
/** What each pixel shows, so reflections and splashes land only on the wet street. */
export const MAT = new Uint8Array(W * H);
/** How wet and mirror-like each street pixel is, 0–1. */
export const WET = new Float32Array(W * H);
export const M_SKY = 0;
export const M_ROAD = 1;
export const M_WALK = 2;
export const M_SOLID = 3;
// ---------------------------------------------------------------------------
// Streets
// ---------------------------------------------------------------------------
export const BLOCK = 90;
/** Cross streets are centered every BLOCK meters, this wide each side of the center line. */
export const CROSS_HALF = 8;
export const FIRST_CROSS = -1;
export const LAST_CROSS = 4;
/** The avenue's roadway, and the building line behind its sidewalks. */
export const ROAD_HALF = 10;
export const LINE = 19;
/** The plaza at the top of the avenue, where the drone comes to rest just short of it. */
export const PLAZA = { z0: (LAST_CROSS + 1) * BLOCK - CROSS_HALF, z1: 560, half: 62 };
/** The screen tower standing in the middle of the far side of the plaza. */
export const TOWER = { x0: -26, x1: 26, z0: 568, z1: 608, h: 124 };
/** Behind the tower a last cross street runs left and right, in front of the buildings closing off the view. */
export const BACK_STREET = { z0: 620, z1: 650 };
/** The cross street a z lies in, if any. */
export function crossAt(z: number): number | undefined {
const k = Math.round(z / BLOCK);
if (k < FIRST_CROSS || k > LAST_CROSS) return undefined;
return Math.abs(z - k * BLOCK) < CROSS_HALF ? k : undefined;
}
/** In the plaza the avenue splits in two, each roadway swinging out to pass one side of the tower. */
export const splitAt = (z: number): number => 38 * smoothstep(PLAZA.z0 + 25, PLAZA.z1, z);
export const LANE_HALF = ROAD_HALF / 2;
/** Center line of one carriageway (side +1 outbound on the right, -1 inbound on the left). */
export const roadwayX = (side: number, z: number): number => side * (LANE_HALF + splitAt(z));
/** True when ground at (x, z) is roadway rather than pavement. */
export function isRoad(x: number, z: number): boolean {
if (z < PLAZA.z0) return Math.abs(x) < ROAD_HALF || crossAt(z) !== undefined;
if (z > BACK_STREET.z0) return z < BACK_STREET.z1;
return Math.abs(Math.abs(x) - LANE_HALF - splitAt(z)) < LANE_HALF;
}
// ---------------------------------------------------------------------------
// Signals: each intersection cycles avenue green → yellow → an all-way pedestrian scramble
// ---------------------------------------------------------------------------
export const CYCLE = 45;
export const GREEN = 23;
export const YELLOW = 26;
export const WALK_END = 43;
/** Seconds into the current signal cycle at intersection k. */
export const signalPhase = (k: number, t: number): number => (((t + 9 + k * 6) % CYCLE) + CYCLE) % CYCLE;
export const cycleIndex = (k: number, t: number): number => Math.floor((t + 9 + k * 6) / CYCLE);
// ---------------------------------------------------------------------------
// Street furniture
// ---------------------------------------------------------------------------
/** Street-food stalls sit in 12 m slots along the sidewalks, against the buildings. */
export const STALL_SLOT = 12;
export function stallAt(slot: number, side: number): boolean {
const zc = slot * STALL_SLOT + STALL_SLOT / 2;
if (zc > PLAZA.z0 - 6 || zc < -80) return false;
const k = Math.round(zc / BLOCK);
if (Math.abs(zc - k * BLOCK) < CROSS_HALF + 7) return false;
return hash(slot, side, 41) < 0.32;
}
/** Manhole steam vents along the road. */
export const VENT_SLOT = 23;
export function ventAt(slot: number): { x: number; z: number } | undefined {
if (hash(slot, 0, 43) > 0.45) return undefined;
const z = slot * VENT_SLOT + VENT_SLOT * hash(slot, 1, 43);
if (z > PLAZA.z0 || crossAt(z) !== undefined) return undefined;
return { x: (hash(slot, 2, 43) - 0.5) * 12, z };
}

View File

@ -1,4 +1,5 @@
import type { Meditation } from './types';
import { cyberpunkCity } from './cyberpunk-city';
import { desertSunrise } from './desert-sunrise';
import { mediterraneanCoast } from './mediterranean-coast';
import { morningFlight } from './morning-flight';
@ -8,7 +9,7 @@ import { theReef } from './the-reef';
import { tibetanMonastery } from './tibetan-monastery';
/** 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, morningFlight];
export const meditations: readonly Meditation[] = [northernCabin, mediterraneanCoast, theReef, ringedPlanet, desertSunrise, tibetanMonastery, morningFlight, cyberpunkCity];
export function findMeditation(id: string): Meditation | undefined {
return meditations.find((m) => m.id === id);

View File

@ -8,6 +8,20 @@ export interface Scene {
render(s: Surface, t: number): void;
}
/**
* An ambient loop. By default it 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. With `until` it
* fades to silence over `fadeOut` seconds ending at that moment, instead of at the end of the meditation.
*/
export interface Ambience {
src: string;
volume?: number;
from?: number;
fadeIn?: number;
until?: number;
fadeOut?: number;
}
export interface Meditation {
id: string;
title: string;
@ -20,11 +34,9 @@ export interface Meditation {
/** Optional music file, e.g. 'audio/northern-cabin.mp3' (placed in /public). */
music?: string;
/**
* 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`
* 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.
* Optional ambient sounds that loop seamlessly, kept in step with the scene clock. Give one, or a
* list to layer several (e.g. rain and city noise) that play together.
*/
ambience?: { src: string; volume?: number; from?: number; fadeIn?: number; until?: number; fadeOut?: number };
ambience?: Ambience | readonly Ambience[];
createScene(): Scene;
}

View File

@ -22,41 +22,41 @@ const ICONS = {
'<svg viewBox="0 0 10 10" fill="currentColor"><path d="M1 1h3v1H2v2H1zM6 1h3v3H8V2H6zM1 6h1v2h2v1H1zM8 6h1v3H6V8h2z"/></svg>',
};
/** Music plus an optional looping ambience, driven together from the meditation clock. */
/** Music plus any looping ambiences, driven together from the meditation clock. */
class Soundtrack {
private readonly music: Music;
private readonly ambience: AmbientLoop;
private readonly ambience: AmbientLoop[];
constructor(m: Meditation, enabled: boolean) {
this.music = new Music(enabled ? m.music : undefined, 0.75);
const a = m.ambience;
this.ambience = new AmbientLoop(enabled ? a?.src : undefined, a?.volume, a?.fadeIn, a?.fadeOut, a?.from, a?.until);
const list = enabled && m.ambience ? [m.ambience].flat() : [];
this.ambience = list.map((a) => new AmbientLoop(a.src, a.volume, a.fadeIn, a.fadeOut, a.from, a.until));
}
play(t: number): void {
this.music.seek(t);
this.music.play();
this.ambience.start(t);
for (const a of this.ambience) a.start(t);
}
pause(): void {
this.music.pause();
this.ambience.pause();
for (const a of this.ambience) a.pause();
}
seek(t: number): void {
this.music.seek(t);
this.ambience.seek(t);
for (const a of this.ambience) a.seek(t);
}
update(t: number, duration: number): void {
this.music.update(t, duration);
this.ambience.update(t, duration);
for (const a of this.ambience) a.update(t, duration);
}
destroy(): void {
this.music.destroy();
this.ambience.destroy();
for (const a of this.ambience) a.destroy();
}
}