/**
* The contour field, framework-free. Ported from daemon-sec's
* client/src/components/daemon/contour-field.tsx (same shader, same
* timing) so the sibling sites share one hero ground without React.
*
* A fragment shader on a single triangle, in raw WebGL: every pixel is
* computed from four octaves of moving noise, the noise is cut into
* bands, and a thin line is drawn where one band meets the next, each in
* one of the six accents. The lines bend around the pointer.
*
* Type set straight on the field gets clean ground. The field takes the
* hero's shelf rows (`[data-index-zone]`) and anything else inside the
* canvas's parent marked `data-contour-clear`, up to six boxes in all,
* as rectangles, and draws no line inside them, bringing the lines back
* over a soft margin outside. The lines pass round the words, not
* through them. A section banner marks its title block and its ledger.
*
* Colours are this site's tokens, resolved where the canvas sits in the
* cascade and read again when <html> changes its theme. Pauses
* off-screen and in hidden tabs; one still frame under reduced motion
* (OS setting or `<html data-motion="reduce">`); `onFail` if WebGL is
* unavailable or the context is lost.
*/
export interface ContourOptions {
/** Selector for the box the lines stay out of, looked up inside the
* canvas's parent. */
zone?: string;
onFail?: () => void;
}
/* daemon-sec's defaults (its lib/contour-prefs.ts). That site lets a
visitor move all three from a panel; this one has no such panel, so
they are fixed. */
const LINES = 9;
const SPEED = 1;
const STRENGTH = 0.7;
/** How far outside the keep-clear box the lines take to come back, in
* CSS px. */
const FEATHER = 48;
/** The shortest height the pattern is scaled to, in CSS px. */
const MIN_UNIT = 620;
/** Where the clock starts, and the phase the still frame is drawn at:
* the first seconds of the noise are flat. */
const START = 20;
/** How long a still frame goes on checking that the keep-clear box has
* stopped moving, in ms. */
const SETTLE = 300;
/* The tokens the field paints with, ground first, then the accents in
the order the bands cycle through them. These are the names that flip
with the mode, so the lines are dark ink on cream and light on night. */
const TOKENS = ["--base", "--pine", "--foam", "--gold", "--love", "--iris", "--rose"];
/* One body, two dialects. WebGL2 is GLSL ES 3.00, where derivatives are
part of the language; WebGL1 needs them as an extension and spells its
inputs and its output differently. The preambles below paper over
that, so the shader itself is written once. */
const VERT_BODY = `
IN vec2 a_pos;
void main() { gl_Position = vec4(a_pos, 0.0, 1.0); }
`;
const FRAG_BODY = `
uniform float u_time;
uniform vec2 u_res;
uniform vec2 u_mouse;
uniform float u_lines;
uniform float u_strength;
uniform vec4 u_zone[6];
uniform float u_feather;
uniform vec3 u_bg;
uniform vec3 u_c[6];
float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123); }
float noise(vec2 p) {
vec2 i = floor(p); vec2 f = fract(p); vec2 w = f * f * (3.0 - 2.0 * f);
return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), w.x),
mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), w.x), w.y);
}
float fbm(vec2 p) {
float a = 0.5; float s = 0.0;
for (int i = 0; i < 4; i++) { s += a * noise(p); p = p * 2.03 + vec2(17.0, 9.0); a *= 0.5; }
return s;
}
vec3 pick(float i) {
vec3 c = u_c[0];
c = mix(c, u_c[1], step(0.5, i)); c = mix(c, u_c[2], step(1.5, i));
c = mix(c, u_c[3], step(2.5, i)); c = mix(c, u_c[4], step(3.5, i));
c = mix(c, u_c[5], step(4.5, i));
return c;
}
/* The keep-clear boxes: 0 anywhere inside one, 1 a feather's width
outside all of them. Measured as the distance to each rectangle, so
the margin turns the corners on a radius and no square edge is ever
drawn. A slot whose right edge is left of its left edge is empty. */
float keep(vec2 p) {
float k = 1.0;
for (int i = 0; i < 6; i++) {
vec4 z = u_zone[i];
if (z.z > z.x) {
vec2 q = abs(p - 0.5 * (z.xy + z.zw)) - 0.5 * (z.zw - z.xy);
float sd = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0);
k = min(k, smoothstep(0.0, u_feather, sd));
}
}
return k;
}
void main() {
vec2 uv = gl_FragCoord.xy / u_res.y;
vec2 m = u_mouse / u_res.y;
float t = u_time * 0.06;
vec2 q = uv * 1.6;
vec2 warp = vec2(fbm(q + vec2(t, -t)), fbm(q + vec2(5.2 - t, 1.3 + t)));
float v = fbm(q + 1.6 * warp);
float d = distance(uv, m);
v += 0.22 * exp(-d * d * 9.0);
float x = v * u_lines;
float band = floor(x);
float f = abs(fract(x) - 0.5);
float px = fwidth(x);
float line = 1.0 - smoothstep(px * 0.7, px * 1.9, f);
OUT = vec4(mix(u_bg, pick(mod(band, 6.0)), line * u_strength * keep(gl_FragCoord.xy)), 1.0);
}
`;
const GL2 = {
vert: `#version 300 es\n#define IN in\n${VERT_BODY}`,
frag: `#version 300 es\nprecision highp float;\nout vec4 fragColor;\n#define OUT fragColor\n${FRAG_BODY}`,
};
const GL1 = {
vert: `#define IN attribute\n${VERT_BODY}`,
frag: `#extension GL_OES_standard_derivatives : enable\nprecision highp float;\n#define OUT gl_FragColor\n${FRAG_BODY}`,
};
type Rgb = [number, number, number];
/** A token as 0–1 channels. Routed through `color` on a probe, so
* whatever the token is written as comes back resolved, and resolved
* where the canvas sits in the cascade.
*
* The probe is made fresh for each read and lives inside the canvas.
* Fresh, because under reduced motion the site gives every element a
* 0.01ms transition on every property, and an element whose colour has
* just been changed answers with the one it is leaving. Inside the
* canvas, so it is never laid out and the hero's own children are left
* as they were. */
function channels(cv: HTMLCanvasElement, token: string): Rgb {
const probe = document.createElement("span");
probe.style.color = `var(${token})`;
cv.appendChild(probe);
const css = getComputedStyle(probe).color;
probe.remove();
const n = (css.match(/[\d.]+/g) ?? []).slice(0, 3).map(Number);
if (n.length < 3) return [0, 0, 0];
/* rgb() counts to 255; color(srgb …) is already 0–1. */
const k = css.startsWith("rgb") ? 255 : 1;
return [n[0] / k, n[1] / k, n[2] / k];
}
function compile(gl: WebGLRenderingContext, type: number, source: string) {
const shader = gl.createShader(type);
if (!shader) return null;
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
if (import.meta.env.DEV) console.error("contour-field shader:", gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
}
export function mountContourField(cv: HTMLCanvasElement, options: ContourOptions = {}): () => void {
const zoneSelector = options.zone ?? "[data-index-zone]";
const host = cv.parentElement;
if (!host) {
options.onFail?.();
return () => {};
}
/* Alpha is left on although every pixel drawn is opaque: a canvas that
has just been resized, or not yet drawn, then shows the hero's own
ground through it rather than a black frame. Low-power, like the dot
field: this is a backdrop, not worth waking a second GPU for. */
const attrs: WebGLContextAttributes = {
alpha: true,
antialias: false,
depth: false,
stencil: false,
powerPreference: "low-power",
};
const gl2 = cv.getContext("webgl2", attrs);
const gl = (gl2 ?? cv.getContext("webgl", attrs)) as WebGLRenderingContext | null;
if (!gl) {
if (import.meta.env.DEV) console.error("contour-field: no WebGL context");
options.onFail?.();
return () => {};
}
/* Hand the context back now, not when the canvas is collected: a
browser keeps only so many. */
const lose = () => gl.getExtension("WEBGL_lose_context")?.loseContext();
const giveUp = () => {
lose();
options.onFail?.();
return () => {};
};
// Without derivatives there is no even line width; better no field
// than a field of jagged ones.
if (!gl2 && !gl.getExtension("OES_standard_derivatives")) return giveUp();
const src = gl2 ? GL2 : GL1;
const vert = compile(gl, gl.VERTEX_SHADER, src.vert);
const frag = compile(gl, gl.FRAGMENT_SHADER, src.frag);
const program = gl.createProgram();
if (!vert || !frag || !program) return giveUp();
gl.attachShader(program, vert);
gl.attachShader(program, frag);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
if (import.meta.env.DEV) console.error("contour-field link:", gl.getProgramInfoLog(program));
return giveUp();
}
gl.useProgram(program);
// One triangle that covers the clip square, rather than two that
// share a diagonal.
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
const aPos = gl.getAttribLocation(program, "a_pos");
gl.enableVertexAttribArray(aPos);
gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);
const u = (name: string) => gl.getUniformLocation(program, name);
const uTime = u("u_time");
const uRes = u("u_res");
const uMouse = u("u_mouse");
const uZone = u("u_zone");
const uFeather = u("u_feather");
const uBg = u("u_bg");
const uC = u("u_c");
gl.uniform1f(u("u_lines"), LINES);
gl.uniform1f(u("u_strength"), STRENGTH);
/* ── Colour ── */
let stale = true;
const paint = () => {
stale = false;
const [bg, ...accents] = TOKENS.map((t) => channels(cv, t));
gl.uniform3f(uBg, bg[0], bg[1], bg[2]);
gl.uniform3fv(uC, new Float32Array(accents.flat()));
};
/* ── The keep-clear box ──
The hero builds its list in script, after this may have mounted, and
builds it again on a theme or breakpoint change, so the element is
looked up lazily and looked up again once it has left the document. */
let zoneEl: HTMLElement | null = null;
/* Other type that wants the same clean ground: the hero's sub-line,
a banner's title block and ledger. Marked `data-contour-clear`,
each its own box beside the rows'. */
let alsoClear: HTMLElement[] = [];
const MAX_CLEAR = 6;
const zones = new Float32Array(MAX_CLEAR * 4);
let zoneLost = true;
const findZone = () => {
zoneLost = false;
alsoClear = Array.from(host.querySelectorAll<HTMLElement>("[data-contour-clear]"));
const el = host.querySelector<HTMLElement>(zoneSelector);
if (el === zoneEl) return;
if (zoneEl) resize.unobserve(zoneEl);
zoneEl = el;
if (el) resize.observe(el);
};
/* ── Motion ── */
const reducedMq = window.matchMedia("(prefers-reduced-motion: reduce)");
/* Asked every frame, not once at mount: either switch can be thrown
while the page is open, and the field should stop or start with it. */
const held = () => reducedMq.matches || document.documentElement.dataset.motion === "reduce";
/* The pointer in client px. The frame turns it into canvas pixels
against the rect it has just measured, so the handlers read no
layout and a scroll under a resting pointer still lands the bend
under it. Off the hero it parks far away, and the bend snaps there
and back rather than easing across the whole field. */
const FAR = -9999;
const pointer = { x: 0, y: 0, over: false };
const at = { x: FAR, y: FAR };
const onMove = (e: PointerEvent) => {
/* touch has no hover; a finger scrolling past should not drag the lines */
if (e.pointerType === "touch") return;
pointer.x = e.clientX;
pointer.y = e.clientY;
pointer.over = true;
};
const onLeave = () => {
pointer.over = false;
};
let frame = 0;
let last = 0;
let clock = START;
let inView = true;
let lost = false;
/* The still frame's geometry as last drawn, and until when it is still
being checked; see `draw`. */
let drawn = "";
let settle = 0;
/* One frame, drawn now. `dt` is how far the pointer's ease moves on;
a redraw outside the loop passes none and leaves it where it was.
Says whether a still frame's geometry has changed since the last. */
const render = (dt = 0): boolean => {
if (lost) return false;
const still = held();
const box = cv.getBoundingClientRect();
/* Sized in device pixels, capped: this is a full-bleed shader on the
first screen, and past 1.5x the extra pixels cost a frame budget
for a difference in a 1px line nobody can see. */
const ratio = Math.min(1.5, window.devicePixelRatio || 1);
const w = Math.max(1, Math.round(box.width * ratio));
const h = Math.max(1, Math.round(box.height * ratio));
if (cv.width !== w || cv.height !== h) {
cv.width = w;
cv.height = h;
}
gl.viewport(0, 0, w, h);
/* canvas pixels per client pixel; gl_FragCoord counts up from the
bottom edge, so every y below is measured from there */
const kx = w / (box.width || 1);
const ky = h / (box.height || 1);
if (stale) paint();
/* The rows' box is measured on every frame rather than cached: the
hero scales its artboard and reflows its copy without the list
itself changing size, which is all an observer on it would see.
The frame needs this layout anyway. */
if (zoneLost || (zoneEl && !zoneEl.isConnected)) findZone();
const clear = zoneEl ? [zoneEl, ...alsoClear] : alsoClear;
for (let i = 0; i < MAX_CLEAR; i++) {
const r = clear[i]?.getBoundingClientRect();
const o = i * 4;
if (!r || r.width === 0 || r.height === 0) {
zones[o] = 0;
zones[o + 1] = 0;
zones[o + 2] = -1;
zones[o + 3] = -1;
continue;
}
zones[o] = (r.left - box.left) * kx;
zones[o + 1] = (box.bottom - r.bottom) * ky;
zones[o + 2] = (r.right - box.left) * kx;
zones[o + 3] = (box.bottom - r.top) * ky;
}
gl.uniform4fv(uZone, zones);
gl.uniform1f(uFeather, FEATHER * kx);
let moved = false;
if (still) {
const shape = [w, h, ...zones].join();
moved = shape !== drawn;
drawn = shape;
}
const tx = pointer.over && !still ? (pointer.x - box.left) * kx : FAR;
const ty = pointer.over && !still ? (box.bottom - pointer.y) * ky : FAR;
if (tx === FAR || at.x === FAR) {
at.x = tx;
at.y = ty;
} else {
/* the reference's 12% a frame, held to that pace at any refresh rate */
const k = 1 - Math.pow(1 - 0.12, dt * 60);
at.x += (tx - at.x) * k;
at.y += (ty - at.y) * k;
}
gl.uniform1f(uTime, still ? START : clock);
/* The shader measures in units of `u_res.y`. A banner is a fraction
of the hero's height, and at its real height it would get the
hero's whole terrain squeezed into a strip; a floor on the unit
keeps the lines the same size everywhere. */
gl.uniform2f(uRes, w, Math.max(h, MIN_UNIT * ky));
gl.uniform2f(uMouse, at.x, at.y);
gl.drawArrays(gl.TRIANGLES, 0, 3);
cv.classList.add("is-live");
return moved;
};
const draw = (now: number) => {
frame = 0;
if (lost) return;
/* With motion off this is one still frame, and no loop is left to
notice the rows' box moving after it. It can: under reduced motion
the site's CSS turns every style change into a 0.01ms transition,
and a box read while one is pending comes back where it used to
be. So the same frame is drawn again until the box has held still
for a moment, and then nothing runs at all. */
if (held()) {
last = 0;
if (render()) settle = now + SETTLE;
if (now < settle) frame = requestAnimationFrame(draw);
return;
}
if (!inView || document.hidden) {
last = 0;
return;
}
const dt = last ? Math.min(0.05, (now - last) / 1000) : 0.016;
last = now;
clock += dt * SPEED;
render(dt);
frame = requestAnimationFrame(draw);
};
/* Ask for a frame: the next of the loop if it is running, the one that
restarts it if it had paused, or a fresh still frame. */
const kick = () => {
settle = performance.now() + SETTLE;
if (!frame && !lost) frame = requestAnimationFrame(draw);
};
/* Resizing a canvas clears it, and an observer reports after the
frame's own callbacks have run, so the redraw happens here, in the
same turn, or every step of a window drag would show a frame with no
lines. The kick after it re-measures once the hero's own observer
has refitted its artboard. */
const resize = new ResizeObserver(() => {
render();
kick();
});
resize.observe(cv);
const seen =
typeof IntersectionObserver !== "undefined"
? new IntersectionObserver((entries) => {
inView = entries[entries.length - 1].isIntersecting;
kick();
})
: null;
seen?.observe(cv);
/* The hero swapping its composition in or out: the list is a new node. */
const built = new MutationObserver(() => {
zoneLost = true;
kick();
});
built.observe(host, { childList: true });
/* A canvas bitmap does not follow the cascade, so a mode change has
to be heard. Drawn in the same turn, not on the next frame: the
theme toggle's wipe snapshots the page as soon as the attribute
flips. */
const onMode = () => {
stale = true;
render();
kick();
};
const onLost = () => {
lost = true;
cancelAnimationFrame(frame);
options.onFail?.();
};
host.addEventListener("pointermove", onMove, { passive: true });
host.addEventListener("pointerleave", onLeave);
document.addEventListener("visibilitychange", kick);
window.addEventListener("daemonmodechange", onMode);
reducedMq.addEventListener("change", kick);
const modeMo = new MutationObserver(onMode);
modeMo.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme", "data-palette", "data-motion"] });
cv.addEventListener("webglcontextlost", onLost);
/* A late webfont can rewrap the hero's copy and move the list with it;
with motion off there is no loop to notice, so ask once more. */
let released = false;
document.fonts?.ready.then(() => {
if (!released) kick();
});
kick();
return () => {
released = true;
if (frame) cancelAnimationFrame(frame);
resize.disconnect();
seen?.disconnect();
built.disconnect();
modeMo.disconnect();
host.removeEventListener("pointermove", onMove);
host.removeEventListener("pointerleave", onLeave);
document.removeEventListener("visibilitychange", kick);
window.removeEventListener("daemonmodechange", onMode);
reducedMq.removeEventListener("change", kick);
/* before the context goes, or losing it on purpose reports a failure */
cv.removeEventListener("webglcontextlost", onLost);
gl.deleteBuffer(buffer);
gl.deleteProgram(program);
gl.deleteShader(vert);
gl.deleteShader(frag);
lose();
};
}