@votax572002/fluxfx 0.1.1 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,13 +1,13 @@
1
- "use strict";var _=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var me=Object.prototype.hasOwnProperty;var he=(o,e)=>{for(var i in e)_(o,i,{get:e[i],enumerable:!0})},pe=(o,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of fe(e))!me.call(o,r)&&r!==i&&_(o,r,{get:()=>e[r],enumerable:!(t=de(e,r))||t.enumerable});return o};var ve=o=>pe(_({},"__esModule",{value:!0}),o);var Ce={};he(Ce,{FluxEngine:()=>T,FluxFX:()=>Ae,WebGLQuad:()=>x});module.exports=ve(Ce);var O=class{constructor(){this.listeners=new Set;this.rafId=null;this.startTime=0;this.lastTime=0;this.isDocumentHidden=!1;this.handleVisibilityChange=()=>{this.isDocumentHidden=document.hidden,this.isDocumentHidden?this.stopLoop():this.listeners.size>0&&(this.lastTime=0,this.startLoop())};this.tick=e=>{if(this.listeners.size===0||this.isDocumentHidden){this.stopLoop();return}this.startTime===0&&(this.startTime=e);let i=this.lastTime===0?16.67:Math.min(e-this.lastTime,100);this.lastTime=e;let t=(e-this.startTime)*.001,r=i*.001;this.listeners.forEach(s=>{s(t,r,e)}),this.rafId=window.requestAnimationFrame(this.tick)};typeof document<"u"&&document.addEventListener("visibilitychange",this.handleVisibilityChange)}startLoop(){this.rafId!==null||typeof window>"u"||this.isDocumentHidden||(this.lastTime=0,this.rafId=window.requestAnimationFrame(this.tick))}stopLoop(){this.rafId!==null&&typeof window<"u"&&(window.cancelAnimationFrame(this.rafId),this.rafId=null)}add(e){return this.listeners.add(e),this.listeners.size===1&&this.startLoop(),()=>this.remove(e)}remove(e){this.listeners.delete(e),this.listeners.size===0&&this.stopLoop()}get activeCount(){return this.listeners.size}get isRunning(){return this.rafId!==null}},V=new O;var g=class{static acquireVec2(e=0,i=0){let t=this.vec2Pool.pop()??new Float32Array(2);return t[0]=e,t[1]=i,t}static releaseVec2(e){this.vec2Pool.length<128&&this.vec2Pool.push(e)}static acquireVec3(e=0,i=0,t=0){let r=this.vec3Pool.pop()??new Float32Array(3);return r[0]=e,r[1]=i,r[2]=t,r}static releaseVec3(e){this.vec3Pool.length<128&&this.vec3Pool.push(e)}static acquireVec4(e=0,i=0,t=0,r=1){let s=this.vec4Pool.pop()??new Float32Array(4);return s[0]=e,s[1]=i,s[2]=t,s[3]=r,s}static releaseVec4(e){this.vec4Pool.length<128&&this.vec4Pool.push(e)}static hexToVec3Into(e,i){let t=e.charCodeAt(0)===35?e.slice(1):e;if(t.length===3){let s=parseInt(t[0],16),c=parseInt(t[1],16),a=parseInt(t[2],16);return i[0]=(s<<4|s)/255,i[1]=(c<<4|c)/255,i[2]=(a<<4|a)/255,i}let r=parseInt(t,16);return Number.isNaN(r)?(i[0]=1,i[1]=1,i[2]=1,i):(i[0]=(r>>16&255)/255,i[1]=(r>>8&255)/255,i[2]=(r&255)/255,i)}};g.vec2Pool=[],g.vec3Pool=[],g.vec4Pool=[],g.scratchVec2=new Float32Array(2),g.scratchVec3=new Float32Array(3),g.scratchVec4=new Float32Array(4);var D=class{constructor(e){this.samples=new Float32Array(30);this.sampleIdx=0;this.sampleCount=0;this.stableUpWindows=0;this.lastAdjustAt=0;this.minScale=Math.max(.5,e.minScale),this.maxScale=Math.max(this.minScale,e.maxScale),this.currentScale=this.maxScale,this.downThresholdMs=e.downThresholdMs??20.5,this.upThresholdMs=e.upThresholdMs??17.2,this.cooldownMs=e.cooldownMs??750}get scale(){return this.currentScale}setBounds(e,i){let t=Math.max(.5,e),r=Math.max(t,i),s=this.currentScale;return this.minScale=t,this.maxScale=r,this.currentScale=Math.min(r,Math.max(t,this.currentScale)),r>s&&(this.currentScale=r),this.sampleCount=0,this.sampleIdx=0,this.stableUpWindows=0,Math.abs(this.currentScale-s)>.01}recordFrame(e,i){if(this.minScale>=this.maxScale||e<=0||e>60)return!1;if(this.samples[this.sampleIdx]=e,this.sampleIdx=(this.sampleIdx+1)%this.samples.length,this.sampleCount<this.samples.length)return this.sampleCount++,!1;if(i-this.lastAdjustAt<this.cooldownMs)return!1;let t=0;for(let s=0;s<this.samples.length;s++)t+=this.samples[s];let r=t/this.samples.length;if(r>this.downThresholdMs&&this.currentScale>this.minScale)return this.currentScale=Math.max(this.minScale,Number((this.currentScale-.15).toFixed(2))),this.stableUpWindows=0,this.lastAdjustAt=i,!0;if(r<this.upThresholdMs&&this.currentScale<this.maxScale){if(this.stableUpWindows++,this.stableUpWindows>=2)return this.currentScale=Math.min(this.maxScale,Number((this.currentScale+.1).toFixed(2))),this.stableUpWindows=0,this.lastAdjustAt=i,!0}else this.stableUpWindows=0;return!1}};var E=null;function n(o,e="#ffffff"){if(typeof o!="string")return e;let i=o.trim();if(!i)return e;if(typeof document<"u"){if(!E){let t=document.createElement("canvas");t.width=1,t.height=1,E=t.getContext("2d")}if(E){E.fillStyle="#010203",E.fillStyle=i;let t=E.fillStyle;if(/^#[0-9a-f]{6}$/i.test(t))return t;let r=t.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);if(r)return"#"+[Number(r[1]),Number(r[2]),Number(r[3])].map(s=>Math.max(0,Math.min(255,s)).toString(16).padStart(2,"0")).join("")}}return e}var S=`#version 300 es
1
+ "use strict";var J=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var Be=(o,e)=>{for(var t in e)J(o,t,{get:e[t],enumerable:!0})},Ue=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Pe(e))!Ae.call(o,r)&&r!==t&&J(o,r,{get:()=>e[r],enumerable:!(i=De(e,r))||i.enumerable});return o};var _e=o=>Ue(J({},"__esModule",{value:!0}),o);var Ke={};Be(Ke,{FluxEngine:()=>N,FluxFX:()=>Ye,WebGLQuad:()=>R,createWebGLEffect:()=>E});module.exports=_e(Ke);var ue=["normal","reduced-res","low-fps","survival"];var $=class{constructor(e){this.idx=0;this.count=0;this.lastSampleAt=0;this.samples=new Float32Array(e)}push(e,t){this.samples[this.idx]=e,this.idx=(this.idx+1)%this.samples.length,this.count<this.samples.length&&this.count++,this.lastSampleAt=t}reset(){this.idx=0,this.count=0,this.lastSampleAt=0}isReady(e,t){return this.count>=this.samples.length&&e-this.lastSampleAt<=t}compute(){if(this.count===0)return{avgMs:0,slowRatio:0};let e=0,t=0;for(let i=0;i<this.count;i++){let r=this.samples[i];e+=r,r>26&&t++}return{avgMs:e/this.count,slowRatio:t/this.count}}},Z=class{constructor(){this.mainChannel=new $(30);this.gpuChannel=new $(12);this.listeners=new Set;this.currentTier=0;this.lastEvalAt=0;this.lastTransitionAt=0;this.badChecks=0;this.goodChecks=0;this.lastAvgFrameMs=0;this.lastSlowRatio=0;this.survivalTimer=null}recordMainThread(e,t){e<=0||e>250||(this.mainChannel.push(e,t),this.maybeEvaluate(t))}recordGpuFrame(e,t,i){if(e<=0||e>250||t<=0)return;let r=e*(t/60);this.gpuChannel.push(r,i),this.maybeEvaluate(i)}resetMainThread(){this.mainChannel.reset()}resetAll(){this.mainChannel.reset(),this.gpuChannel.reset(),this.badChecks=0,this.goodChecks=0,this.lastAvgFrameMs=0,this.lastSlowRatio=0}onTierChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}get tier(){return this.currentTier}get label(){return ue[this.currentTier]}getSnapshot(){return{tier:this.currentTier,label:ue[this.currentTier],avgFrameMs:Math.round(this.lastAvgFrameMs*100)/100,slowFrameRatio:Math.round(this.lastSlowRatio*1e3)/1e3}}clearSurvivalProbe(){this.survivalTimer!==null&&(clearTimeout(this.survivalTimer),this.survivalTimer=null)}scheduleSurvivalProbe(){this.clearSurvivalProbe(),typeof setTimeout=="function"&&(this.survivalTimer=setTimeout(()=>{if(this.survivalTimer=null,this.currentTier===3){if(typeof document<"u"&&document.hidden){this.scheduleSurvivalProbe();return}this.mainChannel.reset(),this.gpuChannel.reset(),this.badChecks=0,this.goodChecks=0,this.setTier(2,performance.now())}},6e3))}maybeEvaluate(e){if(e-this.lastEvalAt<400)return;this.lastEvalAt=e;let t=this.mainChannel.isReady(e,1500),i=this.gpuChannel.isReady(e,2500);if(!t&&!i)return;let r=0,s=0;if(t){let a=this.mainChannel.compute();r=Math.max(r,a.avgMs),s=Math.max(s,a.slowRatio)}if(i){let a=this.gpuChannel.compute();r=Math.max(r,a.avgMs),s=Math.max(s,a.slowRatio)}if(this.lastAvgFrameMs=r,this.lastSlowRatio=s,r>22.5||s>=.35){this.badChecks++,this.goodChecks=0,this.badChecks>=2&&this.currentTier<3&&e-this.lastTransitionAt>=2e3&&(this.setTier(this.currentTier+1,e),this.badChecks=0);return}if(r<18.2&&s<.1){this.goodChecks++,this.badChecks=0,this.currentTier>0&&this.goodChecks>=3&&e-this.lastTransitionAt>=5e3&&(this.setTier(this.currentTier-1,e),this.goodChecks=0);return}this.badChecks=0,this.goodChecks=0}setTier(e,t){if(e===this.currentTier)return;let i=this.currentTier;this.currentTier=e,this.lastTransitionAt=t,e===3?this.scheduleSurvivalProbe():this.clearSurvivalProbe(),this.listeners.forEach(r=>r(e,i))}},P=new Z;var ee=class{constructor(){this.listeners=new Set;this.visibilityListeners=new Set;this.rafId=null;this.startTime=0;this.lastTime=0;this.avgFrameTimeMs=0;this.isDocumentHidden=!1;this.handleVisibilityChange=()=>{this.isDocumentHidden=typeof document<"u"?document.hidden:!1,this.isDocumentHidden?(this.stopLoop(),P.resetAll()):this.listeners.size>0&&(this.lastTime=0,this.startLoop()),this.visibilityListeners.forEach(e=>{e(this.isDocumentHidden)})};this.tick=e=>{if(this.listeners.size===0||this.isDocumentHidden){this.stopLoop();return}this.startTime===0&&(this.startTime=e);let t=this.lastTime===0?16.67:e-this.lastTime,i=Math.min(t,100);this.lastTime=e,t>0&&t<500&&(this.avgFrameTimeMs=this.avgFrameTimeMs===0?t:this.avgFrameTimeMs*.9+t*.1),P.recordMainThread(t,e);let r=(e-this.startTime)*.001,s=i*.001;this.listeners.forEach(a=>{a(r,s,e)}),this.listeners.size>0&&!this.isDocumentHidden?this.rafId=window.requestAnimationFrame(this.tick):this.rafId=null};typeof document<"u"&&(this.isDocumentHidden=document.hidden,document.addEventListener("visibilitychange",this.handleVisibilityChange))}startLoop(){this.rafId!==null||typeof window>"u"||this.isDocumentHidden||(this.lastTime=0,this.rafId=window.requestAnimationFrame(this.tick))}stopLoop(){this.rafId!==null&&typeof window<"u"&&(window.cancelAnimationFrame(this.rafId),this.rafId=null),this.lastTime=0,this.avgFrameTimeMs=0,P.resetMainThread()}onVisibilityChange(e){return this.visibilityListeners.add(e),()=>{this.visibilityListeners.delete(e)}}add(e){return this.listeners.add(e),this.listeners.size===1&&this.startLoop(),()=>this.remove(e)}remove(e){this.listeners.delete(e),this.listeners.size===0&&this.stopLoop()}get isHidden(){return this.isDocumentHidden}get activeCount(){return this.listeners.size}get isRunning(){return this.rafId!==null}get frameTimeMs(){return!this.isRunning||this.avgFrameTimeMs<=0?0:Math.round(this.avgFrameTimeMs*100)/100}get fps(){return!this.isRunning||this.avgFrameTimeMs<=0?0:Math.round(1e3/this.avgFrameTimeMs)}},A=new ee;var y=class{static acquireVec2(e=0,t=0){let i=this.vec2Pool.pop()??new Float32Array(2);return i[0]=e,i[1]=t,i}static releaseVec2(e){this.vec2Pool.length<128&&this.vec2Pool.push(e)}static acquireVec3(e=0,t=0,i=0){let r=this.vec3Pool.pop()??new Float32Array(3);return r[0]=e,r[1]=t,r[2]=i,r}static releaseVec3(e){this.vec3Pool.length<128&&this.vec3Pool.push(e)}static acquireVec4(e=0,t=0,i=0,r=1){let s=this.vec4Pool.pop()??new Float32Array(4);return s[0]=e,s[1]=t,s[2]=i,s[3]=r,s}static releaseVec4(e){this.vec4Pool.length<128&&this.vec4Pool.push(e)}static hexToVec3Into(e,t){let i=e.charCodeAt(0)===35?e.slice(1):e;if(i.length===3){let s=parseInt(i[0],16),a=parseInt(i[1],16),n=parseInt(i[2],16);return t[0]=(s<<4|s)/255,t[1]=(a<<4|a)/255,t[2]=(n<<4|n)/255,t}let r=parseInt(i,16);return Number.isNaN(r)?(t[0]=1,t[1]=1,t[2]=1,t):(t[0]=(r>>16&255)/255,t[1]=(r>>8&255)/255,t[2]=(r&255)/255,t)}};y.vec2Pool=[],y.vec3Pool=[],y.vec4Pool=[],y.scratchVec2=new Float32Array(2),y.scratchVec3=new Float32Array(3),y.scratchVec4=new Float32Array(4);var j=class{constructor(e){this.samples=new Float32Array(30);this.sampleIdx=0;this.sampleCount=0;this.stableUpWindows=0;this.lastAdjustAt=0;this.minScale=Math.max(.5,e.minScale),this.maxScale=Math.max(this.minScale,e.maxScale),this.currentScale=this.maxScale,this.downThresholdMs=e.downThresholdMs??20.5,this.upThresholdMs=e.upThresholdMs??17.2,this.cooldownMs=e.cooldownMs??750}get scale(){return this.currentScale}setBounds(e,t){let i=Math.max(.5,e),r=Math.max(i,t),s=this.currentScale;return this.minScale=i,this.maxScale=r,this.currentScale=Math.min(r,Math.max(i,this.currentScale)),r>s&&(this.currentScale=r),this.sampleCount=0,this.sampleIdx=0,this.stableUpWindows=0,Math.abs(this.currentScale-s)>.01}recordFrame(e,t){if(this.minScale>=this.maxScale||e<=0||e>60)return!1;if(this.samples[this.sampleIdx]=e,this.sampleIdx=(this.sampleIdx+1)%this.samples.length,this.sampleCount<this.samples.length)return this.sampleCount++,!1;if(t-this.lastAdjustAt<this.cooldownMs)return!1;let i=0;for(let s=0;s<this.samples.length;s++)i+=this.samples[s];let r=i/this.samples.length;if(r>this.downThresholdMs&&this.currentScale>this.minScale)return this.currentScale=Math.max(this.minScale,Number((this.currentScale-.15).toFixed(2))),this.stableUpWindows=0,this.lastAdjustAt=t,!0;if(r<this.upThresholdMs&&this.currentScale<this.maxScale){if(this.stableUpWindows++,this.stableUpWindows>=2)return this.currentScale=Math.min(this.maxScale,Number((this.currentScale+.1).toFixed(2))),this.stableUpWindows=0,this.lastAdjustAt=t,!0}else this.stableUpWindows=0;return!1}};var V=null;function x(o,e="#ffffff"){if(typeof o!="string")return e;let t=o.trim();if(!t)return e;if(typeof document<"u"){if(!V){let i=document.createElement("canvas");i.width=1,i.height=1,V=i.getContext("2d")}if(V){V.fillStyle="#010203",V.fillStyle=t;let i=V.fillStyle;if(/^#[0-9a-f]{6}$/i.test(i))return i;let r=i.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);if(r)return"#"+[Number(r[1]),Number(r[2]),Number(r[3])].map(s=>Math.max(0,Math.min(255,s)).toString(16).padStart(2,"0")).join("")}}return e}function he(o){let e=o.trim().toLowerCase();if(!e||e==="transparent"||e==="none")return null;let t=e.match(/^rgba?\(\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*[,\s]\s*([\d.]+)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/);if(t){let r=Math.max(0,Math.min(255,parseFloat(t[1])))/255,s=Math.max(0,Math.min(255,parseFloat(t[2])))/255,a=Math.max(0,Math.min(255,parseFloat(t[3])))/255,n=1;return t[4]!==void 0&&(n=t[4].endsWith("%")?parseFloat(t[4])/100:parseFloat(t[4])),[r,s,a,Math.max(0,Math.min(1,n))]}let i=e.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);if(i){let r=i[1],s=r.length===3?r.split("").map(a=>a+a).join(""):r;return[parseInt(s.slice(0,2),16)/255,parseInt(s.slice(2,4),16)/255,parseInt(s.slice(4,6),16)/255,1]}return null}function de(o,e,t){let i=r=>r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4);return .2126*i(o)+.7152*i(e)+.0722*i(t)}function fe(o){if(typeof document>"u"||typeof window>"u")return!0;let e=o;for(;e;){let a=(e.getAttribute("data-theme")||e.getAttribute("data-mode")||e.getAttribute("data-bs-theme")||"").trim().toLowerCase();if(a==="dark")return!0;if(a==="light")return!1;if(e.classList.contains("dark")||e.classList.contains("dark-mode"))return!0;if(e.classList.contains("light")||e.classList.contains("light-mode"))return!1;e=e.parentElement}let t=document.documentElement,i=document.body,r=(t?.getAttribute("data-theme")||t?.getAttribute("data-mode")||t?.getAttribute("data-bs-theme")||"").trim().toLowerCase();if(r==="dark")return!0;if(r==="light")return!1;if(t?.classList.contains("dark")||i?.classList.contains("dark"))return!0;if(t?.classList.contains("light")||i?.classList.contains("light"))return!1;let s=o;for(;s;){let a=window.getComputedStyle(s).backgroundColor,n=he(a);if(n&&n[3]>.12)return de(n[0],n[1],n[2])<.42;s=s.parentElement}return typeof window.matchMedia=="function"?window.matchMedia("(prefers-color-scheme: dark)").matches:!0}function te(o,e,t){let i=Math.max(o,e,t),r=Math.min(o,e,t),s=(i+r)*.5;if(i===r)return[0,0,s];let a=i-r,n=s>.5?a/(2-i-r):a/(i+r),l=0;return i===o?l=((e-t)/a+(e<t?6:0))/6:i===e?l=((t-o)/a+2)/6:l=((o-e)/a+4)/6,[l,n,s]}function me(o,e,t){if(e===0)return[t,t,t];let i=(a,n,l)=>{let c=l;return c<0&&(c+=1),c>1&&(c-=1),c<1/6?a+(n-a)*6*c:c<1/2?n:c<2/3?a+(n-a)*(2/3-c)*6:a},r=t<.5?t*(1+e):t+e-t*e,s=2*t-r;return[i(s,r,o+1/3),i(s,r,o),i(s,r,o-1/3)]}function q(o,e){return o.map(([t,i,r])=>{let[s,a,n]=te(t,i,r);if(e)return[t,i,r];let l=Math.min(a,.72)*.92,c=Math.max(.36,Math.min(.6,n*.78+.14));return me(s,l,c)})}function pe(o,e){if(typeof window>"u"||!o)return null;let t=o;for(;t;){if(t.getAttribute("data-fluxfx-canvas")!=="true"){let i=window.getComputedStyle(t).backgroundColor,r=he(i);if(r&&r[3]>.14)return r}if(t===e)break;t=t.parentElement}return null}function ve(o,e){let[t,i,r]=te(e[0],e[1],e[2]),s=de(e[0],e[1],e[2]);if(i<.2)return q(o,s<.42);let a=s<.38;return o.map(([n,l,c],u)=>{let[h,f,d]=te(n,l,c),m=Math.abs(h-t),p=Math.min(m,1-m),v=h;if(p<.22){let U=[.46,.56,.34];v=(t+U[u%U.length])%1}let g=Math.max(.55,Math.min(.92,f<.35?.72:f)),b=a?Math.max(.68,Math.min(.86,d*.45+.48)):Math.max(.24,Math.min(.44,d*.5+.12)),S=Math.abs(b-r)<.22?a?Math.min(.88,r+.34):Math.max(.2,r-.34):b;return me(v,g,S)})}var z=`#version 300 es
2
2
  precision highp float;
3
3
  layout(location = 0) in vec2 aPosition;
4
4
  out vec2 vUv;
5
5
  void main() {
6
6
  vUv = aPosition * 0.5 + 0.5;
7
7
  gl_Position = vec4(aPosition, 0.0, 1.0);
8
- }`,h=class{static hashSource(e,i){let t=e+"|"+i,r=2166136261;for(let s=0;s<t.length;s++)r^=t.charCodeAt(s),r=Math.imul(r,16777619);return(r>>>0).toString(36)}static compileShader(e,i,t){let r=e.createShader(i);if(!r)throw new Error("[FluxFX] Failed to create WebGLShader");if(e.shaderSource(r,t),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(r);throw e.deleteShader(r),new Error(`[FluxFX] Shader compile error:
9
- ${s}`)}return r}static getOrCreateProgram(e,i,t=S){let r=this.contextCache.get(e);r||(r=new Map,this.contextCache.set(e,r));let s=this.hashSource(t,i),c=r.get(s);if(c)return c;e.getExtension("KHR_parallel_shader_compile");let a=this.compileShader(e,e.VERTEX_SHADER,t),l=this.compileShader(e,e.FRAGMENT_SHADER,i),u=e.createProgram();if(!u)throw e.deleteShader(a),e.deleteShader(l),new Error("[FluxFX] Failed to create WebGLProgram");if(e.attachShader(u,a),e.attachShader(u,l),e.linkProgram(u),e.deleteShader(a),e.deleteShader(l),!e.getProgramParameter(u,e.LINK_STATUS)){let f=e.getProgramInfoLog(u);throw e.deleteProgram(u),new Error(`[FluxFX] Program link error:
10
- ${f}`)}let d={program:u,uniforms:new Map};return r.set(s,d),d}static getUniformLocation(e,i,t){if(i.uniforms.has(t))return i.uniforms.get(t)??null;let r=e.getUniformLocation(i.program,t);return i.uniforms.set(t,r),r}static precompile(e,i){for(let t=0;t<i.length;t++)this.getOrCreateProgram(e,i[t])}static disposeContext(e){let i=this.contextCache.get(e);i&&(i.forEach(t=>e.deleteProgram(t.program)),i.clear(),this.contextCache.delete(e))}};h.contextCache=new WeakMap;var ge=`
8
+ }`,T=class{static hashSource(e,t){let i=e+"|"+t,r=2166136261;for(let s=0;s<i.length;s++)r^=i.charCodeAt(s),r=Math.imul(r,16777619);return(r>>>0).toString(36)}static compileShader(e,t,i){let r=e.createShader(t);if(!r)throw new Error("[FluxFX] Failed to create WebGLShader");if(e.shaderSource(r,i),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(r);throw e.deleteShader(r),new Error(`[FluxFX] Shader compile error:
9
+ ${s}`)}return r}static getOrCreateProgram(e,t,i=z){let r=this.contextCache.get(e);r||(r=new Map,this.contextCache.set(e,r));let s=this.hashSource(i,t),a=r.get(s);if(a)return a;e.getExtension("KHR_parallel_shader_compile");let n=this.compileShader(e,e.VERTEX_SHADER,i),l=this.compileShader(e,e.FRAGMENT_SHADER,t),c=e.createProgram();if(!c)throw e.deleteShader(n),e.deleteShader(l),new Error("[FluxFX] Failed to create WebGLProgram");if(e.attachShader(c,n),e.attachShader(c,l),e.linkProgram(c),e.deleteShader(n),e.deleteShader(l),!e.getProgramParameter(c,e.LINK_STATUS)){let h=e.getProgramInfoLog(c);throw e.deleteProgram(c),new Error(`[FluxFX] Program link error:
10
+ ${h}`)}let u={program:c,uniforms:new Map};return r.set(s,u),u}static getUniformLocation(e,t,i){if(t.uniforms.has(i))return t.uniforms.get(i)??null;let r=e.getUniformLocation(t.program,i);return t.uniforms.set(i,r),r}static precompile(e,t){for(let i=0;i<t.length;i++)this.getOrCreateProgram(e,t[i])}static disposeContext(e){let t=this.contextCache.get(e);t&&(t.forEach(i=>e.deleteProgram(i.program)),t.clear(),this.contextCache.delete(e))}};T.contextCache=new WeakMap;var Ie=`
11
11
  let gl = null;
12
12
  let canvas = null;
13
13
  let displayProgram = null;
@@ -18,12 +18,27 @@ let rafId = 0;
18
18
 
19
19
  let running = false;
20
20
  let pausedByHost = false;
21
+ let survivalPaused = false;
21
22
  let reducedMotion = false;
22
23
  let contextLost = false;
23
24
  let needsResize = false;
24
25
 
26
+ const AMBIENT_FPS = 30;
27
+ const ACTIVE_FPS = 60;
28
+ const INTERACTION_BOOST_MS = 1800;
29
+ let ambientFps = AMBIENT_FPS;
30
+ let activeFps = ACTIVE_FPS;
31
+ const STATS_REPORT_INTERVAL_MS = 350;
32
+
33
+ let boostUntil = 0;
34
+ let lastRafTime = 0;
35
+ let lastDrawTime = 0;
36
+ let lastTargetFps = 0;
37
+ let prevFrameDrew = false;
38
+ let avgDrawDeltaMs = 0;
39
+ let lastStatsReport = 0;
40
+
25
41
  let elapsedSec = 0;
26
- let lastFrameTime = 0;
27
42
  let lastDeltaSec = 0.01667;
28
43
  let currentSpeed = 1.0;
29
44
  let targetSpeed = 1.0;
@@ -81,7 +96,12 @@ function cancelFrame(id) {
81
96
  else clearTimeout(id);
82
97
  }
83
98
 
84
- // Frame-rate independent exponential smoothing (identical feel at 60Hz, 90Hz, 120Hz ProMotion)
99
+ function boostInteraction(durationMs) {
100
+ const until = performance.now() + (durationMs || INTERACTION_BOOST_MS);
101
+ if (until > boostUntil) boostUntil = until;
102
+ }
103
+
104
+ // Frame-rate independent exponential smoothing (identical feel at 30Hz, 60Hz, 120Hz ProMotion)
85
105
  function damp(lambda, dt) {
86
106
  return 1 - Math.exp(-lambda * dt);
87
107
  }
@@ -137,7 +157,7 @@ function applyUniform(prog, cache, name, val) {
137
157
  function computeFboDims(canvasW, canvasH) {
138
158
  let w = Math.max(1, Math.floor(canvasW * feedbackScale));
139
159
  let h = Math.max(1, Math.floor(canvasH * feedbackScale));
140
- // Cap longest edge so 4K/5K Retina screens stay locked at 60/120 FPS
160
+ // Cap longest edge so 4K/5K Retina screens stay locked at target FPS
141
161
  const longest = Math.max(w, h);
142
162
  if (longest > feedbackMaxDim) {
143
163
  const ratio = feedbackMaxDim / longest;
@@ -257,9 +277,9 @@ function applySize() {
257
277
  canvas.width = w;
258
278
  canvas.height = h;
259
279
  gl.viewport(0, 0, w, h);
260
- if (pingPong) {
261
- resizePingPong(w, h);
262
- }
280
+ }
281
+ if (pingPong) {
282
+ resizePingPong(canvas.width, canvas.height);
263
283
  }
264
284
  }
265
285
 
@@ -409,29 +429,69 @@ function stopLoop() {
409
429
  running = false;
410
430
  cancelFrame(rafId);
411
431
  rafId = 0;
412
- lastFrameTime = 0;
432
+ lastRafTime = 0;
433
+ lastDrawTime = 0;
434
+ lastTargetFps = 0;
435
+ prevFrameDrew = false;
436
+ avgDrawDeltaMs = 0;
437
+ lastStatsReport = 0;
438
+ self.postMessage({ type: 'stats', fps: 0, frameTimeMs: 0, targetFps: 0 });
413
439
  }
414
440
 
415
441
  function startLoopIfAllowed() {
416
- if (running || pausedByHost || reducedMotion || contextLost || !gl) return;
442
+ if (running || pausedByHost || survivalPaused || reducedMotion || contextLost || !gl) return;
417
443
  running = true;
418
- lastFrameTime = 0;
444
+ lastRafTime = 0;
445
+ lastDrawTime = 0;
446
+ prevFrameDrew = false;
419
447
  rafId = scheduleFrame(render);
420
448
  }
421
449
 
422
450
  function render(now) {
423
451
  if (!running || !gl || contextLost) return;
424
- const delta = lastFrameTime ? Math.min(now - lastFrameTime, 100) : 16.67;
425
- lastFrameTime = now;
426
- const dt = Math.max(0.001, Math.min(delta * 0.001, 0.05));
452
+
453
+ const rafDelta = lastRafTime ? Math.min(now - lastRafTime, 100) : 16.67;
454
+ lastRafTime = now;
455
+
456
+ // Measure dynamic resolution only on frames immediately following a GPU draw
457
+ if (prevFrameDrew) {
458
+ if (updateDynamicRes(rafDelta, now)) {
459
+ needsResize = true;
460
+ }
461
+ prevFrameDrew = false;
462
+ }
463
+
464
+ const isBoosted = now < boostUntil || mouseDown > 0.5;
465
+ const targetFps = isBoosted ? activeFps : ambientFps;
466
+ const minIntervalMs = (1000 / targetFps) - 2.0;
467
+
468
+ if (lastDrawTime > 0 && (now - lastDrawTime) < minIntervalMs) {
469
+ rafId = scheduleFrame(render);
470
+ return;
471
+ }
472
+
473
+ const rawDrawDelta = lastDrawTime ? (now - lastDrawTime) : (1000 / targetFps);
474
+ const drawDelta = Math.min(rawDrawDelta, 100);
475
+ lastDrawTime = now;
476
+
477
+ if (targetFps !== lastTargetFps) {
478
+ lastTargetFps = targetFps;
479
+ avgDrawDeltaMs = 0;
480
+ } else if (rawDrawDelta > 0 && rawDrawDelta < 500) {
481
+ avgDrawDeltaMs =
482
+ avgDrawDeltaMs === 0
483
+ ? rawDrawDelta
484
+ : avgDrawDeltaMs * 0.85 + rawDrawDelta * 0.15;
485
+ }
486
+
487
+ const dt = Math.max(0.001, Math.min(drawDelta * 0.001, 0.05));
427
488
  lastDeltaSec = dt;
428
489
 
429
490
  // Smoothly ramp speed and integrate phase time (zero jump when speed changes)
430
491
  currentSpeed += (targetSpeed - currentSpeed) * damp(7.5, dt);
431
492
  elapsedSec += dt * currentSpeed;
432
493
 
433
- const dprChanged = updateDynamicRes(delta, now);
434
- if (needsResize || dprChanged) {
494
+ if (needsResize) {
435
495
  needsResize = false;
436
496
  applySize();
437
497
  }
@@ -458,6 +518,17 @@ function render(now) {
458
518
  scrollVel = Math.max(-6, Math.min(6, (scrollProgress - prevS) / dt));
459
519
 
460
520
  drawFrame();
521
+ prevFrameDrew = true;
522
+
523
+ if (avgDrawDeltaMs > 0 && now - lastStatsReport >= STATS_REPORT_INTERVAL_MS) {
524
+ lastStatsReport = now;
525
+ self.postMessage({
526
+ type: 'stats',
527
+ fps: Math.round(1000 / avgDrawDeltaMs),
528
+ frameTimeMs: Math.round(avgDrawDeltaMs * 100) / 100,
529
+ targetFps: targetFps,
530
+ });
531
+ }
461
532
 
462
533
  rafId = scheduleFrame(render);
463
534
  }
@@ -498,6 +569,9 @@ self.onmessage = function(e) {
498
569
  minScale = msg.minDpr;
499
570
  dynamicRes = msg.dynamicRes;
500
571
  reducedMotion = !!msg.reducedMotion;
572
+ ambientFps = msg.ambientFps || AMBIENT_FPS;
573
+ activeFps = msg.activeFps || ACTIVE_FPS;
574
+ survivalPaused = !!msg.survivalPaused;
501
575
  savedVertexSrc = msg.vertexShader;
502
576
  savedFragmentSrc = msg.fragmentShader;
503
577
  savedFeedbackSrc = msg.feedbackShader || null;
@@ -548,6 +622,7 @@ self.onmessage = function(e) {
548
622
  case 'resize':
549
623
  width = msg.width;
550
624
  height = msg.height;
625
+ boostInteraction(600);
551
626
  if (reducedMotion && !pausedByHost && !contextLost) {
552
627
  needsResize = false;
553
628
  applySize();
@@ -556,6 +631,34 @@ self.onmessage = function(e) {
556
631
  needsResize = true;
557
632
  }
558
633
  break;
634
+ case 'protection':
635
+ ambientFps = msg.ambientFps || AMBIENT_FPS;
636
+ activeFps = msg.activeFps || ACTIVE_FPS;
637
+ minScale = msg.minDpr;
638
+ baseDpr = msg.maxDpr;
639
+ dprScale = baseDpr;
640
+ if (typeof msg.feedbackMaxDim === 'number') {
641
+ feedbackMaxDim = msg.feedbackMaxDim;
642
+ }
643
+ sampleCount = 0;
644
+ sampleIdx = 0;
645
+ stableWindows = 0;
646
+ if (msg.suspended) {
647
+ survivalPaused = true;
648
+ stopLoop();
649
+ } else {
650
+ const wasSuspended = survivalPaused;
651
+ survivalPaused = false;
652
+ if (reducedMotion && !pausedByHost && !contextLost) {
653
+ needsResize = false;
654
+ applySize();
655
+ drawFrame();
656
+ } else {
657
+ needsResize = true;
658
+ if (wasSuspended) startLoopIfAllowed();
659
+ }
660
+ }
661
+ break;
559
662
  case 'dprBounds':
560
663
  minScale = msg.minDpr;
561
664
  baseDpr = msg.maxDpr;
@@ -579,11 +682,13 @@ self.onmessage = function(e) {
579
682
  mouseVel[0] = 0;
580
683
  mouseVel[1] = 0;
581
684
  targetMouseActive = 1;
685
+ boostInteraction(INTERACTION_BOOST_MS);
582
686
  break;
583
687
  case 'mouse':
584
688
  targetMouse[0] = msg.x;
585
689
  targetMouse[1] = msg.y;
586
690
  targetMouseActive = 1;
691
+ boostInteraction(INTERACTION_BOOST_MS);
587
692
  break;
588
693
  case 'mouseLeave':
589
694
  targetMouseActive = 0;
@@ -593,9 +698,11 @@ self.onmessage = function(e) {
593
698
  break;
594
699
  case 'mouseDown':
595
700
  mouseDown = msg.down ? 1 : 0;
701
+ boostInteraction(INTERACTION_BOOST_MS);
596
702
  break;
597
703
  case 'scroll':
598
704
  targetScroll = msg.progress;
705
+ boostInteraction(1200);
599
706
  if (reducedMotion && !pausedByHost && !contextLost) {
600
707
  scrollProgress = targetScroll;
601
708
  scrollVel = 0;
@@ -607,6 +714,7 @@ self.onmessage = function(e) {
607
714
  if (msg.name === 'uSpeed' && typeof msg.value === 'number') {
608
715
  targetSpeed = msg.value;
609
716
  }
717
+ boostInteraction(1200);
610
718
  if (reducedMotion && !contextLost) drawFrame();
611
719
  break;
612
720
  case 'uniformsBatch':
@@ -618,6 +726,7 @@ self.onmessage = function(e) {
618
726
  }
619
727
  }
620
728
  }
729
+ boostInteraction(1200);
621
730
  if (reducedMotion && !contextLost) drawFrame();
622
731
  break;
623
732
  case 'reducedMotion':
@@ -668,7 +777,9 @@ self.onmessage = function(e) {
668
777
  if (feedbackProgram) gl.deleteProgram(feedbackProgram);
669
778
  if (vbo) gl.deleteBuffer(vbo);
670
779
  if (vao) gl.deleteVertexArray(vao);
671
- gl.getExtension('WEBGL_lose_context')?.loseContext();
780
+ if (!gl.isContextLost()) {
781
+ gl.getExtension('WEBGL_lose_context')?.loseContext();
782
+ }
672
783
  }
673
784
  gl = null;
674
785
  canvas = null;
@@ -676,7 +787,7 @@ self.onmessage = function(e) {
676
787
  break;
677
788
  }
678
789
  };
679
- `,I=null;function H(){if(typeof window>"u"||typeof Worker>"u"||typeof OffscreenCanvas>"u"||typeof HTMLCanvasElement>"u"||!("transferControlToOffscreen"in HTMLCanvasElement.prototype))return!1;let o=typeof navigator<"u"?navigator.userAgent:"";return!(/iP(ad|hone|od)/i.test(o)||/^((?!chrome|android).)*safari/i.test(o))}function z(){if(!I){let o=new Blob([ge],{type:"application/javascript"});I=URL.createObjectURL(o)}return new Worker(I)}var G=S;var A={low:{max:1,min:.65,retinaMin:.85,fboMaxDim:512},medium:{max:2,min:.75,retinaMin:1,fboMaxDim:896},high:{max:2,min:1,retinaMin:1.25,fboMaxDim:1152}},be=new Float32Array([-1,-1,3,-1,-1,3]),ye=12;function C(o,e){return 1-Math.exp(-o*e)}var R=class R{constructor(e,i){this.resizeObserver=null;this.visibilityObserver=null;this.reducedMotionQuery=null;this.dprMediaQuery=null;this.worker=null;this.isOffscreen=!1;this.gl=null;this.programEntry=null;this.feedbackProgramEntry=null;this.vao=null;this.vbo=null;this.dynamicRes=null;this.lastRenderNow=0;this.elapsedSec=0;this.lastDeltaSec=.01667;this.currentSpeed=1;this.targetSpeed=1;this.needsResize=!1;this.pingPong=null;this.fboW=1;this.fboH=1;this.fboFormat=0;this.fboType=0;this.readIdx=0;this.writeIdx=1;this.customUniforms=new Map;this.mouse=g.acquireVec2(.5,.5);this.targetMouse=g.acquireVec2(.5,.5);this.mouseVel=g.acquireVec2(0,0);this.mouseDown=0;this.mouseActive=0;this.targetMouseActive=0;this.isPointerInside=!1;this.scroll=0;this.targetScroll=0;this.scrollVel=0;this.hasScrollListener=!1;this.width=1;this.height=1;this.isPaused=!1;this.isHiddenByViewport=!1;this.isContextLost=!1;this.isReducedMotion=!1;this.isDestroyed=!1;this.hasPointerListener=!1;this.countedContext=!1;this.handleContextLost=e=>{e.preventDefault(),this.isContextLost=!0,this.lastRenderNow=0,this.gl&&h.disposeContext(this.gl),this.programEntry=null,this.feedbackProgramEntry=null,this.pingPong=null,this.vao=null,this.vbo=null};this.handleContextRestored=()=>{if(!(this.isDestroyed||!this.gl))try{this.isContextLost=!1,this.initMainThreadPipeline(this.gl),this.drawMainThreadFrame()}catch(e){console.error("[FluxFX] Failed to restore WebGL2 context:",e)}};this.handleDprChange=()=>{this.isDestroyed||(this.syncDprBounds(),this.watchDevicePixelRatio())};this.handleReducedMotionChange=e=>{this.applyReducedMotionState(this.respectReducedMotion&&e.matches)};this.handlePointerEnter=e=>{if(this.isPaused||this.isHiddenByViewport||this.isReducedMotion)return;let i=this.getLocalPointerCoords(e);if(!i)return;let[t,r]=i;this.isPointerInside=!0,this.targetMouseActive=1,this.isOffscreen&&this.worker?this.worker.postMessage({type:"mouseEnter",x:t,y:r}):(this.mouse[0]=t,this.mouse[1]=r,this.targetMouse[0]=t,this.targetMouse[1]=r,this.mouseVel[0]=0,this.mouseVel[1]=0)};this.handlePointerMove=e=>{if(this.isPaused||this.isHiddenByViewport||this.isReducedMotion)return;let i=this.getLocalPointerCoords(e);if(!i){this.isPointerInside&&this.handlePointerLeave();return}let[t,r]=i;if(!this.isPointerInside){this.handlePointerEnter(e);return}this.isOffscreen&&this.worker?this.worker.postMessage({type:"mouse",x:t,y:r}):(this.targetMouse[0]=t,this.targetMouse[1]=r)};this.handlePointerLeave=()=>{!this.isPointerInside&&this.targetMouseActive===0||(this.isPointerInside=!1,this.targetMouseActive=0,this.mouseDown=0,this.mouseVel[0]=0,this.mouseVel[1]=0,this.isOffscreen&&this.worker&&this.worker.postMessage({type:"mouseLeave"}))};this.handlePointerDown=e=>{this.isPaused||this.isHiddenByViewport||this.isReducedMotion||(this.isPointerInside||this.handlePointerEnter(e),this.mouseDown=1,this.isOffscreen&&this.worker&&this.worker.postMessage({type:"mouseDown",down:!0}))};this.handlePointerUp=()=>{this.mouseDown!==0&&(this.mouseDown=0,this.isOffscreen&&this.worker&&this.worker.postMessage({type:"mouseDown",down:!1}))};this.handleScroll=()=>{if(!this.trackScroll||this.isDestroyed)return;let e=this.computeScrollProgress();this.isOffscreen&&this.worker?this.worker.postMessage({type:"scroll",progress:e}):(this.targetScroll=e,this.isReducedMotion&&!this.isPaused&&!this.isHiddenByViewport&&(this.scroll=e,this.scrollVel=0,this.drawMainThreadFrame()))};this.handleDocVisibility=()=>{!this.isOffscreen||!this.worker||(document.hidden?this.worker.postMessage({type:"pause"}):!this.isPaused&&!this.isHiddenByViewport&&this.worker.postMessage({type:"resume"}))};this.container=e,this.options={...i},this.interactive=i.interactive??!0,this.respectReducedMotion=i.respectReducedMotion??!0,this.trackScroll=i.trackScroll??!1,this.feedbackScale=i.feedbackScale??.5,this.feedbackFloat=i.feedbackFloat??!0;let t=i.quality??"medium",r=A[t]??A.medium;this.feedbackMaxDim=i.feedbackMaxDim??r.fboMaxDim,typeof window<"u"&&typeof window.matchMedia=="function"&&(this.reducedMotionQuery=window.matchMedia("(prefers-reduced-motion: reduce)"),this.isReducedMotion=this.respectReducedMotion&&this.reducedMotionQuery.matches),window.getComputedStyle(this.container).position==="static"&&(this.container.style.position="relative"),this.container.style.isolation="isolate",this.canvas=document.createElement("canvas"),this.canvas.setAttribute("data-fluxfx-canvas","true"),this.canvas.style.position="absolute",this.canvas.style.inset="0",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.zIndex="-1",this.canvas.style.pointerEvents="none",this.canvas.style.display="block",this.container.prepend(this.canvas);let c=this.container.getBoundingClientRect();if(this.width=Math.max(1,Math.floor(c.width)),this.height=Math.max(1,Math.floor(c.height)),this.trackScroll){let f=this.computeScrollProgress();this.scroll=f,this.targetScroll=f}let{minDpr:a,maxDpr:l}=this.resolveDprBounds(),u=i.dynamicResolution??!0,d=i.offscreen??!0;this.seedUniformsFromOptions(i,!0),d&&H()?this.initOffscreenMode(i,a,l,u):this.initMainThreadMode(i,a,l,u),this.bindObservers(i.pauseWhenHidden??!0)}static get activeContexts(){return this._activeContexts}resolveDprBounds(){let e=this.options.quality??"medium",i=A[e]??A.medium,t=typeof window<"u"&&window.devicePixelRatio||1,r=t>=1.5,s=this.options.maxDpr??Math.min(t,i.max),c=r?i.retinaMin:i.min;return{minDpr:this.options.minDpr??Math.min(c,s),maxDpr:s}}computeScrollProgress(){if(typeof window>"u")return 0;let e=this.container.getBoundingClientRect(),i=window.innerHeight||1,t=i+e.height;return t<=0?0:Math.min(1,Math.max(0,(i-e.top)/t))}markContextActive(){this.countedContext||(this.countedContext=!0,R._activeContexts++,R._activeContexts>ye&&console.warn(`[FluxFX] ${R._activeContexts} active WebGL contexts detected. Browsers typically cap contexts around 8\u201316; consider limiting simultaneous WebGL backgrounds.`))}markContextReleased(){this.countedContext&&(this.countedContext=!1,R._activeContexts=Math.max(0,R._activeContexts-1))}seedUniformsFromOptions(e,i=!1){let t={};if(typeof e.speed=="number"?(this.targetSpeed=e.speed,i&&(this.currentSpeed=e.speed),this.customUniforms.set("uSpeed",e.speed),t.uSpeed=e.speed):this.customUniforms.has("uSpeed")||(this.targetSpeed=1,this.currentSpeed=1,this.customUniforms.set("uSpeed",1),t.uSpeed=1),e.colors&&e.colors.length>0){let r=Array.isArray(e.colors)?e.colors:String(e.colors).split(",").map(a=>a.trim()).filter(Boolean),s=n(r[0],"#ffffff"),c=Math.min(r.length,3);for(let a=0;a<c;a++){let l=n(r[a],s),u=g.hexToVec3Into(l,g.scratchVec3),d=[u[0],u[1],u[2]];this.customUniforms.set(`uColor${a+1}`,d),t[`uColor${a+1}`]=d}if(c===1){let a=this.customUniforms.get("uColor1");this.customUniforms.set("uColor2",[a[0],a[1],a[2]]),t.uColor2=[a[0],a[1],a[2]]}}if(e.uniforms)for(let[r,s]of Object.entries(e.uniforms))this.customUniforms.set(r,s),t[r]=typeof s=="number"?s:Array.from(s);return t}fallbackToMainThread(e,i,t,r){if(this.isDestroyed)return;this.worker&&(this.worker.terminate(),this.worker=null),this.isOffscreen=!1,this.markContextReleased();let s=this.canvas.cloneNode(!1);this.canvas.replaceWith(s),this.canvas=s,this.initMainThreadMode(e,i,t,r)}initOffscreenMode(e,i,t,r){try{let s=z(),c=this.canvas.transferControlToOffscreen();this.worker=s,this.isOffscreen=!0,this.markContextActive(),s.onmessage=l=>{l.data?.type==="error"&&this.fallbackToMainThread(e,i,t,r)},s.onerror=()=>{this.fallbackToMainThread(e,i,t,r)};let a={};this.customUniforms.forEach((l,u)=>{a[u]=typeof l=="number"?l:Array.from(l)}),s.postMessage({type:"init",canvas:c,width:this.width,height:this.height,minDpr:i,maxDpr:t,dynamicRes:r,reducedMotion:this.isReducedMotion,vertexShader:e.vertexShader??G,fragmentShader:e.fragmentShader,feedbackShader:e.feedbackShader??null,feedbackScale:this.feedbackScale,feedbackMaxDim:this.feedbackMaxDim,feedbackFloat:this.feedbackFloat,initialScroll:this.scroll,uniforms:a},[c])}catch{this.isOffscreen=!1,this.markContextReleased(),this.initMainThreadMode(e,i,t,r)}}computeFboDimsMain(e,i){let t=Math.max(1,Math.floor(e*this.feedbackScale)),r=Math.max(1,Math.floor(i*this.feedbackScale)),s=Math.max(t,r);if(s>this.feedbackMaxDim){let c=this.feedbackMaxDim/s;t=Math.max(1,Math.floor(t*c)),r=Math.max(1,Math.floor(r*c))}return[t,r]}destroyPingPongMain(){if(!this.pingPong||!this.gl){this.pingPong=null;return}for(let e=0;e<2;e++)this.gl.deleteFramebuffer(this.pingPong[e].fbo),this.gl.deleteTexture(this.pingPong[e].tex);this.pingPong=null}createPingPongMain(e){if(this.destroyPingPongMain(),!this.options.feedbackShader||this.isContextLost)return;let[i,t]=this.computeFboDimsMain(this.canvas.width,this.canvas.height);this.fboW=i,this.fboH=t;let r=e.RGBA8,s=e.UNSIGNED_BYTE;this.feedbackFloat&&(e.getExtension("EXT_color_buffer_float")||e.getExtension("EXT_color_buffer_half_float"))&&(r=e.RGBA16F,s=e.HALF_FLOAT);let a=(u,d)=>{let f=[];for(let p=0;p<2;p++){let m=e.createTexture(),v=e.createFramebuffer();if(!m||!v)return m&&e.deleteTexture(m),v&&e.deleteFramebuffer(v),f.forEach(y=>{e.deleteFramebuffer(y.fbo),e.deleteTexture(y.tex)}),null;if(e.bindTexture(e.TEXTURE_2D,m),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,u,this.fboW,this.fboH,0,e.RGBA,d,null),e.bindFramebuffer(e.FRAMEBUFFER,v),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,m,0),e.checkFramebufferStatus(e.FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE)return e.deleteFramebuffer(v),e.deleteTexture(m),f.forEach(y=>{e.deleteFramebuffer(y.fbo),e.deleteTexture(y.tex)}),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindTexture(e.TEXTURE_2D,null),null;e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),f.push({fbo:v,tex:m})}return e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindTexture(e.TEXTURE_2D,null),[f[0],f[1]]},l=a(r,s);!l&&r!==e.RGBA8&&(r=e.RGBA8,s=e.UNSIGNED_BYTE,l=a(r,s)),this.fboFormat=r,this.fboType=s,this.pingPong=l,this.readIdx=0,this.writeIdx=1}resizePingPongMain(){if(!this.pingPong||!this.gl||this.isContextLost)return;let[e,i]=this.computeFboDimsMain(this.canvas.width,this.canvas.height);if(e===this.fboW&&i===this.fboH)return;let t=this.gl,r=this.fboW,s=this.fboH,c=this.pingPong[this.readIdx],a=[];for(let l=0;l<2;l++){let u=t.createTexture(),d=t.createFramebuffer();t.bindTexture(t.TEXTURE_2D,u),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texImage2D(t.TEXTURE_2D,0,this.fboFormat,e,i,0,t.RGBA,this.fboType,null),t.bindFramebuffer(t.FRAMEBUFFER,d),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,u,0),a.push({fbo:d,tex:u})}t.bindFramebuffer(t.READ_FRAMEBUFFER,c.fbo),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,a[0].fbo),t.blitFramebuffer(0,0,r,s,0,0,e,i,t.COLOR_BUFFER_BIT,t.LINEAR),t.bindFramebuffer(t.READ_FRAMEBUFFER,null),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),t.bindTexture(t.TEXTURE_2D,null);for(let l=0;l<2;l++)t.deleteFramebuffer(this.pingPong[l].fbo),t.deleteTexture(this.pingPong[l].tex);this.pingPong=[a[0],a[1]],this.fboW=e,this.fboH=i,this.readIdx=0,this.writeIdx=1}initMainThreadPipeline(e){let i=this.options.vertexShader??S;this.programEntry=h.getOrCreateProgram(e,this.options.fragmentShader,i),this.options.feedbackShader?this.feedbackProgramEntry=h.getOrCreateProgram(e,this.options.feedbackShader,i):this.feedbackProgramEntry=null,this.vao=e.createVertexArray(),e.bindVertexArray(this.vao),this.vbo=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.vbo),e.bufferData(e.ARRAY_BUFFER,be,e.STATIC_DRAW),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0),e.bindVertexArray(null),this.needsResize=!1,this.applyCanvasSize(),this.options.feedbackShader&&this.createPingPongMain(e)}initMainThreadMode(e,i,t,r){let s=this.canvas.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance",preserveDrawingBuffer:!1});if(!s){console.warn("[FluxFX] WebGL2 is not supported on this device.");return}this.gl=s,this.markContextActive(),this.canvas.addEventListener("webglcontextlost",this.handleContextLost,!1),this.canvas.addEventListener("webglcontextrestored",this.handleContextRestored,!1),this.dynamicRes=new D({minScale:r?i:t,maxScale:t}),this.initMainThreadPipeline(s),this.drawMainThreadFrame()}applyCanvasSize(){if(!this.gl||!this.dynamicRes||this.isContextLost)return;let e=this.dynamicRes.scale,i=Math.max(1,Math.round(this.width*e)),t=Math.max(1,Math.round(this.height*e));(this.canvas.width!==i||this.canvas.height!==t)&&(this.canvas.width=i,this.canvas.height=t,this.gl.viewport(0,0,i,t),this.pingPong&&this.resizePingPongMain())}bindCommonUniformsMain(e,i,t,r){let s=h.getUniformLocation(e,i,"uTime");s&&e.uniform1f(s,this.elapsedSec);let c=h.getUniformLocation(e,i,"uDelta");c&&e.uniform1f(c,this.lastDeltaSec);let a=h.getUniformLocation(e,i,"uResolution");a&&e.uniform2f(a,t,r);let l=h.getUniformLocation(e,i,"uCanvasResolution");l&&e.uniform2f(l,this.canvas.width,this.canvas.height);let u=h.getUniformLocation(e,i,"uDpr");u&&this.dynamicRes&&e.uniform1f(u,this.dynamicRes.scale);let d=h.getUniformLocation(e,i,"uMouse");d&&e.uniform2f(d,this.mouse[0],this.mouse[1]);let f=h.getUniformLocation(e,i,"uMouseVel");f&&e.uniform2f(f,this.mouseVel[0],this.mouseVel[1]);let p=h.getUniformLocation(e,i,"uMouseDown");p&&e.uniform1f(p,this.mouseDown);let m=h.getUniformLocation(e,i,"uMouseActive");m&&e.uniform1f(m,this.mouseActive);let v=h.getUniformLocation(e,i,"uScroll");v&&e.uniform1f(v,this.scroll);let y=h.getUniformLocation(e,i,"uScrollVel");y&&e.uniform1f(y,this.scrollVel),this.customUniforms.forEach((b,L)=>{let M=h.getUniformLocation(e,i,L);M&&(L==="uSpeed"?e.uniform1f(M,this.currentSpeed):typeof b=="number"?e.uniform1f(M,b):b.length===2?e.uniform2f(M,b[0],b[1]):b.length===3?e.uniform3f(M,b[0],b[1],b[2]):b.length===4&&e.uniform4f(M,b[0],b[1],b[2],b[3]))})}drawMainThreadFrame(){if(!this.gl||!this.programEntry||this.isContextLost)return;let e=this.gl;if(e.bindVertexArray(this.vao),this.feedbackProgramEntry&&this.pingPong){e.bindFramebuffer(e.FRAMEBUFFER,this.pingPong[this.writeIdx].fbo),e.viewport(0,0,this.fboW,this.fboH),e.useProgram(this.feedbackProgramEntry.program),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.pingPong[this.readIdx].tex);let i=h.getUniformLocation(e,this.feedbackProgramEntry,"uPrevFrame");i&&e.uniform1i(i,0),this.bindCommonUniformsMain(e,this.feedbackProgramEntry,this.fboW,this.fboH),e.drawArrays(e.TRIANGLES,0,3);let t=this.readIdx;this.readIdx=this.writeIdx,this.writeIdx=t,e.bindFramebuffer(e.FRAMEBUFFER,null),e.viewport(0,0,this.canvas.width,this.canvas.height)}if(e.useProgram(this.programEntry.program),this.pingPong){e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.pingPong[this.readIdx].tex);let i=h.getUniformLocation(e,this.programEntry,"uFeedback");i&&e.uniform1i(i,0);let t=h.getUniformLocation(e,this.programEntry,"uPrevFrame");t&&e.uniform1i(t,0)}this.bindCommonUniformsMain(e,this.programEntry,this.canvas.width,this.canvas.height),e.drawArrays(e.TRIANGLES,0,3)}render(e,i){if(this.isOffscreen||this.isPaused||this.isHiddenByViewport||this.isReducedMotion||this.isContextLost||this.isDestroyed||!this.gl||!this.programEntry)return;let t=performance.now(),r=this.lastRenderNow?t-this.lastRenderNow:16.67;this.lastRenderNow=t;let s=Math.max(.001,Math.min(r*.001,.05));this.lastDeltaSec=s,this.currentSpeed+=(this.targetSpeed-this.currentSpeed)*C(7.5,s),this.elapsedSec+=s*this.currentSpeed;let c=!1;if(this.needsResize&&(this.needsResize=!1,c=!0),this.dynamicRes&&this.dynamicRes.recordFrame(r,t)&&(c=!0),c&&this.applyCanvasSize(),this.mouseActive+=(this.targetMouseActive-this.mouseActive)*C(7,s),this.mouseActive<.001&&this.targetMouseActive===0&&(this.mouseActive=0),this.targetMouseActive>.5){let a=this.mouse[0],l=this.mouse[1],u=C(13,s);this.mouse[0]+=(this.targetMouse[0]-this.mouse[0])*u,this.mouse[1]+=(this.targetMouse[1]-this.mouse[1])*u,this.mouseVel[0]=Math.max(-8,Math.min(8,(this.mouse[0]-a)/s)),this.mouseVel[1]=Math.max(-8,Math.min(8,(this.mouse[1]-l)/s))}else this.mouseVel[0]=0,this.mouseVel[1]=0;if(this.trackScroll){let a=this.scroll;this.scroll+=(this.targetScroll-this.scroll)*C(9.5,s),this.scrollVel=Math.max(-6,Math.min(6,(this.scroll-a)/s))}this.drawMainThreadFrame()}syncDprBounds(){let{minDpr:e,maxDpr:i}=this.resolveDprBounds(),r=this.options.dynamicResolution??!0?e:i;this.isOffscreen&&this.worker?this.worker.postMessage({type:"dprBounds",minDpr:r,maxDpr:i}):this.dynamicRes&&this.dynamicRes.setBounds(r,i)&&(this.isReducedMotion&&!this.isPaused&&!this.isHiddenByViewport?(this.needsResize=!1,this.applyCanvasSize(),this.drawMainThreadFrame()):this.needsResize=!0)}watchDevicePixelRatio(){if(this.dprMediaQuery&&(this.dprMediaQuery.removeEventListener("change",this.handleDprChange),this.dprMediaQuery=null),typeof window>"u"||typeof window.matchMedia!="function")return;let e=window.devicePixelRatio||1;this.dprMediaQuery=window.matchMedia(`(resolution: ${e}dppx)`),this.dprMediaQuery.addEventListener("change",this.handleDprChange)}updateOptions(e){if(this.isDestroyed)return;let i=this.options.quality;this.options={...this.options,...e};let t=this.seedUniformsFromOptions(e,!1);if((e.quality!==void 0&&e.quality!==i||e.minDpr!==void 0||e.maxDpr!==void 0||e.dynamicResolution!==void 0)&&this.syncDprBounds(),typeof e.interactive=="boolean"&&e.interactive!==this.interactive&&(this.interactive=e.interactive,this.syncPointerListener()),typeof e.trackScroll=="boolean"&&e.trackScroll!==this.trackScroll&&(this.trackScroll=e.trackScroll,this.syncScrollListener()),typeof e.respectReducedMotion=="boolean"){this.respectReducedMotion=e.respectReducedMotion;let r=this.reducedMotionQuery?.matches??!1;this.applyReducedMotionState(this.respectReducedMotion&&r)}this.isOffscreen&&this.worker?Object.keys(t).length>0&&this.worker.postMessage({type:"uniformsBatch",uniforms:t}):this.isReducedMotion&&(this.needsResize&&(this.needsResize=!1,this.applyCanvasSize()),this.drawMainThreadFrame())}applyReducedMotionState(e){this.isReducedMotion!==e&&(this.isReducedMotion=e,this.lastRenderNow=0,this.isOffscreen&&this.worker?this.worker.postMessage({type:"reducedMotion",value:e}):e&&(this.needsResize&&(this.needsResize=!1,this.applyCanvasSize()),this.drawMainThreadFrame()))}getLocalPointerCoords(e){let i=this.container.getBoundingClientRect();if(i.width<=0||i.height<=0||e.clientX<i.left||e.clientX>i.right||e.clientY<i.top||e.clientY>i.bottom)return null;let t=(e.clientX-i.left)/i.width,r=1-(e.clientY-i.top)/i.height;return[t,r]}syncPointerListener(){this.interactive&&!this.hasPointerListener?(this.container.addEventListener("pointerenter",this.handlePointerEnter,{passive:!0}),this.container.addEventListener("pointermove",this.handlePointerMove,{passive:!0}),this.container.addEventListener("pointerleave",this.handlePointerLeave,{passive:!0}),this.container.addEventListener("pointerdown",this.handlePointerDown,{passive:!0}),window.addEventListener("pointerup",this.handlePointerUp,{passive:!0}),window.addEventListener("pointercancel",this.handlePointerUp,{passive:!0}),this.hasPointerListener=!0):!this.interactive&&this.hasPointerListener&&(this.container.removeEventListener("pointerenter",this.handlePointerEnter),this.container.removeEventListener("pointermove",this.handlePointerMove),this.container.removeEventListener("pointerleave",this.handlePointerLeave),this.container.removeEventListener("pointerdown",this.handlePointerDown),window.removeEventListener("pointerup",this.handlePointerUp),window.removeEventListener("pointercancel",this.handlePointerUp),this.handlePointerLeave(),this.hasPointerListener=!1)}syncScrollListener(){this.trackScroll&&!this.hasScrollListener?(window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.hasScrollListener=!0,this.handleScroll()):!this.trackScroll&&this.hasScrollListener&&(window.removeEventListener("scroll",this.handleScroll),this.hasScrollListener=!1)}bindObservers(e){typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(i=>{let t=i[0];if(!t)return;let r=Math.max(1,Math.floor(t.contentRect.width)),s=Math.max(1,Math.floor(t.contentRect.height));r===this.width&&s===this.height||(this.width=r,this.height=s,this.trackScroll&&this.handleScroll(),this.isOffscreen&&this.worker?this.worker.postMessage({type:"resize",width:this.width,height:this.height}):this.isReducedMotion&&!this.isPaused&&!this.isHiddenByViewport?(this.needsResize=!1,this.applyCanvasSize(),this.drawMainThreadFrame()):this.needsResize=!0)}),this.resizeObserver.observe(this.container)),e&&typeof IntersectionObserver<"u"&&(this.visibilityObserver=new IntersectionObserver(i=>{let t=i[0]?.isIntersecting??!0;this.isHiddenByViewport=!t,t||this.handlePointerLeave(),this.isOffscreen&&this.worker?this.worker.postMessage({type:t&&!this.isPaused?"resume":"pause"}):t||(this.lastRenderNow=0)},{rootMargin:"50px"}),this.visibilityObserver.observe(this.container)),this.reducedMotionQuery&&this.reducedMotionQuery.addEventListener("change",this.handleReducedMotionChange),this.isOffscreen&&typeof document<"u"&&document.addEventListener("visibilitychange",this.handleDocVisibility),this.watchDevicePixelRatio(),this.syncPointerListener(),this.syncScrollListener()}setUniform(e,i){this.isDestroyed||(this.customUniforms.set(e,i),e==="uSpeed"&&typeof i=="number"&&(this.targetSpeed=i),this.isOffscreen&&this.worker?this.worker.postMessage({type:"uniform",name:e,value:typeof i=="number"?i:Array.from(i)}):this.isReducedMotion&&this.drawMainThreadFrame())}setColor(e,i){let t=n(i,"#ffffff"),r=g.hexToVec3Into(t,g.scratchVec3);this.setUniform(e,[r[0],r[1],r[2]])}pause(){this.isPaused||this.isDestroyed||(this.isPaused=!0,this.lastRenderNow=0,this.handlePointerLeave(),this.isOffscreen&&this.worker&&this.worker.postMessage({type:"pause"}))}resume(){!this.isPaused||this.isDestroyed||(this.isPaused=!1,this.lastRenderNow=0,this.isOffscreen&&this.worker&&!this.isHiddenByViewport?this.worker.postMessage({type:"resume"}):this.isReducedMotion&&!this.isHiddenByViewport&&(this.needsResize&&(this.needsResize=!1,this.applyCanvasSize()),this.drawMainThreadFrame()))}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.resizeObserver?.disconnect(),this.resizeObserver=null,this.visibilityObserver?.disconnect(),this.visibilityObserver=null,this.reducedMotionQuery&&(this.reducedMotionQuery.removeEventListener("change",this.handleReducedMotionChange),this.reducedMotionQuery=null),this.dprMediaQuery&&(this.dprMediaQuery.removeEventListener("change",this.handleDprChange),this.dprMediaQuery=null),typeof document<"u"&&document.removeEventListener("visibilitychange",this.handleDocVisibility),this.hasPointerListener&&(this.container.removeEventListener("pointerenter",this.handlePointerEnter),this.container.removeEventListener("pointermove",this.handlePointerMove),this.container.removeEventListener("pointerleave",this.handlePointerLeave),this.container.removeEventListener("pointerdown",this.handlePointerDown),window.removeEventListener("pointerup",this.handlePointerUp),window.removeEventListener("pointercancel",this.handlePointerUp),this.hasPointerListener=!1),this.hasScrollListener&&(window.removeEventListener("scroll",this.handleScroll),this.hasScrollListener=!1),this.canvas.removeEventListener("webglcontextlost",this.handleContextLost,!1),this.canvas.removeEventListener("webglcontextrestored",this.handleContextRestored,!1),this.isOffscreen&&this.worker&&(this.worker.postMessage({type:"destroy"}),this.worker=null),this.gl&&(this.destroyPingPongMain(),this.vbo&&this.gl.deleteBuffer(this.vbo),this.vao&&this.gl.deleteVertexArray(this.vao),h.disposeContext(this.gl),this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null),this.markContextReleased(),g.releaseVec2(this.mouse),g.releaseVec2(this.targetMouse),g.releaseVec2(this.mouseVel),this.customUniforms.clear(),this.canvas.remove())}};R._activeContexts=0;var x=R;var T=class{constructor(){this.plugins=new Map;this.activeByElement=new WeakMap;this.activeSet=new Set;this.visibilityObserver=null;this.visibilityCallbacks=new WeakMap;this.removeTicker=null}ensureObserver(){return typeof window>"u"||typeof IntersectionObserver>"u"?null:(this.visibilityObserver||(this.visibilityObserver=new IntersectionObserver(e=>{for(let i=0;i<e.length;i++){let t=e[i],r=this.visibilityCallbacks.get(t.target);r&&r.forEach(s=>s(t.isIntersecting))}},{rootMargin:"50px"})),this.visibilityObserver)}ensureTicker(){this.removeTicker||(this.removeTicker=V.add((e,i)=>{this.activeSet.forEach(t=>{if(!(!t.visible||t.faulted||!t.instance.update))try{t.instance.update(e,i)}catch(r){t.faulted=!0,console.error(`[FluxFX] Runtime error in "${t.name}" (auto-paused):`,r)}})}))}stopTickerIfEmpty(){this.activeSet.size===0&&this.removeTicker&&(this.removeTicker(),this.removeTicker=null)}register(e){return this.plugins.set(e.name,e),this}has(e){return this.plugins.has(e)}getStats(){let e=0;this.activeSet.forEach(t=>{t.visible&&e++});let i=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;return{mounted:this.activeSet.size,visible:e,activeLoops:V.isRunning?1:0,registered:this.plugins.size,webglContexts:x.activeContexts,reducedMotion:i}}apply(e,i,t={}){let r=this.plugins.get(i);if(!r)return console.warn(`[FluxFX] Effect "${i}" is not registered.`),()=>{};let s=this.activeByElement.get(e);s||(s=new Map,this.activeByElement.set(e,s));let c=s.get(i);c&&c.destroy();let a;try{a=r.mount(e,t)}catch(p){return console.error(`[FluxFX] Failed to mount "${i}":`,p),()=>{}}let l=t.pauseWhenHidden??!0,u=null,d=!1,f={el:e,name:i,plugin:r,instance:a,visible:!0,faulted:!1,destroy:()=>{if(!d){d=!0,u?.(),this.activeSet.delete(f),s?.delete(i);try{f.instance.destroy()}catch(p){console.error(`[FluxFX] Cleanup error in "${i}":`,p)}this.stopTickerIfEmpty()}}};if(l){let p=this.ensureObserver();if(p){let m=this.visibilityCallbacks.get(e);m||(m=new Set,this.visibilityCallbacks.set(e,m),p.observe(e));let v=y=>{f.visible=y,y?f.instance.resume?.():f.instance.pause?.()};m.add(v),u=()=>{m?.delete(v),m&&m.size===0&&(p.unobserve(e),this.visibilityCallbacks.delete(e))}}}return s.set(i,f),this.activeSet.add(f),f.instance.update&&this.ensureTicker(),f.destroy}update(e,i,t={}){let s=this.activeByElement.get(e)?.get(i);if(!s)return!1;if(s.instance.setOptions)try{return s.instance.setOptions(t),!0}catch(c){return console.error(`[FluxFX] Hot-update error in "${i}":`,c),!1}try{return s.instance.destroy(),s.instance=s.plugin.mount(e,t),s.faulted=!1,s.visible||s.instance.pause?.(),s.instance.update&&this.ensureTicker(),!0}catch(c){return s.faulted=!0,console.error(`[FluxFX] Fallback remount error in "${i}":`,c),!1}}scan(e=document){if(typeof document>"u")return;e.querySelectorAll("[data-fx]").forEach(t=>{let r=t.getAttribute("data-fx");if(!r)return;let s=r.trim().split(/\s+/).filter(Boolean),c=this.parseDatasetOptions(t),a=this.activeByElement.get(t);s.forEach(l=>{a?.has(l)||this.apply(t,l,c)})})}init(e){typeof document>"u"||(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.scan(e??document),{once:!0}):this.scan(e??document))}destroyAll(){let e=Array.from(this.activeSet);for(let i=0;i<e.length;i++)e[i].destroy()}parseDatasetOptions(e){let i={};for(let[t,r]of Object.entries(e.dataset)){if(!t.startsWith("fx")||t==="fx"||r===void 0)continue;let s=t.slice(2),c=s.charAt(0).toLowerCase()+s.slice(1);r==="true"?i[c]=!0:r==="false"?i[c]=!1:r!==""&&!Number.isNaN(Number(r))?i[c]=Number(r):i[c]=r}return i}},k=new T;var xe=`#version 300 es
790
+ `,ie=null;function re(){if(typeof window>"u"||typeof Worker>"u"||typeof OffscreenCanvas>"u"||typeof HTMLCanvasElement>"u"||!("transferControlToOffscreen"in HTMLCanvasElement.prototype))return!1;let o=typeof navigator<"u"?navigator.userAgent:"";return!(/iP(ad|hone|od)/i.test(o)||/^((?!chrome|android).)*safari/i.test(o))}function ge(){if(!ie){let o=new Blob([Ie],{type:"application/javascript"});ie=URL.createObjectURL(o)}return new Worker(ie)}var be=z;var O={low:{max:1,min:.65,retinaMin:.85,fboMaxDim:512},medium:{max:2,min:.75,retinaMin:1,fboMaxDim:896},high:{max:2,min:1,retinaMin:1.25,fboMaxDim:1152}},Ve=new Float32Array([-1,-1,3,-1,-1,3]),Oe=12;function Te(){if(typeof navigator>"u")return!1;let o=navigator.userAgent||"";return/Safari/i.test(o)&&!/Chrome|Chromium|Edg|CriOS|FxiOS|OPR/i.test(o)}function ye(){if(typeof navigator>"u")return 8;let o=navigator.userAgent||"",e=/Mobi|Android|iPhone|iPad|iPod/i.test(o);return Te()||e?6:8}function X(){return typeof performance<"u"?performance.now():Date.now()}var se=30,oe=60,H=1800;function Y(o,e){return 1-Math.exp(-o*e)}var C=class C{constructor(e,t){this.resizeObserver=null;this.visibilityObserver=null;this.reducedMotionQuery=null;this.dprMediaQuery=null;this.worker=null;this.isOffscreen=!1;this.gl=null;this.programEntry=null;this.feedbackProgramEntry=null;this.vao=null;this.vbo=null;this.dynamicRes=null;this.lastRenderNow=0;this.lastDrawNow=0;this.lastTargetFps=0;this.prevFrameDrew=!1;this.avgDrawDeltaMs=0;this.boostUntil=0;this.reportedFps=0;this.reportedFrameTimeMs=0;this.elapsedSec=0;this.lastDeltaSec=.01667;this.currentSpeed=1;this.targetSpeed=1;this.needsResize=!1;this.pingPong=null;this.fboW=1;this.fboH=1;this.fboFormat=0;this.fboType=0;this.readIdx=0;this.writeIdx=1;this.customUniforms=new Map;this.mouse=y.acquireVec2(.5,.5);this.targetMouse=y.acquireVec2(.5,.5);this.mouseVel=y.acquireVec2(0,0);this.mouseDown=0;this.mouseActive=0;this.targetMouseActive=0;this.isPointerInside=!1;this.scroll=0;this.targetScroll=0;this.scrollVel=0;this.hasScrollListener=!1;this.width=1;this.height=1;this.isPaused=!1;this.isHiddenByViewport=!1;this.isContextLost=!1;this.isReducedMotion=!1;this.isDestroyed=!1;this.wakeCallback=null;this.ambientFps=se;this.activeFps=oe;this.protectionTier=P.tier;this.isSurvivalSuspended=!1;this.unsubscribeGuard=null;this.isBudgetSuspended=!1;this.lastActiveAt=X();this.hasDocVisibilityListener=!1;this.hasPointerListener=!1;this.countedContext=!1;this.isBodyMount=!1;this.origBodyMinHeight="";this.themeMode="auto";this.resolvedDarkTheme=!0;this.currentTheme=1;this.themeTweenRaf=0;this.colorSchemeQuery=null;this.themeMutationObserver=null;this.basePaletteRgb=[];this.activePaletteRgb=[];this.scrollStopsRgb=[];this.lastScrollColorT=-1;this.hasScrollColorListener=!1;this.scrollColorRaf=0;this.hasTouchListener=!1;this.touchBurstTimer=0;this.touchLeaveTimer=0;this.layerMode="background";this.adaptToSurface=!1;this.rawBasePaletteRgb=[];this.lastSurfaceEl=null;this.lastSurfaceKey="";this.lastSurfaceCheckAt=0;this.isSurfaceAdapted=!1;this.handleThemeChange=()=>{if(this.isDestroyed)return;let e=this.detectDarkTheme(this.themeMode);e!==this.resolvedDarkTheme&&(this.resolvedDarkTheme=e,this.startThemeTransition(e))};this.handleScrollColorEvent=()=>{this.isDestroyed||this.scrollStopsRgb.length<2||this.scrollColorRaf||(this.scrollColorRaf=requestAnimationFrame(()=>{if(this.scrollColorRaf=0,this.isDestroyed||this.scrollStopsRgb.length<2)return;let e=this.computeScrollProgress();this.updateScrollColorShift(e)}))};this.handleTouchStart=e=>{if(!this.interactive||this.isPaused||this.isHiddenByViewport||this.isReducedMotion)return;let t=e.touches[0];if(!t)return;if(this.isShadowedByChildInteractive(t.target)){this.isPointerInside&&this.handlePointerLeave();return}let i=this.getLocalTouchCoords(t);if(!i)return;this.touchLeaveTimer&&(window.clearTimeout(this.touchLeaveTimer),this.touchLeaveTimer=0),this.touchBurstTimer&&(window.clearTimeout(this.touchBurstTimer),this.touchBurstTimer=0);let[r,s]=i;this.inspectSurfaceFromTarget(t.target,!0),this.isPointerInside=!0,this.targetMouseActive=1,this.mouseDown=1,this.boostInteraction(H),this.isOffscreen&&this.worker?(this.worker.postMessage({type:"mouseEnter",x:r,y:s}),this.worker.postMessage({type:"mouseDown",down:!0})):(this.mouse[0]=r,this.mouse[1]=s,this.targetMouse[0]=r,this.targetMouse[1]=s,this.mouseVel[0]=0,this.mouseVel[1]=0),this.touchBurstTimer=window.setTimeout(()=>{this.touchBurstTimer=0,!this.isDestroyed&&(this.mouseDown=0,this.isOffscreen&&this.worker&&this.worker.postMessage({type:"mouseDown",down:!1}))},160)};this.handleTouchMove=e=>{if(!this.interactive||this.isPaused||this.isHiddenByViewport||this.isReducedMotion)return;let t=e.touches[0];if(!t)return;if(this.isShadowedByChildInteractive(t.target)){this.isPointerInside&&this.handlePointerLeave();return}let i=this.getLocalTouchCoords(t);if(!i)return;let[r,s]=i;this.inspectSurfaceFromTarget(t.target),this.boostInteraction(H),this.targetMouseActive=1,this.isOffscreen&&this.worker?this.worker.postMessage({type:"mouse",x:r,y:s}):(this.targetMouse[0]=r,this.targetMouse[1]=s)};this.handleTouchEnd=()=>{this.isDestroyed||(this.mouseDown=0,this.isOffscreen&&this.worker&&this.worker.postMessage({type:"mouseDown",down:!1}),this.touchLeaveTimer&&window.clearTimeout(this.touchLeaveTimer),this.touchLeaveTimer=window.setTimeout(()=>{this.touchLeaveTimer=0,this.isDestroyed||this.handlePointerLeave()},550))};this.handleContextLost=e=>{e.preventDefault(),this.isContextLost=!0,this.resetFrameTracking(),this.gl&&T.disposeContext(this.gl),this.programEntry=null,this.feedbackProgramEntry=null,this.pingPong=null,this.vao=null,this.vbo=null,this.wakeCallback?.()};this.handleContextRestored=()=>{if(!(this.isDestroyed||!this.gl))try{this.isContextLost=!1,this.initMainThreadPipeline(this.gl),this.drawMainThreadFrame(),this.wakeCallback?.()}catch(e){console.error("[FluxFX] Failed to restore WebGL2 context:",e)}};this.handleProtectionTierChange=e=>{this.isDestroyed||this.protectionTier===e||(this.protectionTier=e,this.applyProtectionState(),this.isDestroyed||this.pushUniformBatch({uQuality:this.computeEffectiveQuality()}))};this.handleDprChange=()=>{this.isDestroyed||(this.syncDprBounds(),this.watchDevicePixelRatio())};this.handleReducedMotionChange=e=>{this.applyReducedMotionState(this.respectReducedMotion&&e.matches)};this.handlePointerEnter=e=>{if(this.isPaused||this.isHiddenByViewport||this.isReducedMotion)return;if(this.isShadowedByChildInteractive(e.target)){this.isPointerInside&&this.handlePointerLeave();return}let t=this.getLocalPointerCoords(e);if(!t)return;let[i,r]=t;this.isPointerInside=!0,this.targetMouseActive=1,this.boostInteraction(H),this.protectionTier>=3&&this.applyProtectionState(),this.lastActiveAt=X(),this.isBudgetSuspended&&!this.isPaused&&this.restoreContextFromBudget(),this.isOffscreen&&this.worker?this.worker.postMessage({type:"mouseEnter",x:i,y:r}):(this.mouse[0]=i,this.mouse[1]=r,this.targetMouse[0]=i,this.targetMouse[1]=r,this.mouseVel[0]=0,this.mouseVel[1]=0)};this.handlePointerMove=e=>{if(this.isPaused||this.isHiddenByViewport||this.isReducedMotion)return;if(this.isShadowedByChildInteractive(e.target)){this.isPointerInside&&this.handlePointerLeave();return}let t=this.getLocalPointerCoords(e);if(!t){this.isPointerInside&&this.handlePointerLeave();return}let[i,r]=t;if(!this.isPointerInside){this.handlePointerEnter(e),this.inspectSurfaceFromTarget(e.target,!0);return}this.inspectSurfaceFromTarget(e.target),this.boostInteraction(H),this.isOffscreen&&this.worker?this.worker.postMessage({type:"mouse",x:i,y:r}):(this.targetMouse[0]=i,this.targetMouse[1]=r)};this.handlePointerLeave=()=>{!this.isPointerInside&&this.targetMouseActive===0||(this.isPointerInside=!1,this.targetMouseActive=0,this.lastSurfaceEl=null,this.lastSurfaceKey="",this.isSurfaceAdapted&&(this.isSurfaceAdapted=!1,this.startPaletteTween(this.basePaletteRgb,240)),this.mouseDown=0,this.mouseVel[0]=0,this.mouseVel[1]=0,this.isOffscreen&&this.worker&&this.worker.postMessage({type:"mouseLeave"}),this.protectionTier>=3&&this.applyProtectionState())};this.handlePointerDown=e=>{if(!(this.isPaused||this.isHiddenByViewport||this.isReducedMotion)){if(this.isShadowedByChildInteractive(e.target)){this.isPointerInside&&this.handlePointerLeave();return}this.isPointerInside||this.handlePointerEnter(e),this.mouseDown=1,this.boostInteraction(H),this.protectionTier>=3&&this.applyProtectionState(),this.isOffscreen&&this.worker&&this.worker.postMessage({type:"mouseDown",down:!0})}};this.handlePointerUp=()=>{this.mouseDown!==0&&(this.mouseDown=0,this.isOffscreen&&this.worker&&this.worker.postMessage({type:"mouseDown",down:!1}),this.protectionTier>=3&&this.applyProtectionState())};this.handleScroll=()=>{if(!this.trackScroll||this.isDestroyed)return;let e=this.computeScrollProgress();this.boostInteraction(1200),this.isOffscreen&&this.worker?this.worker.postMessage({type:"scroll",progress:e}):(this.targetScroll=e,this.isReducedMotion&&!this.isPaused&&!this.isHiddenByViewport&&(this.scroll=e,this.scrollVel=0,this.drawMainThreadFrame()))};this.handleDocVisibility=()=>{!this.isOffscreen||!this.worker||(document.hidden?(this.resetFrameTracking(),this.worker.postMessage({type:"pause"})):!this.isPaused&&!this.isHiddenByViewport&&this.worker.postMessage({type:"resume"}))};this.container=e,this.options={...t},this.interactive=t.interactive??!0,this.respectReducedMotion=t.respectReducedMotion??!0,this.trackScroll=t.trackScroll??!1,this.feedbackScale=t.feedbackScale??.5,this.feedbackFloat=t.feedbackFloat??!0,C.instances.add(this);let i=t.quality??"medium",r=O[i]??O.medium;this.baseFeedbackMaxDim=t.feedbackMaxDim??r.fboMaxDim;let s=this.resolveTierConfig();this.ambientFps=s.ambientFps,this.activeFps=s.activeFps,this.feedbackMaxDim=s.feedbackMaxDim,this.isSurvivalSuspended=s.suspended,typeof window<"u"&&typeof window.matchMedia=="function"&&(this.reducedMotionQuery=window.matchMedia("(prefers-reduced-motion: reduce)"),this.isReducedMotion=this.respectReducedMotion&&this.reducedMotionQuery.matches),this.isBodyMount=typeof document<"u"&&this.container===document.body,window.getComputedStyle(this.container).position==="static"&&(this.container.style.position="relative"),this.container.style.isolation="isolate",this.isBodyMount&&(this.origBodyMinHeight=this.container.style.minHeight,this.container.style.minHeight||(this.container.style.minHeight="100dvh")),this.canvas=document.createElement("canvas"),this.canvas.setAttribute("data-fluxfx-canvas","true"),this.canvas.style.position=this.isBodyMount?"fixed":"absolute",this.canvas.style.inset="0",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.zIndex="-1",this.canvas.style.pointerEvents="none",this.canvas.style.display="block",this.container.prepend(this.canvas),this.layerMode=t.layer??"background",this.adaptToSurface=t.adaptToSurface??!1,this.applyCanvasLayerStyle(),this.themeMode=t.theme??"auto",this.resolvedDarkTheme=this.detectDarkTheme(this.themeMode),this.currentTheme=this.resolvedDarkTheme?1:0;let n=this.container.getBoundingClientRect();if(this.width=Math.max(1,Math.floor(n.width)),this.height=Math.max(1,Math.floor(n.height)),this.trackScroll){let p=this.computeScrollProgress();this.scroll=p,this.targetScroll=p}let{minDpr:l,maxDpr:c}=this.resolveDprBounds(),u=t.dynamicResolution??!0,h=t.offscreen??!0;this.seedUniformsFromOptions(t,!0);let f=typeof window<"u"&&window.innerHeight||0,d=typeof window<"u"&&window.innerWidth||0,m=(t.pauseWhenHidden??!0)&&f>0&&(n.bottom<-50||n.top>f+50||n.right<-50||n.left>d+50);m&&(this.isHiddenByViewport=!0),C.ensureContextBudget(this,m)?h&&re()?this.initOffscreenMode(t,l,c,u):this.initMainThreadMode(t,l,c,u):(this.isBudgetSuspended=!0,this.applyBudgetFallbackStyle()),this.bindObservers(t.pauseWhenHidden??!0),this.unsubscribeGuard=P.onTierChange(this.handleProtectionTierChange)}static acquireRecycledMainContext(){for(;this.recycledMainContexts.length>0;){let e=this.recycledMainContexts.pop();if(!e.gl.isContextLost())return e}return null}static recycleMainContext(e,t){let i=Math.max(this._maxContexts,ye());return this.recycledMainContexts.length>=i?!1:(this.recycledMainContexts.push({canvas:e,gl:t}),!0)}static get activeContexts(){return this._activeContexts}static get maxActiveContexts(){return this._maxContexts}static get suspendedContexts(){let e=0;return this.instances.forEach(t=>{!t.isDestroyed&&t.isBudgetSuspended&&e++}),e}static setMaxActiveContexts(e){let t=Math.max(1,Math.floor(e));t!==this._maxContexts&&(this._maxContexts=t,this.enforceContextBudget(),this.reclaimBudgetForWaiting())}static pickEvictionVictim(e,t){let i=null,r=null;return this.instances.forEach(s=>{s===e||s.isDestroyed||s.isBudgetSuspended||!s.countedContext||(s.isHiddenByViewport||s.isPaused?(!i||s.lastActiveAt<i.lastActiveAt)&&(i=s):t&&!s.isPointerInside&&s.mouseDown===0&&(!r||s.lastActiveAt<r.lastActiveAt)&&(r=s))}),i??r}static ensureContextBudget(e,t){if(this._activeContexts<this._maxContexts)return!0;if(t)return!1;let i=this.pickEvictionVictim(e,!0);return i?(i.suspendContextForBudget(),this._activeContexts<this._maxContexts):!1}static enforceContextBudget(){for(;this._activeContexts>this._maxContexts;){let e=this.pickEvictionVictim(null,!0);if(!e)break;e.suspendContextForBudget()}}static reclaimBudgetForWaiting(){for(;this._activeContexts<this._maxContexts;){let e=null;if(this.instances.forEach(t=>{t.isDestroyed||!t.isBudgetSuspended||t.isPaused||t.isHiddenByViewport||(!e||t.lastActiveAt>e.lastActiveAt)&&(e=t)}),!e||!e.restoreContextFromBudget())break}}static getRenderStats(){let e=0,t=0,i=0;return this.instances.forEach(r=>{r.isDestroyed||r.isPaused||r.isHiddenByViewport||r.isReducedMotion||r.isContextLost||r.isSurvivalSuspended||r.reportedFps>0&&(e++,r.reportedFps>t&&(t=r.reportedFps,i=r.reportedFrameTimeMs))}),{activeRendering:e,fps:t,frameTimeMs:i}}boostInteraction(e=H){let t=performance.now()+e;t>this.boostUntil&&(this.boostUntil=t)}resetFrameTracking(){this.lastRenderNow=0,this.lastDrawNow=0,this.lastTargetFps=0,this.prevFrameDrew=!1,this.avgDrawDeltaMs=0,this.reportedFps=0,this.reportedFrameTimeMs=0}resolveTierConfig(){let e=this.baseFeedbackMaxDim;return this.protectionTier===1?{ambientFps:se,activeFps:oe,feedbackMaxDim:Math.max(256,Math.round(e*.75)),suspended:!1}:this.protectionTier===2?{ambientFps:20,activeFps:30,feedbackMaxDim:Math.max(256,Math.round(e*.55)),suspended:!1}:this.protectionTier>=3?{ambientFps:15,activeFps:30,feedbackMaxDim:Math.max(256,Math.round(e*.5)),suspended:!this.isPointerInside&&this.mouseDown===0}:{ambientFps:se,activeFps:oe,feedbackMaxDim:e,suspended:!1}}resolveDprBounds(){let e=this.options.quality??"medium",t=O[e]??O.medium,i=typeof window<"u"&&window.devicePixelRatio||1,r=i>=1.5,s=this.options.maxDpr??Math.min(i,t.max),a=r?t.retinaMin:t.min,n=this.options.minDpr??Math.min(a,s);if(this.protectionTier===1){let l=Math.max(.65,Number((s*.75).toFixed(2)));return{minDpr:Math.min(n,l),maxDpr:l}}if(this.protectionTier>=2){let l=Math.max(.55,Math.min(n,Number((s*.6).toFixed(2))));return{minDpr:l,maxDpr:l}}return{minDpr:n,maxDpr:s}}computeScrollProgress(){if(typeof window>"u")return 0;let e=this.container.getBoundingClientRect(),t=window.innerHeight||1,i=t+e.height;return i<=0?0:Math.min(1,Math.max(0,(t-e.top)/i))}markContextActive(){this.countedContext||(this.countedContext=!0,C._activeContexts++,C._activeContexts>Oe&&console.warn(`[FluxFX] ${C._activeContexts} active WebGL contexts detected. Browsers typically cap contexts around 8\u201316; consider limiting simultaneous WebGL backgrounds.`))}markContextReleased(){this.countedContext&&(this.countedContext=!1,C._activeContexts=Math.max(0,C._activeContexts-1))}uniformVec3Css(e,t,i=1){let r=this.customUniforms.get(e),s=t[0],a=t[1],n=t[2];return r&&typeof r!="number"&&r.length>=3&&(s=Math.round(Math.min(1,Math.max(0,r[0]))*255),a=Math.round(Math.min(1,Math.max(0,r[1]))*255),n=Math.round(Math.min(1,Math.max(0,r[2]??0))*255)),i<1?`rgba(${s}, ${a}, ${n}, ${i})`:`rgb(${s}, ${a}, ${n})`}applyBudgetFallbackStyle(){if(this.isDestroyed)return;let e=this.customUniforms.get("uTransparentBg"),t=typeof e=="number"&&e>.5,i=this.customUniforms.get("uBgColor"),r=i&&typeof i!="number"&&i.length>=3&&i[0]+i[1]+(i[2]??0)>.003,s=this.uniformVec3Css("uColor1",[99,102,241],t?.38:.45),a=this.uniformVec3Css("uColor2",[6,182,212],t?.32:.38),n=this.uniformVec3Css("uColor3",[244,63,94],t?.22:.28),l=t?"transparent":r?this.uniformVec3Css("uBgColor",[6,8,16],1):"#070a14";this.canvas.style.background=`radial-gradient(circle at 22% 28%, ${s}, transparent 60%), radial-gradient(circle at 78% 72%, ${a}, transparent 62%), radial-gradient(circle at 55% 45%, ${n}, transparent 68%), ${l}`}syncDocVisibilityListener(){typeof document>"u"||(this.isOffscreen&&!this.hasDocVisibilityListener?(document.addEventListener("visibilitychange",this.handleDocVisibility),this.hasDocVisibilityListener=!0):!this.isOffscreen&&this.hasDocVisibilityListener&&(document.removeEventListener("visibilitychange",this.handleDocVisibility),this.hasDocVisibilityListener=!1))}releaseMainThreadContext(e){if(!this.gl){e||this.canvas.remove();return}let t=this.gl;if(t.isContextLost())this.pingPong=null,T.disposeContext(t),e||this.canvas.remove();else{this.destroyPingPongMain(),this.vbo&&t.deleteBuffer(this.vbo),this.vao&&t.deleteVertexArray(this.vao),T.disposeContext(t),t.bindFramebuffer(t.FRAMEBUFFER,null),t.bindVertexArray(null),t.bindBuffer(t.ARRAY_BUFFER,null),t.useProgram(null),t.viewport(0,0,1,1),t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),this.canvas.width=1,this.canvas.height=1;let r=this.canvas;if(e){let s=this.canvas.cloneNode(!1);this.canvas.replaceWith(s),this.canvas=s}else this.canvas.remove();!C.recycleMainContext(r,t)&&!Te()&&t.getExtension("WEBGL_lose_context")?.loseContext()}this.gl=null}suspendContextForBudget(){this.isDestroyed||this.isBudgetSuspended||(this.isBudgetSuspended=!0,this.resetFrameTracking(),this.canvas.removeEventListener("webglcontextlost",this.handleContextLost,!1),this.canvas.removeEventListener("webglcontextrestored",this.handleContextRestored,!1),this.isOffscreen&&this.worker&&(this.worker.postMessage({type:"destroy"}),this.worker=null),this.isOffscreen=!1,this.syncDocVisibilityListener(),this.releaseMainThreadContext(!0),this.programEntry=null,this.feedbackProgramEntry=null,this.vao=null,this.vbo=null,this.dynamicRes=null,this.isContextLost=!1,this.markContextReleased(),this.applyBudgetFallbackStyle(),this.wakeCallback?.())}restoreContextFromBudget(){if(this.isDestroyed||!this.isBudgetSuspended||!C.ensureContextBudget(this,!1))return!1;let e=this.canvas.cloneNode(!1);e.style.background="",this.canvas.replaceWith(e),this.canvas=e;let t=this.container.getBoundingClientRect();this.width=Math.max(1,Math.floor(t.width)),this.height=Math.max(1,Math.floor(t.height));let{minDpr:i,maxDpr:r}=this.resolveDprBounds(),s=this.options.dynamicResolution??!0,a=this.options.offscreen??!0;return this.isBudgetSuspended=!1,this.isContextLost=!1,this.lastActiveAt=X(),a&&re()?this.initOffscreenMode(this.options,i,r,s):this.initMainThreadMode(this.options,i,r,s),this.syncDocVisibilityListener(),this.wakeCallback?.(),this.countedContext}computeEffectiveQuality(){let e=this.options.quality??"medium",t=e==="high"?1:e==="low"?0:.5;return this.protectionTier>=2?t=0:this.protectionTier===1&&(t=Math.min(t,.5)),t}shouldPreserveBg(){return typeof this.options.preserveBg=="boolean"?this.options.preserveBg:this.layerMode==="overlay"}applyCanvasLayerStyle(){if(this.layerMode==="overlay"){this.canvas.style.zIndex="10";let e=typeof this.options.overlayOpacity=="number"?Math.max(.05,Math.min(1,this.options.overlayOpacity)):.78;this.canvas.style.opacity=String(e)}else this.canvas.style.zIndex="-1",this.canvas.style.opacity="1"}startPaletteTween(e,t=220){if(e.length===0)return;this.themeTweenRaf&&(cancelAnimationFrame(this.themeTweenRaf),this.themeTweenRaf=0);let i=this.toTriplet(this.activePaletteRgb.length>0?this.activePaletteRgb:this.basePaletteRgb),r=this.toTriplet(e);if(this.isReducedMotion||typeof requestAnimationFrame!="function"){this.activePaletteRgb=r,this.pushUniformBatch({uColor1:r[0],uColor2:r[1],uColor3:r[2]});return}let s=performance.now();this.boostInteraction(420);let a=n=>{if(this.isDestroyed){this.themeTweenRaf=0;return}let l=Math.min(1,(n-s)/t),c=l<.5?2*l*l:1-Math.pow(-2*l+2,2)/2,u=(m,p)=>[m[0]+(p[0]-m[0])*c,m[1]+(p[1]-m[1])*c,m[2]+(p[2]-m[2])*c],h=u(i[0],r[0]),f=u(i[1],r[1]),d=u(i[2],r[2]);this.activePaletteRgb=[h,f,d],this.pushUniformBatch({uColor1:h,uColor2:f,uColor3:d}),l<1?this.themeTweenRaf=requestAnimationFrame(a):this.themeTweenRaf=0};this.themeTweenRaf=requestAnimationFrame(a)}inspectSurfaceFromTarget(e,t=!1){if(!this.adaptToSurface||this.isDestroyed)return;let i=e instanceof HTMLElement?e:null,r=performance.now();if(!t&&i===this.lastSurfaceEl&&r-this.lastSurfaceCheckAt<180)return;this.lastSurfaceEl=i,this.lastSurfaceCheckAt=r;let s=pe(i,this.container);if(!s){this.isSurfaceAdapted&&(this.isSurfaceAdapted=!1,this.lastSurfaceKey="",this.startPaletteTween(this.basePaletteRgb,220));return}let a=`${Math.round(s[0]*255)},${Math.round(s[1]*255)},${Math.round(s[2]*255)}`;if(!t&&a===this.lastSurfaceKey)return;this.lastSurfaceKey=a;let n=this.rawBasePaletteRgb.length>0?this.rawBasePaletteRgb:this.basePaletteRgb;if(n.length===0)return;let l=ve(n,[s[0],s[1],s[2]]);this.isSurfaceAdapted=!0,this.startPaletteTween(l,220)}parseColorList(e){if(!e)return[];let t=Array.isArray(e)?e:String(e).split(",").map(s=>s.trim()).filter(Boolean);if(t.length===0)return[];let i=x(t[0],"#6366f1"),r=[];for(let s=0;s<t.length;s++){let a=x(t[s],i),n=y.hexToVec3Into(a,y.scratchVec3);r.push([n[0],n[1],n[2]])}return r}parseScrollStops(e){if(!Array.isArray(e)||e.length===0)return[];let t=[];for(let i=0;i<e.length;i++){let r=e[i],s=Array.isArray(r)?r[0]:r;if(typeof s=="string"&&s.trim()){let a=x(s,"#6366f1"),n=y.hexToVec3Into(a,y.scratchVec3);t.push([n[0],n[1],n[2]])}}return t}detectDarkTheme(e){return e==="dark"?!0:e==="light"?!1:fe(this.container)}resolveTargetPalette(e){let t=e?this.parseColorList(this.options.darkColors):this.parseColorList(this.options.lightColors);if(t.length>0)return t;let i=this.parseColorList(this.options.colors);return i.length>0?q(i,e):this.basePaletteRgb}toTriplet(e){let t=e[0]??[.39,.4,.95],i=e[1]??t,r=e[2]??i;return[[t[0],t[1],t[2]],[i[0],i[1],i[2]],[r[0],r[1],r[2]]]}pushUniformBatch(e){if(!this.isDestroyed){for(let[t,i]of Object.entries(e))this.customUniforms.set(t,i);if(this.isBudgetSuspended){this.applyBudgetFallbackStyle();return}this.isOffscreen&&this.worker?this.worker.postMessage({type:"uniformsBatch",uniforms:e}):this.isReducedMotion&&!this.isPaused&&!this.isHiddenByViewport&&this.drawMainThreadFrame()}}startThemeTransition(e){this.themeTweenRaf&&(cancelAnimationFrame(this.themeTweenRaf),this.themeTweenRaf=0);let t=e?1:0,i=this.resolveTargetPalette(e);i.length>0&&(this.basePaletteRgb=i);let r=this.currentTheme,s=this.toTriplet(this.activePaletteRgb.length>0?this.activePaletteRgb:this.basePaletteRgb),a=this.toTriplet(this.basePaletteRgb);if(this.isReducedMotion||typeof requestAnimationFrame!="function"){this.currentTheme=t,this.activePaletteRgb=a,this.pushUniformBatch({uTheme:t,uColor1:a[0],uColor2:a[1],uColor3:a[2]});return}let n=performance.now(),l=280;this.boostInteraction(500);let c=u=>{if(this.isDestroyed){this.themeTweenRaf=0;return}let h=Math.min(1,(u-n)/l),f=h<.5?2*h*h:1-Math.pow(-2*h+2,2)/2;this.currentTheme=r+(t-r)*f;let d=(g,b)=>[g[0]+(b[0]-g[0])*f,g[1]+(b[1]-g[1])*f,g[2]+(b[2]-g[2])*f],m=d(s[0],a[0]),p=d(s[1],a[1]),v=d(s[2],a[2]);this.activePaletteRgb=[m,p,v],this.pushUniformBatch({uTheme:this.currentTheme,uColor1:m,uColor2:p,uColor3:v}),h<1?this.themeTweenRaf=requestAnimationFrame(c):(this.themeTweenRaf=0,this.scrollStopsRgb.length>=2&&(this.lastScrollColorT=-1,this.updateScrollColorShift(this.computeScrollProgress())))};this.themeTweenRaf=requestAnimationFrame(c)}bindThemeWatchers(){if(this.unbindThemeWatchers(),!(typeof window>"u"||typeof document>"u")&&(typeof window.matchMedia=="function"&&(this.colorSchemeQuery=window.matchMedia("(prefers-color-scheme: dark)"),typeof this.colorSchemeQuery.addEventListener=="function"&&this.colorSchemeQuery.addEventListener("change",this.handleThemeChange)),typeof MutationObserver<"u")){this.themeMutationObserver=new MutationObserver(this.handleThemeChange);let e=["class","data-theme","data-mode","data-bs-theme","style"];this.themeMutationObserver.observe(document.documentElement,{attributes:!0,attributeFilter:e}),document.body&&this.themeMutationObserver.observe(document.body,{attributes:!0,attributeFilter:e}),this.container!==document.body&&this.container!==document.documentElement&&this.themeMutationObserver.observe(this.container,{attributes:!0,attributeFilter:e})}}unbindThemeWatchers(){this.themeTweenRaf&&(cancelAnimationFrame(this.themeTweenRaf),this.themeTweenRaf=0),this.colorSchemeQuery&&typeof this.colorSchemeQuery.removeEventListener=="function"&&this.colorSchemeQuery.removeEventListener("change",this.handleThemeChange),this.colorSchemeQuery=null,this.themeMutationObserver?.disconnect(),this.themeMutationObserver=null}updateScrollColorShift(e){if(this.scrollStopsRgb.length<2)return;let t=Math.min(1,Math.max(0,e));if(Math.abs(t-this.lastScrollColorT)<.002)return;this.lastScrollColorT=t;let i=q(this.scrollStopsRgb,this.resolvedDarkTheme),r=i.length-1,s=t*r,a=Math.min(r-1,Math.floor(s)),n=s-a,l=i[a],c=i[a+1],u=i[Math.min(i.length-1,a+2)]??l,h=[l[0]+(c[0]-l[0])*n,l[1]+(c[1]-l[1])*n,l[2]+(c[2]-l[2])*n],f=[c[0]+(u[0]-c[0])*n,c[1]+(u[1]-c[1])*n,c[2]+(u[2]-c[2])*n],d=this.basePaletteRgb[2]??u;this.activePaletteRgb=[h,f,d],this.pushUniformBatch({uColor1:h,uColor2:f,uColor3:d})}syncScrollColorListener(){if(typeof window>"u")return;let e=this.scrollStopsRgb.length>=2;e&&!this.hasScrollColorListener?(window.addEventListener("scroll",this.handleScrollColorEvent,{passive:!0}),this.hasScrollColorListener=!0,this.lastScrollColorT=-1,this.updateScrollColorShift(this.computeScrollProgress())):!e&&this.hasScrollColorListener&&(window.removeEventListener("scroll",this.handleScrollColorEvent),this.hasScrollColorListener=!1,this.scrollColorRaf&&(cancelAnimationFrame(this.scrollColorRaf),this.scrollColorRaf=0))}getLocalTouchCoords(e){let t=this.container.getBoundingClientRect();if(t.width<=0||t.height<=0)return null;let i=(e.clientX-t.left)/t.width,r=1-(e.clientY-t.top)/t.height;return i<0||i>1||r<0||r>1?null:[i,r]}syncTouchListener(){typeof window>"u"||(this.interactive&&!this.hasTouchListener?(this.container.addEventListener("touchstart",this.handleTouchStart,{passive:!0}),this.container.addEventListener("touchmove",this.handleTouchMove,{passive:!0}),this.container.addEventListener("touchend",this.handleTouchEnd,{passive:!0}),this.container.addEventListener("touchcancel",this.handleTouchEnd,{passive:!0}),this.hasTouchListener=!0):!this.interactive&&this.hasTouchListener&&(this.container.removeEventListener("touchstart",this.handleTouchStart),this.container.removeEventListener("touchmove",this.handleTouchMove),this.container.removeEventListener("touchend",this.handleTouchEnd),this.container.removeEventListener("touchcancel",this.handleTouchEnd),this.hasTouchListener=!1))}seedUniformsFromOptions(e,t=!1){let i={};if(typeof e.speed=="number"?(this.targetSpeed=e.speed,t&&(this.currentSpeed=e.speed),this.customUniforms.set("uSpeed",e.speed),i.uSpeed=e.speed):this.customUniforms.has("uSpeed")||(this.targetSpeed=1,this.currentSpeed=1,this.customUniforms.set("uSpeed",1),i.uSpeed=1),t||e.quality!==void 0){let n=this.computeEffectiveQuality();this.customUniforms.set("uQuality",n),i.uQuality=n}e.scrollColors!==void 0&&(this.scrollStopsRgb=this.parseScrollStops(e.scrollColors),this.lastScrollColorT=-1);let r=this.resolvedDarkTheme;e.theme!==void 0&&(this.themeMode=e.theme);let s=this.detectDarkTheme(this.themeMode);if(this.resolvedDarkTheme=s,t&&(this.currentTheme=s?1:0,this.customUniforms.set("uTheme",this.currentTheme),i.uTheme=this.currentTheme),t||e.colors!==void 0||e.lightColors!==void 0||e.darkColors!==void 0||e.theme!==void 0||e.scrollColors!==void 0){let n=this.parseColorList(this.options.colors);n.length>0&&(this.rawBasePaletteRgb=n);let l=this.resolveTargetPalette(s);if(l.length>0)if(this.basePaletteRgb=l,this.rawBasePaletteRgb.length===0&&(this.rawBasePaletteRgb=l),!t&&s!==r)this.startThemeTransition(s);else{let[c,u,h]=this.toTriplet(l);this.activePaletteRgb=[c,u,h],this.customUniforms.set("uColor1",c),this.customUniforms.set("uColor2",u),this.customUniforms.set("uColor3",h),i.uColor1=c,i.uColor2=u,i.uColor3=h,t||(this.currentTheme=s?1:0,this.customUniforms.set("uTheme",this.currentTheme),i.uTheme=this.currentTheme)}}if(e.uniforms)for(let[n,l]of Object.entries(e.uniforms))this.customUniforms.set(n,l),i[n]=typeof l=="number"?l:Array.from(l);return this.shouldPreserveBg()&&(this.customUniforms.set("uTransparentBg",1),i.uTransparentBg=1),i}fallbackToMainThread(e,t,i,r){if(this.isDestroyed)return;this.worker&&(this.worker.terminate(),this.worker=null),this.isOffscreen=!1,this.resetFrameTracking(),this.markContextReleased();let s=this.canvas.cloneNode(!1);this.canvas.replaceWith(s),this.canvas=s,this.initMainThreadMode(e,t,i,r)}initOffscreenMode(e,t,i,r){try{let s=ge(),a=this.canvas.transferControlToOffscreen();this.worker=s,this.isOffscreen=!0,this.markContextActive(),s.onmessage=l=>{if(l.data?.type==="error")this.fallbackToMainThread(e,t,i,r);else if(l.data?.type==="stats"){this.reportedFps=typeof l.data.fps=="number"?l.data.fps:0,this.reportedFrameTimeMs=typeof l.data.frameTimeMs=="number"?l.data.frameTimeMs:0;let c=typeof l.data.targetFps=="number"?l.data.targetFps:0;this.reportedFrameTimeMs>0&&c>0&&P.recordGpuFrame(this.reportedFrameTimeMs,c,performance.now())}},s.onerror=()=>{this.fallbackToMainThread(e,t,i,r)};let n={};this.customUniforms.forEach((l,c)=>{n[c]=typeof l=="number"?l:Array.from(l)}),s.postMessage({type:"init",canvas:a,width:this.width,height:this.height,minDpr:t,maxDpr:i,dynamicRes:r,reducedMotion:this.isReducedMotion,vertexShader:e.vertexShader??be,fragmentShader:e.fragmentShader,feedbackShader:e.feedbackShader??null,feedbackScale:this.feedbackScale,feedbackMaxDim:this.feedbackMaxDim,feedbackFloat:this.feedbackFloat,initialScroll:this.scroll,ambientFps:this.ambientFps,activeFps:this.activeFps,survivalPaused:this.isSurvivalSuspended,uniforms:n},[a])}catch{this.isOffscreen=!1,this.markContextReleased(),this.initMainThreadMode(e,t,i,r)}}computeFboDimsMain(e,t){let i=Math.max(1,Math.floor(e*this.feedbackScale)),r=Math.max(1,Math.floor(t*this.feedbackScale)),s=Math.max(i,r);if(s>this.feedbackMaxDim){let a=this.feedbackMaxDim/s;i=Math.max(1,Math.floor(i*a)),r=Math.max(1,Math.floor(r*a))}return[i,r]}destroyPingPongMain(){if(!this.pingPong||!this.gl){this.pingPong=null;return}for(let e=0;e<2;e++)this.gl.deleteFramebuffer(this.pingPong[e].fbo),this.gl.deleteTexture(this.pingPong[e].tex);this.pingPong=null}createPingPongMain(e){if(this.destroyPingPongMain(),!this.options.feedbackShader||this.isContextLost)return;let[t,i]=this.computeFboDimsMain(this.canvas.width,this.canvas.height);this.fboW=t,this.fboH=i;let r=e.RGBA8,s=e.UNSIGNED_BYTE;this.feedbackFloat&&(e.getExtension("EXT_color_buffer_float")||e.getExtension("EXT_color_buffer_half_float"))&&(r=e.RGBA16F,s=e.HALF_FLOAT);let n=(c,u)=>{let h=[];for(let f=0;f<2;f++){let d=e.createTexture(),m=e.createFramebuffer();if(!d||!m)return d&&e.deleteTexture(d),m&&e.deleteFramebuffer(m),h.forEach(p=>{e.deleteFramebuffer(p.fbo),e.deleteTexture(p.tex)}),null;if(e.bindTexture(e.TEXTURE_2D,d),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,c,this.fboW,this.fboH,0,e.RGBA,u,null),e.bindFramebuffer(e.FRAMEBUFFER,m),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,d,0),e.checkFramebufferStatus(e.FRAMEBUFFER)!==e.FRAMEBUFFER_COMPLETE)return e.deleteFramebuffer(m),e.deleteTexture(d),h.forEach(p=>{e.deleteFramebuffer(p.fbo),e.deleteTexture(p.tex)}),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindTexture(e.TEXTURE_2D,null),null;e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),h.push({fbo:m,tex:d})}return e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindTexture(e.TEXTURE_2D,null),[h[0],h[1]]},l=n(r,s);!l&&r!==e.RGBA8&&(r=e.RGBA8,s=e.UNSIGNED_BYTE,l=n(r,s)),this.fboFormat=r,this.fboType=s,this.pingPong=l,this.readIdx=0,this.writeIdx=1}resizePingPongMain(){if(!this.pingPong||!this.gl||this.isContextLost)return;let[e,t]=this.computeFboDimsMain(this.canvas.width,this.canvas.height);if(e===this.fboW&&t===this.fboH)return;let i=this.gl,r=this.fboW,s=this.fboH,a=this.pingPong[this.readIdx],n=[];for(let l=0;l<2;l++){let c=i.createTexture(),u=i.createFramebuffer();i.bindTexture(i.TEXTURE_2D,c),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,this.fboFormat,e,t,0,i.RGBA,this.fboType,null),i.bindFramebuffer(i.FRAMEBUFFER,u),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,c,0),n.push({fbo:u,tex:c})}i.bindFramebuffer(i.READ_FRAMEBUFFER,a.fbo),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,n[0].fbo),i.blitFramebuffer(0,0,r,s,0,0,e,t,i.COLOR_BUFFER_BIT,i.LINEAR),i.bindFramebuffer(i.READ_FRAMEBUFFER,null),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),i.bindTexture(i.TEXTURE_2D,null);for(let l=0;l<2;l++)i.deleteFramebuffer(this.pingPong[l].fbo),i.deleteTexture(this.pingPong[l].tex);this.pingPong=[n[0],n[1]],this.fboW=e,this.fboH=t,this.readIdx=0,this.writeIdx=1}initMainThreadPipeline(e){let t=this.options.vertexShader??z;this.programEntry=T.getOrCreateProgram(e,this.options.fragmentShader,t),this.options.feedbackShader?this.feedbackProgramEntry=T.getOrCreateProgram(e,this.options.feedbackShader,t):this.feedbackProgramEntry=null,this.vao=e.createVertexArray(),e.bindVertexArray(this.vao),this.vbo=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.vbo),e.bufferData(e.ARRAY_BUFFER,Ve,e.STATIC_DRAW),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0),e.bindVertexArray(null),this.needsResize=!1,this.applyCanvasSize(),this.options.feedbackShader&&this.createPingPongMain(e)}initMainThreadMode(e,t,i,r){let s=null,a=C.acquireRecycledMainContext();if(a?(a.canvas.style.background="",this.canvas.replaceWith(a.canvas),this.canvas=a.canvas,s=a.gl):s=this.canvas.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,powerPreference:"high-performance",preserveDrawingBuffer:!1}),!s){console.warn("[FluxFX] WebGL2 is not supported on this device."),this.isBudgetSuspended=!0,this.applyBudgetFallbackStyle();return}this.gl=s,this.markContextActive(),this.canvas.addEventListener("webglcontextlost",this.handleContextLost,!1),this.canvas.addEventListener("webglcontextrestored",this.handleContextRestored,!1),this.dynamicRes=new j({minScale:r?t:i,maxScale:i}),this.initMainThreadPipeline(s),this.drawMainThreadFrame()}applyCanvasSize(){if(!this.gl||!this.dynamicRes||this.isContextLost)return;let e=this.dynamicRes.scale,t=Math.max(1,Math.round(this.width*e)),i=Math.max(1,Math.round(this.height*e));(this.canvas.width!==t||this.canvas.height!==i)&&(this.canvas.width=t,this.canvas.height=i,this.gl.viewport(0,0,t,i)),this.pingPong&&this.resizePingPongMain()}bindCommonUniformsMain(e,t,i,r){let s=T.getUniformLocation(e,t,"uTime");s&&e.uniform1f(s,this.elapsedSec);let a=T.getUniformLocation(e,t,"uDelta");a&&e.uniform1f(a,this.lastDeltaSec);let n=T.getUniformLocation(e,t,"uResolution");n&&e.uniform2f(n,i,r);let l=T.getUniformLocation(e,t,"uCanvasResolution");l&&e.uniform2f(l,this.canvas.width,this.canvas.height);let c=T.getUniformLocation(e,t,"uDpr");c&&this.dynamicRes&&e.uniform1f(c,this.dynamicRes.scale);let u=T.getUniformLocation(e,t,"uMouse");u&&e.uniform2f(u,this.mouse[0],this.mouse[1]);let h=T.getUniformLocation(e,t,"uMouseVel");h&&e.uniform2f(h,this.mouseVel[0],this.mouseVel[1]);let f=T.getUniformLocation(e,t,"uMouseDown");f&&e.uniform1f(f,this.mouseDown);let d=T.getUniformLocation(e,t,"uMouseActive");d&&e.uniform1f(d,this.mouseActive);let m=T.getUniformLocation(e,t,"uScroll");m&&e.uniform1f(m,this.scroll);let p=T.getUniformLocation(e,t,"uScrollVel");p&&e.uniform1f(p,this.scrollVel),this.customUniforms.forEach((v,g)=>{let b=T.getUniformLocation(e,t,g);b&&(g==="uSpeed"?e.uniform1f(b,this.currentSpeed):typeof v=="number"?e.uniform1f(b,v):v.length===2?e.uniform2f(b,v[0],v[1]):v.length===3?e.uniform3f(b,v[0],v[1],v[2]):v.length===4&&e.uniform4f(b,v[0],v[1],v[2],v[3]))})}drawMainThreadFrame(){if(!this.gl||!this.programEntry||this.isContextLost)return;let e=this.gl;if(e.bindVertexArray(this.vao),this.feedbackProgramEntry&&this.pingPong){e.bindFramebuffer(e.FRAMEBUFFER,this.pingPong[this.writeIdx].fbo),e.viewport(0,0,this.fboW,this.fboH),e.useProgram(this.feedbackProgramEntry.program),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.pingPong[this.readIdx].tex);let t=T.getUniformLocation(e,this.feedbackProgramEntry,"uPrevFrame");t&&e.uniform1i(t,0),this.bindCommonUniformsMain(e,this.feedbackProgramEntry,this.fboW,this.fboH),e.drawArrays(e.TRIANGLES,0,3);let i=this.readIdx;this.readIdx=this.writeIdx,this.writeIdx=i,e.bindFramebuffer(e.FRAMEBUFFER,null),e.viewport(0,0,this.canvas.width,this.canvas.height)}if(e.useProgram(this.programEntry.program),this.pingPong){e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.pingPong[this.readIdx].tex);let t=T.getUniformLocation(e,this.programEntry,"uFeedback");t&&e.uniform1i(t,0);let i=T.getUniformLocation(e,this.programEntry,"uPrevFrame");i&&e.uniform1i(i,0)}this.bindCommonUniformsMain(e,this.programEntry,this.canvas.width,this.canvas.height),e.drawArrays(e.TRIANGLES,0,3)}render(e,t){if(this.isOffscreen||this.isPaused||this.isHiddenByViewport||this.isReducedMotion||this.isContextLost||this.isSurvivalSuspended||this.isBudgetSuspended||this.isDestroyed||!this.gl||!this.programEntry)return;let i=performance.now(),r=this.lastRenderNow?Math.min(i-this.lastRenderNow,100):16.67;this.lastRenderNow=i,this.prevFrameDrew&&(this.dynamicRes&&this.dynamicRes.recordFrame(r,i)&&(this.needsResize=!0),this.prevFrameDrew=!1);let a=i<this.boostUntil||this.mouseDown>.5?this.activeFps:this.ambientFps,n=1e3/a-2;if(this.lastDrawNow>0&&i-this.lastDrawNow<n)return;let l=this.lastDrawNow?i-this.lastDrawNow:1e3/a,c=Math.min(l,100);this.lastDrawNow=i,a!==this.lastTargetFps?(this.lastTargetFps=a,this.avgDrawDeltaMs=0):l>0&&l<500&&(this.avgDrawDeltaMs=this.avgDrawDeltaMs===0?l:this.avgDrawDeltaMs*.85+l*.15),this.avgDrawDeltaMs>0&&(this.reportedFps=Math.round(1e3/this.avgDrawDeltaMs),this.reportedFrameTimeMs=Math.round(this.avgDrawDeltaMs*100)/100),l>0&&l<500&&P.recordGpuFrame(l,a,i);let u=Math.max(.001,Math.min(c*.001,.05));if(this.lastDeltaSec=u,this.currentSpeed+=(this.targetSpeed-this.currentSpeed)*Y(7.5,u),this.elapsedSec+=u*this.currentSpeed,this.needsResize&&(this.needsResize=!1,this.applyCanvasSize()),this.mouseActive+=(this.targetMouseActive-this.mouseActive)*Y(7,u),this.mouseActive<.001&&this.targetMouseActive===0&&(this.mouseActive=0),this.targetMouseActive>.5){let h=this.mouse[0],f=this.mouse[1],d=Y(13,u);this.mouse[0]+=(this.targetMouse[0]-this.mouse[0])*d,this.mouse[1]+=(this.targetMouse[1]-this.mouse[1])*d,this.mouseVel[0]=Math.max(-8,Math.min(8,(this.mouse[0]-h)/u)),this.mouseVel[1]=Math.max(-8,Math.min(8,(this.mouse[1]-f)/u))}else this.mouseVel[0]=0,this.mouseVel[1]=0;if(this.trackScroll){let h=this.scroll;this.scroll+=(this.targetScroll-this.scroll)*Y(9.5,u),this.scrollVel=Math.max(-6,Math.min(6,(this.scroll-h)/u))}this.drawMainThreadFrame(),this.prevFrameDrew=!0}applyProtectionState(){if(this.isDestroyed||this.isBudgetSuspended)return;let e=this.resolveTierConfig(),{minDpr:t,maxDpr:i}=this.resolveDprBounds(),s=this.options.dynamicResolution??!0?t:i,a=this.isSurvivalSuspended,n=this.feedbackMaxDim;this.ambientFps=e.ambientFps,this.activeFps=e.activeFps,this.feedbackMaxDim=e.feedbackMaxDim,this.isSurvivalSuspended=e.suspended,this.isSurvivalSuspended&&!a&&this.resetFrameTracking(),this.isOffscreen&&this.worker?this.worker.postMessage({type:"protection",minDpr:s,maxDpr:i,feedbackMaxDim:this.feedbackMaxDim,ambientFps:this.ambientFps,activeFps:this.activeFps,suspended:this.isSurvivalSuspended}):((this.dynamicRes?.setBounds(s,i)??!1)||n!==this.feedbackMaxDim)&&(this.isReducedMotion&&!this.isPaused&&!this.isHiddenByViewport?(this.needsResize=!1,this.applyCanvasSize(),this.drawMainThreadFrame()):this.needsResize=!0),a!==this.isSurvivalSuspended&&this.wakeCallback?.()}syncDprBounds(){this.applyProtectionState()}watchDevicePixelRatio(){if(this.dprMediaQuery&&(this.dprMediaQuery.removeEventListener("change",this.handleDprChange),this.dprMediaQuery=null),typeof window>"u"||typeof window.matchMedia!="function")return;let e=window.devicePixelRatio||1;this.dprMediaQuery=window.matchMedia(`(resolution: ${e}dppx)`),this.dprMediaQuery.addEventListener("change",this.handleDprChange)}updateOptions(e){if(this.isDestroyed)return;let t=this.options.quality;this.options={...this.options,...e},e.layer!==void 0&&(this.layerMode=e.layer),(e.layer!==void 0||e.overlayOpacity!==void 0)&&this.applyCanvasLayerStyle(),typeof e.adaptToSurface=="boolean"&&(this.adaptToSurface=e.adaptToSurface,!this.adaptToSurface&&this.isSurfaceAdapted&&(this.isSurfaceAdapted=!1,this.lastSurfaceEl=null,this.lastSurfaceKey="",this.startPaletteTween(this.basePaletteRgb,200)));let i=this.seedUniformsFromOptions(e,!1);if(e.preserveBg!==void 0||e.layer!==void 0){let s=this.shouldPreserveBg()?1:Number(this.customUniforms.get("uTransparentBg")??0);this.customUniforms.set("uTransparentBg",s),i.uTransparentBg=s}if(this.boostInteraction(1200),e.quality!==void 0&&e.quality!==t){let r=O[e.quality]??O.medium;this.baseFeedbackMaxDim=this.options.feedbackMaxDim??r.fboMaxDim}if(e.feedbackMaxDim!==void 0&&(this.baseFeedbackMaxDim=e.feedbackMaxDim),(e.quality!==void 0&&e.quality!==t||e.feedbackMaxDim!==void 0||e.minDpr!==void 0||e.maxDpr!==void 0||e.dynamicResolution!==void 0)&&this.syncDprBounds(),typeof e.interactive=="boolean"&&e.interactive!==this.interactive&&(this.interactive=e.interactive,this.syncPointerListener(),this.syncTouchListener()),typeof e.trackScroll=="boolean"&&e.trackScroll!==this.trackScroll&&(this.trackScroll=e.trackScroll,this.syncScrollListener()),e.scrollColors!==void 0&&this.syncScrollColorListener(),typeof e.respectReducedMotion=="boolean"){this.respectReducedMotion=e.respectReducedMotion;let r=this.reducedMotionQuery?.matches??!1;this.applyReducedMotionState(this.respectReducedMotion&&r)}if(this.isBudgetSuspended){this.applyBudgetFallbackStyle();return}this.isOffscreen&&this.worker?Object.keys(i).length>0&&this.worker.postMessage({type:"uniformsBatch",uniforms:i}):this.isReducedMotion&&(this.needsResize&&(this.needsResize=!1,this.applyCanvasSize()),this.drawMainThreadFrame())}applyReducedMotionState(e){this.isReducedMotion!==e&&(this.isReducedMotion=e,this.resetFrameTracking(),this.isOffscreen&&this.worker?this.worker.postMessage({type:"reducedMotion",value:e}):e&&(this.needsResize&&(this.needsResize=!1,this.applyCanvasSize()),this.drawMainThreadFrame()),this.wakeCallback?.())}getLocalPointerCoords(e){let t=this.container.getBoundingClientRect();if(t.width<=0||t.height<=0||e.clientX<t.left||e.clientX>t.right||e.clientY<t.top||e.clientY>t.bottom)return null;let i=(e.clientX-t.left)/t.width,r=1-(e.clientY-t.top)/t.height;return[i,r]}syncInteractiveAttr(){if(this.interactive&&!this.isDestroyed){this.container.setAttribute("data-fluxfx-interactive","true");return}let e=!1;C.instances.forEach(t=>{t!==this&&!t.isDestroyed&&t.interactive&&t.container===this.container&&(e=!0)}),e||this.container.removeAttribute("data-fluxfx-interactive")}isShadowedByChildInteractive(e){if(!(e instanceof Element))return!1;let t=e.closest('[data-fluxfx-interactive="true"]');return!!(t&&t!==this.container&&this.container.contains(t))}syncPointerListener(){this.syncInteractiveAttr(),this.interactive&&!this.hasPointerListener?(this.container.addEventListener("pointerenter",this.handlePointerEnter,{passive:!0}),this.container.addEventListener("pointermove",this.handlePointerMove,{passive:!0}),this.container.addEventListener("pointerleave",this.handlePointerLeave,{passive:!0}),this.container.addEventListener("pointerdown",this.handlePointerDown,{passive:!0}),window.addEventListener("pointerup",this.handlePointerUp,{passive:!0}),window.addEventListener("pointercancel",this.handlePointerUp,{passive:!0}),this.hasPointerListener=!0):!this.interactive&&this.hasPointerListener&&(this.container.removeEventListener("pointerenter",this.handlePointerEnter),this.container.removeEventListener("pointermove",this.handlePointerMove),this.container.removeEventListener("pointerleave",this.handlePointerLeave),this.container.removeEventListener("pointerdown",this.handlePointerDown),window.removeEventListener("pointerup",this.handlePointerUp),window.removeEventListener("pointercancel",this.handlePointerUp),this.handlePointerLeave(),this.hasPointerListener=!1)}syncScrollListener(){this.trackScroll&&!this.hasScrollListener?(window.addEventListener("scroll",this.handleScroll,{passive:!0}),this.hasScrollListener=!0,this.handleScroll()):!this.trackScroll&&this.hasScrollListener&&(window.removeEventListener("scroll",this.handleScroll),this.hasScrollListener=!1)}bindObservers(e){typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(t=>{let i=t[0];if(!i)return;let r=Math.max(1,Math.floor(i.contentRect.width)),s=Math.max(1,Math.floor(i.contentRect.height));r===this.width&&s===this.height||(this.width=r,this.height=s,this.boostInteraction(600),this.trackScroll&&this.handleScroll(),this.isOffscreen&&this.worker?this.worker.postMessage({type:"resize",width:this.width,height:this.height}):this.isReducedMotion&&!this.isPaused&&!this.isHiddenByViewport?(this.needsResize=!1,this.applyCanvasSize(),this.drawMainThreadFrame()):this.needsResize=!0)}),this.resizeObserver.observe(this.container)),e&&typeof IntersectionObserver<"u"&&(this.visibilityObserver=new IntersectionObserver(t=>{let i=t[0]?.isIntersecting??!0;if(this.isHiddenByViewport=!i,i){if(this.lastActiveAt=X(),this.isBudgetSuspended&&!this.isPaused){this.restoreContextFromBudget();return}}else this.handlePointerLeave(),this.resetFrameTracking();this.isOffscreen&&this.worker&&this.worker.postMessage({type:i&&!this.isPaused?"resume":"pause"}),this.wakeCallback?.()},{rootMargin:"50px"}),this.visibilityObserver.observe(this.container)),this.reducedMotionQuery&&this.reducedMotionQuery.addEventListener("change",this.handleReducedMotionChange),this.isOffscreen&&typeof document<"u"&&document.addEventListener("visibilitychange",this.handleDocVisibility),this.watchDevicePixelRatio(),this.bindThemeWatchers(),this.syncPointerListener(),this.syncTouchListener(),this.syncScrollListener(),this.syncScrollColorListener()}setUniform(e,t){if(!this.isDestroyed){if(this.customUniforms.set(e,t),e==="uSpeed"&&typeof t=="number"&&(this.targetSpeed=t),this.boostInteraction(1200),this.isBudgetSuspended){this.applyBudgetFallbackStyle();return}this.isOffscreen&&this.worker?this.worker.postMessage({type:"uniform",name:e,value:typeof t=="number"?t:Array.from(t)}):this.isReducedMotion&&this.drawMainThreadFrame()}}setColor(e,t){let i=x(t,"#ffffff"),r=y.hexToVec3Into(i,y.scratchVec3);this.setUniform(e,[r[0],r[1],r[2]])}get isIdle(){return this.isDestroyed||this.isPaused||this.isHiddenByViewport||this.isReducedMotion||this.isContextLost}onWake(e){this.wakeCallback=e}pause(){this.isPaused||this.isDestroyed||(this.isPaused=!0,this.resetFrameTracking(),this.handlePointerLeave(),this.isOffscreen&&this.worker&&this.worker.postMessage({type:"pause"}))}resume(){if(!(!this.isPaused||this.isDestroyed)){if(this.isPaused=!1,this.lastRenderNow=0,this.lastDrawNow=0,this.lastActiveAt=X(),this.isBudgetSuspended&&!this.isHiddenByViewport){this.restoreContextFromBudget();return}this.isOffscreen&&this.worker&&!this.isHiddenByViewport?this.worker.postMessage({type:"resume"}):this.isReducedMotion&&!this.isHiddenByViewport&&(this.needsResize&&(this.needsResize=!1,this.applyCanvasSize()),this.drawMainThreadFrame())}}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.wakeCallback=null,this.unsubscribeGuard?.(),this.unsubscribeGuard=null,this.unbindThemeWatchers(),this.touchBurstTimer&&(window.clearTimeout(this.touchBurstTimer),this.touchBurstTimer=0),this.touchLeaveTimer&&(window.clearTimeout(this.touchLeaveTimer),this.touchLeaveTimer=0),this.hasTouchListener&&(this.container.removeEventListener("touchstart",this.handleTouchStart),this.container.removeEventListener("touchmove",this.handleTouchMove),this.container.removeEventListener("touchend",this.handleTouchEnd),this.container.removeEventListener("touchcancel",this.handleTouchEnd),this.hasTouchListener=!1),this.hasScrollColorListener&&(window.removeEventListener("scroll",this.handleScrollColorEvent),this.hasScrollColorListener=!1),this.scrollColorRaf&&(cancelAnimationFrame(this.scrollColorRaf),this.scrollColorRaf=0),this.isBodyMount&&(this.container.style.minHeight=this.origBodyMinHeight),C.instances.delete(this),this.syncInteractiveAttr(),this.resetFrameTracking(),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.visibilityObserver?.disconnect(),this.visibilityObserver=null,this.reducedMotionQuery&&(this.reducedMotionQuery.removeEventListener("change",this.handleReducedMotionChange),this.reducedMotionQuery=null),this.dprMediaQuery&&(this.dprMediaQuery.removeEventListener("change",this.handleDprChange),this.dprMediaQuery=null),typeof document<"u"&&document.removeEventListener("visibilitychange",this.handleDocVisibility),this.hasPointerListener&&(this.container.removeEventListener("pointerenter",this.handlePointerEnter),this.container.removeEventListener("pointermove",this.handlePointerMove),this.container.removeEventListener("pointerleave",this.handlePointerLeave),this.container.removeEventListener("pointerdown",this.handlePointerDown),window.removeEventListener("pointerup",this.handlePointerUp),window.removeEventListener("pointercancel",this.handlePointerUp),this.hasPointerListener=!1),this.hasScrollListener&&(window.removeEventListener("scroll",this.handleScroll),this.hasScrollListener=!1),this.canvas.removeEventListener("webglcontextlost",this.handleContextLost,!1),this.canvas.removeEventListener("webglcontextrestored",this.handleContextRestored,!1),this.isOffscreen&&this.worker&&(this.worker.postMessage({type:"destroy"}),this.worker=null),this.releaseMainThreadContext(!1),this.markContextReleased(),y.releaseVec2(this.mouse),y.releaseVec2(this.targetMouse),y.releaseVec2(this.mouseVel),this.customUniforms.clear(),C.reclaimBudgetForWaiting())}};C._activeContexts=0,C._maxContexts=ye(),C.instances=new Set,C.recycledMainContexts=[];var R=C;var N=class{constructor(){this.plugins=new Map;this.activeByElement=new WeakMap;this.activeSet=new Set;this.visibilityObserver=null;this.visibilityCallbacks=new WeakMap;this.removeTicker=null;this.removeVisibilitySub=null}ensureObserver(){return typeof window>"u"||typeof IntersectionObserver>"u"?null:(this.visibilityObserver||(this.visibilityObserver=new IntersectionObserver(e=>{for(let t=0;t<e.length;t++){let i=e[t],r=this.visibilityCallbacks.get(i.target);r&&r.forEach(s=>s(i.isIntersecting))}},{rootMargin:"50px"})),this.visibilityObserver)}ensureVisibilitySub(){this.removeVisibilitySub||(this.removeVisibilitySub=A.onVisibilityChange(e=>{this.activeSet.forEach(t=>{t.faulted||(e?t.instance.pause?.():t.visible&&t.instance.resume?.())}),this.syncTickerState()}))}hasActiveTickWork(){let e=!1;return this.activeSet.forEach(t=>{e||!t.visible||t.faulted||!t.instance.update||t.instance.isIdle?.()||(e=!0)}),e}syncTickerState(){this.hasActiveTickWork()?this.ensureTicker():this.removeTicker&&(this.removeTicker(),this.removeTicker=null)}ensureTicker(){this.removeTicker||(this.removeTicker=A.add((e,t)=>{let i=!1;this.activeSet.forEach(r=>{if(!(!r.visible||r.faulted||!r.instance.update)&&!r.instance.isIdle?.()){try{r.instance.update(e,t)}catch(s){r.faulted=!0,console.error(`[FluxFX] Runtime error in "${r.name}" (auto-paused):`,s);return}r.instance.isIdle?.()||(i=!0)}}),i||this.syncTickerState()}))}cleanupEmptyEngine(){this.syncTickerState(),this.activeSet.size===0&&this.removeVisibilitySub&&(this.removeVisibilitySub(),this.removeVisibilitySub=null)}bindWake(e){e.instance.onWake?.(()=>{this.activeSet.has(e)&&this.syncTickerState()})}register(e){return this.plugins.set(e.name,e),this}has(e){return this.plugins.has(e)}setMaxWebGLContexts(e){R.setMaxActiveContexts(e)}getStats(){let e=0,t=0,i=!1,r=A.isHidden;this.activeSet.forEach(u=>{u.visible&&e++;let h=u.instance.isIdle?.()??!1;r||!u.visible||u.faulted||h?t++:!u.instance.isWebGL&&u.instance.isIdle&&(i=!0)});let s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,a=R.getRenderStats(),n=A.fps,l=A.frameTimeMs;!r&&a.activeRendering>0&&!i?(n=a.fps,l=a.frameTimeMs):r&&(n=0,l=0);let c=P.getSnapshot();return{mounted:this.activeSet.size,visible:e,pausedEffects:t,activeLoops:A.isRunning?1:0,registered:this.plugins.size,webglContexts:R.activeContexts,activeContexts:R.activeContexts,maxWebGLContexts:R.maxActiveContexts,suspendedContexts:R.suspendedContexts,fps:n,frameTimeMs:l,reducedMotion:s,protectionTier:c.tier,protectionLabel:c.label}}apply(e,t,i={}){let r=this.plugins.get(t);if(!r)return console.warn(`[FluxFX] Effect "${t}" is not registered.`),()=>{};let s=this.activeByElement.get(e);s||(s=new Map,this.activeByElement.set(e,s));let a=s.get(t);a&&a.destroy();let n;try{n=r.mount(e,i)}catch(f){return console.error(`[FluxFX] Failed to mount "${t}":`,f),()=>{}}let l=i.pauseWhenHidden??!0,c=null,u=!1,h={el:e,name:t,plugin:r,instance:n,options:{...i},visible:!0,faulted:!1,destroy:()=>{if(!u){u=!0,c?.(),this.activeSet.delete(h),s?.delete(t);try{h.instance.destroy()}catch(f){console.error(`[FluxFX] Cleanup error in "${t}":`,f)}this.cleanupEmptyEngine()}}};if(l){let f=this.ensureObserver();if(f){let d=this.visibilityCallbacks.get(e);d||(d=new Set,this.visibilityCallbacks.set(e,d),f.observe(e));let m=p=>{h.visible=p,p&&!A.isHidden?h.instance.resume?.():h.instance.pause?.(),this.syncTickerState()};d.add(m),c=()=>{d?.delete(m),d&&d.size===0&&(f.unobserve(e),this.visibilityCallbacks.delete(e))}}}return s.set(t,h),this.activeSet.add(h),this.bindWake(h),this.ensureVisibilitySub(),A.isHidden&&h.instance.pause?.(),this.syncTickerState(),h.destroy}update(e,t,i={}){let s=this.activeByElement.get(e)?.get(t);if(!s)return!1;s.options={...s.options,...i};let a=s.options;if(s.instance.setOptions)try{return s.instance.setOptions(a),this.syncTickerState(),!0}catch(n){return console.error(`[FluxFX] Hot-update error in "${t}":`,n),!1}try{return s.instance.destroy(),s.instance=s.plugin.mount(e,a),s.faulted=!1,this.bindWake(s),(!s.visible||A.isHidden)&&s.instance.pause?.(),this.syncTickerState(),!0}catch(n){return s.faulted=!0,console.error(`[FluxFX] Fallback remount error in "${t}":`,n),this.syncTickerState(),!1}}scan(e=document){if(typeof document>"u")return;e.querySelectorAll("[data-fx]").forEach(i=>{let r=i.getAttribute("data-fx");if(!r)return;let s=r.trim().split(/\s+/).filter(Boolean),a=this.parseDatasetOptions(i),n=this.activeByElement.get(i);s.forEach(l=>{n?.has(l)||this.apply(i,l,a)})})}init(e){typeof document>"u"||(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.scan(e??document),{once:!0}):this.scan(e??document))}destroyAll(){let e=Array.from(this.activeSet);for(let t=0;t<e.length;t++)e[t].destroy()}parseDatasetOptions(e){let t={},i=new Set(["preserveBg","adaptToSurface","interactive","trackScroll","glare","offscreen","dynamicResolution","pauseWhenHidden","respectReducedMotion"]),r=new Set(["colors","lightColors","darkColors","scrollColors"]);for(let[s,a]of Object.entries(e.dataset)){if(!s.startsWith("fx")||s==="fx"||a===void 0)continue;let n=s.slice(2),l=n.charAt(0).toLowerCase()+n.slice(1),c=a.trim(),u=c.toLowerCase();c===""&&i.has(l)||u==="true"?t[l]=!0:u==="false"?t[l]=!1:r.has(l)?t[l]=c.split(",").map(h=>h.trim()).filter(Boolean):c!==""&&!Number.isNaN(Number(c))?t[l]=Number(c):t[l]=c}return t}},K=new N;function He(o){if(o==null)return!1;let e=String(o).trim().toLowerCase();if(!e)return!1;if(e==="transparent"||e==="none")return!0;let t=e.match(/^rgba?\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+(?:\s*,\s*([\d.]+))?\s*\)$/);return t&&t[1]!==void 0?parseFloat(t[1])<=.001:!1}function Me(o){let e=o.replace("#","").trim(),t=e.length===3?e.split("").map(a=>a+a).join(""):e;if(t.length!==6)return!0;let i=parseInt(t.slice(0,2),16)/255,r=parseInt(t.slice(2,4),16)/255,s=parseInt(t.slice(4,6),16)/255;return .2126*i+.7152*r+.0722*s>.45}function xe(o,e){if(Array.isArray(o.colors)&&o.colors.length>0){let s=o.colors.filter(Boolean);if(s.length===1){let c=x(s[0],e[0]);return[c,c,c]}if(s.length===2){let c=x(s[0],e[0]),u=x(s[1],e[1]);return[c,u,u]}let a=x(s[0],e[0]),n=x(s[1]??a,e[1]),l=x(s[2]??n,e[2]);return[a,n,l]}if(typeof o.colors=="string"){let s=o.colors.split(",").map(a=>a.trim()).filter(Boolean);if(s.length===1){let a=x(s[0],e[0]);return[a,a,a]}if(s.length===2){let a=x(s[0],e[0]),n=x(s[1],e[1]);return[a,n,n]}if(s.length>2)return[x(s[0],e[0]),x(s[1],e[1]),x(s[2],e[2])]}if(o.color1===void 0&&o.color2===void 0&&o.color3===void 0)return e;let t=x(o.color1,e[0]),i=o.color2!==void 0?x(o.color2,t):t,r=o.color3!==void 0?x(o.color3,i):i;return[t,i,r]}function B(o,e){let t=He(o.bgColor),i=!t&&o.bgColor!==void 0&&String(o.bgColor).trim()!=="",r=i?x(o.bgColor,e):e,s=y.hexToVec3Into(r,y.scratchVec3);return{uBgColor:[s[0],s[1],s[2]],uHasBgColor:i?1:0,uTransparentBg:t?1:0,bgHex:r,hasBgColor:i,transparentBg:t}}function We(o){return o==="high"?.65:o==="low"?.35:.5}function E(o){return{name:o.name,mount(e,t){let i=t.quality??"medium",r=new R(e,{fragmentShader:o.fragmentShader,vertexShader:o.vertexShader,feedbackShader:o.feedbackShader,feedbackScale:o.feedbackShader?We(i):void 0,feedbackFloat:o.feedbackShader?o.feedbackFloat??!0:void 0,feedbackMaxDim:typeof t.feedbackMaxDim=="number"?t.feedbackMaxDim:void 0,speed:typeof t.speed=="number"?t.speed:1,quality:i,colors:xe(t,o.defaultColors),uniforms:o.resolveUniforms?o.resolveUniforms(t):void 0,theme:t.theme,lightColors:t.lightColors,darkColors:t.darkColors,scrollColors:t.scrollColors,trackScroll:t.trackScroll,layer:t.layer,preserveBg:t.preserveBg,adaptToSurface:t.adaptToSurface,overlayOpacity:t.overlayOpacity,interactive:t.interactive!==!1,dynamicResolution:t.dynamicResolution,minDpr:t.minDpr,maxDpr:t.maxDpr,offscreen:t.offscreen,pauseWhenHidden:t.pauseWhenHidden,respectReducedMotion:t.respectReducedMotion});return{isWebGL:!0,update(s,a){r.render(s,a)},setOptions(s){r.updateOptions({speed:typeof s.speed=="number"?s.speed:1,quality:s.quality,colors:xe(s,o.defaultColors),uniforms:o.resolveUniforms?o.resolveUniforms(s):void 0,theme:s.theme,lightColors:s.lightColors,darkColors:s.darkColors,scrollColors:s.scrollColors,trackScroll:s.trackScroll,layer:s.layer,preserveBg:s.preserveBg,adaptToSurface:s.adaptToSurface,overlayOpacity:s.overlayOpacity,interactive:s.interactive!==!1,dynamicResolution:s.dynamicResolution,minDpr:s.minDpr,maxDpr:s.maxDpr,feedbackMaxDim:typeof s.feedbackMaxDim=="number"?s.feedbackMaxDim:void 0,respectReducedMotion:s.respectReducedMotion})},isIdle(){return r.isIdle},onWake(s){r.onWake(s)},pause(){r.pause()},resume(){r.resume()},destroy(){r.destroy()}}}}}var Ge=`#version 300 es
680
791
  precision highp float;
681
792
 
682
793
  in vec2 vUv;
@@ -686,6 +797,11 @@ uniform float uTime;
686
797
  uniform vec2 uResolution;
687
798
  uniform vec2 uMouse;
688
799
  uniform float uMouseActive;
800
+ uniform vec3 uBgColor;
801
+ uniform float uHasBgColor;
802
+ uniform float uTransparentBg;
803
+ uniform float uTheme;
804
+ uniform float uQuality;
689
805
  uniform vec3 uColor1;
690
806
  uniform vec3 uColor2;
691
807
  uniform vec3 uColor3;
@@ -708,13 +824,17 @@ float noise(vec2 p) {
708
824
  float fbm(vec2 p) {
709
825
  float value = 0.0;
710
826
  float amp = 0.5;
827
+ float norm = 0.0;
711
828
  mat2 rot = mat2(0.8, 0.6, -0.6, 0.8);
829
+ int octaves = uQuality < 0.25 ? 2 : (uQuality < 0.75 ? 3 : 4);
712
830
  for (int i = 0; i < 4; i++) {
831
+ if (i >= octaves) break;
713
832
  value += amp * noise(p);
833
+ norm += amp;
714
834
  p = rot * p * 2.02;
715
835
  amp *= 0.5;
716
836
  }
717
- return value;
837
+ return (value / max(norm, 0.001)) * 0.9375;
718
838
  }
719
839
 
720
840
  void main() {
@@ -734,17 +854,41 @@ void main() {
734
854
  float ribbon1 = smoothstep(0.15, 0.85, sin(p.y * 3.0 + f * 4.5 + t) * 0.5 + 0.5);
735
855
  float ribbon2 = smoothstep(0.2, 0.9, cos(p.x * 2.2 - f * 3.8 - t * 1.2) * 0.5 + 0.5);
736
856
 
737
- vec3 baseDark = vec3(0.03, 0.04, 0.09);
738
- vec3 col = mix(baseDark, uColor1, smoothstep(0.1, 0.9, ribbon1) * 0.85);
739
- col = mix(col, uColor2, smoothstep(0.2, 0.85, ribbon2 * f) * 0.9);
740
- col += uColor3 * smoothstep(0.25, 0.9, f * ribbon1) * 0.65;
741
-
742
- float vig = 1.0 - dot(uv - 0.5, uv - 0.5) * 0.75;
857
+ float m1 = smoothstep(0.1, 0.9, ribbon1) * 0.85;
858
+ float m2 = smoothstep(0.2, 0.85, ribbon2 * f) * 0.9;
859
+ float m3 = smoothstep(0.25, 0.9, f * ribbon1) * 0.65;
743
860
  float grain = (hash(gl_FragCoord.xy + fract(uTime)) - 0.5) * 0.02;
744
- col = col * vig + grain;
745
861
 
746
- fragColor = vec4(col, 1.0);
747
- }`,N=["#4f46e5","#06b6d4","#ec4899"];function q(o,e){if(Array.isArray(o.colors)&&o.colors.length>0){let t=n(o.colors[0],e[0]),r=n(o.colors[1]??t,e[1]),s=n(o.colors[2]??t,e[2]);return[t,r,s]}if(typeof o.colors=="string"){let t=o.colors.split(",").map(r=>r.trim()).filter(Boolean);if(t.length===1){let r=n(t[0],e[0]);return[r,r,n(e[2],e[2])]}if(t.length>1)return[n(t[0],e[0]),n(t[1],e[1]),n(t[2]??t[0],e[2])]}return[n(o.color1,e[0]),n(o.color2,e[1]),n(o.color3,e[2])]}var Q={name:"aurora",mount(o,e){let i=new x(o,{fragmentShader:xe,speed:typeof e.speed=="number"?e.speed:1,quality:e.quality??"medium",colors:q(e,N),interactive:e.interactive!==!1,dynamicResolution:e.dynamicResolution,minDpr:e.minDpr,maxDpr:e.maxDpr,offscreen:e.offscreen,pauseWhenHidden:e.pauseWhenHidden,respectReducedMotion:e.respectReducedMotion});return{update(t,r){i.render(t,r)},setOptions(t){i.updateOptions({speed:typeof t.speed=="number"?t.speed:1,quality:t.quality,colors:q(t,N),interactive:t.interactive!==!1,respectReducedMotion:t.respectReducedMotion})},pause(){i.pause()},resume(){i.resume()},destroy(){i.destroy()}}}};var Me=`#version 300 es
862
+ if (uTransparentBg > 0.5) {
863
+ float w1 = smoothstep(0.18, 0.9, ribbon1) * 0.85;
864
+ float w2 = smoothstep(0.22, 0.88, ribbon2 * f) * 0.9;
865
+ float w3 = smoothstep(0.28, 0.92, f * ribbon1) * 0.65;
866
+ float wSum = w1 + w2 + w3 + 0.0001;
867
+ vec3 ribbonCol = (uColor1 * w1 + uColor2 * w2 + uColor3 * w3) / wSum;
868
+ ribbonCol = clamp(ribbonCol + uColor3 * w3 * 0.35 + vec3(grain), 0.0, 1.0);
869
+ float alpha = clamp(max(max(w1, w2), w3), 0.0, 1.0);
870
+ fragColor = vec4(ribbonCol * alpha, alpha);
871
+ return;
872
+ }
873
+
874
+ float darkAmt = clamp(uTheme, 0.0, 1.0);
875
+ vec3 baseDark = uHasBgColor > 0.5 ? uBgColor : vec3(0.03, 0.04, 0.09);
876
+ vec3 baseLight = uHasBgColor > 0.5 ? uBgColor : vec3(0.96, 0.95, 0.925);
877
+
878
+ vec3 darkCol = mix(baseDark, uColor1, m1);
879
+ darkCol = mix(darkCol, uColor2, m2);
880
+ darkCol += uColor3 * m3;
881
+ float darkVig = 1.0 - dot(uv - 0.5, uv - 0.5) * 0.75;
882
+ darkCol = max(darkCol * darkVig + grain, vec3(0.0));
883
+
884
+ vec3 lightCol = mix(baseLight, uColor1, m1 * 0.44);
885
+ lightCol = mix(lightCol, uColor2, m2 * 0.40);
886
+ lightCol = mix(lightCol, uColor3, m3 * 0.34);
887
+ float lightVig = 1.0 - dot(uv - 0.5, uv - 0.5) * 0.14;
888
+ lightCol = clamp(lightCol * lightVig + grain * 0.5, 0.0, 1.0);
889
+
890
+ fragColor = vec4(mix(lightCol, darkCol, darkAmt), 1.0);
891
+ }`,Ce=E({name:"aurora",fragmentShader:Ge,defaultColors:["#4f46e5","#06b6d4","#ec4899"],resolveUniforms(o){let e=B(o,"#080a17");return{uBgColor:e.uBgColor,uHasBgColor:e.uHasBgColor,uTransparentBg:e.uTransparentBg}}});var ze=`#version 300 es
748
892
  precision highp float;
749
893
 
750
894
  in vec2 vUv;
@@ -754,12 +898,19 @@ uniform float uTime;
754
898
  uniform vec2 uResolution;
755
899
  uniform vec2 uMouse;
756
900
  uniform float uMouseActive;
901
+ uniform vec3 uBgColor;
902
+ uniform float uHasBgColor;
903
+ uniform float uTransparentBg;
904
+ uniform float uTheme;
905
+ uniform float uQuality;
757
906
  uniform vec3 uColor1;
758
907
  uniform vec3 uColor2;
759
908
  uniform vec3 uColor3;
760
909
 
761
910
  float field(vec2 p, float t) {
762
- for (int i = 1; i < 6; i++) {
911
+ int iters = uQuality < 0.25 ? 3 : (uQuality < 0.75 ? 4 : 5);
912
+ for (int i = 1; i <= 5; i++) {
913
+ if (i > iters) break;
763
914
  float fi = float(i);
764
915
  p.x += 0.35 / fi * sin(fi * 2.2 * p.y + t + 0.4 * fi);
765
916
  p.y += 0.35 / fi * cos(fi * 2.2 * p.x + t * 0.9 + 0.3 * fi);
@@ -791,13 +942,34 @@ void main() {
791
942
  float spec = pow(max(dot(normal, halfVec), 0.0), 28.0);
792
943
  float fresnel = pow(1.0 - max(dot(normal, viewDir), 0.0), 3.0);
793
944
 
794
- vec3 base = mix(uColor1 * 0.25, uColor2 * 0.75, h);
795
- vec3 col = base * (0.45 + 0.75 * diff);
796
- col += mix(vec3(0.95), uColor3, 0.35) * spec * 1.1;
797
- col += uColor3 * fresnel * 0.45;
945
+ if (uTransparentBg > 0.5) {
946
+ vec3 ridgeBase = mix(uColor1, uColor2, smoothstep(0.15, 0.9, h));
947
+ vec3 metalCol = ridgeBase * (0.55 + 0.65 * diff);
948
+ metalCol += mix(vec3(0.95), uColor3, 0.35) * spec * 1.15;
949
+ metalCol += uColor3 * fresnel * 0.5;
950
+ metalCol = clamp(metalCol, 0.0, 1.0);
951
+ float alpha = clamp(smoothstep(0.2, 0.88, h) * 0.78 + spec * 0.9 + fresnel * 0.45, 0.0, 1.0);
952
+ fragColor = vec4(metalCol * alpha, alpha);
953
+ return;
954
+ }
955
+
956
+ float darkAmt = clamp(uTheme, 0.0, 1.0);
957
+
958
+ vec3 darkBase = uHasBgColor > 0.5 ? uBgColor : uColor1 * 0.25;
959
+ vec3 baseD = mix(darkBase, uColor2 * 0.75, h);
960
+ vec3 darkCol = baseD * (0.45 + 0.75 * diff);
961
+ darkCol += mix(vec3(0.95), uColor3, 0.35) * spec * 1.1;
962
+ darkCol += uColor3 * fresnel * 0.45;
798
963
 
799
- fragColor = vec4(col, 1.0);
800
- }`,j=["#18181b","#94a3b8","#38bdf8"];function $(o,e){if(Array.isArray(o.colors)&&o.colors.length>0){let t=n(o.colors[0],e[0]),r=n(o.colors[1]??t,e[1]),s=n(o.colors[2]??t,e[2]);return[t,r,s]}if(typeof o.colors=="string"){let t=o.colors.split(",").map(r=>r.trim()).filter(Boolean);if(t.length===1){let r=n(t[0],e[0]);return[r,r,n(e[2],e[2])]}if(t.length>1)return[n(t[0],e[0]),n(t[1],e[1]),n(t[2]??t[0],e[2])]}return[n(o.color1,e[0]),n(o.color2,e[1]),n(o.color3,e[2])]}var Y={name:"liquid-metal",mount(o,e){let i=new x(o,{fragmentShader:Me,speed:typeof e.speed=="number"?e.speed:1,quality:e.quality??"medium",colors:$(e,j),interactive:e.interactive!==!1,dynamicResolution:e.dynamicResolution,minDpr:e.minDpr,maxDpr:e.maxDpr,offscreen:e.offscreen,pauseWhenHidden:e.pauseWhenHidden,respectReducedMotion:e.respectReducedMotion});return{update(t,r){i.render(t,r)},setOptions(t){i.updateOptions({speed:typeof t.speed=="number"?t.speed:1,quality:t.quality,colors:$(t,j),interactive:t.interactive!==!1,respectReducedMotion:t.respectReducedMotion})},pause(){i.pause()},resume(){i.resume()},destroy(){i.destroy()}}}};var Re=`#version 300 es
964
+ vec3 lightBase = uHasBgColor > 0.5 ? uBgColor : mix(vec3(0.92, 0.935, 0.96), uColor1, 0.16);
965
+ vec3 baseL = mix(lightBase, mix(vec3(0.76, 0.80, 0.88), uColor2, 0.42), h);
966
+ vec3 lightCol = baseL * (0.78 + 0.30 * diff);
967
+ lightCol += mix(vec3(1.0), uColor3, 0.28) * spec * 0.85;
968
+ lightCol = mix(lightCol, uColor3, fresnel * 0.24);
969
+ lightCol = clamp(lightCol, 0.0, 1.0);
970
+
971
+ fragColor = vec4(mix(lightCol, darkCol, darkAmt), 1.0);
972
+ }`,we=E({name:"liquid-metal",fragmentShader:ze,defaultColors:["#18181b","#94a3b8","#38bdf8"],resolveUniforms(o){let e=B(o,"#0f172a");return{uBgColor:e.uBgColor,uHasBgColor:e.uHasBgColor,uTransparentBg:e.uTransparentBg}}});var Xe=`#version 300 es
801
973
  precision highp float;
802
974
 
803
975
  in vec2 vUv;
@@ -858,7 +1030,6 @@ void main() {
858
1030
  vel *= velDecay;
859
1031
  dye *= dyeDecay;
860
1032
 
861
- // Subtle autonomous emitter (uTime is already smoothly speed-integrated)
862
1033
  float t = uTime * 0.55;
863
1034
  vec2 autoPos = vec2(
864
1035
  0.5 + 0.28 * cos(t * 0.9) * sin(t * 0.4),
@@ -899,7 +1070,7 @@ void main() {
899
1070
  dye = clamp(dye, vec2(0.0), vec2(1.0));
900
1071
 
901
1072
  fragColor = vec4(encodedVel, dye);
902
- }`,we=`#version 300 es
1073
+ }`,Ne=`#version 300 es
903
1074
  precision highp float;
904
1075
 
905
1076
  in vec2 vUv;
@@ -908,6 +1079,10 @@ out vec4 fragColor;
908
1079
  uniform sampler2D uFeedback;
909
1080
  uniform float uTime;
910
1081
  uniform vec2 uResolution;
1082
+ uniform vec3 uBgColor;
1083
+ uniform float uHasBgColor;
1084
+ uniform float uTransparentBg;
1085
+ uniform float uTheme;
911
1086
  uniform vec3 uColor1;
912
1087
  uniform vec3 uColor2;
913
1088
  uniform vec3 uColor3;
@@ -917,7 +1092,6 @@ float hash(vec2 p) {
917
1092
  }
918
1093
 
919
1094
  void main() {
920
- // Sample gradients using actual FBO texture resolution (eliminates Retina specular banding)
921
1095
  vec2 fboTexel = 1.0 / max(vec2(textureSize(uFeedback, 0)), vec2(1.0));
922
1096
  vec4 state = texture(uFeedback, vUv);
923
1097
 
@@ -936,20 +1110,48 @@ void main() {
936
1110
  float spec = pow(max(dot(normal, lightDir), 0.0), 20.0) * smoothstep(0.08, 0.6, density);
937
1111
 
938
1112
  float flowEnergy = clamp(length(vel) * 1.4, 0.0, 1.0);
939
- vec3 baseDark = vec3(0.025, 0.03, 0.065) + uColor1 * 0.04;
940
-
941
- vec3 col = baseDark;
942
- col = mix(col, uColor1, smoothstep(0.03, 0.78, dyeA) * 0.92);
943
- col = mix(col, uColor2, smoothstep(0.06, 0.85, dyeB) * 0.88);
944
- col += uColor3 * smoothstep(0.18, 0.95, dyeA * dyeB * 1.6 + flowEnergy * density * 0.65) * 0.75;
945
- col += mix(vec3(1.0), uColor3, 0.4) * spec * 0.55;
1113
+ float m1 = smoothstep(0.03, 0.78, dyeA) * 0.92;
1114
+ float m2 = smoothstep(0.06, 0.85, dyeB) * 0.88;
1115
+ float m3 = smoothstep(0.18, 0.95, dyeA * dyeB * 1.6 + flowEnergy * density * 0.65) * 0.75;
946
1116
 
947
- float vig = 1.0 - dot(vUv - 0.5, vUv - 0.5) * 0.65;
1117
+ float darkAmt = clamp(uTheme, 0.0, 1.0);
948
1118
  float grain = (hash(gl_FragCoord.xy + fract(uTime)) - 0.5) * 0.015;
949
- col = max(col * vig + grain, vec3(0.0));
950
1119
 
951
- fragColor = vec4(col, 1.0);
952
- }`,K=["#6366f1","#06b6d4","#f43f5e"];function J(o,e){if(Array.isArray(o.colors)&&o.colors.length>0){let t=n(o.colors[0],e[0]),r=n(o.colors[1]??t,e[1]),s=n(o.colors[2]??t,e[2]);return[t,r,s]}if(typeof o.colors=="string"){let t=o.colors.split(",").map(r=>r.trim()).filter(Boolean);if(t.length===1){let r=n(t[0],e[0]);return[r,r,n(e[2],e[2])]}if(t.length>1)return[n(t[0],e[0]),n(t[1],e[1]),n(t[2]??t[0],e[2])]}return[n(o.color1,e[0]),n(o.color2,e[1]),n(o.color3,e[2])]}function Z(o){return{uDissipation:typeof o.dissipation=="number"?o.dissipation:.975,uRadius:typeof o.radius=="number"?o.radius:.0045,uSwirl:typeof o.swirl=="number"?o.swirl:1.4}}var ee={name:"fluid",mount(o,e){let i=new x(o,{fragmentShader:we,feedbackShader:Re,feedbackScale:e.quality==="high"?.65:e.quality==="low"?.35:.5,feedbackFloat:!0,speed:typeof e.speed=="number"?e.speed:1,quality:e.quality??"medium",colors:J(e,K),uniforms:Z(e),interactive:e.interactive!==!1,dynamicResolution:e.dynamicResolution,minDpr:e.minDpr,maxDpr:e.maxDpr,offscreen:e.offscreen,pauseWhenHidden:e.pauseWhenHidden,respectReducedMotion:e.respectReducedMotion});return{update(t,r){i.render(t,r)},setOptions(t){i.updateOptions({speed:typeof t.speed=="number"?t.speed:1,quality:t.quality,colors:J(t,K),uniforms:Z(t),interactive:t.interactive!==!1,respectReducedMotion:t.respectReducedMotion})},pause(){i.pause()},resume(){i.resume()},destroy(){i.destroy()}}}};var Fe=`#version 300 es
1120
+ vec3 baseDark = uHasBgColor > 0.5
1121
+ ? uBgColor
1122
+ : (vec3(0.025, 0.03, 0.065) + uColor1 * 0.04);
1123
+ vec3 darkCol = baseDark;
1124
+ darkCol = mix(darkCol, uColor1, m1);
1125
+ darkCol = mix(darkCol, uColor2, m2);
1126
+ darkCol += uColor3 * m3;
1127
+ darkCol += mix(vec3(1.0), uColor3, 0.4) * spec * 0.55;
1128
+ float darkVig = 1.0 - dot(vUv - 0.5, vUv - 0.5) * 0.65;
1129
+ darkCol = max(darkCol * darkVig + grain, vec3(0.0));
1130
+
1131
+ vec3 baseLight = uHasBgColor > 0.5 ? uBgColor : vec3(0.96, 0.953, 0.935);
1132
+ vec3 lightCol = baseLight;
1133
+ lightCol = mix(lightCol, uColor1, m1 * 0.58);
1134
+ lightCol = mix(lightCol, uColor2, m2 * 0.54);
1135
+ lightCol = mix(lightCol, uColor3, m3 * 0.50);
1136
+ lightCol += vec3(0.28) * spec * 0.42;
1137
+ float lightVig = 1.0 - dot(vUv - 0.5, vUv - 0.5) * 0.12;
1138
+ lightCol = clamp(lightCol * lightVig + grain * 0.5, 0.0, 1.0);
1139
+
1140
+ vec3 opaqueCol = mix(lightCol, darkCol, darkAmt);
1141
+
1142
+ float wSum = m1 + m2 + m3 + 0.0001;
1143
+ vec3 dyeCol = (uColor1 * m1 + uColor2 * m2 + uColor3 * m3) / wSum;
1144
+ dyeCol += mix(vec3(1.0), uColor3, 0.4) * spec * 0.48;
1145
+ dyeCol = clamp(dyeCol + vec3(grain), 0.0, 1.0);
1146
+
1147
+ float alpha = clamp(max(max(m1, m2), max(m3, spec * 0.55)), 0.0, 1.0);
1148
+
1149
+ if (uTransparentBg > 0.5) {
1150
+ fragColor = vec4(dyeCol * alpha, alpha);
1151
+ } else {
1152
+ fragColor = vec4(opaqueCol, 1.0);
1153
+ }
1154
+ }`,Se=E({name:"fluid",fragmentShader:Ne,feedbackShader:Xe,feedbackFloat:!0,defaultColors:["#6366f1","#06b6d4","#f43f5e"],resolveUniforms(o){let e=B(o,"#060810");return{uBgColor:e.uBgColor,uHasBgColor:e.uHasBgColor,uTransparentBg:e.uTransparentBg,uDissipation:typeof o.dissipation=="number"?o.dissipation:.975,uRadius:typeof o.radius=="number"?o.radius:.0045,uSwirl:typeof o.swirl=="number"?o.swirl:1.4}}});var Qe=`#version 300 es
953
1155
  precision highp float;
954
1156
 
955
1157
  in vec2 vUv;
@@ -990,25 +1192,21 @@ void main() {
990
1192
  vec2 vD = decodeVel(d);
991
1193
  vec2 vU = decodeVel(u);
992
1194
 
993
- // Vorticity confinement for wispy ink tendrils in still water
994
1195
  float vorticity = (vR.y - vL.y) - (vU.x - vD.x);
995
1196
  vec2 grad = vec2(abs(vU.y) - abs(vD.y), abs(vR.x) - abs(vL.x));
996
1197
  vec2 perp = normalize(grad + vec2(0.0001));
997
1198
  vel += vec2(perp.y, -perp.x) * vorticity * uCurl * dt * 1.65;
998
1199
 
999
- // Advect velocity & ink pigments backward along flow
1000
1200
  vec2 backUv = clamp(vUv - vel * dt * 0.48 * clamp(uSpeed, 0.25, 3.0), texel, 1.0 - texel);
1001
1201
  vec4 adv = texture(uPrevFrame, backUv);
1002
1202
  vec2 advVel = decodeVel(adv);
1003
1203
 
1004
- // Water viscosity: velocity damps faster than suspended ink pigments
1005
1204
  float visc = pow(clamp(uDissipation * 0.985, 0.88, 0.992), dt * 60.0);
1006
1205
  float inkHold = pow(clamp(uDissipation + 0.006, 0.92, 0.998), dt * 60.0);
1007
1206
 
1008
1207
  vel = mix(advVel, (vL + vR + vD + vU) * 0.25, 0.07) * visc;
1009
1208
  vec2 ink = mix(adv.ba, (l.ba + r.ba + d.ba + u.ba) * 0.25, 0.035) * inkHold;
1010
1209
 
1011
- // Gentle ambient ink drift so canvas feels alive before pointer interaction
1012
1210
  float t = uTime * 0.42;
1013
1211
  vec2 driftPos = vec2(
1014
1212
  0.5 + 0.25 * sin(t * 0.85),
@@ -1021,7 +1219,6 @@ void main() {
1021
1219
  ink.x += driftSplat * (0.45 + 0.45 * sin(t * 1.2)) * dt * 0.85;
1022
1220
  ink.y += driftSplat * (0.45 + 0.45 * cos(t * 0.9)) * dt * 0.75;
1023
1221
 
1024
- // Pointer ink injection (strictly scoped to active container)
1025
1222
  if (uMouseActive > 0.01) {
1026
1223
  vec2 deltaP = (vUv - uMouse) * vec2(aspect, 1.0);
1027
1224
  float dist2 = dot(deltaP, deltaP);
@@ -1037,7 +1234,6 @@ void main() {
1037
1234
  ink.y += deposit * (0.35 + 0.65 * (1.0 - wave));
1038
1235
  }
1039
1236
 
1040
- // Press & hold drops a concentrated ink bloom
1041
1237
  if (uMouseDown > 0.5) {
1042
1238
  vec2 outward = normalize(deltaP + vec2(0.0001));
1043
1239
  float bloom = exp(-dist2 / max(uRadius * 2.4, 0.003));
@@ -1051,7 +1247,7 @@ void main() {
1051
1247
  vec2 encVel = clamp(vel * 0.5 + 0.5, vec2(0.02), vec2(0.98));
1052
1248
 
1053
1249
  fragColor = vec4(encVel, ink);
1054
- }`,Ee=`#version 300 es
1250
+ }`,$e=`#version 300 es
1055
1251
  precision highp float;
1056
1252
 
1057
1253
  in vec2 vUv;
@@ -1060,6 +1256,10 @@ out vec4 fragColor;
1060
1256
  uniform sampler2D uFeedback;
1061
1257
  uniform float uTime;
1062
1258
  uniform vec2 uResolution;
1259
+ uniform vec3 uBgColor;
1260
+ uniform float uHasBgColor;
1261
+ uniform float uTransparentBg;
1262
+ uniform float uTheme;
1063
1263
  uniform vec3 uColor1;
1064
1264
  uniform vec3 uColor2;
1065
1265
  uniform vec3 uColor3;
@@ -1075,7 +1275,6 @@ void main() {
1075
1275
  float ink1 = fbo.b;
1076
1276
  float ink2 = fbo.a;
1077
1277
 
1078
- // Subtle refractive distortion along ink pigment gradient
1079
1278
  float hC = ink1 * 0.7 + ink2 * 0.55;
1080
1279
  float hL = dot(texture(uFeedback, vUv - vec2(fboTexel.x * 2.0, 0.0)).ba, vec2(0.7, 0.55));
1081
1280
  float hR = dot(texture(uFeedback, vUv + vec2(fboTexel.x * 2.0, 0.0)).ba, vec2(0.7, 0.55));
@@ -1089,30 +1288,51 @@ void main() {
1089
1288
  float p1 = mix(ink1, refFbo.b, 0.45);
1090
1289
  float p2 = mix(ink2, refFbo.a, 0.45);
1091
1290
 
1092
- // Water backdrop + Beer-Lambert style pigment absorption
1093
- vec3 waterBase = vec3(0.025, 0.03, 0.06) + uColor1 * 0.035;
1094
1291
  float absorb1 = smoothstep(0.02, 0.82, p1);
1095
1292
  float absorb2 = smoothstep(0.04, 0.86, p2);
1096
-
1097
- vec3 col = waterBase;
1098
- col = mix(col, uColor1, absorb1 * 0.92);
1099
- col = mix(col, uColor2, absorb2 * 0.86);
1100
-
1101
- // Rich filament veins where pigments fold and overlap
1102
1293
  float filament = smoothstep(0.22, 0.92, p1 * p2 * 1.7 + length(grad) * 2.2);
1103
- col = mix(col, uColor3, filament * 0.68);
1104
1294
 
1105
- // Soft water surface sheen along pigment ridges
1106
1295
  vec3 n = normalize(vec3((hL - hR) * 2.8, (hD - hU) * 2.8, 1.0));
1107
1296
  float rim = pow(1.0 - max(n.z, 0.0), 2.2) * smoothstep(0.05, 0.65, hC);
1108
- col += mix(vec3(0.9), uColor3, 0.45) * rim * 0.35;
1109
-
1110
- float vig = 1.0 - dot(vUv - 0.5, vUv - 0.5) * 0.62;
1111
1297
  float grain = (hash(gl_FragCoord.xy + fract(uTime)) - 0.5) * 0.015;
1112
- col = max(col * vig + grain, vec3(0.0));
1113
1298
 
1114
- fragColor = vec4(col, 1.0);
1115
- }`,te=["#1e1b4b","#0284c7","#e11d48"];function ie(o,e){if(Array.isArray(o.colors)&&o.colors.length>0){let t=n(o.colors[0],e[0]),r=n(o.colors[1]??t,e[1]),s=n(o.colors[2]??t,e[2]);return[t,r,s]}if(typeof o.colors=="string"){let t=o.colors.split(",").map(r=>r.trim()).filter(Boolean);if(t.length===1){let r=n(t[0],e[0]);return[r,r,n(e[2],e[2])]}if(t.length>1)return[n(t[0],e[0]),n(t[1],e[1]),n(t[2]??t[0],e[2])]}return[n(o.color1,e[0]),n(o.color2,e[1]),n(o.color3,e[2])]}function re(o){return{uDissipation:typeof o.dissipation=="number"?o.dissipation:.982,uRadius:typeof o.radius=="number"?o.radius:.004,uCurl:typeof o.curl=="number"?o.curl:1.75}}var oe={name:"ink",mount(o,e){let i=new x(o,{fragmentShader:Ee,feedbackShader:Fe,feedbackScale:e.quality==="high"?.65:e.quality==="low"?.35:.5,feedbackFloat:!0,speed:typeof e.speed=="number"?e.speed:1,quality:e.quality??"medium",colors:ie(e,te),uniforms:re(e),interactive:e.interactive!==!1,dynamicResolution:e.dynamicResolution,minDpr:e.minDpr,maxDpr:e.maxDpr,offscreen:e.offscreen,pauseWhenHidden:e.pauseWhenHidden,respectReducedMotion:e.respectReducedMotion});return{update(t,r){i.render(t,r)},setOptions(t){i.updateOptions({speed:typeof t.speed=="number"?t.speed:1,quality:t.quality,colors:ie(t,te),uniforms:re(t),interactive:t.interactive!==!1,respectReducedMotion:t.respectReducedMotion})},pause(){i.pause()},resume(){i.resume()},destroy(){i.destroy()}}}};var Le=`#version 300 es
1299
+ if (uTransparentBg > 0.5) {
1300
+ float a1 = absorb1 * 0.92;
1301
+ float a2 = absorb2 * 0.86;
1302
+ float a3 = filament * 0.68;
1303
+ float wSum = a1 + a2 + a3 + 0.0001;
1304
+ vec3 inkCol = (uColor1 * a1 + uColor2 * a2 + uColor3 * a3) / wSum;
1305
+ inkCol += mix(vec3(0.9), uColor3, 0.45) * rim * 0.35;
1306
+ inkCol = clamp(inkCol + vec3(grain), 0.0, 1.0);
1307
+ float alpha = clamp(max(max(a1, a2), max(a3, rim * 0.35)), 0.0, 1.0);
1308
+ fragColor = vec4(inkCol * alpha, alpha);
1309
+ return;
1310
+ }
1311
+
1312
+ float darkAmt = clamp(uTheme, 0.0, 1.0);
1313
+
1314
+ vec3 waterDark = uHasBgColor > 0.5
1315
+ ? uBgColor
1316
+ : (vec3(0.025, 0.03, 0.06) + uColor1 * 0.035);
1317
+ vec3 darkCol = waterDark;
1318
+ darkCol = mix(darkCol, uColor1, absorb1 * 0.92);
1319
+ darkCol = mix(darkCol, uColor2, absorb2 * 0.86);
1320
+ darkCol = mix(darkCol, uColor3, filament * 0.68);
1321
+ darkCol += mix(vec3(0.9), uColor3, 0.45) * rim * 0.35;
1322
+ float darkVig = 1.0 - dot(vUv - 0.5, vUv - 0.5) * 0.62;
1323
+ darkCol = max(darkCol * darkVig + grain, vec3(0.0));
1324
+
1325
+ vec3 waterLight = uHasBgColor > 0.5 ? uBgColor : vec3(0.965, 0.955, 0.935);
1326
+ vec3 lightCol = waterLight;
1327
+ lightCol = mix(lightCol, uColor1 * 0.82, absorb1 * 0.68);
1328
+ lightCol = mix(lightCol, uColor2 * 0.86, absorb2 * 0.62);
1329
+ lightCol = mix(lightCol, uColor3 * 0.90, filament * 0.55);
1330
+ lightCol += vec3(0.14) * rim * 0.25;
1331
+ float lightVig = 1.0 - dot(vUv - 0.5, vUv - 0.5) * 0.12;
1332
+ lightCol = clamp(lightCol * lightVig + grain * 0.5, 0.0, 1.0);
1333
+
1334
+ fragColor = vec4(mix(lightCol, darkCol, darkAmt), 1.0);
1335
+ }`,Re=E({name:"ink",fragmentShader:$e,feedbackShader:Qe,feedbackFloat:!0,defaultColors:["#1e1b4b","#0284c7","#e11d48"],resolveUniforms(o){let e=B(o,"#060810");return{uBgColor:e.uBgColor,uHasBgColor:e.uHasBgColor,uTransparentBg:e.uTransparentBg,uDissipation:typeof o.dissipation=="number"?o.dissipation:.982,uRadius:typeof o.radius=="number"?o.radius:.004,uCurl:typeof o.curl=="number"?o.curl:1.75}}});var je=`#version 300 es
1116
1336
  precision highp float;
1117
1337
 
1118
1338
  in vec2 vUv;
@@ -1153,18 +1373,15 @@ void main() {
1153
1373
  vec2 vD = decodeVel(d);
1154
1374
  vec2 vU = decodeVel(u);
1155
1375
 
1156
- // Vorticity confinement for wispy curling ink tendrils
1157
1376
  float curl = (vR.y - vL.y) - (vU.x - vD.x);
1158
1377
  vec2 grad = vec2(abs(vU.y) - abs(vD.y), abs(vR.x) - abs(vL.x));
1159
1378
  vec2 swirlDir = normalize(grad + vec2(0.0001));
1160
1379
  vel += vec2(swirlDir.y, -swirlDir.x) * curl * uCurl * dt * 1.5;
1161
1380
 
1162
- // Semi-Lagrangian advection along flow
1163
1381
  vec2 backUv = clamp(vUv - vel * dt * 0.52 * clamp(uSpeed, 0.25, 3.0), texel, 1.0 - texel);
1164
1382
  vec4 adv = texture(uPrevFrame, backUv);
1165
1383
  vec2 advVel = decodeVel(adv);
1166
1384
 
1167
- // Soft pressure-like neighbor smoothing keeps incompressible swirls silky
1168
1385
  vec2 avgVel = (vL + vR + vD + vU) * 0.25;
1169
1386
  vec2 avgInk = (l.ba + r.ba + d.ba + u.ba) * 0.25;
1170
1387
 
@@ -1174,7 +1391,6 @@ void main() {
1174
1391
  vel = mix(advVel, avgVel, 0.09) * velDecay;
1175
1392
  vec2 ink = mix(adv.ba, avgInk, 0.032) * inkDecay;
1176
1393
 
1177
- // Autonomous curving ink plumes (gives live video-like motion on load)
1178
1394
  float t = uTime * 0.45;
1179
1395
  for (int i = 0; i < 3; i++) {
1180
1396
  float fi = float(i);
@@ -1194,7 +1410,6 @@ void main() {
1194
1410
  ink.y += splat * (1.0 - pulse * 0.65) * dt * 0.75;
1195
1411
  }
1196
1412
 
1197
- // Interactive cursor stroke & click/hold ink bloom (strictly inside container)
1198
1413
  if (uMouseActive > 0.01) {
1199
1414
  vec2 diff = (vUv - uMouse) * vec2(aspect, 1.0);
1200
1415
  float distSq = dot(diff, diff);
@@ -1223,7 +1438,7 @@ void main() {
1223
1438
  vec2 encVel = clamp(vel * 0.5 + 0.5, vec2(0.02), vec2(0.98));
1224
1439
 
1225
1440
  fragColor = vec4(encVel, ink);
1226
- }`,Se=`#version 300 es
1441
+ }`,qe=`#version 300 es
1227
1442
  precision highp float;
1228
1443
 
1229
1444
  in vec2 vUv;
@@ -1233,8 +1448,11 @@ uniform sampler2D uFeedback;
1233
1448
  uniform float uTime;
1234
1449
  uniform vec2 uResolution;
1235
1450
  uniform vec3 uBgColor;
1451
+ uniform float uHasBgColor;
1452
+ uniform float uHasExplicitLightMode;
1236
1453
  uniform float uTransparentBg;
1237
1454
  uniform float uLightMode;
1455
+ uniform float uTheme;
1238
1456
  uniform float uAbsorptionGain;
1239
1457
  uniform vec3 uColor1;
1240
1458
  uniform vec3 uColor2;
@@ -1253,7 +1471,6 @@ void main() {
1253
1471
  float pA = fbo.b;
1254
1472
  float pB = fbo.a;
1255
1473
 
1256
- // Fluid surface relief normal from pigment density gradient
1257
1474
  float hC = pA * 0.72 + pB * 0.58;
1258
1475
  float hL = dot(texture(uFeedback, vUv - vec2(fboTexel.x * 2.0, 0.0)).ba, vec2(0.72, 0.58));
1259
1476
  float hR = dot(texture(uFeedback, vUv + vec2(fboTexel.x * 2.0, 0.0)).ba, vec2(0.72, 0.58));
@@ -1265,38 +1482,40 @@ void main() {
1265
1482
  float diffuse = clamp(dot(normal, lightDir), 0.0, 1.0);
1266
1483
  float rimSheen = pow(clamp(dot(normal, normalize(vec3(0.4, 0.6, 0.7))), 0.0, 1.0), 8.0);
1267
1484
 
1268
- // Combine 3 palette tones across dual pigment channels
1269
1485
  vec3 tintMix = normalize(uColor1 * pA + uColor2 * pB + uColor3 * (pA * pB * 1.8) + vec3(0.0001));
1270
1486
  float totalInk = (pA + pB * 0.85) * uAbsorptionGain;
1271
1487
 
1272
- // Light water: Beer-Lambert exponential light absorption on solid bg
1488
+ float darkAmt = clamp(uTheme, 0.0, 1.0);
1489
+ float effectiveLightMode = uHasExplicitLightMode > 0.5
1490
+ ? clamp(uLightMode, 0.0, 1.0)
1491
+ : (1.0 - darkAmt);
1492
+ vec3 effectiveBg = uHasBgColor > 0.5
1493
+ ? uBgColor
1494
+ : mix(vec3(0.96, 0.953, 0.933), vec3(0.032, 0.04, 0.075), darkAmt);
1495
+
1273
1496
  vec3 transmittance = exp(-tintMix * totalInk * 1.35);
1274
1497
  float inkMask = clamp(1.0 - exp(-hC * 1.5), 0.0, 1.0);
1275
- vec3 lightCol = uBgColor * transmittance;
1498
+ vec3 lightCol = effectiveBg * transmittance;
1276
1499
  lightCol *= mix(1.0, 0.90 + 0.16 * diffuse, inkMask * 0.72);
1277
1500
  lightCol += vec3(0.025) * rimSheen * inkMask * (1.0 - inkMask * 0.45);
1278
1501
 
1279
- // Dark water: Luminous bioluminescent plumes on solid bg
1280
1502
  vec3 luminous = (vec3(1.0) - exp(-tintMix * totalInk * 1.25)) * (0.86 + 0.24 * diffuse);
1281
- vec3 darkCol = uBgColor + luminous + luminous * rimSheen * 0.12;
1503
+ vec3 darkCol = effectiveBg + luminous + luminous * rimSheen * 0.12;
1282
1504
 
1283
- vec3 opaqueCol = mix(darkCol, lightCol, clamp(uLightMode, 0.0, 1.0));
1505
+ vec3 opaqueCol = mix(darkCol, lightCol, effectiveLightMode);
1284
1506
 
1285
- // Subtle vignette + fine organic grain on solid bg
1286
1507
  vec2 centered = vUv - 0.5;
1287
- float vignetteStrength = mix(0.36, 0.085, clamp(uLightMode, 0.0, 1.0));
1508
+ float vignetteStrength = mix(0.36, 0.085, effectiveLightMode);
1288
1509
  opaqueCol *= (1.0 - dot(centered, centered) * vignetteStrength);
1289
1510
  float grain = (hash12(vUv * 900.0 + fract(uTime * 0.05)) - 0.5) * 0.011;
1290
1511
  opaqueCol = clamp(opaqueCol + grain, 0.0, 1.0);
1291
1512
 
1292
- // Transparent backdrop mode: only render pigment/ink with alpha over page/body bg
1293
1513
  float inkAlpha = clamp(1.0 - exp(-totalInk * 1.35), 0.0, 1.0);
1294
1514
  vec3 inkRgb = clamp(tintMix * (0.82 + 0.28 * diffuse) + vec3(0.04) * rimSheen, 0.0, 1.0);
1295
1515
 
1296
1516
  if (uTransparentBg > 0.5) {
1297
- // Premultiplied alpha works cleanly with standard canvas alpha blending
1298
1517
  fragColor = vec4(inkRgb * inkAlpha, inkAlpha);
1299
1518
  } else {
1300
1519
  fragColor = vec4(opaqueCol, 1.0);
1301
1520
  }
1302
- }`,se=["#1e3a5f","#2d3748","#0284c7"],Te="#f5f3ee";function Pe(o){if(o==null)return!1;let e=String(o).trim().toLowerCase();if(!e||e==="transparent"||e==="none")return!0;let i=e.match(/^rgba?\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+(?:\s*,\s*([\d.]+))?\s*\)$/);return i&&i[1]!==void 0?parseFloat(i[1])<=.001:!1}function De(o){let e=o.replace("#","").trim(),i=e.length===3?e.split("").map(a=>a+a).join(""):e;if(i.length!==6)return!0;let t=parseInt(i.slice(0,2),16)/255,r=parseInt(i.slice(2,4),16)/255,s=parseInt(i.slice(4,6),16)/255;return .2126*t+.7152*r+.0722*s>.45}function ne(o,e){if(Array.isArray(o.colors)){let t=n(o.colors[0],e[0]),r=n(o.colors[1]??t,e[1]),s=n(o.colors[2]??t,e[2]);return[t,r,s]}if(typeof o.colors=="string"){let t=o.colors.split(",").map(r=>r.trim()).filter(Boolean);if(t.length===1){let r=n(t[0],e[0]);return[r,r,n(e[2],e[2])]}return[n(t[0],e[0]),n(t[1],e[1]),n(t[2]??t[0],e[2])]}return[n(o.color1,e[0]),n(o.color2,e[1]),n(o.color3,e[2])]}function ae(o){let e=Pe(o.bgColor),i=e?"#000000":n(o.bgColor,Te),t=g.hexToVec3Into(i,g.scratchVec3),r=De(i)?1:0,s=typeof o.lightMode=="number"?o.lightMode:typeof o.lightMode=="boolean"?o.lightMode?1:0:r;return{uBgColor:[t[0],t[1],t[2]],uTransparentBg:e?1:0,uLightMode:s,uAbsorptionGain:typeof o.absorptionGain=="number"?o.absorptionGain:1.45,uDissipation:typeof o.dissipation=="number"?o.dissipation:.978,uRadius:typeof o.radius=="number"?o.radius:.0032,uCurl:typeof o.curl=="number"?o.curl:1.85}}var ce={name:"aetheria",mount(o,e){let i=new x(o,{fragmentShader:Se,feedbackShader:Le,feedbackScale:e.quality==="high"?.65:e.quality==="low"?.35:.5,feedbackFloat:!0,speed:typeof e.speed=="number"?e.speed:1,quality:e.quality??"medium",colors:ne(e,se),uniforms:ae(e),interactive:e.interactive!==!1,dynamicResolution:e.dynamicResolution,minDpr:e.minDpr,maxDpr:e.maxDpr,offscreen:e.offscreen,pauseWhenHidden:e.pauseWhenHidden,respectReducedMotion:e.respectReducedMotion});return{update(t,r){i.render(t,r)},setOptions(t){i.updateOptions({speed:typeof t.speed=="number"?t.speed:1,quality:t.quality,colors:ne(t,se),uniforms:ae(t),interactive:t.interactive!==!1,respectReducedMotion:t.respectReducedMotion})},pause(){i.pause()},resume(){i.resume()},destroy(){i.destroy()}}}};var le={name:"tilt-3d",mount(o,e){let i=typeof e.maxTilt=="number"?e.maxTilt:12,t=typeof e.scale=="number"?e.scale:1.03,r=typeof e.perspective=="number"?e.perspective:900,s=e.glare!==!1,c=o.style.transform,a=o.style.position,l=o.style.overflow,u=o.style.willChange;o.style.willChange="transform";let d=null;s&&(getComputedStyle(o).position==="static"&&(o.style.position="relative"),o.style.overflow="hidden",d=document.createElement("div"),Object.assign(d.style,{position:"absolute",inset:"0",pointerEvents:"none",borderRadius:"inherit",opacity:"0",transition:"opacity 0.25s ease",zIndex:"2"}),o.appendChild(d));let f=0,p=0,m=1,v=0,y=0,b=1,L=50,M=50,P=!1,B=U=>{let w=o.getBoundingClientRect(),F=(U.clientX-w.left)/w.width,W=(U.clientY-w.top)/w.height;f=(.5-W)*i*2,p=(F-.5)*i*2,m=t,L=F*100,M=W*100,P=!0,d&&(d.style.opacity="1")},X=()=>{f=0,p=0,m=1,P=!0,d&&(d.style.opacity="0")};return o.addEventListener("pointermove",B,{passive:!0}),o.addEventListener("pointerleave",X,{passive:!0}),{update(U,w){if(!P)return;let F=1-Math.exp(-12*w);v+=(f-v)*F,y+=(p-y)*F,b+=(m-b)*F,o.style.transform=`perspective(${r}px) rotateX(${v.toFixed(2)}deg) rotateY(${y.toFixed(2)}deg) scale3d(${b.toFixed(3)}, ${b.toFixed(3)}, 1)`,d&&(d.style.background=`radial-gradient(circle at ${L.toFixed(1)}% ${M.toFixed(1)}%, rgba(255,255,255,0.22), transparent 60%)`),Math.abs(f-v)<.02&&Math.abs(p-y)<.02&&Math.abs(m-b)<.001&&(P=!1,m===1&&(o.style.transform=c))},destroy(){o.removeEventListener("pointermove",B),o.removeEventListener("pointerleave",X),d?.remove(),o.style.transform=c,o.style.position=a,o.style.overflow=l,o.style.willChange=u}}}};var ue={name:"magnetic",mount(o,e){let i=typeof e.strength=="number"?e.strength:.35,t=o.style.transform,r=o.style.willChange;o.style.willChange="transform";let s=0,c=0,a=0,l=0,u=!1,d=p=>{let m=o.getBoundingClientRect(),v=m.left+m.width/2,y=m.top+m.height/2;s=(p.clientX-v)*i,c=(p.clientY-y)*i,u=!0},f=()=>{s=0,c=0,u=!0};return o.addEventListener("pointermove",d,{passive:!0}),o.addEventListener("pointerleave",f,{passive:!0}),{update(p,m){if(!u)return;let v=1-Math.exp(-10*m);a+=(s-a)*v,l+=(c-l)*v,o.style.transform=`translate3d(${a.toFixed(2)}px, ${l.toFixed(2)}px, 0)`,Math.abs(s-a)<.05&&Math.abs(c-l)<.05&&(u=!1,s===0&&c===0&&(o.style.transform=t))},destroy(){o.removeEventListener("pointermove",d),o.removeEventListener("pointerleave",f),o.style.transform=t,o.style.willChange=r}}}};k.register(Q).register(Y).register(ee).register(oe).register(ce).register(le).register(ue);var Ae=k;typeof window<"u"&&(window.FluxFX=k);0&&(module.exports={FluxEngine,FluxFX,WebGLQuad});
1521
+ }`,Le=E({name:"aetheria",fragmentShader:qe,feedbackShader:je,feedbackFloat:!0,defaultColors:["#1e3a5f","#2d3748","#0284c7"],resolveUniforms(o){let e=B(o,"#f5f3ee"),t=typeof o.lightMode=="number"||typeof o.lightMode=="boolean"||e.hasBgColor,i=Me(e.bgHex)?1:0,r=typeof o.lightMode=="number"?o.lightMode:typeof o.lightMode=="boolean"?o.lightMode?1:0:i;return{uBgColor:e.uBgColor,uHasBgColor:e.uHasBgColor,uHasExplicitLightMode:t?1:0,uTransparentBg:e.uTransparentBg,uLightMode:r,uAbsorptionGain:typeof o.absorptionGain=="number"?o.absorptionGain:1.45,uDissipation:typeof o.dissipation=="number"?o.dissipation:.978,uRadius:typeof o.radius=="number"?o.radius:.0032,uCurl:typeof o.curl=="number"?o.curl:1.85}}});var Ee={name:"tilt-3d",mount(o,e){let t=typeof e.maxTilt=="number"?e.maxTilt:12,i=typeof e.scale=="number"?e.scale:1.03,r=typeof e.perspective=="number"?e.perspective:900,s=e.glare!==!1,a=e.respectReducedMotion??!0,n=o.style.transform,l=o.style.position,c=o.style.overflow,u=o.style.willChange,h=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)"):null,f=a&&(h?.matches??!1);f||(o.style.willChange="transform");let d=null;s&&(getComputedStyle(o).position==="static"&&(o.style.position="relative"),o.style.overflow="hidden",d=document.createElement("div"),Object.assign(d.style,{position:"absolute",inset:"0",pointerEvents:"none",borderRadius:"inherit",opacity:"0",transition:"opacity 0.25s ease",zIndex:"2"}),o.appendChild(d));let m=0,p=0,v=1,g=0,b=0,S=1,U=50,W=50,F=!1,k=!1,M=null,w=null,D=!0,G=()=>{D=!0},ke=()=>{let L=o.getBoundingClientRect();w={left:L.left,top:L.top,width:L.width,height:L.height},D=!1},ae=L=>{let _=a&&L.matches;f!==_&&(f=_,f?(m=0,p=0,v=1,g=0,b=0,S=1,F=!1,d&&(d.style.opacity="0"),o.style.transform=n,o.style.willChange=u):(o.style.willChange="transform",D=!0),M?.())},ne=()=>{D=!0},le=L=>{if(k||f||((D||!w)&&ke(),!w||w.width<=0||w.height<=0))return;let _=(L.clientX-w.left)/w.width,I=(L.clientY-w.top)/w.height;m=(.5-I)*t*2,p=(_-.5)*t*2,v=i,U=_*100,W=I*100,F=!0,d&&(d.style.opacity="1"),M?.()},ce=()=>{f||(m=0,p=0,v=1,d&&(d.style.opacity="0"),(Math.abs(g)>.01||Math.abs(b)>.01||Math.abs(S-1)>.001)&&(F=!0,k||M?.()))},Q=null;return typeof ResizeObserver<"u"&&(Q=new ResizeObserver(G),Q.observe(o)),h&&typeof h.addEventListener=="function"&&h.addEventListener("change",ae),o.addEventListener("pointerenter",ne,{passive:!0}),o.addEventListener("pointermove",le,{passive:!0}),o.addEventListener("pointerleave",ce,{passive:!0}),window.addEventListener("resize",G,{passive:!0}),window.addEventListener("scroll",G,{passive:!0,capture:!0}),{update(L,_){if(!F||k||f)return;let I=1-Math.exp(-12*_);if(g+=(m-g)*I,b+=(p-b)*I,S+=(v-S)*I,d&&(d.style.background=`radial-gradient(circle at ${U.toFixed(1)}% ${W.toFixed(1)}%, rgba(255,255,255,0.22), transparent 60%)`),Math.abs(m-g)<.02&&Math.abs(p-b)<.02&&Math.abs(v-S)<.001){g=m,b=p,S=v,F=!1,o.style.transform=v===1&&m===0&&p===0?n:`perspective(${r}px) rotateX(${g.toFixed(2)}deg) rotateY(${b.toFixed(2)}deg) scale3d(${S.toFixed(3)}, ${S.toFixed(3)}, 1)`;return}o.style.transform=`perspective(${r}px) rotateX(${g.toFixed(2)}deg) rotateY(${b.toFixed(2)}deg) scale3d(${S.toFixed(3)}, ${S.toFixed(3)}, 1)`},isIdle(){return!F||k||f},onWake(L){M=L},pause(){k=!0},resume(){k=!1,D=!0,F&&!f&&M?.()},destroy(){M=null,F=!1,w=null,Q?.disconnect(),Q=null,h&&typeof h.removeEventListener=="function"&&h.removeEventListener("change",ae),o.removeEventListener("pointerenter",ne),o.removeEventListener("pointermove",le),o.removeEventListener("pointerleave",ce),window.removeEventListener("resize",G),window.removeEventListener("scroll",G,!0),d?.remove(),o.style.transform=n,o.style.position=l,o.style.overflow=c,o.style.willChange=u}}}};var Fe={name:"magnetic",mount(o,e){let t=typeof e.strength=="number"?e.strength:.35,i=e.respectReducedMotion??!0,r=o.style.transform,s=o.style.willChange,a=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)"):null,n=i&&(a?.matches??!1);n||(o.style.willChange="transform");let l=0,c=0,u=0,h=0,f=!1,d=!1,m=null,p=null,v=!0,g=()=>{v=!0},b=()=>{let M=o.getBoundingClientRect();p={left:M.left-u,top:M.top-h,width:M.width,height:M.height},v=!1},S=M=>{let w=i&&M.matches;n!==w&&(n=w,n?(l=0,c=0,u=0,h=0,f=!1,o.style.transform=r,o.style.willChange=s):(o.style.willChange="transform",v=!0),m?.())},U=()=>{v=!0},W=M=>{if(d||n||((v||!p)&&b(),!p||p.width<=0||p.height<=0))return;let w=p.left+p.width*.5,D=p.top+p.height*.5;l=(M.clientX-w)*t,c=(M.clientY-D)*t,f=!0,m?.()},F=()=>{n||(l=0,c=0,(Math.abs(u)>.01||Math.abs(h)>.01)&&(f=!0,d||m?.()))},k=null;return typeof ResizeObserver<"u"&&(k=new ResizeObserver(g),k.observe(o)),a&&typeof a.addEventListener=="function"&&a.addEventListener("change",S),o.addEventListener("pointerenter",U,{passive:!0}),o.addEventListener("pointermove",W,{passive:!0}),o.addEventListener("pointerleave",F,{passive:!0}),window.addEventListener("resize",g,{passive:!0}),window.addEventListener("scroll",g,{passive:!0,capture:!0}),{update(M,w){if(!f||d||n)return;let D=1-Math.exp(-10*w);if(u+=(l-u)*D,h+=(c-h)*D,Math.abs(l-u)<.05&&Math.abs(c-h)<.05){u=l,h=c,f=!1,o.style.transform=l===0&&c===0?r:`translate3d(${u.toFixed(2)}px, ${h.toFixed(2)}px, 0)`;return}o.style.transform=`translate3d(${u.toFixed(2)}px, ${h.toFixed(2)}px, 0)`},isIdle(){return!f||d||n},onWake(M){m=M},pause(){d=!0},resume(){d=!1,v=!0,f&&!n&&m?.()},destroy(){m=null,f=!1,p=null,k?.disconnect(),k=null,a&&typeof a.removeEventListener=="function"&&a.removeEventListener("change",S),o.removeEventListener("pointerenter",U),o.removeEventListener("pointermove",W),o.removeEventListener("pointerleave",F),window.removeEventListener("resize",g),window.removeEventListener("scroll",g,!0),o.style.transform=r,o.style.willChange=s}}}};K.register(Ce).register(we).register(Se).register(Re).register(Le).register(Ee).register(Fe);var Ye=K;typeof window<"u"&&(window.FluxFX=K);0&&(module.exports={FluxEngine,FluxFX,WebGLQuad,createWebGLEffect});