{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "millstone-furrow-flow",
  "title": "Millstone Furrow Flow",
  "description": "An ambient processing-section background modelled on a dressed millstone pair: a static bedstone furrow layer under a slowly rotating runner layer, their crossing sweeping a drifting moiré band around the stone, while grain particles spiral outward from the eye, shrinking as they grind finer, and disperse into fading meal dust at the rim.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/core/millstone-furrow-flow/component.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useRef } from \"react\";\n\n// ---------------------------------------------------------------------------\n// MillstoneFurrowFlow — an ambient processing-section background modelled on\n// a dressed millstone pair. Two sickle-furrow patterns are drawn concentric\n// and share a centre but NOT a furrow count: the bedstone (static,\n// underneath) is dressed with 13 furrows, the runner (rotating, on top) with\n// the standard 12. Two near-equal angular frequencies beat against each\n// other — that |13-12| = 1 mismatch is what produces a single crossing band\n// that sweeps once around the stone per runner revolution, not 12 crossings\n// drifting together (which a same-count pair would produce, reading as a\n// restyled radial pattern rather than a genuine moiré). The bedstone's\n// sickle curvature is also mirrored relative to the runner's, matching how a\n// real bedstone is dressed as the runner's counter-pattern so the two\n// furrow sets genuinely scissor rather than merely overlay.\n//\n// A second, independent process rides on top of the furrow field: grain\n// particles spawn at the stone's eye (centre) and spiral outward, shrinking\n// as they travel — coarse feed at the centre, fine meal at the rim — then\n// disperse into a handful of fading dust motes instead of simply vanishing.\n// A particle's own angle is coupled to 60% of the runner's angular rate, so\n// its path traces a shallow spiral rather than a straight radius, visually\n// tying it to the furrow pattern turning beneath it.\n//\n// The real runner stone turns at roughly 120 RPM (~2 rev/s); rendered here\n// at 0.08 rev/s, a deliberate decoupling from the real rate for legibility\n// (a viewer needs seconds, not a strobe, to track the moiré sweep) — the\n// real number is documented, not animated 1:1.\n// ---------------------------------------------------------------------------\n\ntype Vec3 = [number, number, number];\n\nfunction parseColor(raw: string): Vec3 | null {\n  const s = raw.trim();\n  if (s.startsWith(\"#\")) {\n    const hex = s.slice(1);\n    if (hex.length === 3) {\n      const r = parseInt(hex.slice(0, 1) + hex.slice(0, 1), 16);\n      const g = parseInt(hex.slice(1, 2) + hex.slice(1, 2), 16);\n      const b = parseInt(hex.slice(2, 3) + hex.slice(2, 3), 16);\n      return Number.isNaN(r + g + b) ? null : [r, g, b];\n    }\n    if (hex.length >= 6) {\n      const r = parseInt(hex.slice(0, 2), 16);\n      const g = parseInt(hex.slice(2, 4), 16);\n      const b = parseInt(hex.slice(4, 6), 16);\n      return Number.isNaN(r + g + b) ? null : [r, g, b];\n    }\n    return null;\n  }\n  const m = s.match(/rgba?\\(\\s*([\\d.]+)[,\\s]+([\\d.]+)[,\\s]+([\\d.]+)/);\n  return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;\n}\n\nfunction mulberry32(seed: number) {\n  let a = seed >>> 0;\n  return () => {\n    a = (a + 0x6d2b79f5) >>> 0;\n    let t = a;\n    t = Math.imul(t ^ (t >>> 15), t | 1);\n    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\n// -- real millwright numbers, documented rate then a deliberately decoupled\n// rendered rate (round-9 legibility rule: near/above-paint-rate mechanics\n// must render slow, not 1:1) -------------------------------------------------\nconst REAL_RUNNER_RPM = 120; // ~2 rev/s on an operating stone mill\nconst RUNNER_REV_PER_SEC = 0.08; // rendered rate, documented as illustrative\nconst RUNNER_ANGULAR_RATE = RUNNER_REV_PER_SEC * Math.PI * 2; // rad/s\n\nconst RUNNER_FURROW_COUNT = 12; // sickle-dress furrow count, rotating layer\nconst BEDSTONE_FURROW_COUNT = 13; // one more than the runner — the frequency\n// mismatch that turns two overlaid patterns into a genuine beating moiré\nconst STONE_RADIUS_RATIO = 0.48; // of min(w, h)\nconst EYE_RADIUS_RATIO = 0.04; // of stone radius\nconst SICKLE_SWEEP = (12 * Math.PI) / 180; // angular curvature per furrow\nconst FURROW_ALPHA_CENTER = 0.62; // deepest cut, highest local contrast\nconst FURROW_ALPHA_RIM = 0.24; // shallowest land, above --border's 1.1:1 floor\nconst BEDSTONE_ALPHA_SCALE = 0.72; // static layer sits slightly under the runner\nconst CURVE_STEPS = 20; // polyline samples per furrow curve\n\nconst SPAWN_INTERVAL_MS = 900; // one grain every 0.9s\nconst BASE_STONE_RADIUS = 240; // reference radius the real numbers were measured against\nconst BASE_TRAVEL_MS = 4500; // ~4.5s eye-to-rim at the reference radius (~14px/s outward)\nconst MIN_TRAVEL_MS = 1500;\nconst MAX_TRAVEL_MS = 9000;\nconst EASE_EXP = 1.15; // accelerating outward travel (centrifugal build-up)\nconst SIZE_EYE_PX = 5;\nconst SIZE_RIM_PX = 1;\nconst ANGULAR_COUPLE = 0.6; // fraction of the runner's angular delta a grain inherits\nconst DUST_FADE_MS = 800;\nconst DUST_SIZE_PX = 0.5;\n\ninterface Grain {\n  spawnMs: number;\n  spawnAngle: number;\n  spawnRunnerAngle: number;\n}\n\ninterface Dust {\n  x: number;\n  y: number;\n  spawnMs: number;\n}\n\nexport interface MillstoneFurrowFlowProps {\n  /** extra classes merged onto the rendered root element */\n  className?: string;\n}\n\nexport function MillstoneFurrowFlow({ className = \"\" }: MillstoneFurrowFlowProps) {\n  const rootRef = useRef<HTMLDivElement>(null);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n\n  useEffect(() => {\n    const root = rootRef.current;\n    const canvas = canvasRef.current;\n    if (!root || !canvas) return;\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx) return;\n\n    const reduced = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    const rand = mulberry32(0x6d1157a3);\n\n    // -- token-derived ink, re-derived on theme class change, no paint before\n    // the first read ----------------------------------------------------------\n    let muted: Vec3 = [143, 143, 143];\n    let fg: Vec3 = [237, 237, 237];\n    const derive = () => {\n      const cs = getComputedStyle(document.documentElement);\n      muted = parseColor(cs.getPropertyValue(\"--ns-muted\")) ?? muted;\n      fg = parseColor(cs.getPropertyValue(\"--foreground\")) ?? fg;\n    };\n    derive();\n\n    let w = 0;\n    let h = 0;\n    let dpr = 1;\n    let cx = 0;\n    let cy = 0;\n    let stoneR = 0;\n    let eyeR = 0;\n    let travelMs = BASE_TRAVEL_MS;\n    let bedPath: Path2D = new Path2D();\n    let runnerPath: Path2D = new Path2D();\n    let gradient: CanvasGradient | null = null;\n\n    let raf = 0;\n    let visible = true;\n\n    let grains: Grain[] = [];\n    let dust: Dust[] = [];\n    let nextSpawnMs = 0;\n\n    // -- a furrow is a quadratic bezier in polar space: radius eases linearly\n    // eye->rim, angle curves through a midpoint offset by half the sickle\n    // sweep before reaching its endpoint. sweepSign flips the curvature so\n    // the bedstone pattern mirrors the runner's, matching a real dress. -----\n    const buildFurrowPath = (count: number, sweepSign: 1 | -1): Path2D => {\n      const path = new Path2D();\n      const sweep = SICKLE_SWEEP * sweepSign;\n      for (let f = 0; f < count; f++) {\n        const a0 = (f / count) * Math.PI * 2;\n        const aMid = a0 + sweep * 0.5;\n        const aEnd = a0 + sweep;\n        for (let i = 0; i <= CURVE_STEPS; i++) {\n          const t = i / CURVE_STEPS;\n          const ang = (1 - t) * (1 - t) * a0 + 2 * (1 - t) * t * aMid + t * t * aEnd;\n          const r = eyeR + (stoneR - eyeR) * t;\n          const px = cx + Math.cos(ang) * r;\n          const py = cy + Math.sin(ang) * r;\n          if (i === 0) path.moveTo(px, py);\n          else path.lineTo(px, py);\n        }\n      }\n      return path;\n    };\n\n    const buildGradient = (): CanvasGradient => {\n      const g = ctx.createRadialGradient(cx, cy, eyeR, cx, cy, stoneR);\n      g.addColorStop(0, `rgba(${muted[0]},${muted[1]},${muted[2]},${FURROW_ALPHA_CENTER})`);\n      g.addColorStop(1, `rgba(${muted[0]},${muted[1]},${muted[2]},${FURROW_ALPHA_RIM})`);\n      return g;\n    };\n\n    const spawnDust = (x: number, y: number, nowMs: number) => {\n      const count = 3 + Math.floor(rand() * 4); // 3..6\n      for (let i = 0; i < count; i++) {\n        const jitter = 3 + rand() * 3;\n        const jang = rand() * Math.PI * 2;\n        dust.push({\n          x: x + Math.cos(jang) * jitter,\n          y: y + Math.sin(jang) * jitter,\n          spawnMs: nowMs,\n        });\n      }\n    };\n\n    const drawGrain = (x: number, y: number, sizePx: number, alpha: number) => {\n      ctx.beginPath();\n      ctx.arc(x, y, Math.max(0.25, sizePx / 2), 0, Math.PI * 2);\n      ctx.fillStyle = `rgba(${fg[0]},${fg[1]},${fg[2]},${alpha.toFixed(3)})`;\n      ctx.fill();\n    };\n\n    const drawFurrows = (runnerAngle: number) => {\n      if (!gradient) return;\n      ctx.lineWidth = 1;\n      ctx.strokeStyle = gradient;\n      ctx.globalAlpha = BEDSTONE_ALPHA_SCALE;\n      ctx.stroke(bedPath); // static bedstone, underneath\n      ctx.globalAlpha = 1;\n      // rotating runner, on top — the 12-vs-13 frequency mismatch against the\n      // static bedstone is what produces the moiré band sweeping the stone\n      ctx.save();\n      ctx.translate(cx, cy);\n      ctx.rotate(runnerAngle);\n      ctx.translate(-cx, -cy);\n      ctx.stroke(runnerPath);\n      ctx.restore();\n    };\n\n    const render = (nowMs: number, runnerAngle: number) => {\n      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n      ctx.clearRect(0, 0, w, h);\n      if (w <= 0 || h <= 0 || stoneR <= 0) return;\n\n      drawFurrows(runnerAngle);\n\n      for (const g of grains) {\n        const elapsed = nowMs - g.spawnMs;\n        const progress = Math.min(1, Math.max(0, elapsed / travelMs));\n        const eased = Math.pow(progress, EASE_EXP);\n        const r = eyeR + (stoneR - eyeR) * eased;\n        const size = SIZE_EYE_PX + (SIZE_RIM_PX - SIZE_EYE_PX) * progress;\n        const angle = g.spawnAngle + ANGULAR_COUPLE * (runnerAngle - g.spawnRunnerAngle);\n        const x = cx + Math.cos(angle) * r;\n        const y = cy + Math.sin(angle) * r;\n        drawGrain(x, y, size, 1);\n      }\n\n      for (const d of dust) {\n        const age = nowMs - d.spawnMs;\n        const alpha = Math.max(0, 1 - age / DUST_FADE_MS);\n        if (alpha <= 0) continue;\n        drawGrain(d.x, d.y, DUST_SIZE_PX, alpha * 0.9);\n      }\n    };\n\n    const step = (nowMs: number) => {\n      // spawn grain feed — if the field was off-screen and paused long\n      // enough that many spawns were missed, fast-forward the schedule\n      // instead of catching up a runaway burst in one frame\n      if (nowMs - nextSpawnMs > SPAWN_INTERVAL_MS * 4) {\n        nextSpawnMs = nowMs - SPAWN_INTERVAL_MS;\n      }\n      while (nowMs >= nextSpawnMs) {\n        grains.push({\n          spawnMs: nextSpawnMs,\n          spawnAngle: rand() * Math.PI * 2,\n          spawnRunnerAngle: (nextSpawnMs / 1000) * RUNNER_ANGULAR_RATE,\n        });\n        nextSpawnMs += SPAWN_INTERVAL_MS;\n      }\n      // mature grains -> dust at the rim\n      const kept: Grain[] = [];\n      for (const g of grains) {\n        const elapsed = nowMs - g.spawnMs;\n        if (elapsed >= travelMs) {\n          const runnerAngle = (nowMs / 1000) * RUNNER_ANGULAR_RATE;\n          const angle = g.spawnAngle + ANGULAR_COUPLE * (runnerAngle - g.spawnRunnerAngle);\n          const x = cx + Math.cos(angle) * stoneR;\n          const y = cy + Math.sin(angle) * stoneR;\n          spawnDust(x, y, nowMs);\n        } else {\n          kept.push(g);\n        }\n      }\n      grains = kept;\n      // cull expired dust\n      dust = dust.filter((d) => nowMs - d.spawnMs < DUST_FADE_MS);\n    };\n\n    // -- absolute rAF timestamps throughout (never elapsed-since-mount): a\n    // pause/resume via IntersectionObserver never has to rewind or offset a\n    // clock, so grain spawnMs values stay valid and progress never goes\n    // negative across a visibility gap ----------------------------------------\n    const loop = (nowMs: number) => {\n      if (!visible) {\n        raf = 0;\n        return;\n      }\n      step(nowMs);\n      const runnerAngle = (nowMs / 1000) * RUNNER_ANGULAR_RATE;\n      render(nowMs, runnerAngle);\n      raf = requestAnimationFrame(loop);\n    };\n\n    const drawReducedFrame = () => {\n      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n      ctx.clearRect(0, 0, w, h);\n      if (w <= 0 || h <= 0 || stoneR <= 0) return;\n      // deliberately chosen NON-t0 most-structured frame: runner offset from\n      // the bedstone (visible cross-hatch, not full alignment), one grain\n      // mid-grind, one dust puff mid-fade — the whole process visible at once\n      const runnerAngle = (18 * Math.PI) / 180;\n      drawFurrows(runnerAngle);\n      const progress = 0.6;\n      const eased = Math.pow(progress, EASE_EXP);\n      const r = eyeR + (stoneR - eyeR) * eased;\n      const size = SIZE_EYE_PX + (SIZE_RIM_PX - SIZE_EYE_PX) * progress;\n      const angle = Math.PI * 0.35;\n      drawGrain(cx + Math.cos(angle) * r, cy + Math.sin(angle) * r, size, 1);\n      const dustAngle = Math.PI * 1.2;\n      drawGrain(cx + Math.cos(dustAngle) * stoneR, cy + Math.sin(dustAngle) * stoneR, DUST_SIZE_PX, 0.45);\n    };\n\n    const resize = () => {\n      const rect = root.getBoundingClientRect();\n      w = rect.width;\n      h = rect.height;\n      dpr = Math.min(1.5, window.devicePixelRatio || 1);\n      canvas.width = Math.max(1, Math.round(w * dpr));\n      canvas.height = Math.max(1, Math.round(h * dpr));\n      cx = w / 2;\n      cy = h / 2;\n      stoneR = Math.min(w, h) * STONE_RADIUS_RATIO;\n      eyeR = stoneR * EYE_RADIUS_RATIO;\n      // duration scales with stone radius (not a fixed px/s divisor) so a\n      // card-sized instance still reads a full ~4.5s transit at the 240px\n      // reference radius rather than a formula-derived crawl\n      travelMs = Math.min(\n        MAX_TRAVEL_MS,\n        Math.max(MIN_TRAVEL_MS, BASE_TRAVEL_MS * (stoneR / BASE_STONE_RADIUS || 1))\n      );\n      bedPath = buildFurrowPath(BEDSTONE_FURROW_COUNT, -1);\n      runnerPath = buildFurrowPath(RUNNER_FURROW_COUNT, 1);\n      gradient = buildGradient();\n      if (reduced) {\n        drawReducedFrame();\n      } else if (raf === 0 && visible) {\n        render(performance.now(), 0);\n      }\n    };\n\n    resize();\n\n    if (!reduced) {\n      raf = requestAnimationFrame(loop);\n    }\n\n    const ro = new ResizeObserver(resize);\n    ro.observe(root);\n\n    const io = new IntersectionObserver((entries) => {\n      visible = entries[0]?.isIntersecting ?? true;\n      if (!reduced && visible && raf === 0) {\n        raf = requestAnimationFrame(loop);\n      }\n    });\n    io.observe(root);\n\n    const mo = new MutationObserver(() => {\n      derive();\n      gradient = buildGradient();\n      if (reduced) drawReducedFrame();\n    });\n    mo.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\"] });\n\n    return () => {\n      cancelAnimationFrame(raf);\n      raf = 0;\n      ro.disconnect();\n      io.disconnect();\n      mo.disconnect();\n    };\n  }, []);\n\n  return (\n    <div ref={rootRef} className={`relative overflow-hidden bg-background ${className}`}>\n      <canvas ref={canvasRef} aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 h-full w-full\" />\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "components/ui/millstone-furrow-flow.tsx"
    }
  ],
  "cssVars": {
    "theme": {
      "color-ns-muted": "var(--ns-muted)"
    },
    "light": {
      "ns-muted": "#4d4d4d"
    },
    "dark": {
      "ns-muted": "#8f8f8f"
    }
  },
  "meta": {
    "collection": "core",
    "tags": [
      "background",
      "divider",
      "canvas",
      "moire",
      "particles",
      "radial",
      "ambient",
      "processing",
      "industrial"
    ],
    "instruction": "Build <MillstoneFurrowFlow className?> as a `w-full h-full` (or JS-set style dimensions) 2D canvas, DPR capped at 1.5. Geometry is derived from the container's SMALLER dimension: stone radius = min(w,h) * 0.48, eye (grain-feed origin) radius = stone radius * 0.04, both centred in the container. TWO CONCENTRIC FURROW LAYERS, each built once per resize as a single Path2D (never rebuilt per frame): the bedstone layer is 13 sickle-curved lines, the runner layer is 12 — deliberately DIFFERENT counts, because two identical-count radial patterns rotated against each other produce 12 drifting X-crossings, not a moiré; the |13-12|=1 frequency mismatch is what beats into a single band that sweeps once around the stone per runner revolution. Each furrow is stepped (20 samples) as a quadratic bezier in polar space — angle eases through a midpoint offset by half of a fixed 12-degree sickle sweep before reaching the endpoint, radius eases linearly from eye to rim, giving the line its curve rather than a straight radial spoke — and the bedstone's sweep sign is the mirror of the runner's (a real bedstone is dressed as the runner's counter-pattern so the two sets scissor rather than merely overlay). Stroke colour for both layers is a single CanvasGradient (createRadialGradient from eyeRadius to stoneRadius, rgba stops built from the --ns-muted token, alpha ~0.62 at the eye down to ~0.24 at the rim), rebuilt whenever geometry or theme changes, read via getComputedStyle(document.documentElement) plus a MutationObserver on its class, never a literal. Per frame: stroke the static bedstone Path2D once at globalAlpha 0.72, then stroke the runner Path2D once inside ctx.save()/translate(cx,cy)/rotate(runnerAngle)/translate(-cx,-cy)/restore() — rotation is a canvas transform around the shared centre, never a per-point recompute, and a single stroke() call per layer avoids the seam artefacts a segmented per-alpha-step stroke would leave. Runner rate: the real operating rate is ~120 RPM (~2 rev/s), documented but never animated 1:1 — rendered at a deliberately decoupled 0.08 rev/s so the beat band reads as a slow drifting sweep (~12.5s per lap), not a strobe. This crossing is the component's own resting motion and must stay visibly different at t0/2.5s/5s with zero particles on screen — verify by temporarily disabling the grain/dust draw calls. GRAIN PARTICLES: one spawns at the eye every 900ms, at a seeded-random angle (mulberry32, not Math.random, for a reproducible feed pattern), 5px diameter. Its radius-from-centre advances from the eye radius to the stone radius over a duration computed as BASE_TRAVEL_MS (4500ms, the documented ~4.5s eye-to-rim transit at a 240px reference stone radius) scaled by (stoneRadius / 240) and clamped to [1500, 9000]ms, so any container size still reads a full multi-second transit rather than a fixed-px/s crawl — eased by progress^1.15 (accelerating slightly, mimicking centrifugal build-up). Diameter shrinks linearly from 5px at the eye to 1px at the rim (coarse feed to fine meal). The particle's angle is its spawn angle plus 0.6x the runner's angular delta since spawn, so it traces a shallow spiral rather than a straight radius, visually coupling it to the rotating furrow layer beneath. On reaching the rim it does not vanish: it disperses into 3-6 jittered 0.5px dust motes that each fade from full to zero opacity over 800ms before being culled. Steady state is roughly 5 grains mid-travel (900ms spawn interval against a ~4.5s reference transit) plus 0-2 dust dispersals at any moment (drop the 900ms feed rate first if this reads as clutter at card scale before ever killing the component). Grain particles and dust are drawn in the --foreground token at full opacity (dust scaled by its own fade), never --ns-accent — furrow depth and grain colour are both fixed luminance, with zero interactive tint anywhere. NO PAINT BEFORE THE FIRST TOKEN READ: colours and the gradient are derived once before the first frame and re-derived on every documentElement class mutation. The animation clock is the raw rAF timestamp used directly as an absolute time throughout (never an elapsed-since-mount counter reset on resume), so pausing via IntersectionObserver on scroll-out and resuming on scroll-in never rewinds or offsets anything — a long hidden gap is handled by fast-forwarding the spawn schedule (skip stale catch-up spawns) rather than bursting or producing negative-progress grains. ResizeObserver recomputes stone/eye radius, travel duration, and both furrow Path2D objects without touching the grain feed's own clock. prefers-reduced-motion renders exactly one static frame, chosen deliberately non-t0: the runner layer offset 18 degrees from the bedstone (a visible cross-hatch, not alignment), one grain frozen at 60% radius (mid-grind, mid-size) and one dust mote frozen mid-fade at the rim — feed, grind, and dispersal all visible in the single still. Zero dependencies, canvas + CSS only, no interaction. Props: className."
  },
  "type": "registry:ui"
}