{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sphere-shader",
  "title": "Sphere Shader",
  "description": "A glowing 3D sphere rendered with Three.js and a bloom pass, for hero sections.",
  "dependencies": [
    "motion",
    "three",
    "three-stdlib",
    "@react-three/fiber",
    "@react-three/drei"
  ],
  "devDependencies": [
    "@types/three"
  ],
  "files": [
    {
      "path": "packages/sphere-shader/sphere-shader.tsx",
      "content": "\"use client\";\r\n\r\nimport { MotionConfigContext } from \"motion/react\";\r\nimport { useRef, useMemo, useSyncExternalStore, useContext, useLayoutEffect, useEffect, useState } from \"react\";\r\nimport { Canvas, useFrame, useThree, extend } from \"@react-three/fiber\";\r\nimport { OrbitControls, Effects } from \"@react-three/drei\";\r\nimport { UnrealBloomPass, type OrbitControls as OrbitControlsImpl } from \"three-stdlib\";\r\nimport * as THREE from \"three\";\r\nimport { cn } from \"@/lib/utils\";\r\n\r\n/**\r\n * \"user\" (the default) follows a surrounding <MotionConfig reducedMotion>,\r\n * then the visitor's \"reduce motion\" device setting. \"always\" and \"never\"\r\n * force the calm or the full version.\r\n */\r\nexport type ReducedMotion = \"user\" | \"always\" | \"never\";\r\n\r\nconst REDUCED_MOTION_QUERY = \"(prefers-reduced-motion: reduce)\";\r\n\r\nfunction subscribeToReducedMotion(onChange: () => void) {\r\n  const query = window.matchMedia(REDUCED_MOTION_QUERY);\r\n  query.addEventListener(\"change\", onChange);\r\n  return () => query.removeEventListener(\"change\", onChange);\r\n}\r\n\r\n// The prop wins, then MotionConfig, then the device setting. The device is\r\n// read as \"no\" while server rendering, so hydration always matches.\r\nfunction useShouldReduceMotion(mode: ReducedMotion = \"user\") {\r\n  const device = useSyncExternalStore(\r\n    subscribeToReducedMotion,\r\n    () => window.matchMedia(REDUCED_MOTION_QUERY).matches,\r\n    () => false,\r\n  );\r\n  const config = useContext(MotionConfigContext).reducedMotion;\r\n  if (mode !== \"user\") return mode === \"always\";\r\n  if (config === \"always\" || config === \"never\") return config === \"always\";\r\n  return device;\r\n}\r\n\r\n\r\n/**\r\n * Calls onChange(true) while `element` is on screen (or within 200px of it)\r\n * and the tab is showing, and onChange(false) otherwise, so an animation\r\n * loop can sleep while nobody can see it. Returns a function that stops\r\n * watching.\r\n */\r\nfunction watchVisibility(element: Element, onChange: (visible: boolean) => void) {\r\n  let onScreen = true;\r\n  let last: boolean | null = null;\r\n  const update = () => {\r\n    const visible = onScreen && document.visibilityState === \"visible\";\r\n    if (visible !== last) onChange((last = visible));\r\n  };\r\n  const observer =\r\n    typeof IntersectionObserver !== \"undefined\"\r\n      ? new IntersectionObserver(\r\n          ([entry]) => {\r\n            onScreen = entry.isIntersecting;\r\n            update();\r\n          },\r\n          { rootMargin: \"200px\" },\r\n        )\r\n      : null;\r\n  observer?.observe(element);\r\n  document.addEventListener(\"visibilitychange\", update);\r\n  update();\r\n  return () => {\r\n    observer?.disconnect();\r\n    document.removeEventListener(\"visibilitychange\", update);\r\n  };\r\n}\r\n\r\n// Extend Three.js with UnrealBloomPass\r\nextend({ UnrealBloomPass });\r\n\r\n// Declare the extended JSX elements\r\ndeclare module \"@react-three/fiber\" {\r\n  interface ThreeElements {\r\n    unrealBloomPass: {\r\n      threshold?: number;\r\n      strength?: number;\r\n      radius?: number;\r\n    };\r\n  }\r\n}\r\n\r\n// Moon shape. Crater depth 0 keeps the surface smooth; raise it for pits.\r\nconst RADIUS = 60;\r\nconst CRATER = 0;\r\nconst SPIN = 0.25;\r\n\r\n// Seeded random numbers, so the starting scatter is the same on every render\r\n// (and the component stays pure).\r\nfunction seededRandom(seed: number) {\r\n  return () => {\r\n    seed = (seed + 0x6d2b79f5) | 0;\r\n    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);\r\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\r\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\r\n  };\r\n}\r\n\r\nconst ParticleSwarm = ({ reduce = false }: { reduce?: boolean }) => {\r\n  const meshRef = useRef<THREE.InstancedMesh>(null!);\r\n  const count = 3000;\r\n  const speedMult = 1;\r\n  const dummy = useMemo(() => new THREE.Object3D(), []);\r\n  const target = useMemo(() => new THREE.Vector3(), []);\r\n  const pColor = useMemo(() => new THREE.Color(), []);\r\n\r\n  const positions = useMemo(() => {\r\n    const random = seededRandom(1);\r\n    const pos: THREE.Vector3[] = [];\r\n    for (let i = 0; i < count; i++) {\r\n      pos.push(\r\n        new THREE.Vector3(\r\n          (random() - 0.5) * 100,\r\n          (random() - 0.5) * 100,\r\n          (random() - 0.5) * 100,\r\n        ),\r\n      );\r\n    }\r\n    return pos;\r\n  }, []);\r\n\r\n  // Material & Geometry\r\n  const material = useMemo(\r\n    () => new THREE.MeshBasicMaterial({ color: 0xffffff }),\r\n    [],\r\n  );\r\n  const geometry = useMemo(() => new THREE.TetrahedronGeometry(0.25), []);\r\n\r\n  // Time only advances while frames are drawn, so after the canvas sleeps\r\n  // off-screen the swarm carries on from where it stopped.\r\n  const elapsed = useRef(0);\r\n  useFrame((_, delta) => {\r\n    if (!meshRef.current) return;\r\n    elapsed.current += Math.min(delta, 0.1);\r\n    // Reduced motion holds the moon still; it can still be dragged and zoomed.\r\n    const time = reduce ? 0 : elapsed.current * speedMult;\r\n\r\n    for (let i = 0; i < count; i++) {\r\n      const radius = RADIUS;\r\n      const crater = CRATER;\r\n      const spin = SPIN;\r\n\r\n      const t = time * spin;\r\n      const f = i / (count - 1);\r\n\r\n      // Fibonacci sphere distribution\r\n      const ga = 2.399963229728653; // golden angle\r\n      const y = 1 - 2 * f;\r\n      const r = Math.sqrt(1 - y * y);\r\n      const theta = i * ga + t * 0.25;\r\n\r\n      let x = Math.cos(theta) * r;\r\n      let z = Math.sin(theta) * r;\r\n\r\n      // procedural crater field\r\n      const n =\r\n        Math.sin(x * 18.0 + t * 0.2) * Math.sin(y * 22.0) * Math.sin(z * 18.0);\r\n\r\n      const displacement = 1 + n * crater * 0.05;\r\n\r\n      // scale to moon radius\r\n      x *= radius * displacement;\r\n      const yy = y * radius * displacement;\r\n      z *= radius * displacement;\r\n\r\n      // slow planetary rotation\r\n      const ct = Math.cos(t);\r\n      const st = Math.sin(t);\r\n\r\n      const rx = x * ct - z * st;\r\n      const rz = x * st + z * ct;\r\n\r\n      target.set(rx, yy, rz);\r\n\r\n      // approximate normal for lighting\r\n      const invLen = 1 / Math.sqrt(rx * rx + yy * yy + rz * rz);\r\n      const nx = rx * invLen;\r\n      const ny = yy * invLen;\r\n      const nz = rz * invLen;\r\n\r\n      // fixed sunlight direction\r\n      const lx = 0.4;\r\n      const ly = 0.7;\r\n      const lz = 0.5;\r\n\r\n      const light = Math.max(0, nx * lx + ny * ly + nz * lz);\r\n\r\n      // moon gray shading\r\n      const l = 0.25 + light * 0.55 + n * 0.05;\r\n\r\n      pColor.setHSL(0, 0, l);\r\n\r\n      positions[i].lerp(target, 0.1);\r\n      dummy.position.copy(positions[i]);\r\n      dummy.updateMatrix();\r\n      meshRef.current.setMatrixAt(i, dummy.matrix);\r\n      meshRef.current.setColorAt(i, pColor);\r\n    }\r\n    meshRef.current.instanceMatrix.needsUpdate = true;\r\n    if (meshRef.current.instanceColor)\r\n      meshRef.current.instanceColor.needsUpdate = true;\r\n  });\r\n\r\n  return <instancedMesh ref={meshRef} args={[geometry, material, count]} />;\r\n};\r\n\r\n/**\r\n * Places the camera so the moon spans `fill` of the canvas's shorter side,\r\n * whatever the container's size or aspect ratio, and scales the zoom limits\r\n * to match. Runs again whenever the canvas is resized.\r\n */\r\nconst FitCamera = ({ fill }: { fill: number }) => {\r\n  // Subscribed to so the effect re-runs when they change; the instances are\r\n  // read through get() so they are mutated outside React's render data.\r\n  const get = useThree((s) => s.get);\r\n  const hasControls = useThree((s) => s.controls !== null);\r\n  const width = useThree((s) => s.size.width);\r\n  const height = useThree((s) => s.size.height);\r\n\r\n  useLayoutEffect(() => {\r\n    if (!width || !height) return;\r\n    const state = get();\r\n    const camera = state.camera as THREE.PerspectiveCamera;\r\n    const controls = state.controls as OrbitControlsImpl | null;\r\n    const vHalf = THREE.MathUtils.degToRad(camera.fov / 2);\r\n    const hHalf = Math.atan(Math.tan(vHalf) * (width / height));\r\n    const half = Math.min(vHalf, hHalf);\r\n    // The sphere's silhouette subtends asin(R / d); solve d for the angle\r\n    // that covers `fill` of the narrower half-view.\r\n    const silhouette = Math.atan(Math.tan(half) * Math.min(Math.max(fill, 0.1), 1.5));\r\n    const distance = RADIUS / Math.sin(Math.min(silhouette, Math.PI / 2 - 0.01));\r\n\r\n    camera.position.setLength(distance);\r\n    camera.updateProjectionMatrix();\r\n    if (controls) {\r\n      controls.minDistance = distance * 0.45;\r\n      controls.maxDistance = distance * 2;\r\n      controls.update();\r\n    }\r\n  }, [get, hasControls, width, height, fill]);\r\n\r\n  return null;\r\n};\r\n\r\ninterface SphereShaderProps extends React.ComponentProps<\"div\"> {\r\n  /**\r\n   * Classes for the wrapper. Give it a size: the canvas fills it. The black background can\r\n   * be swapped for another, such as \"bg-transparent\".\r\n   */\r\n  className?: string;\r\n  /**\r\n   * How much of the container's shorter side the moon spans, from 0.1 to\r\n   * 1.5 (above 1 it overflows the edges). @default 0.8\r\n   */\r\n  fill?: number;\r\n  /**\r\n   * \"user\" follows a surrounding MotionConfig, then the visitor's reduce-motion setting.\r\n   * \"always\" and \"never\" force the calm or the full version.\r\n   */\r\n  reducedMotion?: ReducedMotion;\r\n}\r\n\r\nconst SphereShader = ({\r\n  className,\r\n  fill = 0.8,\r\n  reducedMotion = \"user\",\r\n  ...props\r\n}: SphereShaderProps) => {\r\n  const reduce = useShouldReduceMotion(reducedMotion);\r\n\r\n  // Renders only while the moon can be seen: scrolled away or in a hidden\r\n  // tab, the 3000-particle frame loop stops.\r\n  const sentinelRef = useRef<HTMLDivElement>(null);\r\n  const [visible, setVisible] = useState(true);\r\n  useEffect(() => {\r\n    const node = sentinelRef.current;\r\n    if (!node) return;\r\n    return watchVisibility(node, setVisible);\r\n  }, []);\r\n\r\n  return (\r\n    <div className={cn(\"relative w-full overflow-hidden bg-black\", className)} {...props}>\r\n      {/* Watched for visibility; the wrapper's own ref stays free for the caller. */}\r\n      <div ref={sentinelRef} aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0\" />\r\n      <Canvas\r\n        frameloop={visible ? \"always\" : \"never\"}\r\n        aria-hidden=\"true\"\r\n        camera={{ position: [0, 0, 100], fov: 60 }}\r\n        className=\"w-full h-full\"\r\n      >\r\n        <fog attach=\"fog\" args={[\"#000000\", 0.01]} />\r\n        <ParticleSwarm reduce={reduce} />\r\n        {/* Zoom limits are set by FitCamera, relative to the fitted distance. */}\r\n        <OrbitControls\r\n          makeDefault\r\n          autoRotate={!reduce}\r\n          autoRotateSpeed={1.5}\r\n          enableZoom={true}\r\n          enablePan={true}\r\n          enableDamping={true}\r\n          dampingFactor={0.05}\r\n          rotateSpeed={0.5}\r\n          zoomSpeed={1.2}\r\n          panSpeed={0.8}\r\n        />\r\n        <FitCamera fill={fill} />\r\n        <Effects disableGamma>\r\n          <unrealBloomPass threshold={0} strength={1.8} radius={0.4} />\r\n        </Effects>\r\n      </Canvas>\r\n    </div>\r\n  );\r\n};\r\n\r\nexport default SphereShader;",
      "type": "registry:component",
      "target": "components/satori-ui/sphere-shader.tsx"
    }
  ],
  "meta": {
    "usage": "<SphereShader className=\"h-[480px]\" />"
  },
  "type": "registry:component"
}