/* ============================================================ *
* Lamp Field — cursor-lit grid of tiny dots (Canvas)
* ============================================================ *
* How it works:
* Cover the stage with a dense grid of tiny dots. At rest each
* dot is barely visible — just a faint hint of the grid. Track
* the pointer with a momentum-driven "ghost" position that trails
* behind, then give every dot a heat value:
* heat rises quickly when the ghost comes near and cools down
* slowly, so lit dots trail behind your cursor and fade out.
* Each dot owns a fixed color picked from the theme palette by
* a position hash, so the lit area glows in multicolor.
* An idle-energy knob dims the whole field when the cursor rests:
* stop moving and the lights gently extinguish back to the faint
* base grid; move again and they ease back up with a short
* ~100ms attack — quick, but visibly graded, never a hard pop.
* Clicking drops a triple splash into the field: three concentric
* wave trains, big → small, race outward and die away on their own.
*
* Key concepts:
* <canvas> + requestAnimationFrame — redraw every frame
* inertial glide (v *= friction) — light coasts onward, never rebounds
* distance falloff (1 - d/R)^2 — brightness decays fast
* two time constants — fast rise (0.3), slow cool (0.055)
* energy envelope (attack/grace/ramp) — graded relight, monotonic fade
* wave train (3 trailing rings) — click ripple, self-extinguishing
* CSS variables + theme:change — colors follow light/dark theme
* ============================================================ */
// ---- 1. Build the dot grid (once per resize) ----
// Dots are spaced 12px apart. Positions and per-dot data
// live in typed arrays — no per-frame object allocation.
const spacing = 12;
const cols = Math.ceil(W / spacing) + 1;
const rows = Math.ceil(H / spacing) + 1;
for (let gy = 0; gy < rows; gy++) {
for (let gx = 0; gx < cols; gx++) {
px[i] = gx * spacing + spacing / 2; // dot x
py[i] = gy * spacing + spacing / 2; // dot y
// deterministic hash 0..1 → picks this dot's palette color
hsh[i] = Math.abs(Math.sin(gx * 127.1 + gy * 311.7) * 43758.5453) % 1;
}
}
// ---- 2. Per-dot color: mono → palette blend ----
// hueRange 70%: 0% = every dot uses palette[0],
// 100% = each dot fully uses its hashed palette color.
const mono = palette[0];
const col = palette[Math.min(3, Math.floor(hsh[i] * 4))];
dotR[i] = mono[0] + (col[0] - mono[0]) * 0.7;
// (same for G and B channels)
// ---- 3. Ghost pointer with momentum (glide, no rebound) ----
// Two regimes driven by one continuous velocity:
// follow — while the pointer sends events, trail it with a
// first-order lerp. This step can never cross the target,
// so no force ever flings the ghost back (that is what
// removes the rebound).
// glide — the frame after the last event, coast onward on the
// last velocity while friction bleeds it away. The light
// keeps travelling in the SAME direction and stops.
const follow = 0.223; // lerp gain while tracking
const friction = 0.808; // speed kept per coasting frame
if (pointerMovedThisFrame) {
const nx = sx + (tx - sx) * follow;
const ny = sy + (ty - sy) * follow;
vx = nx - sx; vy = ny - sy; // remember this frame's motion
sx = nx; sy = ny;
} else {
sx += vx; sy += vy; // coast forward…
vx *= friction; vy *= friction; // …and bleed the speed away
}
// ---- 4. Heat model per dot (every frame) ----
// Spatial falloff: quadratic — bright core, fast decay at the edge.
const R = 220; // light radius in px
const d = Math.hypot(px[i] - sx, py[i] - sy);
const target = d < R ? Math.pow(1 - d / R, 2) : 0;
// Two time constants: rise fast (0.3), cool slowly (0.055).
// This is what makes lights flare up quickly but fade out lazily.
heat[i] += (target - heat[i]) * (target > heat[i] ? 0.3 : 0.055);
// ---- 5. Idle energy — a three-phase envelope ----
// ATTACK: while the pointer sends events, energy climbs toward 1
// with an ease-out lerp: energy += (1 - energy) * attackRate
// It always rises from its CURRENT value, so catching it mid-decay
// continues smoothly — there is no jump to full brightness, yet the
// ~100ms attack is quick enough to feel instant.
// HOLD: 150ms of stillness before fading may start.
// DECAY: then energy ramps linearly down to 0 over idleFade seconds
// (idleFade = 1.5s → 1500ms) — strictly
// monotonic, so resting never flickers. The heat map above is left
// alone: the field "remembers" the lit shape.
const ATTACK = 0.28; // per-frame ease-out rate → ~90% brightness ~100ms
let energy = 0;
if (pointerMovedThisFrame) {
energy += (1 - energy) * ATTACK;
} else if (now - lastMove >= 150) {
energy = Math.max(0, energy - dtMs / 1500);
}
// ---- 6. Click ripple — THREE wave trains + splash core ----
// Each pointerdown spawns FOUR things at the impact point:
// three waves {x, y, t, w} — concentric trains, big → small,
// launched 0 / 150 / 300ms apart (a negative age means the
// wave is still waiting for its delay)
// a core {x, y, t} — glowing splash centre
// WAVES gives each wave its own character: k = reach scale,
// gain = amplitude scale, delay = launch offset, travel = duration
// scale (later waves glide a touch longer), width = band scale
// (real wave trains spread as they run), gap = ring spacing (later
// waves pack tighter). No two circles are exact copies.
// The front radius comes from the wave's AGE with an ease-out
// curve, so each wave BURSTS out fast (wave 1 ~1150px/s at impact)
// and then glides to a stop — never constant-speed, never reversing.
// Amplitude also fades with travelled distance: fade falls with
// lifeT², so a wave is strongest near the impact and thins out
// long before it reaches its rest radius.
const RIP_TRAVEL = 1250; // ms for wave 1 to glide out to full radius
const RIP_GAP = 36; // px between trailing rings (wave 1)
const RIP_WIDTH = 30; // px band width of one ring (wave 1)
const RIP_RINGS = 4; // rings in each train
const WAVES = [
{ k: 1.00, gain: 1.00, delay: 0, travel: 1.00, width: 1.00, gap: 36 },
{ k: 0.70, gain: 0.72, delay: 150, travel: 1.05, width: 1.15, gap: 32 },
{ k: 0.45, gain: 0.50, delay: 300, travel: 1.10, width: 1.30, gap: 28 }
];
const reach = 480; // wave 1 comes to rest here
for (const rp of ripples) {
rp.t += dtMs;
if (rp.t < 0) continue; // delay not elapsed yet
const w = rp.w;
const travel = RIP_TRAVEL * w.travel;
if (rp.t >= travel) { ripples.splice(ripples.indexOf(rp), 1); continue; }
const reachW = reach * w.k; // later waves rest closer in
const p = Math.min(1, rp.t / travel);
const r = reachW * (1 - Math.pow(1 - p, 3)); // ease-out cubic: burst → glide
const lifeT = r / reachW;
const fade = (1 - lifeT * lifeT) * w.gain; // amplitude thins with distance
const halfW = RIP_WIDTH / 2 * w.width * (1 + 0.6 * lifeT); // band widens outward
const rel = r - dist(dot, rp); // distance behind the front
const ring = Math.floor(rel / w.gap + 0.5); // ring 0 rides the front
if (ring < 0 || ring >= RIP_RINGS) continue;
const band = 1 - smoothstep(0, halfW, Math.abs(rel - ring * w.gap));
const v = band * (1 - ring / RIP_RINGS) * fade * 0.85;
if (v > 0.02) drawDot(dot, alpha = v * peak, size = baseSize + v * 6);
}
// The splash core is the "water hammer" at the impact point: it
// flares in over ~90ms (smoothstep), then decays LINEARLY over
// coreLife = 2.5s — outliving all three waves (the last
// one ends ~1.7s in), a warm centre that fades to exactly zero:
const CORE_R = 110; // px radius of the glowing centre
const CORE_ATK = 90; // ms flare-in
for (const cp of cores) {
cp.t += dtMs;
const atk = Math.min(1, cp.t / CORE_ATK);
const env = atk * atk * (3 - 2 * atk) * (1 - cp.t / 2500);
const g = 1 - dist(dot, cp) / CORE_R; // quadratic falloff
const v = g * g * env * 0.85;
if (v > 0.02) drawDot(dot, alpha = v * peak, size = baseSize + v * 6);
}
// Both lists are independent of the cursor glow, stack freely, and
// splice themselves out at end-of-life — zero residue.
// ---- 7. Draw ----
// Base grid first (very faint), then lit dots on top.
// Radius grows mostly at high heat, so lit dots visibly swell; both
// the swell and the alpha scale with energy, so when energy reaches
// 0 every dot is exactly back at base size — no half-lit residue:
// r = baseSize + (heat*1.4 + heat^2*3.2) * energy
// alpha = min(1, heat^0.75 * (brightness/100)) * energy // brightness 90%
ctx.fillStyle = 'rgba(' + dotR[i] + ',' + dotG[i] + ',' + dotB[i] + ','
+ Math.min(1, Math.pow(heat[i], 0.75) * 0.90) * energy + ')';
ctx.arc(px[i], py[i], baseSize + (heat[i] * 1.4 + heat[i] * heat[i] * 3.2) * energy, 0, Math.PI * 2);
ctx.fill();
// ---- 8. Theme awareness ----
// Colors come from CSS variables (--anim-1..4, --anim-fg).
// Re-read them whenever the theme flips.
document.addEventListener('theme:change', () => {
palette = readPalette(); // getComputedStyle → parse rgba()
recolor(); // re-blend every dot's color
});