@votax572002/fluxfx 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,1302 @@
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
2
+ precision highp float;
3
+ layout(location = 0) in vec2 aPosition;
4
+ out vec2 vUv;
5
+ void main() {
6
+ vUv = aPosition * 0.5 + 0.5;
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=`
11
+ let gl = null;
12
+ let canvas = null;
13
+ let displayProgram = null;
14
+ let feedbackProgram = null;
15
+ let vao = null;
16
+ let vbo = null;
17
+ let rafId = 0;
18
+
19
+ let running = false;
20
+ let pausedByHost = false;
21
+ let reducedMotion = false;
22
+ let contextLost = false;
23
+ let needsResize = false;
24
+
25
+ let elapsedSec = 0;
26
+ let lastFrameTime = 0;
27
+ let lastDeltaSec = 0.01667;
28
+ let currentSpeed = 1.0;
29
+ let targetSpeed = 1.0;
30
+
31
+ let width = 1;
32
+ let height = 1;
33
+ let baseDpr = 1;
34
+ let dprScale = 1;
35
+ let minScale = 0.75;
36
+ let dynamicRes = true;
37
+
38
+ let savedVertexSrc = '';
39
+ let savedFragmentSrc = '';
40
+ let savedFeedbackSrc = null;
41
+ let feedbackScale = 0.5;
42
+ let feedbackMaxDim = 896;
43
+ let feedbackFloat = true;
44
+
45
+ let pingPong = null;
46
+ let fboW = 1;
47
+ let fboH = 1;
48
+ let fboFormat = 0;
49
+ let fboType = 0;
50
+ let readIdx = 0;
51
+ let writeIdx = 1;
52
+
53
+ const frameSamples = new Float32Array(30);
54
+ let sampleIdx = 0;
55
+ let sampleCount = 0;
56
+ let stableWindows = 0;
57
+ let lastAdjust = 0;
58
+
59
+ const displayLocs = new Map();
60
+ const feedbackLocs = new Map();
61
+ const customUniforms = new Map();
62
+
63
+ const mouse = new Float32Array([0.5, 0.5]);
64
+ const targetMouse = new Float32Array([0.5, 0.5]);
65
+ const mouseVel = new Float32Array([0.0, 0.0]);
66
+ let mouseDown = 0;
67
+ let mouseActive = 0;
68
+ let targetMouseActive = 0;
69
+
70
+ let scrollProgress = 0;
71
+ let targetScroll = 0;
72
+ let scrollVel = 0;
73
+
74
+ const hasRAF = typeof self.requestAnimationFrame === 'function';
75
+ function scheduleFrame(fn) {
76
+ return hasRAF ? self.requestAnimationFrame(fn) : setTimeout(() => fn(performance.now()), 16);
77
+ }
78
+ function cancelFrame(id) {
79
+ if (!id) return;
80
+ if (hasRAF) self.cancelAnimationFrame(id);
81
+ else clearTimeout(id);
82
+ }
83
+
84
+ // Frame-rate independent exponential smoothing (identical feel at 60Hz, 90Hz, 120Hz ProMotion)
85
+ function damp(lambda, dt) {
86
+ return 1 - Math.exp(-lambda * dt);
87
+ }
88
+
89
+ function compile(type, src) {
90
+ const s = gl.createShader(type);
91
+ gl.shaderSource(s, src);
92
+ gl.compileShader(s);
93
+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
94
+ throw new Error(gl.getShaderInfoLog(s));
95
+ }
96
+ return s;
97
+ }
98
+
99
+ function linkProgram(vertSrc, fragSrc) {
100
+ const v = compile(gl.VERTEX_SHADER, vertSrc);
101
+ const f = compile(gl.FRAGMENT_SHADER, fragSrc);
102
+ const prog = gl.createProgram();
103
+ gl.attachShader(prog, v);
104
+ gl.attachShader(prog, f);
105
+ gl.linkProgram(prog);
106
+ gl.deleteShader(v);
107
+ gl.deleteShader(f);
108
+ if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
109
+ const info = gl.getProgramInfoLog(prog);
110
+ gl.deleteProgram(prog);
111
+ throw new Error(info);
112
+ }
113
+ return prog;
114
+ }
115
+
116
+ function getLoc(prog, cache, name) {
117
+ if (cache.has(name)) return cache.get(name);
118
+ const loc = gl.getUniformLocation(prog, name);
119
+ cache.set(name, loc);
120
+ return loc;
121
+ }
122
+
123
+ function applyUniform(prog, cache, name, val) {
124
+ const loc = getLoc(prog, cache, name);
125
+ if (!loc) return;
126
+ if (typeof val === 'number') {
127
+ gl.uniform1f(loc, val);
128
+ } else if (val.length === 2) {
129
+ gl.uniform2f(loc, val[0], val[1]);
130
+ } else if (val.length === 3) {
131
+ gl.uniform3f(loc, val[0], val[1], val[2]);
132
+ } else if (val.length === 4) {
133
+ gl.uniform4f(loc, val[0], val[1], val[2], val[3]);
134
+ }
135
+ }
136
+
137
+ function computeFboDims(canvasW, canvasH) {
138
+ let w = Math.max(1, Math.floor(canvasW * feedbackScale));
139
+ let h = Math.max(1, Math.floor(canvasH * feedbackScale));
140
+ // Cap longest edge so 4K/5K Retina screens stay locked at 60/120 FPS
141
+ const longest = Math.max(w, h);
142
+ if (longest > feedbackMaxDim) {
143
+ const ratio = feedbackMaxDim / longest;
144
+ w = Math.max(1, Math.floor(w * ratio));
145
+ h = Math.max(1, Math.floor(h * ratio));
146
+ }
147
+ return [w, h];
148
+ }
149
+
150
+ function destroyPingPong() {
151
+ if (!pingPong || !gl) {
152
+ pingPong = null;
153
+ return;
154
+ }
155
+ for (let i = 0; i < pingPong.length; i++) {
156
+ gl.deleteFramebuffer(pingPong[i].fbo);
157
+ gl.deleteTexture(pingPong[i].tex);
158
+ }
159
+ pingPong = null;
160
+ }
161
+
162
+ function createPingPong(canvasW, canvasH) {
163
+ destroyPingPong();
164
+ if (!savedFeedbackSrc || !gl || contextLost) return;
165
+
166
+ const dims = computeFboDims(canvasW, canvasH);
167
+ fboW = dims[0];
168
+ fboH = dims[1];
169
+
170
+ let internalFormat = gl.RGBA8;
171
+ let texType = gl.UNSIGNED_BYTE;
172
+ const canFloat =
173
+ feedbackFloat &&
174
+ (gl.getExtension('EXT_color_buffer_float') ||
175
+ gl.getExtension('EXT_color_buffer_half_float'));
176
+
177
+ if (canFloat) {
178
+ internalFormat = gl.RGBA16F;
179
+ texType = gl.HALF_FLOAT;
180
+ }
181
+
182
+ function buildPair(intFmt, type) {
183
+ const pair = [];
184
+ for (let i = 0; i < 2; i++) {
185
+ const tex = gl.createTexture();
186
+ gl.bindTexture(gl.TEXTURE_2D, tex);
187
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
188
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
189
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
190
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
191
+ gl.texImage2D(gl.TEXTURE_2D, 0, intFmt, fboW, fboH, 0, gl.RGBA, type, null);
192
+
193
+ const fbo = gl.createFramebuffer();
194
+ gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
195
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
196
+
197
+ if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) {
198
+ gl.deleteFramebuffer(fbo);
199
+ gl.deleteTexture(tex);
200
+ for (let j = 0; j < pair.length; j++) {
201
+ gl.deleteFramebuffer(pair[j].fbo);
202
+ gl.deleteTexture(pair[j].tex);
203
+ }
204
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
205
+ gl.bindTexture(gl.TEXTURE_2D, null);
206
+ return null;
207
+ }
208
+
209
+ gl.clearColor(0, 0, 0, 0);
210
+ gl.clear(gl.COLOR_BUFFER_BIT);
211
+ pair.push({ fbo, tex });
212
+ }
213
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
214
+ gl.bindTexture(gl.TEXTURE_2D, null);
215
+ return pair;
216
+ }
217
+
218
+ let pair = buildPair(internalFormat, texType);
219
+ if (!pair && internalFormat !== gl.RGBA8) {
220
+ internalFormat = gl.RGBA8;
221
+ texType = gl.UNSIGNED_BYTE;
222
+ pair = buildPair(internalFormat, texType);
223
+ }
224
+
225
+ fboFormat = internalFormat;
226
+ fboType = texType;
227
+ pingPong = pair;
228
+ readIdx = 0;
229
+ writeIdx = 1;
230
+ }
231
+
232
+ function resizePingPong(canvasW, canvasH) {
233
+ if (!pingPong || !gl || contextLost) return;
234
+ const dims = computeFboDims(canvasW, canvasH);
235
+ const nw = dims[0];
236
+ const nh = dims[1];
237
+ if (nw === fboW && nh === fboH) return;
238
+
239
+ fboW = nw;
240
+ fboH = nh;
241
+ for (let i = 0; i < 2; i++) {
242
+ gl.bindTexture(gl.TEXTURE_2D, pingPong[i].tex);
243
+ gl.texImage2D(gl.TEXTURE_2D, 0, fboFormat, fboW, fboH, 0, gl.RGBA, fboType, null);
244
+ gl.bindFramebuffer(gl.FRAMEBUFFER, pingPong[i].fbo);
245
+ gl.clearColor(0, 0, 0, 0);
246
+ gl.clear(gl.COLOR_BUFFER_BIT);
247
+ }
248
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
249
+ gl.bindTexture(gl.TEXTURE_2D, null);
250
+ }
251
+
252
+ function applySize() {
253
+ if (!canvas || !gl || contextLost) return;
254
+ const w = Math.max(1, Math.round(width * dprScale));
255
+ const h = Math.max(1, Math.round(height * dprScale));
256
+ if (canvas.width !== w || canvas.height !== h) {
257
+ canvas.width = w;
258
+ canvas.height = h;
259
+ gl.viewport(0, 0, w, h);
260
+ if (pingPong) {
261
+ resizePingPong(w, h);
262
+ }
263
+ }
264
+ }
265
+
266
+ function buildGLPipeline() {
267
+ displayLocs.clear();
268
+ feedbackLocs.clear();
269
+ gl.getExtension('KHR_parallel_shader_compile');
270
+
271
+ displayProgram = linkProgram(savedVertexSrc, savedFragmentSrc);
272
+ if (savedFeedbackSrc) {
273
+ feedbackProgram = linkProgram(savedVertexSrc, savedFeedbackSrc);
274
+ }
275
+
276
+ vao = gl.createVertexArray();
277
+ gl.bindVertexArray(vao);
278
+ vbo = gl.createBuffer();
279
+ gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
280
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
281
+ gl.enableVertexAttribArray(0);
282
+ gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
283
+ gl.bindVertexArray(null);
284
+
285
+ needsResize = false;
286
+ applySize();
287
+ if (savedFeedbackSrc) {
288
+ createPingPong(canvas.width, canvas.height);
289
+ }
290
+ }
291
+
292
+ function bindCommonUniforms(prog, cache, resW, resH) {
293
+ const tLoc = getLoc(prog, cache, 'uTime');
294
+ if (tLoc) gl.uniform1f(tLoc, elapsedSec);
295
+
296
+ const dLoc = getLoc(prog, cache, 'uDelta');
297
+ if (dLoc) gl.uniform1f(dLoc, lastDeltaSec);
298
+
299
+ const rLoc = getLoc(prog, cache, 'uResolution');
300
+ if (rLoc) gl.uniform2f(rLoc, resW, resH);
301
+
302
+ const crLoc = getLoc(prog, cache, 'uCanvasResolution');
303
+ if (crLoc) gl.uniform2f(crLoc, canvas.width, canvas.height);
304
+
305
+ const dprLoc = getLoc(prog, cache, 'uDpr');
306
+ if (dprLoc) gl.uniform1f(dprLoc, dprScale);
307
+
308
+ const mLoc = getLoc(prog, cache, 'uMouse');
309
+ if (mLoc) gl.uniform2f(mLoc, mouse[0], mouse[1]);
310
+
311
+ const mvLoc = getLoc(prog, cache, 'uMouseVel');
312
+ if (mvLoc) gl.uniform2f(mvLoc, mouseVel[0], mouseVel[1]);
313
+
314
+ const mdLoc = getLoc(prog, cache, 'uMouseDown');
315
+ if (mdLoc) gl.uniform1f(mdLoc, mouseDown);
316
+
317
+ const maLoc = getLoc(prog, cache, 'uMouseActive');
318
+ if (maLoc) gl.uniform1f(maLoc, mouseActive);
319
+
320
+ const sLoc = getLoc(prog, cache, 'uScroll');
321
+ if (sLoc) gl.uniform1f(sLoc, scrollProgress);
322
+
323
+ const svLoc = getLoc(prog, cache, 'uScrollVel');
324
+ if (svLoc) gl.uniform1f(svLoc, scrollVel);
325
+
326
+ customUniforms.forEach((val, key) => {
327
+ if (key === 'uSpeed') {
328
+ applyUniform(prog, cache, 'uSpeed', currentSpeed);
329
+ } else {
330
+ applyUniform(prog, cache, key, val);
331
+ }
332
+ });
333
+ }
334
+
335
+ function drawFrame() {
336
+ if (!gl || !displayProgram || contextLost) return;
337
+
338
+ gl.bindVertexArray(vao);
339
+
340
+ if (feedbackProgram && pingPong) {
341
+ gl.bindFramebuffer(gl.FRAMEBUFFER, pingPong[writeIdx].fbo);
342
+ gl.viewport(0, 0, fboW, fboH);
343
+ gl.useProgram(feedbackProgram);
344
+
345
+ gl.activeTexture(gl.TEXTURE0);
346
+ gl.bindTexture(gl.TEXTURE_2D, pingPong[readIdx].tex);
347
+ const prevLoc = getLoc(feedbackProgram, feedbackLocs, 'uPrevFrame');
348
+ if (prevLoc) gl.uniform1i(prevLoc, 0);
349
+
350
+ bindCommonUniforms(feedbackProgram, feedbackLocs, fboW, fboH);
351
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
352
+
353
+ const tmp = readIdx;
354
+ readIdx = writeIdx;
355
+ writeIdx = tmp;
356
+
357
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
358
+ gl.viewport(0, 0, canvas.width, canvas.height);
359
+ }
360
+
361
+ gl.useProgram(displayProgram);
362
+ if (pingPong) {
363
+ gl.activeTexture(gl.TEXTURE0);
364
+ gl.bindTexture(gl.TEXTURE_2D, pingPong[readIdx].tex);
365
+ const fbLoc = getLoc(displayProgram, displayLocs, 'uFeedback');
366
+ if (fbLoc) gl.uniform1i(fbLoc, 0);
367
+ const pfLoc = getLoc(displayProgram, displayLocs, 'uPrevFrame');
368
+ if (pfLoc) gl.uniform1i(pfLoc, 0);
369
+ }
370
+
371
+ bindCommonUniforms(displayProgram, displayLocs, canvas.width, canvas.height);
372
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
373
+ }
374
+
375
+ function updateDynamicRes(delta, now) {
376
+ if (!dynamicRes || minScale >= baseDpr || delta <= 0 || delta > 60) return false;
377
+ frameSamples[sampleIdx] = delta;
378
+ sampleIdx = (sampleIdx + 1) % frameSamples.length;
379
+ if (sampleCount < frameSamples.length) {
380
+ sampleCount++;
381
+ return false;
382
+ }
383
+ if (now - lastAdjust < 750) return false;
384
+
385
+ let sum = 0;
386
+ for (let i = 0; i < frameSamples.length; i++) sum += frameSamples[i];
387
+ const avg = sum / frameSamples.length;
388
+
389
+ if (avg > 20.5 && dprScale > minScale) {
390
+ dprScale = Math.max(minScale, Number((dprScale - 0.15).toFixed(2)));
391
+ stableWindows = 0;
392
+ lastAdjust = now;
393
+ return true;
394
+ } else if (avg < 17.2 && dprScale < baseDpr) {
395
+ stableWindows++;
396
+ if (stableWindows >= 2) {
397
+ dprScale = Math.min(baseDpr, Number((dprScale + 0.1).toFixed(2)));
398
+ stableWindows = 0;
399
+ lastAdjust = now;
400
+ return true;
401
+ }
402
+ } else {
403
+ stableWindows = 0;
404
+ }
405
+ return false;
406
+ }
407
+
408
+ function stopLoop() {
409
+ running = false;
410
+ cancelFrame(rafId);
411
+ rafId = 0;
412
+ lastFrameTime = 0;
413
+ }
414
+
415
+ function startLoopIfAllowed() {
416
+ if (running || pausedByHost || reducedMotion || contextLost || !gl) return;
417
+ running = true;
418
+ lastFrameTime = 0;
419
+ rafId = scheduleFrame(render);
420
+ }
421
+
422
+ function render(now) {
423
+ 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));
427
+ lastDeltaSec = dt;
428
+
429
+ // Smoothly ramp speed and integrate phase time (zero jump when speed changes)
430
+ currentSpeed += (targetSpeed - currentSpeed) * damp(7.5, dt);
431
+ elapsedSec += dt * currentSpeed;
432
+
433
+ const dprChanged = updateDynamicRes(delta, now);
434
+ if (needsResize || dprChanged) {
435
+ needsResize = false;
436
+ applySize();
437
+ }
438
+
439
+ // Frame-rate independent hover fade & pointer tracking
440
+ mouseActive += (targetMouseActive - mouseActive) * damp(7.0, dt);
441
+ if (mouseActive < 0.001 && targetMouseActive === 0) mouseActive = 0;
442
+
443
+ if (targetMouseActive > 0.5) {
444
+ const prevMx = mouse[0];
445
+ const prevMy = mouse[1];
446
+ const mAlpha = damp(13.0, dt);
447
+ mouse[0] += (targetMouse[0] - mouse[0]) * mAlpha;
448
+ mouse[1] += (targetMouse[1] - mouse[1]) * mAlpha;
449
+ mouseVel[0] = Math.max(-8, Math.min(8, (mouse[0] - prevMx) / dt));
450
+ mouseVel[1] = Math.max(-8, Math.min(8, (mouse[1] - prevMy) / dt));
451
+ } else {
452
+ mouseVel[0] = 0;
453
+ mouseVel[1] = 0;
454
+ }
455
+
456
+ const prevS = scrollProgress;
457
+ scrollProgress += (targetScroll - scrollProgress) * damp(9.5, dt);
458
+ scrollVel = Math.max(-6, Math.min(6, (scrollProgress - prevS) / dt));
459
+
460
+ drawFrame();
461
+
462
+ rafId = scheduleFrame(render);
463
+ }
464
+
465
+ function onContextLost(e) {
466
+ e.preventDefault();
467
+ contextLost = true;
468
+ stopLoop();
469
+ pingPong = null;
470
+ displayProgram = null;
471
+ feedbackProgram = null;
472
+ }
473
+
474
+ function onContextRestored() {
475
+ if (!gl) return;
476
+ try {
477
+ contextLost = false;
478
+ buildGLPipeline();
479
+ drawFrame();
480
+ if (!reducedMotion) {
481
+ startLoopIfAllowed();
482
+ }
483
+ } catch (err) {
484
+ self.postMessage({ type: 'error', message: 'Context restore failed: ' + String(err) });
485
+ }
486
+ }
487
+
488
+ self.onmessage = function(e) {
489
+ const msg = e.data;
490
+ switch (msg.type) {
491
+ case 'init': {
492
+ try {
493
+ canvas = msg.canvas;
494
+ width = msg.width;
495
+ height = msg.height;
496
+ baseDpr = msg.maxDpr;
497
+ dprScale = baseDpr;
498
+ minScale = msg.minDpr;
499
+ dynamicRes = msg.dynamicRes;
500
+ reducedMotion = !!msg.reducedMotion;
501
+ savedVertexSrc = msg.vertexShader;
502
+ savedFragmentSrc = msg.fragmentShader;
503
+ savedFeedbackSrc = msg.feedbackShader || null;
504
+ feedbackScale = msg.feedbackScale ?? 0.5;
505
+ feedbackMaxDim = msg.feedbackMaxDim ?? 896;
506
+ feedbackFloat = msg.feedbackFloat !== false;
507
+ scrollProgress = msg.initialScroll ?? 0;
508
+ targetScroll = scrollProgress;
509
+
510
+ canvas.addEventListener('webglcontextlost', onContextLost, false);
511
+ canvas.addEventListener('webglcontextrestored', onContextRestored, false);
512
+
513
+ gl = canvas.getContext('webgl2', {
514
+ alpha: true,
515
+ antialias: false,
516
+ depth: false,
517
+ stencil: false,
518
+ powerPreference: 'high-performance',
519
+ preserveDrawingBuffer: false
520
+ });
521
+
522
+ if (!gl) {
523
+ self.postMessage({ type: 'error', message: 'WebGL2 unavailable in worker' });
524
+ return;
525
+ }
526
+
527
+ if (msg.uniforms) {
528
+ for (const k in msg.uniforms) {
529
+ customUniforms.set(k, msg.uniforms[k]);
530
+ if (k === 'uSpeed' && typeof msg.uniforms[k] === 'number') {
531
+ currentSpeed = msg.uniforms[k];
532
+ targetSpeed = msg.uniforms[k];
533
+ }
534
+ }
535
+ }
536
+
537
+ buildGLPipeline();
538
+
539
+ drawFrame();
540
+ if (!reducedMotion) {
541
+ startLoopIfAllowed();
542
+ }
543
+ } catch (err) {
544
+ self.postMessage({ type: 'error', message: String(err) });
545
+ }
546
+ break;
547
+ }
548
+ case 'resize':
549
+ width = msg.width;
550
+ height = msg.height;
551
+ if (reducedMotion && !pausedByHost && !contextLost) {
552
+ needsResize = false;
553
+ applySize();
554
+ drawFrame();
555
+ } else {
556
+ needsResize = true;
557
+ }
558
+ break;
559
+ case 'dprBounds':
560
+ minScale = msg.minDpr;
561
+ baseDpr = msg.maxDpr;
562
+ dprScale = baseDpr;
563
+ sampleCount = 0;
564
+ sampleIdx = 0;
565
+ stableWindows = 0;
566
+ if (reducedMotion && !pausedByHost && !contextLost) {
567
+ needsResize = false;
568
+ applySize();
569
+ drawFrame();
570
+ } else {
571
+ needsResize = true;
572
+ }
573
+ break;
574
+ case 'mouseEnter':
575
+ mouse[0] = msg.x;
576
+ mouse[1] = msg.y;
577
+ targetMouse[0] = msg.x;
578
+ targetMouse[1] = msg.y;
579
+ mouseVel[0] = 0;
580
+ mouseVel[1] = 0;
581
+ targetMouseActive = 1;
582
+ break;
583
+ case 'mouse':
584
+ targetMouse[0] = msg.x;
585
+ targetMouse[1] = msg.y;
586
+ targetMouseActive = 1;
587
+ break;
588
+ case 'mouseLeave':
589
+ targetMouseActive = 0;
590
+ mouseDown = 0;
591
+ mouseVel[0] = 0;
592
+ mouseVel[1] = 0;
593
+ break;
594
+ case 'mouseDown':
595
+ mouseDown = msg.down ? 1 : 0;
596
+ break;
597
+ case 'scroll':
598
+ targetScroll = msg.progress;
599
+ if (reducedMotion && !pausedByHost && !contextLost) {
600
+ scrollProgress = targetScroll;
601
+ scrollVel = 0;
602
+ drawFrame();
603
+ }
604
+ break;
605
+ case 'uniform':
606
+ customUniforms.set(msg.name, msg.value);
607
+ if (msg.name === 'uSpeed' && typeof msg.value === 'number') {
608
+ targetSpeed = msg.value;
609
+ }
610
+ if (reducedMotion && !contextLost) drawFrame();
611
+ break;
612
+ case 'uniformsBatch':
613
+ if (msg.uniforms) {
614
+ for (const k in msg.uniforms) {
615
+ customUniforms.set(k, msg.uniforms[k]);
616
+ if (k === 'uSpeed' && typeof msg.uniforms[k] === 'number') {
617
+ targetSpeed = msg.uniforms[k];
618
+ }
619
+ }
620
+ }
621
+ if (reducedMotion && !contextLost) drawFrame();
622
+ break;
623
+ case 'reducedMotion':
624
+ reducedMotion = !!msg.value;
625
+ if (reducedMotion) {
626
+ stopLoop();
627
+ if (needsResize) {
628
+ needsResize = false;
629
+ applySize();
630
+ }
631
+ drawFrame();
632
+ } else {
633
+ startLoopIfAllowed();
634
+ }
635
+ break;
636
+ case 'renderOnce':
637
+ if (needsResize) {
638
+ needsResize = false;
639
+ applySize();
640
+ }
641
+ drawFrame();
642
+ break;
643
+ case 'pause':
644
+ pausedByHost = true;
645
+ stopLoop();
646
+ break;
647
+ case 'resume':
648
+ pausedByHost = false;
649
+ if (reducedMotion) {
650
+ if (needsResize) {
651
+ needsResize = false;
652
+ applySize();
653
+ }
654
+ drawFrame();
655
+ } else {
656
+ startLoopIfAllowed();
657
+ }
658
+ break;
659
+ case 'destroy':
660
+ stopLoop();
661
+ if (canvas) {
662
+ canvas.removeEventListener('webglcontextlost', onContextLost, false);
663
+ canvas.removeEventListener('webglcontextrestored', onContextRestored, false);
664
+ }
665
+ if (gl) {
666
+ destroyPingPong();
667
+ if (displayProgram) gl.deleteProgram(displayProgram);
668
+ if (feedbackProgram) gl.deleteProgram(feedbackProgram);
669
+ if (vbo) gl.deleteBuffer(vbo);
670
+ if (vao) gl.deleteVertexArray(vao);
671
+ gl.getExtension('WEBGL_lose_context')?.loseContext();
672
+ }
673
+ gl = null;
674
+ canvas = null;
675
+ self.close();
676
+ break;
677
+ }
678
+ };
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
680
+ precision highp float;
681
+
682
+ in vec2 vUv;
683
+ out vec4 fragColor;
684
+
685
+ uniform float uTime;
686
+ uniform vec2 uResolution;
687
+ uniform vec2 uMouse;
688
+ uniform float uMouseActive;
689
+ uniform vec3 uColor1;
690
+ uniform vec3 uColor2;
691
+ uniform vec3 uColor3;
692
+
693
+ float hash(vec2 p) {
694
+ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123);
695
+ }
696
+
697
+ float noise(vec2 p) {
698
+ vec2 i = floor(p);
699
+ vec2 f = fract(p);
700
+ vec2 u = f * f * (3.0 - 2.0 * f);
701
+ return mix(
702
+ mix(hash(i + vec2(0.0, 0.0)), hash(i + vec2(1.0, 0.0)), u.x),
703
+ mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), u.x),
704
+ u.y
705
+ );
706
+ }
707
+
708
+ float fbm(vec2 p) {
709
+ float value = 0.0;
710
+ float amp = 0.5;
711
+ mat2 rot = mat2(0.8, 0.6, -0.6, 0.8);
712
+ for (int i = 0; i < 4; i++) {
713
+ value += amp * noise(p);
714
+ p = rot * p * 2.02;
715
+ amp *= 0.5;
716
+ }
717
+ return value;
718
+ }
719
+
720
+ void main() {
721
+ vec2 uv = vUv;
722
+ float aspect = uResolution.x / max(uResolution.y, 1.0);
723
+ vec2 p = (uv - 0.5) * vec2(aspect, 1.0);
724
+
725
+ vec2 m = (uMouse - 0.5) * vec2(aspect, 1.0);
726
+ float mouseDist = length(p - m);
727
+ p += normalize(p - m + 0.0001) * exp(-mouseDist * 2.5) * 0.08 * uMouseActive;
728
+
729
+ float t = uTime * 0.25;
730
+
731
+ vec2 q = vec2(fbm(p * 1.4 + vec2(t, -t * 0.5)), fbm(p * 1.4 + vec2(-t * 0.6, t * 0.4)));
732
+ float f = fbm(p * 1.8 + 1.6 * q + vec2(t * 0.3, 0.0));
733
+
734
+ float ribbon1 = smoothstep(0.15, 0.85, sin(p.y * 3.0 + f * 4.5 + t) * 0.5 + 0.5);
735
+ float ribbon2 = smoothstep(0.2, 0.9, cos(p.x * 2.2 - f * 3.8 - t * 1.2) * 0.5 + 0.5);
736
+
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;
743
+ float grain = (hash(gl_FragCoord.xy + fract(uTime)) - 0.5) * 0.02;
744
+ col = col * vig + grain;
745
+
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
748
+ precision highp float;
749
+
750
+ in vec2 vUv;
751
+ out vec4 fragColor;
752
+
753
+ uniform float uTime;
754
+ uniform vec2 uResolution;
755
+ uniform vec2 uMouse;
756
+ uniform float uMouseActive;
757
+ uniform vec3 uColor1;
758
+ uniform vec3 uColor2;
759
+ uniform vec3 uColor3;
760
+
761
+ float field(vec2 p, float t) {
762
+ for (int i = 1; i < 6; i++) {
763
+ float fi = float(i);
764
+ p.x += 0.35 / fi * sin(fi * 2.2 * p.y + t + 0.4 * fi);
765
+ p.y += 0.35 / fi * cos(fi * 2.2 * p.x + t * 0.9 + 0.3 * fi);
766
+ }
767
+ return sin(p.x + p.y) * 0.5 + 0.5;
768
+ }
769
+
770
+ void main() {
771
+ float aspect = uResolution.x / max(uResolution.y, 1.0);
772
+ vec2 p = (vUv - 0.5) * vec2(aspect, 1.0) * 1.8;
773
+ vec2 m = (uMouse - 0.5) * vec2(aspect, 1.0) * 1.8;
774
+
775
+ float d = length(p - m);
776
+ p += (p - m) * sin(d * 8.0 - uTime * 3.0) * exp(-d * 1.8) * 0.14 * uMouseActive;
777
+
778
+ float t = uTime * 0.55;
779
+
780
+ float eps = 0.012;
781
+ float h = field(p, t);
782
+ float hx = field(p + vec2(eps, 0.0), t);
783
+ float hy = field(p + vec2(0.0, eps), t);
784
+
785
+ vec3 normal = normalize(vec3((h - hx) * 10.0, (h - hy) * 10.0, 1.0));
786
+ vec3 lightDir = normalize(vec3(0.4, 0.6, 0.85));
787
+ vec3 viewDir = vec3(0.0, 0.0, 1.0);
788
+ vec3 halfVec = normalize(lightDir + viewDir);
789
+
790
+ float diff = max(dot(normal, lightDir), 0.0);
791
+ float spec = pow(max(dot(normal, halfVec), 0.0), 28.0);
792
+ float fresnel = pow(1.0 - max(dot(normal, viewDir), 0.0), 3.0);
793
+
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;
798
+
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
801
+ precision highp float;
802
+
803
+ in vec2 vUv;
804
+ out vec4 fragColor;
805
+
806
+ uniform sampler2D uPrevFrame;
807
+ uniform float uTime;
808
+ uniform float uDelta;
809
+ uniform vec2 uResolution;
810
+ uniform vec2 uMouse;
811
+ uniform vec2 uMouseVel;
812
+ uniform float uMouseDown;
813
+ uniform float uMouseActive;
814
+ uniform float uSpeed;
815
+ uniform float uDissipation;
816
+ uniform float uRadius;
817
+ uniform float uSwirl;
818
+
819
+ vec2 decodeVel(vec4 s) {
820
+ if (s.r < 0.01 && s.g < 0.01) return vec2(0.0);
821
+ return (s.rg - 0.5) * 2.0;
822
+ }
823
+
824
+ void main() {
825
+ vec2 texel = 1.0 / max(uResolution, vec2(1.0));
826
+ float dt = clamp(uDelta, 0.004, 0.033);
827
+ float aspect = uResolution.x / max(uResolution.y, 1.0);
828
+
829
+ vec4 center = texture(uPrevFrame, vUv);
830
+ vec4 left = texture(uPrevFrame, vUv - vec2(texel.x, 0.0));
831
+ vec4 right = texture(uPrevFrame, vUv + vec2(texel.x, 0.0));
832
+ vec4 down = texture(uPrevFrame, vUv - vec2(0.0, texel.y));
833
+ vec4 up = texture(uPrevFrame, vUv + vec2(0.0, texel.y));
834
+
835
+ vec2 vel = decodeVel(center);
836
+ vec2 vL = decodeVel(left);
837
+ vec2 vR = decodeVel(right);
838
+ vec2 vD = decodeVel(down);
839
+ vec2 vU = decodeVel(up);
840
+
841
+ float curl = (vR.y - vL.y) - (vU.x - vD.x);
842
+ vec2 curlGrad = vec2(abs(vU.y) - abs(vD.y), abs(vR.x) - abs(vL.x));
843
+ vec2 swirlDir = normalize(curlGrad + vec2(0.0001));
844
+ vel += vec2(swirlDir.y, -swirlDir.x) * curl * uSwirl * dt * 1.4;
845
+
846
+ vec2 advUv = clamp(vUv - vel * dt * 0.55 * clamp(uSpeed, 0.25, 3.0), texel, 1.0 - texel);
847
+ vec4 adv = texture(uPrevFrame, advUv);
848
+ vec2 advVel = decodeVel(adv);
849
+
850
+ vec2 avgVel = (vL + vR + vD + vU) * 0.25;
851
+ vec2 avgDye = (left.ba + right.ba + down.ba + up.ba) * 0.25;
852
+
853
+ vel = mix(advVel, avgVel, 0.08);
854
+ vec2 dye = mix(adv.ba, avgDye, 0.045);
855
+
856
+ float velDecay = pow(clamp(uDissipation, 0.90, 0.996), dt * 60.0);
857
+ float dyeDecay = pow(clamp(uDissipation + 0.008, 0.92, 0.998), dt * 60.0);
858
+ vel *= velDecay;
859
+ dye *= dyeDecay;
860
+
861
+ // Subtle autonomous emitter (uTime is already smoothly speed-integrated)
862
+ float t = uTime * 0.55;
863
+ vec2 autoPos = vec2(
864
+ 0.5 + 0.28 * cos(t * 0.9) * sin(t * 0.4),
865
+ 0.5 + 0.24 * sin(t * 1.1)
866
+ );
867
+ vec2 autoDir = vec2(-sin(t * 0.9), cos(t * 1.1)) * 0.32;
868
+ vec2 diffAuto = (vUv - autoPos) * vec2(aspect, 1.0);
869
+ float autoMask = exp(-dot(diffAuto, diffAuto) / max(uRadius * 1.35, 0.002));
870
+ vel += autoDir * autoMask * dt * 4.5;
871
+ dye.x += autoMask * (0.5 + 0.5 * sin(t)) * dt * 1.1;
872
+ dye.y += autoMask * (0.5 + 0.5 * cos(t * 1.3)) * dt * 1.1;
873
+
874
+ if (uMouseActive > 0.01) {
875
+ vec2 diff = (vUv - uMouse) * vec2(aspect, 1.0);
876
+ float distSq = dot(diff, diff);
877
+ float splat = exp(-distSq / max(uRadius, 0.001));
878
+
879
+ float mSpeed = length(uMouseVel);
880
+ if (mSpeed > 0.002) {
881
+ vec2 impulse = clamp(uMouseVel, vec2(-3.5), vec2(3.5));
882
+ vel += impulse * splat * 0.48;
883
+ float inject = min(mSpeed * 0.42, 1.0) * splat;
884
+ float phase = 0.5 + 0.5 * sin(uTime * 1.4);
885
+ dye.x += inject * (0.45 + 0.55 * phase);
886
+ dye.y += inject * (0.45 + 0.55 * (1.0 - phase));
887
+ }
888
+
889
+ if (uMouseDown > 0.5) {
890
+ vec2 radial = normalize(diff + vec2(0.0001));
891
+ float burst = exp(-distSq / max(uRadius * 2.2, 0.003));
892
+ vel += radial * burst * 0.85 * dt * 14.0;
893
+ dye += vec2(0.75, 0.95) * burst * dt * 6.5;
894
+ }
895
+ }
896
+
897
+ vel = clamp(vel, vec2(-0.96), vec2(0.96));
898
+ vec2 encodedVel = clamp(vel * 0.5 + 0.5, vec2(0.02), vec2(0.98));
899
+ dye = clamp(dye, vec2(0.0), vec2(1.0));
900
+
901
+ fragColor = vec4(encodedVel, dye);
902
+ }`,we=`#version 300 es
903
+ precision highp float;
904
+
905
+ in vec2 vUv;
906
+ out vec4 fragColor;
907
+
908
+ uniform sampler2D uFeedback;
909
+ uniform float uTime;
910
+ uniform vec2 uResolution;
911
+ uniform vec3 uColor1;
912
+ uniform vec3 uColor2;
913
+ uniform vec3 uColor3;
914
+
915
+ float hash(vec2 p) {
916
+ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123);
917
+ }
918
+
919
+ void main() {
920
+ // Sample gradients using actual FBO texture resolution (eliminates Retina specular banding)
921
+ vec2 fboTexel = 1.0 / max(vec2(textureSize(uFeedback, 0)), vec2(1.0));
922
+ vec4 state = texture(uFeedback, vUv);
923
+
924
+ vec2 vel = (state.r < 0.01 && state.g < 0.01) ? vec2(0.0) : (state.rg - 0.5) * 2.0;
925
+ float dyeA = state.b;
926
+ float dyeB = state.a;
927
+ float density = clamp(dyeA + dyeB * 0.85, 0.0, 1.35);
928
+
929
+ float hL = dot(texture(uFeedback, vUv - vec2(fboTexel.x, 0.0)).ba, vec2(1.0));
930
+ float hR = dot(texture(uFeedback, vUv + vec2(fboTexel.x, 0.0)).ba, vec2(1.0));
931
+ float hD = dot(texture(uFeedback, vUv - vec2(0.0, fboTexel.y)).ba, vec2(1.0));
932
+ float hU = dot(texture(uFeedback, vUv + vec2(0.0, fboTexel.y)).ba, vec2(1.0));
933
+
934
+ vec3 normal = normalize(vec3((hL - hR) * 2.4, (hD - hU) * 2.4, 1.0));
935
+ vec3 lightDir = normalize(vec3(0.35, 0.65, 0.8));
936
+ float spec = pow(max(dot(normal, lightDir), 0.0), 20.0) * smoothstep(0.08, 0.6, density);
937
+
938
+ 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;
946
+
947
+ float vig = 1.0 - dot(vUv - 0.5, vUv - 0.5) * 0.65;
948
+ float grain = (hash(gl_FragCoord.xy + fract(uTime)) - 0.5) * 0.015;
949
+ col = max(col * vig + grain, vec3(0.0));
950
+
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
953
+ precision highp float;
954
+
955
+ in vec2 vUv;
956
+ out vec4 fragColor;
957
+
958
+ uniform sampler2D uPrevFrame;
959
+ uniform float uTime;
960
+ uniform float uDelta;
961
+ uniform vec2 uResolution;
962
+ uniform vec2 uMouse;
963
+ uniform vec2 uMouseVel;
964
+ uniform float uMouseDown;
965
+ uniform float uMouseActive;
966
+ uniform float uSpeed;
967
+ uniform float uDissipation;
968
+ uniform float uRadius;
969
+ uniform float uCurl;
970
+
971
+ vec2 decodeVel(vec4 s) {
972
+ if (s.r < 0.01 && s.g < 0.01) return vec2(0.0);
973
+ return (s.rg - 0.5) * 2.0;
974
+ }
975
+
976
+ void main() {
977
+ vec2 texel = 1.0 / max(uResolution, vec2(1.0));
978
+ float dt = clamp(uDelta, 0.004, 0.033);
979
+ float aspect = uResolution.x / max(uResolution.y, 1.0);
980
+
981
+ vec4 c = texture(uPrevFrame, vUv);
982
+ vec4 l = texture(uPrevFrame, vUv - vec2(texel.x, 0.0));
983
+ vec4 r = texture(uPrevFrame, vUv + vec2(texel.x, 0.0));
984
+ vec4 d = texture(uPrevFrame, vUv - vec2(0.0, texel.y));
985
+ vec4 u = texture(uPrevFrame, vUv + vec2(0.0, texel.y));
986
+
987
+ vec2 vel = decodeVel(c);
988
+ vec2 vL = decodeVel(l);
989
+ vec2 vR = decodeVel(r);
990
+ vec2 vD = decodeVel(d);
991
+ vec2 vU = decodeVel(u);
992
+
993
+ // Vorticity confinement for wispy ink tendrils in still water
994
+ float vorticity = (vR.y - vL.y) - (vU.x - vD.x);
995
+ vec2 grad = vec2(abs(vU.y) - abs(vD.y), abs(vR.x) - abs(vL.x));
996
+ vec2 perp = normalize(grad + vec2(0.0001));
997
+ vel += vec2(perp.y, -perp.x) * vorticity * uCurl * dt * 1.65;
998
+
999
+ // Advect velocity & ink pigments backward along flow
1000
+ vec2 backUv = clamp(vUv - vel * dt * 0.48 * clamp(uSpeed, 0.25, 3.0), texel, 1.0 - texel);
1001
+ vec4 adv = texture(uPrevFrame, backUv);
1002
+ vec2 advVel = decodeVel(adv);
1003
+
1004
+ // Water viscosity: velocity damps faster than suspended ink pigments
1005
+ float visc = pow(clamp(uDissipation * 0.985, 0.88, 0.992), dt * 60.0);
1006
+ float inkHold = pow(clamp(uDissipation + 0.006, 0.92, 0.998), dt * 60.0);
1007
+
1008
+ vel = mix(advVel, (vL + vR + vD + vU) * 0.25, 0.07) * visc;
1009
+ vec2 ink = mix(adv.ba, (l.ba + r.ba + d.ba + u.ba) * 0.25, 0.035) * inkHold;
1010
+
1011
+ // Gentle ambient ink drift so canvas feels alive before pointer interaction
1012
+ float t = uTime * 0.42;
1013
+ vec2 driftPos = vec2(
1014
+ 0.5 + 0.25 * sin(t * 0.85),
1015
+ 0.5 + 0.22 * cos(t * 0.65 + 0.7)
1016
+ );
1017
+ vec2 driftVel = vec2(cos(t * 0.85), -sin(t * 0.65 + 0.7)) * 0.24;
1018
+ vec2 pDrift = (vUv - driftPos) * vec2(aspect, 1.0);
1019
+ float driftSplat = exp(-dot(pDrift, pDrift) / max(uRadius * 1.4, 0.002));
1020
+ vel += driftVel * driftSplat * dt * 3.5;
1021
+ ink.x += driftSplat * (0.45 + 0.45 * sin(t * 1.2)) * dt * 0.85;
1022
+ ink.y += driftSplat * (0.45 + 0.45 * cos(t * 0.9)) * dt * 0.75;
1023
+
1024
+ // Pointer ink injection (strictly scoped to active container)
1025
+ if (uMouseActive > 0.01) {
1026
+ vec2 deltaP = (vUv - uMouse) * vec2(aspect, 1.0);
1027
+ float dist2 = dot(deltaP, deltaP);
1028
+ float brush = exp(-dist2 / max(uRadius, 0.001));
1029
+
1030
+ float speedMag = length(uMouseVel);
1031
+ if (speedMag > 0.002) {
1032
+ vec2 push = clamp(uMouseVel, vec2(-3.2), vec2(3.2));
1033
+ vel += push * brush * 0.44;
1034
+ float deposit = min(speedMag * 0.48, 1.0) * brush;
1035
+ float wave = 0.5 + 0.5 * sin(uTime * 1.1);
1036
+ ink.x += deposit * (0.55 + 0.45 * wave);
1037
+ ink.y += deposit * (0.35 + 0.65 * (1.0 - wave));
1038
+ }
1039
+
1040
+ // Press & hold drops a concentrated ink bloom
1041
+ if (uMouseDown > 0.5) {
1042
+ vec2 outward = normalize(deltaP + vec2(0.0001));
1043
+ float bloom = exp(-dist2 / max(uRadius * 2.4, 0.003));
1044
+ vel += outward * bloom * 0.7 * dt * 11.0;
1045
+ ink += vec2(0.8, 0.9) * bloom * dt * 5.2;
1046
+ }
1047
+ }
1048
+
1049
+ vel = clamp(vel, vec2(-0.96), vec2(0.96));
1050
+ ink = clamp(ink, vec2(0.0), vec2(1.0));
1051
+ vec2 encVel = clamp(vel * 0.5 + 0.5, vec2(0.02), vec2(0.98));
1052
+
1053
+ fragColor = vec4(encVel, ink);
1054
+ }`,Ee=`#version 300 es
1055
+ precision highp float;
1056
+
1057
+ in vec2 vUv;
1058
+ out vec4 fragColor;
1059
+
1060
+ uniform sampler2D uFeedback;
1061
+ uniform float uTime;
1062
+ uniform vec2 uResolution;
1063
+ uniform vec3 uColor1;
1064
+ uniform vec3 uColor2;
1065
+ uniform vec3 uColor3;
1066
+
1067
+ float hash(vec2 p) {
1068
+ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123);
1069
+ }
1070
+
1071
+ void main() {
1072
+ vec2 fboTexel = 1.0 / max(vec2(textureSize(uFeedback, 0)), vec2(1.0));
1073
+ vec4 fbo = texture(uFeedback, vUv);
1074
+
1075
+ float ink1 = fbo.b;
1076
+ float ink2 = fbo.a;
1077
+
1078
+ // Subtle refractive distortion along ink pigment gradient
1079
+ float hC = ink1 * 0.7 + ink2 * 0.55;
1080
+ float hL = dot(texture(uFeedback, vUv - vec2(fboTexel.x * 2.0, 0.0)).ba, vec2(0.7, 0.55));
1081
+ float hR = dot(texture(uFeedback, vUv + vec2(fboTexel.x * 2.0, 0.0)).ba, vec2(0.7, 0.55));
1082
+ float hD = dot(texture(uFeedback, vUv - vec2(0.0, fboTexel.y * 2.0)).ba, vec2(0.7, 0.55));
1083
+ float hU = dot(texture(uFeedback, vUv + vec2(0.0, fboTexel.y * 2.0)).ba, vec2(0.7, 0.55));
1084
+
1085
+ vec2 grad = vec2(hR - hL, hU - hD);
1086
+ vec2 refractedUv = clamp(vUv + grad * 0.018, vec2(0.0), vec2(1.0));
1087
+ vec4 refFbo = texture(uFeedback, refractedUv);
1088
+
1089
+ float p1 = mix(ink1, refFbo.b, 0.45);
1090
+ float p2 = mix(ink2, refFbo.a, 0.45);
1091
+
1092
+ // Water backdrop + Beer-Lambert style pigment absorption
1093
+ vec3 waterBase = vec3(0.025, 0.03, 0.06) + uColor1 * 0.035;
1094
+ float absorb1 = smoothstep(0.02, 0.82, p1);
1095
+ 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
+ float filament = smoothstep(0.22, 0.92, p1 * p2 * 1.7 + length(grad) * 2.2);
1103
+ col = mix(col, uColor3, filament * 0.68);
1104
+
1105
+ // Soft water surface sheen along pigment ridges
1106
+ vec3 n = normalize(vec3((hL - hR) * 2.8, (hD - hU) * 2.8, 1.0));
1107
+ 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
+ float grain = (hash(gl_FragCoord.xy + fract(uTime)) - 0.5) * 0.015;
1112
+ col = max(col * vig + grain, vec3(0.0));
1113
+
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
1116
+ precision highp float;
1117
+
1118
+ in vec2 vUv;
1119
+ out vec4 fragColor;
1120
+
1121
+ uniform sampler2D uPrevFrame;
1122
+ uniform float uTime;
1123
+ uniform float uDelta;
1124
+ uniform vec2 uResolution;
1125
+ uniform vec2 uMouse;
1126
+ uniform vec2 uMouseVel;
1127
+ uniform float uMouseDown;
1128
+ uniform float uMouseActive;
1129
+ uniform float uSpeed;
1130
+ uniform float uDissipation;
1131
+ uniform float uRadius;
1132
+ uniform float uCurl;
1133
+
1134
+ vec2 decodeVel(vec4 s) {
1135
+ if (s.r < 0.01 && s.g < 0.01) return vec2(0.0);
1136
+ return (s.rg - 0.5) * 2.0;
1137
+ }
1138
+
1139
+ void main() {
1140
+ vec2 texel = 1.0 / max(uResolution, vec2(1.0));
1141
+ float dt = clamp(uDelta, 0.004, 0.033);
1142
+ float aspect = uResolution.x / max(uResolution.y, 1.0);
1143
+
1144
+ vec4 c = texture(uPrevFrame, vUv);
1145
+ vec4 l = texture(uPrevFrame, vUv - vec2(texel.x, 0.0));
1146
+ vec4 r = texture(uPrevFrame, vUv + vec2(texel.x, 0.0));
1147
+ vec4 d = texture(uPrevFrame, vUv - vec2(0.0, texel.y));
1148
+ vec4 u = texture(uPrevFrame, vUv + vec2(0.0, texel.y));
1149
+
1150
+ vec2 vel = decodeVel(c);
1151
+ vec2 vL = decodeVel(l);
1152
+ vec2 vR = decodeVel(r);
1153
+ vec2 vD = decodeVel(d);
1154
+ vec2 vU = decodeVel(u);
1155
+
1156
+ // Vorticity confinement for wispy curling ink tendrils
1157
+ float curl = (vR.y - vL.y) - (vU.x - vD.x);
1158
+ vec2 grad = vec2(abs(vU.y) - abs(vD.y), abs(vR.x) - abs(vL.x));
1159
+ vec2 swirlDir = normalize(grad + vec2(0.0001));
1160
+ vel += vec2(swirlDir.y, -swirlDir.x) * curl * uCurl * dt * 1.5;
1161
+
1162
+ // Semi-Lagrangian advection along flow
1163
+ vec2 backUv = clamp(vUv - vel * dt * 0.52 * clamp(uSpeed, 0.25, 3.0), texel, 1.0 - texel);
1164
+ vec4 adv = texture(uPrevFrame, backUv);
1165
+ vec2 advVel = decodeVel(adv);
1166
+
1167
+ // Soft pressure-like neighbor smoothing keeps incompressible swirls silky
1168
+ vec2 avgVel = (vL + vR + vD + vU) * 0.25;
1169
+ vec2 avgInk = (l.ba + r.ba + d.ba + u.ba) * 0.25;
1170
+
1171
+ float velDecay = pow(clamp(uDissipation * 0.982, 0.88, 0.992), dt * 60.0);
1172
+ float inkDecay = pow(clamp(uDissipation + 0.005, 0.92, 0.998), dt * 60.0);
1173
+
1174
+ vel = mix(advVel, avgVel, 0.09) * velDecay;
1175
+ vec2 ink = mix(adv.ba, avgInk, 0.032) * inkDecay;
1176
+
1177
+ // Autonomous curving ink plumes (gives live video-like motion on load)
1178
+ float t = uTime * 0.45;
1179
+ for (int i = 0; i < 3; i++) {
1180
+ float fi = float(i);
1181
+ float phase = t * (0.48 + fi * 0.13) + fi * 2.1;
1182
+ vec2 plumePos = vec2(
1183
+ 0.55 + 0.24 * cos(phase * 0.9 + fi),
1184
+ 0.50 + 0.24 * sin(phase * 1.15 - fi * 0.7)
1185
+ );
1186
+ float ang = phase * 1.4 + fi * 1.7;
1187
+ vec2 plumeDir = vec2(cos(ang), sin(ang)) * 0.28;
1188
+ float pulse = 0.5 + 0.5 * sin(t * 1.6 + fi * 2.3);
1189
+
1190
+ vec2 dp = (vUv - plumePos) * vec2(aspect, 1.0);
1191
+ float splat = exp(-dot(dp, dp) / max(uRadius * 1.35, 0.002));
1192
+ vel += plumeDir * splat * dt * 3.6;
1193
+ ink.x += splat * pulse * dt * 0.95;
1194
+ ink.y += splat * (1.0 - pulse * 0.65) * dt * 0.75;
1195
+ }
1196
+
1197
+ // Interactive cursor stroke & click/hold ink bloom (strictly inside container)
1198
+ if (uMouseActive > 0.01) {
1199
+ vec2 diff = (vUv - uMouse) * vec2(aspect, 1.0);
1200
+ float distSq = dot(diff, diff);
1201
+ float brush = exp(-distSq / max(uRadius, 0.001));
1202
+
1203
+ float mSpeed = length(uMouseVel);
1204
+ if (mSpeed > 0.002) {
1205
+ vec2 push = clamp(uMouseVel, vec2(-3.4), vec2(3.4));
1206
+ vel += push * brush * 0.46;
1207
+ float deposit = min(mSpeed * 0.46, 1.0) * brush;
1208
+ float tintPhase = 0.5 + 0.5 * sin(uTime * 1.15);
1209
+ ink.x += deposit * (0.55 + 0.45 * tintPhase);
1210
+ ink.y += deposit * (0.45 + 0.55 * (1.0 - tintPhase));
1211
+ }
1212
+
1213
+ if (uMouseDown > 0.5) {
1214
+ vec2 radial = normalize(diff + vec2(0.0001));
1215
+ float bloom = exp(-distSq / max(uRadius * 2.3, 0.003));
1216
+ vel += radial * bloom * 0.75 * dt * 12.0;
1217
+ ink += vec2(0.85, 0.9) * bloom * dt * 5.6;
1218
+ }
1219
+ }
1220
+
1221
+ vel = clamp(vel, vec2(-0.96), vec2(0.96));
1222
+ ink = clamp(ink, vec2(0.0), vec2(1.0));
1223
+ vec2 encVel = clamp(vel * 0.5 + 0.5, vec2(0.02), vec2(0.98));
1224
+
1225
+ fragColor = vec4(encVel, ink);
1226
+ }`,Se=`#version 300 es
1227
+ precision highp float;
1228
+
1229
+ in vec2 vUv;
1230
+ out vec4 fragColor;
1231
+
1232
+ uniform sampler2D uFeedback;
1233
+ uniform float uTime;
1234
+ uniform vec2 uResolution;
1235
+ uniform vec3 uBgColor;
1236
+ uniform float uTransparentBg;
1237
+ uniform float uLightMode;
1238
+ uniform float uAbsorptionGain;
1239
+ uniform vec3 uColor1;
1240
+ uniform vec3 uColor2;
1241
+ uniform vec3 uColor3;
1242
+
1243
+ float hash12(vec2 p) {
1244
+ vec3 p3 = fract(vec3(p.xyx) * 0.1031);
1245
+ p3 += dot(p3, p3.yzx + 33.33);
1246
+ return fract((p3.x + p3.y) * p3.z);
1247
+ }
1248
+
1249
+ void main() {
1250
+ vec2 fboTexel = 1.0 / max(vec2(textureSize(uFeedback, 0)), vec2(1.0));
1251
+ vec4 fbo = texture(uFeedback, vUv);
1252
+
1253
+ float pA = fbo.b;
1254
+ float pB = fbo.a;
1255
+
1256
+ // Fluid surface relief normal from pigment density gradient
1257
+ float hC = pA * 0.72 + pB * 0.58;
1258
+ float hL = dot(texture(uFeedback, vUv - vec2(fboTexel.x * 2.0, 0.0)).ba, vec2(0.72, 0.58));
1259
+ float hR = dot(texture(uFeedback, vUv + vec2(fboTexel.x * 2.0, 0.0)).ba, vec2(0.72, 0.58));
1260
+ float hT = dot(texture(uFeedback, vUv + vec2(0.0, fboTexel.y * 2.0)).ba, vec2(0.72, 0.58));
1261
+ float hB = dot(texture(uFeedback, vUv - vec2(0.0, fboTexel.y * 2.0)).ba, vec2(0.72, 0.58));
1262
+
1263
+ vec3 normal = normalize(vec3((hL - hR) * 2.3, (hB - hT) * 2.3, 0.42));
1264
+ vec3 lightDir = normalize(vec3(-0.35, 0.55, 0.75));
1265
+ float diffuse = clamp(dot(normal, lightDir), 0.0, 1.0);
1266
+ float rimSheen = pow(clamp(dot(normal, normalize(vec3(0.4, 0.6, 0.7))), 0.0, 1.0), 8.0);
1267
+
1268
+ // Combine 3 palette tones across dual pigment channels
1269
+ vec3 tintMix = normalize(uColor1 * pA + uColor2 * pB + uColor3 * (pA * pB * 1.8) + vec3(0.0001));
1270
+ float totalInk = (pA + pB * 0.85) * uAbsorptionGain;
1271
+
1272
+ // Light water: Beer-Lambert exponential light absorption on solid bg
1273
+ vec3 transmittance = exp(-tintMix * totalInk * 1.35);
1274
+ float inkMask = clamp(1.0 - exp(-hC * 1.5), 0.0, 1.0);
1275
+ vec3 lightCol = uBgColor * transmittance;
1276
+ lightCol *= mix(1.0, 0.90 + 0.16 * diffuse, inkMask * 0.72);
1277
+ lightCol += vec3(0.025) * rimSheen * inkMask * (1.0 - inkMask * 0.45);
1278
+
1279
+ // Dark water: Luminous bioluminescent plumes on solid bg
1280
+ vec3 luminous = (vec3(1.0) - exp(-tintMix * totalInk * 1.25)) * (0.86 + 0.24 * diffuse);
1281
+ vec3 darkCol = uBgColor + luminous + luminous * rimSheen * 0.12;
1282
+
1283
+ vec3 opaqueCol = mix(darkCol, lightCol, clamp(uLightMode, 0.0, 1.0));
1284
+
1285
+ // Subtle vignette + fine organic grain on solid bg
1286
+ vec2 centered = vUv - 0.5;
1287
+ float vignetteStrength = mix(0.36, 0.085, clamp(uLightMode, 0.0, 1.0));
1288
+ opaqueCol *= (1.0 - dot(centered, centered) * vignetteStrength);
1289
+ float grain = (hash12(vUv * 900.0 + fract(uTime * 0.05)) - 0.5) * 0.011;
1290
+ opaqueCol = clamp(opaqueCol + grain, 0.0, 1.0);
1291
+
1292
+ // Transparent backdrop mode: only render pigment/ink with alpha over page/body bg
1293
+ float inkAlpha = clamp(1.0 - exp(-totalInk * 1.35), 0.0, 1.0);
1294
+ vec3 inkRgb = clamp(tintMix * (0.82 + 0.28 * diffuse) + vec3(0.04) * rimSheen, 0.0, 1.0);
1295
+
1296
+ if (uTransparentBg > 0.5) {
1297
+ // Premultiplied alpha works cleanly with standard canvas alpha blending
1298
+ fragColor = vec4(inkRgb * inkAlpha, inkAlpha);
1299
+ } else {
1300
+ fragColor = vec4(opaqueCol, 1.0);
1301
+ }
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});