/** * The dot field, framework-free. Generated from daemon-sec's * client/src/components/daemon/particle-field.tsx (same shaders, same * timing) so the sibling sites share one look without React. * * Two layers. The cloud: blue-noise dashes that drift and lean toward a * ring lagging the pointer, thinning under any `[data-index-zone]` box. * The icon layer (opt-in): dots that gather into the lit shelf's icon, * placed on a `[data-field-icon]` box inside the canvas's * `[data-field-host]` ancestor. On a light ground dots get a minimum size * and more ink. Colours are read off the canvas's computed style and * re-read whenever changes its theme attributes. Pauses off-screen * and in hidden tabs; one still frame under reduced motion (OS setting or * ``); `onFail` if WebGL is unavailable. */ import { minDistFor, poisson, rng } from "./poisson"; import { nearestInked, rasterise, targetsFor } from "./icon-targets"; export type Accent = string; export interface LitShelf { index: number | null; accent: Accent | null; /** True while a pointer holds the row (vs. a tour lighting it). */ held: boolean; } export interface ShelfSource { get(): LitShelf; subscribe(f: (s: LitShelf) => void): () => void; } export interface FieldOptions { /** Custom-property names for colours, resolved on the canvas. */ vars?: { ink: string; base: string; iris: string; love: string }; /** Accent colour variable for a shelf accent name. */ accentVar?: (accent: string) => string; pageFamily?: string; plateFamily?: string; tone?: "page" | "plate"; /** Draw the drifting cloud (default true). */ cloud?: boolean; /** SVG markup per shelf, in shelf order; enables the icon layer. */ icons?: string[]; /** Which shelf is lit; required with `icons`. */ shelf?: ShelfSource; /** Icon dots rest spread across the canvas and stay visible. */ restFill?: boolean; /** Also gather for a shelf a tour lights, not only a held one. */ tour?: boolean; /** Override motion; defaults to off under reduced motion. */ live?: boolean; onFail?: () => void; } const NO_SHELF: ShelfSource = { get: () => ({ index: null, accent: null, held: false }), subscribe: () => () => {}, }; type Rgb = [number, number, number]; function hexToRgb(hex: string, fallback: Rgb): Rgb { const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim()); if (!m) return fallback; const n = parseInt(m[1], 16); return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255]; } function readVar(el: HTMLElement, name: string, fallback: Rgb): Rgb { return hexToRgb(getComputedStyle(el).getPropertyValue(name), fallback); } const NOISE = ` vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; } vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; } vec4 permute(vec4 x) { return mod289(((x * 34.0) + 1.0) * x); } vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; } float snoise(vec3 v) { const vec2 C = vec2(1.0 / 6.0, 1.0 / 3.0); const vec4 D = vec4(0.0, 0.5, 1.0, 2.0); vec3 i = floor(v + dot(v, C.yyy)); vec3 x0 = v - i + dot(i, C.xxx); vec3 g = step(x0.yzx, x0.xyz); vec3 l = 1.0 - g; vec3 i1 = min(g.xyz, l.zxy); vec3 i2 = max(g.xyz, l.zxy); vec3 x1 = x0 - i1 + C.xxx; vec3 x2 = x0 - i2 + C.yyy; vec3 x3 = x0 - D.yyy; i = mod289(i); vec4 p = permute(permute(permute( i.z + vec4(0.0, i1.z, i2.z, 1.0)) + i.y + vec4(0.0, i1.y, i2.y, 1.0)) + i.x + vec4(0.0, i1.x, i2.x, 1.0)); float n_ = 0.142857142857; vec3 ns = n_ * D.wyz - D.xzx; vec4 j = p - 49.0 * floor(p * ns.z * ns.z); vec4 x_ = floor(j * ns.z); vec4 y_ = floor(j - 7.0 * x_); vec4 x = x_ * ns.x + ns.yyyy; vec4 y = y_ * ns.x + ns.yyyy; vec4 h = 1.0 - abs(x) - abs(y); vec4 b0 = vec4(x.xy, y.xy); vec4 b1 = vec4(x.zw, y.zw); vec4 s0 = floor(b0) * 2.0 + 1.0; vec4 s1 = floor(b1) * 2.0 + 1.0; vec4 sh = -step(h, vec4(0.0)); vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy; vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww; vec3 p0 = vec3(a0.xy, h.x); vec3 p1 = vec3(a0.zw, h.y); vec3 p2 = vec3(a1.xy, h.z); vec3 p3 = vec3(a1.zw, h.w); vec4 norm = taylorInvSqrt(vec4(dot(p0, p0), dot(p1, p1), dot(p2, p2), dot(p3, p3))); p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w; vec4 m = max(0.6 - vec4(dot(x0, x0), dot(x1, x1), dot(x2, x2), dot(x3, x3)), 0.0); m = m * m; return 42.0 * dot(m * m, vec4(dot(p0, x0), dot(p1, x1), dot(p2, x2), dot(p3, x3))); } `; /* Field units: y runs -1..1 over the canvas height, x is ±aspect. */ const VERT = ` precision highp float; attribute vec2 a_rest; attribute vec4 a_seed; attribute vec2 a_from; attribute vec2 a_to; uniform float u_time; uniform vec2 u_extent; uniform float u_pr; uniform float u_pscale; uniform float u_maxPoint; uniform float u_layer; uniform float u_hover; uniform float u_morph; uniform float u_pulse; uniform float u_iconReady; uniform float u_fill; uniform float u_light; uniform float u_ringR; uniform float u_ringW; uniform float u_ringW2; uniform float u_ringDisp; uniform vec2 u_ring; uniform vec2 u_ringLag; uniform vec4 u_zone; uniform vec4 u_icon; varying float v_scale; varying float v_near; varying float v_col; varying vec2 v_dir; ${NOISE} /* The cloud thins under the shelf list so the rows stay readable, but only partly and on a wide, rounded falloff: a hard cut-out read as a box drawn round the list. Measured as a rounded rectangle with a radius as big as its short side, so there is no corner to see. No list, no thinning. */ float zoneFade(vec2 p, float margin) { if (u_zone.z <= u_zone.x) return 1.0; vec2 c = 0.5 * (u_zone.xy + u_zone.zw); vec2 h = 0.5 * (u_zone.zw - u_zone.xy); float r = min(h.x, h.y) * 0.9; vec2 q = abs(p - c) - h + r; float sd = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r; return mix(0.45, 1.0, smoothstep(-0.25, margin, sd)); } void main() { float t = u_time * 0.5; vec2 p; float scale; float near = 0.0; if (u_layer < 0.5) { vec2 rest = a_rest; /* each dot sees the ring a little behind where it is, by its own amount, which spreads the settle across the field */ vec2 ring = mix(u_ringLag, u_ring, a_seed.w); float dist = distance(rest, ring); float noise0 = snoise(vec3(rest * 0.2 + vec2(18.4924, 72.9744), t * 0.5)); float dist1 = distance(rest + noise0 * 0.005, ring); float R = u_ringR; float t1 = smoothstep(R - u_ringW * 2.0, R, dist) - smoothstep(R, R + u_ringW, dist1); float t2 = smoothstep(R - u_ringW2 * 2.0, R, dist) - smoothstep(R, R + u_ringW2, dist1); float t3 = smoothstep(R + u_ringW2, R, dist); t1 = t1 * t1; t2 = t2 * t2 * t2; float s = t1 + t2 * 3.0 + t3 * 0.4; s += snoise(vec3(rest * 30.0 + vec2(11.4924, 12.9744), t * 0.5)) * t3 * 0.5; float nS = snoise(vec3(rest * 2.0 + vec2(18.4924, 72.9744), t * 0.5)); s += pow((nS + 1.5) * 0.5, 2.0) * 0.6; float n1 = snoise(vec3(rest * 4.0 + vec2(88.494, 32.4397), t * 0.35)); float n2 = snoise(vec3(rest * 4.0 + vec2(50.904, 120.947), t * 0.35)); float n3 = snoise(vec3(rest * 20.0 + vec2(18.4924, 72.9744), t * 0.5)); float n4 = snoise(vec3(rest * 20.0 + vec2(50.904, 120.947), t * 0.5)); vec2 disp = vec2(n1, n2) * 0.03 + vec2(n3, n4) * 0.005; float reach = clamp(dist, 0.0, 1.0); disp.x += sin(rest.x * 20.0 + t * 4.0) * 0.02 * reach; disp.y += cos(rest.y * 20.0 + t * 3.0) * 0.02 * reach; vec2 cur = rest + disp; /* the rim is pushed off the ring */ p = cur - (ring - cur) * pow(max(t2, 0.0), 0.75) * u_ringDisp * 0.3; scale = (s + 0.2) * zoneFade(p, 0.25); float nA = snoise(vec3(rest * 10.0 + vec2(18.4924, 72.9744), u_time * 0.85)); float ang = atan(p.y - ring.y, p.x - ring.x) + nA * 0.5; v_dir = vec2(cos(ang), sin(ang)); v_col = (snoise(vec3(rest * 2.0 + vec2(74.664, 91.556), u_time * 0.5)) + 1.0) * 0.5; } else { vec2 iconLocal = mix(a_from, a_to, smoothstep(0.0, 1.0, u_morph)); /* The icon as a volume, not a stencil. Each dot has its own depth through the figure (a stable hash of its seed), and the figure turns a little: a slow idle sway, plus a lean toward the pointer so it follows the hand the way the cloud does. With depth, the turn makes the front of the figure travel further than the back and the dots nearest the eye draw larger and brighter (below), so a gathered shelf icon reads as a small object made of dots rather than a flat outline — the same outline, with a thickness. The rotation is small enough that the glyph never stops reading as itself. */ float depth = fract(a_seed.y * 13.37 + a_seed.z * 0.71) - 0.5; vec2 lean = clamp((u_ringLag - u_icon.xy) / max(u_icon.z * 3.0, 0.001), -1.0, 1.0); float ay = sin(u_time * 0.55) * 0.28 + lean.x * 0.3; float ax = cos(u_time * 0.41) * 0.18 - lean.y * 0.22; vec3 q = vec3(iconLocal, depth * 0.34); q = vec3(q.x * cos(ay) + q.z * sin(ay), q.y, -q.x * sin(ay) + q.z * cos(ay)); q = vec3(q.x, q.y * cos(ax) - q.z * sin(ax), q.y * sin(ax) + q.z * cos(ax)); /* a touch of perspective: what is nearer is a little bigger */ float nearness = q.z / 0.34; vec2 iconPos = u_icon.xy + q.xy * (1.0 + nearness * 0.09) * u_icon.zw; /* Where a dot sets out from: a soft disc round the icon (the square sample, folded to polar), so nothing square is ever drawn. */ float ang0 = atan(a_rest.y, a_rest.x); float rad0 = max(abs(a_rest.x), abs(a_rest.y)) * 2.0; vec2 restDisc = u_icon.xy + vec2(cos(ang0), sin(ang0)) * sqrt(rad0) * u_icon.z * 0.95; /* or, on the plate, spread over the whole surface: the plate's own dots are the ones that gather */ vec2 restFill = a_rest * 2.0 * u_extent * 0.94; vec2 restW = mix(restDisc, restFill, u_fill); restW += 0.02 * vec2( snoise(vec3(a_rest * 3.0, t * 0.2)), snoise(vec3(a_rest * 3.0 + 31.7, t * 0.2))); /* arrival, staggered per dot and eased like power3.out */ float h = clamp((u_hover - a_seed.x * 0.35) / 0.65, 0.0, 1.0); h = 1.0 - pow(1.0 - h, 3.0); h *= u_iconReady; /* On the plate a share of the dots stays behind, so the card keeps its texture round the icon instead of emptying out. */ h *= mix(1.0, step(0.3, a_seed.w), u_fill); /* twinkle: a life cycle from the seed, invisible at its wrap */ float life = fract(u_time / a_seed.z + a_seed.y); float env = smoothstep(0.0, 0.2, life) * (1.0 - smoothstep(0.65, 1.0, life)); p = mix(restW, iconPos, h); float dist = distance(p, iconPos) / max(u_icon.z, 0.001); near = h * smoothstep(0.08, 0.0, dist); /* a ring expanding from the icon's centre after a change, nudging the dots outward as it passes */ if (u_pulse >= 0.0) { vec2 fromC = p - u_icon.xy; float ringD = abs(length(fromC) - u_pulse * u_icon.z * 0.9); float k = ringD / max(u_icon.z, 0.001); p += normalize(fromC + 0.0001) * 0.025 * u_icon.z * exp(-k * k * 60.0) * (1.0 - u_pulse); } /* Unseen at rest: the icon's dots only exist while a shelf is hovered, appearing as they set out and fading as they return. */ float shown = mix(smoothstep(0.0, 0.3, h), 1.0, u_fill); scale = (env * (0.45 + 0.55 * a_seed.w) * 0.7 * (1.0 - h) + 1.6 * near + 0.3 * env * h) * shown; /* the front of the figure draws a size up, the back a size down; only once the dot has arrived, so the journey is unchanged */ scale *= 1.0 + nearness * 0.22 * near; v_col = near; /* the depth rides out on v_dir, which the icon layer never reads for direction: x is nearness in -1..1 */ v_dir = vec2(nearness, 0.0); } v_near = near; v_scale = scale; if (scale < 0.1) { gl_Position = vec4(2.0, 2.0, 2.0, 1.0); gl_PointSize = 1.0; return; } /* The light-ground minimum is for the page cloud; the plate's dots are already drawn a size up, and doubling it made them chunky. */ float px = scale * 7.0 * u_pr * 0.5 * u_pscale + u_light * 1.1 * u_pr * (1.0 - u_layer); /* The plate's dots are its whole surface, not a wash behind a page, so they are drawn a size up. */ if (u_layer > 0.5) px = (px * 1.25 + 0.6 * u_pr) * (1.0 + 0.7 * u_fill); gl_PointSize = min(u_maxPoint, px); gl_Position = vec4(p.x / u_extent.x, p.y / u_extent.y, 0.0, 1.0); } `; const FRAG = ` precision highp float; uniform float u_layer; uniform float u_inkAlpha; uniform float u_iconAlpha; uniform vec3 u_c1; uniform vec3 u_c2; uniform vec3 u_c3; uniform vec3 u_ink; uniform vec3 u_accent; uniform float u_light; varying float v_scale; varying float v_near; varying float v_col; varying vec2 v_dir; float sdRoundBox(vec2 p, vec2 b, float r) { vec2 q = abs(p) - b + r; return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r; } void main() { vec2 uv = gl_PointCoord - 0.5; uv.y = -uv.y; float a; vec3 c; if (u_layer < 0.5) { /* a short dash, turned to face the ring */ vec2 q = vec2(uv.x * v_dir.x + uv.y * v_dir.y, -uv.x * v_dir.y + uv.y * v_dir.x); float sd = sdRoundBox(q, vec2(0.5, mix(0.2, 0.3, u_light)), 0.25); float shape = smoothstep(0.1, 0.0, sd); a = shape * smoothstep(0.1, 0.2, v_scale) * u_inkAlpha; float h = 0.8; c = v_col < h ? mix(u_c1, u_c2, v_col / h) : mix(u_c2, u_c3, (v_col - h) / (1.0 - h)); } else { float disc = smoothstep(0.5, 0.4, length(uv)); a = disc * smoothstep(0.1, 0.2, v_scale) * mix(u_inkAlpha, u_iconAlpha, v_near); /* the back of the figure sits a little further into the ground than the front: the depth cue the size change alone lacks */ a *= 1.0 - 0.28 * v_near * clamp(-v_dir.x, 0.0, 1.0); c = mix(u_ink, u_accent, smoothstep(0.05, 0.6, v_near)); } if (a < 0.01) discard; gl_FragColor = vec4(c * a, a); } `; function compile(gl: WebGLRenderingContext, type: number, src: string) { const sh = gl.createShader(type); if (!sh) return null; gl.shaderSource(sh, src); gl.compileShader(sh); if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) { if (import.meta.env.DEV) console.error("particle-field shader:", gl.getShaderInfoLog(sh)); gl.deleteShader(sh); return null; } return sh; } /* ── Tweens, the GSAP way: retarget from wherever the value is now ── */ const easeOutCubic = (x: number) => 1 - Math.pow(1 - x, 3); class Tween { value: number; private from: number; private to: number; private t0 = 0; private dur = 1; constructor(v: number) { this.value = v; this.from = v; this.to = v; } go(to: number, dur: number, now: number) { if (to === this.to && dur === this.dur) return; this.from = this.value; this.to = to; this.dur = Math.max(1, dur); this.t0 = now; } set(v: number) { this.value = this.from = this.to = v; } tick(now: number) { const x = Math.min(1, (now - this.t0) / this.dur); this.value = this.from + (this.to - this.from) * easeOutCubic(x); return this.value; } } /** * Pixels per field unit. The hero is a unit per half its height; a * shorter band keeps roughly the hero's scale instead of squeezing the * same cloud into less height, so dot spacing, the ring and the drift * read the same on every page. */ function unitPx(w: number, h: number) { return Math.max(h / 2, w * 0.26, 1); } /** The phase the still frame is drawn at. */ const HELD_TIME = 31.0; /** How long the pointer may rest before the ring starts to wander. */ const IDLE_MS = 2800; export function mountParticleField(cv: HTMLCanvasElement, options: FieldOptions = {}): () => void { const fam0 = options.tone === "plate" ? options.plateFamily ?? "night" : options.pageFamily ?? "dawn"; const opts = { pageFamily: "dawn", plateFamily: "night", accentVar: (a: string) => `--color-${fam0}-${a}`, ...options, }; const tone = opts.tone ?? "page"; const withIcons = Boolean(opts.icons && opts.icons.length); const withCloud = opts.cloud ?? true; const restFill = opts.restFill ?? false; const tour = opts.tour ?? false; const heroShelf = opts.shelf ?? NO_SHELF; const live = opts.live ?? (!window.matchMedia("(prefers-reduced-motion: reduce)").matches && document.documentElement.dataset.motion !== "reduce"); const coarse = window.matchMedia("(pointer: coarse)").matches; const setFailed = (_f: boolean) => opts.onFail?.(); const attrs: WebGLContextAttributes = { alpha: true, premultipliedAlpha: true, antialias: false, depth: false, stencil: false, powerPreference: "low-power", }; const gl = cv.getContext("webgl", attrs) || (cv.getContext("experimental-webgl", attrs) as WebGLRenderingContext | null); if (!gl) { if (import.meta.env.DEV) console.error("particle-field: no WebGL context"); setFailed(true); return () => {}; } const vs = compile(gl, gl.VERTEX_SHADER, VERT); const fs = compile(gl, gl.FRAGMENT_SHADER, FRAG); const prog = gl.createProgram(); if (!vs || !fs || !prog) { setFailed(true); return () => {}; } gl.attachShader(prog, vs); gl.attachShader(prog, fs); gl.linkProgram(prog); if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) { if (import.meta.env.DEV) console.error("particle-field link:", gl.getProgramInfoLog(prog)); setFailed(true); return () => {}; } gl.useProgram(prog); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.clearColor(0, 0, 0, 0); /* ── Geometry ── */ /* Dots per square field unit: the hero's 8,000 over its 8.8. */ const perUnit = coarse ? 400 : 900; const morphCount = coarse ? 1600 : 2400; /* Half-extents of the cloud in field units, regrown when the canvas outgrows them. */ const domain = { w: 0, h: 0 }; const hash = rng(7); const seeds = (n: number) => { const s = new Float32Array(n * 4); for (let i = 0; i < n; i++) { s[i * 4] = hash(); // arrival delay s[i * 4 + 1] = hash(); // life phase s[i * 4 + 2] = 2 + hash() * 2; // life length, seconds s[i * 4 + 3] = hash(); // general purpose } return s; }; const buf = { cloudRest: gl.createBuffer(), cloudSeed: gl.createBuffer(), morphRest: gl.createBuffer(), morphSeed: gl.createBuffer(), morphFrom: gl.createBuffer(), morphTo: gl.createBuffer(), }; let cloudN = 0; const buildCloud = () => { const area = domain.w * 2 * domain.h * 2; const count = Math.min(16000, Math.round(perUnit * area)); const pts = poisson({ halfW: domain.w, halfH: domain.h, r: minDistFor(count, domain.w * 2, domain.h * 2), seed: 11, }); cloudN = pts.length / 2; gl.bindBuffer(gl.ARRAY_BUFFER, buf.cloudRest); gl.bufferData(gl.ARRAY_BUFFER, pts, gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, buf.cloudSeed); gl.bufferData(gl.ARRAY_BUFFER, seeds(cloudN), gl.STATIC_DRAW); }; const morphRest = poisson({ halfW: 0.5, halfH: 0.5, r: minDistFor(morphCount, 1, 1), seed: 23 }); const morphN = morphRest.length / 2; gl.bindBuffer(gl.ARRAY_BUFFER, buf.morphRest); gl.bufferData(gl.ARRAY_BUFFER, morphRest, gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, buf.morphSeed); gl.bufferData(gl.ARRAY_BUFFER, seeds(morphN), gl.STATIC_DRAW); const fromArr = new Float32Array(morphRest); const toArr = new Float32Array(morphRest); gl.bindBuffer(gl.ARRAY_BUFFER, buf.morphFrom); gl.bufferData(gl.ARRAY_BUFFER, fromArr, gl.DYNAMIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, buf.morphTo); gl.bufferData(gl.ARRAY_BUFFER, toArr, gl.DYNAMIC_DRAW); const loc = { rest: gl.getAttribLocation(prog, "a_rest"), seed: gl.getAttribLocation(prog, "a_seed"), from: gl.getAttribLocation(prog, "a_from"), to: gl.getAttribLocation(prog, "a_to"), }; gl.enableVertexAttribArray(loc.rest); gl.enableVertexAttribArray(loc.seed); gl.enableVertexAttribArray(loc.from); gl.enableVertexAttribArray(loc.to); const bindLayer = (layer: 0 | 1) => { gl.bindBuffer(gl.ARRAY_BUFFER, layer ? buf.morphRest : buf.cloudRest); gl.vertexAttribPointer(loc.rest, 2, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, layer ? buf.morphSeed : buf.cloudSeed); gl.vertexAttribPointer(loc.seed, 4, gl.FLOAT, false, 0, 0); /* the cloud never reads these; point them at something valid */ gl.bindBuffer(gl.ARRAY_BUFFER, layer ? buf.morphFrom : buf.cloudRest); gl.vertexAttribPointer(loc.from, 2, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, layer ? buf.morphTo : buf.cloudRest); gl.vertexAttribPointer(loc.to, 2, gl.FLOAT, false, 0, 0); }; /* ── Uniforms ── */ const u = (name: string) => gl.getUniformLocation(prog, name); const U = { time: u("u_time"), extent: u("u_extent"), pr: u("u_pr"), pscale: u("u_pscale"), maxPoint: u("u_maxPoint"), layer: u("u_layer"), hover: u("u_hover"), morph: u("u_morph"), pulse: u("u_pulse"), iconReady: u("u_iconReady"), fill: u("u_fill"), light: u("u_light"), ringR: u("u_ringR"), ringW: u("u_ringW"), ringW2: u("u_ringW2"), ringDisp: u("u_ringDisp"), ring: u("u_ring"), ringLag: u("u_ringLag"), zone: u("u_zone"), icon: u("u_icon"), inkAlpha: u("u_inkAlpha"), iconAlpha: u("u_iconAlpha"), c1: u("u_c1"), c2: u("u_c2"), c3: u("u_c3"), ink: u("u_ink"), accent: u("u_accent"), }; const range = gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE) as Float32Array; gl.uniform1f(U.maxPoint, range ? range[1] : 64); gl.uniform1f(U.ringW, 0.03); gl.uniform1f(U.ringW2, 0.1); gl.uniform1f(U.ringDisp, 0.5); gl.uniform1f(U.inkAlpha, 0.7); gl.uniform1f(U.iconAlpha, 0.6); gl.uniform4f(U.zone, 0, 0, -1, -1); gl.uniform4f(U.icon, 0, 0, 0.5, 0.5); gl.uniform1f(U.iconReady, 0); gl.uniform1f(U.fill, restFill ? 1 : 0); /* ── Colour ── */ const INK: Rgb = [0.34, 0.32, 0.47]; let accentName: Accent | null = null; const fam = tone === "plate" ? opts.plateFamily : opts.pageFamily; /* The reading weights, not the -soft washes: the pastels sank into the cream ground and read as white specks. These tokens invert with the mode, so the dots stay dark on light and light on dark. */ const pushPalette = () => { /* Is the ground behind this field light? The page's dawn base, or the plate's night base, after the mode has inverted them. */ const V = opts.vars ?? { ink: tone === "plate" ? `--color-${fam}-text` : `--color-${fam}-ink`, base: `--color-${fam}-base`, iris: `--color-${fam}-iris`, love: `--color-${fam}-love`, }; const [br, bg, bb] = readVar(cv, V.base, [0.98, 0.96, 0.93]); const light = 0.2126 * br + 0.7152 * bg + 0.0722 * bb > 0.5; gl.uniform1f(U.light, light ? 1 : 0); gl.uniform1f(U.inkAlpha, light ? 0.9 : 0.7); const ink = readVar(cv, V.ink, INK); gl.uniform3fv(U.ink, ink); gl.uniform3fv(U.c1, ink); gl.uniform3fv( U.c2, readVar(cv, V.iris, [0.47, 0.35, 0.64]), ); gl.uniform3fv( U.c3, readVar(cv, V.love, [0.69, 0.25, 0.42]), ); gl.uniform3fv( U.accent, accentName ? readVar(cv, opts.accentVar(accentName), ink) : ink, ); }; pushPalette(); /* ── State the frame reads ── */ const box = { left: 0, pageTop: 0, width: 1, height: 1 }; let unit = unitPx(cv.clientWidth, cv.clientHeight); const pointer = { x: 0, y: 0, inside: false }; const ring = { x: 0.3, y: 0.1 }; const ringLag = { x: 0.3, y: 0.1 }; const hover = new Tween(0); const morph = new Tween(1); let pulseT0 = -Infinity; let lastMove = -Infinity; let raf = 0; let running = false; let visible = !document.hidden; let inView = true; let lost = false; let lastNow = 0; const start = performance.now(); const measureBox = () => { const r = cv.getBoundingClientRect(); box.left = r.left; box.pageTop = r.top + window.scrollY; box.width = r.width || 1; box.height = r.height || 1; }; const size = () => { const pr = Math.min(2, window.devicePixelRatio || 1); const w = Math.max(1, Math.round(cv.clientWidth * pr)); const h = Math.max(1, Math.round(cv.clientHeight * pr)); if (cv.width !== w || cv.height !== h) { cv.width = w; cv.height = h; } gl.viewport(0, 0, w, h); unit = unitPx(cv.clientWidth, cv.clientHeight); const ex = cv.clientWidth / 2 / unit; const ey = cv.clientHeight / 2 / unit; gl.uniform2f(U.extent, ex, ey); gl.uniform1f(U.pr, pr); gl.uniform1f(U.pscale, (cv.clientWidth / 2000) * 0.9); if (ex + 0.1 > domain.w || ey + 0.1 > domain.h) { domain.w = Math.max(domain.w, ex + 0.2); domain.h = Math.max(domain.h, ey + 0.15); buildCloud(); } }; /* ── The shelf list (keep-out for the cloud) and the icon's home ── Rects are in page pixels; the canvas may sit inside a scaled composition (the hero scales its 1920×1080 artboard), so a page pixel is `scale` canvas pixels. */ let zoneEl: HTMLElement | null = null; let zoneRo: ResizeObserver | null = null; let iconEl: HTMLElement | null = null; const toField = (px: number, py: number, c: DOMRect) => { const k = unit * (c.width / Math.max(1, cv.clientWidth)); return [(px - c.left - c.width / 2) / k, (c.height / 2 - (py - c.top)) / k]; }; const pageUnit = (c: DOMRect) => unit * (c.width / Math.max(1, cv.clientWidth)); /* The hero swaps between two layouts at 1280px and rebuilds the list when it does, so a held reference goes stale: re-find it whenever the one we have has left the document. */ const adoptZone = (el: HTMLElement) => { if (zoneEl === el) return; zoneRo?.disconnect(); zoneEl = el; zoneRo = new ResizeObserver(() => measureZone()); zoneRo.observe(el); }; /* Where the icon forms: a `[data-field-icon]` box inside the field's own host if there is one (the plate marks its open upper half), otherwise centred on the shelf list. */ const findIcon = () => { const host = cv.closest("[data-field-host]"); iconEl = host?.querySelector("[data-field-icon]") ?? null; }; const measureZone = () => { if (!zoneEl || !zoneEl.isConnected) { const el = document.querySelector("[data-index-zone]"); if (el) adoptZone(el); } if (withIcons && (!iconEl || !iconEl.isConnected)) findIcon(); const c = cv.getBoundingClientRect(); if (withCloud && zoneEl && zoneEl.isConnected) { const z = zoneEl.getBoundingClientRect(); const [x0, y0] = toField(z.left, z.bottom, c); const [x1, y1] = toField(z.right, z.top, c); gl.uniform4f(U.zone, x0, y0, x1, y1); } else { gl.uniform4f(U.zone, 0, 0, -1, -1); } if (!withIcons) return; const home = iconEl && iconEl.isConnected ? iconEl : zoneEl && zoneEl.isConnected ? zoneEl : null; if (!home) { gl.uniform4f(U.icon, 0, 0, 0.5, 0.5); return; } const z = home.getBoundingClientRect(); const k = c.width / Math.max(1, cv.clientWidth); const sizePx = Math.min(440 * k, Math.max(96 * k, 0.9 * Math.min(z.width, z.height))); const [cx, cy] = toField(z.left + z.width / 2, z.top + z.height / 2, c); const s = sizePx / pageUnit(c); gl.uniform4f(U.icon, cx, cy, s, s); }; let zoneTimer = 0; const findZone = (attempt = 0) => { const el = document.querySelector("[data-index-zone]"); if (el) { adoptZone(el); measureZone(); return; } if (attempt < 8) zoneTimer = window.setTimeout(() => findZone(attempt + 1), 250); }; /* ── Icons ── */ let targets: Float32Array[] | null = null; let curIndex: number | null = null; let pending: LitShelf = heroShelf.get(); let cancelled = false; const scratch = document.createElement("canvas"); const jitter = rng(99); const jitters = new Float32Array(morphN * 2); for (let i = 0; i < jitters.length; i++) jitters[i] = jitter(); /* The icon answers the hand only: a shelf the loop lights on its own tour leaves the cloud as it is, so the gather always means "you are pointing at this". */ const applyShelf = (s: LitShelf, now: number, snap = false) => { pending = s; /* One layout read per hover change: cheap, and it means the icon always forms on the list as it is laid out right now. */ const wanted = s.index !== null && (s.held || tour); if (wanted) measureZone(); if (!wanted || s.index === null) { hover.go(0, 800, now); return; } hover.go(1, 500, now); if (!targets || s.index === curIndex) return; /* continue from wherever the last gather got to */ const m = easeOutCubic(Math.min(1, morph.value)); for (let i = 0; i < fromArr.length; i++) fromArr[i] = fromArr[i] + (toArr[i] - fromArr[i]) * m; toArr.set(targets[s.index]); gl.bindBuffer(gl.ARRAY_BUFFER, buf.morphFrom); gl.bufferSubData(gl.ARRAY_BUFFER, 0, fromArr); gl.bindBuffer(gl.ARRAY_BUFFER, buf.morphTo); gl.bufferSubData(gl.ARRAY_BUFFER, 0, toArr); curIndex = s.index; if (snap) { morph.set(1); } else { morph.set(0); morph.go(1, 600, now); pulseT0 = now; } if (s.accent !== accentName) { accentName = s.accent; pushPalette(); } }; /* ── Frames ── */ const drawFrame = (t: number, now: number) => { if (lost) return; gl.uniform1f(U.time, t); gl.uniform1f(U.ringR, 0.175 + Math.sin(t) * 0.03 + Math.cos(t * 3) * 0.02); gl.uniform2f(U.ring, ring.x, ring.y); gl.uniform2f(U.ringLag, ringLag.x, ringLag.y); gl.uniform1f(U.hover, hover.value); gl.uniform1f(U.morph, morph.value); const pulse = (now - pulseT0) / 2000; gl.uniform1f(U.pulse, pulse >= 0 && pulse < 1 ? pulse : -1); gl.clear(gl.COLOR_BUFFER_BIT); gl.uniform1f(U.layer, 0); if (withCloud) { bindLayer(0); gl.drawArrays(gl.POINTS, 0, cloudN); } if (withIcons) { gl.uniform1f(U.layer, 1); bindLayer(1); gl.drawArrays(gl.POINTS, 0, morphN); } }; const still = () => { size(); ring.x = ringLag.x = 0.3; ring.y = ringLag.y = 0.1; /* A held row still gets its icon with motion off; otherwise the frame is the plain cloud. */ const s = withIcons ? heroShelf.get() : { index: null, accent: null, held: false }; if (targets) applyShelf(s, performance.now(), true); hover.set((s.held || tour) && s.index !== null ? 1 : 0); morph.set(1); drawFrame(HELD_TIME, -Infinity); cv.classList.add("is-live"); }; const tick = (now: number) => { raf = requestAnimationFrame(tick); const t = (now - start) / 1000; const dt = Math.min(0.05, (now - lastNow) / 1000 || 0.016); lastNow = now; /* The ring drifts on its own, and only partly toward the hand: a 2%/frame lerp toward the pointer is what reads as weight. */ const wx = 0.35 * Math.sin(t * 0.19) + 0.12 * Math.sin(t * 0.47); const wy = 0.3 * Math.cos(t * 0.14) + 0.1 * Math.cos(t * 0.37); const follow = pointer.inside && now - lastMove < IDLE_MS; const tx = follow ? pointer.x + wx * 0.1 : wx * 0.6; const ty = follow ? pointer.y + wy * 0.1 : wy * 0.6; const k = 1 - Math.pow(1 - (follow ? 0.02 : 0.01), dt * 60); ring.x += (tx - ring.x) * k; ring.y += (ty - ring.y) * k; const k2 = 1 - Math.pow(1 - 0.06, dt * 60); ringLag.x += (ring.x - ringLag.x) * k2; ringLag.y += (ring.y - ringLag.y) * k2; hover.tick(now); morph.tick(now); drawFrame(t, now); cv.classList.add("is-live"); }; const sync = () => { const want = live && visible && inView; if (want && !running) { running = true; size(); lastNow = performance.now(); raf = requestAnimationFrame(tick); } else if (!want && running) { running = false; cancelAnimationFrame(raf); } if (!live) still(); }; const onMove = (e: PointerEvent) => { if (e.pointerType === "touch") return; const top = box.pageTop - window.scrollY; const nx = ((e.clientX - box.left) / box.width) * 2 - 1; const ny = -(((e.clientY - top) / box.height) * 2 - 1); if (nx < -1.05 || nx > 1.05 || ny < -1.05 || ny > 1.05) { pointer.inside = false; return; } pointer.inside = true; pointer.x = (nx * box.width) / 2 / unit; pointer.y = (ny * box.height) / 2 / unit; lastMove = e.timeStamp; }; const onVis = () => { visible = !document.hidden; sync(); }; const onMode = () => { pushPalette(); if (!running) still(); }; const onLost = (e: Event) => { e.preventDefault(); lost = true; cancelAnimationFrame(raf); setFailed(true); }; const unsubscribe = withIcons ? heroShelf.subscribe((s) => { if (live) applyShelf(s, performance.now()); else still(); }) : () => {}; let settleRaf = 0; let settleTimer = 0; const measureSettled = () => { cancelAnimationFrame(settleRaf); clearTimeout(settleTimer); settleRaf = requestAnimationFrame(() => { settleRaf = requestAnimationFrame(() => { measureBox(); measureZone(); if (!running) still(); }); }); /* and once more after the hero's own observer has re-rendered */ settleTimer = window.setTimeout(() => { measureBox(); measureZone(); if (!running) still(); }, 160); }; const ro = new ResizeObserver(() => { measureBox(); size(); measureZone(); measureSettled(); if (!running) still(); }); ro.observe(cv); const io = typeof IntersectionObserver !== "undefined" ? new IntersectionObserver(([e]) => { inView = e.isIntersecting; sync(); }) : null; io?.observe(cv); if (live) window.addEventListener("pointermove", onMove, { passive: true }); window.addEventListener("resize", measureSettled); document.addEventListener("visibilitychange", onVis); window.addEventListener("daemonmodechange", onMode); const modeMo = new MutationObserver(onMode); modeMo.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "data-mode", "data-theme", "style"] }); cv.addEventListener("webglcontextlost", onLost); /* Prepare the icons; the morph layer twinkles at rest until they land. */ (async () => { if (!withIcons) return; const svgs = opts.icons ?? []; const out: Float32Array[] = []; for (const svg of svgs) { const ink = await rasterise(svg, scratch); if (cancelled) return; out.push(targetsFor(morphRest, nearestInked(ink), (i) => jitters[i])); } if (cancelled) return; targets = out; gl.uniform1f(U.iconReady, 1); applyShelf(pending, performance.now(), true); if (!running) still(); })().catch(() => { /* No icon: the morph layer just twinkles. */ }); measureBox(); findZone(); if (withIcons) { if (live) applyShelf(heroShelf.get(), performance.now(), true); } sync(); if (import.meta.env.DEV) { (window as unknown as Record)[withIcons ? "__dmnField" : "__dmnCloud"] = { get hover() { return hover.value; }, get morph() { return morph.value; }, get index() { return curIndex; }, get ready() { return targets !== null; }, get counts() { return { cloud: cloudN, morph: morphN }; }, get ring() { return { ...ring }; }, get iconPx() { /* the icon's centre and size in CSS px, page-relative to the canvas */ const v = gl.getUniform(prog, U.icon as WebGLUniformLocation) as Float32Array; const c = cv.getBoundingClientRect(); const k = unit * (c.width / Math.max(1, cv.clientWidth)); return { x: c.left + c.width / 2 + v[0] * k, y: c.top + c.height / 2 - v[1] * k, size: v[2] * k }; }, get pointer() { return { ...pointer, box: { ...box }, lastMove }; }, set(index: number | null, accent: Accent | null) { applyShelf({ index, accent, held: true }, performance.now()); }, }; } return () => { cancelled = true; running = false; cancelAnimationFrame(raf); clearTimeout(zoneTimer); unsubscribe(); ro.disconnect(); io?.disconnect(); zoneRo?.disconnect(); window.removeEventListener("pointermove", onMove); window.removeEventListener("resize", measureSettled); cancelAnimationFrame(settleRaf); clearTimeout(settleTimer); document.removeEventListener("visibilitychange", onVis); window.removeEventListener("daemonmodechange", onMode); modeMo.disconnect(); cv.removeEventListener("webglcontextlost", onLost); Object.values(buf).forEach((b) => b && gl.deleteBuffer(b)); gl.deleteProgram(prog); gl.deleteShader(vs); gl.deleteShader(fs); }; }