{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"three-sided-billboard-photo-gallery-with-prism-slats-that-rotate-in-a-wave-between-pictures","type":"registry:block","title":"Three-Sided Billboard Photo Gallery with Prism Slats That Rotate in a Wave Between Pictures","description":"Gallery built like a three-sided roadside billboard in WebGL: prism slats rotate in a wave to change between photographs. Free React and HTML code to copy.","dependencies":["framer-motion"],"files":[{"path":"components/we-inc/three-sided-billboard-photo-gallery-with-prism-slats-that-rotate-in-a-wave-between-pictures.tsx","type":"registry:component","content":"import { useEffect, useRef, useState } from \"react\";\nimport type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from \"react\";\nimport { useReducedMotion } from \"framer-motion\";\n\n// One picture per side of the prisms. Exactly three, framed alike.\nconst sides = [\n  {\n    name: \"Vermilion\",\n    src: \"https://images.pexels.com/photos/15689960/pexels-photo-15689960.jpeg?auto=compress&cs=tinysrgb&w=900\",\n    alt: \"Close portrait of a man with a tall afro in a white striped shirt against a red wall\",\n    tone: \"#b5372a\",\n  },\n  {\n    name: \"Saffron\",\n    src: \"https://images.pexels.com/photos/6976854/pexels-photo-6976854.jpeg?auto=compress&cs=tinysrgb&w=900\",\n    alt: \"A woman in a mustard beret and mustard jumper leaning on a tan suitcase against a yellow wall\",\n    tone: \"#e2a12c\",\n  },\n  {\n    name: \"Cobalt\",\n    src: \"https://images.pexels.com/photos/35707519/pexels-photo-35707519.jpeg?auto=compress&cs=tinysrgb&w=900\",\n    alt: \"A woman with an afro and sunglasses crouching in a pink dress and black boots against a bright blue wall\",\n    tone: \"#1f7fd6\",\n  },\n];\n\n/** How many prisms the picture is cut into. Up to 20. */\nconst SLATS = 14;\n/** Seconds between one prism starting to turn and its neighbour following. */\nconst STAGGER = 0.052;\n/** Seconds the billboard rests on a picture before it turns by itself. */\nconst REST = 3.5;\n\nconst VERT = `attribute vec2 a; void main(){ gl_Position = vec4(a, 0.0, 1.0); }`;\n\nconst FRAG = `precision highp float;\nuniform vec2 u_res;\nuniform sampler2D u_t0;\nuniform sampler2D u_t1;\nuniform sampler2D u_t2;\nuniform vec3 u_img;\nuniform float u_ang[20];\nuniform float u_n;\n\nvec2 cover(vec2 uv, float img){\n  float A = u_res.x / u_res.y;\n  vec2 t = uv;\n  if (img > A) t.x = (uv.x - 0.5) * A / img + 0.5;\n  else t.y = (uv.y - 0.5) * img / A + 0.5;\n  return clamp(t, 0.0, 1.0);\n}\nfloat hash(float n){ return fract(sin(n * 91.345) * 47453.5453); }\n\nvoid main(){\n  vec2 uv = vec2(gl_FragCoord.x / u_res.x, 1.0 - gl_FragCoord.y / u_res.y);\n  float x = uv.x * u_n;\n  float i = floor(x);\n  float lx = fract(x) - 0.5;\n  float ang = 0.0;\n  for (int k = 0; k < 20; k++) { if (float(k) == i) ang = u_ang[k]; }\n\n  // Each prism is an equilateral triangle seen from the front, a little narrower than its bay.\n  float side = 0.972;\n  float R = side / 1.7320508;\n  float pxw = u_n / u_res.x;\n  // The dark of the housing seen between prisms, with a little light leaking in from the front.\n  vec3 col = vec3(0.016, 0.017, 0.020) + vec3(0.02) * smoothstep(0.42, 0.5, abs(lx));\n\n  vec2 lamp = normalize(vec2(-0.42, 0.91));\n  vec2 half_ = normalize(lamp + vec2(0.0, 1.0));\n  for (int f = 0; f < 3; f++) {\n    float n = float(f) * 2.0943951 - ang;\n    float c = cos(n);\n    if (c <= 0.0) continue;\n    float x1 = R * sin(n - 1.0471976);\n    float x2 = R * sin(n + 1.0471976);\n    float e = min(lx - x1, x2 - lx);\n    float inside = clamp(e / pxw + 0.5, 0.0, 1.0);\n    if (inside <= 0.0) continue;\n    float w = clamp((lx - x1) / (x2 - x1), 0.0, 1.0);\n    vec2 at = vec2((i + w) / u_n, uv.y);\n    vec3 pic;\n    if (f == 0) pic = texture2D(u_t0, cover(at, u_img.x)).rgb;\n    else if (f == 1) pic = texture2D(u_t1, cover(at, u_img.y)).rgb;\n    else pic = texture2D(u_t2, cover(at, u_img.z)).rgb;\n\n    vec2 nor = vec2(sin(n), c);\n    float diffuse = max(dot(nor, lamp), 0.0);\n    // How far back this point of the face sits. Faces turned into the housing fall into shade.\n    float z = R * mix(cos(n - 1.0471976), cos(n + 1.0471976), w);\n    float depth = smoothstep(-0.45 * R, 0.5 * R, z);\n    vec3 lit = pic * (0.10 + 0.99 * diffuse) * mix(0.42, 1.0, depth);\n    // The printed vinyl is glossy: a band of the lamp slides across a face as it swings past.\n    float gloss = pow(max(dot(nor, half_), 0.0), 130.0);\n    lit += vec3(1.0, 0.98, 0.94) * gloss * 0.30 * (0.4 + 0.6 * depth);\n    // Folded aluminium lip down each long edge of a face.\n    float lip = 1.0 - smoothstep(0.0, 0.022 / max(c, 0.25), min(w, 1.0 - w));\n    vec3 metal = vec3(0.62, 0.64, 0.67) * (0.25 + 0.95 * diffuse) + vec3(1.0) * gloss * 0.6;\n    lit = mix(lit, metal, lip * 0.45);\n    col = mix(col, lit, inside);\n  }\n\n  // Lamps above the board: brighter at the top, and the rails shade the very ends of the prisms.\n  col *= 1.07 - 0.20 * uv.y;\n  col *= 0.55 + 0.45 * smoothstep(0.0, 0.035, uv.y);\n  col *= 0.70 + 0.30 * smoothstep(0.0, 0.022, 1.0 - uv.y);\n  // No two prisms are hung perfectly true, so each takes the light a touch differently.\n  col *= 0.975 + 0.05 * hash(i + 3.0);\n  gl_FragColor = vec4(col, 1.0);\n}`;\n\nexport default function ThreeSidedBillboardPhotoGalleryWithPrismSlatsThatRotateInAWaveBetweenPictures() {\n  const reduce = useReducedMotion();\n  const face = useRef<HTMLButtonElement>(null);\n  const canvas = useRef<HTMLCanvasElement>(null);\n  const pics = useRef<(HTMLImageElement | null)[]>([]);\n  /** Requests from the page to the draw loop: turns to make, and where the pointer is over the board. */\n  const ask = useRef<{ turns: { by: number; from: number }[]; x: number; at: number; touched: number }>({ turns: [], x: 0.5, at: -1e6, touched: -1e6 });\n  const [live, setLive] = useState(false);\n  const [shown, setShown] = useState(0);\n\n  useEffect(() => {\n    const el = face.current;\n    const cv = canvas.current;\n    const imgs = pics.current;\n    if (reduce || !el || !cv || imgs.length < 3 || imgs.some((img) => !img)) return;\n    const gl = cv.getContext(\"webgl\", { antialias: false, alpha: false });\n    if (!gl) return;\n\n    const compile = (type: number, source: string) => {\n      const shader = gl.createShader(type)!;\n      gl.shaderSource(shader, source);\n      gl.compileShader(shader);\n      return shader;\n    };\n    const program = gl.createProgram()!;\n    gl.attachShader(program, compile(gl.VERTEX_SHADER, VERT));\n    gl.attachShader(program, compile(gl.FRAGMENT_SHADER, FRAG));\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, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);\n    const at = gl.getAttribLocation(program, \"a\");\n    gl.enableVertexAttribArray(at);\n    gl.vertexAttribPointer(at, 2, gl.FLOAT, false, 0, 0);\n    const u = (name: string) => gl.getUniformLocation(program, name);\n    gl.uniform1i(u(\"u_t0\"), 0);\n    gl.uniform1i(u(\"u_t1\"), 1);\n    gl.uniform1i(u(\"u_t2\"), 2);\n    gl.uniform1f(u(\"u_n\"), SLATS);\n    const uni = { res: u(\"u_res\"), img: u(\"u_img\"), ang: u(\"u_ang[0]\") };\n\n    const third = (Math.PI * 2) / 3;\n    const angle = new Float32Array(20);\n    const speed = new Float32Array(20);\n    const goal = new Float32Array(20);\n    const lean = new Float32Array(20);\n    /** Each prism hangs a hair off true. */\n    const off = Array.from({ length: 20 }, (_, i) => Math.sin(i * 12.9898) * 0.022);\n    const queue: { col: number; when: number; to: number }[] = [];\n    let step = 0;\n    let ready = false;\n    let visible = true;\n    let raf = 0;\n    let last = 0;\n    let clock = 0;\n    let nextTurn = 0.9;\n\n    const upload = () => {\n      if (ready || imgs.some((img) => !img || !img.complete || !img.naturalWidth)) return;\n      try {\n        imgs.forEach((img, unit) => {\n          gl.activeTexture(gl.TEXTURE0 + unit);\n          gl.bindTexture(gl.TEXTURE_2D, gl.createTexture());\n          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n          gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, img!);\n        });\n        const ratio = (img: HTMLImageElement | null) => (img ? img.naturalWidth / img.naturalHeight : 1);\n        gl.uniform3f(uni.img, ratio(imgs[0]), ratio(imgs[1]), ratio(imgs[2]));\n        ready = true;\n        setLive(true);\n      } catch {\n        // A picture could not be read into the shader: the still version underneath stays on show.\n        ready = false;\n      }\n    };\n\n    const resize = () => {\n      const ratio = Math.min(window.devicePixelRatio || 1, 2);\n      cv.width = Math.max(1, Math.round(el.clientWidth * ratio));\n      cv.height = Math.max(1, Math.round(el.clientHeight * ratio));\n      gl.viewport(0, 0, cv.width, cv.height);\n      gl.uniform2f(uni.res, cv.width, cv.height);\n    };\n\n    const loop = (stamp: number) => {\n      if (ready) {\n        const dt = Math.min(last ? (stamp - last) / 1000 : 0.016, 0.033);\n        last = stamp;\n        clock += dt;\n        const a = ask.current;\n        // With nobody near it, the board turns to its next picture on a timer, starting from the left.\n        if (clock >= nextTurn && stamp - a.touched > 4200) a.turns.push({ by: 1, from: 0 });\n        while (a.turns.length) {\n          const turn = a.turns.shift()!;\n          step += turn.by;\n          for (let i = 0; i < SLATS; i++) queue.push({ col: i, when: clock + Math.abs(i - turn.from) * STAGGER, to: step });\n          nextTurn = clock + REST + SLATS * STAGGER;\n          setShown(((step % 3) + 3) % 3);\n        }\n        for (let q = queue.length - 1; q >= 0; q--) {\n          if (queue[q].when <= clock) {\n            goal[queue[q].col] = queue[q].to;\n            queue.splice(q, 1);\n          }\n        }\n        const near = stamp - a.at < 900;\n        for (let i = 0; i < SLATS; i++) {\n          // A hand passing over the board nudges the prisms beneath it part of the way round.\n          const away = a.x * SLATS - (i + 0.5);\n          const want = near ? 0.5 * Math.exp(-(away * away) / 3.2) : 0;\n          lean[i] += (want - lean[i]) * Math.min(1, dt * 9);\n          const target = goal[i] * third + off[i] + lean[i];\n          // A firm spring, slightly under-damped, so each prism overshoots and clacks back onto its stop.\n          speed[i] += ((target - angle[i]) * 95 - speed[i] * 9.6) * dt;\n          angle[i] += speed[i] * dt;\n        }\n        gl.uniform1fv(uni.ang, angle);\n        gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n      }\n      raf = visible && !document.hidden ? requestAnimationFrame(loop) : 0;\n    };\n    const wake = () => {\n      if (!raf && visible && !document.hidden) {\n        last = 0;\n        raf = requestAnimationFrame(loop);\n      }\n    };\n\n    const ro = new ResizeObserver(resize);\n    ro.observe(el);\n    const io = new IntersectionObserver(([entry]) => {\n      visible = entry.isIntersecting;\n      wake();\n    });\n    io.observe(el);\n    document.addEventListener(\"visibilitychange\", wake);\n    imgs.forEach((img) => img?.addEventListener(\"load\", upload));\n    upload();\n    resize();\n    wake();\n\n    return () => {\n      cancelAnimationFrame(raf);\n      ro.disconnect();\n      io.disconnect();\n      document.removeEventListener(\"visibilitychange\", wake);\n      imgs.forEach((img) => img?.removeEventListener(\"load\", upload));\n    };\n  }, [reduce]);\n\n  /** Turn the board by a number of sides, the wave starting at a given prism. Without the canvas the pictures simply swap. */\n  function turn(by: number, from: number) {\n    if (live) ask.current.turns.push({ by, from });\n    else setShown((n) => (((n + by) % 3) + 3) % 3);\n    ask.current.touched = performance.now();\n  }\n  function over(e: ReactPointerEvent<HTMLButtonElement>) {\n    const r = e.currentTarget.getBoundingClientRect();\n    ask.current.x = (e.clientX - r.left) / r.width;\n    ask.current.at = performance.now();\n    ask.current.touched = ask.current.at;\n  }\n  function onKey(e: ReactKeyboardEvent<HTMLButtonElement>) {\n    if (e.key === \"ArrowRight\") {\n      e.preventDefault();\n      turn(1, 0);\n    } else if (e.key === \"ArrowLeft\") {\n      e.preventDefault();\n      turn(-1, SLATS - 1);\n    }\n  }\n\n  return (\n    <section className=\"relative isolate flex min-h-[800px] w-full flex-col items-center justify-center overflow-hidden bg-[#0d0e12] px-4 py-14\">\n      <style>{`\n        .tsb-seams { background-image: linear-gradient(90deg, rgba(0,0,0,0) calc(100% - 2px), rgba(0,0,0,0.7) calc(100% - 2px)); background-size: calc(100% / ${SLATS}) 100%; }\n        .tsb-case { background: linear-gradient(100deg, #9a9ea6 0%, #d5d8dd 16%, #b3b7be 34%, #e3e5e9 52%, #a4a8b0 70%, #c9ccd2 86%, #8b8f97 100%); }\n        .tsb-well { box-shadow: 0 0 0 1px rgba(0,0,0,0.75), 0 1px 0 1px rgba(255,255,255,0.5), inset 0 0 0 1px #000; }\n        .tsb-rail { background: linear-gradient(180deg, #4a4d55 0%, #2a2c32 18%, #1b1c21 55%, #101114 100%); }\n      `}</style>\n      <div aria-hidden=\"true\" className=\"absolute inset-0 -z-10\" style={{ background: \"radial-gradient(55% 45% at 50% 30%, #23262f 0%, #0d0e12 72%)\" }} />\n\n      {/* The housing: a top rail, the turning face and a bottom rail. */}\n      <div className=\"tsb-case relative w-[min(86vw,430px)] rounded-[7px] p-[12px] shadow-[inset_0_1px_0_rgba(255,255,255,0.85),inset_0_-1px_0_rgba(0,0,0,0.45),inset_1px_0_0_rgba(255,255,255,0.35),inset_-1px_0_0_rgba(0,0,0,0.25),0_1px_2px_rgba(0,0,0,0.8),0_50px_80px_-30px_rgba(0,0,0,0.95)]\">\n        <div className=\"tsb-well rounded-[2px] bg-[#08080a]\">\n        <div aria-hidden=\"true\" className=\"tsb-rail flex h-[18px] items-center justify-between rounded-t-[2px] px-2 shadow-[inset_0_1px_0_rgba(255,255,255,0.22),0_3px_5px_rgba(0,0,0,0.6)]\">\n          <span className=\"h-[5px] w-[5px] rounded-full bg-[#0b0b0d] shadow-[0_1px_0_rgba(255,255,255,0.18)]\" />\n          <span className=\"h-[5px] w-[5px] rounded-full bg-[#0b0b0d] shadow-[0_1px_0_rgba(255,255,255,0.18)]\" />\n        </div>\n        <button\n          ref={face}\n          type=\"button\"\n          aria-label={`Billboard showing ${sides[shown].name}, picture ${shown + 1} of 3. Press to turn to the next picture. Left and right arrows turn it either way.`}\n          onClick={(e) => {\n            const r = e.currentTarget.getBoundingClientRect();\n            turn(1, e.detail === 0 ? 0 : Math.min(SLATS - 1, Math.max(0, Math.floor(((e.clientX - r.left) / r.width) * SLATS))));\n          }}\n          onPointerMove={over}\n          onKeyDown={onKey}\n          className=\"relative block aspect-[4/5] w-full cursor-pointer touch-pan-y overflow-hidden bg-[#08080a] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-300 focus-visible:ring-inset\"\n        >\n          {sides.map((side, i) => (\n            <img\n              key={side.name}\n              src={side.src}\n              alt={side.alt}\n              ref={(node) => {\n                pics.current[i] = node;\n              }}\n              crossOrigin=\"anonymous\"\n              width={900}\n              height={1125}\n              style={{ backgroundColor: side.tone }}\n              className={`absolute inset-0 h-full w-full object-cover ${i === shown ? \"opacity-100\" : \"opacity-0\"}`}\n            />\n          ))}\n          <span aria-hidden=\"true\" className=\"tsb-seams absolute inset-0 block\" />\n          <canvas ref={canvas} aria-hidden=\"true\" className={`absolute inset-0 h-full w-full transition-opacity duration-500 ${live ? \"opacity-100\" : \"opacity-0\"}`} />\n        </button>\n        <div aria-hidden=\"true\" className=\"tsb-rail h-[14px] rounded-b-[2px] shadow-[inset_0_1px_0_rgba(255,255,255,0.16)]\" />\n        </div>\n      </div>\n\n      <div className=\"mt-6 flex w-[min(86vw,430px)] items-center justify-between gap-3\">\n        <div className=\"flex gap-1.5\" role=\"group\" aria-label=\"Choose a picture\">\n          {sides.map((side, i) => (\n            <button\n              key={side.name}\n              type=\"button\"\n              aria-pressed={i === shown}\n              onClick={() => {\n                const by = (((i - shown) % 3) + 3) % 3;\n                if (by) turn(by === 2 ? -1 : 1, by === 2 ? SLATS - 1 : 0);\n              }}\n              className={`flex h-10 items-center gap-2 rounded-full px-3 text-[13px] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-300 ${i === shown ? \"bg-white/10 text-white\" : \"text-zinc-400 hover:text-white\"}`}\n            >\n              <span aria-hidden=\"true\" className=\"h-2.5 w-2.5 rounded-full\" style={{ backgroundColor: side.tone }} />\n              {side.name}\n            </button>\n          ))}\n        </div>\n        <p className=\"hidden whitespace-nowrap text-[13px] text-zinc-400 sm:block\">Click to turn</p>\n      </div>\n    </section>\n  );\n}\n"}]}
