{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"swimming-pool-floor-webgl-background-with-mosaic-tiles-under-drifting-caustic-light","type":"registry:block","title":"Swimming Pool Floor WebGL Background with Mosaic Tiles Under Drifting Caustic Light","description":"Pool background in WebGL: a shader draws a mosaic tile floor under clear water with caustic light drifting over it. Copy the React code or the HTML free.","dependencies":[],"files":[{"path":"components/we-inc/swimming-pool-floor-webgl-background-with-mosaic-tiles-under-drifting-caustic-light.tsx","type":"registry:component","content":"import { useEffect, useRef, useState } from \"react\";\n\n// Everything about the pool. Colours are red, green, blue from 0 to 1.\nconst pool = {\n  speed: 1, // how fast the water moves; 0.5 is a still afternoon\n  tiles: 17, // mosaic tiles across the short side of the block\n  depth: 0.6, // how far the floor is below the surface; deeper water draws finer, brighter light\n  chop: 1, // height of the waves; 0.6 is a calm pool, 1.4 one somebody just left\n  bend: 0.05, // how much the water bends the view of the tiles\n  ripple: 1, // strength of the rings under the pointer; 0 switches them off\n  quality: 0.9, // share of the device pixels that are drawn\n  maxPixels: 1200000, // the canvas never draws more pixels than this\n  tileLight: [0.62, 0.9, 0.93], // palest tile\n  tileDark: [0.15, 0.64, 0.83], // deepest tile\n  lane: [0.03, 0.12, 0.36], // the lane line\n  grout: [0.88, 0.96, 0.95], // the lines between tiles\n};\n\nconst RINGS = 4;\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 uTiles;\nuniform float uDepth;\nuniform float uChop;\nuniform float uBend;\nuniform vec4 uRings[${RINGS}];\nuniform vec3 uTileLight;\nuniform vec3 uTileDark;\nuniform vec3 uLane;\nuniform vec3 uGrout;\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\nvec2 wave(vec2 w, vec2 dir, float freq, float rate, float amp) {\n  return dir * (amp * freq * cos(dot(w, dir) * freq + uTime * rate));\n}\n\n// The slope of the water surface at a point: seven swells crossing each other,\n// pushed around by slow noise so they never line up, plus a ring for each recent touch.\nvec2 slope(vec2 p) {\n  vec2 w = p + 0.5 * vec2(noise(p * 0.55 + vec2(0.0, uTime * 0.11)), noise(p * 0.55 + vec2(4.1, -uTime * 0.09)));\n  vec2 g = wave(w, vec2(0.92, 0.39), 1.9, 1.05, 0.2);\n  g += wave(w, vec2(-0.45, 0.89), 2.6, 1.3, 0.12);\n  g += wave(w, vec2(0.2, -0.98), 3.7, 1.6, 0.065);\n  g += wave(w, vec2(-0.83, -0.56), 5.3, 2.0, 0.036);\n  g += wave(w, vec2(0.71, 0.7), 7.1, 2.5, 0.022);\n  g += wave(w, vec2(-0.98, 0.17), 9.7, 3.0, 0.013);\n  g += wave(w, vec2(0.36, 0.93), 13.1, 3.6, 0.008);\n  for (int i = 0; i < ${RINGS}; i++) {\n    vec2 d = p - uRings[i].xy;\n    float r = length(d) + 0.0001;\n    float age = uTime - uRings[i].z;\n    float x = r - age * 1.5;\n    float env = uRings[i].w * exp(-age * 1.1) * exp(-x * x * 5.0) * smoothstep(0.0, 0.25, age);\n    g -= d / r * (env * 0.85 * sin(x * 11.0));\n  }\n  return g * uChop;\n}\n\nfloat focus(float d, float tr, float det) {\n  return 1.0 / (abs(1.0 + d * tr + d * d * det) + 0.055);\n}\n\nvoid main() {\n  float unit = min(uRes.x, uRes.y);\n  vec2 p = (gl_FragCoord.xy - 0.5 * uRes) / unit * 4.0;\n\n  float e = 0.012;\n  vec2 g = slope(p);\n  vec2 gx = (slope(p + vec2(e, 0.0)) - g) / e;\n  vec2 gy = (slope(p + vec2(0.0, e)) - g) / e;\n  float tr = gx.x + gy.y;\n  float det = gx.x * gy.y - gy.x * gx.y;\n\n  // Light: where the surface curves like a lens the sun is gathered into bright threads on the floor.\n  // Red, green and blue bend by slightly different amounts, which puts a faint rainbow on each thread.\n  vec3 gather = vec3(focus(uDepth * 0.92, tr, det), focus(uDepth, tr, det), focus(uDepth * 1.08, tr, det));\n  vec3 light = 0.8 + 0.17 * (gather - 0.95) / (1.0 + 0.035 * gather);\n\n  // The floor, seen through the moving surface.\n  float scale = uTiles / 4.0;\n  vec2 f0 = p - g * uBend;\n  vec2 fl = vec2(f0.x * 0.966 + f0.y * 0.259, -f0.x * 0.259 + f0.y * 0.966) * scale;\n  vec2 cell = floor(fl);\n  vec2 f = fract(fl);\n  float px = uTiles / unit;\n  float inset = min(min(f.x, f.y), min(1.0 - f.x, 1.0 - f.y));\n  float tile = smoothstep(0.045, 0.045 + px * 1.6 + 0.02, inset);\n\n  float r = hash(cell);\n  float r2 = hash(cell + 31.7);\n  vec3 glaze = mix(uTileDark, uTileLight, r * r) * (0.9 + 0.2 * hash(cell + 7.7));\n  glaze = mix(glaze, uTileLight * 1.08, step(0.9, r2) * 0.55);\n  // The lane line, three tiles wide, ending in a crossbar the way they do short of the wall.\n  float laneX = abs(cell.x - 4.0);\n  float inLane = step(laneX, 1.0) * step(-5.0, cell.y);\n  float inBar = step(laneX, 4.0) * step(-7.0, cell.y) * step(cell.y, -5.0);\n  float dark = max(inLane, inBar);\n  glaze = mix(glaze, uLane * (0.75 + 0.6 * r), dark);\n  // Each tile is a little pillow of glass: brighter toward the top left edge, darker on the far side.\n  float rim = 1.0 - smoothstep(0.0, 0.3, inset);\n  glaze *= 0.93 + 0.07 * smoothstep(0.0, 0.22, inset);\n  glaze += 0.07 * rim * (f.y - f.x);\n  glaze *= 0.95 + 0.1 * noise(fl * 3.1 + r * 20.0);\n  vec3 grout = uGrout * (0.86 + 0.14 * noise(fl * 9.0));\n  vec3 floorCol = mix(grout, glaze, tile);\n\n  vec3 col = floorCol * (0.8 + (light - 0.8) * vec3(1.0, 0.97, 0.88));\n  // Water takes the red out and adds its own blue green.\n  col *= vec3(0.86, 0.98, 1.0);\n  col = mix(col, vec3(0.3, 0.78, 0.88) * (0.75 + 0.25 * light.g), 0.07);\n\n  // Glints of sun on the surface itself.\n  vec3 ns = normalize(vec3(-g * 0.42, 1.0));\n  float glint = pow(max(dot(ns, normalize(vec3(0.22, 0.34, 1.0))), 0.0), 2600.0);\n  col += vec3(1.0, 0.99, 0.94) * glint * 0.75;\n\n  vec2 c = gl_FragCoord.xy / uRes - 0.5;\n  col *= 1.0 - 0.32 * dot(c, c);\n  col = mix(col, 1.0 - exp(-col * 1.35), 0.5);\n  col += (hash(gl_FragCoord.xy + fract(uTime) * 13.0) - 0.5) * 0.012;\n  gl_FragColor = vec4(col, 1.0);\n}`;\n\n/** One fragment shader fills the block. `onLive` reports when a frame has been painted. */\nfunction PoolCanvas({ 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 pool 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\"), rings: at(\"uRings\") };\n    gl.uniform1f(at(\"uTiles\"), pool.tiles);\n    gl.uniform1f(at(\"uDepth\"), pool.depth);\n    gl.uniform1f(at(\"uChop\"), pool.chop);\n    gl.uniform1f(at(\"uBend\"), pool.bend);\n    gl.uniform3fv(at(\"uTileLight\"), pool.tileLight);\n    gl.uniform3fv(at(\"uTileDark\"), pool.tileDark);\n    gl.uniform3fv(at(\"uLane\"), pool.lane);\n    gl.uniform3fv(at(\"uGrout\"), pool.grout);\n\n    const still = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    // Each ring: where it started (in floor units), when, and how strong.\n    const rings = new Float32Array(RINGS * 4);\n    for (let i = 0; i < RINGS; i++) rings[i * 4 + 2] = -100;\n    let next = 0;\n    let raf = 0;\n    let visible = true;\n    let time = 30;\n    let before = 0;\n    let w = 1;\n    let h = 1;\n    let lastDrop = 0;\n    let touched = -1e9;\n    const last = { x: 0, y: 0 };\n\n    const drop = (x: number, y: number, strength: number) => {\n      rings.set([x, y, time, strength * pool.ripple], next * 4);\n      next = (next + 1) % RINGS;\n      lastDrop = time;\n    };\n    const draw = () => {\n      gl.uniform1f(u.time, time);\n      gl.uniform4fv(u.rings, rings);\n      gl.drawArrays(gl.TRIANGLES, 0, 3);\n    };\n    const resize = () => {\n      w = canvas.clientWidth || 1;\n      h = canvas.clientHeight || 1;\n      const scale = Math.min(Math.min(Math.max(window.devicePixelRatio || 1, 1), 2) * pool.quality, Math.sqrt(pool.maxPixels / (w * h)));\n      canvas.width = Math.max(1, Math.round(w * scale));\n      canvas.height = Math.max(1, Math.round(h * scale));\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 * pool.speed;\n      // Nobody in the water: something small drops in every few seconds.\n      if (now - touched > 2500 && time - lastDrop > 2.6) {\n        const wide = (w / Math.min(w, h)) * 2;\n        const tall = (h / Math.min(w, h)) * 2;\n        drop(Math.sin(time * 1.31) * wide * 0.6, Math.cos(time * 0.83) * tall * 0.55, 0.85);\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 inside = e.clientX >= box.left && e.clientX <= box.right && e.clientY >= box.top && e.clientY <= box.bottom;\n      if (!inside) return;\n      const short = Math.min(box.width, box.height);\n      const x = ((e.clientX - box.left - box.width / 2) / short) * 4;\n      const y = (-(e.clientY - box.top - box.height / 2) / short) * 4;\n      touched = performance.now();\n      // A new ring only after the pointer has travelled a little, so a slow drag leaves a wake of them.\n      if (Math.hypot(x - last.x, y - last.y) > 0.45 && time - lastDrop > 0.16) {\n        last.x = x;\n        last.y = y;\n        drop(x, y, 1);\n      }\n    };\n    const onLost = (e: Event) => {\n      e.preventDefault();\n      cancelAnimationFrame(raf);\n      onLive(false);\n    };\n\n    drop(1.1, 0.3, 0.9);\n    rings[2] = time - 0.9; // the first ring is already on its way out when the block appears\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 pool without a shader: a tiled floor in CSS with soft patches of light sliding over it. Shown first, and kept when WebGL is missing. */\nfunction StillPool() {\n  return (\n    <div aria-hidden=\"true\" className=\"absolute inset-0 overflow-hidden bg-[#3fb4cf]\">\n      <div className=\"absolute -inset-[40%] rotate-[-15deg] bg-[linear-gradient(90deg,rgba(8,34,96,0)_56%,rgba(8,34,96,0.92)_56%,rgba(8,34,96,0.92)_59.6%,rgba(8,34,96,0)_59.6%),linear-gradient(135deg,#63cfe0_0%,#2a9cc6_50%,#57c6dc_100%)]\" />\n      <div className=\"absolute -inset-[40%] rotate-[-15deg] bg-[linear-gradient(90deg,rgba(214,244,244,0.75)_0,rgba(214,244,244,0.75)_3px,rgba(214,244,244,0)_3px),linear-gradient(0deg,rgba(214,244,244,0.75)_0,rgba(214,244,244,0.75)_3px,rgba(214,244,244,0)_3px)] bg-[length:44px_44px]\" />\n      <div className=\"swimming-pool-floor-webgl-background-with-mosaic-tiles-under-drifting-caustic-light-sway absolute -inset-[20%] bg-[radial-gradient(22%_14%_at_24%_30%,rgba(255,255,255,0.5)_0%,rgba(255,255,255,0)_100%),radial-gradient(18%_26%_at_62%_44%,rgba(255,255,255,0.42)_0%,rgba(255,255,255,0)_100%),radial-gradient(26%_12%_at_78%_72%,rgba(255,255,255,0.45)_0%,rgba(255,255,255,0)_100%),radial-gradient(16%_20%_at_36%_78%,rgba(255,255,255,0.4)_0%,rgba(255,255,255,0)_100%)]\" />\n    </div>\n  );\n}\n\nexport default function SwimmingPoolFloorWebglBackgroundWithMosaicTilesUnderDriftingCausticLight() {\n  const [live, setLive] = useState(false);\n\n  return (\n    <section className=\"relative isolate h-[620px] overflow-hidden bg-[#3fb4cf] sm:h-[760px]\">\n      <style>{`\n        @keyframes swimming-pool-floor-webgl-background-with-mosaic-tiles-under-drifting-caustic-light-sway { 0%, 100% { transform: translate3d(-3%, 2%, 0) scale(1); } 50% { transform: translate3d(4%, -3%, 0) scale(1.08); } }\n        .swimming-pool-floor-webgl-background-with-mosaic-tiles-under-drifting-caustic-light-sway { animation: swimming-pool-floor-webgl-background-with-mosaic-tiles-under-drifting-caustic-light-sway 9s ease-in-out infinite; }\n        @media (prefers-reduced-motion: reduce) { .swimming-pool-floor-webgl-background-with-mosaic-tiles-under-drifting-caustic-light-sway { animation: none; } }\n      `}</style>\n      <StillPool />\n      <div className={`pointer-events-none absolute inset-0 transition-opacity duration-700 motion-reduce:transition-none ${live ? \"opacity-100\" : \"opacity-0\"}`}>\n        <PoolCanvas onLive={setLive} />\n      </div>\n      <p className=\"absolute bottom-5 left-5 rounded-full bg-[#04163f]/85 px-3.5 py-2 font-mono text-[11px] uppercase tracking-[0.2em] text-cyan-50 sm:bottom-7 sm:left-7\">\n        Pool floor <span className=\"text-cyan-200\">/ 1.4 m, noon, nobody in</span>\n      </p>\n    </section>\n  );\n}\n"}]}
