{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"ink-fluid","type":"registry:ui","title":"Ink Fluid","description":"Real-time fluid ink that swirls off the cursor in shifting colors. A compact WebGL2 stable-fluids solver, scoped to its container.","dependencies":[],"registryDependencies":[],"files":[{"path":"registry/ui/ink-fluid.tsx","type":"registry:ui","content":"\"use client\";\n\nimport { useEffect, useRef } from \"react\";\n\nexport interface InkFluidProps {\n  /** Velocity grid size on the shorter side. Higher is finer and slower. */\n  simResolution?: number;\n  /** Ink texture size on the shorter side. */\n  dyeResolution?: number;\n  /** How quickly ink fades, per second. */\n  dissipation?: number;\n  /** How quickly motion settles, per second. */\n  velocityDissipation?: number;\n  /** Vorticity: how much the ink curls into swirls. */\n  curl?: number;\n  /** Splat radius. */\n  splatRadius?: number;\n  /** How hard cursor motion pushes the ink. */\n  force?: number;\n  /** Throw random splashes while the cursor is away. */\n  idle?: boolean;\n  className?: string;\n}\n\nconst VERT = `precision highp float;\nattribute vec2 aPos;\nuniform vec2 texel;\nvarying vec2 vUv, vL, vR, vT, vB;\nvoid main(){\n  vUv = aPos * .5 + .5;\n  vL = vUv - vec2(texel.x, 0.); vR = vUv + vec2(texel.x, 0.);\n  vT = vUv + vec2(0., texel.y); vB = vUv - vec2(0., texel.y);\n  gl_Position = vec4(aPos, 0., 1.);\n}`;\nconst HEAD = `precision highp float;varying vec2 vUv, vL, vR, vT, vB;`;\n// Classic stable-fluids pipeline: vorticity, divergence, Jacobi pressure solve, projection, advection.\nconst FRAGS = {\n  splat: `uniform sampler2D uTarget;uniform float aspect, radius;uniform vec3 color;uniform vec2 point;\n    void main(){vec2 p=vUv-point;p.x*=aspect;gl_FragColor=vec4(texture2D(uTarget,vUv).xyz+exp(-dot(p,p)/radius)*color,1.);}`,\n  advect: `uniform sampler2D uVelocity, uSource;uniform vec2 texel;uniform float dt, dissipation;\n    void main(){vec2 c=vUv-dt*texture2D(uVelocity,vUv).xy*texel;gl_FragColor=texture2D(uSource,c)/(1.+dissipation*dt);}`,\n  divergence: `uniform sampler2D uVelocity;void main(){vec2 C=texture2D(uVelocity,vUv).xy;\n    float L=vL.x<0.?-C.x:texture2D(uVelocity,vL).x;float R=vR.x>1.?-C.x:texture2D(uVelocity,vR).x;\n    float T=vT.y>1.?-C.y:texture2D(uVelocity,vT).y;float B=vB.y<0.?-C.y:texture2D(uVelocity,vB).y;\n    gl_FragColor=vec4(.5*(R-L+T-B),0.,0.,1.);}`,\n  curl: `uniform sampler2D uVelocity;void main(){gl_FragColor=vec4(.5*(texture2D(uVelocity,vR).y-texture2D(uVelocity,vL).y-texture2D(uVelocity,vT).x+texture2D(uVelocity,vB).x),0.,0.,1.);}`,\n  vorticity: `uniform sampler2D uVelocity, uCurl;uniform float curl, dt;void main(){\n    float L=texture2D(uCurl,vL).x,R=texture2D(uCurl,vR).x,T=texture2D(uCurl,vT).x,B=texture2D(uCurl,vB).x,C=texture2D(uCurl,vUv).x;\n    vec2 f=.5*vec2(abs(T)-abs(B),abs(R)-abs(L));f/=length(f)+1e-4;f*=curl*C;f.y*=-1.;\n    gl_FragColor=vec4(clamp(texture2D(uVelocity,vUv).xy+f*dt,-1000.,1000.),0.,1.);}`,\n  pressure: `uniform sampler2D uPressure, uDivergence;void main(){\n    gl_FragColor=vec4((texture2D(uPressure,vL).x+texture2D(uPressure,vR).x+texture2D(uPressure,vT).x+texture2D(uPressure,vB).x-texture2D(uDivergence,vUv).x)*.25,0.,0.,1.);}`,\n  gradient: `uniform sampler2D uPressure, uVelocity;void main(){\n    vec2 v=texture2D(uVelocity,vUv).xy-vec2(texture2D(uPressure,vR).x-texture2D(uPressure,vL).x,texture2D(uPressure,vT).x-texture2D(uPressure,vB).x);\n    gl_FragColor=vec4(v,0.,1.);}`,\n  scale: `uniform sampler2D uTexture;uniform float value;void main(){gl_FragColor=value*texture2D(uTexture,vUv);}`,\n  display: `uniform sampler2D uTexture;void main(){vec3 c=1.-exp(-texture2D(uTexture,vUv).rgb*3.);gl_FragColor=vec4(c,max(c.r,max(c.g,c.b)));}`,\n};\n\ntype Fbo = { tex: WebGLTexture; fbo: WebGLFramebuffer; w: number; h: number };\n\nfunction hsv(h: number) {\n  const f = (n: number) => {\n    const k = (n + h * 6) % 6;\n    return 1 - Math.max(0, Math.min(k, 4 - k, 1));\n  };\n  return [f(5) * 0.15, f(3) * 0.15, f(1) * 0.15];\n}\n\nexport function InkFluid({\n  simResolution = 128,\n  dyeResolution = 512,\n  dissipation = 0.8,\n  velocityDissipation = 0.4,\n  curl = 20,\n  splatRadius = 0.25,\n  force = 6000,\n  idle = true,\n  className,\n}: InkFluidProps) {\n  const ref = useRef<HTMLDivElement>(null);\n\n  useEffect(() => {\n    if (window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) return;\n    const el = ref.current!;\n    const host = el.parentElement ?? el;\n    // A fresh canvas per effect run: a context lost in cleanup can never be reused.\n    const canvas = document.createElement(\"canvas\");\n    canvas.style.cssText = \"position:absolute;inset:0;width:100%;height:100%;display:block\";\n    el.appendChild(canvas);\n    const gl = canvas.getContext(\"webgl2\", { alpha: true, antialias: false, depth: false, stencil: false });\n    if (!gl || !gl.getExtension(\"EXT_color_buffer_float\")) return () => canvas.remove();\n\n    gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());\n    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);\n    gl.enableVertexAttribArray(0);\n    gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);\n    const vs = gl.createShader(gl.VERTEX_SHADER)!;\n    gl.shaderSource(vs, VERT);\n    gl.compileShader(vs);\n    const programs = Object.fromEntries(\n      Object.entries(FRAGS).map(([name, src]) => {\n        const fs = gl.createShader(gl.FRAGMENT_SHADER)!;\n        gl.shaderSource(fs, HEAD + src);\n        gl.compileShader(fs);\n        const prog = gl.createProgram()!;\n        gl.attachShader(prog, vs);\n        gl.attachShader(prog, fs);\n        gl.bindAttribLocation(prog, 0, \"aPos\");\n        gl.linkProgram(prog);\n        const uniforms: Record<string, WebGLUniformLocation | null> = {};\n        const n = gl.getProgramParameter(prog, gl.ACTIVE_UNIFORMS) as number;\n        for (let i = 0; i < n; i++) {\n          const name = gl.getActiveUniform(prog, i)!.name;\n          uniforms[name] = gl.getUniformLocation(prog, name);\n        }\n        return [name, { prog, uniforms }];\n      }),\n    ) as Record<keyof typeof FRAGS, { prog: WebGLProgram; uniforms: Record<string, WebGLUniformLocation | null> }>;\n\n    let active = programs.display;\n    const pick = (p: typeof active) => {\n      active = p;\n      gl.useProgram(p.prog);\n    };\n    const set = (name: string, ...v: number[]) => {\n      const loc = active.uniforms[name];\n      if (v.length === 1) gl.uniform1f(loc, v[0]);\n      else if (v.length === 2) gl.uniform2f(loc, v[0], v[1]);\n      else gl.uniform3f(loc, v[0], v[1], v[2]);\n    };\n    const bind = (name: string, f: Fbo, unit: number) => {\n      gl.activeTexture(gl.TEXTURE0 + unit);\n      gl.bindTexture(gl.TEXTURE_2D, f.tex);\n      gl.uniform1i(active.uniforms[name], unit);\n    };\n    const blit = (target: Fbo | null) => {\n      gl.bindFramebuffer(gl.FRAMEBUFFER, target ? target.fbo : null);\n      gl.viewport(0, 0, target ? target.w : canvas.width, target ? target.h : canvas.height);\n      gl.drawArrays(gl.TRIANGLES, 0, 3);\n    };\n    const fbo = (w: number, h: number): Fbo => {\n      const tex = gl.createTexture()!;\n      gl.bindTexture(gl.TEXTURE_2D, tex);\n      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, w, h, 0, gl.RGBA, gl.HALF_FLOAT, null);\n      const f = gl.createFramebuffer()!;\n      gl.bindFramebuffer(gl.FRAMEBUFFER, f);\n      gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);\n      gl.clearColor(0, 0, 0, 0);\n      gl.clear(gl.COLOR_BUFFER_BIT);\n      return { tex, fbo: f, w, h };\n    };\n    const double = (w: number, h: number) => {\n      const d = { read: fbo(w, h), write: fbo(w, h), swap: () => ([d.read, d.write] = [d.write, d.read]) };\n      return d;\n    };\n    const size = (res: number) => {\n      const a = canvas.width / canvas.height;\n      const big = Math.round(res * Math.max(a, 1 / a));\n      return a > 1 ? [big, res] : [res, big];\n    };\n\n    let velocity: ReturnType<typeof double>, dye: ReturnType<typeof double>, pressure: ReturnType<typeof double>;\n    let divergence: Fbo, curlFbo: Fbo;\n    const textures: WebGLTexture[] = [];\n    const frameBuffers: WebGLFramebuffer[] = [];\n    const free = () => {\n      textures.forEach((t) => gl.deleteTexture(t));\n      frameBuffers.forEach((f) => gl.deleteFramebuffer(f));\n      textures.length = frameBuffers.length = 0;\n    };\n    const track = <T extends Fbo | ReturnType<typeof double>>(x: T) => {\n      const list: Fbo[] = \"read\" in x ? [x.read, x.write] : [x as Fbo];\n      for (const f of list) {\n        textures.push(f.tex);\n        frameBuffers.push(f.fbo);\n      }\n      return x;\n    };\n\n    // ponytail: resizing restarts the simulation; resample old ink into new targets if that ever matters.\n    const resize = () => {\n      const dpr = Math.min(window.devicePixelRatio || 1, 2);\n      canvas.width = Math.max(1, el.clientWidth * dpr);\n      canvas.height = Math.max(1, el.clientHeight * dpr);\n      free();\n      const [sw, sh] = size(simResolution);\n      const [dw, dh] = size(dyeResolution);\n      velocity = track(double(sw, sh));\n      pressure = track(double(sw, sh));\n      dye = track(double(dw, dh));\n      divergence = track(fbo(sw, sh));\n      curlFbo = track(fbo(sw, sh));\n    };\n\n    const splat = (x: number, y: number, dx: number, dy: number, color: number[]) => {\n      pick(programs.splat);\n      set(\"aspect\", canvas.width / canvas.height);\n      set(\"point\", x, y);\n      set(\"radius\", (splatRadius / 100) * Math.max(1, canvas.width / canvas.height));\n      bind(\"uTarget\", velocity.read, 0);\n      set(\"color\", dx, dy, 0);\n      blit(velocity.write);\n      velocity.swap();\n      bind(\"uTarget\", dye.read, 0);\n      set(\"color\", color[0], color[1], color[2]);\n      blit(dye.write);\n      dye.swap();\n    };\n\n    const step = (dt: number) => {\n      const tx = 1 / velocity.read.w;\n      const ty = 1 / velocity.read.h;\n      pick(programs.curl);\n      set(\"texel\", tx, ty);\n      bind(\"uVelocity\", velocity.read, 0);\n      blit(curlFbo);\n\n      pick(programs.vorticity);\n      set(\"texel\", tx, ty);\n      bind(\"uVelocity\", velocity.read, 0);\n      bind(\"uCurl\", curlFbo, 1);\n      set(\"curl\", curl);\n      set(\"dt\", dt);\n      blit(velocity.write);\n      velocity.swap();\n\n      pick(programs.divergence);\n      set(\"texel\", tx, ty);\n      bind(\"uVelocity\", velocity.read, 0);\n      blit(divergence);\n\n      pick(programs.scale);\n      bind(\"uTexture\", pressure.read, 0);\n      set(\"value\", 0.8);\n      blit(pressure.write);\n      pressure.swap();\n\n      pick(programs.pressure);\n      set(\"texel\", tx, ty);\n      bind(\"uDivergence\", divergence, 0);\n      for (let i = 0; i < 20; i++) {\n        bind(\"uPressure\", pressure.read, 1);\n        blit(pressure.write);\n        pressure.swap();\n      }\n\n      pick(programs.gradient);\n      set(\"texel\", tx, ty);\n      bind(\"uPressure\", pressure.read, 0);\n      bind(\"uVelocity\", velocity.read, 1);\n      blit(velocity.write);\n      velocity.swap();\n\n      pick(programs.advect);\n      set(\"texel\", tx, ty);\n      set(\"dt\", dt);\n      bind(\"uVelocity\", velocity.read, 0);\n      bind(\"uSource\", velocity.read, 0);\n      set(\"dissipation\", velocityDissipation);\n      blit(velocity.write);\n      velocity.swap();\n\n      bind(\"uVelocity\", velocity.read, 0);\n      bind(\"uSource\", dye.read, 1);\n      set(\"dissipation\", dissipation);\n      blit(dye.write);\n      dye.swap();\n\n      pick(programs.display);\n      bind(\"uTexture\", dye.read, 0);\n      blit(null);\n    };\n\n    let raf = 0;\n    let visible = true;\n    let last = performance.now();\n    let lastInput = 0;\n    let nextIdle = 0;\n    let hue = Math.random();\n    const pointer = { x: 0, y: 0, down: false, moved: false };\n\n    const loop = (now: number) => {\n      const dt = Math.min((now - last) / 1000, 1 / 60);\n      last = now;\n      if (idle && now - lastInput > 2500 && now > nextIdle) {\n        nextIdle = now + 900 + Math.random() * 900;\n        burst(1);\n      }\n      step(dt);\n      raf = visible ? requestAnimationFrame(loop) : 0;\n    };\n\n    const onMove = (e: PointerEvent) => {\n      const r = canvas.getBoundingClientRect();\n      const x = (e.clientX - r.left) / r.width;\n      const y = 1 - (e.clientY - r.top) / r.height;\n      if (pointer.moved) {\n        hue = (hue + 0.004) % 1;\n        splat(x, y, (x - pointer.x) * force, (y - pointer.y) * force, hsv(hue));\n      }\n      pointer.x = x;\n      pointer.y = y;\n      pointer.moved = true;\n      lastInput = performance.now();\n    };\n    const onLeave = () => {\n      pointer.moved = false;\n    };\n    const onDown = () => {\n      // A click throws a bright burst in a random direction.\n      const a = Math.random() * Math.PI * 2;\n      splat(pointer.x, pointer.y, Math.cos(a) * 900, Math.sin(a) * 900, hsv(Math.random()).map((c) => c * 6));\n    };\n\n    const burst = (n: number) => {\n      for (let i = 0; i < n; i++) {\n        const a = Math.random() * Math.PI * 2;\n        splat(0.2 + Math.random() * 0.6, 0.2 + Math.random() * 0.6, Math.cos(a) * 1200, Math.sin(a) * 1200, hsv(Math.random()).map((c) => c * 5));\n      }\n    };\n\n    resize();\n    // Opening burst so the surface is alive before the first move.\n    burst(5);\n\n    const ro = new ResizeObserver(() => {\n      if (Math.abs(el.clientWidth * Math.min(window.devicePixelRatio || 1, 2) - canvas.width) > 1) resize();\n    });\n    ro.observe(el);\n    const io = new IntersectionObserver(([entry]) => {\n      visible = entry.isIntersecting;\n      if (visible && !raf) {\n        last = performance.now();\n        raf = requestAnimationFrame(loop);\n      }\n    });\n    io.observe(el);\n    host.addEventListener(\"pointermove\", onMove, { passive: true });\n    host.addEventListener(\"pointerleave\", onLeave);\n    host.addEventListener(\"pointerdown\", onDown);\n\n    return () => {\n      cancelAnimationFrame(raf);\n      ro.disconnect();\n      io.disconnect();\n      host.removeEventListener(\"pointermove\", onMove);\n      host.removeEventListener(\"pointerleave\", onLeave);\n      host.removeEventListener(\"pointerdown\", onDown);\n      gl.getExtension(\"WEBGL_lose_context\")?.loseContext();\n      canvas.remove();\n    };\n  }, [simResolution, dyeResolution, dissipation, velocityDissipation, curl, splatRadius, force, idle]);\n\n  return (\n    <div\n      ref={ref}\n      aria-hidden\n      className={className}\n      style={{ position: \"absolute\", inset: 0, overflow: \"hidden\", pointerEvents: \"none\" }}\n    />\n  );\n}\n"}]}