The showcase prompt, round 3, Gemini 4 Carbon

agent (cont.)

+31:28
  • write_file{"Content":"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\" />\n<title>CAUSTIC — Inverse Optical Foundry</title>\n<style>\n :root {\n --bg: #07080c;\n --panel: rgba(13, 15, 21, 0.78);\n --panel-strong: rgba(16, 19, 27, 0.90);\n --border: rgba(255, 255, 255, 0.09);\n --border-hi: rgba(242, 189, 116, 0.42);\n --text: #ece8df;\n --muted: rgba(236, 232, 223, 0.54);\n --faint: rgba(236, 232, 223, 0.30);\n --gold: #f2bd74;\n --gold-dim: rgba(242, 189, 116, 0.16);\n --cyan: #7fd4e6;\n --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, \"Inter\", \"Segoe UI\", Roboto, sans-serif;\n --mono: ui-monospace, \"SF Mono\", \"JetBrains Mono\", \"Cascadia Code\", Menlo, Consolas, monospace;\n }\n\n * { box-sizing: border-box; margin: 0; padding: 0; -webkit-tap-highlight-color: transparent; }\n\n html, body {\n width: 100%;\n height: 100%;\n overflow: hidden;\n background: var(--bg);\n color: var(--text);\n font-family: var(--sans);\n user-select: none;\n -webkit-user-select: none;\n }\n\n #glCanvas {\n position: fixed;\n inset: 0;\n width: 100%;\n height: 100%;\n display: block;\n touch-action: none;\n cursor: grab;\n }\n #glCanvas.dragging-lamp { cursor: crosshair; }\n #glCanvas.dragging-orbit { cursor: grabbing; }\n\n /* Subtle HUD Layer */\n .hud {\n position: fixed;\n inset: 0;\n pointer-events: none;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n padding: 14px 16px;\n z-index: 10;\n }\n\n .top-bar {\n display: flex;\n align-items: flex-start;\n justify-content: space-between;\n gap: 12px;\n }\n\n .brand-block {\n pointer-events: auto;\n display: flex;\n flex-direction: column;\n gap: 4px;\n background: var(--panel);\n backdrop-filter: blur(16px);\n -webkit-backdrop-filter: blur(16px);\n border: 1px solid var(--border);\n border-radius: 10px;\n padding: 8px 12px;\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.42);\n }\n\n .brand-row {\n display: flex;\n align-items: baseline;\n gap: 9px;\n }\n\n .brand-title {\n font-size: 12px;\n font-weight: 650;\n letter-spacing: 0.18em;\n color: var(--text);\n }\n\n .brand-sub {\n font-family: var(--mono);\n font-size: 10px;\n letter-spacing: 0.06em;\n color: var(--muted);\n }\n\n .telemetry {\n font-family: var(--mono);\n font-size: 10px;\n font-variant-numeric: tabular-nums;\n color: var(--muted);\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 8px;\n }\n\n .telemetry .dot {\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: var(--gold);\n box-shadow: 0 0 8px var(--gold);\n display: inline-block;\n }\n .telemetry.solving .dot {\n background: var(--cyan);\n box-shadow: 0 0 10px var(--cyan);\n }\n\n .top-actions {\n pointer-events: auto;\n display: flex;\n align-items: center;\n gap: 6px;\n flex-wrap: wrap;\n justify-content: flex-end;\n }\n\n button, select {\n font-family: var(--sans);\n font-size: 11px;\n font-weight: 500;\n color: var(--text);\n background: var(--panel);\n backdrop-filter: blur(16px);\n -webkit-backdrop-filter: blur(16px);\n border: 1px solid var(--border);\n border-radius: 8px;\n padding: 6px 10px;\n cursor: pointer;\n transition: border-color 0.16s ease, background 0.16s ease, color 0.16s ease, transform 0.1s ease;\n display: inline-flex;\n align-items: center;\n gap: 5px;\n white-space: nowrap;\n }\n\n button:hover, select:hover {\n border-color: rgba(255, 255, 255, 0.22);\n background: rgba(26, 30, 42, 0.86);\n }\n\n button:active { transform: translateY(1px); }\n\n button.active {\n background: var(--gold-dim);\n border-color: var(--border-hi);\n color: #ffe0b2;\n }\n\n button.cyan-active {\n background: rgba(127, 212, 230, 0.15);\n border-color: rgba(127, 212, 230, 0.45);\n color: #c8f1fa;\n }\n\n /* Floating Sculpt / Loupe Card */\n .loupe-card {\n pointer-events: auto;\n position: fixed;\n right: 16px;\n top: 58px;\n width: 196px;\n background: var(--panel-strong);\n backdrop-filter: blur(20px);\n -webkit-backdrop-filter: blur(20px);\n border: 1px solid var(--border);\n border-radius: 12px;\n padding: 9px;\n box-shadow: 0 14px 40px rgba(0, 0, 0, 0.55);\n display: flex;\n flex-direction: column;\n gap: 7px;\n z-index: 15;\n transition: width 0.22s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.2s ease;\n }\n\n .loupe-card.expanded {\n width: 244px;\n border-color: var(--border-hi);\n }\n\n .loupe-card.collapsed .loupe-body {\n display: none;\n }\n .loupe-card.collapsed {\n width: auto;\n padding: 6px 10px;\n }\n\n .loupe-head {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 6px;\n }\n\n .loupe-tabs {\n display: flex;\n gap: 3px;\n background: rgba(255, 255, 255, 0.04);\n padding: 2px;\n border-radius: 6px;\n }\n\n .loupe-tabs button {\n padding: 3px 7px;\n font-size: 10px;\n border: none;\n background: transparent;\n border-radius: 5px;\n color: var(--muted);\n backdrop-filter: none;\n }\n .loupe-tabs button.active {\n background: rgba(242, 189, 116, 0.2);\n color: #ffe2b8;\n }\n\n .loupe-toggle-btn {\n padding: 2px 6px;\n font-size: 10px;\n border: none;\n background: transparent;\n color: var(--muted);\n }\n\n .loupe-body {\n display: flex;\n flex-direction: column;\n gap: 7px;\n }\n\n .pad-wrap {\n position: relative;\n width: 100%;\n aspect-ratio: 1 / 1;\n border-radius: 8px;\n overflow: hidden;\n border: 1px solid rgba(255, 255, 255, 0.11);\n background: #06070a;\n }\n\n #padCanvas {\n width: 100%;\n height: 100%;\n display: block;\n touch-action: none;\n cursor: crosshair;\n }\n\n .pad-badge {\n position: absolute;\n left: 6px;\n bottom: 5px;\n font-family: var(--mono);\n font-size: 9px;\n color: rgba(255, 255, 255, 0.55);\n background: rgba(6, 7, 10, 0.72);\n padding: 2px 5px;\n border-radius: 4px;\n pointer-events: none;\n }\n\n .sculpt-tools {\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n\n .tool-row {\n display: flex;\n gap: 4px;\n align-items: center;\n }\n\n .tool-row button {\n flex: 1;\n justify-content: center;\n padding: 4px 6px;\n font-size: 10px;\n }\n\n .text-input-row {\n display: flex;\n gap: 4px;\n }\n\n .text-input-row input {\n flex: 1;\n min-width: 0;\n background: rgba(0, 0, 0, 0.45);\n border: 1px solid var(--border);\n border-radius: 6px;\n padding: 4px 7px;\n color: var(--text);\n font-family: var(--mono);\n font-size: 11px;\n outline: none;\n }\n .text-input-row input:focus {\n border-color: var(--border-hi);\n }\n\n /* Bottom Instrument Dock */\n .bottom-dock-wrap {\n display: flex;\n justify-content: center;\n align-items: flex-end;\n width: 100%;\n }\n\n .bottom-dock {\n pointer-events: auto;\n background: var(--panel);\n backdrop-filter: blur(18px);\n -webkit-backdrop-filter: blur(18px);\n border: 1px solid var(--border);\n border-radius: 12px;\n padding: 8px 10px;\n box-shadow: 0 12px 38px rgba(0, 0, 0, 0.55);\n display: flex;\n flex-direction: column;\n gap: 7px;\n max-width: 100%;\n }\n\n .dock-row {\n display: flex;\n align-items: center;\n gap: 6px;\n flex-wrap: wrap;\n justify-content: center;\n }\n\n .dock-group {\n display: flex;\n align-items: center;\n gap: 4px;\n padding: 0 4px;\n }\n\n .sep {\n width: 1px;\n height: 18px;\n background: var(--border);\n margin: 0 2px;\n }\n\n .group-label {\n font-family: var(--mono);\n font-size: 9.5px;\n letter-spacing: 0.06em;\n text-transform: uppercase;\n color: var(--faint);\n margin-right: 3px;\n }\n\n .slider-pill {\n display: inline-flex;\n align-items: center;\n gap: 7px;\n background: rgba(255, 255, 255, 0.035);\n border: 1px solid var(--border);\n border-radius: 8px;\n padding: 4px 9px;\n font-family: var(--mono);\n font-size: 10px;\n color: var(--muted);\n }\n\n input[type=\"range\"] {\n -webkit-appearance: none;\n appearance: none;\n width: 84px;\n height: 3px;\n background: rgba(255, 255, 255, 0.16);\n border-radius: 2px;\n outline: none;\n cursor: pointer;\n }\n input[type=\"range\"]::-webkit-slider-thumb {\n -webkit-appearance: none;\n width: 12px;\n height: 12px;\n border-radius: 50%;\n background: var(--gold);\n border: 2px solid #161821;\n box-shadow: 0 0 8px rgba(242, 189, 116, 0.65);\n }\n\n select {\n padding: 4px 8px;\n font-family: var(--mono);\n font-size: 10px;\n background-color: rgba(20, 23, 32, 0.92);\n }\n\n /* Subtle interaction hint that fades after first interaction */\n .gesture-hint {\n position: fixed;\n left: 18px;\n bottom: 98px;\n font-family: var(--mono);\n font-size: 10px;\n color: var(--muted);\n background: rgba(10, 12, 17, 0.66);\n border: 1px solid rgba(255, 255, 255, 0.07);\n padding: 5px 9px;\n border-radius: 7px;\n pointer-events: none;\n transition: opacity 0.5s ease;\n }\n .gesture-hint.hidden { opacity: 0; }\n\n @media (max-width: 760px) {\n .hud { padding: 10px; }\n .brand-sub { display: none; }\n .loupe-card {\n top: 54px;\n right: 10px;\n width: 152px;\n }\n .loupe-card.expanded { width: 198px; }\n .sep { display: none; }\n .gesture-hint { display: none; }\n input[type=\"range\"] { width: 64px; }\n button, select { padding: 5px 8px; font-size: 10.5px; }\n }\n</style>\n</head>\n<body>\n<canvas id=\"glCanvas\"></canvas>\n\n<div class=\"hud\">\n <div class=\"top-bar\">\n <div class=\"brand-block\">\n <div class=\"brand-row\">\n <span class=\"brand-title\">CAUSTIC</span>\n <span class=\"brand-sub\">MONGE–AMPÈRE OPTICS · EXACT 3D SNELL</span>\n </div>\n <div class=\"telemetry\" id=\"telemetryBar\">\n <span class=\"dot\"></span>\n <span id=\"statRays\">512K BEAMS</span>\n <span>·</span>\n <span id=\"statRelief\">RELIEF 4.6 mm</span>\n <span>·</span>\n <span id=\"statFocus\">ALIGN 99%</span>\n <span>·</span>\n <span id=\"statSolve\">PDE 120 ms</span>\n </div>\n </div>\n\n <div class=\"top-actions\">\n <button id=\"btnAlign\" title=\"Glide point lamp back to optical design axis\">◎ Align Light</button>\n <button id=\"btnAudio\" title=\"Toggle crystalline optical harmonic synthesis\">♪ Sound Off</button>\n <button id=\"btnStl\" title=\"Download watertight binary 3D .STL lens mesh (100×100mm)\">⬇ Lens .STL</button>\n </div>\n </div>\n\n <div class=\"gesture-hint\" id=\"gestureHint\">\n Drag lamp or stage to steer light · Drag upper frame to orbit 3D · Sketch in pad to carve glass\n </div>\n\n <div class=\"bottom-dock-wrap\">\n <div class=\"bottom-dock\">\n <div class=\"dock-row\">\n <div class=\"dock-group\" id=\"presetGroup\">\n <span class=\"group-label\">Lens</span>\n <button data-preset=\"astrolabe\" class=\"active\">Astrolabe</button>\n <button data-preset=\"nautilus\">Nautilus</button>\n <button data-preset=\"saturn\">Saturn</button>\n <button data-preset=\"crane\">Crane</button>\n <button data-preset=\"lorenz\">Lorenz</button>\n <button data-preset=\"custom\" id=\"btnCustomPreset\">✎ Draw / Type</button>\n </div>\n <div class=\"sep\"></div>\n <div class=\"dock-group\">\n <span class=\"group-label\">View</span>\n <button data-cam=\"studio\" class=\"active\">3D Bench</button>\n <button data-cam=\"profile\">Glass Profile</button>\n <button data-cam=\"top\">Overhead</button>\n </div>\n </div>\n\n <div class=\"dock-row\">\n <div class=\"slider-pill\" title=\"Vertical distance between sculpted glass lens and stone stage\">\n <span>Focal Z</span>\n <input type=\"range\" id=\"focalSlider\" min=\"0.45\" max=\"1.65\" step=\"0.005\" value=\"1.00\" />\n <span id=\"focalVal\">110 mm</span>\n </div>\n\n <select id=\"glassSelect\" title=\"Optical material index of refraction & Abbe chromatic dispersion\">\n <option value=\"bk7\" selected>Crown BK7 (n=1.52)</option>\n <option value=\"silica\">Fused Silica (n=1.46)</option>\n <option value=\"flint\">Dense Flint SF11 (n=1.78)</option>\n <option value=\"diamond\">Diamond (n=2.42)</option>\n </select>\n <button id=\"btnRegrind\" style=\"display:none\" class=\"cyan-active\" title=\"Re-solve PDE lens curvature for this refractive index\">↻ Re-grind</button>\n\n <div class=\"sep\"></div>\n\n <div class=\"dock-group\">\n <button id=\"btnRays\" class=\"cyan-active\" title=\"Show 3D Snell refraction laser slice through the glass\">Ray Sheet</button>\n <button id=\"btnGrid\" title=\"Show Optimal Transport (Brenier) equal-flux grid deformation\">Photon Grid</button>\n <button id=\"btnInterf\" title=\"Show laser Mach-Zehnder thickness interference fringes on glass\">Interferogram</button>\n <button id=\"btnCompare\" title=\"Compare absorptive stencil mask (92% light lost) vs lossless refractive lens\">Mask vs. Lens</button>\n </div>\n </div>\n </div>\n </div>\n</div>\n\n<!-- Floating Target & Glass Relief Sculptor Loupe -->\n<div class=\"loupe-card\" id=\"loupeCard\">\n <div class=\"loupe-head\">\n <div class=\"loupe-tabs\">\n <button id=\"tabTarget\" class=\"active\">Target I(x,y)</button>\n <button id=\"tabHeight\">Glass h(x,y)</button>\n </div>\n <button class=\"loupe-toggle-btn\" id=\"btnToggleLoupe\" title=\"Minimize/Expand Pad\">–</button>\n </div>\n <div class=\"loupe-body\">\n <div class=\"pad-wrap\">\n <canvas id=\"padCanvas\" width=\"256\" height=\"256\"></canvas>\n <div class=\"pad-badge\" id=\"padBadge\">Draw to carve lens</div>\n </div>\n <div class=\"sculpt-tools\">\n <div class=\"tool-row\">\n <button id=\"btnBrushDraw\" class=\"active\">✎ Glow Brush</button>\n <button id=\"btnBrushErase\">⌫ Erase</button>\n <button id=\"btnPadClear\">Clear</button>\n </div>\n <div class=\"text-input-row\">\n <input type=\"text\" id=\"glyphInput\" maxlength=\"9\" placeholder=\"Type word / symbol…\" />\n <button id=\"btnCarveText\">Carve</button>\n </div>\n </div>\n </div>\n</div>\n\n<script>\n(() => {\n \"use strict\";\n\n // ============================================================================\n // 1. INLINE WEB WORKER: MULTISCALE MOSER–SNELL OPTIMAL TRANSPORT PDE SOLVER\n // Solves nabla^2 psi = I_sim - I_target + Exact 3D Inverse Snell's Law\n // using radix-2 Makhoul 2D DCT-II Neumann Poisson on 128x128 -> 256x256.\n // ============================================================================\n const WORKER_SOURCE = `\n \"use strict\";\n class DCT2D {\n constructor(N) {\n this.N = N;\n this.bitRev = new Uint32Array(N);\n const bits = Math.log2(N) | 0;\n for (let i = 0; i < N; i++) {\n let r = 0, x = i;\n for (let b = 0; b < bits; b++) { r = (r << 1) | (x & 1); x >>= 1; }\n this.bitRev[i] = r;\n }\n this.cosTab = new Float32Array(N / 2);\n this.sinTab = new Float32Array(N / 2);\n for (let k = 0; k < N / 2; k++) {\n const ang = -2 * Math.PI * k / N;\n this.cosTab[k] = Math.cos(ang);\n this.sinTab[k] = Math.sin(ang);\n }\n this.dctCos = new Float32Array(N);\n this.dctSin = new Float32Array(N);\n for (let k = 0; k < N; k++) {\n const ang = -Math.PI * k / (2 * N);\n this.dctCos[k] = Math.cos(ang);\n this.dctSin[k] = Math.sin(ang);\n }\n this.eig1D = new Float32Array(N);\n for (let k = 0; k < N; k++) {\n this.eig1D[k] = 2 * Math.cos(Math.PI * k / N) - 2;\n }\n this.re = new Float32Array(N);\n this.im = new Float32Array(N);\n this.tmp = new Float32Array(N * N);\n }\n\n fft(re, im, invert) {\n const N = this.N, bitRev = this.bitRev;\n for (let i = 0; i < N; i++) {\n const j = bitRev[i];\n if (i < j) {\n let t = re[i]; re[i] = re[j]; re[j] = t;\n t = im[i]; im[i] = im[j]; im[j] = t;\n }\n }\n const sign = invert ? -1 : 1;\n for (let len = 2; len <= N; len <<= 1) {\n const half = len >> 1, step = N / len;\n for (let i = 0; i < N; i += len) {\n for (let j = 0; j < half; j++) {\n const idx = j * step;\n const wr = this.cosTab[idx], wi = sign * this.sinTab[idx];\n const uRe = re[i + j], uIm = im[i + j];\n const vRe = re[i + j + half] * wr - im[i + j + half] * wi;\n const vIm = re[i + j + half] * wi + im[i + j + half] * wr;\n re[i + j] = uRe + vRe; im[i + j] = uIm + vIm;\n re[i + j + half] = uRe - vRe; im[i + j + half] = uIm - vIm;\n }\n }\n }\n if (invert) {\n const invN = 1 / N;\n for (let i = 0; i < N; i++) { re[i] *= invN; im[i] *= invN; }\n }\n }\n\n dct1d(src, offset, stride, dst, dOffset, dStride) {\n const N = this.N, half = N >> 1, re = this.re, im = this.im;\n for (let i = 0; i < half; i++) {\n re[i] = src[offset + (2 * i) * stride];\n re[N - 1 - i] = src[offset + (2 * i + 1) * stride];\n im[i] = 0; im[N - 1 - i] = 0;\n }\n this.fft(re, im, false);\n for (let k = 0; k < N; k++) {\n dst[dOffset + k * dStride] = 2 * (re[k] * this.dctCos[k] - im[k] * this.dctSin[k]);\n }\n }\n\n idct1d(src, offset, stride, dst, dOffset, dStride) {\n const N = this.N, half = N >> 1, re = this.re, im = this.im;\n re[0] = src[offset] * 0.5; im[0] = 0;\n for (let k = 1; k < N; k++) {\n const a = 0.5 * src[offset + k * stride];\n const b = -0.5 * src[offset + (N - k) * stride];\n const cs = this.dctCos[k], sn = -this.dctSin[k];\n re[k] = a * cs - b * sn;\n im[k] = a * sn + b * cs;\n }\n this.fft(re, im, true);\n for (let i = 0; i < half; i++) {\n dst[dOffset + (2 * i) * dStride] = re[i];\n dst[dOffset + (2 * i + 1) * dStride] = re[N - 1 - i];\n }\n }\n\n solvePoisson(rhs, out) {\n const N = this.N, tmp = this.tmp, eig = this.eig1D;\n for (let y = 0; y < N; y++) this.dct1d(rhs, y * N, 1, tmp, y * N, 1);\n for (let x = 0; x < N; x++) this.dct1d(tmp, x, N, out, x, N);\n out[0] = 0;\n for (let y = 0; y < N; y++) {\n const ey = eig[y];\n for (let x = 0; x < N; x++) {\n if (x === 0 && y === 0) continue;\n out[y * N + x] /= (eig[x] + ey);\n }\n }\n for (let x = 0; x < N; x++) this.idct1d(out, x, N, tmp, x, N);\n for (let y = 0; y < N; y++) this.idct1d(tmp, y * N, 1, out, y * N, 1);\n }\n\n gaussianBlur(src, out, sigma) {\n if (sigma <= 0) { out.set(src); return; }\n const N = this.N, tmp = this.tmp;\n for (let y = 0; y < N; y++) this.dct1d(src, y * N, 1, tmp, y * N, 1);\n for (let x = 0; x < N; x++) this.dct1d(tmp, x, N, out, x, N);\n const sigScale = 0.5 * sigma * sigma * (Math.PI * Math.PI) / (N * N);\n for (let y = 0; y < N; y++) {\n for (let x = 0; x < N; x++) {\n out[y * N + x] *= Math.exp(-sigScale * (x * x + y * y));\n }\n }\n for (let x = 0; x < N; x++) this.idct1d(out, x, N, tmp, x, N);\n for (let y = 0; y < N; y++) this.idct1d(tmp, y * N, 1, out, y * N, 1);\n }\n }\n\n function createLevel(N) {\n return {\n N, dct: new DCT2D(N), dx: 2.0 / N,\n IinX: new Float32Array(N * N), IinY: new Float32Array(N * N), IinZ: new Float32Array(N * N),\n rho0: new Float32Array(N * N), sumRho0: 0,\n Isim: new Float32Array(N * N), targBlur: new Float32Array(N * N),\n rhs: new Float32Array(N * N), psi: new Float32Array(N * N),\n gpX: new Float32Array(N * N), gpY: new Float32Array(N * N),\n rX: new Float32Array(N * N), rY: new Float32Array(N * N),\n desX: new Float32Array(N * N), desY: new Float32Array(N * N),\n gx: new Float32Array(N * N), gy: new Float32Array(N * N)\n };\n }\n\n function updateIncidentRays(lv, F, T_glass, nGlass, Z_light) {\n const N = lv.N;\n lv.F = F; lv.nGlass = nGlass;\n let sum = 0;\n for (let y = 0; y < N; y++) {\n const py = ((y + 0.5) / N) * 2 - 1;\n for (let x = 0; x < N; x++) {\n const px = ((x + 0.5) / N) * 2 - 1;\n const dz = -(Z_light - (F + T_glass));\n const len = Math.hypot(px, py, dz);\n const ix = px / len, iy = py / len, iz = dz / len;\n const eta = 1.0 / nGlass, cosI = -iz;\n const idx = y * N + x;\n lv.IinX[idx] = eta * ix;\n lv.IinY[idx] = eta * iy;\n lv.IinZ[idx] = -Math.sqrt(Math.max(1e-6, 1 - eta * eta * (1 - cosI * cosI)));\n const flux = Math.pow(cosI, 3);\n lv.rho0[idx] = flux;\n sum += flux;\n }\n }\n lv.sumRho0 = sum;\n }\n\n function solveInverseSnellH(lv, desX, desY, h) {\n const { N, dx, F, nGlass, IinX, IinY, IinZ, gx, gy, rhs, dct } = lv;\n for (let y = 0; y < N; y++) {\n const py = ((y + 0.5) / N) * 2 - 1;\n for (let x = 0; x < N; x++) {\n const i = y * N + x;\n const px = ((x + 0.5) / N) * 2 - 1;\n const pz = F + h[i];\n const dxP = (desX[i] / N) * 2 - 1 - px;\n const dyP = (desY[i] / N) * 2 - 1 - py;\n const dzP = -pz;\n const invL = 1.0 / Math.hypot(dxP, dyP, dzP);\n const Vx = dxP * invL - nGlass * IinX[i];\n const Vy = dyP * invL - nGlass * IinY[i];\n const Vz = dzP * invL - nGlass * IinZ[i];\n gx[i] = -Vx / Vz;\n gy[i] = -Vy / Vz;\n }\n }\n for (let y = 0; y < N; y++) {\n for (let x = 0; x < N; x++) {\n const fr = (x < N - 1) ? 0.5 * (gx[y * N + x] + gx[y * N + x + 1]) : 0;\n const fl = (x > 0) ? 0.5 * (gx[y * N + x - 1] + gx[y * N + x]) : 0;\n const ft = (y < N - 1) ? 0.5 * (gy[y * N + x] + gy[(y + 1) * N + x]) : 0;\n const fb = (y > 0) ? 0.5 * (gy[(y - 1) * N + x] + gy[y * N + x]) : 0;\n rhs[y * N + x] = (fr - fl + ft - fb) * dx;\n }\n }\n dct.solvePoisson(rhs, h);\n }\n\n function traceSplatFast(lv, h) {\n const { N, dx, F, nGlass, IinX, IinY, IinZ, rho0, sumRho0, Isim, rX, rY } = lv;\n Isim.fill(0);\n for (let y = 0; y < N; y++) {\n for (let x = 0; x < N; x++) {\n const idx = y * N + x;\n const hx = (x > 0 && x < N - 1) ? (h[idx + 1] - h[idx - 1]) / (2 * dx)\n : (x === 0 ? (h[idx + 1] - h[idx]) / dx : (h[idx] - h[idx - 1]) / dx);\n const hy = (y > 0 && y < N - 1) ? (h[idx + N] - h[idx - N]) / (2 * dx)\n : (y === 0 ? (h[idx + N] - h[idx]) / dx : (h[idx] - h[idx - N]) / dx);\n const invN = 1.0 / Math.sqrt(hx * hx + hy * hy + 1.0);\n const nx = -hx * invN, ny = -hy * invN, nz = invN;\n const ix = IinX[idx], iy = IinY[idx], iz = IinZ[idx];\n const cosI = -(ix * nx + iy * ny + iz * nz);\n const k = 1.0 - nGlass * nGlass * (1.0 - cosI * cosI);\n const s = nGlass * cosI - Math.sqrt(Math.max(1e-6, k));\n const tx = nGlass * ix + s * nx, ty = nGlass * iy + s * ny, tz = nGlass * iz + s * nz;\n const px = ((x + 0.5) / N) * 2 - 1, py = ((y + 0.5) / N) * 2 - 1, pz = F + h[idx];\n const t = -pz / tz;\n rX[idx] = ((px + t * tx) * 0.5 + 0.5) * N;\n rY[idx] = ((py + t * ty) * 0.5 + 0.5) * N;\n }\n }\n for (let y = 0; y < N - 1; y++) {\n for (let x = 0; x < N - 1; x++) {\n const i00 = y * N + x, i10 = i00 + 1, i01 = i00 + N, i11 = i01 + 1;\n const x00 = rX[i00], y00 = rY[i00], x10 = rX[i10], y10 = rY[i10];\n const x01 = rX[i01], y01 = rY[i01], x11 = rX[i11], y11 = rY[i11];\n const flux = 0.25 * (rho0[i00] + rho0[i10] + rho0[i01] + rho0[i11]);\n const span = Math.max(Math.abs(x11 - x00), Math.abs(y11 - y00), Math.abs(x10 - x01), Math.abs(y10 - y01));\n const subs = span > 3.5 ? (span > 7 ? 5 : 3) : 2;\n const wSub = flux / (subs * subs);\n for (let sy = 0; sy < subs; sy++) {\n const v = (sy + 0.5) / subs, mv = 1 - v;\n for (let sx = 0; sx < subs; sx++) {\n const u = (sx + 0.5) / subs, mu = 1 - u;\n const px = Math.max(0, Math.min(N - 1.001, mu * mv * x00 + u * mv * x10 + mu * v * x01 + u * v * x11 - 0.5));\n const py = Math.max(0, Math.min(N - 1.001, mu * mv * y00 + u * mv * y10 + mu * v * y01 + u * v * y11 - 0.5));\n const ix = px | 0, iy = py | 0, fx = px - ix, fy = py - iy;\n const base = iy * N + ix;\n Isim[base] += wSub * (1 - fx) * (1 - fy);\n Isim[base + 1] += wSub * fx * (1 - fy);\n Isim[base + N] += wSub * (1 - fx) * fy;\n Isim[base + N + 1] += wSub * fx * fy;\n }\n }\n }\n }\n let s = 0;\n for (let i = 0; i < N * N; i++) s += Isim[i];\n if (s > 0) { const sc = sumRho0 / s; for (let i = 0; i < N * N; i++) Isim[i] *= sc; }\n }\n\n function bSample(arr, N, gxPos, gyPos) {\n const px = Math.max(0, Math.min(N - 1.001, gxPos - 0.5));\n const py = Math.max(0, Math.min(N - 1.001, gyPos - 0.5));\n const ix = px | 0, iy = py | 0, fx = px - ix, fy = py - iy;\n const row = iy * N + ix;\n return (1 - fx) * (1 - fy) * arr[row] + fx * (1 - fy) * arr[row + 1] +\n (1 - fx) * fy * arr[row + N] + fx * fy * arr[row + N + 1];\n }\n\n const lv128 = createLevel(128);\n const lv256 = createLevel(256);\n\n self.onmessage = (e) => {\n const { id, target256, F, T_glass, nGlass, Z_light } = e.data;\n const t0 = performance.now();\n updateIncidentRays(lv128, F, T_glass, nGlass, Z_light);\n updateIncidentRays(lv256, F, T_glass, nGlass, Z_light);\n\n const N = 128;\n const targ128 = new Float32Array(N * N);\n let sumT128 = 0;\n for (let y = 0; y < N; y++) {\n for (let x = 0; x < N; x++) {\n const i0 = (2 * y) * 256 + (2 * x);\n // Enforce clean C^2 ambient floor & soft aperture margin so boundary stays diffeomorphic\n const u = (x + 0.5) / N * 2 - 1, v = (y + 0.5) / N * 2 - 1;\n const edge = Math.max(Math.abs(u), Math.abs(v));\n const wEdge = edge > 0.85 ? Math.max(0, 1 - (edge - 0.85) / 0.13) : 1.0;\n let raw = 0.25 * (target256[i0] + target256[i0 + 1] + target256[i0 + 256] + target256[i0 + 257]);\n raw = 0.032 + Math.max(0, raw - 0.032) * (wEdge * wEdge);\n targ128[y * N + x] = raw;\n sumT128 += raw;\n }\n }\n const sc128 = lv128.sumRho0 / sumT128;\n for (let i = 0; i < N * N; i++) targ128[i] *= sc128;\n\n const h128 = new Float32Array(N * N);\n for (let y = 0; y < N; y++) {\n for (let x = 0; x < N; x++) {\n lv128.desX[y * N + x] = x + 0.5;\n lv128.desY[y * N + x] = y + 0.5;\n }\n }\n solveInverseSnellH(lv128, lv128.desX, lv128.desY, h128);\n solveInverseSnellH(lv128, lv128.desX, lv128.desY, h128);\n\n const sigmas = [7.0, 4.2, 2.5, 1.4, 0.7, 0.0, 0.0, 0.0, 0.0];\n const meanI = lv128.sumRho0 / (N * N);\n for (let iter = 0; iter < sigmas.length; iter++) {\n const sig = sigmas[iter];\n lv128.dct.gaussianBlur(targ128, lv128.targBlur, sig);\n traceSplatFast(lv128, h128);\n if (sig > 0.2) lv128.dct.gaussianBlur(lv128.Isim, lv128.Isim, sig * 0.45);\n for (let i = 0; i < N * N; i++) lv128.rhs[i] = lv128.Isim[i] - lv128.targBlur[i];\n lv128.dct.solvePoisson(lv128.rhs, lv128.psi);\n for (let y = 0; y < N; y++) {\n const ym = Math.max(0, y - 1), yp = Math.min(N - 1, y + 1), dyS = yp - ym;\n for (let x = 0; x < N; x++) {\n const xm = Math.max(0, x - 1), xp = Math.min(N - 1, x + 1), dxS = xp - xm;\n lv128.gpX[y * N + x] = (lv128.psi[y * N + xp] - lv128.psi[y * N + xm]) / dxS;\n lv128.gpY[y * N + x] = (lv128.psi[yp * N + x] - lv128.psi[ym * N + x]) / dyS;\n }\n }\n for (let i = 0; i < N * N; i++) {\n const rx = lv128.rX[i], ry = lv128.rY[i];\n const denom = Math.max(0.08 * meanI, 0.5 * (bSample(lv128.Isim, N, rx, ry) + bSample(lv128.targBlur, N, rx, ry)));\n lv128.desX[i] = Math.max(0.5, Math.min(N - 0.5, rx + 0.80 * (bSample(lv128.gpX, N, rx, ry) / denom)));\n lv128.desY[i] = Math.max(0.5, Math.min(N - 0.5, ry + 0.80 * (bSample(lv128.gpY, N, rx, ry) / denom)));\n }\n solveInverseSnellH(lv128, lv128.desX, lv128.desY, h128);\n }\n\n const N2 = 256;\n const h256 = new Float32Array(N2 * N2);\n for (let y = 0; y < N2; y++) {\n const gy = (y + 0.5) * 0.5;\n for (let x = 0; x < N2; x++) {\n h256[y * N2 + x] = bSample(h128, N, (x + 0.5) * 0.5, gy);\n }\n }\n const targ256 = new Float32Array(N2 * N2);\n let sumT2 = 0;\n for (let y = 0; y < N2; y++) {\n const v = (y + 0.5) / N2 * 2 - 1;\n for (let x = 0; x < N2; x++) {\n const u = (x + 0.5) / N2 * 2 - 1;\n const edge = Math.max(Math.abs(u), Math.abs(v));\n const wEdge = edge > 0.85 ? Math.max(0, 1 - (edge - 0.85) / 0.13) : 1.0;\n const idx = y * N2 + x;\n const raw = 0.032 + Math.max(0, target256[idx] - 0.032) * (wEdge * wEdge);\n targ256[idx] = raw;\n sumT2 += raw;\n }\n }\n const sc2 = lv256.sumRho0 / sumT2;\n for (let i = 0; i < N2 * N2; i++) targ256[i] *= sc2;\n const meanI2 = lv256.sumRho0 / (N2 * N2);\n\n for (let iter = 0; iter < 3; iter++) {\n traceSplatFast(lv256, h256);\n for (let i = 0; i < N2 * N2; i++) lv256.rhs[i] = lv256.Isim[i] - targ256[i];\n lv256.dct.solvePoisson(lv256.rhs, lv256.psi);\n for (let y = 0; y < N2; y++) {\n const ym = Math.max(0, y - 1), yp = Math.min(N2 - 1, y + 1), dyS = yp - ym;\n for (let x = 0; x < N2; x++) {\n const xm = Math.max(0, x - 1), xp = Math.min(N2 - 1, x + 1), dxS = xp - xm;\n lv256.gpX[y * N2 + x] = (lv256.psi[y * N2 + xp] - lv256.psi[y * N2 + xm]) / dxS;\n lv256.gpY[y * N2 + x] = (lv256.psi[yp * N2 + x] - lv256.psi[ym * N2 + x]) / dyS;\n }\n }\n for (let i = 0; i < N2 * N2; i++) {\n const rx = lv256.rX[i], ry = lv256.rY[i];\n const denom = Math.max(0.06 * meanI2, 0.5 * (bSample(lv256.Isim, N2, rx, ry) + bSample(targ256, N2, rx, ry)));\n lv256.desX[i] = Math.max(0.5, Math.min(N2 - 0.5, rx + 0.75 * (bSample(lv256.gpX, N2, rx, ry) / denom)));\n lv256.desY[i] = Math.max(0.5, Math.min(N2 - 0.5, ry + 0.75 * (bSample(lv256.gpY, N2, rx, ry) / denom)));\n }\n solveInverseSnellH(lv256, lv256.desX, lv256.desY, h256);\n }\n\n let minH = Infinity, maxH = -Infinity;\n for (let i = 0; i < N2 * N2; i++) {\n if (h256[i] < minH) minH = h256[i];\n if (h256[i] > maxH) maxH = h256[i];\n }\n const solveMs = performance.now() - t0;\n self.postMessage({\n id,\n h256,\n minH,\n maxH,\n reliefMm: (maxH - minH) * 50.0, // 2.0 normalized units == 100mm physical width\n solveMs\n }, [h256.buffer]);\n };\n `;\n\n // ============================================================================\n // 2. OPTICAL CONSTANTS & PROCEDURAL TARGET ARTWORKS (256 x 256)\n // ============================================================================\n const N_GRID = 256;\n const DESIGN_F = 2.20; // 110 mm design focal distance (1.0 unit = 50 mm)\n const T_GLASS = 0.28; // 14 mm base optical crystal thickness\n const DESIGN_Z_LIGHT = 7.4; // 370 mm lamp zenith height\n\n const MATERIALS = {\n bk7: { name: \"Crown BK7\", nD: 1.517, disp: 0.011, tint: [0.92, 0.98, 0.97] },\n silica: { name: \"Fused Silica\", nD: 1.458, disp: 0.008, tint: [0.96, 0.98, 1.00] },\n flint: { name: \"Dense Flint\", nD: 1.785, disp: 0.032, tint: [0.98, 0.96, 0.88] },\n diamond: { name: \"Diamond\", nD: 2.417, disp: 0.052, tint: [0.93, 0.96, 1.00] }\n };\n\n function sdSegment(px, py, ax, ay, bx, by) {\n const vx = px - ax, vy = py - ay, ux = bx - ax, uy = by - ay;\n const h = Math.max(0, Math.min(1, (vx * ux + vy * uy) / (ux * ux + uy * uy + 1e-9)));\n return Math.hypot(vx - ux * h, vy - uy * h);\n }\n\n const PRESETS = {\n astrolabe(N = N_GRID) {\n const t = new Float32Array(N * N);\n for (let y = 0; y < N; y++) {\n const v = (y + 0.5) / N * 2 - 1;\n for (let x = 0; x < N; x++) {\n const u = (x + 0.5) / N * 2 - 1;\n const r = Math.hypot(u, v), th = Math.atan2(v, u);\n let val = 0.032;\n // Outer degree ring + graduations\n val += 1.05 * Math.exp(-Math.pow((r - 0.73) / 0.017, 2));\n if (r > 0.67 && r < 0.74) {\n const ticks = Math.pow(Math.abs(Math.cos(18 * th)), 28);\n val += 0.45 * ticks * Math.exp(-Math.pow((r - 0.70) / 0.028, 2));\n }\n // Equator & Tropic rings\n val += 0.78 * Math.exp(-Math.pow((r - 0.49) / 0.014, 2));\n // Off-center ecliptic zodiac circle (astrolabe rete)\n const re = Math.hypot(u - 0.13, v - 0.11);\n val += 0.98 * Math.exp(-Math.pow((re - 0.41) / 0.016, 2));\n // 8-point compass spider lines\n const star = Math.abs(Math.sin(4 * th)) * r;\n if (r < 0.73 && r > 0.10) {\n val += 0.78 * Math.exp(-Math.pow(star / 0.0135, 2)) * (1 - 0.32 * r);\n }\n // Central sun ring & pinpoint core\n val += 1.22 * Math.exp(-Math.pow((r - 0.115) / 0.015, 2));\n val += 0.95 * Math.exp(-Math.pow(r / 0.032, 2));\n t[y * N + x] = Math.min(1.4, val);\n }\n }\n return t;\n },\n\n nautilus(N = N_GRID) {\n const t = new Float32Array(N * N);\n t.fill(0.032);\n const a = 0.033, b = 0.174;\n const pts = [];\n for (let th = 0; th <= 5.42 * Math.PI; th += 0.011) {\n const r = a * Math.exp(b * th);\n if (r > 0.74) break;\n pts.push([r * Math.cos(th) - 0.06, r * Math.sin(th) - 0.02, 0.015 + 0.008 * (r / 0.74), 1.18]);\n }\n for (let k = 10; k <= 33; k++) {\n const th = k * 0.50;\n const rOut = a * Math.exp(b * th);\n const rIn = a * Math.exp(b * (th - 2 * Math.PI));\n if (rOut > 0.73 || rIn < 0.024) continue;\n for (let s = 0; s <= 1; s += 0.035) {\n const rr = rIn + (rOut - rIn) * s;\n const ang = th - 0.23 * Math.sin(Math.PI * s);\n pts.push([rr * Math.cos(ang) - 0.06, rr * Math.sin(ang) - 0.02, 0.012, 0.78]);\n }\n }\n for (const [cx, cy, rad, inten] of pts) {\n const gx = (cx * 0.5 + 0.5) * N, gy = (cy * 0.5 + 0.5) * N;\n const sig = rad * 0.5 * N, rPix = Math.ceil(sig * 2.8);\n const x0 = Math.max(0, Math.floor(gx - rPix)), x1 = Math.min(N - 1, Math.ceil(gx + rPix));\n const y0 = Math.max(0, Math.floor(gy - rPix)), y1 = Math.min(N - 1, Math.ceil(gy + rPix));\n for (let y = y0; y <= y1; y++) {\n for (let x = x0; x <= x1; x++) {\n const d2 = ((x + 0.5 - gx) ** 2 + (y + 0.5 - gy) ** 2) / (sig * sig);\n if (d2 < 7.5) {\n const v = 0.032 + inten * Math.exp(-d2);\n if (v > t[y * N + x]) t[y * N + x] = Math.min(1.4, v);\n }\n }\n }\n }\n return t;\n },\n\n saturn(N = N_GRID) {\n const t = new Float32Array(N * N);\n const tilt = -0.40, cs = Math.cos(tilt), sn = Math.sin(tilt);\n const Rplanet = 0.225;\n for (let y = 0; y < N; y++) {\n const py = (y + 0.5) / N * 2 - 1;\n for (let x = 0; x < N; x++) {\n const px = (x + 0.5) / N * 2 - 1;\n const rx = px * cs - py * sn, ry = px * sn + py * cs;\n const rp = Math.hypot(rx, ry / 0.90);\n let val = 0.032;\n const rRing = Math.hypot(rx, ry / 0.28);\n const inFront = ry < 0;\n const behindPlanet = (rp < Rplanet * 0.98) && !inFront;\n const inShadow = (ry > 0) && (rx > 0.04) && (Math.abs(ry - 0.16 * rx) < 0.155);\n\n if (!behindPlanet && !inShadow) {\n if (rRing > 0.31 && rRing < 0.50) {\n const w = Math.sin(Math.PI * (rRing - 0.31) / 0.19);\n val += 1.08 * Math.pow(Math.max(0, w), 0.55) * (0.86 + 0.14 * Math.sin(rRing * 95));\n }\n if (rRing > 0.535 && rRing < 0.685) {\n const w = Math.sin(Math.PI * (rRing - 0.535) / 0.15);\n val += 0.85 * Math.pow(Math.max(0, w), 0.5);\n }\n }\n const occByFront = inFront && (rRing > 0.31 && rRing < 0.685);\n if (rp <= Rplanet * 1.04 && !occByFront) {\n const limb = Math.exp(-Math.pow((rp - Rplanet * 0.94) / 0.020, 2));\n const body = rp < Rplanet ? (0.42 * (1 - 0.45 * rp / Rplanet) * (0.82 + 0.22 * Math.cos(ry * 28)) * Math.max(0.15, 0.65 - 1.2 * rx)) : 0;\n val = Math.max(val, 0.032 + 1.16 * limb + body);\n }\n const dTitan = Math.hypot(px + 0.60, py - 0.46);\n const dEnc = Math.hypot(px - 0.52, py + 0.44);\n val += 1.05 * Math.exp(-(dTitan * dTitan) / (0.019 * 0.019));\n val += 0.82 * Math.exp(-(dEnc * dEnc) / (0.015 * 0.015));\n t[y * N + x] = Math.min(1.38, val);\n }\n }\n return t;\n },\n\n crane(N = N_GRID) {\n const t = new Float32Array(N * N);\n const segs = [\n // Sweeping origami upper wings\n [-0.03, 0.06, -0.71, 0.52, 1.18, 0.016],\n [-0.71, 0.52, -0.28, -0.09, 1.12, 0.015],\n [-0.28, -0.09, -0.03, 0.06, 0.86, 0.013],\n [-0.71, 0.52, -0.14, 0.18, 0.64, 0.012],\n [0.06, 0.10, 0.70, 0.46, 1.18, 0.016],\n [0.70, 0.46, 0.23, -0.07, 1.08, 0.015],\n [0.23, -0.07, 0.06, 0.10, 0.82, 0.013],\n [0.70, 0.46, 0.17, 0.17, 0.60, 0.012],\n // Central origami body facets\n [-0.03, 0.06, 0.06, 0.10, 0.96, 0.014],\n [-0.03, 0.06, -0.02, -0.27, 1.02, 0.014],\n [0.06, 0.10, -0.02, -0.27, 1.02, 0.014],\n [-0.28, -0.09, -0.02, -0.27, 0.94, 0.014],\n [0.23, -0.07, -0.02, -0.27, 0.94, 0.014],\n // Poised rising neck & folded head/beak\n [0.23, -0.07, 0.43, -0.44, 1.16, 0.015],\n [0.07, -0.19, 0.43, -0.44, 0.98, 0.014],\n [0.43, -0.44, 0.65, -0.35, 1.22, 0.014],\n [0.36, -0.35, 0.65, -0.35, 0.96, 0.013],\n // Elegant tapered tail spire\n [-0.28, -0.09, -0.54, -0.58, 1.16, 0.015],\n [-0.02, -0.27, -0.54, -0.58, 1.04, 0.014]\n ];\n for (let y = 0; y < N; y++) {\n const py = (y + 0.5) / N * 2 - 1;\n for (let x = 0; x < N; x++) {\n const px = (x + 0.5) / N * 2 - 1;\n let val = 0.032;\n for (const [ax, ay, bx, by, inten, w] of segs) {\n const d = sdSegment(px, py, ax, ay, bx, by);\n const g = inten * Math.exp(-(d * d) / (w * w));\n if (0.032 + g > val) val = 0.032 + g;\n }\n t[y * N + x] = val;\n }\n }\n return t;\n },\n\n lorenz(N = N_GRID) {\n const t = new Float32Array(N * N);\n t.fill(0.032);\n let x = 0.1, y = 0.0, z = 0.0;\n const dt = 0.0035, sigma = 10, rho = 28, beta = 8 / 3;\n for (let i = 0; i < 16500; i++) {\n const dx = sigma * (y - x), dy = x * (rho - z) - y, dz = x * y - beta * z;\n x += dx * dt; y += dy * dt; z += dz * dt;\n if (i < 400) continue;\n const px = (x / 24.0) * 0.74;\n const py = ((z - 25.5) / 23.5) * 0.72;\n const gx = (px * 0.5 + 0.5) * N, gy = (py * 0.5 + 0.5) * N;\n const ix0 = Math.max(0, Math.floor(gx - 3)), ix1 = Math.min(N - 1, Math.ceil(gx + 3));\n const iy0 = Math.max(0, Math.floor(gy - 3)), iy1 = Math.min(N - 1, Math.ceil(gy + 3));\n for (let yy = iy0; yy <= iy1; yy++) {\n for (let xx = ix0; xx <= ix1; xx++) {\n const d2 = ((xx + 0.5 - gx) ** 2 + (yy + 0.5 - gy) ** 2) / (1.85 * 1.85);\n t[yy * N + xx] += 0.042 * Math.exp(-d2);\n }\n }\n }\n for (let i = 0; i < N * N; i++) t[i] = Math.min(1.38, t[i]);\n return t;\n }\n };\n\n // ============================================================================\n // 3. CRYSTALLINE OPTICAL MODAL SYNTHESIZER (WebAudio — Muted by Default)\n // ============================================================================\n class GlassHarmonicaSynth {\n constructor() {\n this.ctx = null;\n this.enabled = false;\n this.voices = [];\n this.master = null;\n this.lastLockPing = 0;\n }\n\n toggle() {\n if (!this.ctx) {\n const AC = window.AudioContext || window.webkitAudioContext;\n if (!AC) return false;\n this.ctx = new AC();\n this.master = this.ctx.createGain();\n this.master.gain.value = 0.0;\n this.master.connect(this.ctx.destination);\n\n // 5 crystalline Lydian glass partials (C5, G5, D6, F#6, A6)\n const baseFreqs = [523.25, 783.99, 1174.66, 1479.98, 1760.0];\n for (let i = 0; i < baseFreqs.length; i++) {\n const osc = this.ctx.createOscillator();\n const gain = this.ctx.createGain();\n osc.type = \"sine\";\n osc.frequency.value = baseFreqs[i];\n gain.gain.value = 0.0;\n osc.connect(gain);\n gain.connect(this.master);\n osc.start();\n this.voices.push({ osc, gain, base: baseFreqs[i], idx: i });\n }\n }\n this.enabled = !this.enabled;\n if (this.enabled && this.ctx.state === \"suspended\") this.ctx.resume();\n const now = this.ctx.currentTime;\n this.master.gain.setTargetAtTime(this.enabled ? 0.14 : 0.0, now, 0.08);\n return this.enabled;\n }\n\n update(alignment, lampSpeed) {\n if (!this.enabled || !this.ctx) return;\n const now = this.ctx.currentTime;\n // Off-axis dispersion detunes partials; exact alignment phase-locks them into a pure bell chord!\n const detuneSpread = (1.0 - alignment) * 26.0;\n const motionBoost = Math.min(1.0, lampSpeed * 3.5);\n for (const v of this.voices) {\n const sign = (v.idx % 2 === 0) ? 1 : -1;\n const targetF = v.base + sign * detuneSpread * (v.idx + 1) * 0.35;\n v.osc.frequency.setTargetAtTime(targetF, now, 0.06);\n const amp = (0.08 + 0.14 * Math.pow(alignment, 3) + 0.07 * motionBoost) / (1 + v.idx * 0.55);\n v.gain.gain.setTargetAtTime(amp, now, 0.07);\n }\n if (alignment > 0.985 && (now - this.lastLockPing) > 1.8 && lampSpeed > 0.015) {\n this.lastLockPing = now;\n this.ping(2093.0, 0.055, 0.65); // Delicate C7 crystal lock chime\n }\n }\n\n chimeSolve() {\n if (!this.enabled || !this.ctx) return;\n const notes = [1046.5, 1318.5, 1567.98, 2093.0];\n notes.forEach((f, idx) => {\n setTimeout(() => this.ping(f, 0.04, 0.35), idx * 32);\n });\n }\n\n ping(freq, peak, dur) {\n if (!this.enabled || !this.ctx) return;\n const now = this.ctx.currentTime;\n const osc = this.ctx.createOscillator();\n const g = this.ctx.createGain();\n osc.type = \"sine\";\n osc.frequency.setValueAtTime(freq, now);\n g.gain.setValueAtTime(0.0001, now);\n g.gain.exponentialRampToValueAtTime(peak, now + 0.012);\n g.gain.exponentialRampToValueAtTime(0.0001, now + dur);\n osc.connect(g);\n g.connect(this.master);\n osc.start(now);\n osc.stop(now + dur + 0.02);\n }\n }\n\n // ============================================================================\n // 4. WATERTIGHT BINARY .STL SOLID LENS EXPORTER (100mm x 100mm Physical Optic)\n // ============================================================================\n function exportBinarySTL(h256, minH, presetName) {\n // Downsample smoothly to 128x128 solid manifold mesh (66,560 triangles -> ~3.3 MB crisp CNC/SLA STL)\n const M = 128;\n const scaleXY = 50.0; // [-1, 1] -> [-50mm, +50mm] = 100mm x 100mm lens\n const baseThickMm = 6.0;\n const zTop = (T_GLASS * 50.0);\n // Sample bottom sculpted surface zBot(i,j) in mm (flipped so flat face can sit on print bed at z=0, sculpted face on top!)\n // Putting flat face at z = 0 and sculpted optical surface at z = baseThickMm - (h - maxH)*50 makes it 100% support-free 3D printable!\n const zSurf = new Float32Array((M + 1) * (M + 1));\n let maxHmm = -Infinity;\n for (let j = 0; j <= M; j++) {\n const sy = Math.min(255, Math.max(0, Math.round((j / M) * 255)));\n for (let i = 0; i <= M; i++) {\n const sx = Math.min(255, Math.max(0, Math.round((i / M) * 255)));\n const hMm = -h256[sy * 256 + sx] * 50.0; // invert for upward-facing print bed orientation\n zSurf[j * (M + 1) + i] = hMm;\n if (hMm > maxHmm) maxHmm = hMm;\n }\n }\n let minSurf = Infinity;\n for (let i = 0; i < zSurf.length; i++) if (zSurf[i] < minSurf) minSurf = zSurf[i];\n for (let i = 0; i < zSurf.length; i++) zSurf[i] = baseThickMm + (zSurf[i] - minSurf);\n\n const triCount = (M * M * 2) * 2 + (M * 2) * 4; // Top sculpted + Bottom flat + 4 walls\n const buf = new ArrayBuffer(84 + triCount * 50);\n const dv = new DataView(buf);\n const headerStr = `CAUSTIC Optical Lens (${presetName}) 100x100mm f=110mm`;\n for (let i = 0; i < 80; i++) dv.setUint8(i, i < headerStr.length ? headerStr.charCodeAt(i) : 32);\n dv.setUint32(80, triCount, true);\n\n let off = 84;\n function pushTri(ax, ay, az, bx, by, bz, cx, cy, cz) {\n const ux = bx - ax, uy = by - ay, uz = bz - az;\n const vx = cx - ax, vy = cy - ay, vz = cz - az;\n let nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;\n const len = Math.hypot(nx, ny, nz) || 1;\n dv.setFloat32(off, nx / len, true); dv.setFloat32(off + 4, ny / len, true); dv.setFloat32(off + 8, nz / len, true);\n dv.setFloat32(off + 12, ax, true); dv.setFloat32(off + 16, ay, true); dv.setFloat32(off + 20, az, true);\n dv.setFloat32(off + 24, bx, true); dv.setFloat32(off + 28, by, true); dv.setFloat32(off + 32, bz, true);\n dv.setFloat32(off + 36, cx, true); dv.setFloat32(off + 40, cy, true); dv.setFloat32(off + 44, cz, true);\n dv.setUint16(off + 48, 0, true);\n off += 50;\n }\n\n const coord = (k) => ((k / M) * 2 - 1) * scaleXY;\n for (let j = 0; j < M; j++) {\n const y0 = coord(j), y1 = coord(j + 1);\n for (let i = 0; i < M; i++) {\n const x0 = coord(i), x1 = coord(i + 1);\n const z00 = zSurf[j * (M + 1) + i], z10 = zSurf[j * (M + 1) + i + 1];\n const z01 = zSurf[(j + 1) * (M + 1) + i], z11 = zSurf[(j + 1) * (M + 1) + i + 1];\n // Sculpted top (+Z)\n pushTri(x0, y0, z00, x1, y0, z10, x1, y1, z11);\n pushTri(x0, y0, z00, x1, y1, z11, x0, y1, z01);\n // Flat bottom (z = 0, -Z normal)\n pushTri(x0, y0, 0, x1, y1, 0, x1, y0, 0);\n pushTri(x0, y0, 0, x0, y1, 0, x1, y1, 0);\n }\n }\n // 4 perimeter watertight side walls\n for (let k = 0; k < M; k++) {\n const c0 = coord(k), c1 = coord(k + 1);\n // South (j = 0)\n pushTri(c0, -scaleXY, 0, c1, -scaleXY, 0, c1, -scaleXY, zSurf[k + 1]);\n pushTri(c0, -scaleXY, 0, c1, -scaleXY, zSurf[k + 1], c0, -scaleXY, zSurf[k]);\n // North (j = M)\n const rN = M * (M + 1);\n pushTri(c1, scaleXY, 0, c0, scaleXY, 0, c0, scaleXY, zSurf[rN + k]);\n pushTri(c1, scaleXY, 0, c0, scaleXY, zSurf[rN + k], c1, scaleXY, zSurf[rN + k + 1]);\n // West (i = 0)\n pushTri(-scaleXY, c1, 0, -scaleXY, c0, 0, -scaleXY, c0, zSurf[k * (M + 1)]);\n pushTri(-scaleXY, c1, 0, -scaleXY, c0, zSurf[k * (M + 1)], -scaleXY, c1, zSurf[(k + 1) * (M + 1)]);\n // East (i = M)\n pushTri(scaleXY, c0, 0, scaleXY, c1, 0, scaleXY, c1, zSurf[(k + 1) * (M + 1) + M]);\n pushTri(scaleXY, c0, 0, scaleXY, c1, zSurf[(k + 1) * (M + 1) + M], scaleXY, c0, zSurf[k * (M + 1) + M]);\n }\n\n const blob = new Blob([buf], { type: \"application/octet-stream\" });\n const url = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = `caustic-lens-${presetName}-100mm.stl`;\n document.body.appendChild(a);\n a.click();\n a.remove();\n setTimeout(() => URL.revokeObjectURL(url), 3000);\n }\n\n // ============================================================================\n // 5. MATRIX UTILITIES (Minimal Zero-Dependency 4x4 Camera Math)\n // ============================================================================\n function mat4Perspective(fovRad, aspect, near, far) {\n const f = 1.0 / Math.tan(fovRad * 0.5), nf = 1.0 / (near - far);\n return new Float32Array([\n f / aspect, 0, 0, 0,\n 0, f, 0, 0,\n 0, 0, (far + near) * nf, -1,\n 0, 0, (2 * far * near) * nf, 0\n ]);\n }\n\n function mat4LookAt(eye, center, up) {\n let zx = eye[0] - center[0], zy = eye[1] - center[1], zz = eye[2] - center[2];\n let len = 1 / (Math.hypot(zx, zy, zz) || 1);\n zx *= len; zy *= len; zz *= len;\n let xx = up[1] * zz - up[2] * zy, xy = up[2] * zx - up[0] * zz, xz = up[0] * zy - up[1] * zx;\n len = Math.hypot(xx, xy, xz);\n if (len < 1e-5) { xx = 1; xy = 0; xz = 0; } else { xx /= len; xy /= len; xz /= len; }\n const yx = zy * xz - zz * xy, yy = zz * xx - zx * xz, yz = zx * xy - zy * xx;\n return new Float32Array([\n xx, yx, zx, 0,\n xy, yy, zy, 0,\n xz, yz, zz, 0,\n -(xx * eye[0] + xy * eye[1] + xz * eye[2]),\n -(yx * eye[0] + yy * eye[1] + yz * eye[2]),\n -(zx * eye[0] + zy * eye[1] + zz * eye[2]),\n 1\n ]);\n }\n\n function mat4Mul(a, b) {\n const out = new Float32Array(16);\n for (let c = 0; c < 4; c++) {\n for (let r = 0; r < 4; r++) {\n out[c * 4 + r] =\n a[0 * 4 + r] * b[c * 4 + 0] +\n a[1 * 4 + r] * b[c * 4 + 1] +\n a[2 * 4 + r] * b[c * 4 + 2] +\n a[3 * 4 + r] * b[c * 4 + 3];\n }\n }\n return out;\n }\n\n function projectToScreen(vp, wx, wy, wz, width, height) {\n const cx = vp[0] * wx + vp[4] * wy + vp[8] * wz + vp[12];\n const cy = vp[1] * wx + vp[5] * wy + vp[9] * wz + vp[13];\n const cw = vp[3] * wx + vp[7] * wy + vp[11] * wz + vp[15];\n if (cw <= 0.01) return null;\n return [\n ((cx / cw) * 0.5 + 0.5) * width,\n (0.5 - (cy / cw) * 0.5) * height\n ];\n }\n\n // ============================================================================\n // 6. WEBGL2 MULTI-PASS OPTICAL ENGINE\n // ============================================================================\n const canvas = document.getElementById(\"glCanvas\");\n const gl = canvas.getContext(\"webgl2\", { antialias: true, alpha: false, powerPreference: \"high-performance\" });\n if (!gl) {\n document.body.innerHTML = \"<div style='padding:32px;color:#ece8df;font-family:sans-serif'>WebGL2 is required to run this real-time optical simulation.</div>\";\n return;\n }\n\n const extColorFloat = gl.getExtension(\"EXT_color_buffer_float\");\n const extFloatBlend = gl.getExtension(\"EXT_float_blend\");\n const extLinearFloat = gl.getExtension(\"OES_texture_float_linear\");\n const useFloatCausticFBO = !!(extColorFloat && extFloatBlend);\n\n function compileShader(type, src) {\n const sh = gl.createShader(type);\n gl.shaderSource(sh, src);\n gl.compileShader(sh);\n if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {\n console.error(gl.getShaderInfoLog(sh), src);\n throw new Error(gl.getShaderInfoLog(sh));\n }\n return sh;\n }\n\n function createProgram(vsSrc, fsSrc) {\n const p = gl.createProgram();\n gl.attachShader(p, compileShader(gl.VERTEX_SHADER, vsSrc));\n gl.attachShader(p, compileShader(gl.FRAGMENT_SHADER, fsSrc));\n gl.linkProgram(p);\n if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {\n throw new Error(gl.getProgramInfoLog(p));\n }\n return p;\n }\n\n // Shared GLSL Uniform Cubic B-Spline (C^2 smooth!) Evaluator on uHeightTex (256x256 R32F)\n // Guarantees continuous 2nd derivatives across texels -> zero discrete grid artifacts in caustics!\n const GLSL_BSPLINE_HEIGHT = `\n uniform sampler2D uHeightTex;\n const float H_RES = 256.0;\n\n // Returns vec3(h, dh/dpx, dh/dps) where px, ps in [-1, 1]\n vec3 sampleGlassSpline(vec2 p) {\n vec2 uv = clamp(p * 0.5 + 0.5, 0.0, 1.0);\n vec2 coord = uv * H_RES - 0.5;\n vec2 base = floor(coord);\n vec2 f = coord - base;\n\n // Cubic B-spline weights w(f) and derivatives dw/df\n vec2 omf = 1.0 - f;\n vec2 w0 = (omf * omf * omf) / 6.0;\n vec2 w1 = (3.0 * f * f * f - 6.0 * f * f + 4.0) / 6.0;\n vec2 w2 = (-3.0 * f * f * f + 3.0 * f * f + 3.0 * f + 1.0) / 6.0;\n vec2 w3 = (f * f * f) / 6.0;\n\n vec2 dw0 = -0.5 * omf * omf;\n vec2 dw1 = 1.5 * f * f - 2.0 * f;\n vec2 dw2 = -1.5 * f * f + f + 0.5;\n vec2 dw3 = 0.5 * f * f;\n\n float wx[4] = float[4](w0.x, w1.x, w2.x, w3.x);\n float wy[4] = float[4](w0.y, w1.y, w2.y, w3.y);\n float dx[4] = float[4](dw0.x, dw1.x, dw2.x, dw3.x);\n float dy[4] = float[4](dw0.y, dw1.y, dw2.y, dw3.y);\n\n float h = 0.0, dhx = 0.0, dhy = 0.0;\n for (int j = 0; j < 4; j++) {\n int iy = clamp(int(base.y) + j - 1, 0, 255);\n float rowH = 0.0, rowDx = 0.0;\n for (int i = 0; i < 4; i++) {\n int ix = clamp(int(base.x) + i - 1, 0, 255);\n float v = texelFetch(uHeightTex, ivec2(ix, iy), 0).r;\n rowH += v * wx[i];\n rowDx += v * dx[i];\n }\n h += rowH * wy[j];\n dhx += rowDx * wy[j];\n dhy += rowH * dy[j];\n }\n // Convert derivative from texel units to physical [-1, 1] units: d(coord)/d(p) = 0.5 * H_RES\n float scaleD = 0.5 * H_RES;\n return vec3(h, dhx * scaleD, dhy * scaleD);\n }\n\n // Exact 3D Snell refraction of ray from point lamp uLightPos (in optical coords: px, ps, zHeight)\n // through flat top (z = uFocalZ + uTGlass) and sculpted bottom (z = uFocalZ + h(px,ps)) onto stage (z = 0).\n // Returns vec4(landPx, landPs, transmittedFluxFactor, validFlag)\n vec4 traceRefractedRay(vec2 p, vec3 lightOpt, float focalZ, float tGlass, float nIOR) {\n vec3 hGrad = sampleGlassSpline(p);\n float zTop = focalZ + tGlass;\n // Approximate entrance point on top face so ray hits bottom at p\n vec3 dirAirApprox = normalize(vec3(p, focalZ) - lightOpt);\n vec2 pTop = p - dirAirApprox.xy * (tGlass / max(0.25, -dirAirApprox.z)) * (1.0 / nIOR);\n vec3 I_air = normalize(vec3(pTop, zTop) - lightOpt);\n float cosI1 = max(0.001, -I_air.z);\n float eta1 = 1.0 / nIOR;\n float k1 = 1.0 - eta1 * eta1 * (1.0 - cosI1 * cosI1);\n vec3 I_glass = vec3(eta1 * I_air.xy, -sqrt(max(1e-6, k1)));\n\n // Schlick Fresnel transmission at top face\n float r0 = (nIOR - 1.0) / (nIOR + 1.0);\n r0 = r0 * r0;\n float T1 = 1.0 - (r0 + (1.0 - r0) * pow(1.0 - cosI1, 5.0));\n\n // Bottom sculpted surface normal pointing UP into glass: N = (-hx, -hy, 1)\n vec3 N_up = normalize(vec3(-hGrad.y, -hGrad.z, 1.0));\n float cosI2 = -dot(I_glass, N_up);\n if (cosI2 <= 0.01) return vec4(p, 0.0, 0.0);\n float k2 = 1.0 - nIOR * nIOR * (1.0 - cosI2 * cosI2);\n if (k2 <= 0.0002) {\n // Real Total Internal Reflection!\n return vec4(p, 0.0, 0.0);\n }\n float cosT2 = sqrt(k2);\n vec3 T_out = nIOR * I_glass + (nIOR * cosI2 - cosT2) * N_up;\n if (T_out.z >= -0.02) return vec4(p, 0.0, 0.0);\n\n float T2 = 1.0 - (r0 + (1.0 - r0) * pow(1.0 - cosT2, 5.0));\n float pz = focalZ + hGrad.x;\n float tHit = -pz / T_out.z;\n vec2 hit = p + T_out.xy * tHit;\n float flux = pow(cosI1, 3.0) * T1 * T2;\n return vec4(hit, flux, 1.0);\n }\n `;\n\n // ----------------------------------------------------------------------------\n // PASS 1 SHADER: CONTINUOUS GPU SPECTRAL CAUSTIC MICRO-MESH (5 WAVELENGTHS!)\n // ----------------------------------------------------------------------------\n const CAUSTIC_VS = `#version 300 es\n precision highp float;\n layout(location = 0) in vec2 aGridUV; // [0, 1]^2 across lens aperture\n\n uniform vec3 uLightOpt; // (lx, ls, ly_height)\n uniform float uFocalZ;\n uniform float uTGlass;\n uniform float uBaseIOR;\n uniform float uDispersion;\n uniform float uExposureScale;\n uniform int uNumBands;\n\n ${GLSL_BSPLINE_HEIGHT}\n\n out vec3 vColor;\n out float vValid;\n\n void main() {\n // Spectral dispersion offset across 5 bands (655nm Red -> 440nm Violet) or 3 RGB bands\n float bandOffset = 0.0;\n vec3 specWeight = vec3(1.0);\n if (uNumBands == 5) {\n if (gl_InstanceID == 0) { bandOffset = -1.00; specWeight = vec3(0.46, 0.04, 0.00); } // 655nm Deep Red\n else if (gl_InstanceID == 1) { bandOffset = -0.45; specWeight = vec3(0.38, 0.28, 0.00); } // 595nm Warm Amber\n else if (gl_InstanceID == 2) { bandOffset = 0.00; specWeight = vec3(0.14, 0.44, 0.06); } // 535nm Emerald\n else if (gl_InstanceID == 3) { bandOffset = 0.52; specWeight = vec3(0.02, 0.18, 0.36); } // 485nm Cyan\n else { bandOffset = 1.15; specWeight = vec3(0.06, 0.02, 0.42); } // 440nm Violet\n } else {\n if (gl_InstanceID == 0) { bandOffset = -0.85; specWeight = vec3(1.00, 0.12, 0.00); }\n else if (gl_InstanceID == 1) { bandOffset = 0.00; specWeight = vec3(0.06, 0.80, 0.10); }\n else { bandOffset = 0.95; specWeight = vec3(0.02, 0.08, 0.76); }\n }\n\n float nLambda = uBaseIOR + bandOffset * uDispersion;\n vec2 p = aGridUV * 2.0 - 1.0;\n\n // Evaluate exact ray landing & local Jacobian area compression via finite differential\n float eps = 2.0 / 320.0;\n vec4 r0 = traceRefractedRay(p, uLightOpt, uFocalZ, uTGlass, nLambda);\n vec4 rx = traceRefractedRay(p + vec2(eps, 0.0), uLightOpt, uFocalZ, uTGlass, nLambda);\n vec4 ry = traceRefractedRay(p + vec2(0.0, eps), uLightOpt, uFocalZ, uTGlass, nLambda);\n\n vec2 dX = (rx.xy - r0.xy) / eps;\n vec2 dY = (ry.xy - r0.xy) / eps;\n float jacobian = abs(dX.x * dY.y - dX.y * dY.x);\n\n // Conserved photon irradiance = incident_flux / jacobian (clamped only at sub-pixel caustic singularity)\n float irradiance = r0.z / max(jacobian, 0.0045);\n\n // Soft aperture edge feather so outer glass bevel doesn't cast hard square clipping line\n vec2 edgeDist = abs(p);\n float edgeFeather = smoothstep(1.0, 0.965, max(edgeDist.x, edgeDist.y));\n\n vValid = r0.w * rx.w * ry.w;\n vColor = specWeight * irradiance * edgeFeather * uExposureScale;\n\n // Map stage [-1.45, +1.45]^2 into Caustic FBO NDC [-1, +1]^2 (allows wide off-axis caustic sweeps!)\n const float STAGE_EXTENT = 1.45;\n gl_Position = vec4(r0.xy / STAGE_EXTENT, 0.0, 1.0);\n }\n `;\n\n const CAUSTIC_FS = `#version 300 es\n precision highp float;\n in vec3 vColor;\n in float vValid;\n out vec4 fragColor;\n void main() {\n if (vValid < 0.5) discard;\n fragColor = vec4(vColor, 1.0);\n }\n `;\n\n // ----------------------------------------------------------------------------\n // PASS 2 SHADER: DUAL-KAWASE PHYSICALLY SOFT HDR CAUSTIC HALATION / BLOOM\n // ----------------------------------------------------------------------------\n const QUAD_VS = `#version 300 es\n precision highp float;\n out vec2 vUV;\n void main() {\n vec2 pos = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);\n vUV = pos;\n gl_Position = vec4(pos * 2.0 - 1.0, 0.0, 1.0);\n }\n `;\n\n const BLOOM_FS = `#version 300 es\n precision highp float;\n in vec2 vUV;\n uniform sampler2D uTex;\n uniform vec2 uTexel;\n uniform float uRadius;\n out vec4 fragColor;\n void main() {\n vec2 d = uTexel * uRadius;\n vec3 s = texture(uTex, vUV).rgb * 0.28;\n s += texture(uTex, vUV + vec2( d.x, d.y)).rgb * 0.18;\n s += texture(uTex, vUV + vec2(-d.x, d.y)).rgb * 0.18;\n s += texture(uTex, vUV + vec2( d.x, -d.y)).rgb * 0.18;\n s += texture(uTex, vUV + vec2(-d.x, -d.y)).rgb * 0.18;\n fragColor = vec4(s, 1.0);\n }\n `;\n\n // ----------------------------------------------------------------------------\n // PASS 3A: STUDIO BACKGROUND + OBSIDIAN STAGE FLOOR + HDR CAUSTIC PROJECTION\n // ----------------------------------------------------------------------------\n const STAGE_VS = `#version 300 es\n precision highp float;\n layout(location = 0) in vec3 aPos;\n uniform mat4 uVP;\n out vec3 vWorldPos;\n void main() {\n vWorldPos = aPos;\n gl_Position = uVP * vec4(aPos, 1.0);\n }\n `;\n\n const STAGE_FS = `#version 300 es\n precision highp float;\n in vec3 vWorldPos;\n uniform sampler2D uCausticTex;\n uniform sampler2D uBloomTex;\n uniform sampler2D uTargetTex;\n uniform vec3 uCamPos;\n uniform vec3 uLightWorld;\n uniform float uFocalZ;\n uniform float uCausticScale;\n uniform int uCompareMask;\n\n out vec4 fragColor;\n\n // Subtle procedural slate micro-grain\n float hash21(vec2 p) {\n p = fract(p * vec2(123.34, 456.21));\n p += dot(p, p + 45.32);\n return fract(p.x * p.y);\n }\n\n void main() {\n // Optical stage coords: px = x, ps = -z\n vec2 optP = vec2(vWorldPos.x, -vWorldPos.z);\n const float STAGE_EXTENT = 1.45;\n vec2 causticUV = optP / (2.0 * STAGE_EXTENT) + 0.5;\n\n // Base dark anodized obsidian tabletop\n float rStage = length(vWorldPos.xz);\n float grain = (hash21(floor(vWorldPos.xz * 260.0)) - 0.5) * 0.012;\n vec3 baseSlate = vec3(0.026, 0.028, 0.036) + grain;\n\n // Subtle soft specular sheen from point lamp on matte stone\n vec3 L = normalize(uLightWorld - vWorldPos);\n vec3 V = normalize(uCamPos - vWorldPos);\n vec3 H = normalize(L + V);\n float spec = pow(max(0.0, H.y), 42.0) * 0.035;\n // Soft shadow cast by glass mount frame outside [-1,1]^2 vs subtle ambient occlusion\n vec2 boxD = abs(optP) - vec2(1.0);\n float frameBorder = abs(max(boxD.x, boxD.y));\n baseSlate += vec3(1.0, 0.88, 0.72) * spec * smoothstep(0.0, 0.4, max(boxD.x, boxD.y) + 0.2);\n\n // Calibrated hairline optical bench reticle & 100mm aperture frame ticks\n float borderLine = exp(-pow(frameBorder / 0.0045, 2.0)) * step(max(abs(optP.x), abs(optP.y)), 1.03);\n float tickMarks = 0.0;\n if (abs(frameBorder - 0.022) < 0.018 && max(abs(optP.x), abs(optP.y)) < 1.03) {\n float c = (abs(optP.x) > abs(optP.y)) ? optP.y : optP.x;\n tickMarks = exp(-pow(sin(c * 3.14159265 * 10.0) / 0.12, 2.0)) * 0.35;\n }\n vec3 reticleCol = vec3(0.32, 0.35, 0.44) * (borderLine * 0.42 + tickMarks * 0.22);\n\n // Sample live raytraced HDR Caustics + physically soft Dual-Kawase halation\n vec3 causticRaw = vec3(0.0);\n vec3 bloomRaw = vec3(0.0);\n if (causticUV.x > 0.002 && causticUV.x < 0.998 && causticUV.y > 0.002 && causticUV.y < 0.998) {\n causticRaw = texture(uCausticTex, causticUV).rgb * uCausticScale;\n bloomRaw = texture(uBloomTex, causticUV).rgb * uCausticScale;\n }\n\n vec3 lightDeposit = causticRaw + bloomRaw * 0.36;\n\n // Optional \"Mask vs. Lens\" split comparison (left half: absorptive stencil mask; right half: refractive lens!)\n if (uCompareMask == 1 && abs(optP.x) < 1.0 && abs(optP.y) < 1.0) {\n if (optP.x < 0.0) {\n vec2 tUV = optP * 0.5 + 0.5;\n float targVal = texture(uTargetTex, tUV).r;\n // Absorptive mask simply blocks light where targVal < max, peaking at ONLY 1.0x uniform lamp irradiance!\n // Notice how dim 1.0x un-concentrated sunlight is compared to 20x-30x optimal-transport photon focusing!\n float maskTrans = clamp((targVal - 0.032) / 1.15, 0.0, 1.0);\n float directSun = 0.14; // exact same 1.0x mean incident photon budget!\n lightDeposit = vec3(1.0, 0.88, 0.68) * (directSun * maskTrans);\n }\n // Hairline split divider at x = 0\n float splitLine = exp(-pow(optP.x / 0.004, 2.0));\n reticleCol += vec3(0.95, 0.74, 0.45) * splitLine * 0.65;\n }\n\n vec3 col = baseSlate + reticleCol + lightDeposit;\n\n // Smooth radial fade into dark studio floor\n float vig = smoothstep(3.3, 1.35, rStage);\n col *= vig;\n\n // Filmic ACES-inspired highlight roll-off so 30x caustic cusps glow incandescent white-gold!\n col = (col * (2.51 * col + 0.03)) / (col * (2.43 * col + 0.59) + 0.14);\n col = pow(max(col, 0.0), vec3(1.0 / 2.2));\n fragColor = vec4(col, 1.0);\n }\n `;\n\n // ----------------------------------------------------------------------------\n // PASS 3B: 3D WATERTIGHT SCULPTED OPTICAL GLASS BLOCK (Refraction + Interferogram)\n // ----------------------------------------------------------------------------\n const GLASS_VS = `#version 300 es\n precision highp float;\n layout(location = 0) in vec3 aGridPos; // (px, ps, faceType: 0=bottom sculpted, 1=top flat, 2..5=side walls)\n layout(location = 1) in vec3 aWallNormal;\n\n uniform mat4 uVP;\n uniform float uFocalZ;\n uniform float uTGlass;\n\n ${GLSL_BSPLINE_HEIGHT}\n\n out vec3 vWorldPos;\n out vec3 vNormal;\n out vec2 vOptP;\n out float vHeight;\n out float vFaceType;\n\n void main() {\n vec2 p = aGridPos.xy;\n float face = aGridPos.z;\n vec3 hGrad = sampleGlassSpline(p);\n float yWorld = 0.0;\n vec3 nWorld = vec3(0.0, 1.0, 0.0);\n\n if (face < 0.5) {\n // Bottom sculpted optical face: y = uFocalZ + h(px, ps)\n // Optical normal into air is (hx, hy, -1) -> World (X=px, Y=z, Z=-ps) normal is (hx, -1.0, -hy)!\n yWorld = uFocalZ + hGrad.x;\n nWorld = normalize(vec3(hGrad.y, -1.0, -hGrad.z));\n } else if (face < 1.5) {\n // Top flat entrance face\n yWorld = uFocalZ + uTGlass;\n nWorld = vec3(0.0, 1.0, 0.0);\n } else {\n // Polished perimeter bevel walls: aWallNormal.y stores top(1) vs bottom(0) selector\n float isTop = aWallNormal.y;\n yWorld = (isTop > 0.5) ? (uFocalZ + uTGlass) : (uFocalZ + hGrad.x);\n nWorld = normalize(vec3(aWallNormal.x, 0.0, aWallNormal.z));\n }\n\n vec3 worldPos = vec3(p.x, yWorld, -p.y);\n vWorldPos = worldPos;\n vNormal = nWorld;\n vOptP = p;\n vHeight = hGrad.x;\n vFaceType = face;\n gl_Position = uVP * vec4(worldPos, 1.0);\n }\n `;\n\n const GLASS_FS = `#version 300 es\n precision highp float;\n in vec3 vWorldPos;\n in vec3 vNormal;\n in vec2 vOptP;\n in float vHeight;\n in float vFaceType;\n\n uniform sampler2D uSceneCopyTex;\n uniform vec2 uViewport;\n uniform vec3 uCamPos;\n uniform vec3 uLightWorld;\n uniform float uBaseIOR;\n uniform vec3 uGlassTint;\n uniform int uShowInterf;\n\n out vec4 fragColor;\n\n void main() {\n vec3 N = normalize(gl_FrontFacing ? vNormal : -vNormal);\n vec3 V = normalize(uCamPos - vWorldPos);\n vec3 I = -V;\n\n // True screen-space optical refraction with subtle R/G/B chromatic offset\n vec2 screenUV = gl_FragCoord.xy / uViewport;\n vec3 R_refr = refract(I, N, 1.0 / uBaseIOR);\n vec2 refrOffset = R_refr.xz * 0.048 * (vFaceType > 1.5 ? 1.65 : 1.0);\n\n vec3 bgR = texture(uSceneCopyTex, clamp(screenUV + refrOffset * 0.94, 0.002, 0.998)).rgb;\n vec3 bgG = texture(uSceneCopyTex, clamp(screenUV + refrOffset * 1.00, 0.002, 0.998)).rgb;\n vec3 bgB = texture(uSceneCopyTex, clamp(screenUV + refrOffset * 1.06, 0.002, 0.998)).rgb;\n vec3 refrCol = vec3(bgR.r, bgG.g, bgB.b);\n\n // Beer-Lambert optical crystal edge tint (polished green-aqua crown glass edges!)\n float cosTheta = max(0.02, dot(N, V));\n float pathLen = (vFaceType > 1.5) ? 0.55 : (0.14 / max(0.25, cosTheta));\n vec3 absorb = pow(uGlassTint, vec3(pathLen * 2.4));\n refrCol *= absorb;\n if (vFaceType > 1.5) {\n // Polished ground-glass edge catchlight\n refrCol += vec3(0.06, 0.11, 0.13) * uGlassTint;\n }\n\n // Schlick Fresnel reflection from overhead lamp & cool studio softboxes\n float r0 = pow((uBaseIOR - 1.0) / (uBaseIOR + 1.0), 2.0);\n float fresnel = r0 + (1.0 - r0) * pow(1.0 - cosTheta, 5.0);\n\n vec3 L = normalize(uLightWorld - vWorldPos);\n vec3 H = normalize(L + V);\n float specLamp = pow(max(0.0, dot(N, H)), 180.0) * 1.6 + pow(max(0.0, dot(N, H)), 24.0) * 0.14;\n vec3 R_refl = reflect(I, N);\n // Subtle studio softbox sky reflection strip\n float studioStrip = smoothstep(0.35, 0.85, R_refl.y) * (0.55 + 0.45 * smoothstep(-0.3, 0.5, R_refl.x));\n vec3 envRefl = vec3(0.30, 0.36, 0.46) * studioStrip + vec3(1.0, 0.90, 0.72) * specLamp;\n\n // Subtle bevel edge highlight on glass perimeter\n vec2 edgeD = abs(vOptP);\n float rim = smoothstep(0.982, 1.0, max(edgeD.x, edgeD.y));\n vec3 col = mix(refrCol, envRefl, clamp(fresnel * 1.25, 0.04, 0.92)) + vec3(0.14, 0.20, 0.24) * rim * 0.45;\n\n // Optional Mach-Zehnder Laser Interferogram (reveals micron height contours cos(4*pi*h/lambda)!)\n if (uShowInterf == 1 && vFaceType < 1.5) {\n float phase = vHeight * 260.0;\n float fringe = 0.5 + 0.5 * cos(phase);\n fringe = pow(fringe, 3.0);\n vec3 interfCol = mix(vec3(0.02, 0.14, 0.18), vec3(0.45, 0.96, 0.88), fringe);\n col = mix(col, col * 0.45 + interfCol * 0.68, 0.62);\n }\n\n fragColor = vec4(col, 1.0);\n }\n `;\n\n // ----------------------------------------------------------------------------\n // PASS 3C: DIAGNOSTIC 3D LINES (Snell Ray Sheet, Optimal Transport Grid, Lamp Cone)\n // ----------------------------------------------------------------------------\n const LINE_VS = `#version 300 es\n precision highp float;\n layout(location = 0) in vec3 aPos;\n layout(location = 1) in vec4 aCol;\n uniform mat4 uVP;\n out vec4 vCol;\n void main() {\n vCol = aCol;\n gl_Position = uVP * vec4(aPos, 1.0);\n }\n `;\n\n const LINE_FS = `#version 300 es\n precision highp float;\n in vec4 vCol;\n out vec4 fragColor;\n void main() {\n fragColor = vCol;\n }\n `;\n\n // 3D Point Lamp Billboard Glow Shader\n const LAMP_VS = `#version 300 es\n precision highp float;\n uniform mat4 uVP;\n uniform vec3 uLampPos;\n uniform vec3 uCamRight;\n uniform vec3 uCamUp;\n uniform float uSize;\n out vec2 vQuad;\n void main() {\n vec2 corners[4] = vec2[4](vec2(-1,-1), vec2(1,-1), vec2(-1,1), vec2(1,1));\n int idx[6] = int[6](0, 1, 2, 2, 1, 3);\n vec2 q = corners[idx[gl_VertexID]];\n vQuad = q;\n vec3 world = uLampPos + (uCamRight * q.x + uCamUp * q.y) * uSize;\n gl_Position = uVP * vec4(world, 1.0);\n }\n `;\n\n const LAMP_FS = `#version 300 es\n precision highp float;\n in vec2 vQuad;\n uniform float uFocusLock;\n out vec4 fragColor;\n void main() {\n float r = length(vQuad);\n if (r > 1.0) discard;\n float core = exp(-r * r * 38.0);\n float halo = exp(-r * r * 5.2) * 0.55 + pow(max(0.0, 1.0 - r), 3.0) * 0.22;\n vec3 col = vec3(1.0, 0.94, 0.82) * core * 1.4 + mix(vec3(1.0, 0.74, 0.38), vec3(0.65, 0.92, 1.0), uFocusLock * 0.25) * halo;\n fragColor = vec4(col, 1.0);\n }\n `;\n\n const progCaustic = createProgram(CAUSTIC_VS, CAUSTIC_FS);\n const progBloom = createProgram(QUAD_VS, BLOOM_FS);\n const progStage = createProgram(STAGE_VS, STAGE_FS);\n const progGlass = createProgram(GLASS_VS, GLASS_FS);\n const progLine = createProgram(LINE_VS, LINE_FS);\n const progLamp = createProgram(LAMP_VS, LAMP_FS);\n\n // ============================================================================\n // 7. GPU BUFFERS, TEXTURES & FRAMEBUFFERS\n // ============================================================================\n // 1) Heightfield R32F Texture (256x256) + Target R32F Texture (256x256)\n const heightTex = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, heightTex);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.R32F, N_GRID, N_GRID, 0, gl.RED, gl.FLOAT, new Float32Array(N_GRID * N_GRID));\n\n const targetTex = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, targetTex);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, extLinearFloat ? gl.LINEAR : gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, extLinearFloat ? gl.LINEAR : gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.R32F, N_GRID, N_GRID, 0, gl.RED, gl.FLOAT, new Float32Array(N_GRID * N_GRID));\n\n // 2) Caustic FBO (1024x1024 RGBA16F HDR or RGBA8 scaled fallback) + Bloom FBOs (512x512)\n const CAUSTIC_RES = 1024;\n function createFBO(w, h, useFloat) {\n const tex = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, tex);\n const filter = (!useFloat || extLinearFloat) ? gl.LINEAR : gl.NEAREST;\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n if (useFloat) {\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, w, h, 0, gl.RGBA, gl.HALF_FLOAT, null);\n } else {\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n }\n const fbo = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n return { fbo, tex, w, h };\n }\n\n const fboCaustic = createFBO(CAUSTIC_RES, CAUSTIC_RES, useFloatCausticFBO);\n const fboBloomA = createFBO(512, 512, useFloatCausticFBO);\n const fboBloomB = createFBO(256, 256, useFloatCausticFBO);\n\n // Scene copy texture for true 3D glass refraction\n const sceneCopyTex = gl.createTexture();\n let sceneCopyW = 0, sceneCopyH = 0;\n function ensureSceneCopyTex(w, h) {\n if (sceneCopyW === w && sceneCopyH === h) return;\n sceneCopyW = w; sceneCopyH = h;\n gl.bindTexture(gl.TEXTURE_2D, sceneCopyTex);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n }\n\n // 3) Continuous Refractive Beam Micro-Mesh (320 x 320 = 102,400 quads = 204,800 tris/band)\n const BEAM_N = 320;\n const beamVAO = gl.createVertexArray();\n gl.bindVertexArray(beamVAO);\n const beamVerts = new Float32Array((BEAM_N + 1) * (BEAM_N + 1) * 2);\n for (let y = 0; y <= BEAM_N; y++) {\n for (let x = 0; x <= BEAM_N; x++) {\n const idx = (y * (BEAM_N + 1) + x) * 2;\n beamVerts[idx] = x / BEAM_N;\n beamVerts[idx + 1] = y / BEAM_N;\n }\n }\n const beamVBO = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, beamVBO);\n gl.bufferData(gl.ARRAY_BUFFER, beamVerts, gl.STATIC_DRAW);\n gl.enableVertexAttribArray(0);\n gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);\n\n const beamIndices = new Uint32Array(BEAM_N * BEAM_N * 6);\n let bi = 0;\n for (let y = 0; y < BEAM_N; y++) {\n for (let x = 0; x < BEAM_N; x++) {\n const i00 = y * (BEAM_N + 1) + x, i10 = i00 + 1;\n const i01 = i00 + (BEAM_N + 1), i11 = i01 + 1;\n beamIndices[bi++] = i00; beamIndices[bi++] = i10; beamIndices[bi++] = i11;\n beamIndices[bi++] = i00; beamIndices[bi++] = i11; beamIndices[bi++] = i01;\n }\n }\n const beamIBO = gl.createBuffer();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, beamIBO);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, beamIndices, gl.STATIC_DRAW);\n gl.bindVertexArray(null);\n\n // 4) Stage Floor Mesh (Large horizontal slab at y = 0)\n const stageVAO = gl.createVertexArray();\n gl.bindVertexArray(stageVAO);\n const S_EXT = 3.6;\n const stageVBO = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, stageVBO);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([\n -S_EXT, 0, -S_EXT, S_EXT, 0, -S_EXT, S_EXT, 0, S_EXT,\n -S_EXT, 0, -S_EXT, S_EXT, 0, S_EXT, -S_EXT, 0, S_EXT\n ]), gl.STATIC_DRAW);\n gl.enableVertexAttribArray(0);\n gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);\n gl.bindVertexArray(null);\n\n // 5) 3D Watertight Glass Block Mesh (160x160 sculpted bottom + top + 4 polished side walls)\n const GLASS_M = 160;\n const glassVAO = gl.createVertexArray();\n gl.bindVertexArray(glassVAO);\n const glassVertList = [];\n const glassIdxList = [];\n\n function addGlassSurface(faceType) {\n const base = glassVertList.length / 6;\n for (let j = 0; j <= GLASS_M; j++) {\n const ps = (j / GLASS_M) * 2 - 1;\n for (let i = 0; i <= GLASS_M; i++) {\n const px = (i / GLASS_M) * 2 - 1;\n glassVertList.push(px, ps, faceType, 0, 0, 0);\n }\n }\n for (let j = 0; j < GLASS_M; j++) {\n for (let i = 0; i < GLASS_M; i++) {\n const i00 = base + j * (GLASS_M + 1) + i, i10 = i00 + 1;\n const i01 = i00 + (GLASS_M + 1), i11 = i01 + 1;\n if (faceType === 0) {\n glassIdxList.push(i00, i11, i10, i00, i01, i11);\n } else {\n glassIdxList.push(i00, i10, i11, i00, i11, i01);\n }\n }\n }\n }\n addGlassSurface(0); // Sculpted bottom\n addGlassSurface(1); // Flat top\n\n // 4 Polished Perimeter Side Walls\n function addWallStrip(pxFn, psFn, nx, nz) {\n const base = glassVertList.length / 6;\n for (let k = 0; k <= GLASS_M; k++) {\n const t = (k / GLASS_M) * 2 - 1;\n const px = pxFn(t), ps = psFn(t);\n glassVertList.push(px, ps, 2, nx, 0, nz); // bottom edge\n glassVertList.push(px, ps, 2, nx, 1, nz); // top edge\n }\n for (let k = 0; k < GLASS_M; k++) {\n const b0 = base + 2 * k, t0 = b0 + 1, b1 = b0 + 2, t1 = b0 + 3;\n glassIdxList.push(b0, b1, t1, b0, t1, t0);\n }\n }\n addWallStrip((t) => t, () => -1, 0, 1); // Front (+Z world, ps = -1)\n addWallStrip((t) => -t, () => 1, 0, -1); // Back (-Z world, ps = +1)\n addWallStrip(() => 1, (t) => t, 1, 0); // Right (+X world)\n addWallStrip(() => -1, (t) => -t, -1, 0); // Left (-X world)\n\n const glassVBO = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, glassVBO);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(glassVertList), gl.STATIC_DRAW);\n gl.enableVertexAttribArray(0);\n gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 24, 0);\n gl.enableVertexAttribArray(1);\n gl.vertexAttribPointer(1, 3, gl.FLOAT, false, 24, 12);\n\n const glassIBO = gl.createBuffer();\n const glassIndexCount = glassIdxList.length;\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, glassIBO);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint32Array(glassIdxList), gl.STATIC_DRAW);\n gl.bindVertexArray(null);\n\n // 6) Dynamic 3D Line Buffer (Ray Sheet, Photon Grid, Lamp Aperture Cone, Mount Pins)\n const lineVAO = gl.createVertexArray();\n gl.bindVertexArray(lineVAO);\n const lineVBO = gl.createBuffer();\n const MAX_LINE_FLOATS = 32768 * 7;\n const lineData = new Float32Array(MAX_LINE_FLOATS);\n gl.bindBuffer(gl.ARRAY_BUFFER, lineVBO);\n gl.bufferData(gl.ARRAY_BUFFER, lineData.byteLength, gl.DYNAMIC_DRAW);\n gl.enableVertexAttribArray(0);\n gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 28, 0);\n gl.enableVertexAttribArray(1);\n gl.vertexAttribPointer(1, 4, gl.FLOAT, false, 28, 12);\n gl.bindVertexArray(null);\n\n const emptyVAO = gl.createVertexArray();\n\n // ============================================================================\n // 8. APPLICATION STATE, SOLVER WORKER & INTERACTIVE PAD\n // ============================================================================\n const synth = new GlassHarmonicaSynth();\n const workerBlob = new Blob([WORKER_SOURCE], { type: \"application/javascript\" });\n const solverWorker = new Worker(URL.createObjectURL(workerBlob));\n\n const state = {\n preset: \"astrolabe\",\n carvedForGlass: \"bk7\",\n selectedGlass: \"bk7\",\n focalRatio: 1.00, // 1.00 * DESIGN_F\n showRays: true,\n showGrid: false,\n showInterf: false,\n compareMask: false,\n raySliceS: 0.0, // y-slice across optical lens [-0.85, +0.85]\n\n // Camera spherical orbit around bench center (0, 1.05, 0)\n camYaw: 0.34,\n camPitch: 0.56,\n camDist: 6.35,\n camTargetYaw: 0.34,\n camTargetPitch: 0.56,\n camTargetDist: 6.35,\n camCenterY: 1.02,\n camTargetCenterY: 1.02,\n\n // 3D Point Lamp in optical coordinates (lx, ls, lz_height)\n // Start at graceful 13-degree off-axis angle so opening 2.0s glides into dramatic focus lock!\n lampX: 1.48,\n lampS: -0.92,\n lampZ: DESIGN_Z_LIGHT,\n lampTargetX: 0.0,\n lampTargetS: 0.0,\n autoChoreo: true,\n userInteracted: false,\n presetCycleTimer: 0,\n\n // Live heightfield morphing (hCurrent smoothly springs toward hSolved at 60fps!)\n target256: PRESETS.astrolabe(),\n hCurrent: new Float32Array(N_GRID * N_GRID),\n hSolved: new Float32Array(N_GRID * N_GRID),\n minH: -0.05,\n maxH: 0.05,\n reliefMm: 4.8,\n solveMs: 0,\n solving: false,\n solveReqId: 0,\n\n // Pad Loupe state\n loupeTab: \"target\", // \"target\" | \"height\"\n brushMode: \"draw\", // \"draw\" | \"erase\"\n numSpectralBands: 5 // Adaptive 5-band full prism spectrum (falls back to 3 on software GL)\n };\n\n // Upload initial target texture\n function uploadTargetTexture() {\n gl.bindTexture(gl.TEXTURE_2D, targetTex);\n gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, N_GRID, N_GRID, gl.RED, gl.FLOAT, state.target256);\n }\n uploadTargetTexture();\n\n // Render Target or Solved Glass Heightfield onto the 2D Loupe Pad Canvas\n const padCanvas = document.getElementById(\"padCanvas\");\n const padCtx = padCanvas.getContext(\"2d\");\n const padImgData = padCtx.createImageData(N_GRID, N_GRID);\n\n function renderPadCanvas() {\n const d = padImgData.data;\n if (state.loupeTab === \"target\") {\n let maxV = 0.2;\n for (let i = 0; i < N_GRID * N_GRID; i++) if (state.target256[i] > maxV) maxV = state.target256[i];\n for (let y = 0; y < N_GRID; y++) {\n const row = (N_GRID - 1 - y);\n for (let x = 0; x < N_GRID; x++) {\n const v = Math.max(0, (state.target256[y * N_GRID + x] - 0.032) / (maxV - 0.032));\n const g = Math.pow(v, 0.62);\n const p = (row * N_GRID + x) * 4;\n d[p] = Math.min(255, (10 + g * 245) | 0);\n d[p + 1] = Math.min(255, (12 + Math.pow(g, 1.15) * 206) | 0);\n d[p + 2] = Math.min(255, (18 + Math.pow(g, 1.45) * 138) | 0);\n d[p + 3] = 255;\n }\n }\n } else {\n // Shaded Aqua-Crystal Relief + Interferometric Contours\n const span = (state.maxH - state.minH) || 0.05;\n const dx = 2.0 / N_GRID;\n for (let y = 0; y < N_GRID; y++) {\n const row = (N_GRID - 1 - y);\n for (let x = 0; x < N_GRID; x++) {\n const i = y * N_GRID + x;\n const hn = (state.hSolved[i] - state.minH) / span;\n const hx = (state.hSolved[y * N_GRID + Math.min(255, x + 1)] - state.hSolved[y * N_GRID + Math.max(0, x - 1)]) / (2 * dx);\n const hy = (state.hSolved[Math.min(255, y + 1) * N_GRID + x] - state.hSolved[Math.max(0, y - 1) * N_GRID + x]) / (2 * dx);\n const hill = Math.max(0.25, Math.min(1.45, 0.68 + 1.9 * (-hx * 0.65 + hy * 0.65)));\n const contour = 0.88 + 0.12 * Math.cos(state.hSolved[i] * 240.0);\n const lum = (0.24 + 0.62 * hn) * hill * contour;\n const p = (row * N_GRID + x) * 4;\n d[p] = Math.min(255, (lum * 135) | 0);\n d[p + 1] = Math.min(255, (lum * 208) | 0);\n d[p + 2] = Math.min(255, (lum * 232) | 0);\n d[p + 3] = 255;\n }\n }\n }\n padCtx.putImageData(padImgData, 0, 0);\n }\n\n const telemetryBar = document.getElementById(\"telemetryBar\");\n const statRelief = document.getElementById(\"statRelief\");\n const statSolve = document.getElementById(\"statSolve\");\n const statFocus = document.getElementById(\"statFocus\");\n const statRays = document.getElementById(\"statRays\");\n const btnRegrind = document.getElementById(\"btnRegrind\");\n\n function requestLensSolve(targetArr) {\n state.solving = true;\n telemetryBar.classList.add(\"solving\");\n statSolve.textContent = \"SOLVING PDE…\";\n const id = ++state.solveReqId;\n const mat = MATERIALS[state.selectedGlass];\n state.carvedForGlass = state.selectedGlass;\n btnRegrind.style.display = \"none\";\n\n const copy = new Float32Array(targetArr);\n solverWorker.postMessage({\n id,\n target256: copy,\n F: DESIGN_F,\n T_glass: T_GLASS,\n nGlass: mat.nD,\n Z_light: DESIGN_Z_LIGHT\n }, [copy.buffer]);\n }\n\n solverWorker.onmessage = (e) => {\n const { id, h256, minH, maxH, reliefMm, solveMs } = e.data;\n if (id !== state.solveReqId) return;\n state.hSolved = h256;\n state.minH = minH;\n state.maxH = maxH;\n state.reliefMm = reliefMm;\n state.solveMs = solveMs;\n state.solving = false;\n telemetryBar.classList.remove(\"solving\");\n statRelief.textContent = `RELIEF ${reliefMm.toFixed(1)} mm`;\n statSolve.textContent = `PDE ${Math.round(solveMs)} ms`;\n if (state.loupeTab === \"height\") renderPadCanvas();\n synth.chimeSolve();\n };\n\n // Trigger initial lens solve immediately!\n renderPadCanvas();\n requestLensSolve(state.target256);\n\n // ============================================================================\n // 9. CPU EXACT SNELL RAYTRACER FOR 3D DIAGNOSTIC OVERLAYS (Ray Sheet & Grid)\n // ============================================================================\n function sampleHCPU(px, ps) {\n const gx = Math.max(0, Math.min(N_GRID - 1.001, (px * 0.5 + 0.5) * N_GRID - 0.5));\n const gs = Math.max(0, Math.min(N_GRID - 1.001, (ps * 0.5 + 0.5) * N_GRID - 0.5));\n const ix = gx | 0, is = gs | 0, fx = gx - ix, fs = gs - is;\n const h = state.hCurrent;\n const v00 = h[is * N_GRID + ix], v10 = h[is * N_GRID + ix + 1];\n const v01 = h[(is + 1) * N_GRID + ix], v11 = h[(is + 1) * N_GRID + ix + 1];\n const val = (1 - fx) * (1 - fs) * v00 + fx * (1 - fs) * v10 + (1 - fx) * fs * v01 + fx * fs * v11;\n\n const dx = 2.0 / N_GRID;\n const xm = Math.max(0, ix - 1), xp = Math.min(N_GRID - 1, ix + 1);\n const sm = Math.max(0, is - 1), sp = Math.min(N_GRID - 1, is + 1);\n const hx = (h[is * N_GRID + xp] - h[is * N_GRID + xm]) / ((xp - xm) * dx);\n const hs = (h[sp * N_GRID + ix] - h[sm * N_GRID + ix]) / ((sp - sm) * dx);\n return [val, hx, hs];\n }\n\n function traceSingleRay3D(px, ps, focalZ, nIOR) {\n const [hVal, hx, hs] = sampleHCPU(px, ps);\n const zTop = focalZ + T_GLASS;\n const lx = state.lampX, ls = state.lampS, lz = state.lampZ;\n let dax = px - lx, das = ps - ls, daz = focalZ - lz;\n const dLen = Math.hypot(dax, das, daz);\n dax /= dLen; das /= dLen; daz /= dLen;\n const pTopX = px - dax * (T_GLASS / Math.max(0.25, -daz)) / nIOR;\n const pTopS = ps - das * (T_GLASS / Math.max(0.25, -daz)) / nIOR;\n\n let ix = pTopX - lx, is = pTopS - ls, iz = zTop - lz;\n const il = Math.hypot(ix, is, iz);\n ix /= il; is /= il; iz /= il;\n const eta1 = 1.0 / nIOR, cosI1 = Math.max(0.001, -iz);\n const gx = eta1 * ix, gs = eta1 * is, gz = -Math.sqrt(Math.max(1e-6, 1 - eta1 * eta1 * (1 - cosI1 * cosI1)));\n\n const invN = 1.0 / Math.hypot(hx, hs, 1.0);\n const nx = -hx * invN, ns = -hs * invN, nz = invN;\n const cosI2 = -(gx * nx + gs * ns + gz * nz);\n const k2 = 1.0 - nIOR * nIOR * (1.0 - cosI2 * cosI2);\n if (cosI2 <= 0.01 || k2 <= 0.0002) return null;\n const s = nIOR * cosI2 - Math.sqrt(k2);\n const tx = nIOR * gx + s * nx, ts = nIOR * gs + s * ns, tz = nIOR * gz + s * nz;\n if (tz >= -0.02) return null;\n const pz = focalZ + hVal;\n const tHit = -pz / tz;\n return {\n top: [pTopX, zTop, -pTopS],\n bot: [px, pz, -ps],\n stage: [px + tx * tHit, 0.003, -(ps + ts * tHit)]\n };\n }\n\n function buildDiagnosticLines(focalZ, nIOR) {\n let ptr = 0;\n function seg(ax, ay, az, bx, by, bz, r, g, b, a1, a2) {\n if (ptr + 14 > MAX_LINE_FLOATS) return;\n lineData[ptr++] = ax; lineData[ptr++] = ay; lineData[ptr++] = az;\n lineData[ptr++] = r * a1; lineData[ptr++] = g * a1; lineData[ptr++] = b * a1; lineData[ptr++] = a1;\n lineData[ptr++] = bx; lineData[ptr++] = by; lineData[ptr++] = bz;\n lineData[ptr++] = r * a2; lineData[ptr++] = g * a2; lineData[ptr++] = b * a2; lineData[ptr++] = a2;\n }\n\n const lampW = [state.lampX, state.lampZ, -state.lampS];\n const zTop = focalZ + T_GLASS;\n\n // 1) Subtle precision corner suspension guide filaments + lamp aperture cone\n const corners = [[-1, -1], [1, -1], [1, 1], [-1, 1]];\n for (const [cx, cs] of corners) {\n // Lamp -> glass corner subtle volumetric guide ray\n seg(lampW[0], lampW[1], lampW[2], cx, zTop, -cs, 0.95, 0.78, 0.50, 0.14, 0.04);\n // Vertical bench caliper post from floor to glass corner\n seg(cx * 1.03, 0.0, -cs * 1.03, cx * 1.03, zTop + 0.03, -cs * 1.03, 0.35, 0.40, 0.50, 0.16, 0.22);\n }\n\n // Subtle zenith target ring at (0, DESIGN_Z_LIGHT, 0) so user sees the focal lock sweet-spot!\n const RING_N = 32, R_ZEN = 0.14;\n for (let i = 0; i < RING_N; i++) {\n const a0 = (i / RING_N) * Math.PI * 2, a1 = ((i + 1) / RING_N) * Math.PI * 2;\n seg(\n Math.cos(a0) * R_ZEN, DESIGN_Z_LIGHT, Math.sin(a0) * R_ZEN,\n Math.cos(a1) * R_ZEN, DESIGN_Z_LIGHT, Math.sin(a1) * R_ZEN,\n 0.50, 0.84, 0.96, 0.20, 0.20\n );\n }\n\n // 2) 3D Snell Refraction Laser Ray Sheet (68 rays across slice plane ps = raySliceS)\n if (state.showRays) {\n const NUM_RAYS = 68;\n const ps = state.raySliceS;\n // Slice indicator bar on top of glass\n seg(-1.0, zTop + 0.004, -ps, 1.0, zTop + 0.004, -ps, 0.48, 0.86, 0.96, 0.35, 0.35);\n for (let i = 0; i < NUM_RAYS; i++) {\n const px = -0.94 + (1.88 * i) / (NUM_RAYS - 1);\n const ray = traceSingleRay3D(px, ps, focalZ, nIOR);\n if (!ray) continue;\n // Incident ray: Lamp -> Top flat surface\n seg(lampW[0], lampW[1], lampW[2], ray.top[0], ray.top[1], ray.top[2], 1.0, 0.84, 0.55, 0.08, 0.20);\n // Internal glass ray: Top -> Sculpted bottom\n seg(ray.top[0], ray.top[1], ray.top[2], ray.bot[0], ray.bot[1], ray.bot[2], 0.52, 0.90, 1.0, 0.34, 0.48);\n // Refracted caustic ray: Sculpted bottom -> Stage floor!\n seg(ray.bot[0], ray.bot[1], ray.bot[2], ray.stage[0], ray.stage[1], ray.stage[2], 1.0, 0.78, 0.42, 0.36, 0.26);\n }\n }\n\n // 3) Optimal Transport (Brenier) Grid Overlay (28 x 28 mesh on glass AND refracted on stage!)\n if (state.showGrid) {\n const G = 28;\n const stagePts = new Array((G + 1) * (G + 1));\n for (let j = 0; j <= G; j++) {\n const ps = -0.92 + (1.84 * j) / G;\n for (let i = 0; i <= G; i++) {\n const px = -0.92 + (1.84 * i) / G;\n stagePts[j * (G + 1) + i] = traceSingleRay3D(px, ps, focalZ, nIOR);\n }\n }\n for (let j = 0; j <= G; j++) {\n for (let i = 0; i <= G; i++) {\n const a = stagePts[j * (G + 1) + i];\n if (!a) continue;\n if (i < G) {\n const b = stagePts[j * (G + 1) + i + 1];\n if (b) {\n seg(a.top[0], a.top[1] + 0.002, a.top[2], b.top[0], b.top[1] + 0.002, b.top[2], 0.5, 0.85, 0.98, 0.14, 0.14);\n seg(a.stage[0], 0.005, a.stage[2], b.stage[0], 0.005, b.stage[2], 0.48, 0.86, 0.98, 0.26, 0.26);\n }\n }\n if (j < G) {\n const b = stagePts[(j + 1) * (G + 1) + i];\n if (b) {\n seg(a.top[0], a.top[1] + 0.002, a.top[2], b.top[0], b.top[1] + 0.002, b.top[2], 0.5, 0.85, 0.98, 0.14, 0.14);\n seg(a.stage[0], 0.005, a.stage[2], b.stage[0], 0.005, b.stage[2], 0.48, 0.86, 0.98, 0.26, 0.26);\n }\n }\n }\n }\n }\n\n gl.bindBuffer(gl.ARRAY_BUFFER, lineVBO);\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, lineData.subarray(0, ptr));\n return ptr / 7;\n }\n\n // ============================================================================\n // 10. UI CONTROLS, POINTER DIRECT MANIPULATION & LIVE SKETCHING\n // ============================================================================\n const presetOrder = [\"astrolabe\", \"nautilus\", \"saturn\", \"crane\", \"lorenz\"];\n const presetBtns = document.querySelectorAll(\"#presetGroup button[data-preset]\");\n const loupeCard = document.getElementById(\"loupeCard\");\n\n function selectPreset(name, fromAuto = false) {\n state.preset = name;\n presetBtns.forEach((b) => b.classList.toggle(\"active\", b.dataset.preset === name));\n if (name === \"custom\") {\n loupeCard.classList.remove(\"collapsed\");\n loupeCard.classList.add(\"expanded\");\n document.getElementById(\"btnToggleLoupe\").textContent = \"–\";\n state.loupeTab = \"target\";\n document.getElementById(\"tabTarget\").classList.add(\"active\");\n document.getElementById(\"tabHeight\").classList.remove(\"active\");\n renderPadCanvas();\n return;\n }\n loupeCard.classList.remove(\"expanded\");\n if (!fromAuto) markUserInteracted();\n state.target256 = PRESETS[name]();\n uploadTargetTexture();\n renderPadCanvas();\n requestLensSolve(state.target256);\n }\n\n presetBtns.forEach((btn) => {\n btn.addEventListener(\"click\", () => selectPreset(btn.dataset.preset, false));\n });\n\n function markUserInteracted() {\n if (!state.userInteracted) {\n state.userInteracted = true;\n document.getElementById(\"gestureHint\").classList.add(\"hidden\");\n }\n state.autoChoreo = false;\n }\n\n // Camera View Presets\n const camBtns = document.querySelectorAll(\"button[data-cam]\");\n function setCameraPreset(mode) {\n camBtns.forEach((b) => b.classList.toggle(\"active\", b.dataset.cam === mode));\n if (mode === \"studio\") {\n state.camTargetYaw = 0.34; state.camTargetPitch = 0.56; state.camTargetDist = 6.35; state.camTargetCenterY = 1.02;\n } else if (mode === \"profile\") {\n state.camTargetYaw = 0.14; state.camTargetPitch = 0.13; state.camTargetDist = 5.20; state.camTargetCenterY = 1.65;\n } else if (mode === \"top\") {\n state.camTargetYaw = 0.0; state.camTargetPitch = 1.50; state.camTargetDist = 5.45; state.camTargetCenterY = 0.25;\n }\n }\n camBtns.forEach((btn) => btn.addEventListener(\"click\", () => {\n markUserInteracted();\n setCameraPreset(btn.dataset.cam);\n }));\n\n // Focal Height Slider\n const focalSlider = document.getElementById(\"focalSlider\");\n const focalVal = document.getElementById(\"focalVal\");\n focalSlider.addEventListener(\"input\", () => {\n markUserInteracted();\n let v = parseFloat(focalSlider.value);\n if (Math.abs(v - 1.0) < 0.022) { v = 1.0; focalSlider.value = \"1.00\"; } // subtle magnetic detent at exact focus!\n state.focalRatio = v;\n focalVal.textContent = `${Math.round(v * 110)} mm`;\n });\n\n // Glass Material Selector\n const glassSelect = document.getElementById(\"glassSelect\");\n glassSelect.addEventListener(\"change\", () => {\n markUserInteracted();\n state.selectedGlass = glassSelect.value;\n // Show \"Re-grind\" button when viewing an existing lens made for a different index of refraction!\n // (Lets physicists observe Lensmaker focal-shift f ~ 1/(n-1) first, then re-grind on demand!)\n btnRegrind.style.display = (state.selectedGlass !== state.carvedForGlass) ? \"inline-flex\" : \"none\";\n });\n\n btnRegrind.addEventListener(\"click\", () => {\n markUserInteracted();\n requestLensSolve(state.target256);\n });\n\n // Diagnostic Toggles\n const btnRays = document.getElementById(\"btnRays\");\n const btnGrid = document.getElementById(\"btnGrid\");\n const btnInterf = document.getElementById(\"btnInterf\");\n const btnCompare = document.getElementById(\"btnCompare\");\n\n btnRays.addEventListener(\"click\", () => {\n state.showRays = !state.showRays;\n btnRays.classList.toggle(\"cyan-active\", state.showRays);\n });\n btnGrid.addEventListener(\"click\", () => {\n state.showGrid = !state.showGrid;\n btnGrid.classList.toggle(\"cyan-active\", state.showGrid);\n });\n btnInterf.addEventListener(\"click\", () => {\n state.showInterf = !state.showInterf;\n btnInterf.classList.toggle(\"cyan-active\", state.showInterf);\n });\n btnCompare.addEventListener(\"click\", () => {\n state.compareMask = !state.compareMask;\n btnCompare.classList.toggle(\"active\", state.compareMask);\n });\n\n // Top Utility Buttons\n document.getElementById(\"btnAlign\").addEventListener(\"click\", () => {\n state.autoChoreo = false;\n state.lampTargetX = 0.0;\n state.lampTargetS = 0.0;\n state.focalRatio = 1.0;\n focalSlider.value = \"1.00\";\n focalVal.textContent = \"110 mm\";\n });\n\n const btnAudio = document.getElementById(\"btnAudio\");\n btnAudio.addEventListener(\"click\", () => {\n const on = synth.toggle();\n btnAudio.textContent = on ? \"♪ Sound On\" : \"♪ Sound Off\";\n btnAudio.classList.toggle(\"active\", on);\n });\n\n document.getElementById(\"btnStl\").addEventListener(\"click\", () => {\n exportBinarySTL(state.hSolved, state.minH, state.preset);\n });\n\n // Loupe Pad Tabs & Live Brush / Typography Sculpting\n const tabTarget = document.getElementById(\"tabTarget\");\n const tabHeight = document.getElementById(\"tabHeight\");\n const padBadge = document.getElementById(\"padBadge\");\n tabTarget.addEventListener(\"click\", () => {\n state.loupeTab = \"target\";\n tabTarget.classList.add(\"active\"); tabHeight.classList.remove(\"active\");\n padBadge.textContent = \"Draw to carve lens\";\n renderPadCanvas();\n });\n tabHeight.addEventListener(\"click\", () => {\n state.loupeTab = \"height\";\n tabHeight.classList.add(\"active\"); tabTarget.classList.remove(\"active\");\n padBadge.textContent = \"Smooth C² surface\";\n renderPadCanvas();\n });\n\n const btnToggleLoupe = document.getElementById(\"btnToggleLoupe\");\n btnToggleLoupe.addEventListener(\"click\", () => {\n const col = loupeCard.classList.toggle(\"collapsed\");\n btnToggleLoupe.textContent = col ? \"✎ Pad\" : \"–\";\n });\n\n const btnBrushDraw = document.getElementById(\"btnBrushDraw\");\n const btnBrushErase = document.getElementById(\"btnBrushErase\");\n btnBrushDraw.addEventListener(\"click\", () => {\n state.brushMode = \"draw\";\n btnBrushDraw.classList.add(\"active\"); btnBrushErase.classList.remove(\"active\");\n });\n btnBrushErase.addEventListener(\"click\", () => {\n state.brushMode = \"erase\";\n btnBrushErase.classList.add(\"active\"); btnBrushDraw.classList.remove(\"active\");\n });\n\n document.getElementById(\"btnPadClear\").addEventListener(\"click\", () => {\n markUserInteracted();\n state.preset = \"custom\";\n presetBtns.forEach((b) => b.classList.toggle(\"active\", b.dataset.preset === \"custom\"));\n state.target256.fill(0.032);\n // Tiny central alignment spark so empty target still has non-degenerate mass\n state.target256[128 * 256 + 128] = 0.35;\n state.loupeTab = \"target\";\n tabTarget.classList.add(\"active\"); tabHeight.classList.remove(\"active\");\n uploadTargetTexture();\n renderPadCanvas();\n });\n\n // Carve Custom Typography onto Target Grid\n const glyphInput = document.getElementById(\"glyphInput\");\n function carveCustomText() {\n const txt = (glyphInput.value || \"LUX\").trim().toUpperCase();\n if (!txt) return;\n markUserInteracted();\n state.preset = \"custom\";\n presetBtns.forEach((b) => b.classList.toggle(\"active\", b.dataset.preset === \"custom\"));\n state.loupeTab = \"target\";\n tabTarget.classList.add(\"active\"); tabHeight.classList.remove(\"active\");\n\n const off = document.createElement(\"canvas\");\n off.width = N_GRID; off.height = N_GRID;\n const ctx = off.getContext(\"2d\");\n ctx.fillStyle = \"#000\";\n ctx.fillRect(0, 0, N_GRID, N_GRID);\n ctx.fillStyle = \"#fff\";\n ctx.textAlign = \"center\";\n ctx.textBaseline = \"middle\";\n const fontSize = Math.min(108, Math.floor(215 / Math.max(1.4, txt.length * 0.62)));\n ctx.font = `600 ${fontSize}px Georgia, \"Times New Roman\", serif`;\n ctx.fillText(txt, N_GRID / 2, N_GRID / 2 + 2);\n\n // Subtle decorative framing arcs above and below text\n ctx.strokeStyle = \"rgba(255,255,255,0.65)\";\n ctx.lineWidth = 3.2;\n ctx.beginPath(); ctx.arc(128, 128, 98, -0.78 * Math.PI, -0.22 * Math.PI); ctx.stroke();\n ctx.beginPath(); ctx.arc(128, 128, 98, 0.22 * Math.PI, 0.78 * Math.PI); ctx.stroke();\n\n const img = ctx.getImageData(0, 0, N_GRID, N_GRID).data;\n // Slight 3x3 Gaussian soften for silky caustic strokes\n const raw = new Float32Array(N_GRID * N_GRID);\n for (let y = 0; y < N_GRID; y++) {\n const sy = N_GRID - 1 - y;\n for (let x = 0; x < N_GRID; x++) {\n raw[y * N_GRID + x] = img[(sy * N_GRID + x) * 4] / 255.0;\n }\n }\n for (let y = 0; y < N_GRID; y++) {\n for (let x = 0; x < N_GRID; x++) {\n let sum = 0, wSum = 0;\n for (let dy = -2; dy <= 2; dy++) {\n const yy = Math.max(0, Math.min(255, y + dy));\n for (let dx = -2; dx <= 2; dx++) {\n const xx = Math.max(0, Math.min(255, x + dx));\n const w = Math.exp(-(dx * dx + dy * dy) / 2.6);\n sum += raw[yy * N_GRID + xx] * w; wSum += w;\n }\n }\n state.target256[y * N_GRID + x] = 0.032 + 1.18 * (sum / wSum);\n }\n }\n uploadTargetTexture();\n renderPadCanvas();\n requestLensSolve(state.target256);\n state.lampTargetX = 0; state.lampTargetS = 0;\n }\n\n document.getElementById(\"btnCarveText\").addEventListener(\"click\", carveCustomText);\n glyphInput.addEventListener(\"keydown\", (e) => { if (e.key === \"Enter\") carveCustomText(); });\n\n // Interactive Freehand Drawing on Loupe Pad (throttled live 160ms PDE re-carve!)\n let padDrawing = false, lastPadPos = null, liveSolveTimer = null;\n function getPadCoords(e) {\n const r = padCanvas.getBoundingClientRect();\n const u = Math.max(0, Math.min(1, (e.clientX - r.left) / r.width));\n const v = Math.max(0, Math.min(1, 1.0 - (e.clientY - r.top) / r.height));\n return [u * N_GRID, v * N_GRID];\n }\n\n function paintStroke(x0, y0, x1, y1) {\n const dist = Math.hypot(x1 - x0, y1 - y0);\n const steps = Math.max(1, Math.ceil(dist * 0.75));\n const rad = state.brushMode === \"erase\" ? 11.0 : 5.2;\n for (let s = 0; s <= steps; s++) {\n const t = s / steps;\n const cx = x0 + (x1 - x0) * t, cy = y0 + (y1 - y0) * t;\n // Keep inside clean optical aperture [18..238]\n const px = Math.max(18, Math.min(238, cx)), py = Math.max(18, Math.min(238, cy));\n const rPix = Math.ceil(rad * 2.4);\n const ix0 = Math.max(0, Math.floor(px - rPix)), ix1 = Math.min(255, Math.ceil(px + rPix));\n const iy0 = Math.max(0, Math.floor(py - rPix)), iy1 = Math.min(255, Math.ceil(py + rPix));\n for (let y = iy0; y <= iy1; y++) {\n for (let x = ix0; x <= ix1; x++) {\n const d2 = ((x + 0.5 - px) ** 2 + (y + 0.5 - py) ** 2) / (rad * rad);\n if (d2 > 6.0) continue;\n const idx = y * N_GRID + x;\n if (state.brushMode === \"erase\") {\n state.target256[idx] = 0.032 + (state.target256[idx] - 0.032) * (1 - 0.85 * Math.exp(-d2));\n } else {\n const v = 0.032 + 1.18 * Math.exp(-d2);\n if (v > state.target256[idx]) state.target256[idx] = v;\n }\n }\n }\n }\n uploadTargetTexture();\n renderPadCanvas();\n if (!liveSolveTimer) {\n liveSolveTimer = setTimeout(() => {\n liveSolveTimer = null;\n if (!state.solving) requestLensSolve(state.target256);\n }, 170);\n }\n }\n\n padCanvas.addEventListener(\"pointerdown\", (e) => {\n markUserInteracted();\n padCanvas.setPointerCapture(e.pointerId);\n if (state.loupeTab !== \"target\") {\n state.loupeTab = \"target\";\n tabTarget.classList.add(\"active\"); tabHeight.classList.remove(\"active\");\n }\n if (state.preset !== \"custom\") {\n // First stroke on a preset transitions smoothly into Custom Sculpt mode!\n state.preset = \"custom\";\n presetBtns.forEach((b) => b.classList.toggle(\"active\", b.dataset.preset === \"custom\"));\n }\n padDrawing = true;\n lastPadPos = getPadCoords(e);\n paintStroke(lastPadPos[0], lastPadPos[1], lastPadPos[0], lastPadPos[1]);\n state.lampTargetX = 0; state.lampTargetS = 0;\n });\n\n padCanvas.addEventListener(\"pointermove\", (e) => {\n if (!padDrawing) return;\n const cur = getPadCoords(e);\n paintStroke(lastPadPos[0], lastPadPos[1], cur[0], cur[1]);\n lastPadPos = cur;\n });\n\n function finishPadStroke() {\n if (!padDrawing) return;\n padDrawing = false;\n if (liveSolveTimer) { clearTimeout(liveSolveTimer); liveSolveTimer = null; }\n requestLensSolve(state.target256);\n }\n padCanvas.addEventListener(\"pointerup\", finishPadStroke);\n padCanvas.addEventListener(\"pointercancel\", finishPadStroke);\n\n // ============================================================================\n // 11. MAIN 3D VIEWPORT POINTER CONTROLS (Dual-Zone: Steer Lamp OR Orbit 3D!)\n // ============================================================================\n let dragMode = null; // \"lamp\" | \"orbit\" | \"slice\"\n let dragLastX = 0, dragLastY = 0;\n let currentVP = new Float32Array(16);\n\n canvas.addEventListener(\"pointerdown\", (e) => {\n markUserInteracted();\n canvas.setPointerCapture(e.pointerId);\n dragLastX = e.clientX;\n dragLastY = e.clientY;\n\n const w = canvas.clientWidth, h = canvas.clientHeight;\n const lampScr = projectToScreen(currentVP, state.lampX, state.lampZ, -state.lampS, w, h);\n const stageCenterScr = projectToScreen(currentVP, 0, 0, 0, w, h);\n\n if (e.button === 2 || e.altKey) {\n dragMode = \"orbit\";\n } else if (lampScr && Math.hypot(e.clientX - lampScr[0], e.clientY - lampScr[1]) < 64) {\n dragMode = \"lamp\";\n } else if (stageCenterScr && e.clientY > h * 0.48) {\n // Dragging on the lower stage half steers the 3D light rays tactilely!\n dragMode = \"lamp\";\n } else {\n dragMode = \"orbit\";\n }\n canvas.classList.toggle(\"dragging-lamp\", dragMode === \"lamp\");\n canvas.classList.toggle(\"dragging-orbit\", dragMode === \"orbit\");\n });\n\n canvas.addEventListener(\"pointermove\", (e) => {\n if (!dragMode) return;\n const dx = e.clientX - dragLastX, dy = e.clientY - dragLastY;\n dragLastX = e.clientX; dragLastY = e.clientY;\n\n if (dragMode === \"lamp\") {\n // Convert screen delta into camera-aligned horizontal lamp motion\n const scale = 0.0075;\n const cosY = Math.cos(state.camYaw), sinY = Math.sin(state.camYaw);\n // Right vector in world XZ is (cosY, -sinY); Forward in world XZ is (-sinY, -cosY)\n const dWorldX = dx * cosY * scale + dy * sinY * scale;\n const dWorldZ = -dx * sinY * scale + dy * cosY * scale;\n state.lampTargetX = Math.max(-3.0, Math.min(3.0, state.lampTargetX + dWorldX));\n state.lampTargetS = Math.max(-3.0, Math.min(3.0, state.lampTargetS - dWorldZ));\n // Gentle magnetic sweet-spot detent right near exact (0,0) optical axis!\n if (Math.hypot(state.lampTargetX, state.lampTargetS) < 0.065) {\n state.lampTargetX *= 0.65;\n state.lampTargetS *= 0.65;\n }\n if (state.showRays && e.shiftKey) {\n state.raySliceS = Math.max(-0.88, Math.min(0.88, state.raySliceS - dy * 0.005));\n }\n } else if (dragMode === \"orbit\") {\n camBtns.forEach((b) => b.classList.remove(\"active\"));\n state.camTargetYaw -= dx * 0.0065;\n state.camTargetPitch = Math.max(0.07, Math.min(1.52, state.camTargetPitch + dy * 0.0065));\n }\n });\n\n function endViewportDrag() {\n dragMode = null;\n canvas.classList.remove(\"dragging-lamp\", \"dragging-orbit\");\n // Snap cleanly to 0 if released inside the tiny zenith sweet spot ring\n if (Math.hypot(state.lampTargetX, state.lampTargetS) < 0.11) {\n state.lampTargetX = 0.0;\n state.lampTargetS = 0.0;\n }\n }\n canvas.addEventListener(\"pointerup\", endViewportDrag);\n canvas.addEventListener(\"pointercancel\", endViewportDrag);\n canvas.addEventListener(\"contextmenu\", (e) => e.preventDefault());\n\n canvas.addEventListener(\"wheel\", (e) => {\n e.preventDefault();\n state.camTargetDist = Math.max(3.4, Math.min(9.6, state.camTargetDist + e.deltaY * 0.0035));\n }, { passive: false });\n\n // URL parameter hooks for flexible blog embedding (?preset=nautilus&rays=0)\n const params = new URLSearchParams(window.location.search);\n if (params.get(\"preset\") && PRESETS[params.get(\"preset\")]) {\n selectPreset(params.get(\"preset\"), true);\n }\n if (params.get(\"rays\") === \"0\") {\n state.showRays = false;\n btnRays.classList.remove(\"cyan-active\");\n }\n\n // ============================================================================\n // 12. MAIN 60FPS ANIMATION & MULTI-PASS RENDER LOOP\n // ============================================================================\n let lastTime = performance.now();\n let startTime = lastTime;\n let slowFrameStreak = 0;\n\n function resizeCanvas() {\n const dpr = Math.min(window.devicePixelRatio || 1, 2.0);\n const w = Math.max(2, Math.floor(window.innerWidth * dpr));\n const h = Math.max(2, Math.floor(window.innerHeight * dpr));\n if (canvas.width !== w || canvas.height !== h) {\n canvas.width = w;\n canvas.height = h;\n }\n ensureSceneCopyTex(w, h);\n }\n\n // Cache uniform locations once for zero GC pressure\n const uCaustic = {\n lightOpt: gl.getUniformLocation(progCaustic, \"uLightOpt\"),\n focalZ: gl.getUniformLocation(progCaustic, \"uFocalZ\"),\n tGlass: gl.getUniformLocation(progCaustic, \"uTGlass\"),\n baseIOR: gl.getUniformLocation(progCaustic, \"uBaseIOR\"),\n disp: gl.getUniformLocation(progCaustic, \"uDispersion\"),\n expScale: gl.getUniformLocation(progCaustic, \"uExposureScale\"),\n numBands: gl.getUniformLocation(progCaustic, \"uNumBands\"),\n heightTex: gl.getUniformLocation(progCaustic, \"uHeightTex\")\n };\n const uBloom = {\n tex: gl.getUniformLocation(progBloom, \"uTex\"),\n texel: gl.getUniformLocation(progBloom, \"uTexel\"),\n radius: gl.getUniformLocation(progBloom, \"uRadius\")\n };\n const uStage = {\n vp: gl.getUniformLocation(progStage, \"uVP\"),\n causticTex: gl.getUniformLocation(progStage, \"uCausticTex\"),\n bloomTex: gl.getUniformLocation(progStage, \"uBloomTex\"),\n targetTex: gl.getUniformLocation(progStage, \"uTargetTex\"),\n camPos: gl.getUniformLocation(progStage, \"uCamPos\"),\n lightWorld: gl.getUniformLocation(progStage, \"uLightWorld\"),\n focalZ: gl.getUniformLocation(progStage, \"uFocalZ\"),\n causticScale: gl.getUniformLocation(progStage, \"uCausticScale\"),\n compareMask: gl.getUniformLocation(progStage, \"uCompareMask\")\n };\n const uGlass = {\n vp: gl.getUniformLocation(progGlass, \"uVP\"),\n focalZ: gl.getUniformLocation(progGlass, \"uFocalZ\"),\n tGlass: gl.getUniformLocation(progGlass, \"uTGlass\"),\n heightTex: gl.getUniformLocation(progGlass, \"uHeightTex\"),\n sceneCopy: gl.getUniformLocation(progGlass, \"uSceneCopyTex\"),\n viewport: gl.getUniformLocation(progGlass, \"uViewport\"),\n camPos: gl.getUniformLocation(progGlass, \"uCamPos\"),\n lightWorld: gl.getUniformLocation(progGlass, \"uLightWorld\"),\n baseIOR: gl.getUniformLocation(progGlass, \"uBaseIOR\"),\n glassTint: gl.getUniformLocation(progGlass, \"uGlassTint\"),\n showInterf: gl.getUniformLocation(progGlass, \"uShowInterf\")\n };\n const uLine = { vp: gl.getUniformLocation(progLine, \"uVP\") };\n const uLamp = {\n vp: gl.getUniformLocation(progLamp, \"uVP\"),\n pos: gl.getUniformLocation(progLamp, \"uLampPos\"),\n right: gl.getUniformLocation(progLamp, \"uCamRight\"),\n up: gl.getUniformLocation(progLamp, \"uCamUp\"),\n size: gl.getUniformLocation(progLamp, \"uSize\"),\n lock: gl.getUniformLocation(progLamp, \"uFocusLock\")\n };\n\n function frame(now) {\n const dt = Math.min(0.05, (now - lastTime) * 0.001);\n const rawFrameMs = now - lastTime;\n lastTime = now;\n const elapsed = (now - startTime) * 0.001;\n\n // Adaptive spectral band governor for software GL / low-power mobile\n if (elapsed > 1.5 && rawFrameMs > 28 && state.numSpectralBands === 5) {\n slowFrameStreak++;\n if (slowFrameStreak > 12) state.numSpectralBands = 3;\n } else {\n slowFrameStreak = 0;\n }\n statRays.textContent = state.numSpectralBands === 5 ? \"512K BEAMS · 5λ\" : \"307K BEAMS · 3λ\";\n\n resizeCanvas();\n\n // 1) Autonomous Opening Choreography (sweeps chaotic caustics -> razor focus -> gentle tour)\n if (state.autoChoreo) {\n // Cycle every 8.5s: 0..1.6s dramatic sweep into focus, 1.6..6.8s gentle living focus shimmer, 6.8..8.5s morph to next!\n const period = 8.5;\n const cyc = elapsed % period;\n const tourIdx = Math.floor(elapsed / period) % presetOrder.length;\n const desiredPreset = presetOrder[tourIdx];\n if (desiredPreset !== state.preset && elapsed > 2.0) {\n selectPreset(desiredPreset, true);\n }\n\n if (cyc < 1.55) {\n const u = 1.0 - cyc / 1.55;\n const ease = u * u * (3 - 2 * u);\n const ang = elapsed * 0.9;\n state.lampTargetX = Math.cos(ang) * 1.45 * ease;\n state.lampTargetS = Math.sin(ang) * 1.05 * ease;\n } else if (cyc < 7.2) {\n // Subtle living sunlight micro-shimmer around focal lock!\n state.lampTargetX = Math.cos(elapsed * 1.35) * 0.055;\n state.lampTargetS = Math.sin(elapsed * 1.05) * 0.055;\n } else {\n const u = (cyc - 7.2) / (period - 7.2);\n const ease = u * u;\n state.lampTargetX = Math.cos(elapsed * 1.1) * 1.15 * ease;\n state.lampTargetS = Math.sin(elapsed * 1.1) * 0.85 * ease;\n }\n // Gentle studio camera breathing\n state.camTargetYaw = 0.34 + Math.sin(elapsed * 0.28) * 0.14;\n if (state.showRays) {\n state.raySliceS = Math.sin(elapsed * 0.55) * 0.52;\n }\n }\n\n // 2) Smooth Spring Interpolation of Lamp, Camera & 3D Glass Surface Heightfield\n const prevLampX = state.lampX, prevLampS = state.lampS;\n const kLamp = 1.0 - Math.exp(-11.0 * dt);\n state.lampX += (state.lampTargetX - state.lampX) * kLamp;\n state.lampS += (state.lampTargetS - state.lampS) * kLamp;\n const lampSpeed = Math.hypot(state.lampX - prevLampX, state.lampS - prevLampS) / Math.max(1e-4, dt);\n\n const kCam = 1.0 - Math.exp(-8.5 * dt);\n state.camYaw += (state.camTargetYaw - state.camYaw) * kCam;\n state.camPitch += (state.camTargetPitch - state.camPitch) * kCam;\n state.camDist += (state.camTargetDist - state.camDist) * kCam;\n state.camCenterY += (state.camTargetCenterY - state.camCenterY) * kCam;\n\n // Smoothly morph physical 3D glass surface hCurrent -> hSolved\n const kGlass = 1.0 - Math.exp(-7.5 * dt);\n let maxDiffH = 0;\n for (let i = 0; i < N_GRID * N_GRID; i++) {\n const diff = state.hSolved[i] - state.hCurrent[i];\n if (Math.abs(diff) > maxDiffH) maxDiffH = Math.abs(diff);\n state.hCurrent[i] += diff * kGlass;\n }\n if (maxDiffH > 1e-6) {\n gl.bindTexture(gl.TEXTURE_2D, heightTex);\n gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, N_GRID, N_GRID, gl.RED, gl.FLOAT, state.hCurrent);\n }\n\n const focalZ = DESIGN_F * state.focalRatio;\n const mat = MATERIALS[state.selectedGlass];\n\n // Optical alignment score (0..1) for HUD telemetry & crystalline harmonic synth\n const offAxis = Math.hypot(state.lampX, state.lampS) / 2.2;\n const offFocal = Math.abs(state.focalRatio - (MATERIALS[state.carvedForGlass].nD - 1) / (mat.nD - 1));\n const alignment = Math.max(0, Math.min(1, Math.exp(-2.8 * offAxis * offAxis - 5.0 * offFocal * offFocal)));\n statFocus.textContent = `ALIGN ${Math.round(alignment * 100)}%`;\n synth.update(alignment, lampSpeed);\n\n // --------------------------------------------------------------------------\n // PASS 1: RENDER CONTINUOUS GPU SPECTRAL CAUSTICS INTO CAUSTIC FBO\n // --------------------------------------------------------------------------\n gl.bindFramebuffer(gl.FRAMEBUFFER, fboCaustic.fbo);\n gl.viewport(0, 0, fboCaustic.w, fboCaustic.h);\n gl.disable(gl.DEPTH_TEST);\n gl.disable(gl.CULL_FACE);\n gl.clearColor(0, 0, 0, 0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE, gl.ONE);\n\n gl.useProgram(progCaustic);\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, heightTex);\n gl.uniform1i(uCaustic.heightTex, 0);\n gl.uniform3f(uCaustic.lightOpt, state.lampX, state.lampS, state.lampZ);\n gl.uniform1f(uCaustic.focalZ, focalZ);\n gl.uniform1f(uCaustic.tGlass, T_GLASS);\n gl.uniform1f(uCaustic.baseIOR, mat.nD);\n gl.uniform1f(uCaustic.disp, mat.disp);\n // Scale exposure slightly down when using 8-bit fallback FBO so highlights never clip before tone-mapping\n const fboScale = useFloatCausticFBO ? 0.145 : 0.022;\n const stageRecoverScale = useFloatCausticFBO ? 1.0 : (0.145 / 0.022);\n gl.uniform1f(uCaustic.expScale, fboScale);\n gl.uniform1i(uCaustic.numBands, state.numSpectralBands);\n\n gl.bindVertexArray(beamVAO);\n gl.drawElementsInstanced(gl.TRIANGLES, beamIndices.length, gl.UNSIGNED_INT, 0, state.numSpectralBands);\n\n // --------------------------------------------------------------------------\n // PASS 2: DUAL-KAWASE PHYSICALLY SOFT HDR CAUSTIC HALATION / BLOOM\n // --------------------------------------------------------------------------\n gl.disable(gl.BLEND);\n gl.useProgram(progBloom);\n gl.bindVertexArray(emptyVAO);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, fboBloomA.fbo);\n gl.viewport(0, 0, fboBloomA.w, fboBloomA.h);\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, fboCaustic.tex);\n gl.uniform1i(uBloom.tex, 0);\n gl.uniform2f(uBloom.texel, 1 / fboCaustic.w, 1 / fboCaustic.h);\n gl.uniform1f(uBloom.radius, 1.5);\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, fboBloomB.fbo);\n gl.viewport(0, 0, fboBloomB.w, fboBloomB.h);\n gl.bindTexture(gl.TEXTURE_2D, fboBloomA.tex);\n gl.uniform2f(uBloom.texel, 1 / fboBloomA.w, 1 / fboBloomA.h);\n gl.uniform1f(uBloom.radius, 2.2);\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, fboBloomA.fbo);\n gl.viewport(0, 0, fboBloomA.w, fboBloomA.h);\n gl.bindTexture(gl.TEXTURE_2D, fboBloomB.tex);\n gl.uniform2f(uBloom.texel, 1 / fboBloomB.w, 1 / fboBloomB.h);\n gl.uniform1f(uBloom.radius, 1.8);\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n\n // --------------------------------------------------------------------------\n // PASS 3: UNIFIED 3D ATELIER OPTICAL BENCH SCENE\n // --------------------------------------------------------------------------\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n const W = canvas.width, H = canvas.height;\n gl.viewport(0, 0, W, H);\n gl.clearColor(0.027, 0.031, 0.045, 1.0);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n gl.enable(gl.DEPTH_TEST);\n gl.depthMask(true);\n\n const cosP = Math.cos(state.camPitch), sinP = Math.sin(state.camPitch);\n const cosY = Math.cos(state.camYaw), sinY = Math.sin(state.camYaw);\n const camPos = [\n state.camDist * cosP * sinY,\n state.camCenterY + state.camDist * sinP,\n state.camDist * cosP * cosY\n ];\n const center = [0, state.camCenterY * 0.52, 0];\n const proj = mat4Perspective(39 * Math.PI / 180, W / H, 0.15, 40.0);\n const view = mat4LookAt(camPos, center, [0, 1, 0]);\n currentVP = mat4Mul(proj, view);\n const lightWorld = [state.lampX, state.lampZ, -state.lampS];\n\n // 3A: Obsidian Receiver Stage + Live Caustics\n gl.useProgram(progStage);\n gl.uniformMatrix4fv(uStage.vp, false, currentVP);\n gl.uniform3fv(uStage.camPos, camPos);\n gl.uniform3fv(uStage.lightWorld, lightWorld);\n gl.uniform1f(uStage.focalZ, focalZ);\n gl.uniform1f(uStage.causticScale, stageRecoverScale);\n gl.uniform1i(uStage.compareMask, state.compareMask ? 1 : 0);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, fboCaustic.tex);\n gl.uniform1i(uStage.causticTex, 0);\n gl.activeTexture(gl.TEXTURE1);\n gl.bindTexture(gl.TEXTURE_2D, fboBloomA.tex);\n gl.uniform1i(uStage.bloomTex, 1);\n gl.activeTexture(gl.TEXTURE2);\n gl.bindTexture(gl.TEXTURE_2D, targetTex);\n gl.uniform1i(uStage.targetTex, 2);\n\n gl.bindVertexArray(stageVAO);\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n\n // Copy rendered stage into sceneCopyTex so the 3D crystal block refracts the live caustic tabletop!\n gl.bindTexture(gl.TEXTURE_2D, sceneCopyTex);\n gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 0, 0, W, H);\n\n // 3B: Render 3D Sculpted Optical Crystal Block (Back faces then Front faces for true depth!)\n gl.useProgram(progGlass);\n gl.uniformMatrix4fv(uGlass.vp, false, currentVP);\n gl.uniform1f(uGlass.focalZ, focalZ);\n gl.uniform1f(uGlass.tGlass, T_GLASS);\n gl.uniform2f(uGlass.viewport, W, H);\n gl.uniform3fv(uGlass.camPos, camPos);\n gl.uniform3fv(uGlass.lightWorld, lightWorld);\n gl.uniform1f(uGlass.baseIOR, mat.nD);\n gl.uniform3fv(uGlass.glassTint, mat.tint);\n gl.uniform1i(uGlass.showInterf, state.showInterf ? 1 : 0);\n\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, heightTex);\n gl.uniform1i(uGlass.heightTex, 0);\n gl.activeTexture(gl.TEXTURE1);\n gl.bindTexture(gl.TEXTURE_2D, sceneCopyTex);\n gl.uniform1i(uGlass.sceneCopy, 1);\n\n gl.bindVertexArray(glassVAO);\n gl.enable(gl.CULL_FACE);\n gl.cullFace(gl.FRONT);\n gl.drawElements(gl.TRIANGLES, glassIndexCount, gl.UNSIGNED_INT, 0);\n gl.cullFace(gl.BACK);\n gl.drawElements(gl.TRIANGLES, glassIndexCount, gl.UNSIGNED_INT, 0);\n gl.disable(gl.CULL_FACE);\n\n // 3C: Additive 3D Diagnostic Lines (Ray Sheet, Optimal Transport Grid, Bench Guides) + Point Lamp\n const lineVertCount = buildDiagnosticLines(focalZ, mat.nD);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE, gl.ONE);\n gl.depthMask(false);\n\n if (lineVertCount > 0) {\n gl.useProgram(progLine);\n gl.uniformMatrix4fv(uLine.vp, false, currentVP);\n gl.bindVertexArray(lineVAO);\n gl.drawArrays(gl.LINES, 0, lineVertCount);\n }\n\n // 3D Point Lamp Filament Halo\n gl.useProgram(progLamp);\n gl.uniformMatrix4fv(uLamp.vp, false, currentVP);\n gl.uniform3fv(uLamp.pos, lightWorld);\n gl.uniform3f(uLamp.right, view[0], view[4], view[8]);\n gl.uniform3f(uLamp.up, view[1], view[5], view[9]);\n gl.uniform1f(uLamp.size, 0.34);\n gl.uniform1f(uLamp.lock, alignment);\n gl.bindVertexArray(emptyVAO);\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n\n gl.depthMask(true);\n gl.disable(gl.BLEND);\n requestAnimationFrame(frame);\n }\n\n requestAnimationFrame(frame);\n})();\n</script>\n</body>\n</html>\n","Overwrite":true,"Path":"~/run/index.html"}

    input

    {
      "Content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\" />\n<title>CAUSTIC — Inverse Optical Foundry</title>\n<style>\n  :root {\n    --bg: #07080c;\n    --panel: rgba(13, 15, 21, 0.78);\n    --panel-strong: rgba(16, 19, 27, 0.90);\n    --border: rgba(255, 255, 255, 0.09);\n    --border-hi: rgba(242, 189, 116, 0.42);\n    --text: #ece8df;\n    --muted: rgba(236, 232, 223, 0.54);\n    --faint: rgba(236, 232, 223, 0.30);\n    --gold: #f2bd74;\n    --gold-dim: rgba(242, 189, 116, 0.16);\n    --cyan: #7fd4e6;\n    --sans: ui-sans-serif, -apple-system, BlinkMacSystemFont, \"Inter\", \"Segoe UI\", Roboto, sans-serif;\n    --mono: ui-monospace, \"SF Mono\", \"JetBrains Mono\", \"Cascadia Code\", Menlo, Consolas, monospace;\n  }\n\n  * { box-sizing: border-box; margin: 0; padding: 0; -webkit-tap-highlight-color: transparent; }\n\n  html, body {\n    width: 100%;\n    height: 100%;\n    overflow: hidden;\n    background: var(--bg);\n    color: var(--text);\n    font-family: var(--sans);\n    user-select: none;\n    -webkit-user-select: none;\n  }\n\n  #glCanvas {\n    position: fixed;\n    inset: 0;\n    width: 100%;\n    height: 100%;\n    display: block;\n    touch-action: none;\n    cursor: grab;\n  }\n  #glCanvas.dragging-lamp { cursor: crosshair; }\n  #glCanvas.dragging-orbit { cursor: grabbing; }\n\n  /* Subtle HUD Layer */\n  .hud {\n    position: fixed;\n    inset: 0;\n    pointer-events: none;\n    display: flex;\n    flex-direction: column;\n    justify-content: space-between;\n    padding: 14px 16px;\n    z-index: 10;\n  }\n\n  .top-bar {\n    display: flex;\n    align-items: flex-start;\n    justify-content: space-between;\n    gap: 12px;\n  }\n\n  .brand-block {\n    pointer-events: auto;\n    display: flex;\n    flex-direction: column;\n    gap: 4px;\n    background: var(--panel);\n    backdrop-filter: blur(16px);\n    -webkit-backdrop-filter: blur(16px);\n    border: 1px solid var(--border);\n    border-radius: 10px;\n    padding: 8px 12px;\n    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.42);\n  }\n\n  .brand-row {\n    display: flex;\n    align-items: baseline;\n    gap: 9px;\n  }\n\n  .brand-title {\n    font-size: 12px;\n    font-weight: 650;\n    letter-spacing: 0.18em;\n    color: var(--text);\n  }\n\n  .brand-sub {\n    font-family: var(--mono);\n    font-size: 10px;\n    letter-spacing: 0.06em;\n    color: var(--muted);\n  }\n\n  .telemetry {\n    font-family: var(--mono);\n    font-size: 10px;\n    font-variant-numeric: tabular-nums;\n    color: var(--muted);\n    display: flex;\n    flex-wrap: wrap;\n    align-items: center;\n    gap: 8px;\n  }\n\n  .telemetry .dot {\n    width: 6px;\n    height: 6px;\n    border-radius: 50%;\n    background: var(--gold);\n    box-shadow: 0 0 8px var(--gold);\n    display: inline-block;\n  }\n  .telemetry.solving .dot {\n    background: var(--cyan);\n    box-shadow: 0 0 10px var(--cyan);\n  }\n\n  .top-actions {\n    pointer-events: auto;\n    display: flex;\n    align-items: center;\n    gap: 6px;\n    flex-wrap: wrap;\n    justify-content: flex-end;\n  }\n\n  button, select {\n    font-family: var(--sans);\n    font-size: 11px;\n    font-weight: 500;\n    color: var(--text);\n    background: var(--panel);\n    backdrop-filter: blur(16px);\n    -webkit-backdrop-filter: blur(16px);\n    border: 1px solid var(--border);\n    border-radius: 8px;\n    padding: 6px 10px;\n    cursor: pointer;\n    transition: border-color 0.16s ease, background 0.16s ease, color 0.16s ease, transform 0.1s ease;\n    display: inline-flex;\n    align-items: center;\n    gap: 5px;\n    white-space: nowrap;\n  }\n\n  button:hover, select:hover {\n    border-color: rgba(255, 255, 255, 0.22);\n    background: rgba(26, 30, 42, 0.86);\n  }\n\n  button:active { transform: translateY(1px); }\n\n  button.active {\n    background: var(--gold-dim);\n    border-color: var(--border-hi);\n    color: #ffe0b2;\n  }\n\n  button.cyan-active {\n    background: rgba(127, 212, 230, 0.15);\n    border-color: rgba(127, 212, 230, 0.45);\n    color: #c8f1fa;\n  }\n\n  /* Floating Sculpt / Loupe Card */\n  .loupe-card {\n    pointer-events: auto;\n    position: fixed;\n    right: 16px;\n    top: 58px;\n    width: 196px;\n    background: var(--panel-strong);\n    backdrop-filter: blur(20px);\n    -webkit-backdrop-filter: blur(20px);\n    border: 1px solid var(--border);\n    border-radius: 12px;\n    padding: 9px;\n    box-shadow: 0 14px 40px rgba(0, 0, 0, 0.55);\n    display: flex;\n    flex-direction: column;\n    gap: 7px;\n    z-index: 15;\n    transition: width 0.22s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.2s ease;\n  }\n\n  .loupe-card.expanded {\n    width: 244px;\n    border-color: var(--border-hi);\n  }\n\n  .loupe-card.collapsed .loupe-body {\n    display: none;\n  }\n  .loupe-card.collapsed {\n    width: auto;\n    padding: 6px 10px;\n  }\n\n  .loupe-head {\n    display: flex;\n    align-items: center;\n    justify-content: space-between;\n    gap: 6px;\n  }\n\n  .loupe-tabs {\n    display: flex;\n    gap: 3px;\n    background: rgba(255, 255, 255, 0.04);\n    padding: 2px;\n    border-radius: 6px;\n  }\n\n  .loupe-tabs button {\n    padding: 3px 7px;\n    font-size: 10px;\n    border: none;\n    background: transparent;\n    border-radius: 5px;\n    color: var(--muted);\n    backdrop-filter: none;\n  }\n  .loupe-tabs button.active {\n    background: rgba(242, 189, 116, 0.2);\n    color: #ffe2b8;\n  }\n\n  .loupe-toggle-btn {\n    padding: 2px 6px;\n    font-size: 10px;\n    border: none;\n    background: transparent;\n    color: var(--muted);\n  }\n\n  .loupe-body {\n    display: flex;\n    flex-direction: column;\n    gap: 7px;\n  }\n\n  .pad-wrap {\n    position: relative;\n    width: 100%;\n    aspect-ratio: 1 / 1;\n    border-radius: 8px;\n    overflow: hidden;\n    border: 1px solid rgba(255, 255, 255, 0.11);\n    background: #06070a;\n  }\n\n  #padCanvas {\n    width: 100%;\n    height: 100%;\n    display: block;\n    touch-action: none;\n    cursor: crosshair;\n  }\n\n  .pad-badge {\n    position: absolute;\n    left: 6px;\n    bottom: 5px;\n    font-family: var(--mono);\n    font-size: 9px;\n    color: rgba(255, 255, 255, 0.55);\n    background: rgba(6, 7, 10, 0.72);\n    padding: 2px 5px;\n    border-radius: 4px;\n    pointer-events: none;\n  }\n\n  .sculpt-tools {\n    display: flex;\n    flex-direction: column;\n    gap: 6px;\n  }\n\n  .tool-row {\n    display: flex;\n    gap: 4px;\n    align-items: center;\n  }\n\n  .tool-row button {\n    flex: 1;\n    justify-content: center;\n    padding: 4px 6px;\n    font-size: 10px;\n  }\n\n  .text-input-row {\n    display: flex;\n    gap: 4px;\n  }\n\n  .text-input-row input {\n    flex: 1;\n    min-width: 0;\n    background: rgba(0, 0, 0, 0.45);\n    border: 1px solid var(--border);\n    border-radius: 6px;\n    padding: 4px 7px;\n    color: var(--text);\n    font-family: var(--mono);\n    font-size: 11px;\n    outline: none;\n  }\n  .text-input-row input:focus {\n    border-color: var(--border-hi);\n  }\n\n  /* Bottom Instrument Dock */\n  .bottom-dock-wrap {\n    display: flex;\n    justify-content: center;\n    align-items: flex-end;\n    width: 100%;\n  }\n\n  .bottom-dock {\n    pointer-events: auto;\n    background: var(--panel);\n    backdrop-filter: blur(18px);\n    -webkit-backdrop-filter: blur(18px);\n    border: 1px solid var(--border);\n    border-radius: 12px;\n    padding: 8px 10px;\n    box-shadow: 0 12px 38px rgba(0, 0, 0, 0.55);\n    display: flex;\n    flex-direction: column;\n    gap: 7px;\n    max-width: 100%;\n  }\n\n  .dock-row {\n    display: flex;\n    align-items: center;\n    gap: 6px;\n    flex-wrap: wrap;\n    justify-content: center;\n  }\n\n  .dock-group {\n    display: flex;\n    align-items: center;\n    gap: 4px;\n    padding: 0 4px;\n  }\n\n  .sep {\n    width: 1px;\n    height: 18px;\n    background: var(--border);\n    margin: 0 2px;\n  }\n\n  .group-label {\n    font-family: var(--mono);\n    font-size: 9.5px;\n    letter-spacing: 0.06em;\n    text-transform: uppercase;\n    color: var(--faint);\n    margin-right: 3px;\n  }\n\n  .slider-pill {\n    display: inline-flex;\n    align-items: center;\n    gap: 7px;\n    background: rgba(255, 255, 255, 0.035);\n    border: 1px solid var(--border);\n    border-radius: 8px;\n    padding: 4px 9px;\n    font-family: var(--mono);\n    font-size: 10px;\n    color: var(--muted);\n  }\n\n  input[type=\"range\"] {\n    -webkit-appearance: none;\n    appearance: none;\n    width: 84px;\n    height: 3px;\n    background: rgba(255, 255, 255, 0.16);\n    border-radius: 2px;\n    outline: none;\n    cursor: pointer;\n  }\n  input[type=\"range\"]::-webkit-slider-thumb {\n    -webkit-appearance: none;\n    width: 12px;\n    height: 12px;\n    border-radius: 50%;\n    background: var(--gold);\n    border: 2px solid #161821;\n    box-shadow: 0 0 8px rgba(242, 189, 116, 0.65);\n  }\n\n  select {\n    padding: 4px 8px;\n    font-family: var(--mono);\n    font-size: 10px;\n    background-color: rgba(20, 23, 32, 0.92);\n  }\n\n  /* Subtle interaction hint that fades after first interaction */\n  .gesture-hint {\n    position: fixed;\n    left: 18px;\n    bottom: 98px;\n    font-family: var(--mono);\n    font-size: 10px;\n    color: var(--muted);\n    background: rgba(10, 12, 17, 0.66);\n    border: 1px solid rgba(255, 255, 255, 0.07);\n    padding: 5px 9px;\n    border-radius: 7px;\n    pointer-events: none;\n    transition: opacity 0.5s ease;\n  }\n  .gesture-hint.hidden { opacity: 0; }\n\n  @media (max-width: 760px) {\n    .hud { padding: 10px; }\n    .brand-sub { display: none; }\n    .loupe-card {\n      top: 54px;\n      right: 10px;\n      width: 152px;\n    }\n    .loupe-card.expanded { width: 198px; }\n    .sep { display: none; }\n    .gesture-hint { display: none; }\n    input[type=\"range\"] { width: 64px; }\n    button, select { padding: 5px 8px; font-size: 10.5px; }\n  }\n</style>\n</head>\n<body>\n<canvas id=\"glCanvas\"></canvas>\n\n<div class=\"hud\">\n  <div class=\"top-bar\">\n    <div class=\"brand-block\">\n      <div class=\"brand-row\">\n        <span class=\"brand-title\">CAUSTIC</span>\n        <span class=\"brand-sub\">MONGE–AMPÈRE OPTICS · EXACT 3D SNELL</span>\n      </div>\n      <div class=\"telemetry\" id=\"telemetryBar\">\n        <span class=\"dot\"></span>\n        <span id=\"statRays\">512K BEAMS</span>\n        <span>·</span>\n        <span id=\"statRelief\">RELIEF 4.6 mm</span>\n        <span>·</span>\n        <span id=\"statFocus\">ALIGN 99%</span>\n        <span>·</span>\n        <span id=\"statSolve\">PDE 120 ms</span>\n      </div>\n    </div>\n\n    <div class=\"top-actions\">\n      <button id=\"btnAlign\" title=\"Glide point lamp back to optical design axis\">◎ Align Light</button>\n      <button id=\"btnAudio\" title=\"Toggle crystalline optical harmonic synthesis\">♪ Sound Off</button>\n      <button id=\"btnStl\" title=\"Download watertight binary 3D .STL lens mesh (100×100mm)\">⬇ Lens .STL</button>\n    </div>\n  </div>\n\n  <div class=\"gesture-hint\" id=\"gestureHint\">\n    Drag lamp or stage to steer light · Drag upper frame to orbit 3D · Sketch in pad to carve glass\n  </div>\n\n  <div class=\"bottom-dock-wrap\">\n    <div class=\"bottom-dock\">\n      <div class=\"dock-row\">\n        <div class=\"dock-group\" id=\"presetGroup\">\n          <span class=\"group-label\">Lens</span>\n          <button data-preset=\"astrolabe\" class=\"active\">Astrolabe</button>\n          <button data-preset=\"nautilus\">Nautilus</button>\n          <button data-preset=\"saturn\">Saturn</button>\n          <button data-preset=\"crane\">Crane</button>\n          <button data-preset=\"lorenz\">Lorenz</button>\n          <button data-preset=\"custom\" id=\"btnCustomPreset\">✎ Draw / Type</button>\n        </div>\n        <div class=\"sep\"></div>\n        <div class=\"dock-group\">\n          <span class=\"group-label\">View</span>\n          <button data-cam=\"studio\" class=\"active\">3D Bench</button>\n          <button data-cam=\"profile\">Glass Profile</button>\n          <button data-cam=\"top\">Overhead</button>\n        </div>\n      </div>\n\n      <div class=\"dock-row\">\n        <div class=\"slider-pill\" title=\"Vertical distance between sculpted glass lens and stone stage\">\n          <span>Focal Z</span>\n          <input type=\"range\" id=\"focalSlider\" min=\"0.45\" max=\"1.65\" step=\"0.005\" value=\"1.00\" />\n          <span id=\"focalVal\">110 mm</span>\n        </div>\n\n        <select id=\"glassSelect\" title=\"Optical material index of refraction & Abbe chromatic dispersion\">\n          <option value=\"bk7\" selected>Crown BK7 (n=1.52)</option>\n          <option value=\"silica\">Fused Silica (n=1.46)</option>\n          <option value=\"flint\">Dense Flint SF11 (n=1.78)</option>\n          <option value=\"diamond\">Diamond (n=2.42)</option>\n        </select>\n        <button id=\"btnRegrind\" style=\"display:none\" class=\"cyan-active\" title=\"Re-solve PDE lens curvature for this refractive index\">↻ Re-grind</button>\n\n        <div class=\"sep\"></div>\n\n        <div class=\"dock-group\">\n          <button id=\"btnRays\" class=\"cyan-active\" title=\"Show 3D Snell refraction laser slice through the glass\">Ray Sheet</button>\n          <button id=\"btnGrid\" title=\"Show Optimal Transport (Brenier) equal-flux grid deformation\">Photon Grid</button>\n          <button id=\"btnInterf\" title=\"Show laser Mach-Zehnder thickness interference fringes on glass\">Interferogram</button>\n          <button id=\"btnCompare\" title=\"Compare absorptive stencil mask (92% light lost) vs lossless refractive lens\">Mask vs. Lens</button>\n        </div>\n      </div>\n    </div>\n  </div>\n</div>\n\n<!-- Floating Target & Glass Relief Sculptor Loupe -->\n<div class=\"loupe-card\" id=\"loupeCard\">\n  <div class=\"loupe-head\">\n    <div class=\"loupe-tabs\">\n      <button id=\"tabTarget\" class=\"active\">Target I(x,y)</button>\n      <button id=\"tabHeight\">Glass h(x,y)</button>\n    </div>\n    <button class=\"loupe-toggle-btn\" id=\"btnToggleLoupe\" title=\"Minimize/Expand Pad\">–</button>\n  </div>\n  <div class=\"loupe-body\">\n    <div class=\"pad-wrap\">\n      <canvas id=\"padCanvas\" width=\"256\" height=\"256\"></canvas>\n      <div class=\"pad-badge\" id=\"padBadge\">Draw to carve lens</div>\n    </div>\n    <div class=\"sculpt-tools\">\n      <div class=\"tool-row\">\n        <button id=\"btnBrushDraw\" class=\"active\">✎ Glow Brush</button>\n        <button id=\"btnBrushErase\">⌫ Erase</button>\n        <button id=\"btnPadClear\">Clear</button>\n      </div>\n      <div class=\"text-input-row\">\n        <input type=\"text\" id=\"glyphInput\" maxlength=\"9\" placeholder=\"Type word / symbol…\" />\n        <button id=\"btnCarveText\">Carve</button>\n      </div>\n    </div>\n  </div>\n</div>\n\n<script>\n(() => {\n  \"use strict\";\n\n  // ============================================================================\n  // 1. INLINE WEB WORKER: MULTISCALE MOSER–SNELL OPTIMAL TRANSPORT PDE SOLVER\n  //    Solves nabla^2 psi = I_sim - I_target + Exact 3D Inverse Snell's Law\n  //    using radix-2 Makhoul 2D DCT-II Neumann Poisson on 128x128 -> 256x256.\n  // ============================================================================\n  const WORKER_SOURCE = `\n    \"use strict\";\n    class DCT2D {\n      constructor(N) {\n        this.N = N;\n        this.bitRev = new Uint32Array(N);\n        const bits = Math.log2(N) | 0;\n        for (let i = 0; i < N; i++) {\n          let r = 0, x = i;\n          for (let b = 0; b < bits; b++) { r = (r << 1) | (x & 1); x >>= 1; }\n          this.bitRev[i] = r;\n        }\n        this.cosTab = new Float32Array(N / 2);\n        this.sinTab = new Float32Array(N / 2);\n        for (let k = 0; k < N / 2; k++) {\n          const ang = -2 * Math.PI * k / N;\n          this.cosTab[k] = Math.cos(ang);\n          this.sinTab[k] = Math.sin(ang);\n        }\n        this.dctCos = new Float32Array(N);\n        this.dctSin = new Float32Array(N);\n        for (let k = 0; k < N; k++) {\n          const ang = -Math.PI * k / (2 * N);\n          this.dctCos[k] = Math.cos(ang);\n          this.dctSin[k] = Math.sin(ang);\n        }\n        this.eig1D = new Float32Array(N);\n        for (let k = 0; k < N; k++) {\n          this.eig1D[k] = 2 * Math.cos(Math.PI * k / N) - 2;\n        }\n        this.re = new Float32Array(N);\n        this.im = new Float32Array(N);\n        this.tmp = new Float32Array(N * N);\n      }\n\n      fft(re, im, invert) {\n        const N = this.N, bitRev = this.bitRev;\n        for (let i = 0; i < N; i++) {\n          const j = bitRev[i];\n          if (i < j) {\n            let t = re[i]; re[i] = re[j]; re[j] = t;\n            t = im[i]; im[i] = im[j]; im[j] = t;\n          }\n        }\n        const sign = invert ? -1 : 1;\n        for (let len = 2; len <= N; len <<= 1) {\n          const half = len >> 1, step = N / len;\n          for (let i = 0; i < N; i += len) {\n            for (let j = 0; j < half; j++) {\n              const idx = j * step;\n              const wr = this.cosTab[idx], wi = sign * this.sinTab[idx];\n              const uRe = re[i + j], uIm = im[i + j];\n              const vRe = re[i + j + half] * wr - im[i + j + half] * wi;\n              const vIm = re[i + j + half] * wi + im[i + j + half] * wr;\n              re[i + j] = uRe + vRe; im[i + j] = uIm + vIm;\n              re[i + j + half] = uRe - vRe; im[i + j + half] = uIm - vIm;\n            }\n          }\n        }\n        if (invert) {\n          const invN = 1 / N;\n          for (let i = 0; i < N; i++) { re[i] *= invN; im[i] *= invN; }\n        }\n      }\n\n      dct1d(src, offset, stride, dst, dOffset, dStride) {\n        const N = this.N, half = N >> 1, re = this.re, im = this.im;\n        for (let i = 0; i < half; i++) {\n          re[i] = src[offset + (2 * i) * stride];\n          re[N - 1 - i] = src[offset + (2 * i + 1) * stride];\n          im[i] = 0; im[N - 1 - i] = 0;\n        }\n        this.fft(re, im, false);\n        for (let k = 0; k < N; k++) {\n          dst[dOffset + k * dStride] = 2 * (re[k] * this.dctCos[k] - im[k] * this.dctSin[k]);\n        }\n      }\n\n      idct1d(src, offset, stride, dst, dOffset, dStride) {\n        const N = this.N, half = N >> 1, re = this.re, im = this.im;\n        re[0] = src[offset] * 0.5; im[0] = 0;\n        for (let k = 1; k < N; k++) {\n          const a = 0.5 * src[offset + k * stride];\n          const b = -0.5 * src[offset + (N - k) * stride];\n          const cs = this.dctCos[k], sn = -this.dctSin[k];\n          re[k] = a * cs - b * sn;\n          im[k] = a * sn + b * cs;\n        }\n        this.fft(re, im, true);\n        for (let i = 0; i < half; i++) {\n          dst[dOffset + (2 * i) * dStride] = re[i];\n          dst[dOffset + (2 * i + 1) * dStride] = re[N - 1 - i];\n        }\n      }\n\n      solvePoisson(rhs, out) {\n        const N = this.N, tmp = this.tmp, eig = this.eig1D;\n        for (let y = 0; y < N; y++) this.dct1d(rhs, y * N, 1, tmp, y * N, 1);\n        for (let x = 0; x < N; x++) this.dct1d(tmp, x, N, out, x, N);\n        out[0] = 0;\n        for (let y = 0; y < N; y++) {\n          const ey = eig[y];\n          for (let x = 0; x < N; x++) {\n            if (x === 0 && y === 0) continue;\n            out[y * N + x] /= (eig[x] + ey);\n          }\n        }\n        for (let x = 0; x < N; x++) this.idct1d(out, x, N, tmp, x, N);\n        for (let y = 0; y < N; y++) this.idct1d(tmp, y * N, 1, out, y * N, 1);\n      }\n\n      gaussianBlur(src, out, sigma) {\n        if (sigma <= 0) { out.set(src); return; }\n        const N = this.N, tmp = this.tmp;\n        for (let y = 0; y < N; y++) this.dct1d(src, y * N, 1, tmp, y * N, 1);\n        for (let x = 0; x < N; x++) this.dct1d(tmp, x, N, out, x, N);\n        const sigScale = 0.5 * sigma * sigma * (Math.PI * Math.PI) / (N * N);\n        for (let y = 0; y < N; y++) {\n          for (let x = 0; x < N; x++) {\n            out[y * N + x] *= Math.exp(-sigScale * (x * x + y * y));\n          }\n        }\n        for (let x = 0; x < N; x++) this.idct1d(out, x, N, tmp, x, N);\n        for (let y = 0; y < N; y++) this.idct1d(tmp, y * N, 1, out, y * N, 1);\n      }\n    }\n\n    function createLevel(N) {\n      return {\n        N, dct: new DCT2D(N), dx: 2.0 / N,\n        IinX: new Float32Array(N * N), IinY: new Float32Array(N * N), IinZ: new Float32Array(N * N),\n        rho0: new Float32Array(N * N), sumRho0: 0,\n        Isim: new Float32Array(N * N), targBlur: new Float32Array(N * N),\n        rhs: new Float32Array(N * N), psi: new Float32Array(N * N),\n        gpX: new Float32Array(N * N), gpY: new Float32Array(N * N),\n        rX: new Float32Array(N * N), rY: new Float32Array(N * N),\n        desX: new Float32Array(N * N), desY: new Float32Array(N * N),\n        gx: new Float32Array(N * N), gy: new Float32Array(N * N)\n      };\n    }\n\n    function updateIncidentRays(lv, F, T_glass, nGlass, Z_light) {\n      const N = lv.N;\n      lv.F = F; lv.nGlass = nGlass;\n      let sum = 0;\n      for (let y = 0; y < N; y++) {\n        const py = ((y + 0.5) / N) * 2 - 1;\n        for (let x = 0; x < N; x++) {\n          const px = ((x + 0.5) / N) * 2 - 1;\n          const dz = -(Z_light - (F + T_glass));\n          const len = Math.hypot(px, py, dz);\n          const ix = px / len, iy = py / len, iz = dz / len;\n          const eta = 1.0 / nGlass, cosI = -iz;\n          const idx = y * N + x;\n          lv.IinX[idx] = eta * ix;\n          lv.IinY[idx] = eta * iy;\n          lv.IinZ[idx] = -Math.sqrt(Math.max(1e-6, 1 - eta * eta * (1 - cosI * cosI)));\n          const flux = Math.pow(cosI, 3);\n          lv.rho0[idx] = flux;\n          sum += flux;\n        }\n      }\n      lv.sumRho0 = sum;\n    }\n\n    function solveInverseSnellH(lv, desX, desY, h) {\n      const { N, dx, F, nGlass, IinX, IinY, IinZ, gx, gy, rhs, dct } = lv;\n      for (let y = 0; y < N; y++) {\n        const py = ((y + 0.5) / N) * 2 - 1;\n        for (let x = 0; x < N; x++) {\n          const i = y * N + x;\n          const px = ((x + 0.5) / N) * 2 - 1;\n          const pz = F + h[i];\n          const dxP = (desX[i] / N) * 2 - 1 - px;\n          const dyP = (desY[i] / N) * 2 - 1 - py;\n          const dzP = -pz;\n          const invL = 1.0 / Math.hypot(dxP, dyP, dzP);\n          const Vx = dxP * invL - nGlass * IinX[i];\n          const Vy = dyP * invL - nGlass * IinY[i];\n          const Vz = dzP * invL - nGlass * IinZ[i];\n          gx[i] = -Vx / Vz;\n          gy[i] = -Vy / Vz;\n        }\n      }\n      for (let y = 0; y < N; y++) {\n        for (let x = 0; x < N; x++) {\n          const fr = (x < N - 1) ? 0.5 * (gx[y * N + x] + gx[y * N + x + 1]) : 0;\n          const fl = (x > 0)     ? 0.5 * (gx[y * N + x - 1] + gx[y * N + x]) : 0;\n          const ft = (y < N - 1) ? 0.5 * (gy[y * N + x] + gy[(y + 1) * N + x]) : 0;\n          const fb = (y > 0)     ? 0.5 * (gy[(y - 1) * N + x] + gy[y * N + x]) : 0;\n          rhs[y * N + x] = (fr - fl + ft - fb) * dx;\n        }\n      }\n      dct.solvePoisson(rhs, h);\n    }\n\n    function traceSplatFast(lv, h) {\n      const { N, dx, F, nGlass, IinX, IinY, IinZ, rho0, sumRho0, Isim, rX, rY } = lv;\n      Isim.fill(0);\n      for (let y = 0; y < N; y++) {\n        for (let x = 0; x < N; x++) {\n          const idx = y * N + x;\n          const hx = (x > 0 && x < N - 1) ? (h[idx + 1] - h[idx - 1]) / (2 * dx)\n                   : (x === 0 ? (h[idx + 1] - h[idx]) / dx : (h[idx] - h[idx - 1]) / dx);\n          const hy = (y > 0 && y < N - 1) ? (h[idx + N] - h[idx - N]) / (2 * dx)\n                   : (y === 0 ? (h[idx + N] - h[idx]) / dx : (h[idx] - h[idx - N]) / dx);\n          const invN = 1.0 / Math.sqrt(hx * hx + hy * hy + 1.0);\n          const nx = -hx * invN, ny = -hy * invN, nz = invN;\n          const ix = IinX[idx], iy = IinY[idx], iz = IinZ[idx];\n          const cosI = -(ix * nx + iy * ny + iz * nz);\n          const k = 1.0 - nGlass * nGlass * (1.0 - cosI * cosI);\n          const s = nGlass * cosI - Math.sqrt(Math.max(1e-6, k));\n          const tx = nGlass * ix + s * nx, ty = nGlass * iy + s * ny, tz = nGlass * iz + s * nz;\n          const px = ((x + 0.5) / N) * 2 - 1, py = ((y + 0.5) / N) * 2 - 1, pz = F + h[idx];\n          const t = -pz / tz;\n          rX[idx] = ((px + t * tx) * 0.5 + 0.5) * N;\n          rY[idx] = ((py + t * ty) * 0.5 + 0.5) * N;\n        }\n      }\n      for (let y = 0; y < N - 1; y++) {\n        for (let x = 0; x < N - 1; x++) {\n          const i00 = y * N + x, i10 = i00 + 1, i01 = i00 + N, i11 = i01 + 1;\n          const x00 = rX[i00], y00 = rY[i00], x10 = rX[i10], y10 = rY[i10];\n          const x01 = rX[i01], y01 = rY[i01], x11 = rX[i11], y11 = rY[i11];\n          const flux = 0.25 * (rho0[i00] + rho0[i10] + rho0[i01] + rho0[i11]);\n          const span = Math.max(Math.abs(x11 - x00), Math.abs(y11 - y00), Math.abs(x10 - x01), Math.abs(y10 - y01));\n          const subs = span > 3.5 ? (span > 7 ? 5 : 3) : 2;\n          const wSub = flux / (subs * subs);\n          for (let sy = 0; sy < subs; sy++) {\n            const v = (sy + 0.5) / subs, mv = 1 - v;\n            for (let sx = 0; sx < subs; sx++) {\n              const u = (sx + 0.5) / subs, mu = 1 - u;\n              const px = Math.max(0, Math.min(N - 1.001, mu * mv * x00 + u * mv * x10 + mu * v * x01 + u * v * x11 - 0.5));\n              const py = Math.max(0, Math.min(N - 1.001, mu * mv * y00 + u * mv * y10 + mu * v * y01 + u * v * y11 - 0.5));\n              const ix = px | 0, iy = py | 0, fx = px - ix, fy = py - iy;\n              const base = iy * N + ix;\n              Isim[base] += wSub * (1 - fx) * (1 - fy);\n              Isim[base + 1] += wSub * fx * (1 - fy);\n              Isim[base + N] += wSub * (1 - fx) * fy;\n              Isim[base + N + 1] += wSub * fx * fy;\n            }\n          }\n        }\n      }\n      let s = 0;\n      for (let i = 0; i < N * N; i++) s += Isim[i];\n      if (s > 0) { const sc = sumRho0 / s; for (let i = 0; i < N * N; i++) Isim[i] *= sc; }\n    }\n\n    function bSample(arr, N, gxPos, gyPos) {\n      const px = Math.max(0, Math.min(N - 1.001, gxPos - 0.5));\n      const py = Math.max(0, Math.min(N - 1.001, gyPos - 0.5));\n      const ix = px | 0, iy = py | 0, fx = px - ix, fy = py - iy;\n      const row = iy * N + ix;\n      return (1 - fx) * (1 - fy) * arr[row] + fx * (1 - fy) * arr[row + 1] +\n             (1 - fx) * fy * arr[row + N] + fx * fy * arr[row + N + 1];\n    }\n\n    const lv128 = createLevel(128);\n    const lv256 = createLevel(256);\n\n    self.onmessage = (e) => {\n      const { id, target256, F, T_glass, nGlass, Z_light } = e.data;\n      const t0 = performance.now();\n      updateIncidentRays(lv128, F, T_glass, nGlass, Z_light);\n      updateIncidentRays(lv256, F, T_glass, nGlass, Z_light);\n\n      const N = 128;\n      const targ128 = new Float32Array(N * N);\n      let sumT128 = 0;\n      for (let y = 0; y < N; y++) {\n        for (let x = 0; x < N; x++) {\n          const i0 = (2 * y) * 256 + (2 * x);\n          // Enforce clean C^2 ambient floor & soft aperture margin so boundary stays diffeomorphic\n          const u = (x + 0.5) / N * 2 - 1, v = (y + 0.5) / N * 2 - 1;\n          const edge = Math.max(Math.abs(u), Math.abs(v));\n          const wEdge = edge > 0.85 ? Math.max(0, 1 - (edge - 0.85) / 0.13) : 1.0;\n          let raw = 0.25 * (target256[i0] + target256[i0 + 1] + target256[i0 + 256] + target256[i0 + 257]);\n          raw = 0.032 + Math.max(0, raw - 0.032) * (wEdge * wEdge);\n          targ128[y * N + x] = raw;\n          sumT128 += raw;\n        }\n      }\n      const sc128 = lv128.sumRho0 / sumT128;\n      for (let i = 0; i < N * N; i++) targ128[i] *= sc128;\n\n      const h128 = new Float32Array(N * N);\n      for (let y = 0; y < N; y++) {\n        for (let x = 0; x < N; x++) {\n          lv128.desX[y * N + x] = x + 0.5;\n          lv128.desY[y * N + x] = y + 0.5;\n        }\n      }\n      solveInverseSnellH(lv128, lv128.desX, lv128.desY, h128);\n      solveInverseSnellH(lv128, lv128.desX, lv128.desY, h128);\n\n      const sigmas = [7.0, 4.2, 2.5, 1.4, 0.7, 0.0, 0.0, 0.0, 0.0];\n      const meanI = lv128.sumRho0 / (N * N);\n      for (let iter = 0; iter < sigmas.length; iter++) {\n        const sig = sigmas[iter];\n        lv128.dct.gaussianBlur(targ128, lv128.targBlur, sig);\n        traceSplatFast(lv128, h128);\n        if (sig > 0.2) lv128.dct.gaussianBlur(lv128.Isim, lv128.Isim, sig * 0.45);\n        for (let i = 0; i < N * N; i++) lv128.rhs[i] = lv128.Isim[i] - lv128.targBlur[i];\n        lv128.dct.solvePoisson(lv128.rhs, lv128.psi);\n        for (let y = 0; y < N; y++) {\n          const ym = Math.max(0, y - 1), yp = Math.min(N - 1, y + 1), dyS = yp - ym;\n          for (let x = 0; x < N; x++) {\n            const xm = Math.max(0, x - 1), xp = Math.min(N - 1, x + 1), dxS = xp - xm;\n            lv128.gpX[y * N + x] = (lv128.psi[y * N + xp] - lv128.psi[y * N + xm]) / dxS;\n            lv128.gpY[y * N + x] = (lv128.psi[yp * N + x] - lv128.psi[ym * N + x]) / dyS;\n          }\n        }\n        for (let i = 0; i < N * N; i++) {\n          const rx = lv128.rX[i], ry = lv128.rY[i];\n          const denom = Math.max(0.08 * meanI, 0.5 * (bSample(lv128.Isim, N, rx, ry) + bSample(lv128.targBlur, N, rx, ry)));\n          lv128.desX[i] = Math.max(0.5, Math.min(N - 0.5, rx + 0.80 * (bSample(lv128.gpX, N, rx, ry) / denom)));\n          lv128.desY[i] = Math.max(0.5, Math.min(N - 0.5, ry + 0.80 * (bSample(lv128.gpY, N, rx, ry) / denom)));\n        }\n        solveInverseSnellH(lv128, lv128.desX, lv128.desY, h128);\n      }\n\n      const N2 = 256;\n      const h256 = new Float32Array(N2 * N2);\n      for (let y = 0; y < N2; y++) {\n        const gy = (y + 0.5) * 0.5;\n        for (let x = 0; x < N2; x++) {\n          h256[y * N2 + x] = bSample(h128, N, (x + 0.5) * 0.5, gy);\n        }\n      }\n      const targ256 = new Float32Array(N2 * N2);\n      let sumT2 = 0;\n      for (let y = 0; y < N2; y++) {\n        const v = (y + 0.5) / N2 * 2 - 1;\n        for (let x = 0; x < N2; x++) {\n          const u = (x + 0.5) / N2 * 2 - 1;\n          const edge = Math.max(Math.abs(u), Math.abs(v));\n          const wEdge = edge > 0.85 ? Math.max(0, 1 - (edge - 0.85) / 0.13) : 1.0;\n          const idx = y * N2 + x;\n          const raw = 0.032 + Math.max(0, target256[idx] - 0.032) * (wEdge * wEdge);\n          targ256[idx] = raw;\n          sumT2 += raw;\n        }\n      }\n      const sc2 = lv256.sumRho0 / sumT2;\n      for (let i = 0; i < N2 * N2; i++) targ256[i] *= sc2;\n      const meanI2 = lv256.sumRho0 / (N2 * N2);\n\n      for (let iter = 0; iter < 3; iter++) {\n        traceSplatFast(lv256, h256);\n        for (let i = 0; i < N2 * N2; i++) lv256.rhs[i] = lv256.Isim[i] - targ256[i];\n        lv256.dct.solvePoisson(lv256.rhs, lv256.psi);\n        for (let y = 0; y < N2; y++) {\n          const ym = Math.max(0, y - 1), yp = Math.min(N2 - 1, y + 1), dyS = yp - ym;\n          for (let x = 0; x < N2; x++) {\n            const xm = Math.max(0, x - 1), xp = Math.min(N2 - 1, x + 1), dxS = xp - xm;\n            lv256.gpX[y * N2 + x] = (lv256.psi[y * N2 + xp] - lv256.psi[y * N2 + xm]) / dxS;\n            lv256.gpY[y * N2 + x] = (lv256.psi[yp * N2 + x] - lv256.psi[ym * N2 + x]) / dyS;\n          }\n        }\n        for (let i = 0; i < N2 * N2; i++) {\n          const rx = lv256.rX[i], ry = lv256.rY[i];\n          const denom = Math.max(0.06 * meanI2, 0.5 * (bSample(lv256.Isim, N2, rx, ry) + bSample(targ256, N2, rx, ry)));\n          lv256.desX[i] = Math.max(0.5, Math.min(N2 - 0.5, rx + 0.75 * (bSample(lv256.gpX, N2, rx, ry) / denom)));\n          lv256.desY[i] = Math.max(0.5, Math.min(N2 - 0.5, ry + 0.75 * (bSample(lv256.gpY, N2, rx, ry) / denom)));\n        }\n        solveInverseSnellH(lv256, lv256.desX, lv256.desY, h256);\n      }\n\n      let minH = Infinity, maxH = -Infinity;\n      for (let i = 0; i < N2 * N2; i++) {\n        if (h256[i] < minH) minH = h256[i];\n        if (h256[i] > maxH) maxH = h256[i];\n      }\n      const solveMs = performance.now() - t0;\n      self.postMessage({\n        id,\n        h256,\n        minH,\n        maxH,\n        reliefMm: (maxH - minH) * 50.0, // 2.0 normalized units == 100mm physical width\n        solveMs\n      }, [h256.buffer]);\n    };\n  `;\n\n  // ============================================================================\n  // 2. OPTICAL CONSTANTS & PROCEDURAL TARGET ARTWORKS (256 x 256)\n  // ============================================================================\n  const N_GRID = 256;\n  const DESIGN_F = 2.20;      // 110 mm design focal distance (1.0 unit = 50 mm)\n  const T_GLASS  = 0.28;      // 14 mm base optical crystal thickness\n  const DESIGN_Z_LIGHT = 7.4; // 370 mm lamp zenith height\n\n  const MATERIALS = {\n    bk7:     { name: \"Crown BK7\",    nD: 1.517, disp: 0.011, tint: [0.92, 0.98, 0.97] },\n    silica:  { name: \"Fused Silica\", nD: 1.458, disp: 0.008, tint: [0.96, 0.98, 1.00] },\n    flint:   { name: \"Dense Flint\",  nD: 1.785, disp: 0.032, tint: [0.98, 0.96, 0.88] },\n    diamond: { name: \"Diamond\",      nD: 2.417, disp: 0.052, tint: [0.93, 0.96, 1.00] }\n  };\n\n  function sdSegment(px, py, ax, ay, bx, by) {\n    const vx = px - ax, vy = py - ay, ux = bx - ax, uy = by - ay;\n    const h = Math.max(0, Math.min(1, (vx * ux + vy * uy) / (ux * ux + uy * uy + 1e-9)));\n    return Math.hypot(vx - ux * h, vy - uy * h);\n  }\n\n  const PRESETS = {\n    astrolabe(N = N_GRID) {\n      const t = new Float32Array(N * N);\n      for (let y = 0; y < N; y++) {\n        const v = (y + 0.5) / N * 2 - 1;\n        for (let x = 0; x < N; x++) {\n          const u = (x + 0.5) / N * 2 - 1;\n          const r = Math.hypot(u, v), th = Math.atan2(v, u);\n          let val = 0.032;\n          // Outer degree ring + graduations\n          val += 1.05 * Math.exp(-Math.pow((r - 0.73) / 0.017, 2));\n          if (r > 0.67 && r < 0.74) {\n            const ticks = Math.pow(Math.abs(Math.cos(18 * th)), 28);\n            val += 0.45 * ticks * Math.exp(-Math.pow((r - 0.70) / 0.028, 2));\n          }\n          // Equator & Tropic rings\n          val += 0.78 * Math.exp(-Math.pow((r - 0.49) / 0.014, 2));\n          // Off-center ecliptic zodiac circle (astrolabe rete)\n          const re = Math.hypot(u - 0.13, v - 0.11);\n          val += 0.98 * Math.exp(-Math.pow((re - 0.41) / 0.016, 2));\n          // 8-point compass spider lines\n          const star = Math.abs(Math.sin(4 * th)) * r;\n          if (r < 0.73 && r > 0.10) {\n            val += 0.78 * Math.exp(-Math.pow(star / 0.0135, 2)) * (1 - 0.32 * r);\n          }\n          // Central sun ring & pinpoint core\n          val += 1.22 * Math.exp(-Math.pow((r - 0.115) / 0.015, 2));\n          val += 0.95 * Math.exp(-Math.pow(r / 0.032, 2));\n          t[y * N + x] = Math.min(1.4, val);\n        }\n      }\n      return t;\n    },\n\n    nautilus(N = N_GRID) {\n      const t = new Float32Array(N * N);\n      t.fill(0.032);\n      const a = 0.033, b = 0.174;\n      const pts = [];\n      for (let th = 0; th <= 5.42 * Math.PI; th += 0.011) {\n        const r = a * Math.exp(b * th);\n        if (r > 0.74) break;\n        pts.push([r * Math.cos(th) - 0.06, r * Math.sin(th) - 0.02, 0.015 + 0.008 * (r / 0.74), 1.18]);\n      }\n      for (let k = 10; k <= 33; k++) {\n        const th = k * 0.50;\n        const rOut = a * Math.exp(b * th);\n        const rIn = a * Math.exp(b * (th - 2 * Math.PI));\n        if (rOut > 0.73 || rIn < 0.024) continue;\n        for (let s = 0; s <= 1; s += 0.035) {\n          const rr = rIn + (rOut - rIn) * s;\n          const ang = th - 0.23 * Math.sin(Math.PI * s);\n          pts.push([rr * Math.cos(ang) - 0.06, rr * Math.sin(ang) - 0.02, 0.012, 0.78]);\n        }\n      }\n      for (const [cx, cy, rad, inten] of pts) {\n        const gx = (cx * 0.5 + 0.5) * N, gy = (cy * 0.5 + 0.5) * N;\n        const sig = rad * 0.5 * N, rPix = Math.ceil(sig * 2.8);\n        const x0 = Math.max(0, Math.floor(gx - rPix)), x1 = Math.min(N - 1, Math.ceil(gx + rPix));\n        const y0 = Math.max(0, Math.floor(gy - rPix)), y1 = Math.min(N - 1, Math.ceil(gy + rPix));\n        for (let y = y0; y <= y1; y++) {\n          for (let x = x0; x <= x1; x++) {\n            const d2 = ((x + 0.5 - gx) ** 2 + (y + 0.5 - gy) ** 2) / (sig * sig);\n            if (d2 < 7.5) {\n              const v = 0.032 + inten * Math.exp(-d2);\n              if (v > t[y * N + x]) t[y * N + x] = Math.min(1.4, v);\n            }\n          }\n        }\n      }\n      return t;\n    },\n\n    saturn(N = N_GRID) {\n      const t = new Float32Array(N * N);\n      const tilt = -0.40, cs = Math.cos(tilt), sn = Math.sin(tilt);\n      const Rplanet = 0.225;\n      for (let y = 0; y < N; y++) {\n        const py = (y + 0.5) / N * 2 - 1;\n        for (let x = 0; x < N; x++) {\n          const px = (x + 0.5) / N * 2 - 1;\n          const rx = px * cs - py * sn, ry = px * sn + py * cs;\n          const rp = Math.hypot(rx, ry / 0.90);\n          let val = 0.032;\n          const rRing = Math.hypot(rx, ry / 0.28);\n          const inFront = ry < 0;\n          const behindPlanet = (rp < Rplanet * 0.98) && !inFront;\n          const inShadow = (ry > 0) && (rx > 0.04) && (Math.abs(ry - 0.16 * rx) < 0.155);\n\n          if (!behindPlanet && !inShadow) {\n            if (rRing > 0.31 && rRing < 0.50) {\n              const w = Math.sin(Math.PI * (rRing - 0.31) / 0.19);\n              val += 1.08 * Math.pow(Math.max(0, w), 0.55) * (0.86 + 0.14 * Math.sin(rRing * 95));\n            }\n            if (rRing > 0.535 && rRing < 0.685) {\n              const w = Math.sin(Math.PI * (rRing - 0.535) / 0.15);\n              val += 0.85 * Math.pow(Math.max(0, w), 0.5);\n            }\n          }\n          const occByFront = inFront && (rRing > 0.31 && rRing < 0.685);\n          if (rp <= Rplanet * 1.04 && !occByFront) {\n            const limb = Math.exp(-Math.pow((rp - Rplanet * 0.94) / 0.020, 2));\n            const body = rp < Rplanet ? (0.42 * (1 - 0.45 * rp / Rplanet) * (0.82 + 0.22 * Math.cos(ry * 28)) * Math.max(0.15, 0.65 - 1.2 * rx)) : 0;\n            val = Math.max(val, 0.032 + 1.16 * limb + body);\n          }\n          const dTitan = Math.hypot(px + 0.60, py - 0.46);\n          const dEnc = Math.hypot(px - 0.52, py + 0.44);\n          val += 1.05 * Math.exp(-(dTitan * dTitan) / (0.019 * 0.019));\n          val += 0.82 * Math.exp(-(dEnc * dEnc) / (0.015 * 0.015));\n          t[y * N + x] = Math.min(1.38, val);\n        }\n      }\n      return t;\n    },\n\n    crane(N = N_GRID) {\n      const t = new Float32Array(N * N);\n      const segs = [\n        // Sweeping origami upper wings\n        [-0.03, 0.06, -0.71, 0.52, 1.18, 0.016],\n        [-0.71, 0.52, -0.28, -0.09, 1.12, 0.015],\n        [-0.28, -0.09, -0.03, 0.06, 0.86, 0.013],\n        [-0.71, 0.52, -0.14, 0.18, 0.64, 0.012],\n        [0.06, 0.10, 0.70, 0.46, 1.18, 0.016],\n        [0.70, 0.46, 0.23, -0.07, 1.08, 0.015],\n        [0.23, -0.07, 0.06, 0.10, 0.82, 0.013],\n        [0.70, 0.46, 0.17, 0.17, 0.60, 0.012],\n        // Central origami body facets\n        [-0.03, 0.06, 0.06, 0.10, 0.96, 0.014],\n        [-0.03, 0.06, -0.02, -0.27, 1.02, 0.014],\n        [0.06, 0.10, -0.02, -0.27, 1.02, 0.014],\n        [-0.28, -0.09, -0.02, -0.27, 0.94, 0.014],\n        [0.23, -0.07, -0.02, -0.27, 0.94, 0.014],\n        // Poised rising neck & folded head/beak\n        [0.23, -0.07, 0.43, -0.44, 1.16, 0.015],\n        [0.07, -0.19, 0.43, -0.44, 0.98, 0.014],\n        [0.43, -0.44, 0.65, -0.35, 1.22, 0.014],\n        [0.36, -0.35, 0.65, -0.35, 0.96, 0.013],\n        // Elegant tapered tail spire\n        [-0.28, -0.09, -0.54, -0.58, 1.16, 0.015],\n        [-0.02, -0.27, -0.54, -0.58, 1.04, 0.014]\n      ];\n      for (let y = 0; y < N; y++) {\n        const py = (y + 0.5) / N * 2 - 1;\n        for (let x = 0; x < N; x++) {\n          const px = (x + 0.5) / N * 2 - 1;\n          let val = 0.032;\n          for (const [ax, ay, bx, by, inten, w] of segs) {\n            const d = sdSegment(px, py, ax, ay, bx, by);\n            const g = inten * Math.exp(-(d * d) / (w * w));\n            if (0.032 + g > val) val = 0.032 + g;\n          }\n          t[y * N + x] = val;\n        }\n      }\n      return t;\n    },\n\n    lorenz(N = N_GRID) {\n      const t = new Float32Array(N * N);\n      t.fill(0.032);\n      let x = 0.1, y = 0.0, z = 0.0;\n      const dt = 0.0035, sigma = 10, rho = 28, beta = 8 / 3;\n      for (let i = 0; i < 16500; i++) {\n        const dx = sigma * (y - x), dy = x * (rho - z) - y, dz = x * y - beta * z;\n        x += dx * dt; y += dy * dt; z += dz * dt;\n        if (i < 400) continue;\n        const px = (x / 24.0) * 0.74;\n        const py = ((z - 25.5) / 23.5) * 0.72;\n        const gx = (px * 0.5 + 0.5) * N, gy = (py * 0.5 + 0.5) * N;\n        const ix0 = Math.max(0, Math.floor(gx - 3)), ix1 = Math.min(N - 1, Math.ceil(gx + 3));\n        const iy0 = Math.max(0, Math.floor(gy - 3)), iy1 = Math.min(N - 1, Math.ceil(gy + 3));\n        for (let yy = iy0; yy <= iy1; yy++) {\n          for (let xx = ix0; xx <= ix1; xx++) {\n            const d2 = ((xx + 0.5 - gx) ** 2 + (yy + 0.5 - gy) ** 2) / (1.85 * 1.85);\n            t[yy * N + xx] += 0.042 * Math.exp(-d2);\n          }\n        }\n      }\n      for (let i = 0; i < N * N; i++) t[i] = Math.min(1.38, t[i]);\n      return t;\n    }\n  };\n\n  // ============================================================================\n  // 3. CRYSTALLINE OPTICAL MODAL SYNTHESIZER (WebAudio — Muted by Default)\n  // ============================================================================\n  class GlassHarmonicaSynth {\n    constructor() {\n      this.ctx = null;\n      this.enabled = false;\n      this.voices = [];\n      this.master = null;\n      this.lastLockPing = 0;\n    }\n\n    toggle() {\n      if (!this.ctx) {\n        const AC = window.AudioContext || window.webkitAudioContext;\n        if (!AC) return false;\n        this.ctx = new AC();\n        this.master = this.ctx.createGain();\n        this.master.gain.value = 0.0;\n        this.master.connect(this.ctx.destination);\n\n        // 5 crystalline Lydian glass partials (C5, G5, D6, F#6, A6)\n        const baseFreqs = [523.25, 783.99, 1174.66, 1479.98, 1760.0];\n        for (let i = 0; i < baseFreqs.length; i++) {\n          const osc = this.ctx.createOscillator();\n          const gain = this.ctx.createGain();\n          osc.type = \"sine\";\n          osc.frequency.value = baseFreqs[i];\n          gain.gain.value = 0.0;\n          osc.connect(gain);\n          gain.connect(this.master);\n          osc.start();\n          this.voices.push({ osc, gain, base: baseFreqs[i], idx: i });\n        }\n      }\n      this.enabled = !this.enabled;\n      if (this.enabled && this.ctx.state === \"suspended\") this.ctx.resume();\n      const now = this.ctx.currentTime;\n      this.master.gain.setTargetAtTime(this.enabled ? 0.14 : 0.0, now, 0.08);\n      return this.enabled;\n    }\n\n    update(alignment, lampSpeed) {\n      if (!this.enabled || !this.ctx) return;\n      const now = this.ctx.currentTime;\n      // Off-axis dispersion detunes partials; exact alignment phase-locks them into a pure bell chord!\n      const detuneSpread = (1.0 - alignment) * 26.0;\n      const motionBoost = Math.min(1.0, lampSpeed * 3.5);\n      for (const v of this.voices) {\n        const sign = (v.idx % 2 === 0) ? 1 : -1;\n        const targetF = v.base + sign * detuneSpread * (v.idx + 1) * 0.35;\n        v.osc.frequency.setTargetAtTime(targetF, now, 0.06);\n        const amp = (0.08 + 0.14 * Math.pow(alignment, 3) + 0.07 * motionBoost) / (1 + v.idx * 0.55);\n        v.gain.gain.setTargetAtTime(amp, now, 0.07);\n      }\n      if (alignment > 0.985 && (now - this.lastLockPing) > 1.8 && lampSpeed > 0.015) {\n        this.lastLockPing = now;\n        this.ping(2093.0, 0.055, 0.65); // Delicate C7 crystal lock chime\n      }\n    }\n\n    chimeSolve() {\n      if (!this.enabled || !this.ctx) return;\n      const notes = [1046.5, 1318.5, 1567.98, 2093.0];\n      notes.forEach((f, idx) => {\n        setTimeout(() => this.ping(f, 0.04, 0.35), idx * 32);\n      });\n    }\n\n    ping(freq, peak, dur) {\n      if (!this.enabled || !this.ctx) return;\n      const now = this.ctx.currentTime;\n      const osc = this.ctx.createOscillator();\n      const g = this.ctx.createGain();\n      osc.type = \"sine\";\n      osc.frequency.setValueAtTime(freq, now);\n      g.gain.setValueAtTime(0.0001, now);\n      g.gain.exponentialRampToValueAtTime(peak, now + 0.012);\n      g.gain.exponentialRampToValueAtTime(0.0001, now + dur);\n      osc.connect(g);\n      g.connect(this.master);\n      osc.start(now);\n      osc.stop(now + dur + 0.02);\n    }\n  }\n\n  // ============================================================================\n  // 4. WATERTIGHT BINARY .STL SOLID LENS EXPORTER (100mm x 100mm Physical Optic)\n  // ============================================================================\n  function exportBinarySTL(h256, minH, presetName) {\n    // Downsample smoothly to 128x128 solid manifold mesh (66,560 triangles -> ~3.3 MB crisp CNC/SLA STL)\n    const M = 128;\n    const scaleXY = 50.0; // [-1, 1] -> [-50mm, +50mm] = 100mm x 100mm lens\n    const baseThickMm = 6.0;\n    const zTop = (T_GLASS * 50.0);\n    // Sample bottom sculpted surface zBot(i,j) in mm (flipped so flat face can sit on print bed at z=0, sculpted face on top!)\n    // Putting flat face at z = 0 and sculpted optical surface at z = baseThickMm - (h - maxH)*50 makes it 100% support-free 3D printable!\n    const zSurf = new Float32Array((M + 1) * (M + 1));\n    let maxHmm = -Infinity;\n    for (let j = 0; j <= M; j++) {\n      const sy = Math.min(255, Math.max(0, Math.round((j / M) * 255)));\n      for (let i = 0; i <= M; i++) {\n        const sx = Math.min(255, Math.max(0, Math.round((i / M) * 255)));\n        const hMm = -h256[sy * 256 + sx] * 50.0; // invert for upward-facing print bed orientation\n        zSurf[j * (M + 1) + i] = hMm;\n        if (hMm > maxHmm) maxHmm = hMm;\n      }\n    }\n    let minSurf = Infinity;\n    for (let i = 0; i < zSurf.length; i++) if (zSurf[i] < minSurf) minSurf = zSurf[i];\n    for (let i = 0; i < zSurf.length; i++) zSurf[i] = baseThickMm + (zSurf[i] - minSurf);\n\n    const triCount = (M * M * 2) * 2 + (M * 2) * 4; // Top sculpted + Bottom flat + 4 walls\n    const buf = new ArrayBuffer(84 + triCount * 50);\n    const dv = new DataView(buf);\n    const headerStr = `CAUSTIC Optical Lens (${presetName}) 100x100mm f=110mm`;\n    for (let i = 0; i < 80; i++) dv.setUint8(i, i < headerStr.length ? headerStr.charCodeAt(i) : 32);\n    dv.setUint32(80, triCount, true);\n\n    let off = 84;\n    function pushTri(ax, ay, az, bx, by, bz, cx, cy, cz) {\n      const ux = bx - ax, uy = by - ay, uz = bz - az;\n      const vx = cx - ax, vy = cy - ay, vz = cz - az;\n      let nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;\n      const len = Math.hypot(nx, ny, nz) || 1;\n      dv.setFloat32(off, nx / len, true); dv.setFloat32(off + 4, ny / len, true); dv.setFloat32(off + 8, nz / len, true);\n      dv.setFloat32(off + 12, ax, true);  dv.setFloat32(off + 16, ay, true);   dv.setFloat32(off + 20, az, true);\n      dv.setFloat32(off + 24, bx, true);  dv.setFloat32(off + 28, by, true);   dv.setFloat32(off + 32, bz, true);\n      dv.setFloat32(off + 36, cx, true);  dv.setFloat32(off + 40, cy, true);   dv.setFloat32(off + 44, cz, true);\n      dv.setUint16(off + 48, 0, true);\n      off += 50;\n    }\n\n    const coord = (k) => ((k / M) * 2 - 1) * scaleXY;\n    for (let j = 0; j < M; j++) {\n      const y0 = coord(j), y1 = coord(j + 1);\n      for (let i = 0; i < M; i++) {\n        const x0 = coord(i), x1 = coord(i + 1);\n        const z00 = zSurf[j * (M + 1) + i],       z10 = zSurf[j * (M + 1) + i + 1];\n        const z01 = zSurf[(j + 1) * (M + 1) + i], z11 = zSurf[(j + 1) * (M + 1) + i + 1];\n        // Sculpted top (+Z)\n        pushTri(x0, y0, z00, x1, y0, z10, x1, y1, z11);\n        pushTri(x0, y0, z00, x1, y1, z11, x0, y1, z01);\n        // Flat bottom (z = 0, -Z normal)\n        pushTri(x0, y0, 0, x1, y1, 0, x1, y0, 0);\n        pushTri(x0, y0, 0, x0, y1, 0, x1, y1, 0);\n      }\n    }\n    // 4 perimeter watertight side walls\n    for (let k = 0; k < M; k++) {\n      const c0 = coord(k), c1 = coord(k + 1);\n      // South (j = 0)\n      pushTri(c0, -scaleXY, 0, c1, -scaleXY, 0, c1, -scaleXY, zSurf[k + 1]);\n      pushTri(c0, -scaleXY, 0, c1, -scaleXY, zSurf[k + 1], c0, -scaleXY, zSurf[k]);\n      // North (j = M)\n      const rN = M * (M + 1);\n      pushTri(c1, scaleXY, 0, c0, scaleXY, 0, c0, scaleXY, zSurf[rN + k]);\n      pushTri(c1, scaleXY, 0, c0, scaleXY, zSurf[rN + k], c1, scaleXY, zSurf[rN + k + 1]);\n      // West (i = 0)\n      pushTri(-scaleXY, c1, 0, -scaleXY, c0, 0, -scaleXY, c0, zSurf[k * (M + 1)]);\n      pushTri(-scaleXY, c1, 0, -scaleXY, c0, zSurf[k * (M + 1)], -scaleXY, c1, zSurf[(k + 1) * (M + 1)]);\n      // East (i = M)\n      pushTri(scaleXY, c0, 0, scaleXY, c1, 0, scaleXY, c1, zSurf[(k + 1) * (M + 1) + M]);\n      pushTri(scaleXY, c0, 0, scaleXY, c1, zSurf[(k + 1) * (M + 1) + M], scaleXY, c0, zSurf[k * (M + 1) + M]);\n    }\n\n    const blob = new Blob([buf], { type: \"application/octet-stream\" });\n    const url = URL.createObjectURL(blob);\n    const a = document.createElement(\"a\");\n    a.href = url;\n    a.download = `caustic-lens-${presetName}-100mm.stl`;\n    document.body.appendChild(a);\n    a.click();\n    a.remove();\n    setTimeout(() => URL.revokeObjectURL(url), 3000);\n  }\n\n  // ============================================================================\n  // 5. MATRIX UTILITIES (Minimal Zero-Dependency 4x4 Camera Math)\n  // ============================================================================\n  function mat4Perspective(fovRad, aspect, near, far) {\n    const f = 1.0 / Math.tan(fovRad * 0.5), nf = 1.0 / (near - far);\n    return new Float32Array([\n      f / aspect, 0, 0, 0,\n      0, f, 0, 0,\n      0, 0, (far + near) * nf, -1,\n      0, 0, (2 * far * near) * nf, 0\n    ]);\n  }\n\n  function mat4LookAt(eye, center, up) {\n    let zx = eye[0] - center[0], zy = eye[1] - center[1], zz = eye[2] - center[2];\n    let len = 1 / (Math.hypot(zx, zy, zz) || 1);\n    zx *= len; zy *= len; zz *= len;\n    let xx = up[1] * zz - up[2] * zy, xy = up[2] * zx - up[0] * zz, xz = up[0] * zy - up[1] * zx;\n    len = Math.hypot(xx, xy, xz);\n    if (len < 1e-5) { xx = 1; xy = 0; xz = 0; } else { xx /= len; xy /= len; xz /= len; }\n    const yx = zy * xz - zz * xy, yy = zz * xx - zx * xz, yz = zx * xy - zy * xx;\n    return new Float32Array([\n      xx, yx, zx, 0,\n      xy, yy, zy, 0,\n      xz, yz, zz, 0,\n      -(xx * eye[0] + xy * eye[1] + xz * eye[2]),\n      -(yx * eye[0] + yy * eye[1] + yz * eye[2]),\n      -(zx * eye[0] + zy * eye[1] + zz * eye[2]),\n      1\n    ]);\n  }\n\n  function mat4Mul(a, b) {\n    const out = new Float32Array(16);\n    for (let c = 0; c < 4; c++) {\n      for (let r = 0; r < 4; r++) {\n        out[c * 4 + r] =\n          a[0 * 4 + r] * b[c * 4 + 0] +\n          a[1 * 4 + r] * b[c * 4 + 1] +\n          a[2 * 4 + r] * b[c * 4 + 2] +\n          a[3 * 4 + r] * b[c * 4 + 3];\n      }\n    }\n    return out;\n  }\n\n  function projectToScreen(vp, wx, wy, wz, width, height) {\n    const cx = vp[0] * wx + vp[4] * wy + vp[8] * wz + vp[12];\n    const cy = vp[1] * wx + vp[5] * wy + vp[9] * wz + vp[13];\n    const cw = vp[3] * wx + vp[7] * wy + vp[11] * wz + vp[15];\n    if (cw <= 0.01) return null;\n    return [\n      ((cx / cw) * 0.5 + 0.5) * width,\n      (0.5 - (cy / cw) * 0.5) * height\n    ];\n  }\n\n  // ============================================================================\n  // 6. WEBGL2 MULTI-PASS OPTICAL ENGINE\n  // ============================================================================\n  const canvas = document.getElementById(\"glCanvas\");\n  const gl = canvas.getContext(\"webgl2\", { antialias: true, alpha: false, powerPreference: \"high-performance\" });\n  if (!gl) {\n    document.body.innerHTML = \"<div style='padding:32px;color:#ece8df;font-family:sans-serif'>WebGL2 is required to run this real-time optical simulation.</div>\";\n    return;\n  }\n\n  const extColorFloat = gl.getExtension(\"EXT_color_buffer_float\");\n  const extFloatBlend = gl.getExtension(\"EXT_float_blend\");\n  const extLinearFloat = gl.getExtension(\"OES_texture_float_linear\");\n  const useFloatCausticFBO = !!(extColorFloat && extFloatBlend);\n\n  function compileShader(type, src) {\n    const sh = gl.createShader(type);\n    gl.shaderSource(sh, src);\n    gl.compileShader(sh);\n    if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) {\n      console.error(gl.getShaderInfoLog(sh), src);\n      throw new Error(gl.getShaderInfoLog(sh));\n    }\n    return sh;\n  }\n\n  function createProgram(vsSrc, fsSrc) {\n    const p = gl.createProgram();\n    gl.attachShader(p, compileShader(gl.VERTEX_SHADER, vsSrc));\n    gl.attachShader(p, compileShader(gl.FRAGMENT_SHADER, fsSrc));\n    gl.linkProgram(p);\n    if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {\n      throw new Error(gl.getProgramInfoLog(p));\n    }\n    return p;\n  }\n\n  // Shared GLSL Uniform Cubic B-Spline (C^2 smooth!) Evaluator on uHeightTex (256x256 R32F)\n  // Guarantees continuous 2nd derivatives across texels -> zero discrete grid artifacts in caustics!\n  const GLSL_BSPLINE_HEIGHT = `\n    uniform sampler2D uHeightTex;\n    const float H_RES = 256.0;\n\n    // Returns vec3(h, dh/dpx, dh/dps) where px, ps in [-1, 1]\n    vec3 sampleGlassSpline(vec2 p) {\n      vec2 uv = clamp(p * 0.5 + 0.5, 0.0, 1.0);\n      vec2 coord = uv * H_RES - 0.5;\n      vec2 base = floor(coord);\n      vec2 f = coord - base;\n\n      // Cubic B-spline weights w(f) and derivatives dw/df\n      vec2 omf = 1.0 - f;\n      vec2 w0 = (omf * omf * omf) / 6.0;\n      vec2 w1 = (3.0 * f * f * f - 6.0 * f * f + 4.0) / 6.0;\n      vec2 w2 = (-3.0 * f * f * f + 3.0 * f * f + 3.0 * f + 1.0) / 6.0;\n      vec2 w3 = (f * f * f) / 6.0;\n\n      vec2 dw0 = -0.5 * omf * omf;\n      vec2 dw1 = 1.5 * f * f - 2.0 * f;\n      vec2 dw2 = -1.5 * f * f + f + 0.5;\n      vec2 dw3 = 0.5 * f * f;\n\n      float wx[4] = float[4](w0.x, w1.x, w2.x, w3.x);\n      float wy[4] = float[4](w0.y, w1.y, w2.y, w3.y);\n      float dx[4] = float[4](dw0.x, dw1.x, dw2.x, dw3.x);\n      float dy[4] = float[4](dw0.y, dw1.y, dw2.y, dw3.y);\n\n      float h = 0.0, dhx = 0.0, dhy = 0.0;\n      for (int j = 0; j < 4; j++) {\n        int iy = clamp(int(base.y) + j - 1, 0, 255);\n        float rowH = 0.0, rowDx = 0.0;\n        for (int i = 0; i < 4; i++) {\n          int ix = clamp(int(base.x) + i - 1, 0, 255);\n          float v = texelFetch(uHeightTex, ivec2(ix, iy), 0).r;\n          rowH += v * wx[i];\n          rowDx += v * dx[i];\n        }\n        h += rowH * wy[j];\n        dhx += rowDx * wy[j];\n        dhy += rowH * dy[j];\n      }\n      // Convert derivative from texel units to physical [-1, 1] units: d(coord)/d(p) = 0.5 * H_RES\n      float scaleD = 0.5 * H_RES;\n      return vec3(h, dhx * scaleD, dhy * scaleD);\n    }\n\n    // Exact 3D Snell refraction of ray from point lamp uLightPos (in optical coords: px, ps, zHeight)\n    // through flat top (z = uFocalZ + uTGlass) and sculpted bottom (z = uFocalZ + h(px,ps)) onto stage (z = 0).\n    // Returns vec4(landPx, landPs, transmittedFluxFactor, validFlag)\n    vec4 traceRefractedRay(vec2 p, vec3 lightOpt, float focalZ, float tGlass, float nIOR) {\n      vec3 hGrad = sampleGlassSpline(p);\n      float zTop = focalZ + tGlass;\n      // Approximate entrance point on top face so ray hits bottom at p\n      vec3 dirAirApprox = normalize(vec3(p, focalZ) - lightOpt);\n      vec2 pTop = p - dirAirApprox.xy * (tGlass / max(0.25, -dirAirApprox.z)) * (1.0 / nIOR);\n      vec3 I_air = normalize(vec3(pTop, zTop) - lightOpt);\n      float cosI1 = max(0.001, -I_air.z);\n      float eta1 = 1.0 / nIOR;\n      float k1 = 1.0 - eta1 * eta1 * (1.0 - cosI1 * cosI1);\n      vec3 I_glass = vec3(eta1 * I_air.xy, -sqrt(max(1e-6, k1)));\n\n      // Schlick Fresnel transmission at top face\n      float r0 = (nIOR - 1.0) / (nIOR + 1.0);\n      r0 = r0 * r0;\n      float T1 = 1.0 - (r0 + (1.0 - r0) * pow(1.0 - cosI1, 5.0));\n\n      // Bottom sculpted surface normal pointing UP into glass: N = (-hx, -hy, 1)\n      vec3 N_up = normalize(vec3(-hGrad.y, -hGrad.z, 1.0));\n      float cosI2 = -dot(I_glass, N_up);\n      if (cosI2 <= 0.01) return vec4(p, 0.0, 0.0);\n      float k2 = 1.0 - nIOR * nIOR * (1.0 - cosI2 * cosI2);\n      if (k2 <= 0.0002) {\n        // Real Total Internal Reflection!\n        return vec4(p, 0.0, 0.0);\n      }\n      float cosT2 = sqrt(k2);\n      vec3 T_out = nIOR * I_glass + (nIOR * cosI2 - cosT2) * N_up;\n      if (T_out.z >= -0.02) return vec4(p, 0.0, 0.0);\n\n      float T2 = 1.0 - (r0 + (1.0 - r0) * pow(1.0 - cosT2, 5.0));\n      float pz = focalZ + hGrad.x;\n      float tHit = -pz / T_out.z;\n      vec2 hit = p + T_out.xy * tHit;\n      float flux = pow(cosI1, 3.0) * T1 * T2;\n      return vec4(hit, flux, 1.0);\n    }\n  `;\n\n  // ----------------------------------------------------------------------------\n  // PASS 1 SHADER: CONTINUOUS GPU SPECTRAL CAUSTIC MICRO-MESH (5 WAVELENGTHS!)\n  // ----------------------------------------------------------------------------\n  const CAUSTIC_VS = `#version 300 es\n    precision highp float;\n    layout(location = 0) in vec2 aGridUV; // [0, 1]^2 across lens aperture\n\n    uniform vec3 uLightOpt;   // (lx, ls, ly_height)\n    uniform float uFocalZ;\n    uniform float uTGlass;\n    uniform float uBaseIOR;\n    uniform float uDispersion;\n    uniform float uExposureScale;\n    uniform int uNumBands;\n\n    ${GLSL_BSPLINE_HEIGHT}\n\n    out vec3 vColor;\n    out float vValid;\n\n    void main() {\n      // Spectral dispersion offset across 5 bands (655nm Red -> 440nm Violet) or 3 RGB bands\n      float bandOffset = 0.0;\n      vec3 specWeight = vec3(1.0);\n      if (uNumBands == 5) {\n        if (gl_InstanceID == 0)      { bandOffset = -1.00; specWeight = vec3(0.46, 0.04, 0.00); } // 655nm Deep Red\n        else if (gl_InstanceID == 1) { bandOffset = -0.45; specWeight = vec3(0.38, 0.28, 0.00); } // 595nm Warm Amber\n        else if (gl_InstanceID == 2) { bandOffset =  0.00; specWeight = vec3(0.14, 0.44, 0.06); } // 535nm Emerald\n        else if (gl_InstanceID == 3) { bandOffset =  0.52; specWeight = vec3(0.02, 0.18, 0.36); } // 485nm Cyan\n        else                         { bandOffset =  1.15; specWeight = vec3(0.06, 0.02, 0.42); } // 440nm Violet\n      } else {\n        if (gl_InstanceID == 0)      { bandOffset = -0.85; specWeight = vec3(1.00, 0.12, 0.00); }\n        else if (gl_InstanceID == 1) { bandOffset =  0.00; specWeight = vec3(0.06, 0.80, 0.10); }\n        else                         { bandOffset =  0.95; specWeight = vec3(0.02, 0.08, 0.76); }\n      }\n\n      float nLambda = uBaseIOR + bandOffset * uDispersion;\n      vec2 p = aGridUV * 2.0 - 1.0;\n\n      // Evaluate exact ray landing & local Jacobian area compression via finite differential\n      float eps = 2.0 / 320.0;\n      vec4 r0 = traceRefractedRay(p, uLightOpt, uFocalZ, uTGlass, nLambda);\n      vec4 rx = traceRefractedRay(p + vec2(eps, 0.0), uLightOpt, uFocalZ, uTGlass, nLambda);\n      vec4 ry = traceRefractedRay(p + vec2(0.0, eps), uLightOpt, uFocalZ, uTGlass, nLambda);\n\n      vec2 dX = (rx.xy - r0.xy) / eps;\n      vec2 dY = (ry.xy - r0.xy) / eps;\n      float jacobian = abs(dX.x * dY.y - dX.y * dY.x);\n\n      // Conserved photon irradiance = incident_flux / jacobian (clamped only at sub-pixel caustic singularity)\n      float irradiance = r0.z / max(jacobian, 0.0045);\n\n      // Soft aperture edge feather so outer glass bevel doesn't cast hard square clipping line\n      vec2 edgeDist = abs(p);\n      float edgeFeather = smoothstep(1.0, 0.965, max(edgeDist.x, edgeDist.y));\n\n      vValid = r0.w * rx.w * ry.w;\n      vColor = specWeight * irradiance * edgeFeather * uExposureScale;\n\n      // Map stage [-1.45, +1.45]^2 into Caustic FBO NDC [-1, +1]^2 (allows wide off-axis caustic sweeps!)\n      const float STAGE_EXTENT = 1.45;\n      gl_Position = vec4(r0.xy / STAGE_EXTENT, 0.0, 1.0);\n    }\n  `;\n\n  const CAUSTIC_FS = `#version 300 es\n    precision highp float;\n    in vec3 vColor;\n    in float vValid;\n    out vec4 fragColor;\n    void main() {\n      if (vValid < 0.5) discard;\n      fragColor = vec4(vColor, 1.0);\n    }\n  `;\n\n  // ----------------------------------------------------------------------------\n  // PASS 2 SHADER: DUAL-KAWASE PHYSICALLY SOFT HDR CAUSTIC HALATION / BLOOM\n  // ----------------------------------------------------------------------------\n  const QUAD_VS = `#version 300 es\n    precision highp float;\n    out vec2 vUV;\n    void main() {\n      vec2 pos = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);\n      vUV = pos;\n      gl_Position = vec4(pos * 2.0 - 1.0, 0.0, 1.0);\n    }\n  `;\n\n  const BLOOM_FS = `#version 300 es\n    precision highp float;\n    in vec2 vUV;\n    uniform sampler2D uTex;\n    uniform vec2 uTexel;\n    uniform float uRadius;\n    out vec4 fragColor;\n    void main() {\n      vec2 d = uTexel * uRadius;\n      vec3 s = texture(uTex, vUV).rgb * 0.28;\n      s += texture(uTex, vUV + vec2( d.x,  d.y)).rgb * 0.18;\n      s += texture(uTex, vUV + vec2(-d.x,  d.y)).rgb * 0.18;\n      s += texture(uTex, vUV + vec2( d.x, -d.y)).rgb * 0.18;\n      s += texture(uTex, vUV + vec2(-d.x, -d.y)).rgb * 0.18;\n      fragColor = vec4(s, 1.0);\n    }\n  `;\n\n  // ----------------------------------------------------------------------------\n  // PASS 3A: STUDIO BACKGROUND + OBSIDIAN STAGE FLOOR + HDR CAUSTIC PROJECTION\n  // ----------------------------------------------------------------------------\n  const STAGE_VS = `#version 300 es\n    precision highp float;\n    layout(location = 0) in vec3 aPos;\n    uniform mat4 uVP;\n    out vec3 vWorldPos;\n    void main() {\n      vWorldPos = aPos;\n      gl_Position = uVP * vec4(aPos, 1.0);\n    }\n  `;\n\n  const STAGE_FS = `#version 300 es\n    precision highp float;\n    in vec3 vWorldPos;\n    uniform sampler2D uCausticTex;\n    uniform sampler2D uBloomTex;\n    uniform sampler2D uTargetTex;\n    uniform vec3 uCamPos;\n    uniform vec3 uLightWorld;\n    uniform float uFocalZ;\n    uniform float uCausticScale;\n    uniform int uCompareMask;\n\n    out vec4 fragColor;\n\n    // Subtle procedural slate micro-grain\n    float hash21(vec2 p) {\n      p = fract(p * vec2(123.34, 456.21));\n      p += dot(p, p + 45.32);\n      return fract(p.x * p.y);\n    }\n\n    void main() {\n      // Optical stage coords: px = x, ps = -z\n      vec2 optP = vec2(vWorldPos.x, -vWorldPos.z);\n      const float STAGE_EXTENT = 1.45;\n      vec2 causticUV = optP / (2.0 * STAGE_EXTENT) + 0.5;\n\n      // Base dark anodized obsidian tabletop\n      float rStage = length(vWorldPos.xz);\n      float grain = (hash21(floor(vWorldPos.xz * 260.0)) - 0.5) * 0.012;\n      vec3 baseSlate = vec3(0.026, 0.028, 0.036) + grain;\n\n      // Subtle soft specular sheen from point lamp on matte stone\n      vec3 L = normalize(uLightWorld - vWorldPos);\n      vec3 V = normalize(uCamPos - vWorldPos);\n      vec3 H = normalize(L + V);\n      float spec = pow(max(0.0, H.y), 42.0) * 0.035;\n      // Soft shadow cast by glass mount frame outside [-1,1]^2 vs subtle ambient occlusion\n      vec2 boxD = abs(optP) - vec2(1.0);\n      float frameBorder = abs(max(boxD.x, boxD.y));\n      baseSlate += vec3(1.0, 0.88, 0.72) * spec * smoothstep(0.0, 0.4, max(boxD.x, boxD.y) + 0.2);\n\n      // Calibrated hairline optical bench reticle & 100mm aperture frame ticks\n      float borderLine = exp(-pow(frameBorder / 0.0045, 2.0)) * step(max(abs(optP.x), abs(optP.y)), 1.03);\n      float tickMarks = 0.0;\n      if (abs(frameBorder - 0.022) < 0.018 && max(abs(optP.x), abs(optP.y)) < 1.03) {\n        float c = (abs(optP.x) > abs(optP.y)) ? optP.y : optP.x;\n        tickMarks = exp(-pow(sin(c * 3.14159265 * 10.0) / 0.12, 2.0)) * 0.35;\n      }\n      vec3 reticleCol = vec3(0.32, 0.35, 0.44) * (borderLine * 0.42 + tickMarks * 0.22);\n\n      // Sample live raytraced HDR Caustics + physically soft Dual-Kawase halation\n      vec3 causticRaw = vec3(0.0);\n      vec3 bloomRaw = vec3(0.0);\n      if (causticUV.x > 0.002 && causticUV.x < 0.998 && causticUV.y > 0.002 && causticUV.y < 0.998) {\n        causticRaw = texture(uCausticTex, causticUV).rgb * uCausticScale;\n        bloomRaw = texture(uBloomTex, causticUV).rgb * uCausticScale;\n      }\n\n      vec3 lightDeposit = causticRaw + bloomRaw * 0.36;\n\n      // Optional \"Mask vs. Lens\" split comparison (left half: absorptive stencil mask; right half: refractive lens!)\n      if (uCompareMask == 1 && abs(optP.x) < 1.0 && abs(optP.y) < 1.0) {\n        if (optP.x < 0.0) {\n          vec2 tUV = optP * 0.5 + 0.5;\n          float targVal = texture(uTargetTex, tUV).r;\n          // Absorptive mask simply blocks light where targVal < max, peaking at ONLY 1.0x uniform lamp irradiance!\n          // Notice how dim 1.0x un-concentrated sunlight is compared to 20x-30x optimal-transport photon focusing!\n          float maskTrans = clamp((targVal - 0.032) / 1.15, 0.0, 1.0);\n          float directSun = 0.14; // exact same 1.0x mean incident photon budget!\n          lightDeposit = vec3(1.0, 0.88, 0.68) * (directSun * maskTrans);\n        }\n        // Hairline split divider at x = 0\n        float splitLine = exp(-pow(optP.x / 0.004, 2.0));\n        reticleCol += vec3(0.95, 0.74, 0.45) * splitLine * 0.65;\n      }\n\n      vec3 col = baseSlate + reticleCol + lightDeposit;\n\n      // Smooth radial fade into dark studio floor\n      float vig = smoothstep(3.3, 1.35, rStage);\n      col *= vig;\n\n      // Filmic ACES-inspired highlight roll-off so 30x caustic cusps glow incandescent white-gold!\n      col = (col * (2.51 * col + 0.03)) / (col * (2.43 * col + 0.59) + 0.14);\n      col = pow(max(col, 0.0), vec3(1.0 / 2.2));\n      fragColor = vec4(col, 1.0);\n    }\n  `;\n\n  // ----------------------------------------------------------------------------\n  // PASS 3B: 3D WATERTIGHT SCULPTED OPTICAL GLASS BLOCK (Refraction + Interferogram)\n  // ----------------------------------------------------------------------------\n  const GLASS_VS = `#version 300 es\n    precision highp float;\n    layout(location = 0) in vec3 aGridPos; // (px, ps, faceType: 0=bottom sculpted, 1=top flat, 2..5=side walls)\n    layout(location = 1) in vec3 aWallNormal;\n\n    uniform mat4 uVP;\n    uniform float uFocalZ;\n    uniform float uTGlass;\n\n    ${GLSL_BSPLINE_HEIGHT}\n\n    out vec3 vWorldPos;\n    out vec3 vNormal;\n    out vec2 vOptP;\n    out float vHeight;\n    out float vFaceType;\n\n    void main() {\n      vec2 p = aGridPos.xy;\n      float face = aGridPos.z;\n      vec3 hGrad = sampleGlassSpline(p);\n      float yWorld = 0.0;\n      vec3 nWorld = vec3(0.0, 1.0, 0.0);\n\n      if (face < 0.5) {\n        // Bottom sculpted optical face: y = uFocalZ + h(px, ps)\n        // Optical normal into air is (hx, hy, -1) -> World (X=px, Y=z, Z=-ps) normal is (hx, -1.0, -hy)!\n        yWorld = uFocalZ + hGrad.x;\n        nWorld = normalize(vec3(hGrad.y, -1.0, -hGrad.z));\n      } else if (face < 1.5) {\n        // Top flat entrance face\n        yWorld = uFocalZ + uTGlass;\n        nWorld = vec3(0.0, 1.0, 0.0);\n      } else {\n        // Polished perimeter bevel walls: aWallNormal.y stores top(1) vs bottom(0) selector\n        float isTop = aWallNormal.y;\n        yWorld = (isTop > 0.5) ? (uFocalZ + uTGlass) : (uFocalZ + hGrad.x);\n        nWorld = normalize(vec3(aWallNormal.x, 0.0, aWallNormal.z));\n      }\n\n      vec3 worldPos = vec3(p.x, yWorld, -p.y);\n      vWorldPos = worldPos;\n      vNormal = nWorld;\n      vOptP = p;\n      vHeight = hGrad.x;\n      vFaceType = face;\n      gl_Position = uVP * vec4(worldPos, 1.0);\n    }\n  `;\n\n  const GLASS_FS = `#version 300 es\n    precision highp float;\n    in vec3 vWorldPos;\n    in vec3 vNormal;\n    in vec2 vOptP;\n    in float vHeight;\n    in float vFaceType;\n\n    uniform sampler2D uSceneCopyTex;\n    uniform vec2 uViewport;\n    uniform vec3 uCamPos;\n    uniform vec3 uLightWorld;\n    uniform float uBaseIOR;\n    uniform vec3 uGlassTint;\n    uniform int uShowInterf;\n\n    out vec4 fragColor;\n\n    void main() {\n      vec3 N = normalize(gl_FrontFacing ? vNormal : -vNormal);\n      vec3 V = normalize(uCamPos - vWorldPos);\n      vec3 I = -V;\n\n      // True screen-space optical refraction with subtle R/G/B chromatic offset\n      vec2 screenUV = gl_FragCoord.xy / uViewport;\n      vec3 R_refr = refract(I, N, 1.0 / uBaseIOR);\n      vec2 refrOffset = R_refr.xz * 0.048 * (vFaceType > 1.5 ? 1.65 : 1.0);\n\n      vec3 bgR = texture(uSceneCopyTex, clamp(screenUV + refrOffset * 0.94, 0.002, 0.998)).rgb;\n      vec3 bgG = texture(uSceneCopyTex, clamp(screenUV + refrOffset * 1.00, 0.002, 0.998)).rgb;\n      vec3 bgB = texture(uSceneCopyTex, clamp(screenUV + refrOffset * 1.06, 0.002, 0.998)).rgb;\n      vec3 refrCol = vec3(bgR.r, bgG.g, bgB.b);\n\n      // Beer-Lambert optical crystal edge tint (polished green-aqua crown glass edges!)\n      float cosTheta = max(0.02, dot(N, V));\n      float pathLen = (vFaceType > 1.5) ? 0.55 : (0.14 / max(0.25, cosTheta));\n      vec3 absorb = pow(uGlassTint, vec3(pathLen * 2.4));\n      refrCol *= absorb;\n      if (vFaceType > 1.5) {\n        // Polished ground-glass edge catchlight\n        refrCol += vec3(0.06, 0.11, 0.13) * uGlassTint;\n      }\n\n      // Schlick Fresnel reflection from overhead lamp & cool studio softboxes\n      float r0 = pow((uBaseIOR - 1.0) / (uBaseIOR + 1.0), 2.0);\n      float fresnel = r0 + (1.0 - r0) * pow(1.0 - cosTheta, 5.0);\n\n      vec3 L = normalize(uLightWorld - vWorldPos);\n      vec3 H = normalize(L + V);\n      float specLamp = pow(max(0.0, dot(N, H)), 180.0) * 1.6 + pow(max(0.0, dot(N, H)), 24.0) * 0.14;\n      vec3 R_refl = reflect(I, N);\n      // Subtle studio softbox sky reflection strip\n      float studioStrip = smoothstep(0.35, 0.85, R_refl.y) * (0.55 + 0.45 * smoothstep(-0.3, 0.5, R_refl.x));\n      vec3 envRefl = vec3(0.30, 0.36, 0.46) * studioStrip + vec3(1.0, 0.90, 0.72) * specLamp;\n\n      // Subtle bevel edge highlight on glass perimeter\n      vec2 edgeD = abs(vOptP);\n      float rim = smoothstep(0.982, 1.0, max(edgeD.x, edgeD.y));\n      vec3 col = mix(refrCol, envRefl, clamp(fresnel * 1.25, 0.04, 0.92)) + vec3(0.14, 0.20, 0.24) * rim * 0.45;\n\n      // Optional Mach-Zehnder Laser Interferogram (reveals micron height contours cos(4*pi*h/lambda)!)\n      if (uShowInterf == 1 && vFaceType < 1.5) {\n        float phase = vHeight * 260.0;\n        float fringe = 0.5 + 0.5 * cos(phase);\n        fringe = pow(fringe, 3.0);\n        vec3 interfCol = mix(vec3(0.02, 0.14, 0.18), vec3(0.45, 0.96, 0.88), fringe);\n        col = mix(col, col * 0.45 + interfCol * 0.68, 0.62);\n      }\n\n      fragColor = vec4(col, 1.0);\n    }\n  `;\n\n  // ----------------------------------------------------------------------------\n  // PASS 3C: DIAGNOSTIC 3D LINES (Snell Ray Sheet, Optimal Transport Grid, Lamp Cone)\n  // ----------------------------------------------------------------------------\n  const LINE_VS = `#version 300 es\n    precision highp float;\n    layout(location = 0) in vec3 aPos;\n    layout(location = 1) in vec4 aCol;\n    uniform mat4 uVP;\n    out vec4 vCol;\n    void main() {\n      vCol = aCol;\n      gl_Position = uVP * vec4(aPos, 1.0);\n    }\n  `;\n\n  const LINE_FS = `#version 300 es\n    precision highp float;\n    in vec4 vCol;\n    out vec4 fragColor;\n    void main() {\n      fragColor = vCol;\n    }\n  `;\n\n  // 3D Point Lamp Billboard Glow Shader\n  const LAMP_VS = `#version 300 es\n    precision highp float;\n    uniform mat4 uVP;\n    uniform vec3 uLampPos;\n    uniform vec3 uCamRight;\n    uniform vec3 uCamUp;\n    uniform float uSize;\n    out vec2 vQuad;\n    void main() {\n      vec2 corners[4] = vec2[4](vec2(-1,-1), vec2(1,-1), vec2(-1,1), vec2(1,1));\n      int idx[6] = int[6](0, 1, 2, 2, 1, 3);\n      vec2 q = corners[idx[gl_VertexID]];\n      vQuad = q;\n      vec3 world = uLampPos + (uCamRight * q.x + uCamUp * q.y) * uSize;\n      gl_Position = uVP * vec4(world, 1.0);\n    }\n  `;\n\n  const LAMP_FS = `#version 300 es\n    precision highp float;\n    in vec2 vQuad;\n    uniform float uFocusLock;\n    out vec4 fragColor;\n    void main() {\n      float r = length(vQuad);\n      if (r > 1.0) discard;\n      float core = exp(-r * r * 38.0);\n      float halo = exp(-r * r * 5.2) * 0.55 + pow(max(0.0, 1.0 - r), 3.0) * 0.22;\n      vec3 col = vec3(1.0, 0.94, 0.82) * core * 1.4 + mix(vec3(1.0, 0.74, 0.38), vec3(0.65, 0.92, 1.0), uFocusLock * 0.25) * halo;\n      fragColor = vec4(col, 1.0);\n    }\n  `;\n\n  const progCaustic = createProgram(CAUSTIC_VS, CAUSTIC_FS);\n  const progBloom   = createProgram(QUAD_VS, BLOOM_FS);\n  const progStage   = createProgram(STAGE_VS, STAGE_FS);\n  const progGlass   = createProgram(GLASS_VS, GLASS_FS);\n  const progLine    = createProgram(LINE_VS, LINE_FS);\n  const progLamp    = createProgram(LAMP_VS, LAMP_FS);\n\n  // ============================================================================\n  // 7. GPU BUFFERS, TEXTURES & FRAMEBUFFERS\n  // ============================================================================\n  // 1) Heightfield R32F Texture (256x256) + Target R32F Texture (256x256)\n  const heightTex = gl.createTexture();\n  gl.bindTexture(gl.TEXTURE_2D, heightTex);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n  gl.texImage2D(gl.TEXTURE_2D, 0, gl.R32F, N_GRID, N_GRID, 0, gl.RED, gl.FLOAT, new Float32Array(N_GRID * N_GRID));\n\n  const targetTex = gl.createTexture();\n  gl.bindTexture(gl.TEXTURE_2D, targetTex);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, extLinearFloat ? gl.LINEAR : gl.NEAREST);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, extLinearFloat ? gl.LINEAR : gl.NEAREST);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n  gl.texImage2D(gl.TEXTURE_2D, 0, gl.R32F, N_GRID, N_GRID, 0, gl.RED, gl.FLOAT, new Float32Array(N_GRID * N_GRID));\n\n  // 2) Caustic FBO (1024x1024 RGBA16F HDR or RGBA8 scaled fallback) + Bloom FBOs (512x512)\n  const CAUSTIC_RES = 1024;\n  function createFBO(w, h, useFloat) {\n    const tex = gl.createTexture();\n    gl.bindTexture(gl.TEXTURE_2D, tex);\n    const filter = (!useFloat || extLinearFloat) ? gl.LINEAR : gl.NEAREST;\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n    if (useFloat) {\n      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, w, h, 0, gl.RGBA, gl.HALF_FLOAT, null);\n    } else {\n      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n    }\n    const fbo = gl.createFramebuffer();\n    gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);\n    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);\n    gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n    return { fbo, tex, w, h };\n  }\n\n  const fboCaustic = createFBO(CAUSTIC_RES, CAUSTIC_RES, useFloatCausticFBO);\n  const fboBloomA  = createFBO(512, 512, useFloatCausticFBO);\n  const fboBloomB  = createFBO(256, 256, useFloatCausticFBO);\n\n  // Scene copy texture for true 3D glass refraction\n  const sceneCopyTex = gl.createTexture();\n  let sceneCopyW = 0, sceneCopyH = 0;\n  function ensureSceneCopyTex(w, h) {\n    if (sceneCopyW === w && sceneCopyH === h) return;\n    sceneCopyW = w; sceneCopyH = h;\n    gl.bindTexture(gl.TEXTURE_2D, sceneCopyTex);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n  }\n\n  // 3) Continuous Refractive Beam Micro-Mesh (320 x 320 = 102,400 quads = 204,800 tris/band)\n  const BEAM_N = 320;\n  const beamVAO = gl.createVertexArray();\n  gl.bindVertexArray(beamVAO);\n  const beamVerts = new Float32Array((BEAM_N + 1) * (BEAM_N + 1) * 2);\n  for (let y = 0; y <= BEAM_N; y++) {\n    for (let x = 0; x <= BEAM_N; x++) {\n      const idx = (y * (BEAM_N + 1) + x) * 2;\n      beamVerts[idx] = x / BEAM_N;\n      beamVerts[idx + 1] = y / BEAM_N;\n    }\n  }\n  const beamVBO = gl.createBuffer();\n  gl.bindBuffer(gl.ARRAY_BUFFER, beamVBO);\n  gl.bufferData(gl.ARRAY_BUFFER, beamVerts, gl.STATIC_DRAW);\n  gl.enableVertexAttribArray(0);\n  gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);\n\n  const beamIndices = new Uint32Array(BEAM_N * BEAM_N * 6);\n  let bi = 0;\n  for (let y = 0; y < BEAM_N; y++) {\n    for (let x = 0; x < BEAM_N; x++) {\n      const i00 = y * (BEAM_N + 1) + x, i10 = i00 + 1;\n      const i01 = i00 + (BEAM_N + 1),   i11 = i01 + 1;\n      beamIndices[bi++] = i00; beamIndices[bi++] = i10; beamIndices[bi++] = i11;\n      beamIndices[bi++] = i00; beamIndices[bi++] = i11; beamIndices[bi++] = i01;\n    }\n  }\n  const beamIBO = gl.createBuffer();\n  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, beamIBO);\n  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, beamIndices, gl.STATIC_DRAW);\n  gl.bindVertexArray(null);\n\n  // 4) Stage Floor Mesh (Large horizontal slab at y = 0)\n  const stageVAO = gl.createVertexArray();\n  gl.bindVertexArray(stageVAO);\n  const S_EXT = 3.6;\n  const stageVBO = gl.createBuffer();\n  gl.bindBuffer(gl.ARRAY_BUFFER, stageVBO);\n  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([\n    -S_EXT, 0, -S_EXT,   S_EXT, 0, -S_EXT,   S_EXT, 0,  S_EXT,\n    -S_EXT, 0, -S_EXT,   S_EXT, 0,  S_EXT,  -S_EXT, 0,  S_EXT\n  ]), gl.STATIC_DRAW);\n  gl.enableVertexAttribArray(0);\n  gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);\n  gl.bindVertexArray(null);\n\n  // 5) 3D Watertight Glass Block Mesh (160x160 sculpted bottom + top + 4 polished side walls)\n  const GLASS_M = 160;\n  const glassVAO = gl.createVertexArray();\n  gl.bindVertexArray(glassVAO);\n  const glassVertList = [];\n  const glassIdxList = [];\n\n  function addGlassSurface(faceType) {\n    const base = glassVertList.length / 6;\n    for (let j = 0; j <= GLASS_M; j++) {\n      const ps = (j / GLASS_M) * 2 - 1;\n      for (let i = 0; i <= GLASS_M; i++) {\n        const px = (i / GLASS_M) * 2 - 1;\n        glassVertList.push(px, ps, faceType, 0, 0, 0);\n      }\n    }\n    for (let j = 0; j < GLASS_M; j++) {\n      for (let i = 0; i < GLASS_M; i++) {\n        const i00 = base + j * (GLASS_M + 1) + i, i10 = i00 + 1;\n        const i01 = i00 + (GLASS_M + 1),          i11 = i01 + 1;\n        if (faceType === 0) {\n          glassIdxList.push(i00, i11, i10, i00, i01, i11);\n        } else {\n          glassIdxList.push(i00, i10, i11, i00, i11, i01);\n        }\n      }\n    }\n  }\n  addGlassSurface(0); // Sculpted bottom\n  addGlassSurface(1); // Flat top\n\n  // 4 Polished Perimeter Side Walls\n  function addWallStrip(pxFn, psFn, nx, nz) {\n    const base = glassVertList.length / 6;\n    for (let k = 0; k <= GLASS_M; k++) {\n      const t = (k / GLASS_M) * 2 - 1;\n      const px = pxFn(t), ps = psFn(t);\n      glassVertList.push(px, ps, 2, nx, 0, nz); // bottom edge\n      glassVertList.push(px, ps, 2, nx, 1, nz); // top edge\n    }\n    for (let k = 0; k < GLASS_M; k++) {\n      const b0 = base + 2 * k, t0 = b0 + 1, b1 = b0 + 2, t1 = b0 + 3;\n      glassIdxList.push(b0, b1, t1, b0, t1, t0);\n    }\n  }\n  addWallStrip((t) => t,  () => -1,  0,  1); // Front (+Z world, ps = -1)\n  addWallStrip((t) => -t, () =>  1,  0, -1); // Back (-Z world, ps = +1)\n  addWallStrip(() =>  1,  (t) => t,  1,  0); // Right (+X world)\n  addWallStrip(() => -1,  (t) => -t, -1, 0); // Left (-X world)\n\n  const glassVBO = gl.createBuffer();\n  gl.bindBuffer(gl.ARRAY_BUFFER, glassVBO);\n  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(glassVertList), gl.STATIC_DRAW);\n  gl.enableVertexAttribArray(0);\n  gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 24, 0);\n  gl.enableVertexAttribArray(1);\n  gl.vertexAttribPointer(1, 3, gl.FLOAT, false, 24, 12);\n\n  const glassIBO = gl.createBuffer();\n  const glassIndexCount = glassIdxList.length;\n  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, glassIBO);\n  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint32Array(glassIdxList), gl.STATIC_DRAW);\n  gl.bindVertexArray(null);\n\n  // 6) Dynamic 3D Line Buffer (Ray Sheet, Photon Grid, Lamp Aperture Cone, Mount Pins)\n  const lineVAO = gl.createVertexArray();\n  gl.bindVertexArray(lineVAO);\n  const lineVBO = gl.createBuffer();\n  const MAX_LINE_FLOATS = 32768 * 7;\n  const lineData = new Float32Array(MAX_LINE_FLOATS);\n  gl.bindBuffer(gl.ARRAY_BUFFER, lineVBO);\n  gl.bufferData(gl.ARRAY_BUFFER, lineData.byteLength, gl.DYNAMIC_DRAW);\n  gl.enableVertexAttribArray(0);\n  gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 28, 0);\n  gl.enableVertexAttribArray(1);\n  gl.vertexAttribPointer(1, 4, gl.FLOAT, false, 28, 12);\n  gl.bindVertexArray(null);\n\n  const emptyVAO = gl.createVertexArray();\n\n  // ============================================================================\n  // 8. APPLICATION STATE, SOLVER WORKER & INTERACTIVE PAD\n  // ============================================================================\n  const synth = new GlassHarmonicaSynth();\n  const workerBlob = new Blob([WORKER_SOURCE], { type: \"application/javascript\" });\n  const solverWorker = new Worker(URL.createObjectURL(workerBlob));\n\n  const state = {\n    preset: \"astrolabe\",\n    carvedForGlass: \"bk7\",\n    selectedGlass: \"bk7\",\n    focalRatio: 1.00, // 1.00 * DESIGN_F\n    showRays: true,\n    showGrid: false,\n    showInterf: false,\n    compareMask: false,\n    raySliceS: 0.0,   // y-slice across optical lens [-0.85, +0.85]\n\n    // Camera spherical orbit around bench center (0, 1.05, 0)\n    camYaw: 0.34,\n    camPitch: 0.56,\n    camDist: 6.35,\n    camTargetYaw: 0.34,\n    camTargetPitch: 0.56,\n    camTargetDist: 6.35,\n    camCenterY: 1.02,\n    camTargetCenterY: 1.02,\n\n    // 3D Point Lamp in optical coordinates (lx, ls, lz_height)\n    // Start at graceful 13-degree off-axis angle so opening 2.0s glides into dramatic focus lock!\n    lampX: 1.48,\n    lampS: -0.92,\n    lampZ: DESIGN_Z_LIGHT,\n    lampTargetX: 0.0,\n    lampTargetS: 0.0,\n    autoChoreo: true,\n    userInteracted: false,\n    presetCycleTimer: 0,\n\n    // Live heightfield morphing (hCurrent smoothly springs toward hSolved at 60fps!)\n    target256: PRESETS.astrolabe(),\n    hCurrent: new Float32Array(N_GRID * N_GRID),\n    hSolved: new Float32Array(N_GRID * N_GRID),\n    minH: -0.05,\n    maxH: 0.05,\n    reliefMm: 4.8,\n    solveMs: 0,\n    solving: false,\n    solveReqId: 0,\n\n    // Pad Loupe state\n    loupeTab: \"target\", // \"target\" | \"height\"\n    brushMode: \"draw\",  // \"draw\" | \"erase\"\n    numSpectralBands: 5 // Adaptive 5-band full prism spectrum (falls back to 3 on software GL)\n  };\n\n  // Upload initial target texture\n  function uploadTargetTexture() {\n    gl.bindTexture(gl.TEXTURE_2D, targetTex);\n    gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, N_GRID, N_GRID, gl.RED, gl.FLOAT, state.target256);\n  }\n  uploadTargetTexture();\n\n  // Render Target or Solved Glass Heightfield onto the 2D Loupe Pad Canvas\n  const padCanvas = document.getElementById(\"padCanvas\");\n  const padCtx = padCanvas.getContext(\"2d\");\n  const padImgData = padCtx.createImageData(N_GRID, N_GRID);\n\n  function renderPadCanvas() {\n    const d = padImgData.data;\n    if (state.loupeTab === \"target\") {\n      let maxV = 0.2;\n      for (let i = 0; i < N_GRID * N_GRID; i++) if (state.target256[i] > maxV) maxV = state.target256[i];\n      for (let y = 0; y < N_GRID; y++) {\n        const row = (N_GRID - 1 - y);\n        for (let x = 0; x < N_GRID; x++) {\n          const v = Math.max(0, (state.target256[y * N_GRID + x] - 0.032) / (maxV - 0.032));\n          const g = Math.pow(v, 0.62);\n          const p = (row * N_GRID + x) * 4;\n          d[p]     = Math.min(255, (10 + g * 245) | 0);\n          d[p + 1] = Math.min(255, (12 + Math.pow(g, 1.15) * 206) | 0);\n          d[p + 2] = Math.min(255, (18 + Math.pow(g, 1.45) * 138) | 0);\n          d[p + 3] = 255;\n        }\n      }\n    } else {\n      // Shaded Aqua-Crystal Relief + Interferometric Contours\n      const span = (state.maxH - state.minH) || 0.05;\n      const dx = 2.0 / N_GRID;\n      for (let y = 0; y < N_GRID; y++) {\n        const row = (N_GRID - 1 - y);\n        for (let x = 0; x < N_GRID; x++) {\n          const i = y * N_GRID + x;\n          const hn = (state.hSolved[i] - state.minH) / span;\n          const hx = (state.hSolved[y * N_GRID + Math.min(255, x + 1)] - state.hSolved[y * N_GRID + Math.max(0, x - 1)]) / (2 * dx);\n          const hy = (state.hSolved[Math.min(255, y + 1) * N_GRID + x] - state.hSolved[Math.max(0, y - 1) * N_GRID + x]) / (2 * dx);\n          const hill = Math.max(0.25, Math.min(1.45, 0.68 + 1.9 * (-hx * 0.65 + hy * 0.65)));\n          const contour = 0.88 + 0.12 * Math.cos(state.hSolved[i] * 240.0);\n          const lum = (0.24 + 0.62 * hn) * hill * contour;\n          const p = (row * N_GRID + x) * 4;\n          d[p]     = Math.min(255, (lum * 135) | 0);\n          d[p + 1] = Math.min(255, (lum * 208) | 0);\n          d[p + 2] = Math.min(255, (lum * 232) | 0);\n          d[p + 3] = 255;\n        }\n      }\n    }\n    padCtx.putImageData(padImgData, 0, 0);\n  }\n\n  const telemetryBar = document.getElementById(\"telemetryBar\");\n  const statRelief   = document.getElementById(\"statRelief\");\n  const statSolve    = document.getElementById(\"statSolve\");\n  const statFocus    = document.getElementById(\"statFocus\");\n  const statRays     = document.getElementById(\"statRays\");\n  const btnRegrind   = document.getElementById(\"btnRegrind\");\n\n  function requestLensSolve(targetArr) {\n    state.solving = true;\n    telemetryBar.classList.add(\"solving\");\n    statSolve.textContent = \"SOLVING PDE…\";\n    const id = ++state.solveReqId;\n    const mat = MATERIALS[state.selectedGlass];\n    state.carvedForGlass = state.selectedGlass;\n    btnRegrind.style.display = \"none\";\n\n    const copy = new Float32Array(targetArr);\n    solverWorker.postMessage({\n      id,\n      target256: copy,\n      F: DESIGN_F,\n      T_glass: T_GLASS,\n      nGlass: mat.nD,\n      Z_light: DESIGN_Z_LIGHT\n    }, [copy.buffer]);\n  }\n\n  solverWorker.onmessage = (e) => {\n    const { id, h256, minH, maxH, reliefMm, solveMs } = e.data;\n    if (id !== state.solveReqId) return;\n    state.hSolved = h256;\n    state.minH = minH;\n    state.maxH = maxH;\n    state.reliefMm = reliefMm;\n    state.solveMs = solveMs;\n    state.solving = false;\n    telemetryBar.classList.remove(\"solving\");\n    statRelief.textContent = `RELIEF ${reliefMm.toFixed(1)} mm`;\n    statSolve.textContent = `PDE ${Math.round(solveMs)} ms`;\n    if (state.loupeTab === \"height\") renderPadCanvas();\n    synth.chimeSolve();\n  };\n\n  // Trigger initial lens solve immediately!\n  renderPadCanvas();\n  requestLensSolve(state.target256);\n\n  // ============================================================================\n  // 9. CPU EXACT SNELL RAYTRACER FOR 3D DIAGNOSTIC OVERLAYS (Ray Sheet & Grid)\n  // ============================================================================\n  function sampleHCPU(px, ps) {\n    const gx = Math.max(0, Math.min(N_GRID - 1.001, (px * 0.5 + 0.5) * N_GRID - 0.5));\n    const gs = Math.max(0, Math.min(N_GRID - 1.001, (ps * 0.5 + 0.5) * N_GRID - 0.5));\n    const ix = gx | 0, is = gs | 0, fx = gx - ix, fs = gs - is;\n    const h = state.hCurrent;\n    const v00 = h[is * N_GRID + ix],           v10 = h[is * N_GRID + ix + 1];\n    const v01 = h[(is + 1) * N_GRID + ix],     v11 = h[(is + 1) * N_GRID + ix + 1];\n    const val = (1 - fx) * (1 - fs) * v00 + fx * (1 - fs) * v10 + (1 - fx) * fs * v01 + fx * fs * v11;\n\n    const dx = 2.0 / N_GRID;\n    const xm = Math.max(0, ix - 1), xp = Math.min(N_GRID - 1, ix + 1);\n    const sm = Math.max(0, is - 1), sp = Math.min(N_GRID - 1, is + 1);\n    const hx = (h[is * N_GRID + xp] - h[is * N_GRID + xm]) / ((xp - xm) * dx);\n    const hs = (h[sp * N_GRID + ix] - h[sm * N_GRID + ix]) / ((sp - sm) * dx);\n    return [val, hx, hs];\n  }\n\n  function traceSingleRay3D(px, ps, focalZ, nIOR) {\n    const [hVal, hx, hs] = sampleHCPU(px, ps);\n    const zTop = focalZ + T_GLASS;\n    const lx = state.lampX, ls = state.lampS, lz = state.lampZ;\n    let dax = px - lx, das = ps - ls, daz = focalZ - lz;\n    const dLen = Math.hypot(dax, das, daz);\n    dax /= dLen; das /= dLen; daz /= dLen;\n    const pTopX = px - dax * (T_GLASS / Math.max(0.25, -daz)) / nIOR;\n    const pTopS = ps - das * (T_GLASS / Math.max(0.25, -daz)) / nIOR;\n\n    let ix = pTopX - lx, is = pTopS - ls, iz = zTop - lz;\n    const il = Math.hypot(ix, is, iz);\n    ix /= il; is /= il; iz /= il;\n    const eta1 = 1.0 / nIOR, cosI1 = Math.max(0.001, -iz);\n    const gx = eta1 * ix, gs = eta1 * is, gz = -Math.sqrt(Math.max(1e-6, 1 - eta1 * eta1 * (1 - cosI1 * cosI1)));\n\n    const invN = 1.0 / Math.hypot(hx, hs, 1.0);\n    const nx = -hx * invN, ns = -hs * invN, nz = invN;\n    const cosI2 = -(gx * nx + gs * ns + gz * nz);\n    const k2 = 1.0 - nIOR * nIOR * (1.0 - cosI2 * cosI2);\n    if (cosI2 <= 0.01 || k2 <= 0.0002) return null;\n    const s = nIOR * cosI2 - Math.sqrt(k2);\n    const tx = nIOR * gx + s * nx, ts = nIOR * gs + s * ns, tz = nIOR * gz + s * nz;\n    if (tz >= -0.02) return null;\n    const pz = focalZ + hVal;\n    const tHit = -pz / tz;\n    return {\n      top:   [pTopX, zTop, -pTopS],\n      bot:   [px, pz, -ps],\n      stage: [px + tx * tHit, 0.003, -(ps + ts * tHit)]\n    };\n  }\n\n  function buildDiagnosticLines(focalZ, nIOR) {\n    let ptr = 0;\n    function seg(ax, ay, az, bx, by, bz, r, g, b, a1, a2) {\n      if (ptr + 14 > MAX_LINE_FLOATS) return;\n      lineData[ptr++] = ax; lineData[ptr++] = ay; lineData[ptr++] = az;\n      lineData[ptr++] = r * a1; lineData[ptr++] = g * a1; lineData[ptr++] = b * a1; lineData[ptr++] = a1;\n      lineData[ptr++] = bx; lineData[ptr++] = by; lineData[ptr++] = bz;\n      lineData[ptr++] = r * a2; lineData[ptr++] = g * a2; lineData[ptr++] = b * a2; lineData[ptr++] = a2;\n    }\n\n    const lampW = [state.lampX, state.lampZ, -state.lampS];\n    const zTop = focalZ + T_GLASS;\n\n    // 1) Subtle precision corner suspension guide filaments + lamp aperture cone\n    const corners = [[-1, -1], [1, -1], [1, 1], [-1, 1]];\n    for (const [cx, cs] of corners) {\n      // Lamp -> glass corner subtle volumetric guide ray\n      seg(lampW[0], lampW[1], lampW[2], cx, zTop, -cs, 0.95, 0.78, 0.50, 0.14, 0.04);\n      // Vertical bench caliper post from floor to glass corner\n      seg(cx * 1.03, 0.0, -cs * 1.03, cx * 1.03, zTop + 0.03, -cs * 1.03, 0.35, 0.40, 0.50, 0.16, 0.22);\n    }\n\n    // Subtle zenith target ring at (0, DESIGN_Z_LIGHT, 0) so user sees the focal lock sweet-spot!\n    const RING_N = 32, R_ZEN = 0.14;\n    for (let i = 0; i < RING_N; i++) {\n      const a0 = (i / RING_N) * Math.PI * 2, a1 = ((i + 1) / RING_N) * Math.PI * 2;\n      seg(\n        Math.cos(a0) * R_ZEN, DESIGN_Z_LIGHT, Math.sin(a0) * R_ZEN,\n        Math.cos(a1) * R_ZEN, DESIGN_Z_LIGHT, Math.sin(a1) * R_ZEN,\n        0.50, 0.84, 0.96, 0.20, 0.20\n      );\n    }\n\n    // 2) 3D Snell Refraction Laser Ray Sheet (68 rays across slice plane ps = raySliceS)\n    if (state.showRays) {\n      const NUM_RAYS = 68;\n      const ps = state.raySliceS;\n      // Slice indicator bar on top of glass\n      seg(-1.0, zTop + 0.004, -ps, 1.0, zTop + 0.004, -ps, 0.48, 0.86, 0.96, 0.35, 0.35);\n      for (let i = 0; i < NUM_RAYS; i++) {\n        const px = -0.94 + (1.88 * i) / (NUM_RAYS - 1);\n        const ray = traceSingleRay3D(px, ps, focalZ, nIOR);\n        if (!ray) continue;\n        // Incident ray: Lamp -> Top flat surface\n        seg(lampW[0], lampW[1], lampW[2], ray.top[0], ray.top[1], ray.top[2], 1.0, 0.84, 0.55, 0.08, 0.20);\n        // Internal glass ray: Top -> Sculpted bottom\n        seg(ray.top[0], ray.top[1], ray.top[2], ray.bot[0], ray.bot[1], ray.bot[2], 0.52, 0.90, 1.0, 0.34, 0.48);\n        // Refracted caustic ray: Sculpted bottom -> Stage floor!\n        seg(ray.bot[0], ray.bot[1], ray.bot[2], ray.stage[0], ray.stage[1], ray.stage[2], 1.0, 0.78, 0.42, 0.36, 0.26);\n      }\n    }\n\n    // 3) Optimal Transport (Brenier) Grid Overlay (28 x 28 mesh on glass AND refracted on stage!)\n    if (state.showGrid) {\n      const G = 28;\n      const stagePts = new Array((G + 1) * (G + 1));\n      for (let j = 0; j <= G; j++) {\n        const ps = -0.92 + (1.84 * j) / G;\n        for (let i = 0; i <= G; i++) {\n          const px = -0.92 + (1.84 * i) / G;\n          stagePts[j * (G + 1) + i] = traceSingleRay3D(px, ps, focalZ, nIOR);\n        }\n      }\n      for (let j = 0; j <= G; j++) {\n        for (let i = 0; i <= G; i++) {\n          const a = stagePts[j * (G + 1) + i];\n          if (!a) continue;\n          if (i < G) {\n            const b = stagePts[j * (G + 1) + i + 1];\n            if (b) {\n              seg(a.top[0], a.top[1] + 0.002, a.top[2], b.top[0], b.top[1] + 0.002, b.top[2], 0.5, 0.85, 0.98, 0.14, 0.14);\n              seg(a.stage[0], 0.005, a.stage[2], b.stage[0], 0.005, b.stage[2], 0.48, 0.86, 0.98, 0.26, 0.26);\n            }\n          }\n          if (j < G) {\n            const b = stagePts[(j + 1) * (G + 1) + i];\n            if (b) {\n              seg(a.top[0], a.top[1] + 0.002, a.top[2], b.top[0], b.top[1] + 0.002, b.top[2], 0.5, 0.85, 0.98, 0.14, 0.14);\n              seg(a.stage[0], 0.005, a.stage[2], b.stage[0], 0.005, b.stage[2], 0.48, 0.86, 0.98, 0.26, 0.26);\n            }\n          }\n        }\n      }\n    }\n\n    gl.bindBuffer(gl.ARRAY_BUFFER, lineVBO);\n    gl.bufferSubData(gl.ARRAY_BUFFER, 0, lineData.subarray(0, ptr));\n    return ptr / 7;\n  }\n\n  // ============================================================================\n  // 10. UI CONTROLS, POINTER DIRECT MANIPULATION & LIVE SKETCHING\n  // ============================================================================\n  const presetOrder = [\"astrolabe\", \"nautilus\", \"saturn\", \"crane\", \"lorenz\"];\n  const presetBtns = document.querySelectorAll(\"#presetGroup button[data-preset]\");\n  const loupeCard = document.getElementById(\"loupeCard\");\n\n  function selectPreset(name, fromAuto = false) {\n    state.preset = name;\n    presetBtns.forEach((b) => b.classList.toggle(\"active\", b.dataset.preset === name));\n    if (name === \"custom\") {\n      loupeCard.classList.remove(\"collapsed\");\n      loupeCard.classList.add(\"expanded\");\n      document.getElementById(\"btnToggleLoupe\").textContent = \"–\";\n      state.loupeTab = \"target\";\n      document.getElementById(\"tabTarget\").classList.add(\"active\");\n      document.getElementById(\"tabHeight\").classList.remove(\"active\");\n      renderPadCanvas();\n      return;\n    }\n    loupeCard.classList.remove(\"expanded\");\n    if (!fromAuto) markUserInteracted();\n    state.target256 = PRESETS[name]();\n    uploadTargetTexture();\n    renderPadCanvas();\n    requestLensSolve(state.target256);\n  }\n\n  presetBtns.forEach((btn) => {\n    btn.addEventListener(\"click\", () => selectPreset(btn.dataset.preset, false));\n  });\n\n  function markUserInteracted() {\n    if (!state.userInteracted) {\n      state.userInteracted = true;\n      document.getElementById(\"gestureHint\").classList.add(\"hidden\");\n    }\n    state.autoChoreo = false;\n  }\n\n  // Camera View Presets\n  const camBtns = document.querySelectorAll(\"button[data-cam]\");\n  function setCameraPreset(mode) {\n    camBtns.forEach((b) => b.classList.toggle(\"active\", b.dataset.cam === mode));\n    if (mode === \"studio\") {\n      state.camTargetYaw = 0.34; state.camTargetPitch = 0.56; state.camTargetDist = 6.35; state.camTargetCenterY = 1.02;\n    } else if (mode === \"profile\") {\n      state.camTargetYaw = 0.14; state.camTargetPitch = 0.13; state.camTargetDist = 5.20; state.camTargetCenterY = 1.65;\n    } else if (mode === \"top\") {\n      state.camTargetYaw = 0.0;  state.camTargetPitch = 1.50; state.camTargetDist = 5.45; state.camTargetCenterY = 0.25;\n    }\n  }\n  camBtns.forEach((btn) => btn.addEventListener(\"click\", () => {\n    markUserInteracted();\n    setCameraPreset(btn.dataset.cam);\n  }));\n\n  // Focal Height Slider\n  const focalSlider = document.getElementById(\"focalSlider\");\n  const focalVal = document.getElementById(\"focalVal\");\n  focalSlider.addEventListener(\"input\", () => {\n    markUserInteracted();\n    let v = parseFloat(focalSlider.value);\n    if (Math.abs(v - 1.0) < 0.022) { v = 1.0; focalSlider.value = \"1.00\"; } // subtle magnetic detent at exact focus!\n    state.focalRatio = v;\n    focalVal.textContent = `${Math.round(v * 110)} mm`;\n  });\n\n  // Glass Material Selector\n  const glassSelect = document.getElementById(\"glassSelect\");\n  glassSelect.addEventListener(\"change\", () => {\n    markUserInteracted();\n    state.selectedGlass = glassSelect.value;\n    // Show \"Re-grind\" button when viewing an existing lens made for a different index of refraction!\n    // (Lets physicists observe Lensmaker focal-shift f ~ 1/(n-1) first, then re-grind on demand!)\n    btnRegrind.style.display = (state.selectedGlass !== state.carvedForGlass) ? \"inline-flex\" : \"none\";\n  });\n\n  btnRegrind.addEventListener(\"click\", () => {\n    markUserInteracted();\n    requestLensSolve(state.target256);\n  });\n\n  // Diagnostic Toggles\n  const btnRays = document.getElementById(\"btnRays\");\n  const btnGrid = document.getElementById(\"btnGrid\");\n  const btnInterf = document.getElementById(\"btnInterf\");\n  const btnCompare = document.getElementById(\"btnCompare\");\n\n  btnRays.addEventListener(\"click\", () => {\n    state.showRays = !state.showRays;\n    btnRays.classList.toggle(\"cyan-active\", state.showRays);\n  });\n  btnGrid.addEventListener(\"click\", () => {\n    state.showGrid = !state.showGrid;\n    btnGrid.classList.toggle(\"cyan-active\", state.showGrid);\n  });\n  btnInterf.addEventListener(\"click\", () => {\n    state.showInterf = !state.showInterf;\n    btnInterf.classList.toggle(\"cyan-active\", state.showInterf);\n  });\n  btnCompare.addEventListener(\"click\", () => {\n    state.compareMask = !state.compareMask;\n    btnCompare.classList.toggle(\"active\", state.compareMask);\n  });\n\n  // Top Utility Buttons\n  document.getElementById(\"btnAlign\").addEventListener(\"click\", () => {\n    state.autoChoreo = false;\n    state.lampTargetX = 0.0;\n    state.lampTargetS = 0.0;\n    state.focalRatio = 1.0;\n    focalSlider.value = \"1.00\";\n    focalVal.textContent = \"110 mm\";\n  });\n\n  const btnAudio = document.getElementById(\"btnAudio\");\n  btnAudio.addEventListener(\"click\", () => {\n    const on = synth.toggle();\n    btnAudio.textContent = on ? \"♪ Sound On\" : \"♪ Sound Off\";\n    btnAudio.classList.toggle(\"active\", on);\n  });\n\n  document.getElementById(\"btnStl\").addEventListener(\"click\", () => {\n    exportBinarySTL(state.hSolved, state.minH, state.preset);\n  });\n\n  // Loupe Pad Tabs & Live Brush / Typography Sculpting\n  const tabTarget = document.getElementById(\"tabTarget\");\n  const tabHeight = document.getElementById(\"tabHeight\");\n  const padBadge  = document.getElementById(\"padBadge\");\n  tabTarget.addEventListener(\"click\", () => {\n    state.loupeTab = \"target\";\n    tabTarget.classList.add(\"active\"); tabHeight.classList.remove(\"active\");\n    padBadge.textContent = \"Draw to carve lens\";\n    renderPadCanvas();\n  });\n  tabHeight.addEventListener(\"click\", () => {\n    state.loupeTab = \"height\";\n    tabHeight.classList.add(\"active\"); tabTarget.classList.remove(\"active\");\n    padBadge.textContent = \"Smooth C² surface\";\n    renderPadCanvas();\n  });\n\n  const btnToggleLoupe = document.getElementById(\"btnToggleLoupe\");\n  btnToggleLoupe.addEventListener(\"click\", () => {\n    const col = loupeCard.classList.toggle(\"collapsed\");\n    btnToggleLoupe.textContent = col ? \"✎ Pad\" : \"–\";\n  });\n\n  const btnBrushDraw = document.getElementById(\"btnBrushDraw\");\n  const btnBrushErase = document.getElementById(\"btnBrushErase\");\n  btnBrushDraw.addEventListener(\"click\", () => {\n    state.brushMode = \"draw\";\n    btnBrushDraw.classList.add(\"active\"); btnBrushErase.classList.remove(\"active\");\n  });\n  btnBrushErase.addEventListener(\"click\", () => {\n    state.brushMode = \"erase\";\n    btnBrushErase.classList.add(\"active\"); btnBrushDraw.classList.remove(\"active\");\n  });\n\n  document.getElementById(\"btnPadClear\").addEventListener(\"click\", () => {\n    markUserInteracted();\n    state.preset = \"custom\";\n    presetBtns.forEach((b) => b.classList.toggle(\"active\", b.dataset.preset === \"custom\"));\n    state.target256.fill(0.032);\n    // Tiny central alignment spark so empty target still has non-degenerate mass\n    state.target256[128 * 256 + 128] = 0.35;\n    state.loupeTab = \"target\";\n    tabTarget.classList.add(\"active\"); tabHeight.classList.remove(\"active\");\n    uploadTargetTexture();\n    renderPadCanvas();\n  });\n\n  // Carve Custom Typography onto Target Grid\n  const glyphInput = document.getElementById(\"glyphInput\");\n  function carveCustomText() {\n    const txt = (glyphInput.value || \"LUX\").trim().toUpperCase();\n    if (!txt) return;\n    markUserInteracted();\n    state.preset = \"custom\";\n    presetBtns.forEach((b) => b.classList.toggle(\"active\", b.dataset.preset === \"custom\"));\n    state.loupeTab = \"target\";\n    tabTarget.classList.add(\"active\"); tabHeight.classList.remove(\"active\");\n\n    const off = document.createElement(\"canvas\");\n    off.width = N_GRID; off.height = N_GRID;\n    const ctx = off.getContext(\"2d\");\n    ctx.fillStyle = \"#000\";\n    ctx.fillRect(0, 0, N_GRID, N_GRID);\n    ctx.fillStyle = \"#fff\";\n    ctx.textAlign = \"center\";\n    ctx.textBaseline = \"middle\";\n    const fontSize = Math.min(108, Math.floor(215 / Math.max(1.4, txt.length * 0.62)));\n    ctx.font = `600 ${fontSize}px Georgia, \"Times New Roman\", serif`;\n    ctx.fillText(txt, N_GRID / 2, N_GRID / 2 + 2);\n\n    // Subtle decorative framing arcs above and below text\n    ctx.strokeStyle = \"rgba(255,255,255,0.65)\";\n    ctx.lineWidth = 3.2;\n    ctx.beginPath(); ctx.arc(128, 128, 98, -0.78 * Math.PI, -0.22 * Math.PI); ctx.stroke();\n    ctx.beginPath(); ctx.arc(128, 128, 98,  0.22 * Math.PI,  0.78 * Math.PI); ctx.stroke();\n\n    const img = ctx.getImageData(0, 0, N_GRID, N_GRID).data;\n    // Slight 3x3 Gaussian soften for silky caustic strokes\n    const raw = new Float32Array(N_GRID * N_GRID);\n    for (let y = 0; y < N_GRID; y++) {\n      const sy = N_GRID - 1 - y;\n      for (let x = 0; x < N_GRID; x++) {\n        raw[y * N_GRID + x] = img[(sy * N_GRID + x) * 4] / 255.0;\n      }\n    }\n    for (let y = 0; y < N_GRID; y++) {\n      for (let x = 0; x < N_GRID; x++) {\n        let sum = 0, wSum = 0;\n        for (let dy = -2; dy <= 2; dy++) {\n          const yy = Math.max(0, Math.min(255, y + dy));\n          for (let dx = -2; dx <= 2; dx++) {\n            const xx = Math.max(0, Math.min(255, x + dx));\n            const w = Math.exp(-(dx * dx + dy * dy) / 2.6);\n            sum += raw[yy * N_GRID + xx] * w; wSum += w;\n          }\n        }\n        state.target256[y * N_GRID + x] = 0.032 + 1.18 * (sum / wSum);\n      }\n    }\n    uploadTargetTexture();\n    renderPadCanvas();\n    requestLensSolve(state.target256);\n    state.lampTargetX = 0; state.lampTargetS = 0;\n  }\n\n  document.getElementById(\"btnCarveText\").addEventListener(\"click\", carveCustomText);\n  glyphInput.addEventListener(\"keydown\", (e) => { if (e.key === \"Enter\") carveCustomText(); });\n\n  // Interactive Freehand Drawing on Loupe Pad (throttled live 160ms PDE re-carve!)\n  let padDrawing = false, lastPadPos = null, liveSolveTimer = null;\n  function getPadCoords(e) {\n    const r = padCanvas.getBoundingClientRect();\n    const u = Math.max(0, Math.min(1, (e.clientX - r.left) / r.width));\n    const v = Math.max(0, Math.min(1, 1.0 - (e.clientY - r.top) / r.height));\n    return [u * N_GRID, v * N_GRID];\n  }\n\n  function paintStroke(x0, y0, x1, y1) {\n    const dist = Math.hypot(x1 - x0, y1 - y0);\n    const steps = Math.max(1, Math.ceil(dist * 0.75));\n    const rad = state.brushMode === \"erase\" ? 11.0 : 5.2;\n    for (let s = 0; s <= steps; s++) {\n      const t = s / steps;\n      const cx = x0 + (x1 - x0) * t, cy = y0 + (y1 - y0) * t;\n      // Keep inside clean optical aperture [18..238]\n      const px = Math.max(18, Math.min(238, cx)), py = Math.max(18, Math.min(238, cy));\n      const rPix = Math.ceil(rad * 2.4);\n      const ix0 = Math.max(0, Math.floor(px - rPix)), ix1 = Math.min(255, Math.ceil(px + rPix));\n      const iy0 = Math.max(0, Math.floor(py - rPix)), iy1 = Math.min(255, Math.ceil(py + rPix));\n      for (let y = iy0; y <= iy1; y++) {\n        for (let x = ix0; x <= ix1; x++) {\n          const d2 = ((x + 0.5 - px) ** 2 + (y + 0.5 - py) ** 2) / (rad * rad);\n          if (d2 > 6.0) continue;\n          const idx = y * N_GRID + x;\n          if (state.brushMode === \"erase\") {\n            state.target256[idx] = 0.032 + (state.target256[idx] - 0.032) * (1 - 0.85 * Math.exp(-d2));\n          } else {\n            const v = 0.032 + 1.18 * Math.exp(-d2);\n            if (v > state.target256[idx]) state.target256[idx] = v;\n          }\n        }\n      }\n    }\n    uploadTargetTexture();\n    renderPadCanvas();\n    if (!liveSolveTimer) {\n      liveSolveTimer = setTimeout(() => {\n        liveSolveTimer = null;\n        if (!state.solving) requestLensSolve(state.target256);\n      }, 170);\n    }\n  }\n\n  padCanvas.addEventListener(\"pointerdown\", (e) => {\n    markUserInteracted();\n    padCanvas.setPointerCapture(e.pointerId);\n    if (state.loupeTab !== \"target\") {\n      state.loupeTab = \"target\";\n      tabTarget.classList.add(\"active\"); tabHeight.classList.remove(\"active\");\n    }\n    if (state.preset !== \"custom\") {\n      // First stroke on a preset transitions smoothly into Custom Sculpt mode!\n      state.preset = \"custom\";\n      presetBtns.forEach((b) => b.classList.toggle(\"active\", b.dataset.preset === \"custom\"));\n    }\n    padDrawing = true;\n    lastPadPos = getPadCoords(e);\n    paintStroke(lastPadPos[0], lastPadPos[1], lastPadPos[0], lastPadPos[1]);\n    state.lampTargetX = 0; state.lampTargetS = 0;\n  });\n\n  padCanvas.addEventListener(\"pointermove\", (e) => {\n    if (!padDrawing) return;\n    const cur = getPadCoords(e);\n    paintStroke(lastPadPos[0], lastPadPos[1], cur[0], cur[1]);\n    lastPadPos = cur;\n  });\n\n  function finishPadStroke() {\n    if (!padDrawing) return;\n    padDrawing = false;\n    if (liveSolveTimer) { clearTimeout(liveSolveTimer); liveSolveTimer = null; }\n    requestLensSolve(state.target256);\n  }\n  padCanvas.addEventListener(\"pointerup\", finishPadStroke);\n  padCanvas.addEventListener(\"pointercancel\", finishPadStroke);\n\n  // ============================================================================\n  // 11. MAIN 3D VIEWPORT POINTER CONTROLS (Dual-Zone: Steer Lamp OR Orbit 3D!)\n  // ============================================================================\n  let dragMode = null; // \"lamp\" | \"orbit\" | \"slice\"\n  let dragLastX = 0, dragLastY = 0;\n  let currentVP = new Float32Array(16);\n\n  canvas.addEventListener(\"pointerdown\", (e) => {\n    markUserInteracted();\n    canvas.setPointerCapture(e.pointerId);\n    dragLastX = e.clientX;\n    dragLastY = e.clientY;\n\n    const w = canvas.clientWidth, h = canvas.clientHeight;\n    const lampScr = projectToScreen(currentVP, state.lampX, state.lampZ, -state.lampS, w, h);\n    const stageCenterScr = projectToScreen(currentVP, 0, 0, 0, w, h);\n\n    if (e.button === 2 || e.altKey) {\n      dragMode = \"orbit\";\n    } else if (lampScr && Math.hypot(e.clientX - lampScr[0], e.clientY - lampScr[1]) < 64) {\n      dragMode = \"lamp\";\n    } else if (stageCenterScr && e.clientY > h * 0.48) {\n      // Dragging on the lower stage half steers the 3D light rays tactilely!\n      dragMode = \"lamp\";\n    } else {\n      dragMode = \"orbit\";\n    }\n    canvas.classList.toggle(\"dragging-lamp\", dragMode === \"lamp\");\n    canvas.classList.toggle(\"dragging-orbit\", dragMode === \"orbit\");\n  });\n\n  canvas.addEventListener(\"pointermove\", (e) => {\n    if (!dragMode) return;\n    const dx = e.clientX - dragLastX, dy = e.clientY - dragLastY;\n    dragLastX = e.clientX; dragLastY = e.clientY;\n\n    if (dragMode === \"lamp\") {\n      // Convert screen delta into camera-aligned horizontal lamp motion\n      const scale = 0.0075;\n      const cosY = Math.cos(state.camYaw), sinY = Math.sin(state.camYaw);\n      // Right vector in world XZ is (cosY, -sinY); Forward in world XZ is (-sinY, -cosY)\n      const dWorldX = dx * cosY * scale + dy * sinY * scale;\n      const dWorldZ = -dx * sinY * scale + dy * cosY * scale;\n      state.lampTargetX = Math.max(-3.0, Math.min(3.0, state.lampTargetX + dWorldX));\n      state.lampTargetS = Math.max(-3.0, Math.min(3.0, state.lampTargetS - dWorldZ));\n      // Gentle magnetic sweet-spot detent right near exact (0,0) optical axis!\n      if (Math.hypot(state.lampTargetX, state.lampTargetS) < 0.065) {\n        state.lampTargetX *= 0.65;\n        state.lampTargetS *= 0.65;\n      }\n      if (state.showRays && e.shiftKey) {\n        state.raySliceS = Math.max(-0.88, Math.min(0.88, state.raySliceS - dy * 0.005));\n      }\n    } else if (dragMode === \"orbit\") {\n      camBtns.forEach((b) => b.classList.remove(\"active\"));\n      state.camTargetYaw -= dx * 0.0065;\n      state.camTargetPitch = Math.max(0.07, Math.min(1.52, state.camTargetPitch + dy * 0.0065));\n    }\n  });\n\n  function endViewportDrag() {\n    dragMode = null;\n    canvas.classList.remove(\"dragging-lamp\", \"dragging-orbit\");\n    // Snap cleanly to 0 if released inside the tiny zenith sweet spot ring\n    if (Math.hypot(state.lampTargetX, state.lampTargetS) < 0.11) {\n      state.lampTargetX = 0.0;\n      state.lampTargetS = 0.0;\n    }\n  }\n  canvas.addEventListener(\"pointerup\", endViewportDrag);\n  canvas.addEventListener(\"pointercancel\", endViewportDrag);\n  canvas.addEventListener(\"contextmenu\", (e) => e.preventDefault());\n\n  canvas.addEventListener(\"wheel\", (e) => {\n    e.preventDefault();\n    state.camTargetDist = Math.max(3.4, Math.min(9.6, state.camTargetDist + e.deltaY * 0.0035));\n  }, { passive: false });\n\n  // URL parameter hooks for flexible blog embedding (?preset=nautilus&rays=0)\n  const params = new URLSearchParams(window.location.search);\n  if (params.get(\"preset\") && PRESETS[params.get(\"preset\")]) {\n    selectPreset(params.get(\"preset\"), true);\n  }\n  if (params.get(\"rays\") === \"0\") {\n    state.showRays = false;\n    btnRays.classList.remove(\"cyan-active\");\n  }\n\n  // ============================================================================\n  // 12. MAIN 60FPS ANIMATION & MULTI-PASS RENDER LOOP\n  // ============================================================================\n  let lastTime = performance.now();\n  let startTime = lastTime;\n  let slowFrameStreak = 0;\n\n  function resizeCanvas() {\n    const dpr = Math.min(window.devicePixelRatio || 1, 2.0);\n    const w = Math.max(2, Math.floor(window.innerWidth * dpr));\n    const h = Math.max(2, Math.floor(window.innerHeight * dpr));\n    if (canvas.width !== w || canvas.height !== h) {\n      canvas.width = w;\n      canvas.height = h;\n    }\n    ensureSceneCopyTex(w, h);\n  }\n\n  // Cache uniform locations once for zero GC pressure\n  const uCaustic = {\n    lightOpt: gl.getUniformLocation(progCaustic, \"uLightOpt\"),\n    focalZ: gl.getUniformLocation(progCaustic, \"uFocalZ\"),\n    tGlass: gl.getUniformLocation(progCaustic, \"uTGlass\"),\n    baseIOR: gl.getUniformLocation(progCaustic, \"uBaseIOR\"),\n    disp: gl.getUniformLocation(progCaustic, \"uDispersion\"),\n    expScale: gl.getUniformLocation(progCaustic, \"uExposureScale\"),\n    numBands: gl.getUniformLocation(progCaustic, \"uNumBands\"),\n    heightTex: gl.getUniformLocation(progCaustic, \"uHeightTex\")\n  };\n  const uBloom = {\n    tex: gl.getUniformLocation(progBloom, \"uTex\"),\n    texel: gl.getUniformLocation(progBloom, \"uTexel\"),\n    radius: gl.getUniformLocation(progBloom, \"uRadius\")\n  };\n  const uStage = {\n    vp: gl.getUniformLocation(progStage, \"uVP\"),\n    causticTex: gl.getUniformLocation(progStage, \"uCausticTex\"),\n    bloomTex: gl.getUniformLocation(progStage, \"uBloomTex\"),\n    targetTex: gl.getUniformLocation(progStage, \"uTargetTex\"),\n    camPos: gl.getUniformLocation(progStage, \"uCamPos\"),\n    lightWorld: gl.getUniformLocation(progStage, \"uLightWorld\"),\n    focalZ: gl.getUniformLocation(progStage, \"uFocalZ\"),\n    causticScale: gl.getUniformLocation(progStage, \"uCausticScale\"),\n    compareMask: gl.getUniformLocation(progStage, \"uCompareMask\")\n  };\n  const uGlass = {\n    vp: gl.getUniformLocation(progGlass, \"uVP\"),\n    focalZ: gl.getUniformLocation(progGlass, \"uFocalZ\"),\n    tGlass: gl.getUniformLocation(progGlass, \"uTGlass\"),\n    heightTex: gl.getUniformLocation(progGlass, \"uHeightTex\"),\n    sceneCopy: gl.getUniformLocation(progGlass, \"uSceneCopyTex\"),\n    viewport: gl.getUniformLocation(progGlass, \"uViewport\"),\n    camPos: gl.getUniformLocation(progGlass, \"uCamPos\"),\n    lightWorld: gl.getUniformLocation(progGlass, \"uLightWorld\"),\n    baseIOR: gl.getUniformLocation(progGlass, \"uBaseIOR\"),\n    glassTint: gl.getUniformLocation(progGlass, \"uGlassTint\"),\n    showInterf: gl.getUniformLocation(progGlass, \"uShowInterf\")\n  };\n  const uLine = { vp: gl.getUniformLocation(progLine, \"uVP\") };\n  const uLamp = {\n    vp: gl.getUniformLocation(progLamp, \"uVP\"),\n    pos: gl.getUniformLocation(progLamp, \"uLampPos\"),\n    right: gl.getUniformLocation(progLamp, \"uCamRight\"),\n    up: gl.getUniformLocation(progLamp, \"uCamUp\"),\n    size: gl.getUniformLocation(progLamp, \"uSize\"),\n    lock: gl.getUniformLocation(progLamp, \"uFocusLock\")\n  };\n\n  function frame(now) {\n    const dt = Math.min(0.05, (now - lastTime) * 0.001);\n    const rawFrameMs = now - lastTime;\n    lastTime = now;\n    const elapsed = (now - startTime) * 0.001;\n\n    // Adaptive spectral band governor for software GL / low-power mobile\n    if (elapsed > 1.5 && rawFrameMs > 28 && state.numSpectralBands === 5) {\n      slowFrameStreak++;\n      if (slowFrameStreak > 12) state.numSpectralBands = 3;\n    } else {\n      slowFrameStreak = 0;\n    }\n    statRays.textContent = state.numSpectralBands === 5 ? \"512K BEAMS · 5λ\" : \"307K BEAMS · 3λ\";\n\n    resizeCanvas();\n\n    // 1) Autonomous Opening Choreography (sweeps chaotic caustics -> razor focus -> gentle tour)\n    if (state.autoChoreo) {\n      // Cycle every 8.5s: 0..1.6s dramatic sweep into focus, 1.6..6.8s gentle living focus shimmer, 6.8..8.5s morph to next!\n      const period = 8.5;\n      const cyc = elapsed % period;\n      const tourIdx = Math.floor(elapsed / period) % presetOrder.length;\n      const desiredPreset = presetOrder[tourIdx];\n      if (desiredPreset !== state.preset && elapsed > 2.0) {\n        selectPreset(desiredPreset, true);\n      }\n\n      if (cyc < 1.55) {\n        const u = 1.0 - cyc / 1.55;\n        const ease = u * u * (3 - 2 * u);\n        const ang = elapsed * 0.9;\n        state.lampTargetX = Math.cos(ang) * 1.45 * ease;\n        state.lampTargetS = Math.sin(ang) * 1.05 * ease;\n      } else if (cyc < 7.2) {\n        // Subtle living sunlight micro-shimmer around focal lock!\n        state.lampTargetX = Math.cos(elapsed * 1.35) * 0.055;\n        state.lampTargetS = Math.sin(elapsed * 1.05) * 0.055;\n      } else {\n        const u = (cyc - 7.2) / (period - 7.2);\n        const ease = u * u;\n        state.lampTargetX = Math.cos(elapsed * 1.1) * 1.15 * ease;\n        state.lampTargetS = Math.sin(elapsed * 1.1) * 0.85 * ease;\n      }\n      // Gentle studio camera breathing\n      state.camTargetYaw = 0.34 + Math.sin(elapsed * 0.28) * 0.14;\n      if (state.showRays) {\n        state.raySliceS = Math.sin(elapsed * 0.55) * 0.52;\n      }\n    }\n\n    // 2) Smooth Spring Interpolation of Lamp, Camera & 3D Glass Surface Heightfield\n    const prevLampX = state.lampX, prevLampS = state.lampS;\n    const kLamp = 1.0 - Math.exp(-11.0 * dt);\n    state.lampX += (state.lampTargetX - state.lampX) * kLamp;\n    state.lampS += (state.lampTargetS - state.lampS) * kLamp;\n    const lampSpeed = Math.hypot(state.lampX - prevLampX, state.lampS - prevLampS) / Math.max(1e-4, dt);\n\n    const kCam = 1.0 - Math.exp(-8.5 * dt);\n    state.camYaw += (state.camTargetYaw - state.camYaw) * kCam;\n    state.camPitch += (state.camTargetPitch - state.camPitch) * kCam;\n    state.camDist += (state.camTargetDist - state.camDist) * kCam;\n    state.camCenterY += (state.camTargetCenterY - state.camCenterY) * kCam;\n\n    // Smoothly morph physical 3D glass surface hCurrent -> hSolved\n    const kGlass = 1.0 - Math.exp(-7.5 * dt);\n    let maxDiffH = 0;\n    for (let i = 0; i < N_GRID * N_GRID; i++) {\n      const diff = state.hSolved[i] - state.hCurrent[i];\n      if (Math.abs(diff) > maxDiffH) maxDiffH = Math.abs(diff);\n      state.hCurrent[i] += diff * kGlass;\n    }\n    if (maxDiffH > 1e-6) {\n      gl.bindTexture(gl.TEXTURE_2D, heightTex);\n      gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, N_GRID, N_GRID, gl.RED, gl.FLOAT, state.hCurrent);\n    }\n\n    const focalZ = DESIGN_F * state.focalRatio;\n    const mat = MATERIALS[state.selectedGlass];\n\n    // Optical alignment score (0..1) for HUD telemetry & crystalline harmonic synth\n    const offAxis = Math.hypot(state.lampX, state.lampS) / 2.2;\n    const offFocal = Math.abs(state.focalRatio - (MATERIALS[state.carvedForGlass].nD - 1) / (mat.nD - 1));\n    const alignment = Math.max(0, Math.min(1, Math.exp(-2.8 * offAxis * offAxis - 5.0 * offFocal * offFocal)));\n    statFocus.textContent = `ALIGN ${Math.round(alignment * 100)}%`;\n    synth.update(alignment, lampSpeed);\n\n    // --------------------------------------------------------------------------\n    // PASS 1: RENDER CONTINUOUS GPU SPECTRAL CAUSTICS INTO CAUSTIC FBO\n    // --------------------------------------------------------------------------\n    gl.bindFramebuffer(gl.FRAMEBUFFER, fboCaustic.fbo);\n    gl.viewport(0, 0, fboCaustic.w, fboCaustic.h);\n    gl.disable(gl.DEPTH_TEST);\n    gl.disable(gl.CULL_FACE);\n    gl.clearColor(0, 0, 0, 0);\n    gl.clear(gl.COLOR_BUFFER_BIT);\n\n    gl.enable(gl.BLEND);\n    gl.blendFunc(gl.ONE, gl.ONE);\n\n    gl.useProgram(progCaustic);\n    gl.activeTexture(gl.TEXTURE0);\n    gl.bindTexture(gl.TEXTURE_2D, heightTex);\n    gl.uniform1i(uCaustic.heightTex, 0);\n    gl.uniform3f(uCaustic.lightOpt, state.lampX, state.lampS, state.lampZ);\n    gl.uniform1f(uCaustic.focalZ, focalZ);\n    gl.uniform1f(uCaustic.tGlass, T_GLASS);\n    gl.uniform1f(uCaustic.baseIOR, mat.nD);\n    gl.uniform1f(uCaustic.disp, mat.disp);\n    // Scale exposure slightly down when using 8-bit fallback FBO so highlights never clip before tone-mapping\n    const fboScale = useFloatCausticFBO ? 0.145 : 0.022;\n    const stageRecoverScale = useFloatCausticFBO ? 1.0 : (0.145 / 0.022);\n    gl.uniform1f(uCaustic.expScale, fboScale);\n    gl.uniform1i(uCaustic.numBands, state.numSpectralBands);\n\n    gl.bindVertexArray(beamVAO);\n    gl.drawElementsInstanced(gl.TRIANGLES, beamIndices.length, gl.UNSIGNED_INT, 0, state.numSpectralBands);\n\n    // --------------------------------------------------------------------------\n    // PASS 2: DUAL-KAWASE PHYSICALLY SOFT HDR CAUSTIC HALATION / BLOOM\n    // --------------------------------------------------------------------------\n    gl.disable(gl.BLEND);\n    gl.useProgram(progBloom);\n    gl.bindVertexArray(emptyVAO);\n\n    gl.bindFramebuffer(gl.FRAMEBUFFER, fboBloomA.fbo);\n    gl.viewport(0, 0, fboBloomA.w, fboBloomA.h);\n    gl.activeTexture(gl.TEXTURE0);\n    gl.bindTexture(gl.TEXTURE_2D, fboCaustic.tex);\n    gl.uniform1i(uBloom.tex, 0);\n    gl.uniform2f(uBloom.texel, 1 / fboCaustic.w, 1 / fboCaustic.h);\n    gl.uniform1f(uBloom.radius, 1.5);\n    gl.drawArrays(gl.TRIANGLES, 0, 3);\n\n    gl.bindFramebuffer(gl.FRAMEBUFFER, fboBloomB.fbo);\n    gl.viewport(0, 0, fboBloomB.w, fboBloomB.h);\n    gl.bindTexture(gl.TEXTURE_2D, fboBloomA.tex);\n    gl.uniform2f(uBloom.texel, 1 / fboBloomA.w, 1 / fboBloomA.h);\n    gl.uniform1f(uBloom.radius, 2.2);\n    gl.drawArrays(gl.TRIANGLES, 0, 3);\n\n    gl.bindFramebuffer(gl.FRAMEBUFFER, fboBloomA.fbo);\n    gl.viewport(0, 0, fboBloomA.w, fboBloomA.h);\n    gl.bindTexture(gl.TEXTURE_2D, fboBloomB.tex);\n    gl.uniform2f(uBloom.texel, 1 / fboBloomB.w, 1 / fboBloomB.h);\n    gl.uniform1f(uBloom.radius, 1.8);\n    gl.drawArrays(gl.TRIANGLES, 0, 3);\n\n    // --------------------------------------------------------------------------\n    // PASS 3: UNIFIED 3D ATELIER OPTICAL BENCH SCENE\n    // --------------------------------------------------------------------------\n    gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n    const W = canvas.width, H = canvas.height;\n    gl.viewport(0, 0, W, H);\n    gl.clearColor(0.027, 0.031, 0.045, 1.0);\n    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n    gl.enable(gl.DEPTH_TEST);\n    gl.depthMask(true);\n\n    const cosP = Math.cos(state.camPitch), sinP = Math.sin(state.camPitch);\n    const cosY = Math.cos(state.camYaw),   sinY = Math.sin(state.camYaw);\n    const camPos = [\n      state.camDist * cosP * sinY,\n      state.camCenterY + state.camDist * sinP,\n      state.camDist * cosP * cosY\n    ];\n    const center = [0, state.camCenterY * 0.52, 0];\n    const proj = mat4Perspective(39 * Math.PI / 180, W / H, 0.15, 40.0);\n    const view = mat4LookAt(camPos, center, [0, 1, 0]);\n    currentVP = mat4Mul(proj, view);\n    const lightWorld = [state.lampX, state.lampZ, -state.lampS];\n\n    // 3A: Obsidian Receiver Stage + Live Caustics\n    gl.useProgram(progStage);\n    gl.uniformMatrix4fv(uStage.vp, false, currentVP);\n    gl.uniform3fv(uStage.camPos, camPos);\n    gl.uniform3fv(uStage.lightWorld, lightWorld);\n    gl.uniform1f(uStage.focalZ, focalZ);\n    gl.uniform1f(uStage.causticScale, stageRecoverScale);\n    gl.uniform1i(uStage.compareMask, state.compareMask ? 1 : 0);\n\n    gl.activeTexture(gl.TEXTURE0);\n    gl.bindTexture(gl.TEXTURE_2D, fboCaustic.tex);\n    gl.uniform1i(uStage.causticTex, 0);\n    gl.activeTexture(gl.TEXTURE1);\n    gl.bindTexture(gl.TEXTURE_2D, fboBloomA.tex);\n    gl.uniform1i(uStage.bloomTex, 1);\n    gl.activeTexture(gl.TEXTURE2);\n    gl.bindTexture(gl.TEXTURE_2D, targetTex);\n    gl.uniform1i(uStage.targetTex, 2);\n\n    gl.bindVertexArray(stageVAO);\n    gl.drawArrays(gl.TRIANGLES, 0, 6);\n\n    // Copy rendered stage into sceneCopyTex so the 3D crystal block refracts the live caustic tabletop!\n    gl.bindTexture(gl.TEXTURE_2D, sceneCopyTex);\n    gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 0, 0, W, H);\n\n    // 3B: Render 3D Sculpted Optical Crystal Block (Back faces then Front faces for true depth!)\n    gl.useProgram(progGlass);\n    gl.uniformMatrix4fv(uGlass.vp, false, currentVP);\n    gl.uniform1f(uGlass.focalZ, focalZ);\n    gl.uniform1f(uGlass.tGlass, T_GLASS);\n    gl.uniform2f(uGlass.viewport, W, H);\n    gl.uniform3fv(uGlass.camPos, camPos);\n    gl.uniform3fv(uGlass.lightWorld, lightWorld);\n    gl.uniform1f(uGlass.baseIOR, mat.nD);\n    gl.uniform3fv(uGlass.glassTint, mat.tint);\n    gl.uniform1i(uGlass.showInterf, state.showInterf ? 1 : 0);\n\n    gl.activeTexture(gl.TEXTURE0);\n    gl.bindTexture(gl.TEXTURE_2D, heightTex);\n    gl.uniform1i(uGlass.heightTex, 0);\n    gl.activeTexture(gl.TEXTURE1);\n    gl.bindTexture(gl.TEXTURE_2D, sceneCopyTex);\n    gl.uniform1i(uGlass.sceneCopy, 1);\n\n    gl.bindVertexArray(glassVAO);\n    gl.enable(gl.CULL_FACE);\n    gl.cullFace(gl.FRONT);\n    gl.drawElements(gl.TRIANGLES, glassIndexCount, gl.UNSIGNED_INT, 0);\n    gl.cullFace(gl.BACK);\n    gl.drawElements(gl.TRIANGLES, glassIndexCount, gl.UNSIGNED_INT, 0);\n    gl.disable(gl.CULL_FACE);\n\n    // 3C: Additive 3D Diagnostic Lines (Ray Sheet, Optimal Transport Grid, Bench Guides) + Point Lamp\n    const lineVertCount = buildDiagnosticLines(focalZ, mat.nD);\n    gl.enable(gl.BLEND);\n    gl.blendFunc(gl.ONE, gl.ONE);\n    gl.depthMask(false);\n\n    if (lineVertCount > 0) {\n      gl.useProgram(progLine);\n      gl.uniformMatrix4fv(uLine.vp, false, currentVP);\n      gl.bindVertexArray(lineVAO);\n      gl.drawArrays(gl.LINES, 0, lineVertCount);\n    }\n\n    // 3D Point Lamp Filament Halo\n    gl.useProgram(progLamp);\n    gl.uniformMatrix4fv(uLamp.vp, false, currentVP);\n    gl.uniform3fv(uLamp.pos, lightWorld);\n    gl.uniform3f(uLamp.right, view[0], view[4], view[8]);\n    gl.uniform3f(uLamp.up, view[1], view[5], view[9]);\n    gl.uniform1f(uLamp.size, 0.34);\n    gl.uniform1f(uLamp.lock, alignment);\n    gl.bindVertexArray(emptyVAO);\n    gl.drawArrays(gl.TRIANGLES, 0, 6);\n\n    gl.depthMask(true);\n    gl.disable(gl.BLEND);\n    requestAnimationFrame(frame);\n  }\n\n  requestAnimationFrame(frame);\n})();\n</script>\n</body>\n</html>\n",
      "Overwrite": true,
      "Path": "~/run/index.html"
    }

    result, 1 line

    Created file.