{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"raked-zen-sand-garden-webgl-background-with-basalt-stones-and-a-slow-turning-sun-shadow","type":"registry:block","title":"Raked Zen Sand Garden WebGL Background with Basalt Stones and a Slow Turning Sun Shadow","description":"Zen garden background: a WebGL shader rakes pale sand around dark basalt stones and a low sun swings their shadows slowly round. Free React and HTML code.","dependencies":[],"files":[{"path":"components/we-inc/raked-zen-sand-garden-webgl-background-with-basalt-stones-and-a-slow-turning-sun-shadow.tsx","type":"registry:component","content":"import { useEffect, useRef, useState } from \"react\";\n\n// Everything about the garden. Colours are red, green, blue from 0 to 1.\nconst garden = {\n  speed: 1, // how fast the sun and the branch move; 0 stops the afternoon\n  grooves: 34, // rake lines across the short side of the block\n  rings: 5, // rake lines circling each stone before the straight lines take over\n  relief: 0.24, // how deep the rake cut; 0.15 is a light comb, 0.45 a heavy one\n  canopy: 0.8, // darkness of the branch shadow in the corner; 0 clears the sky\n  quality: 0.9, // share of the device pixels that are drawn\n  maxPixels: 1000000, // the canvas never draws more pixels than this\n  sand: [0.93, 0.85, 0.71],\n  skylight: [0.64, 0.61, 0.66], // the colour of the shadows\n  stone: [0.25, 0.25, 0.27],\n  // x and y place a stone, from -0.5 to 0.5 across the block. size is in rake lines, stretch makes it long,\n  // turn spins it (in radians) and height says how far it stands out of the sand.\n  stones: [\n    { x: 0.2, y: 0.08, size: 3.3, stretch: 1.45, turn: 0.5, height: 3.4 },\n    { x: -0.27, y: -0.2, size: 2.1, stretch: 1.2, turn: -0.9, height: 2.0 },\n    { x: -0.14, y: 0.27, size: 1.25, stretch: 1.3, turn: 2.2, height: 1.1 },\n  ],\n};\n\nconst STONES = garden.stones.length;\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 uGrooves;\nuniform float uRings;\nuniform float uRelief;\nuniform float uCanopy;\nuniform vec2 uSun;\nuniform vec4 uStones[${STONES}];\nuniform vec2 uShape[${STONES}];\nuniform vec3 uSand;\nuniform vec3 uSky;\nuniform vec3 uStone;\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\n// One stone. x is the distance from its edge in rake lines (negative inside); y runs from 0 at its\n// middle to 1 at its edge. The outline is an ellipse with a few lumps, so no two stones match.\nvec2 stoneEdge(vec2 p, vec4 s, vec2 shape) {\n  vec2 d = p - s.xy + 0.001;\n  float c = cos(shape.x);\n  float si = sin(shape.x);\n  d = vec2(d.x * c + d.y * si, -d.x * si + d.y * c);\n  float a = atan(d.y, d.x * 0.8);\n  float lumps = 1.0 + 0.05 * sin(3.0 * a + shape.x * 7.0) + 0.03 * sin(5.0 * a + 1.3 + shape.x * 3.0);\n  vec2 r = s.z * lumps * vec2(s.w, 1.0);\n  float k1 = length(d / r);\n  float k2 = length(d / (r * r));\n  return vec2(k1 * (k1 - 1.0) / k2, k1);\n}\n\n// Height of the garden at a point: x is the height, y the distance to the nearest stone.\nvec2 ground(vec2 p) {\n  float near = 1000.0;\n  float rock = 0.0;\n  for (int i = 0; i < ${STONES}; i++) {\n    vec2 d = stoneEdge(p, uStones[i], uShape[i]);\n    near = min(near, d.x);\n    // A river stone: steep where it meets the sand, nearly flat on top.\n    float t = min(d.y, 1.0);\n    rock = max(rock, uShape[i].y * sqrt(1.0 - t * t * t * t));\n  }\n  // Straight lines pulled by hand are never quite straight.\n  float line = p.y * 0.9 + p.x * 0.44 + 0.3 * sin(p.x * 0.19 + 1.3) + 0.14 * sin(p.x * 0.47 + p.y * 0.13);\n  float c = near < uRings ? near : line;\n  float s = sin(3.14159265 * c);\n  float furrow = 1.0 - sqrt(s * s + 0.035);\n  // The comb lifts where the straight lines meet the outermost ring, which leaves a smooth seam.\n  float sandH = uRelief * furrow * smoothstep(0.0, 0.5, near) * smoothstep(0.0, 0.3, abs(near - uRings));\n  sandH += 0.34 * exp(-max(near, 0.0) * 2.2);\n  sandH += 0.12 * sin(p.x * 0.11 + 0.7) * sin(p.y * 0.14 + 2.1);\n  return vec2(max(sandH, rock), near);\n}\n\nvoid main() {\n  float unit = min(uRes.x, uRes.y);\n  float pxSize = uGrooves / unit;\n  vec2 p = (gl_FragCoord.xy - 0.5 * uRes) * pxSize;\n\n  vec2 here = ground(p);\n  float e = 0.05;\n  vec2 slope = vec2(ground(p + vec2(e, 0.0)).x - here.x, ground(p + vec2(0.0, e)).x - here.x) / e;\n  float isStone = smoothstep(pxSize, -pxSize, here.y);\n\n  // Grains: every pixel of sand leans its own way a little, which is what makes it glitter in low sun.\n  vec2 fc = floor(gl_FragCoord.xy);\n  vec2 grit = vec2(hash(fc), hash(fc + 19.19)) - 0.5;\n  vec2 lumps = vec2(noise(p * 5.0), noise(p * 5.0 + 31.0)) - 0.5;\n  vec2 rough = mix(grit * 0.36 + lumps * 0.2, (vec2(noise(p * 1.5), noise(p * 1.5 + 9.0)) - 0.5) * 0.16 + grit * 0.07, isStone);\n  vec3 n = normalize(vec3(-slope + rough, 1.0));\n\n  float ce = cos(uSun.y);\n  vec3 L = vec3(cos(uSun.x) * ce, sin(uSun.x) * ce, sin(uSun.y));\n\n  // Walk toward the sun. Anything standing above the ray, a stone or the next ridge of sand, shades this point.\n  vec3 at = vec3(p, here.x);\n  float shade = 1.0;\n  float stepLen = 0.07;\n  float along = 0.0;\n  for (int i = 0; i < 18; i++) {\n    along += stepLen;\n    stepLen *= 1.33;\n    vec3 s = at + L * along;\n    float gap = s.z - ground(s.xy).x;\n    shade = min(shade, 0.55 + 5.0 * gap / along);\n  }\n  shade = smoothstep(0.0, 1.0, clamp(shade, 0.0, 1.0));\n\n  // A branch overhangs one corner. Its leaves throw soft, shifting patches.\n  vec2 uv = gl_FragCoord.xy / uRes;\n  vec2 lp = p * 0.085 - L.xy * 1.1 + vec2(sin(uTime * 0.31), cos(uTime * 0.23)) * 0.09;\n  float leaves = 0.58 * noise(lp * 1.5 + 3.0) + 0.3 * noise(lp * 3.7 + vec2(uTime * 0.04, 0.0)) + 0.12 * noise(lp * 8.1);\n  float corner = smoothstep(0.85, 1.5, uv.x * 0.85 + uv.y * 0.95 + 0.3 * noise(lp * 0.8));\n  float canopy = smoothstep(0.52, 0.4, leaves) * corner * uCanopy;\n\n  float lit = max(dot(n, L), 0.0);\n  float direct = lit * shade * (1.0 - canopy);\n  vec3 sun = vec3(1.0, 0.93, 0.8);\n\n  // Sand.\n  float tone = 0.92 + 0.12 * noise(p * 1.7) + 0.05 * (hash(fc + 3.0) - 0.5);\n  vec3 sand = uSand * tone;\n  sand *= 1.0 - 0.3 * step(0.992, hash(fc + 71.3));\n  sand *= 1.0 - 0.3 * exp(-max(here.y, 0.0) * 1.6);\n  vec3 col = sand * (uSky * 0.78 + sun * direct * 1.5);\n  col += sun * pow(lit, 24.0) * shade * (1.0 - canopy) * step(0.93, hash(fc + 5.5)) * 0.35;\n\n  // Stone: dark, a little speckled, with a dull shine where it faces the sun.\n  float speck = noise(p * 6.0) * 0.5 + hash(fc) * 0.5;\n  vec3 rock = uStone * (0.9 + 0.2 * noise(p * 0.9 + 4.0)) * (0.9 + 0.2 * speck);\n  vec3 H = normalize(L + vec3(0.0, 0.0, 1.0));\n  vec3 rockCol = rock * (uSky * 0.85 + sun * direct * 2.6) + sun * pow(max(dot(n, H), 0.0), 26.0) * shade * (1.0 - canopy) * 0.22;\n  col = mix(col, rockCol, isStone);\n\n  vec2 c = uv - 0.5;\n  col *= 1.0 - 0.3 * dot(c, c);\n  col = mix(col, 1.0 - exp(-col * 1.4), 0.35);\n  gl_FragColor = vec4(pow(max(col, 0.0), vec3(0.95)), 1.0);\n}`;\n\nconst mix = (a: number, b: number, t: number) => a + (b - a) * t;\n\n/** One fragment shader fills the block. `onLive` reports when a frame has been painted. */\nfunction SandCanvas({ 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 garden 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\"), sun: at(\"uSun\"), stones: at(\"uStones\"), shape: at(\"uShape\") };\n    gl.uniform1f(at(\"uGrooves\"), garden.grooves);\n    gl.uniform1f(at(\"uRings\"), garden.rings);\n    gl.uniform1f(at(\"uRelief\"), garden.relief);\n    gl.uniform1f(at(\"uCanopy\"), garden.canopy);\n    gl.uniform3fv(at(\"uSand\"), garden.sand);\n    gl.uniform3fv(at(\"uSky\"), garden.skylight);\n    gl.uniform3fv(at(\"uStone\"), garden.stone);\n    gl.uniform2fv(u.shape, garden.stones.flatMap((s) => [s.turn, s.height]));\n\n    const still = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    // The sun: its compass direction and its height above the horizon, both in radians.\n    const sun = { turn: 2.5, lift: 0.42, toTurn: 2.5, toLift: 0.42, touched: -1e9 };\n    let raf = 0;\n    let visible = true;\n    let time = 12;\n    let before = 0;\n\n    const draw = () => {\n      gl.uniform1f(u.time, time);\n      gl.uniform2f(u.sun, sun.turn, sun.lift);\n      gl.drawArrays(gl.TRIANGLES, 0, 3);\n    };\n    const resize = () => {\n      const w = canvas.clientWidth || 1;\n      const h = canvas.clientHeight || 1;\n      const scale = Math.min(Math.min(Math.max(window.devicePixelRatio || 1, 1), 2) * garden.quality, Math.sqrt(garden.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      // Stones are placed as a share of the block, so they stay in frame on a tall phone.\n      const short = Math.min(w, h);\n      gl.uniform4fv(u.stones, garden.stones.flatMap((s) => [(s.x * w * garden.grooves) / short, (s.y * h * garden.grooves) / short, s.size, s.stretch]));\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 * garden.speed;\n      // Left alone, the afternoon runs by itself: the sun swings round and sinks, then comes back.\n      if (now - sun.touched > 2600) {\n        sun.toTurn = 2.55 + 0.75 * Math.sin(time * 0.21);\n        sun.toLift = 0.4 + 0.14 * Math.sin(time * 0.33 + 1.0);\n      }\n      const k = 1 - Math.exp(-dt * 2.6);\n      sun.turn = mix(sun.turn, sun.toTurn, k);\n      sun.lift = mix(sun.lift, sun.toLift, k);\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 - 0.5;\n      const y = 0.5 - (e.clientY - box.top) / box.height;\n      if (Math.abs(x) > 0.5 || Math.abs(y) > 0.5) return;\n      // The sun stands where the pointer is: its direction from the middle of the garden, and lower the further out it goes.\n      sun.toTurn = Math.atan2(y * box.height, x * box.width);\n      // Take the short way round when the pointer crosses behind the centre.\n      while (sun.toTurn - sun.turn > Math.PI) sun.toTurn -= Math.PI * 2;\n      while (sun.toTurn - sun.turn < -Math.PI) sun.toTurn += Math.PI * 2;\n      sun.toLift = mix(0.85, 0.24, Math.min(1, Math.hypot(x, y) * 2));\n      sun.touched = performance.now();\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 garden without a shader: CSS rake lines, two stones and their rings. Shown first, and kept when WebGL is missing. */\nfunction StillSand() {\n  const lines = \"repeating-linear-gradient(176deg, #e9dcc3 0px, #d9c8a8 9px, #b9a481 15px, #efe3cc 19px, #e9dcc3 22px)\";\n  const rings = \"repeating-radial-gradient(ellipse at center, #e9dcc3 0px, #d9c8a8 9px, #b9a481 15px, #efe3cc 19px, #e9dcc3 22px)\";\n  return (\n    <div aria-hidden=\"true\" className=\"absolute inset-0 overflow-hidden bg-[#dccdb0]\" style={{ backgroundImage: lines }}>\n      {[\n        { left: \"70%\", top: \"42%\", w: 190, h: 132, turn: -28 },\n        { left: \"23%\", top: \"70%\", w: 110, h: 92, turn: 40 },\n      ].map((s) => (\n        <span key={s.left} className=\"absolute -translate-x-1/2 -translate-y-1/2 rounded-[50%]\" style={{ left: s.left, top: s.top, width: s.w + 220, height: s.h + 220, backgroundImage: rings, transform: `translate(-50%, -50%) rotate(${s.turn}deg)` }}>\n          <span className=\"absolute left-1/2 top-1/2 rounded-[46%_54%_52%_48%/55%_48%_52%_45%] bg-[radial-gradient(circle_at_34%_30%,#5b5a5c_0%,#2c2b2e_55%,#1a191c_100%)] shadow-[26px_30px_26px_-6px_rgba(60,52,70,0.55)]\" style={{ width: s.w, height: s.h, transform: \"translate(-50%, -50%)\" }} />\n        </span>\n      ))}\n      <div className=\"raked-zen-sand-garden-webgl-background-with-basalt-stones-and-a-slow-turning-sun-shadow-shade absolute -inset-[10%] bg-[radial-gradient(34%_30%_at_88%_14%,rgba(70,66,84,0.5)_0%,rgba(70,66,84,0)_100%),radial-gradient(22%_26%_at_66%_6%,rgba(70,66,84,0.4)_0%,rgba(70,66,84,0)_100%),radial-gradient(20%_30%_at_98%_44%,rgba(70,66,84,0.38)_0%,rgba(70,66,84,0)_100%)]\" />\n    </div>\n  );\n}\n\nexport default function RakedZenSandGardenWebglBackgroundWithBasaltStonesAndASlowTurningSunShadow() {\n  const [live, setLive] = useState(false);\n\n  return (\n    <section className=\"relative isolate h-[620px] overflow-hidden bg-[#dccdb0] sm:h-[760px]\">\n      <style>{`\n        @keyframes raked-zen-sand-garden-webgl-background-with-basalt-stones-and-a-slow-turning-sun-shadow-shade { 0%, 100% { transform: translate3d(0, 0, 0); } 50% { transform: translate3d(-2.5%, 2%, 0); } }\n        .raked-zen-sand-garden-webgl-background-with-basalt-stones-and-a-slow-turning-sun-shadow-shade { animation: raked-zen-sand-garden-webgl-background-with-basalt-stones-and-a-slow-turning-sun-shadow-shade 7s ease-in-out infinite; }\n        @media (prefers-reduced-motion: reduce) { .raked-zen-sand-garden-webgl-background-with-basalt-stones-and-a-slow-turning-sun-shadow-shade { animation: none; } }\n      `}</style>\n      <StillSand />\n      <div className={`pointer-events-none absolute inset-0 transition-opacity duration-700 motion-reduce:transition-none ${live ? \"opacity-100\" : \"opacity-0\"}`}>\n        <SandCanvas onLive={setLive} />\n      </div>\n      <p className=\"absolute bottom-5 left-5 rounded-full bg-[#211d18]/85 px-3.5 py-2 font-mono text-[11px] uppercase tracking-[0.2em] text-stone-50 sm:bottom-7 sm:left-7\">\n        Raked sand <span className=\"text-stone-300\">/ three stones, late sun</span>\n      </p>\n    </section>\n  );\n}\n"}]}
