{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"polished-terrazzo-floor-webgl-background-with-marble-chips-and-brass-strips-that-catch-a-moving-lamp","type":"registry:block","title":"Polished Terrazzo Floor WebGL Background with Marble Chips and Brass Strips That Catch a Moving Lamp","description":"Terrazzo background in WebGL: a shader sets marble chips in cream cement, lays brass strips and mirrors a lamp the pointer moves. Free React and HTML code.","dependencies":[],"files":[{"path":"components/we-inc/polished-terrazzo-floor-webgl-background-with-marble-chips-and-brass-strips-that-catch-a-moving-lamp.tsx","type":"registry:component","content":"import { useEffect, useRef, useState } from \"react\";\n\n// Everything about the floor. Colours are red, green, blue from 0 to 1.\nconst floor = {\n  speed: 1, // how fast the lamp swings when nobody is steering it; 0 parks it\n  span: 4.6, // how much floor the shorter side of a wide screen shows\n  spanNarrow: 3.0, // the same for a phone\n  chipSize: 1, // 0.7 gives a fine Venetian mix, 1.5 big Palladiana slabs\n  fill: 0.56, // share of the floor taken by the large chips\n  polish: 1, // how mirror-like the grind is; 0.3 is a honed, satin floor\n  lampHeight: 2.2, // how far the lamp hangs above the floor\n  lampSize: 0.52, // radius of the lamp's glass shade\n  strips: 1, // 1 lays the brass divider strips, 0 pours one seamless slab\n  quality: 0.85, // share of the device pixels that are drawn\n  maxPixels: 1100000, // the canvas never draws more pixels than this\n  cement: [0.86, 0.82, 0.75], // the binder between the chips\n  brass: [0.78, 0.58, 0.26],\n  stones: [\n    [0.94, 0.92, 0.88], // white Carrara\n    [0.71, 0.34, 0.24], // terracotta\n    [0.15, 0.29, 0.24], // green serpentine\n    [0.84, 0.63, 0.27], // Siena yellow\n    [0.13, 0.15, 0.22], // blue-black slate\n    [0.87, 0.67, 0.62], // rose marble\n  ],\n};\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 uSpan;\nuniform vec2 uLamp;\nuniform vec2 uStrip;\nuniform float uChip;\nuniform float uFill;\nuniform float uPolish;\nuniform float uLampHeight;\nuniform float uLampSize;\nuniform float uStrips;\nuniform vec3 uCement;\nuniform vec3 uBrass;\nuniform vec3 uStoneA;\nuniform vec3 uStoneB;\nuniform vec3 uStoneC;\nuniform vec3 uStoneD;\nuniform vec3 uStoneE;\nuniform vec3 uStoneF;\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}\nvec2 hash2(vec2 p) { return vec2(hash(p), hash(p.yx + 19.19)); }\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 stone(float h) {\n  vec3 c = uStoneA;\n  c = mix(c, uStoneB, step(0.34, h));\n  c = mix(c, uStoneC, step(0.5, h));\n  c = mix(c, uStoneD, step(0.64, h));\n  c = mix(c, uStoneE, step(0.76, h));\n  c = mix(c, uStoneF, step(0.88, h));\n  return c;\n}\n\n// Broken stone: the plane is split into cells and each cell is one fragment. Returns the\n// distance to the nearest break and the fragment's own number.\nvec3 shards(vec2 x) {\n  vec2 n = floor(x);\n  vec2 f = fract(x);\n  vec2 mg = vec2(0.0);\n  vec2 mr = vec2(0.0);\n  float md = 8.0;\n  for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {\n    vec2 g = vec2(float(i), float(j));\n    vec2 r = g + hash2(n + g) - f;\n    float d = dot(r, r);\n    if (d < md) { md = d; mr = r; mg = g; }\n  }\n  md = 8.0;\n  for (int j = -2; j <= 2; j++) for (int i = -2; i <= 2; i++) {\n    vec2 g = mg + vec2(float(i), float(j));\n    vec2 r = g + hash2(n + g) - f;\n    if (dot(mr - r, mr - r) > 0.0001) md = min(md, dot(0.5 * (mr + r), normalize(r - mr)));\n  }\n  return vec3(md, n + mg);\n}\n\n// One grade of chip thrown into the mix. Each fragment is shrunk away from its neighbours\n// so cement shows between them, and given its own colour, figure, tilt and polish.\nvoid scatter(vec2 p, float scale, float seed, float keep, float px, inout vec3 albedo, inout vec4 finish) {\n  vec2 x = p * scale + seed * vec2(7.3, 3.1);\n  x += (vec2(noise(x * 3.0), noise(x * 3.0 + 9.1)) - 0.5) * 0.07;\n  vec3 c = shards(x);\n  vec2 id = c.yz + seed * 13.0;\n  float there = step(hash(id), keep);\n  float d = c.x - (0.08 + 0.2 * hash(id + 1.7));\n  float aa = px * scale;\n  float m = there * smoothstep(-aa, aa, d);\n  // A hairline of shadow where the cement has shrunk back from the stone.\n  albedo *= 1.0 - 0.22 * there * smoothstep(0.02, 0.0, abs(d + 0.004)) * (1.0 - m);\n\n  float kind = hash(id + 5.1);\n  vec3 col = stone(kind);\n  float turn = 6.283 * hash(id + 8.8);\n  vec2 grain = vec2(cos(turn) * x.x + sin(turn) * x.y, -sin(turn) * x.x + cos(turn) * x.y);\n  float cloud = noise(grain * vec2(2.2, 6.0) + id);\n  float vein = smoothstep(0.05, 0.0, abs(noise(grain * vec2(1.5, 4.0) + id * 1.7) - 0.5));\n  col *= 0.76 + 0.44 * cloud;\n  col = mix(col, col * 0.66 + 0.1, vein * 0.4);\n  col *= 0.94 + 0.12 * hash(id + 2.2);\n\n  albedo = mix(albedo, col, m);\n  vec2 tilt = (hash2(id + 4.4) - 0.5) * 0.05;\n  finish = mix(finish, vec4(tilt, 0.025 + 0.05 * hash(id + 6.6), 0.5 + 0.2 * hash(id + 7.7)), m);\n}\n\n// The lamp's glass shade as the floor mirrors it from the point p.\nfloat mirrored(vec2 p, vec3 n, float blur, out float glow) {\n  vec3 view = normalize(vec3(-p, 6.0));\n  vec3 r = reflect(-view, n);\n  vec2 hit = p + r.xy * (uLampHeight / max(r.z, 0.05));\n  float d = length(hit - uLamp * (1.0 + uLampHeight / 6.0));\n  glow = exp(-d * d * 0.7);\n  float shade = smoothstep(uLampSize + blur, uLampSize - blur, d);\n  // The bulb sits brighter in the middle of the shade.\n  return shade * (0.5 + 0.5 * smoothstep(uLampSize * 0.42 + blur, uLampSize * 0.42 - blur, d));\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  // Cement first: fine sand, a little mottling and the odd pinhole.\n  vec3 albedo = uCement * (0.93 + 0.1 * noise(p * 2.1) + 0.05 * noise(p * 46.0));\n  albedo *= 1.0 - 0.2 * smoothstep(0.88, 0.96, noise(p * 70.0));\n  vec4 finish = vec4(0.0, 0.0, 0.11, 0.3); // tilt x, tilt y, blur of reflections, mirror strength\n\n  scatter(p, 9.5 / uChip, 3.0, 0.34, px, albedo, finish);\n  scatter(p, 4.6 / uChip, 2.0, 0.42, px, albedo, finish);\n  scatter(p, 2.1 / uChip, 1.0, uFill, px, albedo, finish);\n\n  // Brass divider strips, set on edge in the screed and ground flush with the stone.\n  vec2 off = abs(p - uStrip);\n  float line = min(off.x, off.y);\n  float strip = uStrips * smoothstep(0.03 + px, 0.03 - px, line);\n  float along = off.x < off.y ? p.y : p.x;\n  float across = off.x < off.y ? p.x : p.y;\n  vec3 brass = uBrass * (0.82 + 0.3 * noise(vec2(along * 3.0, across * 260.0)) + 0.1 * noise(vec2(along * 40.0, across * 30.0)));\n  albedo *= 1.0 - 0.35 * uStrips * smoothstep(0.046, 0.03, line) * (1.0 - strip);\n  albedo = mix(albedo, brass * 0.62, strip);\n  finish = mix(finish, vec4(0.0, 0.0, 0.1, 0.8), strip);\n\n  finish.z = mix(0.5, finish.z, uPolish);\n  finish.w *= mix(0.35, 1.0, uPolish);\n  vec3 n = normalize(vec3(finish.xy + (vec2(noise(p * 30.0), noise(p * 30.0 + 7.7)) - 0.5) * 0.008, 1.0));\n\n  vec3 toLamp = vec3(uLamp * (1.0 + uLampHeight / 6.0), uLampHeight) - vec3(p, 0.0);\n  float reach = length(toLamp);\n  float lit = max(dot(n, toLamp / reach), 0.0) / (1.0 + 0.14 * reach * reach);\n  vec3 warm = vec3(1.0, 0.95, 0.86);\n  vec3 col = albedo * (vec3(0.36, 0.37, 0.42) + warm * lit * 1.5);\n\n  float glow;\n  float shade = mirrored(p, n, finish.z, glow);\n  vec3 tint = mix(vec3(1.0), uBrass * 1.5, strip);\n  col += warm * tint * shade * finish.w * 1.1;\n  col += warm * tint * glow * 0.1 * finish.w;\n\n  // A run of skylights overhead, mirrored faintly whatever the lamp is doing.\n  vec3 view = normalize(vec3(-p, 6.0));\n  vec3 r = reflect(-view, n);\n  vec2 sky = p + r.xy * (5.0 / max(r.z, 0.05));\n  sky = vec2(sky.x * 0.94 + sky.y * 0.34, -sky.x * 0.34 + sky.y * 0.94);\n  float bay = smoothstep(0.62 + finish.z, 0.62 - finish.z, abs(mod(sky.x + 1.2, 2.4) - 1.2)) * smoothstep(3.4 + finish.z, 3.4 - finish.z, abs(sky.y - 1.0));\n  col += vec3(0.88, 0.92, 1.0) * bay * finish.w * 0.26;\n\n  vec2 c = gl_FragCoord.xy / uRes - 0.5;\n  col *= 1.0 - 0.42 * dot(c, c);\n  col = mix(col, 1.0 - exp(-col * 1.6), 0.4);\n  col += (hash(gl_FragCoord.xy) - 0.5) * 0.012;\n  gl_FragColor = vec4(pow(max(col, 0.0), vec3(0.9)), 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 FloorCanvas({ 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 drawn floor 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\"), span: at(\"uSpan\"), lamp: at(\"uLamp\"), strip: at(\"uStrip\") };\n    gl.uniform1f(at(\"uChip\"), floor.chipSize);\n    gl.uniform1f(at(\"uFill\"), floor.fill);\n    gl.uniform1f(at(\"uPolish\"), floor.polish);\n    gl.uniform1f(at(\"uLampHeight\"), floor.lampHeight);\n    gl.uniform1f(at(\"uLampSize\"), floor.lampSize);\n    gl.uniform1f(at(\"uStrips\"), floor.strips);\n    gl.uniform3fv(at(\"uCement\"), floor.cement);\n    gl.uniform3fv(at(\"uBrass\"), floor.brass);\n    [\"uStoneA\", \"uStoneB\", \"uStoneC\", \"uStoneD\", \"uStoneE\", \"uStoneF\"].forEach((name, i) => gl.uniform3fv(at(name), floor.stones[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 lamp = { x: 0.1, y: 0.12, tx: 0.1, ty: 0.12, touched: -1e9 };\n    let raf = 0;\n    let visible = true;\n    let time = 0;\n    let before = 0;\n\n    const draw = () => {\n      gl.uniform2f(u.lamp, lamp.x * half.x, lamp.y * half.y);\n      gl.drawArrays(gl.TRIANGLES, 0, 3);\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) * floor.quality, Math.sqrt(floor.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      const span = w < 640 ? floor.spanNarrow : floor.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.viewport(0, 0, canvas.width, canvas.height);\n      gl.uniform2f(u.res, canvas.width, canvas.height);\n      gl.uniform1f(u.span, span);\n      gl.uniform2f(u.strip, -half.x * 0.44, half.y * 0.46);\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 * floor.speed;\n      // Left alone for a few seconds, the lamp goes back to swinging in a slow figure of eight.\n      if (now - lamp.touched > 2600) {\n        lamp.tx = 0.1 + 0.5 * Math.sin(time * 0.5);\n        lamp.ty = 0.12 + 0.34 * Math.sin(time * 1.0 + 0.5);\n      }\n      const k = 1 - Math.exp(-dt * 3.2);\n      lamp.x = mix(lamp.x, lamp.tx, k);\n      lamp.y = mix(lamp.y, lamp.ty, 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) * 2 - 1;\n      const y = 1 - ((e.clientY - box.top) / box.height) * 2;\n      if (Math.abs(x) > 1 || Math.abs(y) > 1) return;\n      lamp.tx = x;\n      lamp.ty = y;\n      lamp.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 fallback floor: a fixed scatter of four-sided chips, worked out once from a seed.\nconst stillChips = (() => {\n  const fills = [\"#f1ece2\", \"#b5573d\", \"#264a3d\", \"#d6a145\", \"#21263a\", \"#deaba0\", \"#f1ece2\", \"#b5573d\"];\n  let seed = 7;\n  const next = () => {\n    seed = (seed * 16807) % 2147483647;\n    return seed / 2147483647;\n  };\n  const chips: { points: string; fill: string }[] = [];\n  for (let row = 0; row < 9; row++) {\n    for (let col = 0; col < 15; col++) {\n      if (next() < 0.22) continue;\n      const cx = col * 70 + 20 + next() * 40;\n      const cy = row * 70 + 20 + next() * 40;\n      const size = 12 + next() * 22;\n      const turn = next() * Math.PI;\n      const points = [0, 1, 2, 3]\n        .map((corner) => {\n          const a = turn + corner * (Math.PI / 2) + (next() - 0.5) * 0.9;\n          const r = size * (0.6 + next() * 0.5);\n          return `${(cx + Math.cos(a) * r).toFixed(1)},${(cy + Math.sin(a) * r).toFixed(1)}`;\n        })\n        .join(\" \");\n      chips.push({ points, fill: fills[Math.floor(next() * fills.length)] });\n    }\n  }\n  return chips;\n})();\n\n/** The floor without a shader: an SVG of flat chips under a soft pool of light. Shown first, and kept when WebGL is missing. */\nfunction StillFloor() {\n  return (\n    <div aria-hidden=\"true\" className=\"absolute inset-0 overflow-hidden bg-[#d9d0bf]\">\n      <svg viewBox=\"0 0 1050 630\" preserveAspectRatio=\"xMidYMid slice\" className=\"absolute inset-0 h-full w-full\">\n        {stillChips.map((chip) => (\n          <polygon key={chip.points} points={chip.points} fill={chip.fill} />\n        ))}\n        <rect x=\"290\" y=\"0\" width=\"5\" height=\"630\" fill=\"#b08a3e\" />\n        <rect x=\"0\" y=\"168\" width=\"1050\" height=\"5\" fill=\"#b08a3e\" />\n      </svg>\n      <div className=\"absolute inset-0 bg-[radial-gradient(34%_42%_at_55%_44%,rgba(255,250,235,0.55)_0%,rgba(255,250,235,0)_70%)]\" />\n      <div className=\"absolute inset-0 bg-[radial-gradient(90%_90%_at_50%_50%,rgba(60,50,40,0)_55%,rgba(60,50,40,0.28)_100%)]\" />\n    </div>\n  );\n}\n\nexport default function PolishedTerrazzoFloorWebglBackgroundWithMarbleChipsAndBrassStripsThatCatchAMovingLamp() {\n  const [live, setLive] = useState(false);\n\n  return (\n    <section className=\"relative isolate h-[620px] overflow-hidden bg-[#d9d0bf] sm:h-[760px]\">\n      <StillFloor />\n      <div className={`pointer-events-none absolute inset-0 transition-opacity duration-700 motion-reduce:transition-none ${live ? \"opacity-100\" : \"opacity-0\"}`}>\n        <FloorCanvas onLive={setLive} />\n      </div>\n      <p className=\"absolute bottom-5 left-5 rounded-full bg-stone-900/90 px-3.5 py-2 font-mono text-[11px] uppercase tracking-[0.2em] text-stone-50 sm:bottom-7 sm:left-7\">\n        Terrazzo <span className=\"hidden text-amber-200 sm:inline\">/ six stones, brass strips, one lamp</span>\n      </p>\n    </section>\n  );\n}\n"}]}
