{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "bar-terrain",
  "title": "Bar Terrain",
  "description": "An instanced field of bars driven by a height function, with a pointer bump.",
  "dependencies": [
    "three",
    "@react-three/fiber"
  ],
  "devDependencies": [
    "@types/three"
  ],
  "registryDependencies": [
    "https://spotcheckui.com/r/spotcheck-base.json",
    "https://spotcheckui.com/r/gl-stage.json",
    "https://spotcheckui.com/r/use-gl-palette.json",
    "https://spotcheckui.com/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/spotcheck/components/spotcheck/bar-terrain.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { useFrame, useThree } from \"@react-three/fiber\"\nimport {\n  BoxGeometry,\n  Color,\n  Fog,\n  type InstancedMesh,\n  MeshLambertMaterial,\n  Object3D,\n  Plane,\n  Raycaster,\n  Vector2,\n  Vector3,\n} from \"three\"\n\nimport { GlStage } from \"@/registry/spotcheck/components/spotcheck/gl-stage\"\nimport { useGlPalette } from \"@/registry/spotcheck/hooks/use-gl-palette\"\nimport { useReducedMotion } from \"@/registry/spotcheck/hooks/use-reduced-motion\"\nimport { cn } from \"@/lib/utils\"\n\nconst SPACING = 0.6\nconst BAR_WIDTH = 0.82\nconst POINTER_EASE = 0.1\nconst LIFT_EASE = 0.06\nconst COLOR_HEIGHT = 1.5\nconst AUTO_PICK_SECONDS = 3\nconst AUTO_REST_SECONDS = 0.7\nconst AUTO_PICK_TRIES = 24\n// The bars keep moving while one is picked, so a pick is checked at this many moments of its time up.\nconst PICK_LOOKAHEAD_STEPS = 8\n// Skips the first frames, which are slow on every device, then judges on the median so one hitch doesn't count.\nconst PACE_SKIP_FRAMES = 5\nconst PACE_SAMPLES = 7\nconst SLOW_FRAME_SECONDS = 1 / 15\nconst SOFTWARE_RENDERER = /swiftshader|llvmpipe|softpipe|software|basic render/i\nconst PALETTE_TOKENS = [\"--ink\", \"--wash\", \"--accent-ink\", \"--paper\"] as const\nconst CAMERA: TerrainCamera = { fov: 26, position: [12.5, 11, 13.5], near: 0.1, far: 200 }\nconst LOOK_AT: [number, number, number] = [0, 0.9, 0]\n\n/** True when the browser draws WebGL on the CPU, because there's no usable graphics card. */\nexport function usesSoftwareRenderer(context: WebGLRenderingContext | WebGL2RenderingContext) {\n  const info = context.getExtension(\"WEBGL_debug_renderer_info\")\n  return Boolean(info) && SOFTWARE_RENDERER.test(String(context.getParameter(info?.UNMASKED_RENDERER_WEBGL ?? 0)))\n}\n\nexport type TerrainCamera = { fov: number; position: [x: number, y: number, z: number]; near?: number; far?: number }\nexport type HeightSource = (col: number, row: number, time: number) => number\n\nconst defaultSource: HeightSource = (col, row, time) =>\n  0.12 + 1.7 * Math.pow(0.5 + 0.5 * Math.sin(col * 0.36 + time * 0.8) * Math.cos(row * 0.47 - time * 0.55), 2.4)\n\n/** Where the lifted bar is. `x` and `y` are pixels inside the stage. */\nexport type BarPick = { col: number; row: number; x: number; y: number; strength: number }\n\n/** Pixels from each edge of the stage that an automatic pick's lifted tip stays clear of. */\nexport type PickInset = { top?: number; right?: number; bottom?: number; left?: number }\n\ntype Pointer = { x: number; y: number; over: boolean }\ntype Palette = Record<(typeof PALETTE_TOKENS)[number], string>\n\ntype FieldProps = {\n  cols: number\n  rows: number\n  source: HeightSource\n  radius: number\n  lift: number\n  still: boolean\n  palette: Palette | null\n  pointer: React.RefObject<Pointer>\n  peak?: number\n  fade?: { near: number; far: number }\n  autoPick: boolean\n  pickInset?: PickInset\n  onPick?: (pick: BarPick | null) => void\n  onSlow?: () => void\n}\n\nfunction Field({ cols, rows, source, radius, lift, still, palette, pointer, peak, fade, autoPick, pickInset, onPick, onSlow }: FieldProps) {\n  const mesh = React.useRef<InstancedMesh>(null)\n  const invalidate = useThree((state) => state.invalidate)\n  const scene = useThree((state) => state.scene)\n  const gl = useThree((state) => state.gl)\n\n  const [geometry, material] = React.useMemo(() => {\n    const box = new BoxGeometry(SPACING * BAR_WIDTH, 1, SPACING * BAR_WIDTH)\n    box.translate(0, 0.5, 0)\n    return [box, new MeshLambertMaterial({ color: 0xffffff })] as const\n  }, [])\n\n  const scratch = React.useMemo(\n    () => ({\n      dummy: new Object3D(),\n      color: new Color(),\n      ink: new Color(),\n      accent: new Color(),\n      wash: new Color(),\n      ray: new Raycaster(),\n      ndc: new Vector2(),\n      floor: new Plane(new Vector3(0, 1, 0), 0),\n      hit: new Vector3(),\n      tip: new Vector3(),\n      bump: { x: 0, z: 0, target: { x: 0, z: 0 }, amount: 0, placed: false },\n      auto: { on: false, next: 1.5 },\n      pace: { frames: 0, samples: [] as number[] },\n    }),\n    [],\n  )\n\n  React.useEffect(() => {\n    return () => {\n      geometry.dispose()\n      material.dispose()\n    }\n  }, [geometry, material])\n\n  React.useEffect(() => {\n    if (!palette) return\n    scratch.ink.set(palette[\"--ink\"])\n    scratch.accent.set(palette[\"--accent-ink\"])\n    scratch.wash.set(palette[\"--wash\"])\n    scene.fog = fade ? new Fog(palette[\"--paper\"], fade.near, fade.far) : null\n    invalidate()\n  }, [fade, invalidate, palette, scene, scratch])\n\n  React.useEffect(() => {\n    if (onSlow && usesSoftwareRenderer(gl.getContext())) onSlow()\n  }, [gl, onSlow])\n\n  React.useEffect(() => {\n    if (!still) return\n    onPick?.(null)\n    invalidate()\n  }, [invalidate, onPick, still])\n\n  const center = (cols: number, index: number) => (index - (cols - 1) / 2) * SPACING\n  const nearest = (cols: number, value: number) => Math.max(0, Math.min(cols - 1, Math.round(value / SPACING + (cols - 1) / 2)))\n\n  useFrame(({ camera, clock, size }, delta) => {\n    const bars = mesh.current\n    if (!bars) return\n\n    if (onSlow && !still) {\n      const { pace } = scratch\n      pace.frames += 1\n      if (pace.frames > PACE_SKIP_FRAMES) pace.samples.push(delta)\n      if (pace.samples.length === PACE_SAMPLES) {\n        const median = pace.samples.toSorted((a, b) => a - b)[Math.floor(PACE_SAMPLES / 2)] ?? 0\n        if (median > SLOW_FRAME_SECONDS) onSlow()\n        scratch.pace = { frames: PACE_SKIP_FRAMES, samples: [] }\n      }\n    }\n\n    const { dummy, color, ink, accent, wash, ray, ndc, floor, hit, tip, bump, auto } = scratch\n    const time = still ? 0 : clock.elapsedTime\n    const over = pointer.current.over && !still\n\n    // The floor point under a spot on screen, snapped to a bar when picks are shown.\n    const floorAt = (x: number, y: number) => {\n      ndc.set(x, y)\n      ray.setFromCamera(ndc, camera)\n      if (!ray.ray.intersectPlane(floor, hit)) return null\n      return onPick || autoPick ? { x: center(cols, nearest(cols, hit.x)), z: center(rows, nearest(rows, hit.z)) } : { x: hit.x, z: hit.z }\n    }\n    const place = (target: { x: number; z: number }) => {\n      bump.target = target\n      if (!bump.placed) Object.assign(bump, { ...target, placed: true })\n    }\n    // How many pixels a bar's fully lifted tip could land outside the stage, less the inset, while it's picked.\n    const overshoot = (target: { x: number; z: number }) => {\n      const col = nearest(cols, target.x)\n      const row = nearest(rows, target.z)\n      let tallest = 0\n      for (let step = 0; step <= PICK_LOOKAHEAD_STEPS; step++) {\n        tallest = Math.max(tallest, source(col, row, time + (step / PICK_LOOKAHEAD_STEPS) * (AUTO_PICK_SECONDS + 1)))\n      }\n      const height = tallest + lift\n      tip.set(target.x, height, target.z).project(camera)\n      const x = ((tip.x + 1) / 2) * size.width\n      const y = ((1 - tip.y) / 2) * size.height\n      const { top = 0, right = 0, bottom = 0, left = 0 } = pickInset ?? {}\n      return Math.max(0, top - y) + Math.max(0, y - (size.height - bottom)) + Math.max(0, left - x) + Math.max(0, x - (size.width - right))\n    }\n\n    if (over) {\n      const target = floorAt(pointer.current.x, pointer.current.y)\n      if (target) place(target)\n      Object.assign(auto, { on: false, next: time + AUTO_PICK_SECONDS })\n    } else if (autoPick && !still && time > auto.next) {\n      auto.on = !auto.on\n      auto.next = time + (auto.on ? AUTO_PICK_SECONDS : AUTO_REST_SECONDS)\n      if (auto.on) {\n        bump.placed = false\n        // Tries a few spots and keeps the one whose lifted tip, and anything drawn at it, fits best.\n        let best: { x: number; z: number } | null = null\n        let bestMiss = Infinity\n        for (let attempt = 0; attempt < AUTO_PICK_TRIES && bestMiss > 0; attempt++) {\n          const target = floorAt(0.05 + Math.random() * 0.75, -0.25 + Math.random() * 0.75)\n          if (!target) continue\n          const miss = overshoot(target)\n          if (miss < bestMiss) [best, bestMiss] = [target, miss]\n        }\n        if (best) place(best)\n      }\n    }\n    bump.x += (bump.target.x - bump.x) * POINTER_EASE\n    bump.z += (bump.target.z - bump.z) * POINTER_EASE\n    bump.amount += ((over || auto.on ? 1 : 0) - bump.amount) * LIFT_EASE\n    if (bump.amount < 0.001) bump.placed = false\n\n    for (let col = 0, index = 0; col < cols; col++) {\n      for (let row = 0; row < rows; row++, index++) {\n        const x = (col - (cols - 1) / 2) * SPACING\n        const z = (row - (rows - 1) / 2) * SPACING\n        const height = source(col, row, time)\n        const distance = (x - bump.x) ** 2 + (z - bump.z) ** 2\n        const raised = Math.exp(-distance / radius) * lift * bump.amount\n\n        dummy.position.set(x, 0, z)\n        dummy.scale.set(1, height + raised, 1)\n        dummy.updateMatrix()\n        bars.setMatrixAt(index, dummy.matrix)\n\n        color.copy(wash).lerp(ink, Math.min(1, height / (peak ?? COLOR_HEIGHT)))\n        if (peak) color.lerp(accent, Math.max(0, Math.min(1, (height - peak * 0.6) / (peak * 0.6))))\n        if (raised > 0.25) color.lerp(accent, Math.min(1, raised / 1.8))\n        bars.setColorAt(index, color)\n      }\n    }\n    bars.instanceMatrix.needsUpdate = true\n    if (bars.instanceColor) bars.instanceColor.needsUpdate = true\n\n    if (!onPick) return\n    if (bump.amount < 0.02) return onPick(null)\n    const col = nearest(cols, bump.x)\n    const row = nearest(rows, bump.z)\n    tip.set(bump.x, source(col, row, time) + lift * bump.amount, bump.z).project(camera)\n    onPick({ col, row, x: ((tip.x + 1) / 2) * size.width, y: ((1 - tip.y) / 2) * size.height, strength: bump.amount })\n  })\n\n  return (\n    <>\n      <hemisphereLight args={[0xffffff, 0x555555, 1.2]} />\n      <directionalLight position={[-5, 12, 6]} intensity={1.3} />\n      <instancedMesh\n        key={cols * rows}\n        ref={mesh}\n        args={[geometry, material, cols * rows]}\n        frustumCulled={false}\n      />\n    </>\n  )\n}\n\ntype BarTerrainProps = Omit<React.ComponentProps<\"div\">, \"children\"> & {\n  /** Bars along the long side. */\n  cols?: number\n  /** Bars along the short side. */\n  rows?: number\n  /** Height of a bar at a grid position and time in seconds. Pass it from a client component. */\n  source?: HeightSource\n  /** How wide the bump under the pointer spreads. */\n  pointerRadius?: number\n  /** How high the bump under the pointer rises. */\n  pointerLift?: number\n  /** Bars this tall turn the accent, and lower ones shade toward it. Off by default. */\n  peak?: number\n  /** Fades the far bars into the page. Distances are in scene units from the camera. */\n  fade?: { near: number; far: number }\n  /** The camera, for a wider view than the default. */\n  camera?: TerrainCamera\n  /** The point the camera faces. */\n  lookAt?: [x: number, y: number, z: number]\n  /** Lifts a bar every few seconds when nobody's pointing. */\n  autoPick?: boolean\n  /** Keeps an automatic pick's lifted tip this many pixels inside the stage, so a label drawn there stays in view. */\n  pickInset?: PickInset\n  /** Runs every frame with the lifted bar, or `null` when there isn't one. Snaps the bump to one bar. */\n  onPick?: (pick: BarPick | null) => void\n  /** Holds a still frame if the device can't keep up, so the page around it stays responsive. */\n  pauseWhenSlow?: boolean\n  /** Describes the data for screen readers. */\n  label?: string\n}\n\nexport function BarTerrain({\n  cols = 30,\n  rows = 16,\n  source = defaultSource,\n  pointerRadius = 1.6,\n  pointerLift = 3.2,\n  peak,\n  fade,\n  camera = CAMERA,\n  lookAt = LOOK_AT,\n  autoPick = false,\n  pickInset,\n  onPick,\n  pauseWhenSlow = false,\n  label = \"3D bar field\",\n  className,\n  ...props\n}: BarTerrainProps) {\n  const host = React.useRef<HTMLDivElement>(null)\n  const pointer = React.useRef<Pointer>({ x: 0, y: 0, over: false })\n  const reduced = useReducedMotion()\n  const palette = useGlPalette(host, PALETTE_TOKENS)\n  const [slow, setSlow] = React.useState(false)\n  const onSlow = React.useCallback(() => setSlow(true), [])\n\n  const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {\n    const rect = event.currentTarget.getBoundingClientRect()\n    pointer.current = {\n      x: ((event.clientX - rect.left) / rect.width) * 2 - 1,\n      y: -((event.clientY - rect.top) / rect.height) * 2 + 1,\n      over: true,\n    }\n  }\n\n  return (\n    <GlStage\n      ref={host}\n      label={label}\n      camera={camera}\n      lookAt={lookAt}\n      animate={!slow}\n      data-paused={slow || undefined}\n      className={cn(\"h-64 cursor-crosshair\", className)}\n      onPointerMove={onPointerMove}\n      onPointerLeave={() => (pointer.current.over = false)}\n      {...props}\n    >\n      <Field\n        cols={cols}\n        rows={rows}\n        source={source}\n        radius={pointerRadius}\n        lift={pointerLift}\n        still={reduced || slow}\n        palette={palette}\n        pointer={pointer}\n        peak={peak}\n        fade={fade}\n        autoPick={autoPick}\n        pickInset={pickInset}\n        onPick={onPick}\n        onSlow={pauseWhenSlow ? onSlow : undefined}\n      />\n    </GlStage>\n  )\n}\n",
      "type": "registry:component"
    }
  ],
  "categories": [
    "webgl"
  ],
  "type": "registry:component"
}