{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"grainient","type":"registry:ui","title":"Grainient","description":"A grainy gradient mesh of up to four colors that slowly morph, with a seed for stable compositions.","dependencies":["motion"],"registryDependencies":["https://ui.mekaigames.com/r/theme.json"],"files":[{"path":"components/ui/grainient.tsx","type":"registry:ui","content":"\"use client\";\n\nimport { useReducedMotion } from \"motion/react\";\nimport { useEffect, useRef } from \"react\";\n\ntype GrainientProps = {\n  /** Two to four hex colors that blend into each other. */\n  colors?: string[];\n  /** Morph speed multiplier. */\n  speed?: number;\n  /** Film grain amount, from 0 to 1. */\n  grain?: number;\n  /** How much the color fields bend and swirl, from 0 to 1. */\n  warp?: number;\n  /** Any number. Each seed gives a different, stable composition. */\n  seed?: number;\n  /** Let the colors lean toward the pointer. */\n  mouseReact?: boolean;\n  /** Render resolution, from 0.25 to 1. Lower is cheaper. */\n  quality?: number;\n  className?: string;\n};\n\nconst VERTEX = `\nattribute vec2 aPos;\nvoid main() { gl_Position = vec4(aPos, 0.0, 1.0); }\n`;\n\nconst FRAGMENT = `\n#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\nuniform vec2 uRes;\nuniform float uTime;\nuniform float uClock;\nuniform vec2 uPointer;\nuniform float uHover;\nuniform vec3 uColors[4];\nuniform vec4 uPoints[4];\nuniform float uCount;\nuniform float uGrain;\nuniform float uWarp;\n\nfloat hash(vec2 p) {\n  p = fract(p * vec2(443.897, 441.423));\n  p += dot(p, p.yx + 19.19);\n  return fract((p.x + p.y) * p.x);\n}\n\nvoid main() {\n  vec2 uv = gl_FragCoord.xy / uRes;\n  float aspect = uRes.x / uRes.y;\n  vec2 p = vec2(uv.x * aspect, uv.y);\n  float t = uTime * 0.15;\n\n  // Bend space before blending, so the color fields swirl instead of sitting as round blobs.\n  vec2 w = p;\n  // Space bulges toward the pointer, so the nearest colors lean in to follow it.\n  vec2 m = vec2(uPointer.x * aspect, uPointer.y);\n  vec2 toPointer = w - m;\n  w -= toPointer * 0.35 * exp(-dot(toPointer, toPointer) * 9.0) * uHover;\n  w += uWarp * 0.28 * vec2(sin(p.y * 3.0 + t * 2.0), cos(p.x * 2.6 - t * 1.6));\n  w += uWarp * 0.12 * vec2(sin(w.y * 6.0 - t * 2.4), cos(w.x * 5.2 + t * 2.0));\n\n  vec3 col = vec3(0.0);\n  float total = 0.0;\n  for (int i = 0; i < 4; i++) {\n    if (float(i) >= uCount) break;\n    vec4 pt = uPoints[i];\n    vec2 center = vec2(pt.x * aspect, pt.y);\n    center += vec2(cos(t * pt.z + pt.w) * 0.22 * aspect, sin(t * (pt.z * 0.8 + 0.3) + pt.w * 1.7) * 0.2);\n    vec2 d = w - center;\n    float weight = 1.0 / (pow(dot(d, d), 1.25) + 0.003);\n    col += uColors[i] * weight;\n    total += weight;\n  }\n  col /= total;\n\n  col *= 0.86 + 0.14 * (1.0 - smoothstep(0.2, 0.95, length(uv - 0.5)));\n  // Grain refreshes at film rate (24 fps), not every frame.\n  float g = hash(gl_FragCoord.xy + floor(uClock * 24.0) * 17.31) - 0.5;\n  col += g * uGrain * 0.2;\n  gl_FragColor = vec4(col, 1.0);\n}\n`;\n\nfunction hexToVec3(hex: string): [number, number, number] {\n  let h = hex.replace(\"#\", \"\");\n  if (h.length === 3) h = h.replace(/./g, (c) => c + c);\n  const n = parseInt(h, 16) || 0;\n  return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];\n}\n\n/** Small seeded random generator, so the same seed always gives the same layout. */\nfunction seededRandom(seed: number) {\n  let a = Math.floor(seed * 9973) ^ 0x9e3779b9;\n  return () => {\n    a = (a + 0x6d2b79f5) | 0;\n    let r = Math.imul(a ^ (a >>> 15), 1 | a);\n    r = (r + Math.imul(r ^ (r >>> 7), 61 | r)) ^ r;\n    return ((r ^ (r >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\nfunction createProgram(gl: WebGLRenderingContext, fragment: string) {\n  const program = gl.createProgram();\n  const shaders: WebGLShader[] = [];\n  for (const [type, source] of [\n    [gl.VERTEX_SHADER, VERTEX],\n    [gl.FRAGMENT_SHADER, fragment],\n  ] as const) {\n    const shader = gl.createShader(type);\n    if (!shader || !program) return null;\n    gl.shaderSource(shader, source);\n    gl.compileShader(shader);\n    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n      console.warn(gl.getShaderInfoLog(shader));\n      return null;\n    }\n    gl.attachShader(program, shader);\n    shaders.push(shader);\n  }\n  if (!program) return null;\n  gl.linkProgram(program);\n  for (const shader of shaders) gl.deleteShader(shader);\n  return gl.getProgramParameter(program, gl.LINK_STATUS) ? program : null;\n}\n\n/** Releases the GPU context once the canvas has really left the page (not on a Strict Mode re-run). */\nfunction releaseLater(gl: WebGLRenderingContext, canvas: HTMLCanvasElement) {\n  window.setTimeout(() => {\n    if (!canvas.isConnected) gl.getExtension(\"WEBGL_lose_context\")?.loseContext();\n  }, 0);\n}\n\nconst DEFAULT_COLORS = [\"#ff784f\", \"#ffc24a\", \"#e2552b\", \"#2d2824\"];\n\n/** A grainy gradient mesh of up to four colors that slowly morph into each other. */\nexport function Grainient({\n  colors = DEFAULT_COLORS,\n  speed = 1,\n  grain = 0.35,\n  warp = 0.5,\n  seed = 1,\n  mouseReact = true,\n  quality = 1,\n  className = \"\",\n}: GrainientProps) {\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const reduce = useReducedMotion();\n  // A string key keeps the effect stable when the parent passes a new array with the same colors.\n  const palette = (colors.length >= 2 ? colors : DEFAULT_COLORS).slice(0, 4).join(\",\");\n\n  useEffect(() => {\n    const canvas = canvasRef.current;\n    if (!canvas) return;\n    const list = palette.split(\",\");\n    const fallback = `linear-gradient(135deg, ${list.join(\", \")})`;\n    const gl = canvas.getContext(\"webgl\", { alpha: false, antialias: false, depth: false, powerPreference: \"low-power\" });\n    const program = gl ? createProgram(gl, FRAGMENT) : null;\n    if (!gl || !program) {\n      canvas.style.background = fallback;\n      return;\n    }\n    canvas.style.background = \"\";\n\n    const buffer = gl.createBuffer();\n    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);\n    const aPos = gl.getAttribLocation(program, \"aPos\");\n    gl.enableVertexAttribArray(aPos);\n    gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);\n    gl.useProgram(program);\n\n    const uniform = (name: string) => gl.getUniformLocation(program, name);\n    const uRes = uniform(\"uRes\");\n    const uTime = uniform(\"uTime\");\n    const uClock = uniform(\"uClock\");\n    const uPointer = uniform(\"uPointer\");\n    const uHover = uniform(\"uHover\");\n    const rgb = new Float32Array(12);\n    list.forEach((hex, i) => rgb.set(hexToVec3(hex), i * 3));\n    gl.uniform3fv(uniform(\"uColors\"), rgb);\n    // Each color point: resting x and y, drift speed and phase, all from the seed.\n    const random = seededRandom(seed);\n    const points = new Float32Array(16);\n    for (let i = 0; i < 4; i++) {\n      points.set([0.12 + random() * 0.76, 0.12 + random() * 0.76, 0.6 + random() * 0.9, random() * Math.PI * 2], i * 4);\n    }\n    gl.uniform4fv(uniform(\"uPoints\"), points);\n    gl.uniform1f(uniform(\"uCount\"), list.length);\n    gl.uniform1f(uniform(\"uGrain\"), Math.min(1, Math.max(0, grain)));\n    gl.uniform1f(uniform(\"uWarp\"), Math.min(1, Math.max(0, warp)));\n\n    const pointer = { x: 0.5, y: 0.5, tx: 0.5, ty: 0.5, hover: 0, target: 0 };\n    let time = 10;\n    let clock = 0;\n    let last = 0;\n    let frame = 0;\n    let visible = true;\n    let lost = false;\n\n    const render = (t: number) => {\n      if (lost) return;\n      const dt = last ? Math.min(50, t - last) : 16;\n      last = t;\n      if (!reduce) {\n        time += (dt / 1000) * speed;\n        clock += dt / 1000;\n        const k = Math.min(1, dt * 0.004);\n        pointer.x += (pointer.tx - pointer.x) * k;\n        pointer.y += (pointer.ty - pointer.y) * k;\n        pointer.hover += (pointer.target - pointer.hover) * Math.min(1, dt * 0.002);\n      }\n      gl.uniform1f(uTime, time % 3600);\n      gl.uniform1f(uClock, clock % 3600);\n      gl.uniform2f(uPointer, pointer.x, pointer.y);\n      gl.uniform1f(uHover, pointer.hover);\n      gl.drawArrays(gl.TRIANGLES, 0, 3);\n      if (!reduce && visible) frame = requestAnimationFrame(render);\n      else frame = 0;\n    };\n\n    const resize = () => {\n      const dpr = Math.min(window.devicePixelRatio || 1, 2) * Math.min(1, Math.max(0.25, quality));\n      canvas.width = Math.max(1, Math.round(canvas.clientWidth * dpr));\n      canvas.height = Math.max(1, Math.round(canvas.clientHeight * dpr));\n      gl.viewport(0, 0, canvas.width, canvas.height);\n      gl.uniform2f(uRes, canvas.width, canvas.height);\n      if (reduce) render(0);\n    };\n    const onMove = (e: PointerEvent) => {\n      const rect = canvas.getBoundingClientRect();\n      const x = (e.clientX - rect.left) / rect.width;\n      const y = 1 - (e.clientY - rect.top) / rect.height;\n      const inside = x >= 0 && x <= 1 && y >= 0 && y <= 1;\n      if (inside) {\n        pointer.tx = x;\n        pointer.ty = y;\n        if (pointer.hover < 0.05) {\n          pointer.x = x;\n          pointer.y = y;\n        }\n      }\n      pointer.target = inside ? 1 : 0;\n    };\n    const onLost = () => {\n      lost = true;\n      cancelAnimationFrame(frame);\n      canvas.style.background = fallback;\n    };\n\n    resize();\n    const observer = new ResizeObserver(resize);\n    observer.observe(canvas);\n    const io = new IntersectionObserver(([entry]) => {\n      visible = entry.isIntersecting;\n      if (visible && !reduce && !frame && !lost) {\n        last = 0;\n        frame = requestAnimationFrame(render);\n      }\n    });\n    io.observe(canvas);\n    canvas.addEventListener(\"webglcontextlost\", onLost);\n    if (!reduce) {\n      if (mouseReact) window.addEventListener(\"pointermove\", onMove, { passive: true });\n      frame = requestAnimationFrame(render);\n    }\n\n    return () => {\n      cancelAnimationFrame(frame);\n      observer.disconnect();\n      io.disconnect();\n      window.removeEventListener(\"pointermove\", onMove);\n      canvas.removeEventListener(\"webglcontextlost\", onLost);\n      gl.deleteBuffer(buffer);\n      gl.deleteProgram(program);\n      releaseLater(gl, canvas);\n    };\n  }, [palette, speed, grain, warp, seed, mouseReact, quality, reduce]);\n\n  return (\n    <canvas\n      ref={canvasRef}\n      className={`pointer-events-none absolute inset-0 block size-full ${className}`}\n      aria-hidden=\"true\"\n    />\n  );\n}\n"}]}