{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "topo-lines",
  "type": "registry:component",
  "title": "Topo Lines",
  "description": "A living topographic map: contour lines of a slowly deforming terrain, with labeled index contours; the cursor raises a hill.",
  "author": "Marcelo Treviño Velázquez <https://furin.dev>",
  "dependencies": [],
  "categories": [
    "Backgrounds"
  ],
  "docs": "Installed in components/furin/topo-lines/. Docs, live controls and props table: https://furin.dev/components/topo-lines/",
  "files": [
    {
      "path": "registry/topo-lines/TopoLines.tsx",
      "content": "\"use client\";\nimport { useEffect, useRef } from \"react\";\nimport type { CSSProperties, ReactNode } from \"react\";\nimport \"./TopoLines.css\";\n\nexport interface TopoLinesProps {\n  /** Contenido que va encima del mapa. */\n  children?: ReactNode;\n  /** Color de las curvas de nivel. */\n  color?: string;\n  /** Color de las curvas maestras y de sus cotas. */\n  accent?: string;\n  /** Color del fondo. */\n  background?: string;\n  /** Cuántas curvas hay entre la cima y el valle. */\n  levels?: number;\n  /** Cada cuántas curvas hay una maestra con su cota. */\n  interval?: number;\n  /** Tamaño de las colinas (mayor = colinas más anchas). */\n  scale?: number;\n  /** Qué tan rápido se deforma el terreno. */\n  speed?: number;\n  /** Muestra la altura (cota) sobre las curvas maestras. */\n  labels?: boolean;\n  /** Clase extra para el contenedor. */\n  className?: string;\n  /** Estilos extra para el contenedor. */\n  style?: CSSProperties;\n}\n\n// ── Ruido de Perlin en 3D (x, y, tiempo) con permutación fija para que el terreno sea siempre el mismo ──\nconst PERM = (() => {\n  const p = new Uint8Array(512);\n  const base = Array.from({ length: 256 }, (_, i) => i);\n  let s = 1337;\n  for (let i = 255; i > 0; i--) { s = (s * 16807) % 2147483647; const j = s % (i + 1); [base[i], base[j]] = [base[j], base[i]]; }\n  for (let i = 0; i < 512; i++) p[i] = base[i & 255];\n  return p;\n})();\nconst fade = (t: number) => t * t * t * (t * (t * 6 - 15) + 10);\nconst lerp = (a: number, b: number, t: number) => a + (b - a) * t;\nfunction grad(h: number, x: number, y: number, z: number) {\n  const u = (h & 15) < 8 ? x : y;\n  const v = (h & 15) < 4 ? y : (h & 15) === 12 || (h & 15) === 14 ? x : z;\n  return ((h & 1) === 0 ? u : -u) + ((h & 2) === 0 ? v : -v);\n}\nfunction noise(x: number, y: number, z: number) {\n  const X = Math.floor(x) & 255, Y = Math.floor(y) & 255, Z = Math.floor(z) & 255;\n  x -= Math.floor(x); y -= Math.floor(y); z -= Math.floor(z);\n  const u = fade(x), v = fade(y), w = fade(z);\n  const A = PERM[X] + Y, AA = PERM[A] + Z, AB = PERM[A + 1] + Z, B = PERM[X + 1] + Y, BA = PERM[B] + Z, BB = PERM[B + 1] + Z;\n  return lerp(\n    lerp(lerp(grad(PERM[AA], x, y, z), grad(PERM[BA], x - 1, y, z), u), lerp(grad(PERM[AB], x, y - 1, z), grad(PERM[BB], x - 1, y - 1, z), u), v),\n    lerp(lerp(grad(PERM[AA + 1], x, y, z - 1), grad(PERM[BA + 1], x - 1, y, z - 1), u), lerp(grad(PERM[AB + 1], x, y - 1, z - 1), grad(PERM[BB + 1], x - 1, y - 1, z - 1), u), v),\n    w,\n  );\n}\n\nlet colorCtx: CanvasRenderingContext2D | null = null;\nconst RGB_CACHE = new Map<string, [number, number, number]>();\nfunction rgb(css: string, def: [number, number, number]): [number, number, number] {\n  const hit = RGB_CACHE.get(css);\n  if (hit) return hit;\n  try {\n    colorCtx ??= document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true })!;\n    colorCtx.clearRect(0, 0, 1, 1);\n    colorCtx.fillStyle = \"#010203\";\n    colorCtx.fillStyle = css;\n    colorCtx.fillRect(0, 0, 1, 1);\n    const d = colorCtx.getImageData(0, 0, 1, 1).data;\n    const out: [number, number, number] = [d[0], d[1], d[2]];\n    if (RGB_CACHE.size > 64) RGB_CACHE.clear();\n    RGB_CACHE.set(css, out);\n    return out;\n  } catch {\n    return def;\n  }\n}\n\ninterface Etiqueta { x: number; y: number; c2: number; s2: number; alfa: number; nivel: number; vive: boolean; }\n\n/** Fondo de mapa topográfico: curvas de nivel de un terreno que se deforma lento, con curvas maestras acotadas. */\nexport function TopoLines({\n  children,\n  color = \"#7f938f\",\n  accent = \"#e6c58e\",\n  background = \"#0a0c0e\",\n  levels = 30,\n  interval = 5,\n  scale = 1,\n  speed = 1,\n  labels = true,\n  className = \"\",\n  style,\n}: TopoLinesProps) {\n  const rootRef = useRef<HTMLDivElement>(null);\n  const props = useRef({ color, accent, background, levels, interval, scale, speed, labels });\n  props.current = { color, accent, background, levels, interval, scale, speed, labels };\n  const wakeRef = useRef<(() => void) | null>(null);\n\n  useEffect(() => {\n    const root = rootRef.current;\n    if (!root) return;\n    const canvas = document.createElement(\"canvas\");\n    canvas.className = \"furin-topo-lines__lienzo\";\n    canvas.setAttribute(\"aria-hidden\", \"true\");\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx) return;\n    root.insertBefore(canvas, root.firstChild);\n\n    const reducido = matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    let w = 0, h = 0, dpr = 1, raf = 0, visible = true, muerto = false, ult = 0;\n    let t = reducido ? 9 : 3;\n    let cel = 6, gw = 0, gh = 0;\n    let campo = new Float32Array(0);\n    // Cursor: levanta una colina bajo el puntero (las curvas se cierran a su alrededor).\n    const ptr = { x: 0, y: 0, tx: 0, ty: 0, pres: 0, presObj: 0, hay: false };\n    const etiquetas: Etiqueta[] = [];\n\n    const medir = () => {\n      dpr = Math.min(window.devicePixelRatio || 1, 2);\n      const r = root.getBoundingClientRect();\n      w = Math.max(1, r.width); h = Math.max(1, r.height);\n      canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr);\n      cel = Math.max(6, Math.sqrt((w * h) / 42000));\n      gw = Math.ceil(w / cel) + 2; gh = Math.ceil(h / cel) + 2;\n      campo = new Float32Array(gw * gh);\n      etiquetas.length = 0;\n      dibujar(0.016);\n      wake();\n    };\n\n    const dibujar = (dt: number) => {\n      const p = props.current;\n      const [cr, cg, cb] = rgb(p.color, [127, 147, 143]);\n      const [ar, ag, ab] = rgb(p.accent, [230, 197, 142]);\n      const [br, bg, bb] = rgb(p.background, [10, 12, 14]);\n      // Las líneas se pintan opacas (mezcladas con el fondo): así los empalmes de los segmentos no dejan puntos más brillantes.\n      const mezcla = (r: number, g: number, b: number, a: number) => `rgb(${Math.round(br + (r - br) * a)},${Math.round(bg + (g - bg) * a)},${Math.round(bb + (b - bb) * a)})`;\n      const nivelesN = Math.max(6, Math.round(p.levels));\n      const paso = 1 / nivelesN;\n      const inter = Math.max(2, Math.round(p.interval));\n\n      // Cursor suave y colina bajo él.\n      const k = 1 - Math.exp(-dt * 7);\n      ptr.x += (ptr.tx - ptr.x) * k; ptr.y += (ptr.ty - ptr.y) * k;\n      ptr.pres += (ptr.presObj - ptr.pres) * (1 - Math.exp(-dt * 3));\n\n      // 1) Campo de alturas: ruido fractal de 3 octavas; el tiempo es la tercera dimensión.\n      const inv = 1 / (230 * p.scale);\n      const sigma2 = 2 * Math.pow(Math.min(w, h) * 0.22, 2);\n      const amp = 0.3 * ptr.pres;\n      for (let j = 0; j < gh; j++) {\n        const y = j * cel;\n        for (let i = 0; i < gw; i++) {\n          const x = i * cel;\n          const nx = x * inv, ny = y * inv;\n          let v = noise(nx, ny, t) * 0.6 + noise(nx * 2.1 + 7.3, ny * 2.1 - 3.1, t * 1.3) * 0.28 + noise(nx * 4.3 - 5.7, ny * 4.3 + 9.1, t * 1.7) * 0.12;\n          v = 0.5 + v * 0.95;\n          if (amp > 0.001) { const dx = x - ptr.x, dy = y - ptr.y; v += amp * Math.exp(-(dx * dx + dy * dy) / sigma2); }\n          campo[j * gw + i] = v;\n        }\n      }\n\n      ctx.setTransform(1, 0, 0, 1, 0, 0);\n      ctx.clearRect(0, 0, canvas.width, canvas.height);\n      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n\n      // Marcas de registro tipo carta topográfica: cruces muy tenues cada 120 px.\n      ctx.strokeStyle = `rgba(${cr},${cg},${cb},0.22)`;\n      ctx.lineWidth = 1;\n      ctx.beginPath();\n      for (let x = 60; x < w; x += 120) for (let y = 60; y < h; y += 120) { ctx.moveTo(x - 3, y); ctx.lineTo(x + 3, y); ctx.moveTo(x, y - 3); ctx.lineTo(x, y + 3); }\n      ctx.stroke();\n\n      // 2) Marching squares por nivel: se agrupa por curva para pintarla de un solo trazo.\n      const total = nivelesN + 1;\n      const segs: number[][] = Array.from({ length: total }, () => []);\n      for (let j = 0; j < gh - 1; j++) {\n        for (let i = 0; i < gw - 1; i++) {\n          const a = campo[j * gw + i], b = campo[j * gw + i + 1], c = campo[(j + 1) * gw + i + 1], d = campo[(j + 1) * gw + i];\n          const mn = Math.min(a, b, c, d), mx = Math.max(a, b, c, d);\n          let l0 = Math.ceil(mn / paso), l1 = Math.floor(mx / paso);\n          if (l1 < 1 || l0 > nivelesN - 1) continue;\n          if (l0 < 1) l0 = 1;\n          if (l1 > nivelesN - 1) l1 = nivelesN - 1;\n          const x0 = i * cel, y0 = j * cel;\n          for (let l = l0; l <= l1; l++) {\n            const lv = l * paso;\n            let caso = 0;\n            if (a > lv) caso |= 1; if (b > lv) caso |= 2; if (c > lv) caso |= 4; if (d > lv) caso |= 8;\n            if (caso === 0 || caso === 15) continue;\n            // Puntos de cruce en los cuatro bordes (arriba, derecha, abajo, izquierda).\n            const tT = (lv - a) / (b - a), tR = (lv - b) / (c - b), tB = (lv - d) / (c - d), tL = (lv - a) / (d - a);\n            const Tx = x0 + tT * cel, Ty = y0, Rx = x0 + cel, Ry = y0 + tR * cel, Bx = x0 + tB * cel, By = y0 + cel, Lx = x0, Ly = y0 + tL * cel;\n            const s = segs[l];\n            switch (caso) {\n              case 1: case 14: s.push(Lx, Ly, Tx, Ty); break;\n              case 2: case 13: s.push(Tx, Ty, Rx, Ry); break;\n              case 3: case 12: s.push(Lx, Ly, Rx, Ry); break;\n              case 4: case 11: s.push(Rx, Ry, Bx, By); break;\n              case 6: case 9: s.push(Tx, Ty, Bx, By); break;\n              case 7: case 8: s.push(Lx, Ly, Bx, By); break;\n              case 5: s.push(Lx, Ly, Tx, Ty, Rx, Ry, Bx, By); break;\n              case 10: s.push(Tx, Ty, Rx, Ry, Lx, Ly, Bx, By); break;\n            }\n          }\n        }\n      }\n\n      ctx.lineCap = \"round\";\n      ctx.lineJoin = \"round\";\n      for (let l = 1; l < total - 1; l++) {\n        const s = segs[l];\n        if (!s.length) continue;\n        const maestra = l % inter === 0;\n        // Las curvas altas se encienden un poco más: da lectura de relieve sin colorear el mapa.\n        const alt = l / nivelesN;\n        if (maestra) { ctx.lineWidth = 1.35; ctx.strokeStyle = mezcla(ar, ag, ab, 0.55 + 0.3 * alt); }\n        else { ctx.lineWidth = 0.8; ctx.strokeStyle = mezcla(cr, cg, cb, 0.3 + 0.3 * alt); }\n        ctx.beginPath();\n        for (let q = 0; q < s.length; q += 4) { ctx.moveTo(s[q], s[q + 1]); ctx.lineTo(s[q + 2], s[q + 3]); }\n        ctx.stroke();\n      }\n\n      // 3) Cotas: cada etiqueta persigue el punto más cercano de su curva maestra y rompe la línea debajo.\n      if (p.labels) {\n        const maestras: number[] = [];\n        for (let l = inter; l < nivelesN; l += inter) maestras.push(l);\n        // Dos etiquetas por curva en pantallas grandes, una en chicas.\n        const porCurva = w * h > 260000 ? 2 : 1;\n        const meta = maestras.flatMap((l) => Array.from({ length: porCurva }, (_, n) => ({ l, n })));\n        while (etiquetas.length < meta.length) {\n          const n = etiquetas.length;\n          const m = meta[n];\n          etiquetas.push({ x: (0.15 + 0.7 * ((n * 0.6180339) % 1)) * w, y: (0.12 + 0.76 * ((n * 0.7548776 + 0.2) % 1)) * h, c2: 1, s2: 0, alfa: 0, nivel: m.l, vive: false });\n        }\n        etiquetas.length = meta.length;\n        ctx.font = `500 ${w < 420 ? 9 : 10}px \"JetBrains Mono\", ui-monospace, Menlo, monospace`;\n        ctx.textAlign = \"center\";\n        ctx.textBaseline = \"middle\";\n        const kk = 1 - Math.exp(-dt * 5);\n        for (let n = 0; n < etiquetas.length; n++) {\n          const e = etiquetas[n];\n          const l = meta[n].l;\n          e.nivel = l;\n          const s = segs[l];\n          let mejor = -1, md = 1e9;\n          for (let q = 0; q < s.length; q += 4) {\n            const mx = (s[q] + s[q + 2]) / 2, my = (s[q + 1] + s[q + 3]) / 2;\n            const d = (mx - e.x) * (mx - e.x) + (my - e.y) * (my - e.y);\n            if (d < md) { md = d; mejor = q; }\n          }\n          if (mejor >= 0 && md < 70 * 70) {\n            const mx = (s[mejor] + s[mejor + 2]) / 2, my = (s[mejor + 1] + s[mejor + 3]) / 2;\n            const ang = Math.atan2(s[mejor + 3] - s[mejor + 1], s[mejor + 2] - s[mejor]);\n            e.x += (mx - e.x) * kk; e.y += (my - e.y) * kk;\n            e.c2 += (Math.cos(2 * ang) - e.c2) * kk; e.s2 += (Math.sin(2 * ang) - e.s2) * kk;\n            e.vive = true;\n          } else if (e.alfa < 0.02) {\n            // Perdió su curva: reaparece en otro lugar cuando ya se apagó.\n            e.x = (0.12 + 0.76 * Math.random()) * w; e.y = (0.12 + 0.76 * Math.random()) * h; e.vive = false;\n          } else e.vive = false;\n          const borde = Math.min(e.x, w - e.x, e.y, h - e.y);\n          let objetivo = e.vive ? Math.min(1, Math.max(0, (borde - 14) / 40)) : 0;\n          // Si otra cota ya ocupa ese sitio, esta cede para que no se encimen.\n          for (let o = 0; o < n; o++) { const q = etiquetas[o]; if (q.alfa > 0.25 && Math.hypot(q.x - e.x, q.y - e.y) < 52) objetivo = 0; }\n          e.alfa += (objetivo - e.alfa) * (1 - Math.exp(-dt * 3));\n          if (e.alfa < 0.02) continue;\n          const ang = Math.atan2(e.s2, e.c2) / 2;\n          const txt = String(1200 + l * 25);\n          const tw = ctx.measureText(txt).width;\n          ctx.save();\n          ctx.translate(e.x, e.y);\n          ctx.rotate(ang);\n          ctx.globalCompositeOperation = \"destination-out\";\n          ctx.globalAlpha = e.alfa;\n          ctx.fillStyle = \"#000\";\n          ctx.fillRect(-tw / 2 - 5, -7, tw + 10, 14);\n          ctx.globalCompositeOperation = \"source-over\";\n          ctx.fillStyle = `rgba(${ar},${ag},${ab},${(0.92 * e.alfa).toFixed(3)})`;\n          ctx.fillText(txt, 0, 0.5);\n          ctx.restore();\n        }\n      }\n    };\n\n    const paso = (ts: number) => {\n      raf = 0;\n      if (muerto || !visible) return;\n      const dt = Math.min(0.05, ult ? (ts - ult) / 1000 : 0.016);\n      ult = ts;\n      t += dt * 0.045 * props.current.speed;\n      dibujar(dt);\n      raf = requestAnimationFrame(paso);\n    };\n    const wake = () => { if (reducido) return; if (!raf && visible && !muerto) { ult = 0; raf = requestAnimationFrame(paso); } };\n    wakeRef.current = () => { if (reducido) dibujar(0.016); else wake(); };\n\n    const ro = new ResizeObserver(medir);\n    ro.observe(root);\n    const io = new IntersectionObserver(([e]) => { visible = e.isIntersecting; if (visible) wake(); }, { rootMargin: \"80px\" });\n    io.observe(root);\n\n    const onMove = (e: PointerEvent) => {\n      const r = root.getBoundingClientRect();\n      ptr.tx = e.clientX - r.left; ptr.ty = e.clientY - r.top;\n      if (!ptr.hay) { ptr.x = ptr.tx; ptr.y = ptr.ty; ptr.hay = true; }\n      ptr.presObj = 1;\n    };\n    const onLeave = () => { ptr.presObj = 0; ptr.hay = false; };\n    if (!reducido) {\n      root.addEventListener(\"pointermove\", onMove, { passive: true });\n      root.addEventListener(\"pointerdown\", onMove, { passive: true });\n      root.addEventListener(\"pointerleave\", onLeave);\n    }\n    medir();\n\n    return () => {\n      muerto = true;\n      wakeRef.current = null;\n      cancelAnimationFrame(raf);\n      ro.disconnect(); io.disconnect();\n      root.removeEventListener(\"pointermove\", onMove);\n      root.removeEventListener(\"pointerdown\", onMove);\n      root.removeEventListener(\"pointerleave\", onLeave);\n      canvas.remove();\n    };\n  }, []);\n\n  useEffect(() => { wakeRef.current?.(); }, [color, accent, levels, interval, scale, speed, labels]);\n\n  const vars = { \"--furin-topo-lines-bg\": background } as CSSProperties;\n  return (\n    <div ref={rootRef} className={`furin-topo-lines ${className}`} style={{ ...vars, ...style }}>\n      <span className=\"furin-topo-lines__vineta\" aria-hidden=\"true\" />\n      {children != null ? <div className=\"furin-topo-lines__contenido\">{children}</div> : null}\n    </div>\n  );\n}\n\nexport default TopoLines;\n",
      "type": "registry:component",
      "target": "components/furin/topo-lines/TopoLines.tsx"
    },
    {
      "path": "registry/topo-lines/TopoLines.css",
      "content": ".furin-topo-lines {\n  position: absolute;\n  inset: 0;\n  display: grid;\n  place-items: center;\n  overflow: hidden;\n  isolation: isolate;\n  background: var(--furin-topo-lines-bg, #0a0c0e);\n  touch-action: pan-y;\n}\n.furin-topo-lines__lienzo { position: absolute; inset: 0; width: 100%; height: 100%; display: block; z-index: 0; }\n.furin-topo-lines__vineta {\n  position: absolute;\n  inset: 0;\n  z-index: 1;\n  pointer-events: none;\n  background: radial-gradient(ellipse 90% 85% at 50% 50%, transparent 35%, var(--furin-topo-lines-bg, #0a0c0e) 112%);\n}\n.furin-topo-lines__contenido { position: relative; z-index: 2; max-width: 100%; pointer-events: none; }\n.furin-topo-lines__contenido > * { pointer-events: auto; }\n",
      "type": "registry:file",
      "target": "components/furin/topo-lines/TopoLines.css"
    }
  ]
}
