scene: shader linking in link.ts, BudgetLadder takes its levels, test GL fake shared, SceneStyle in the config

Groundwork for a second scene behind the same createScene contract: the compile/link path
and ShaderCompileError leave Scene.ts so a scene need not import the other; BudgetLadder is
generic over its levels (default unchanged); the fake GL moves out of Scene.test.ts;
backgroundScene.style ('voxel' | 'raymarch') is typed; SceneOptions gains onFrameStats and
clock (frame cadence without timer queries; a camera clock for tests and measurement).
No behaviour change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Nibu 2026-11-04 21:53:52 +00:00
commit b95b665fed
6 changed files with 161 additions and 116 deletions

View file

@ -1,58 +1,12 @@
import { afterEach, beforeEach, describe, expect, it, Mock, vi } from 'vitest';
import { createScene, ShaderCompileError, HALF_START_BIAS, HALF_START_SCALE } from './Scene';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { fakeCanvas, fakeGl } from './fakeGl';
import { createScene, HALF_START_BIAS, HALF_START_SCALE } from './Scene';
import { ShaderCompileError } from './link';
import { WORLD } from './world';
import { LEVELS } from './budget';
import { fragmentSource } from './shaderSource';
import { startBackgroundScene } from './index';
type Fn = Mock;
/** A GL context where every call is a spy and every constant is 1. Compiles succeed until `failFrom`. */
function fakeGl(failFrom = Infinity, missing: string[] = []) {
let compiles = 0;
const calls: Record<string, Fn> = {};
const spy = (name: string, impl: (...a: any[]) => unknown = () => ({})): Fn => {
if (!calls[name]) calls[name] = vi.fn(impl);
return calls[name];
};
const gl = new Proxy({} as Record<string, unknown>, {
get(_, prop: string) {
// the two start-target formats must be told apart; every other constant is 1
if (prop === 'RGBA32F') return 32;
if (prop === 'RGBA16F') return 16;
if (/^[A-Z][A-Z0-9_]*$/.test(prop)) return 1;
if (prop === 'getExtension')
return spy(prop, (n: string) => (missing.includes(n) ? null : {}));
if (prop === 'compileShader') {
return spy(prop, () => {
compiles += 1;
});
}
if (prop === 'getShaderParameter') return spy(prop, () => compiles < failFrom);
if (prop === 'getShaderInfoLog') return spy(prop, () => 'ERROR: 0:1: bad');
if (prop === 'getProgramParameter') return spy(prop, () => true);
return spy(prop);
},
});
return { gl: gl as unknown as WebGL2RenderingContext, calls };
}
function fakeCanvas(gl: WebGL2RenderingContext | null) {
const canvas = new EventTarget() as EventTarget & {
clientWidth: number;
clientHeight: number;
width: number;
height: number;
getContext: Fn;
};
canvas.clientWidth = 400;
canvas.clientHeight = 300;
canvas.width = 0;
canvas.height = 0;
canvas.getContext = vi.fn(() => gl);
return canvas;
}
let rafQueue: Array<(t: number) => void>;
let cancelled: number;
let win: EventTarget;
@ -397,7 +351,7 @@ describe('startBackgroundScene', () => {
it('applies the device ceiling: saveData runs a still, one frame', async () => {
const { gl, calls } = fakeGl();
const scene = await startBackgroundScene(
{ tier: 'full' },
{ tier: 'full', style: 'raymarch' },
{ saveData: true },
{ canvas: asCanvas(fakeCanvas(gl)) }
);
@ -416,13 +370,19 @@ describe('startBackgroundScene', () => {
const { startBackgroundScene: start } = await import('./index');
const onCompileFail = vi.fn();
const canvas = fakeCanvas(fakeGl().gl);
const scene = await start({ tier: 'full' }, {}, { canvas: asCanvas(canvas), onCompileFail });
const scene = await start(
{ tier: 'full', style: 'raymarch' },
{},
{ canvas: asCanvas(canvas), onCompileFail }
);
expect(scene).toBeNull();
expect(onCompileFail).toHaveBeenCalledTimes(1);
expect(onCompileFail.mock.calls[0][0]).toBeInstanceOf(Error);
expect(canvas.getContext).not.toHaveBeenCalled();
// and with no callback it still does not throw
expect(await start({ tier: 'full' }, {}, { canvas: asCanvas(canvas) })).toBeNull();
expect(
await start({ tier: 'full', style: 'raymarch' }, {}, { canvas: asCanvas(canvas) })
).toBeNull();
} finally {
vi.doUnmock('./Scene');
vi.resetModules();

View file

@ -1,4 +1,5 @@
import { fragmentSource, vertexSource, Stage } from './shaderSource';
import { Stage } from './shaderSource';
import { linkStage, ShaderCompileError, SourcePatch } from './link';
import { cameraPose, pullProgress, CameraPose } from './camera';
import { BudgetLadder, Level, LEVELS } from './budget';
import { startFrameLoop } from './frameLoop';
@ -22,6 +23,17 @@ export interface SceneStats {
atmosphereSize: [number, number];
}
/** The voxel scene's per-frame figures, with no extension needed. */
export interface FrameStats {
/** Milliseconds since the previous frame: the cadence, 33 ms at the 30 fps cap. */
frameMs: number;
/** Milliseconds one frame took to draw and read back; only when the host asked for trace stats, which forces a sync. */
renderMs?: number;
/** Drawing-buffer size as a fraction of the canvas's CSS size times device pixel ratio. */
scale: number;
size: [number, number];
}
/** Trace cost over one finished readback: mean distance evaluations per pass-1 pixel. */
export interface TraceStats {
/** Mean pass-1 steps per pixel. */
@ -32,15 +44,6 @@ export interface TraceStats {
stepsPerPixel: number;
}
/** Measurement seam: the harness rewrites a stage's source to time a variant. Never set in the client. */
export type SourcePatch = (stage: Stage, source: string) => string;
export class ShaderCompileError extends Error {
constructor(readonly stage: Stage | 'vertex', readonly log: string) {
super(`${stage} shader failed to compile:\n${log}`);
}
}
/**
* Why createScene returned null for want of a device feature. Rendering to half floats needs
* EXT_color_buffer_float or EXT_color_buffer_half_float; the prepass start target is RGBA32F with
@ -91,6 +94,10 @@ export interface SceneOptions {
fixedLevel?: Level;
/** Cone prepass that starts pass-1 rays past empty space. Default true; false is the measurement baseline. */
prepass?: boolean;
/** Voxel scene: per finished frame, the cadence and the drawing-buffer scale. */
onFrameStats?: (s: FrameStats) => void;
/** Voxel scene: seconds for the camera path, instead of the clock (measurement, tests). */
clock?: () => number;
/** Hold the camera at this pull-back progress, 0..1, instead of following login (measurement). */
fixedPull?: number;
/** Ignore the 30 fps cap and the visibility pause (measurement). */
@ -99,57 +106,13 @@ export interface SceneOptions {
}
export interface Scene {
/** Texture format of the prepass start target. */
readonly startFormat: 'RGBA32F' | 'RGBA16F';
/** Texture format of the ray-march scene's prepass start target; the voxel scene has none. */
readonly startFormat?: 'RGBA32F' | 'RGBA16F';
/** Start the camera pull-back from the tree. */
login(): void;
dispose(): void;
}
function compile(
gl: WebGL2RenderingContext,
type: number,
source: string,
stage: Stage | 'vertex'
): WebGLShader {
const sh = gl.createShader(type)!;
gl.shaderSource(sh, source);
gl.compileShader(sh);
if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
const log = gl.getShaderInfoLog(sh) ?? '';
gl.deleteShader(sh);
throw new ShaderCompileError(stage, log);
}
return sh;
}
export function linkStage(
gl: WebGL2RenderingContext,
stage: Stage,
patch?: SourcePatch,
defines?: string
): WebGLProgram {
const vs = compile(gl, gl.VERTEX_SHADER, vertexSource, 'vertex');
const fs = compile(
gl,
gl.FRAGMENT_SHADER,
patch ? patch(stage, fragmentSource(stage, defines)) : fragmentSource(stage, defines),
stage
);
const prog = gl.createProgram()!;
gl.attachShader(prog, vs);
gl.attachShader(prog, fs);
gl.linkProgram(prog);
gl.deleteShader(vs);
gl.deleteShader(fs);
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
const log = gl.getProgramInfoLog(prog) ?? '';
gl.deleteProgram(prog);
throw new ShaderCompileError(stage, log);
}
return prog;
}
interface Target {
tex: WebGLTexture;
w: number;

View file

@ -19,7 +19,7 @@ export const LEVELS: readonly Level[] = [
];
/** Median of the last `window` frame times above `budgetMs` for a whole window steps down one level. */
export class BudgetLadder {
export class BudgetLadder<L = Level> {
private level: number;
private recent: number[] = [];
@ -28,15 +28,26 @@ export class BudgetLadder {
private readonly window: number;
/** `startLevel` lets a weak device begin below level 0; it is clamped into the ladder. */
constructor(budgetMs: number, window = 45, startLevel = 0) {
private readonly levels: readonly L[];
/**
* `startLevel` lets a weak device begin below level 0; it is clamped into the ladder. `levels`
* defaults to the ray-march ladder; another scene passes its own.
*/
constructor(
budgetMs: number,
window = 45,
startLevel = 0,
levels: readonly L[] = LEVELS as unknown as readonly L[]
) {
this.budgetMs = budgetMs;
this.window = window;
this.level = Math.min(Math.max(startLevel, 0), LEVELS.length - 1);
this.levels = levels;
this.level = Math.min(Math.max(startLevel, 0), levels.length - 1);
}
get current(): Level {
return LEVELS[this.level];
get current(): L {
return this.levels[this.level];
}
get index(): number {
@ -50,7 +61,7 @@ export class BudgetLadder {
const sorted = [...this.recent].sort((a, b) => a - b);
const median = sorted[Math.floor(sorted.length / 2)];
this.recent = [];
if (median > this.budgetMs && this.level < LEVELS.length - 1) {
if (median > this.budgetMs && this.level < this.levels.length - 1) {
this.level += 1;
return true;
}

View file

@ -0,0 +1,52 @@
// A GL context for tests: every call a spy, so a scene can be driven without a GPU.
import { Mock, vi } from 'vitest';
type Fn = Mock;
/** A GL context where every call is a spy and every constant is 1. Compiles succeed until `failFrom`. */
export function fakeGl(failFrom = Infinity, missing: string[] = []) {
let compiles = 0;
const calls: Record<string, Fn> = {};
const spy = (name: string, impl: (...a: any[]) => unknown = () => ({})): Fn => {
if (!calls[name]) calls[name] = vi.fn(impl);
return calls[name];
};
const gl = new Proxy({} as Record<string, unknown>, {
get(_, prop: string) {
// texture formats must be told apart; every other constant is 1
if (prop === 'RGBA32F') return 32;
if (prop === 'RGBA16F') return 16;
if (prop === 'RG8') return 208;
if (prop === 'RGBA8') return 209;
if (/^[A-Z][A-Z0-9_]*$/.test(prop)) return 1;
if (prop === 'getExtension')
return spy(prop, (n: string) => (missing.includes(n) ? null : {}));
if (prop === 'compileShader') {
return spy(prop, () => {
compiles += 1;
});
}
if (prop === 'getShaderParameter') return spy(prop, () => compiles < failFrom);
if (prop === 'getShaderInfoLog') return spy(prop, () => 'ERROR: 0:1: bad');
if (prop === 'getProgramParameter') return spy(prop, () => true);
return spy(prop);
},
});
return { gl: gl as unknown as WebGL2RenderingContext, calls };
}
export function fakeCanvas(gl: WebGL2RenderingContext | null) {
const canvas = new EventTarget() as EventTarget & {
clientWidth: number;
clientHeight: number;
width: number;
height: number;
getContext: Fn;
};
canvas.clientWidth = 400;
canvas.clientHeight = 300;
canvas.width = 0;
canvas.height = 0;
canvas.getContext = vi.fn(() => gl);
return canvas;
}

View file

@ -0,0 +1,55 @@
// Compiling and linking a stage: the one place a shader failure becomes a ShaderCompileError.
import { fragmentSource, vertexSource, Stage } from './shaderSource';
/** Measurement seam: the harness rewrites a stage's source to time a variant. Never set in the client. */
export type SourcePatch = (stage: Stage, source: string) => string;
export class ShaderCompileError extends Error {
constructor(readonly stage: Stage | 'vertex', readonly log: string) {
super(`${stage} shader failed to compile:\n${log}`);
}
}
function compile(
gl: WebGL2RenderingContext,
type: number,
source: string,
stage: Stage | 'vertex'
): WebGLShader {
const sh = gl.createShader(type)!;
gl.shaderSource(sh, source);
gl.compileShader(sh);
if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {
const log = gl.getShaderInfoLog(sh) ?? '';
gl.deleteShader(sh);
throw new ShaderCompileError(stage, log);
}
return sh;
}
export function linkStage(
gl: WebGL2RenderingContext,
stage: Stage,
patch?: SourcePatch,
defines?: string
): WebGLProgram {
const vs = compile(gl, gl.VERTEX_SHADER, vertexSource, 'vertex');
const fs = compile(
gl,
gl.FRAGMENT_SHADER,
patch ? patch(stage, fragmentSource(stage, defines)) : fragmentSource(stage, defines),
stage
);
const prog = gl.createProgram()!;
gl.attachShader(prog, vs);
gl.attachShader(prog, fs);
gl.linkProgram(prog);
gl.deleteShader(vs);
gl.deleteShader(fs);
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
const log = gl.getProgramInfoLog(prog) ?? '';
gl.deleteProgram(prog);
throw new ShaderCompileError(stage, log);
}
return prog;
}

View file

@ -15,8 +15,12 @@ export interface Capabilities {
hardwareConcurrency?: number;
}
/** 'voxel': the simple heightfield terrain (default). 'raymarch': the sphere-traced world with its tree and clouds. */
export type SceneStyle = 'voxel' | 'raymarch';
export interface BackgroundSceneConfig {
tier?: SceneTier;
style?: SceneStyle;
}
export function readCapabilities(nav: Navigator): Capabilities {