ridge runtime: a lighter per sky, tiles lit by ring column; a backdrop holds tiles by arc

lightCards becomes createLighter: the sun columns and the sky table span the ring
in absolute azimuth, the ground noise is a function of the ground point and so
periodic over the wrap, and a tile is lit from its own files with one overlap
column kept each side. loadBackdrop (every card, at build) becomes createBackdrop:
ensure(arc) fetches, decodes and lights one tile at a time and evicts beyond the
arc and two tiles; a failed tile is retried, never thrown into the scene.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-22 23:31:55 +01:00
commit 0f7a297339
5 changed files with 532 additions and 203 deletions

View file

@ -1,90 +1,235 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { loadBackdrop } from './Backdrop';
import type { LitCard } from './lightCards';
import { createBackdrop, KEEP_MARGIN_TILES, LOAD_MARGIN_TILES } from './Backdrop';
import type { Lighter } from './lightCards';
import { parseManifest } from './manifest';
import { wireManifest } from './manifest.fixture';
import type { PhysicalSky } from './physicalSky';
import { residentTiles, runTiles } from './ring';
import { HFOV_MAX_DEG } from './view';
const sky = {} as PhysicalSky;
const manifest = parseManifest(wireManifest(), '/d/');
const manifest = parseManifest(wireManifest({}, 3, 32), '/d/'); // the ring as the baker cuts it: 32 tiles of 11.25 degrees, 3 cards
const tileOf = (url: string) => Number(/-t(\d\d)-/.exec(url)?.[1]);
const stubDecoder = () => {
const made: { url: string; opts: unknown; closed: boolean }[] = [];
vi.stubGlobal(
'createImageBitmap',
vi.fn(async (blob: Blob & { url: string }, opts: unknown) => {
if (blob.url.endsWith('card-2-geometry.webp') && fail.on) throw new Error('bad card');
const bmp = { url: blob.url, opts, closed: false, close: () => (bmp.closed = true) };
made.push(bmp);
return bmp;
})
);
return made;
/** A decoder that keeps count: which bitmaps are open, which tiles are being decoded at once. */
const rig = (fail: (url: string) => boolean = () => false) => {
const fetched: string[] = [];
const bitmaps: { url: string; closed: boolean; close: () => void }[] = [];
let inFlight = new Map<number, number>();
let mostTiles = 0;
const fetchBlob = vi.fn(async (url: string) => {
fetched.push(url);
if (fail(url)) throw new Error('ridge: 404');
return { url } as unknown as Blob;
});
const decode = vi.fn(async (blob: Blob & { url: string }) => {
const t = tileOf(blob.url);
inFlight.set(t, (inFlight.get(t) ?? 0) + 1);
mostTiles = Math.max(mostTiles, inFlight.size);
await new Promise((r) => setTimeout(r, 0));
inFlight.set(t, (inFlight.get(t) ?? 1) - 1);
if (inFlight.get(t) === 0) inFlight.delete(t);
const b = { url: blob.url, closed: false, close: () => (b.closed = true) };
bitmaps.push(b);
return b as unknown as ImageBitmap;
});
const canvases: { tile: number; card: number; width: number; height: number }[] = [];
const lighter = (): Lighter & { light: ReturnType<typeof vi.fn> } => ({
lost: false,
release: vi.fn(),
light: vi.fn((_b: unknown, tile: number, card: number) => {
const c = { tile, card, width: 202, height: 100 };
canvases.push(c);
return c as unknown as HTMLCanvasElement;
}),
});
return { fetched, bitmaps, fetchBlob, decode, canvases, lighter, mostTiles: () => mostTiles };
};
const fail = { on: false };
const blobFor = async (url: string) => ({ url } as unknown as Blob);
const lit = (m: typeof manifest): LitCard[] =>
m.cards.map((c) => ({ canvas: {} as HTMLCanvasElement, top: c.top, h: c.h, scale: c.scale }));
afterEach(() => {
fail.on = false;
vi.unstubAllGlobals();
});
const urlsOfTiles = (tiles: number[]) =>
tiles.flatMap((t) =>
manifest.tiles[t].flatMap((e) => (e ? [`/d/${e.colour}`, `/d/${e.geometry}`] : []))
);
const arc72 = (centre: number) => ({ fromDeg: centre - 36, toDeg: centre + 36 });
describe('loadBackdrop', () => {
it('fetches and decodes both files of every card straight, lights once, and returns the cards nearest first', async () => {
const made = stubDecoder();
const light = vi.fn((m: typeof manifest) => lit(m));
const bd = await loadBackdrop(manifest, sky, { fetchBlob: blobFor, light });
expect(bd?.cards.map((c) => c.scale)).toEqual([1.2, 1.0167, 1.005]);
expect(bd?.manifest).toBe(manifest);
expect(made.map((b) => b.url).sort()).toEqual(
[0, 1, 2].flatMap((i) => [`/d/card-${i}-colour.webp`, `/d/card-${i}-geometry.webp`]).sort()
afterEach(() => vi.useRealTimers());
describe('createBackdrop', () => {
it('fetches nothing until it is asked, and then the files of the tiles of the arc and one tile beyond it, straight, and no others', async () => {
const r = rig();
const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter });
expect(r.fetchBlob).not.toHaveBeenCalled();
await bd.ensure(arc72(180));
const want = residentTiles(manifest.view, 180, 36 + LOAD_MARGIN_TILES * 11.25).map((t) => t.tile);
expect(want).toHaveLength(10);
expect([...r.fetched].sort()).toEqual(urlsOfTiles(want).sort());
expect(bd.litTiles().map((t) => t.tile).sort((a, b) => a - b)).toEqual(
want.flatMap((t) => manifest.tiles[t].flatMap((e, card) => (e ? [t] : []))).sort((a, b) => a - b)
);
made.forEach((b) =>
expect(b.opts).toEqual({ premultiplyAlpha: 'none', colorSpaceConversion: 'none' })
);
expect(light).toHaveBeenCalledOnce();
// Handed over in manifest order, each card its own pair.
const given = light.mock.calls[0] as unknown as [
unknown,
{ colour: { url: string }; geometry: { url: string } }[],
unknown
];
expect(given[1].map((p) => [p.colour.url, p.geometry.url])).toEqual(
[0, 1, 2].map((i) => [`/d/card-${i}-colour.webp`, `/d/card-${i}-geometry.webp`])
);
expect(given[2]).toBe(sky);
r.bitmaps.forEach((b) => expect(b.closed).toBe(true));
});
it('closes the decoded bitmaps once they are lit', async () => {
const made = stubDecoder();
await loadBackdrop(manifest, sky, { fetchBlob: blobFor, light: lit });
expect(made).toHaveLength(6);
expect(made.every((b) => b.closed)).toBe(true);
it('lights each card of a tile that holds it, naming the tile and the card, and leaves a card the tile lacks out', async () => {
const r = rig();
const lighter = r.lighter();
const bd = createBackdrop(manifest, sky, { ...r, lighter: () => lighter });
await bd.ensure({ fromDeg: 208, toDeg: 209 });
const calls = lighter.light.mock.calls.map((c) => [c[1], c[2]]);
// Tile 17 holds three cards; tile 18 (18 % 4 = 2) holds only two: card 2 is absent there.
expect(calls).toContainEqual([17, 2]);
expect(calls).toContainEqual([18, 1]);
expect(calls).not.toContainEqual([18, 2]);
const colourOf = (c: unknown[]) => (c[0] as { colour: { url: string } }).colour.url;
expect(lighter.light.mock.calls.every((c) => colourOf(c).includes(`-t${String(c[1]).padStart(2, '0')}-`))).toBe(true);
});
it('is null when any one card will not decode, lights nothing and closes what it decoded', async () => {
const made = stubDecoder();
fail.on = true;
const light = vi.fn(lit);
expect(await loadBackdrop(manifest, sky, { fetchBlob: blobFor, light })).toBeNull();
expect(light).not.toHaveBeenCalled();
it('decodes with straight alpha and no colour management by default', async () => {
const made: unknown[] = [];
vi.stubGlobal(
'createImageBitmap',
vi.fn(async (_b: unknown, opts: unknown) => {
made.push(opts);
return { close: () => undefined };
})
);
const r = rig();
const bd = createBackdrop(manifest, sky, { fetchBlob: r.fetchBlob, lighter: r.lighter });
await bd.ensure({ fromDeg: 0, toDeg: 1 });
expect(made.length).toBeGreaterThan(0);
expect(made.every((b) => b.closed)).toBe(true);
made.forEach((o) => expect(o).toEqual({ premultiplyAlpha: 'none', colorSpaceConversion: 'none' }));
vi.unstubAllGlobals();
});
it('is null when a file is missing, and when the lighting pass throws', async () => {
const made = stubDecoder();
const gone = async (url: string) => {
if (url.endsWith('card-1-colour.webp')) throw new Error('ridge: 404');
return blobFor(url);
};
expect(await loadBackdrop(manifest, sky, { fetchBlob: gone, light: lit })).toBeNull();
const boom = () => {
throw new Error('no WebGL2');
};
expect(await loadBackdrop(manifest, sky, { fetchBlob: blobFor, light: boom })).toBeNull();
expect(made.every((b) => b.closed)).toBe(true);
it('decodes one tile at a time', async () => {
const r = rig();
const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter });
await bd.ensure(arc72(100));
expect(r.decode).toHaveBeenCalled();
expect(r.mostTiles()).toBe(1);
});
it('sweeping the heading through 360 degrees fetches each tile once on the way and never holds more than the baker counted', async () => {
const r = rig();
const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter });
const N = runTiles(manifest.view, HFOV_MAX_DEG, manifest.camera.rMaxM, 1000);
const per = new Map<number, number>();
let most = 0;
for (let h = 0; h <= 360; h += 6) {
await bd.ensure(arc72(h));
most = Math.max(most, new Set(bd.litTiles().map((t) => t.tile)).size);
}
// Card 0 is in every tile: its colour file counts a tile's fetches.
for (const u of r.fetched) {
if (u.includes('card-0-') && u.endsWith('colour.webp')) per.set(tileOf(u), (per.get(tileOf(u)) ?? 0) + 1);
}
expect(per.size).toBe(32);
// The tiles round north are held at the start and wanted again at the end of the turn: those two fetches aside, every tile came once.
const start = new Set(residentTiles(manifest.view, 0, 36 + LOAD_MARGIN_TILES * 11.25).map((t) => t.tile));
for (const [t, n] of per) expect(n, `tile ${t}`).toBe(start.has(t) ? 2 : 1);
expect(most).toBeLessThanOrEqual(N);
expect(most).toBeLessThanOrEqual(
Math.ceil((72 + 2 * KEEP_MARGIN_TILES * 11.25) / 11.25) + 1
);
});
it('lets go of the tiles beyond the arc and two tiles of margin, and makes nothing twice that it still holds', async () => {
const r = rig();
const lighter = r.lighter();
const bd = createBackdrop(manifest, sky, { ...r, lighter: () => lighter });
await bd.ensure(arc72(180));
const first = bd.litTiles();
const lit = lighter.light.mock.calls.length;
await bd.ensure(arc72(180)); // the same arc again: nothing is made
expect(lighter.light.mock.calls.length).toBe(lit);
await bd.ensure(arc72(0)); // the far side of the ring: everything held before is let go
first.forEach((t) => expect(t.canvas.width).toBe(0));
const keep = new Set(
residentTiles(manifest.view, 0, 36 + KEEP_MARGIN_TILES * 11.25).map((t) => t.tile)
);
expect(bd.litTiles().length).toBeGreaterThan(0);
bd.litTiles().forEach((t) => {
expect(keep.has(t.tile)).toBe(true);
expect(t.canvas.width).toBe(202);
});
});
it('a tile that fails is absent, not an error, and is made at the next ensure', async () => {
let broken = true;
const r = rig((u) => broken && tileOf(u) === 16 && u.includes('card-1-'));
const lighter = r.lighter();
const bd = createBackdrop(manifest, sky, { ...r, lighter: () => lighter });
await expect(bd.ensure({ fromDeg: 180, toDeg: 181 })).resolves.toBeUndefined();
expect(bd.litTiles().some((t) => t.tile === 16)).toBe(false); // a tile is lit whole or not at all
expect(bd.litTiles().some((t) => t.tile === 15)).toBe(true);
r.bitmaps.forEach((b) => expect(b.closed).toBe(true));
broken = false;
await bd.ensure({ fromDeg: 180, toDeg: 181 });
expect(bd.litTiles().filter((t) => t.tile === 16).map((t) => t.card).sort()).toEqual([0, 1, 2]);
});
it('a lighting pass that throws is a failed tile too', async () => {
const r = rig();
const lighter = r.lighter();
lighter.light.mockImplementation(() => {
throw new Error('no 2D context');
});
const bd = createBackdrop(manifest, sky, { ...r, lighter: () => lighter });
await expect(bd.ensure({ fromDeg: 0, toDeg: 1 })).resolves.toBeUndefined();
expect(bd.litTiles()).toEqual([]);
r.bitmaps.forEach((b) => expect(b.closed).toBe(true));
});
it('is made only where the cards can be lit: a lighter that throws is the caller to answer for', () => {
const r = rig();
expect(() =>
createBackdrop(manifest, sky, {
...r,
lighter: () => {
throw new Error('ridge: no WebGL2');
},
})
).toThrow(/WebGL2/);
});
it('makes another lighter after the context is lost, and releases the spent one', async () => {
const r = rig();
const first = r.lighter();
const second = r.lighter();
const make = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second);
const bd = createBackdrop(manifest, sky, { ...r, lighter: make });
await bd.ensure({ fromDeg: 0, toDeg: 1 });
expect(first.light).toHaveBeenCalled();
(first as { lost: boolean }).lost = true;
await bd.ensure({ fromDeg: 180, toDeg: 181 });
expect(make).toHaveBeenCalledTimes(2);
expect(first.release).toHaveBeenCalled();
expect(second.light).toHaveBeenCalled();
});
it('takes the newest arc when asked again mid-pass, and answers every caller once everything it could make is made', async () => {
const r = rig();
const bd = createBackdrop(manifest, sky, { ...r, lighter: r.lighter });
const a = bd.ensure(arc72(40));
const b = bd.ensure(arc72(220));
await Promise.all([a, b]);
const held = new Set(bd.litTiles().map((t) => t.tile));
residentTiles(manifest.view, 220, 36 + LOAD_MARGIN_TILES * 11.25).forEach((t) => expect(held.has(t.tile)).toBe(true));
});
it('disposes: the canvases are dropped, the lighting context released, and a later ensure does nothing', async () => {
const r = rig();
const lighter = r.lighter();
const bd = createBackdrop(manifest, sky, { ...r, lighter: () => lighter });
await bd.ensure({ fromDeg: 0, toDeg: 1 });
const lit = bd.litTiles().map((t) => t.canvas);
expect(lit.length).toBeGreaterThan(0);
bd.dispose();
bd.dispose();
expect(lighter.release).toHaveBeenCalledTimes(1);
lit.forEach((c) => expect(c.width).toBe(0));
expect(bd.litTiles()).toEqual([]);
const n = r.fetched.length;
await bd.ensure({ fromDeg: 100, toDeg: 101 });
expect(r.fetched).toHaveLength(n);
});
});

View file

@ -1,55 +1,160 @@
// The ridge cards the scene composes, lit: every card's two files fetched and decoded exactly as the baker wrote them, then lit once for the sky
// (`lightCards.ts`). Failure is a value (null), never a throw.
// The ridge cards the scene composes, lit, kept resident by tile: the one owner of which tiles of the ring are in memory. `ensure` is told the arc of
// azimuth the view is about to need; it fetches and decodes the tiles of that arc it does not hold, one tile at a time, lights each card of a tile
// (`lightCards.ts`, one lighter for the one sky this backdrop was made for) and drops the tiles beyond the arc and its margin. A tile that fails is a
// tile the scene draws as absence, retried at the next `ensure`; it is never thrown into the scene.
import type { RidgeManifest } from './manifest';
import type { PhysicalSky } from './physicalSky';
import { lightCards } from './lightCards';
import type { CardBitmaps, LitCard } from './lightCards';
import { createLighter } from './lightCards';
import type { CardBitmaps, Lighter } from './lightCards';
import { residentTiles } from './ring';
/** A range of unwrapped compass azimuth, degrees, `fromDeg <= toDeg`. */
export interface Arc {
fromDeg: number;
toDeg: number;
}
/** One card of one tile, lit: its pixels premultiplied by the card's alpha, `tileW + 2` columns by the band's rows. */
export interface LitTile {
tile: number;
card: number;
canvas: HTMLCanvasElement;
}
export interface Backdrop {
manifest: RidgeManifest;
/** Nearest first, as the manifest lists them. */
cards: LitCard[];
/** Hold the tiles of `arc` and one tile beyond it each side; let go of those past two tiles. Resolves when every tile it could make is made. */
ensure(arc: Arc): Promise<void>;
/** Every card of every tile held, in no order. */
litTiles(): readonly LitTile[];
/** Let go of everything, the lighting context included. Idempotent. */
dispose(): void;
}
export interface BackdropDeps {
fetchBlob: (url: string) => Promise<Blob>;
light: (manifest: RidgeManifest, bitmaps: CardBitmaps[], sky: PhysicalSky) => LitCard[];
decode: (blob: Blob) => Promise<ImageBitmap>;
lighter: (manifest: RidgeManifest, sky: PhysicalSky) => Lighter;
}
/** Tiles fetched beyond the arc each side, and tiles kept beyond it each side (the baker's resident gate counts the keep: `export.py` `run_tiles`). */
export const LOAD_MARGIN_TILES = 1;
export const KEEP_MARGIN_TILES = 2;
const fetchBlob = async (url: string): Promise<Blob> => {
const res = await fetch(url);
if (!res.ok) throw new Error(`ridge: ${url} answered ${res.status}`);
return res.blob();
};
/** Straight alpha and the file's own values: the colour card's alpha is coverage and the geometry card's channels are data, so neither may be premultiplied or colour-managed. */
/** Straight alpha and the file's own values: the colour file's alpha is coverage and the geometry file's channels are data, so neither may be premultiplied or colour-managed. */
const decode = (blob: Blob): Promise<ImageBitmap> =>
createImageBitmap(blob, { premultiplyAlpha: 'none', colorSpaceConversion: 'none' });
export async function loadBackdrop(
/**
* A backdrop for `sky`. Throws at once when the cards cannot be lit (no WebGL2, a shader that will not link): the caller makes the sky-only scene.
* Nothing is fetched until the first `ensure`.
*/
export function createBackdrop(
manifest: RidgeManifest,
sky: PhysicalSky,
deps: Partial<BackdropDeps> = {}
): Promise<Backdrop | null> {
): Backdrop {
const get = deps.fetchBlob ?? fetchBlob;
const light = deps.light ?? lightCards;
const open: ImageBitmap[] = [];
try {
const files = manifest.cards.flatMap((c) => [c.colour, c.geometry]);
const settled = await Promise.allSettled(
files.map(async (f) => decode(await get(`${manifest.dir}${f}`)))
);
settled.forEach((s) => s.status === 'fulfilled' && open.push(s.value));
const failed = settled.find((s) => s.status === 'rejected');
if (failed) throw (failed as PromiseRejectedResult).reason;
const bitmaps = manifest.cards.map((_, i) => ({
colour: open[2 * i],
geometry: open[2 * i + 1],
}));
return { manifest, cards: light(manifest, bitmaps, sky) };
} catch {
return null;
} finally {
open.forEach((b) => b.close?.());
const open = deps.decode ?? decode;
const makeLighter = deps.lighter ?? createLighter;
const { view } = manifest;
const tileDeg = 360 / view.tiles;
let lighter = makeLighter(manifest, sky);
const held = new Map<number, LitTile[]>();
let disposed = false;
let running: Promise<void> | null = null;
let want: Arc | null = null;
const drop = (tile: number) => {
held.get(tile)?.forEach((t) => {
t.canvas.width = 0;
t.canvas.height = 0;
});
held.delete(tile);
};
/** Fetch, decode and light every card of a tile; a tile that is only partly made is not kept. */
async function make(tile: number): Promise<void> {
const cards = manifest.tiles[tile].flatMap((e, card) => (e ? [{ e, card }] : []));
const made: LitTile[] = [];
const bitmaps: ImageBitmap[] = [];
try {
if (lighter.lost) {
lighter.release();
lighter = makeLighter(manifest, sky);
}
const pairs: CardBitmaps[] = [];
for (const { e } of cards) {
const [colour, geometry] = await Promise.all(
[e.colour, e.geometry].map(async (f) => {
const b = await open(await get(`${manifest.dir}${f}`));
bitmaps.push(b);
return b;
})
);
pairs.push({ colour, geometry });
}
if (disposed) return;
cards.forEach(({ card }, i) => made.push({ tile, card, canvas: lighter.light(pairs[i], tile, card) }));
held.set(tile, made);
} catch {
made.forEach((t) => (t.canvas.width = 0));
} finally {
bitmaps.forEach((b) => b.close?.());
}
}
async function pass(arc: Arc): Promise<void> {
const centre = (arc.fromDeg + arc.toDeg) / 2;
const half = (arc.toDeg - arc.fromDeg) / 2;
const near = residentTiles(view, centre, half + LOAD_MARGIN_TILES * tileDeg);
const keep = new Set(
residentTiles(view, centre, half + KEEP_MARGIN_TILES * tileDeg).map((r) => r.tile)
);
[...held.keys()].filter((t) => !keep.has(t)).forEach(drop);
// The tile under the middle of the arc first: what the view needs now comes before what it needs next.
const from = (r: { tile: number; turn: number }) => r.turn * 360 + r.tile * tileDeg + tileDeg / 2;
const order = [...near].sort((a, b) => Math.abs(from(a) - centre) - Math.abs(from(b) - centre));
for (const { tile } of order) {
if (disposed) return;
if (held.has(tile)) continue;
await make(tile);
// A newer arc is waiting: take it up now, with this tile made, instead of finishing an arc the view has left.
if (want && held.has(tile)) return;
}
}
async function loop(): Promise<void> {
while (want && !disposed) {
const arc = want;
want = null;
await pass(arc);
}
}
return {
manifest,
ensure(arc) {
if (disposed) return Promise.resolve();
want = arc;
running ??= loop().finally(() => {
running = null;
});
return running;
},
litTiles: () => [...held.values()].flat(),
dispose() {
if (disposed) return;
disposed = true;
want = null;
[...held.keys()].forEach(drop);
lighter.release();
},
};
}

View file

@ -6,8 +6,9 @@ import {
celShade,
celLevels,
FRAGMENT,
lightCards,
createLighter,
lightingOf,
ringAzimuth,
skyLut,
SKY_LUT,
sunColumns,
@ -49,15 +50,20 @@ describe("the sun in a column's frame", () => {
expect(sunInColumn({ azimuth: 10, elevation: 0 }, 100)[1]).toBeCloseTo(-1, 12);
});
it('is computed for every column of the window, from its own azimuth', () => {
it('is computed for every column of the ring, from its own absolute azimuth', () => {
const view = manifest.view;
const cols = sunColumns(view, { azimuth: 214, elevation: 20 });
expect(cols).toHaveLength(view.planeW * 4);
expect(cols).toHaveLength(view.ringW * 4);
const at = (x: number) => Array.from(cols.slice(x * 4, x * 4 + 3));
const mid = at(view.planeW / 2);
expect(mid[0]).toBeCloseTo(Math.cos(20 * RAD), 3); // the middle column looks near the sun's azimuth
expect(at(0)[1]).toBeGreaterThan(0.1); // the left edge has the sun to its right
expect(at(view.planeW - 1)[1]).toBeLessThan(-0.1);
const sunCol = Math.floor((214 / 360) * view.ringW);
expect(ringAzimuth(sunCol, view.ringW)).toBeCloseTo(214, 1);
expect(at(sunCol)[0]).toBeCloseTo(Math.cos(20 * RAD), 3); // the column that looks at the sun's azimuth
expect(at(sunCol - 1000)[1]).toBeGreaterThan(0.1); // the sun is to the right of columns before it, and to the left of those after
expect(at(sunCol + 1000)[1]).toBeLessThan(-0.1);
// Every column is a unit vector, the first column of the ring looks north and the last looks just west of it.
for (let x = 0; x < view.ringW; x += 400) expect(Math.hypot(...at(x))).toBeCloseTo(1, 5);
expect(ringAzimuth(0, view.ringW)).toBeCloseTo(0.028125, 6);
expect(ringAzimuth(view.ringW - 1, view.ringW)).toBeCloseTo(360 - 0.028125, 6);
});
});
@ -146,10 +152,34 @@ describe('the lighting inputs', () => {
7 // the airglow floor adds a few 1e-9
);
expect(texel(0, SKY_LUT.h - 1)[0]).toBeCloseTo(0, 7);
// The sun lies at 214 degrees, the middle of the window: the cosine from the sun is 1 there and falls to the sides.
const mid = texel(SKY_LUT.w / 2, above)[1];
// The sun lies at 214 degrees: the cosine from the sun is 1 at its column and falls round the ring. The table spans the ring, so 320 columns.
expect(SKY_LUT.w).toBe(320);
const sunI = Math.floor((214 / 360) * SKY_LUT.w);
const mid = texel(sunI, above)[1];
expect(mid).toBeGreaterThan(0.999);
expect(texel(0, above)[1]).toBeLessThan(mid);
expect(texel(sunI + 160, above)[1]).toBeLessThan(-0.9);
});
});
describe('the ring in the shader', () => {
it('reads the sun and the sky by the column of the ring, not of the file, and wraps at the ends', () => {
expect(FRAGMENT).toContain('int col = ((uCol0 + p.x) % uRingW + uRingW) % uRingW;');
expect(FRAGMENT).toContain('texelFetch(uSun, ivec2(col, 0), 0)');
expect(FRAGMENT).toContain('(float(col) + 0.5) / float(uRingW)');
expect(FRAGMENT).toContain('(int(b.x) % w + w) % w'); // the sky table wraps in azimuth
});
it('gives the ground noise the ground point, so it is the same at ring column 0 and column 6400', () => {
// The noise coordinate is dist x (sin psi, cos psi) with psi from the wrapped column: sin and cos of 0 and of a whole turn are one point.
expect(FRAGMENT).toContain('vec2 world = vec2(sin(psi), cos(psi)) * dist;');
expect(FRAGMENT).toContain('float psi = (float(col) + 0.5) / float(uRingW) * 2.0 * PI;');
expect(FRAGMENT).not.toContain("uRadPerPx");
const at = (col: number, w: number) => {
const psi = ((((col % w) + w) % w) + 0.5) / w * 2 * Math.PI;
return [Math.sin(psi), Math.cos(psi)];
};
expect(at(6400, 6400)[0]).toBeCloseTo(at(0, 6400)[0], 12);
expect(at(6400, 6400)[1]).toBeCloseTo(at(0, 6400)[1], 12);
});
});
@ -169,12 +199,13 @@ describe('the display of the shader', () => {
describe('the look reaches the shader', () => {
// A recording WebGL2: every uniform call is kept by the name of its location, nothing is drawn.
const run = (look?: Partial<RidgeLook>) => {
const run = (look?: Partial<RidgeLook>, tile = 0) => {
const uniforms: Record<string, number[]> = {};
const crops: number[][] = [];
const gl = new Proxy(
{
getUniformLocation: (_p: unknown, name: string) => name,
uniform1i: () => undefined,
drawImage: (...a: unknown[]) => crops.push(a.slice(1) as number[]),
getShaderParameter: () => true,
getProgramParameter: () => true,
getExtension: () => null,
@ -192,7 +223,7 @@ describe('the look reaches the shader', () => {
);
const el = { width: 0, height: 0, getContext: () => gl };
vi.stubGlobal('document', { createElement: () => el });
const bmp = { width: 1, height: 1, close: () => undefined } as unknown as ImageBitmap;
const bmp = { width: 1604, height: 7, close: () => undefined } as unknown as ImageBitmap;
const sky = {
sun: { azimuth: 214, elevation: 30 },
atm: {
@ -206,14 +237,34 @@ describe('the look reaches the shader', () => {
view: manifest.view,
} as unknown as PhysicalSky;
const one = { ...manifest, cards: manifest.cards.slice(0, 1) };
let canvas: { width: number; height: number } | undefined;
try {
lightCards(one, [{ colour: bmp, geometry: bmp }], sky, look && { ...DEFAULT_LOOK, ...look });
const lighter = createLighter(one, sky, look && { ...DEFAULT_LOOK, ...look });
canvas = lighter.light({ colour: bmp, geometry: bmp }, tile, 0) as unknown as typeof canvas;
} finally {
vi.unstubAllGlobals();
}
return uniforms;
return Object.assign(uniforms, { crops, canvas });
};
it('lights a tile from its own columns: the ring column of the file, the band, and the interior with one overlap column each side', () => {
const u = run(undefined, 3);
const { view } = manifest;
expect(u.uCol0).toEqual([3 * view.tileW - view.apron]); // tile 3 of 4: the file starts two columns before its first
expect(u.uRingW).toEqual([view.ringW]);
expect(u.uTop).toEqual([manifest.tiles[3][0]!.top]);
expect(u.uSkySize).toEqual([320, 64]);
// The file holds tileW + 2 apron columns; the canvas keeps columns apron - 1 .. apron + tileW: the interior and one column each side.
expect(u.crops).toEqual([[view.apron - 1, 0, view.tileW + 2, 7, 0, 0, view.tileW + 2, 7]]);
expect(u.canvas).toMatchObject({ width: view.tileW + 2, height: 7 });
});
it('throws without WebGL2: the caller makes the sky alone', () => {
vi.stubGlobal('document', { createElement: () => ({ getContext: () => null }) });
expect(() => createLighter(manifest, {} as PhysicalSky)).toThrow(/WebGL2/);
vi.unstubAllGlobals();
});
it('defaults to DEFAULT_LOOK', () => {
const u = run();
expect(u.uInkKeep).toEqual([0.45, 0.55, 0.8]);

View file

@ -1,7 +1,9 @@
// The one lighting pass of the ridge cards (ruling ridge-cards-runtime-lit): each baked G-buffer card (colour with straight alpha, geometry with the
// The one lighting pass of the ridge cards (ruling ridge-cards-runtime-lit): each baked G-buffer card tile (colour with straight alpha, geometry with the
// 'rt8' normal and log-distance, `scripts/ridge-bake/export.py`) is lit once, for the sky this scene build was made for, in one WebGL2 context on a
// canvas of its own, and copied into a 2D canvas of the card's size. After the last card the context is released: there is no per-frame WebGL, and the
// host canvas stays 2D (`Ridge.ts`). A sky change rebuilds the scene and lights again; nothing patches the lit canvases.
// canvas of its own (a lighter, one per sky), and copied into a 2D canvas of the tile's interior plus one overlap column each side. The sun and the sky's
// haze are tables over the whole ring in absolute azimuth, so a tile is lit from its own files alone and the apron (the neighbours' real columns, read for
// the ink pass and dropped) makes its edges equal what a lit neighbour would give. There is no per-frame WebGL, and the host canvas stays 2D
// (`Ridge.ts`). A sky change rebuilds the scene and makes a new lighter; nothing patches the lit canvases.
//
// Per pixel: the normal from the geometry card in the column's frame (r along the ray, t across it, up), the sun brought into that frame per column;
// radiance = albedo x (sun transmittance x max(n.s, 0) + ambient irradiance) / pi; aerial perspective L T(d) + Lsky (1 - T(d)) with d from the
@ -17,23 +19,11 @@ import { ACES_FIT, ACES_IN, ACES_OUT, KNOTS, SCOTOPIC } from './toneMap';
import type { Curve } from './toneMap';
import type { View } from './view';
export interface CardBitmaps {
colour: ImageBitmap;
geometry: ImageBitmap;
}
/** A lit card: its pixels, premultiplied by the card's alpha, at the card's own size, and where the card sits in the plane. */
export interface LitCard {
canvas: HTMLCanvasElement;
top: number;
h: number;
scale: number;
}
/** A real normal has r2 + t2 at most 0.998 (probe on the Vienna bake); the wall code is 2. A code of the data, not of the look. */
export const WALL_RT2 = 1.02;
/** The lookup of the sky's radiance for the haze: azimuth columns by plane rows, filtered in the shader. */
export const SKY_LUT = { w: 64, h: 64 } as const;
/** The lookup of the sky's radiance for the haze: azimuth columns over the whole ring (the angular density of 64 over a 72 degree window) by plane rows, filtered in the shader. */
export const SKY_LUT = { w: 320, h: 64 } as const;
/**
* The look: every number of the art pass (ratatoskr:follow_up:ridge-art-quality-rework), the one owner of them. None is a rule of the machine.
@ -165,9 +155,8 @@ export function sunInColumn(
return [Math.cos(el) * Math.cos(d), Math.cos(el) * Math.sin(d), Math.sin(el)];
}
/** The azimuth of plane column `x` of `w` (the card is the whole baked window wide). */
export const columnAzimuth = (view: View, x: number, w: number): number =>
view.lookAzDeg + ((x + 0.5) / w - 0.5) * view.windowDeg;
/** The compass azimuth of ring column `col` of `w` columns (column 0 = north), taken at the column's centre. */
export const ringAzimuth = (col: number, w: number): number => ((col + 0.5) / w) * 360;
/** A geometry texel's red and green bytes as the shader reads them: a wall, or the unit normal (along the ray, across it, up). */
export function decodeNormal(
@ -184,7 +173,7 @@ export function decodeNormal(
/** Everything the lighting reads of the sky and the manifest, as the numbers the shader's uniforms hold. */
export interface Lighting {
planeW: number;
ringW: number;
planeH: number;
logDMin: number;
logDSpan: number;
@ -249,7 +238,7 @@ export function lightingOf(
look: RidgeLook = DEFAULT_LOOK
): Lighting {
return {
planeW: manifest.view.planeW,
ringW: manifest.view.ringW,
planeH: manifest.view.planeH,
logDMin: manifest.encoding.logDMin,
logDSpan: manifest.encoding.logDMax - manifest.encoding.logDMin,
@ -261,18 +250,18 @@ export function lightingOf(
};
}
/** The sun in every column's frame, RGBA32F texels (a, b, c, 0), one row of `planeW`. */
/** The sun in every column's frame, RGBA32F texels (a, b, c, 0), one row of `ringW`: absolute azimuth, so every tile reads the same table. */
export function sunColumns(view: View, sun: { azimuth: number; elevation: number }): Float32Array {
const out = new Float32Array(view.planeW * 4);
for (let x = 0; x < view.planeW; x += 1) {
const [r, t, u] = sunInColumn(sun, columnAzimuth(view, x, view.planeW));
const out = new Float32Array(view.ringW * 4);
for (let x = 0; x < view.ringW; x += 1) {
const [r, t, u] = sunInColumn(sun, ringAzimuth(x, view.ringW));
out.set([r, t, u, 0], x * 4);
}
return out;
}
/**
* The sky's radiance (per unit of sun irradiance) as the haze needs it: a small grid over the window's azimuths and the plane's rows, the view
* The sky's radiance (per unit of sun irradiance) as the haze needs it: a small grid over the ring's azimuths and the plane's rows, the view
* direction of each texel's centre. Rows below the horizon take the horizon's radiance (the haze in front of a ridge is the air at its foot).
*/
export function skyLut(sky: PhysicalSky, view: View, w: number, h: number): Float32Array {
@ -281,7 +270,7 @@ export function skyLut(sky: PhysicalSky, view: View, w: number, h: number): Floa
for (let j = 0; j < h; j += 1) {
const elDeg = Math.max(0, (view.horizonRow - ((j + 0.5) / h) * view.planeH) / view.pxPerDegV);
for (let i = 0; i < w; i += 1) {
const az = columnAzimuth(view, ((i + 0.5) / w) * view.planeW - 0.5, view.planeW);
const az = ((i + 0.5) / w) * 360;
sky.atm.radiance(Math.sin(elDeg * RAD), Math.cos((az - sky.sun.azimuth) * RAD), rgb);
addNightRadiance(sky.night, Math.sin(elDeg * RAD), az * RAD, rgb);
out.set([rgb[0], rgb[1], rgb[2], 0], (j * w + i) * 4);
@ -304,7 +293,9 @@ uniform sampler2D uSky;
uniform ivec2 uSize;
uniform ivec2 uSkySize;
uniform int uTop;
uniform vec2 uPlane;
uniform int uCol0; // the ring column of the file's first texel (a tile's first column less its apron; may be below 0)
uniform int uRingW;
uniform float uPlaneH;
uniform vec2 uLogD;
uniform vec3 uExt;
uniform vec3 uTSun;
@ -326,7 +317,6 @@ uniform vec2 uCard; // value of this card, gradient
uniform vec2 uGround; // groundNoise, cloudShadows
uniform vec4 uCel; // bands (0 = Lambert), softness, ambientAway, ambientEdge
uniform float uBandLevels[${CEL_MAX}];
uniform float uRadPerPx; // radians of azimuth per plane pixel
out vec4 outColor;
const float PI = 3.14159265358979;
@ -397,12 +387,14 @@ float cel(float x) {
return l;
}
// The sky's table spans the ring: it wraps in azimuth (x) and clamps in elevation (y).
vec3 skyAt(vec2 uv) {
vec2 f = uv * vec2(uSkySize) - 0.5;
vec2 b = floor(f);
vec2 t = f - b;
ivec2 lo = clamp(ivec2(b), ivec2(0), uSkySize - 1);
ivec2 hi = clamp(ivec2(b) + 1, ivec2(0), uSkySize - 1);
int w = uSkySize.x;
ivec2 lo = ivec2((int(b.x) % w + w) % w, clamp(int(b.y), 0, uSkySize.y - 1));
ivec2 hi = ivec2((int(b.x) + 1) % w, clamp(int(b.y) + 1, 0, uSkySize.y - 1));
vec3 a = mix(texelFetch(uSky, ivec2(lo.x, lo.y), 0).rgb, texelFetch(uSky, ivec2(hi.x, lo.y), 0).rgb, t.x);
vec3 c = mix(texelFetch(uSky, ivec2(lo.x, hi.y), 0).rgb, texelFetch(uSky, ivec2(hi.x, hi.y), 0).rgb, t.x);
return mix(a, c, t.y);
@ -444,10 +436,13 @@ void main() {
if (c.a <= 0.0) { outColor = vec4(0.0); return; }
Geo g = geoAt(p);
vec3 s = texelFetch(uSun, ivec2(p.x, 0), 0).xyz;
int col = ((uCol0 + p.x) % uRingW + uRingW) % uRingW;
vec3 s = texelFetch(uSun, ivec2(col, 0), 0).xyz;
if (uRelief.y > 0.0) s = normalize(mix(s, uFixedLight, uRelief.y));
float dist = exp(g.logD);
vec2 world = vec2(float(p.x) * uRadPerPx, 1.0) * dist;
// The ground's noise is a function of the ground point, dist x (sin psi, cos psi) for the column's absolute azimuth psi, so it is periodic over the wrap.
float psi = (float(col) + 0.5) / float(uRingW) * 2.0 * PI;
vec2 world = vec2(sin(psi), cos(psi)) * dist;
vec3 albedo = toLinear(c.rgb);
if (uGround.x > 0.0) albedo *= max(1.0 + uGround.x * (2.0 * fbm(world / 250.0) - 1.0), 0.0);
float cloud = uGround.y > 0.0 ? 1.0 - uGround.y * smoothstep(0.5, 0.72, fbm(world / 4000.0 + 17.0)) : 1.0;
@ -462,7 +457,7 @@ void main() {
}
radiance *= mix(vec3(1.0), NEAR_WARM, uDist.x * (1.0 - dn));
vec3 T = exp(-uExt * (dist / 1000.0));
vec2 uv = vec2((float(p.x) + 0.5) / uPlane.x, (float(uTop + p.y) + 0.5) / uPlane.y);
vec2 uv = vec2((float(col) + 0.5) / float(uRingW), (float(uTop + p.y) + 0.5) / uPlaneH);
vec3 haze = skyAt(uv);
haze += uHazeTint * dot(haze, LUMA);
radiance = radiance * T + haze * (1.0 - T);
@ -544,16 +539,35 @@ function bitmapTexture(gl: WebGL2RenderingContext, unit: number, bmp: ImageBitma
return t;
}
/** A tile of a card as its two files decoded: the colour with straight alpha and the geometry, each tileW + 2 apron columns by the band's rows. */
export interface CardBitmaps {
colour: ImageBitmap;
geometry: ImageBitmap;
}
/** One sky's lighting of the ring's tiles. */
export interface Lighter {
/**
* Light card `card` of tile `tile` from its decoded files: a 2D canvas of the tile's interior columns plus one overlap column each side (the apron is
* read and dropped; the overlap hides the hairline between adjacent canvases at a fractional scale), premultiplied by the card's alpha. The bitmaps
* stay the caller's to close. Throws when the context is lost or the tile holds no such card.
*/
light(bitmaps: CardBitmaps, tile: number, card: number): HTMLCanvasElement;
/** True once the GL context was lost: this lighter is spent and the next ensure makes another. */
readonly lost: boolean;
/** Let go of the GL context and its tables. */
release(): void;
}
/**
* Light the cards of `manifest` for `sky`, nearest first, as the manifest lists them. Throws without WebGL2 or when the shader will not link;
* the caller (`loadBackdrop`) turns any throw into the sky alone. Closes the bitmaps, and releases the context after the last card.
* The lighter for `sky`: one WebGL2 context on a canvas of its own, the program, the ring-wide sun columns and the sky's lookup uploaded once, a tile lit
* per call. Throws without WebGL2 or when the shader will not link; the caller (`Backdrop.ts`) turns any throw into the sky alone.
*/
export function lightCards(
export function createLighter(
manifest: RidgeManifest,
bitmaps: CardBitmaps[],
sky: PhysicalSky,
look: RidgeLook = DEFAULT_LOOK
): LitCard[] {
): Lighter {
const glCanvas = document.createElement('canvas');
const gl = glCanvas.getContext('webgl2', {
alpha: true,
@ -563,6 +577,18 @@ export function lightCards(
stencil: false,
});
if (!gl) throw new Error('ridge: no WebGL2');
let lost = false;
let released = false;
const release = () => {
if (released) return;
released = true;
gl.getExtension('WEBGL_lose_context')?.loseContext();
};
glCanvas.addEventListener?.('webglcontextlost', () => {
lost = true;
});
const { view } = manifest;
const litW = view.tileW + 2;
try {
const lit = lightingOf(manifest, sky, look);
const prog = program(gl);
@ -572,7 +598,8 @@ export function lightCards(
gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
['uColour', 'uGeo', 'uSun', 'uSky'].forEach((n, i) => gl.uniform1i(u(n), i));
gl.uniform2f(u('uPlane'), lit.planeW, lit.planeH);
gl.uniform1i(u('uRingW'), lit.ringW);
gl.uniform1f(u('uPlaneH'), lit.planeH);
gl.uniform2f(u('uLogD'), lit.logDMin, lit.logDSpan);
gl.uniform3f(u('uExt'), ...lit.extinction);
gl.uniform3f(u('uTSun'), ...lit.key.direct);
@ -599,49 +626,49 @@ export function lightCards(
gl.uniform2f(u('uGround'), look.groundNoise, look.cloudShadows);
gl.uniform4f(u('uCel'), look.celBands, look.celSoftness, look.celAmbientAway, look.celAmbientEdge);
gl.uniform1fv(u('uBandLevels'), celLevels(look.celBands, look.celBandLevels));
gl.uniform1f(u('uRadPerPx'), (manifest.view.windowDeg * RAD) / lit.planeW);
gl.uniform2i(u('uSkySize'), SKY_LUT.w, SKY_LUT.h);
const sunTex = floatTexture(gl, 2, lit.planeW, 1, sunColumns(manifest.view, lit.key));
const skyTex = floatTexture(
gl,
3,
SKY_LUT.w,
SKY_LUT.h,
skyLut(sky, manifest.view, SKY_LUT.w, SKY_LUT.h)
);
const out = manifest.cards.map((card, i): LitCard => {
const { colour, geometry } = bitmaps[i];
glCanvas.width = colour.width;
glCanvas.height = colour.height;
gl.viewport(0, 0, colour.width, colour.height);
const colourTex = bitmapTexture(gl, 0, colour);
const geoTex = bitmapTexture(gl, 1, geometry);
gl.uniform2i(u('uSize'), colour.width, colour.height);
gl.uniform1i(u('uTop'), card.top);
gl.uniform2f(
u('uCard'),
1 + look.cardToneStep * (i - (manifest.cards.length - 1) / 2),
look.cardGradient
);
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 3);
const canvas = document.createElement('canvas');
canvas.width = colour.width;
canvas.height = colour.height;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('ridge: no 2D context for a lit card');
ctx.drawImage(glCanvas, 0, 0);
gl.deleteTexture(colourTex);
gl.deleteTexture(geoTex);
colour.close();
geometry.close();
return { canvas, top: card.top, h: card.h, scale: card.scale };
});
gl.deleteTexture(sunTex);
gl.deleteTexture(skyTex);
return out;
} finally {
gl.getExtension('WEBGL_lose_context')?.loseContext();
floatTexture(gl, 2, lit.ringW, 1, sunColumns(view, lit.key));
floatTexture(gl, 3, SKY_LUT.w, SKY_LUT.h, skyLut(sky, view, SKY_LUT.w, SKY_LUT.h));
return {
get lost() {
return lost;
},
release,
light(bitmaps, tile, card) {
const entry = manifest.tiles[tile]?.[card];
if (!entry) throw new Error(`ridge: tile ${tile} holds no card ${card}`);
if (lost || released) throw new Error('ridge: the lighting context is gone');
const { colour, geometry } = bitmaps;
glCanvas.width = colour.width;
glCanvas.height = colour.height;
gl.viewport(0, 0, colour.width, colour.height);
const colourTex = bitmapTexture(gl, 0, colour);
const geoTex = bitmapTexture(gl, 1, geometry);
gl.uniform2i(u('uSize'), colour.width, colour.height);
gl.uniform1i(u('uTop'), entry.top);
gl.uniform1i(u('uCol0'), tile * view.tileW - view.apron);
gl.uniform2f(
u('uCard'),
1 + look.cardToneStep * (card - (manifest.cards.length - 1) / 2),
look.cardGradient
);
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 3);
const canvas = document.createElement('canvas');
canvas.width = litW;
canvas.height = colour.height;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('ridge: no 2D context for a lit tile');
// The file's columns apron - 1 .. apron + tileW (inclusive): the interior and one overlap column each side.
ctx.drawImage(glCanvas, view.apron - 1, 0, litW, colour.height, 0, 0, litW, colour.height);
gl.deleteTexture(colourTex);
gl.deleteTexture(geoTex);
return canvas;
},
};
} catch (e) {
release();
throw e;
}
}

View file

@ -9,10 +9,11 @@ export const DISTANCES: (number | null)[][] = [
[40000, 41000, null, 39000],
];
/** A schema 3 manifest of `k` cards (1 to 3, nearest first), each a band of the 600-row plane, over four tiles of 1600 columns. */
/** A schema 3 manifest of `k` cards (1 to 3, nearest first), each a band of the 600-row plane, over `tiles` tiles (4 by default, 32 as the baker cuts) whose distances repeat the four above. */
export const wireManifest = (
over: Record<string, unknown> = {},
k = 3
k = 3,
tiles = 4
): Record<string, unknown> => ({
schema: 3,
baker_version: 4,
@ -36,8 +37,8 @@ export const wireManifest = (
sky_row: 24,
near_row: 396,
ring_w: 6400,
tile_w: 1600,
tiles: 4,
tile_w: 6400 / tiles,
tiles,
apron: 2,
},
curvature: { r_earth_m: 6371000, k_ref: 0.13 },
@ -47,9 +48,9 @@ export const wireManifest = (
near_m: i ? 1000 * 10 ** (i - 1) * 4 : null,
far_m: i < k - 1 ? 4000 * 10 ** i : null,
})),
tiles: Array.from({ length: 4 }, (_, t) =>
tiles: Array.from({ length: tiles }, (_, t) =>
Array.from({ length: k }, (_, i) => {
const d = DISTANCES[i][t];
const d = DISTANCES[i][t % 4];
return d === null
? null
: {