{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"marbled-paper-webgl-background-with-floating-inks-combed-into-feathers-on-a-wet-size-bath","type":"registry:block","title":"Marbled Paper WebGL Background with Floating Inks Combed into Feathers on a Wet Size Bath","description":"Marbling background in WebGL: a shader floats inks on a wet bath, combs them into feathers and lets the pointer drag a stylus. Free React and HTML code.","dependencies":[],"files":[{"path":"components/we-inc/marbled-paper-webgl-background-with-floating-inks-combed-into-feathers-on-a-wet-size-bath.tsx","type":"registry:component","content":"import { useEffect, useRef, useState } from \"react\";\n\n// Everything about the tray. Colours are red, green, blue from 0 to 1.\nconst bath = {\n  speed: 1, // how fast the liquid creeps; 0 holds the bath still\n  rake: 0.62, // how far the first rake pulled the inks sideways\n  comb: 0.42, // how far the fine comb pulled them into arches; 0 leaves plain raked bands\n  span: 4.4, // how much of the tray the shorter side of a wide screen shows\n  spanNarrow: 2.5, // the same for a phone\n  teeth: 0.22, // gap between comb teeth; smaller makes finer feathers\n  stylus: 1, // how hard the pointer drags the ink; 0 switches the stylus off\n  gloss: 1, // strength of the window reflected in the wet surface\n  quality: 0.85, // share of the device pixels that are drawn\n  maxPixels: 1000000, // the canvas never draws more pixels than this\n  size: [0.93, 0.88, 0.76], // the bare bath that shows between the inks\n  ground: [0.07, 0.11, 0.3], // the ink laid first, which fills most of the tray\n  inks: [\n    [0.11, 0.19, 0.47], // indigo\n    [0.76, 0.2, 0.13], // vermilion\n    [0.87, 0.64, 0.22], // ochre\n    [0.95, 0.9, 0.79], // bone white\n    [0.1, 0.36, 0.33], // bottle green\n  ],\n};\n\nconst SEGMENTS = 24; // how many short stylus moves the bath remembers\nconst SEGMENT_LENGTH = 0.14;\nconst SEGMENT_LIFE = 11; // seconds before a move has fully relaxed\n\nconst VERTEX = `\nattribute vec2 position;\nvoid main() { gl_Position = vec4(position, 0.0, 1.0); }`;\n\nconst FRAGMENT = `\nprecision highp float;\nuniform vec2 uRes;\nuniform float uTime;\nuniform float uSpan;\nuniform vec4 uSeg[${SEGMENTS}];\nuniform vec2 uWindow;\nuniform float uRake;\nuniform float uComb;\nuniform float uTeeth;\nuniform float uGloss;\nuniform vec3 uSize;\nuniform vec3 uGround;\nuniform vec3 uInkA;\nuniform vec3 uInkB;\nuniform vec3 uInkC;\nuniform vec3 uInkD;\nuniform vec3 uInkE;\n\nfloat hash(vec2 p) {\n  p = fract(p * vec2(123.34, 456.21));\n  p += dot(p, p + 45.32);\n  return fract(p.x * p.y);\n}\nfloat noise(vec2 p) {\n  vec2 i = floor(p);\n  vec2 f = fract(p);\n  f = f * f * (3.0 - 2.0 * f);\n  return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), f.x), mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), f.x), f.y);\n}\n\nvec3 pick(float h) {\n  vec3 c = uInkA;\n  c = mix(c, uInkB, step(0.26, h));\n  c = mix(c, uInkC, step(0.47, h));\n  c = mix(c, uInkD, step(0.66, h));\n  c = mix(c, uInkE, step(0.84, h));\n  return c;\n}\n\n// One throw of the brush: a scatter of round drops, each with pigment gathered at its rim\n// and a hairline of bare bath pushed out around it.\nvec3 throwDrops(vec2 q, float seed, float scale, float fill, vec3 under) {\n  vec2 g = q * scale + seed * vec2(13.1, 7.7);\n  g += (vec2(noise(g * 0.8 + seed), noise(g * 0.8 + seed + 5.2)) - 0.5) * 0.5;\n  vec2 id = floor(g);\n  vec2 f = fract(g);\n  float there = step(hash(id + seed * 2.3), fill);\n  vec2 c = 0.5 + (vec2(hash(id + seed), hash(id.yx + seed + 3.7)) - 0.5) * 0.34;\n  float r = 0.15 + 0.17 * hash(id + seed * 3.1);\n  float d = length(f - c) - r;\n  float aa = 0.016 * scale;\n  vec3 ink = pick(hash(id + seed * 9.7));\n  ink *= 1.0 - 0.3 * smoothstep(-0.07, 0.0, d);\n  ink *= 0.9 + 0.2 * noise(g * 9.0);\n  vec3 col = mix(under, uSize, there * 0.85 * smoothstep(0.03 + aa, 0.0, abs(d - 0.022)));\n  return mix(col, ink, there * smoothstep(aa, -aa, d));\n}\n\n// Distance from p to the short line the stylus travelled.\nfloat toSegment(vec2 p, vec2 c, vec2 m) {\n  vec2 a = c - 0.5 * m;\n  float along = clamp(dot(p - a, m) / max(dot(m, m), 1e-6), 0.0, 1.0);\n  return length(p - a - m * along);\n}\n\n// Where the ink now at p lay before anything was dragged through the bath. Each tool moves\n// ink along its own direction by an amount that dies away with distance, so it can be undone\n// exactly by moving the other way, newest stroke first.\nvec2 unwind(vec2 p) {\n  for (int i = 0; i < ${SEGMENTS}; i++) {\n    vec4 s = uSeg[i];\n    p -= s.zw * exp(-toSegment(p, s.xy, s.zw) / 0.2);\n  }\n  float t = uTime * 0.035;\n  p += (vec2(noise(p * 0.45 + vec2(t, 0.0)), noise(p * 0.45 + vec2(4.1, -t))) - 0.5) * 0.5;\n  // The fine comb, drawn up the tray: pointed arches between the teeth.\n  float gap = uTeeth;\n  float fromTooth = gap * (0.5 - abs(fract(p.x / gap) - 0.5));\n  p.y -= uComb * exp(-fromTooth / (gap * 0.3));\n  // The rake before it, drawn left then right on alternate rows.\n  float row = p.y / 0.62;\n  float fromRow = 0.62 * (0.5 - abs(fract(row) - 0.5));\n  float way = mod(floor(row), 2.0) * 2.0 - 1.0;\n  p.x -= uRake * way * exp(-fromRow / 0.2);\n  return p;\n}\n\nvec3 inks(vec2 p) {\n  vec2 q = unwind(p);\n  vec3 col = uGround * (0.85 + 0.3 * noise(q * 6.0));\n  col = throwDrops(q, 1.0, 1.3, 0.8, col);\n  col = throwDrops(vec2(q.x * 0.8 + q.y * 0.6, -q.x * 0.6 + q.y * 0.8), 2.0, 1.9, 0.75, col);\n  col = throwDrops(vec2(q.x * 0.6 - q.y * 0.8, q.x * 0.8 + q.y * 0.6), 3.0, 2.7, 0.7, col);\n  col = throwDrops(q, 4.0, 4.3, 0.5, col);\n  return col;\n}\n\nfloat swell(vec2 p) {\n  float t = uTime * 0.12;\n  return noise(p * 0.9 + vec2(t, -t * 0.7)) + 0.4 * noise(p * 2.3 - vec2(t * 1.3, t));\n}\n\nvoid main() {\n  float unit = min(uRes.x, uRes.y);\n  vec2 p = (gl_FragCoord.xy - 0.5 * uRes) / unit * uSpan;\n  float px = uSpan / unit;\n\n  // Four taps inside the pixel keep the hair-thin feathers from crawling.\n  vec3 col = inks(p + px * vec2(0.38, 0.13));\n  col += inks(p + px * vec2(-0.13, 0.38));\n  col += inks(p + px * vec2(-0.38, -0.13));\n  col += inks(p + px * vec2(0.13, -0.38));\n  col *= 0.25;\n\n  // Daylight falls from the window side of the room.\n  vec2 c = gl_FragCoord.xy / uRes - 0.5;\n  col *= 0.86 + 0.3 * (c.y * 0.7 - c.x * 0.5) + 0.06;\n\n  // The surface is liquid: it carries a slow swell, and mirrors the window above the bench.\n  float e = 0.05;\n  float h = swell(p);\n  vec2 slope = vec2(swell(p + vec2(e, 0.0)) - h, swell(p + vec2(0.0, e)) - h) / e;\n  vec3 n = normalize(vec3(-slope * 0.0045, 1.0));\n  vec3 view = normalize(vec3(-p * 0.25, 1.0));\n  vec3 r = reflect(-view, n);\n  vec2 w = r.xy / r.z - uWindow;\n  w = vec2(w.x * 0.97 + w.y * 0.24, -w.x * 0.24 + w.y * 0.97);\n  vec2 pane = abs(w) - vec2(0.085, 0.13);\n  float glass = smoothstep(0.007, -0.007, max(pane.x, pane.y));\n  float bars = smoothstep(0.003, 0.008, abs(w.x)) * smoothstep(0.003, 0.008, abs(w.y + 0.015));\n  float halo = exp(-dot(w, w) * 9.0);\n  float fres = 0.05 + 0.95 * pow(1.0 - max(dot(view, n), 0.0), 5.0);\n  col += vec3(0.82, 0.9, 1.0) * uGloss * (glass * bars * (0.2 + 0.14 * smoothstep(-0.13, 0.13, w.y)) + halo * 0.06);\n  col += vec3(0.6, 0.7, 0.85) * fres * 0.2 * uGloss;\n\n  col *= 1.0 - 0.5 * dot(c, c);\n  col += (hash(gl_FragCoord.xy) - 0.5) * 0.012;\n  gl_FragColor = vec4(pow(max(col, 0.0), vec3(0.94)), 1.0);\n}`;\n\nconst mix = (a: number, b: number, t: number) => a + (b - a) * t;\nconst ease = (t: number) => {\n  const k = Math.min(1, Math.max(0, t));\n  return k * k * (3 - 2 * k);\n};\n\ntype Move = { x: number; y: number; mx: number; my: number; born: number };\n\n/** One fragment shader fills the block. `onLive` reports when a frame has been painted. */\nfunction BathCanvas({ onLive }: { onLive: (live: boolean) => void }) {\n  const ref = useRef<HTMLCanvasElement>(null);\n\n  useEffect(() => {\n    const canvas = ref.current;\n    const gl = canvas?.getContext(\"webgl\", { antialias: false, alpha: false });\n    if (!canvas || !gl) return; // no WebGL: the CSS pattern underneath stays\n\n    const compile = (type: number, source: string) => {\n      const s = gl.createShader(type)!;\n      gl.shaderSource(s, source);\n      gl.compileShader(s);\n      return s;\n    };\n    const program = gl.createProgram()!;\n    gl.attachShader(program, compile(gl.VERTEX_SHADER, VERTEX));\n    gl.attachShader(program, compile(gl.FRAGMENT_SHADER, FRAGMENT));\n    gl.linkProgram(program);\n    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) return;\n    gl.useProgram(program);\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    const position = gl.getAttribLocation(program, \"position\");\n    gl.enableVertexAttribArray(position);\n    gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);\n    const at = (name: string) => gl.getUniformLocation(program, name);\n    const u = { res: at(\"uRes\"), time: at(\"uTime\"), span: at(\"uSpan\"), seg: at(\"uSeg[0]\"), window: at(\"uWindow\") };\n    gl.uniform1f(at(\"uRake\"), bath.rake);\n    gl.uniform1f(at(\"uComb\"), bath.comb);\n    gl.uniform1f(at(\"uTeeth\"), bath.teeth);\n    gl.uniform1f(at(\"uGloss\"), bath.gloss);\n    gl.uniform3fv(at(\"uSize\"), bath.size);\n    gl.uniform3fv(at(\"uGround\"), bath.ground);\n    [\"uInkA\", \"uInkB\", \"uInkC\", \"uInkD\", \"uInkE\"].forEach((name, i) => gl.uniform3fv(at(name), bath.inks[i]));\n\n    const still = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    const half = { x: 2.3, y: 2.3 }; // half the view, in the shader's units\n    const moves: Move[] = []; // newest first\n    const packed = new Float32Array(SEGMENTS * 4);\n    const tip = { x: 0, y: 0, down: false };\n    let touched = -1e9;\n    let raf = 0;\n    let visible = true;\n    let time = 40;\n    let before = 0;\n\n    // Left alone, a stylus nobody is holding wanders the tray in slow loops.\n    const wander = (t: number) => ({\n      x: half.x * (0.56 * Math.sin(t * 0.21 + 0.4) + 0.2 * Math.sin(t * 0.67)),\n      y: half.y * (0.5 * Math.sin(t * 0.33 + 1.9) + 0.2 * Math.cos(t * 0.83)),\n    });\n    const dragTo = (x: number, y: number, when: number) => {\n      if (!tip.down) {\n        tip.x = x;\n        tip.y = y;\n        tip.down = true;\n        return;\n      }\n      let steps = 0;\n      for (;;) {\n        const dx = x - tip.x;\n        const dy = y - tip.y;\n        const far = Math.hypot(dx, dy);\n        if (far < SEGMENT_LENGTH || steps++ > 5) break;\n        const mx = (dx / far) * SEGMENT_LENGTH;\n        const my = (dy / far) * SEGMENT_LENGTH;\n        moves.unshift({ x: tip.x + mx / 2, y: tip.y + my / 2, mx, my, born: when });\n        if (moves.length > SEGMENTS) moves.pop();\n        tip.x += mx;\n        tip.y += my;\n      }\n    };\n    const draw = () => {\n      packed.fill(0);\n      moves.forEach((m, i) => {\n        // A move fades in as it is made and relaxes with age, and the oldest are let go first.\n        const age = time - m.born;\n        const hold = ease(age / 0.25) * (1 - ease((age - SEGMENT_LIFE * 0.5) / (SEGMENT_LIFE * 0.5))) * (1 - ease((i - SEGMENTS + 8) / 7));\n        packed.set([m.x, m.y, m.mx * hold * bath.stylus, m.my * hold * bath.stylus], i * 4);\n      });\n      gl.uniform4fv(u.seg, packed);\n      gl.uniform1f(u.time, time);\n      gl.uniform2f(u.window, half.x * (0.12 + 0.012 * Math.sin(time * 0.11)), half.y * (0.1 + 0.012 * Math.sin(time * 0.17 + 1)));\n      gl.drawArrays(gl.TRIANGLES, 0, 3);\n    };\n    const seed = () => {\n      // Start with a flourish already drawn, as if the marbler has just lifted the stylus.\n      moves.length = 0;\n      tip.down = false;\n      for (let t = time - 5; t <= time; t += 0.05) {\n        const g = wander(t);\n        dragTo(g.x, g.y, t);\n      }\n    };\n    const resize = () => {\n      const w = canvas.clientWidth;\n      const h = canvas.clientHeight || 1;\n      const scale = Math.min(Math.min(Math.max(window.devicePixelRatio || 1, 1), 2) * bath.quality, Math.sqrt(bath.maxPixels / Math.max(1, w * h)));\n      canvas.width = Math.max(1, Math.round(w * scale));\n      canvas.height = Math.max(1, Math.round(h * scale));\n      // A narrow screen looks at less of the tray, so the feathers stay the same size in the hand.\n      const span = w < 640 ? bath.spanNarrow : bath.span;\n      half.x = (span * 0.5 * w) / Math.min(w, h);\n      half.y = (span * 0.5 * h) / Math.min(w, h);\n      gl.uniform1f(u.span, span);\n      seed();\n      gl.viewport(0, 0, canvas.width, canvas.height);\n      gl.uniform2f(u.res, canvas.width, canvas.height);\n      draw();\n      onLive(true);\n    };\n    const loop = (now: number) => {\n      raf = requestAnimationFrame(loop);\n      const dt = Math.min((now - (before || now)) / 1000, 0.05);\n      before = now;\n      time += dt * bath.speed;\n      if (now - touched > 2400) {\n        const g = wander(time);\n        // Coming back from the pointer, lift the stylus and set it down again where the loop is.\n        if (touched > 0) {\n          tip.down = false;\n          touched = -1e9;\n        }\n        dragTo(g.x, g.y, time);\n      }\n      draw();\n    };\n    const start = () => {\n      cancelAnimationFrame(raf);\n      before = 0;\n      if (still) draw();\n      else if (visible && !document.hidden) raf = requestAnimationFrame(loop);\n    };\n    const onPointer = (e: PointerEvent) => {\n      const box = canvas.getBoundingClientRect();\n      const x = ((e.clientX - box.left) / box.width) * 2 - 1;\n      const y = 1 - ((e.clientY - box.top) / box.height) * 2;\n      if (Math.abs(x) > 1 || Math.abs(y) > 1) {\n        if (touched > 0) tip.down = false;\n        return;\n      }\n      if (touched < 0) tip.down = false;\n      touched = performance.now();\n      dragTo(x * half.x, y * half.y, time);\n    };\n    const onLost = (e: Event) => {\n      e.preventDefault();\n      cancelAnimationFrame(raf);\n      onLive(false);\n    };\n\n    const sizeWatcher = new ResizeObserver(resize);\n    sizeWatcher.observe(canvas);\n    const viewWatcher = new IntersectionObserver(([entry]) => {\n      visible = entry.isIntersecting;\n      start();\n    });\n    viewWatcher.observe(canvas);\n    document.addEventListener(\"visibilitychange\", start);\n    if (!still) window.addEventListener(\"pointermove\", onPointer, { passive: true });\n    canvas.addEventListener(\"webglcontextlost\", onLost);\n    resize();\n    start();\n\n    return () => {\n      cancelAnimationFrame(raf);\n      sizeWatcher.disconnect();\n      viewWatcher.disconnect();\n      document.removeEventListener(\"visibilitychange\", start);\n      window.removeEventListener(\"pointermove\", onPointer);\n      canvas.removeEventListener(\"webglcontextlost\", onLost);\n      gl.getExtension(\"WEBGL_lose_context\")?.loseContext();\n    };\n  }, [onLive]);\n\n  return <canvas ref={ref} aria-hidden=\"true\" className=\"absolute inset-0 h-full w-full\" />;\n}\n\n/** The sheet without a shader: rows of combed arches from one repeating CSS gradient. Shown first, and kept when WebGL is missing. */\nfunction StillBath() {\n  return (\n    <div aria-hidden=\"true\" className=\"absolute inset-0 overflow-hidden bg-[#16224f]\">\n      <div className=\"absolute inset-0 bg-[radial-gradient(ellipse_at_50%_0%,#f2e6c9_0%,#f2e6c9_9%,#16224f_10%,#16224f_19%,#c23321_20%,#c23321_29%,#f2e6c9_30%,#f2e6c9_33%,#1c3078_34%,#1c3078_45%,#dea338_46%,#dea338_53%,#16224f_54%,#16224f_62%,#1a5c54_63%,#1a5c54_69%,#f2e6c9_70%,#f2e6c9_72%,#16224f_73%)] bg-[length:58px_44px]\" />\n      <div className=\"absolute inset-0 bg-[radial-gradient(60%_55%_at_58%_34%,rgba(255,255,255,0.22)_0%,rgba(255,255,255,0)_55%,rgba(8,12,34,0.5)_100%)]\" />\n    </div>\n  );\n}\n\nexport default function MarbledPaperWebglBackgroundWithFloatingInksCombedIntoFeathersOnAWetSizeBath() {\n  const [live, setLive] = useState(false);\n\n  return (\n    <section className=\"relative isolate h-[620px] overflow-hidden bg-[#16224f] sm:h-[760px]\">\n      <StillBath />\n      <div className={`pointer-events-none absolute inset-0 transition-opacity duration-700 motion-reduce:transition-none ${live ? \"opacity-100\" : \"opacity-0\"}`}>\n        <BathCanvas onLive={setLive} />\n      </div>\n      <p className=\"absolute bottom-5 left-5 rounded-full bg-[#0b1230]/85 px-3.5 py-2 font-mono text-[11px] uppercase tracking-[0.2em] text-amber-50 sm:bottom-7 sm:left-7\">\n        Marbling bath <span className=\"hidden text-amber-200 sm:inline\">/ five inks, raked and combed</span>\n      </p>\n    </section>\n  );\n}\n"}]}
