# Integrate `Marbling` from Motion Garden

You are helping me add the **Marbling** component to an existing project.
Everything you need is below — full source, dependencies, props and the
behavioural contract. Read it all before writing anything.

- **Component:** Marbling
- **Category:** Backgrounds
- **Summary:** Paper marbling made with the exact drop and comb math from the paper Mathematical Marbling. Each new ink drop pushes every older ring outward. The rings stretch, but they never overlap or tear. Every few drops, a comb drags through the ink and pulls it into feathers. Drag across it to pull the ink like a stylus.
- **Reference:** https://motion-garden.netlify.app/components/marbling
- **Full catalog (for you, the agent):** https://motion-garden.netlify.app/llms.txt

## Stack this source assumes

- React 19 with the Next.js App Router (never the `pages/` directory)
- TypeScript, strict
- Tailwind CSS v4, CSS-first config (utilities are inline; no `tailwind.config` needed)

If my project differs, adapt the integration — but do not rewrite the animation math to suit a different stack. Ask me first.

## Dependencies

```bash
# Marbling needs no npm packages
```

## Files to create

2 files — all of them are required. Paths are as shipped; the component may live anywhere in my project, but keep every peer file at the exact path shown so the import aliases resolve.

### 1. `components/registry/marbling/marbling.tsx`

```tsx
"use client";

import {
  useEffect,
  useLayoutEffect,
  useRef,
  useSyncExternalStore,
} from "react";
import { useAnimationLoop, type Metrics } from "@/hooks/use-animation-loop";

export interface MarblingProps {
  dropInterval?: number;
  dropSize?: number;
  combStrength?: number;
  tineSpacing?: number;
  sharpness?: number;
  stylus?: boolean;
  inkColor1?: string;
  inkColor2?: string;
  inkColor3?: string;
  paperColor?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const WORLD = 1000;
const CENTER = WORLD / 2;
const TAU = Math.PI * 2;

const FALL_SECONDS = 0.55;
const COMB_SECONDS = 1.4;
const COMB_EVERY = 7;
const COMB_TRAVEL = 0.9;
const FADE_SECONDS = 1.2;

const DROP_VERTS = 48;
const BIRTH_RADIUS = 0.5;
const SIZE_JITTER = 0.2;
const NEST_ODDS = 0.42;
const NEST_MAX = 3;

const MAX_EDGE_PX = 3.5;
const MIN_GAP_PX = 0.35;
const MERGE_FLOOR = 24;
const COARSE = 4;
const MARGIN_PX = 32;

const RENDER_TOLERANCE_PX = 0.2;
const RENDER_CHORD_PX = 28;

const MAX_VERTS = 30000;
const MAX_DROPS = 120;

const STYLUS_FALLOFF_PX = 18;
const STYLUS_STEP = 0.8;
const STYLUS_REACH = 9;
const STROKE_CAP = 128;

const WARM_GROUND = 18;
const WARM_TOP = 10;
const WARM_MAX = 48;
const WARM_COVER = 1.6;
const WARM_COMB_STEP_PX = 6;
const FIRST_COMB_AFTER = 2;

const FALLOFF_STEPS = 64;
const FALLOFF_SPAN = 32;
const FALLOFF_END = FALLOFF_SPAN * FALLOFF_STEPS;
const FALLOFF = new Float64Array(FALLOFF_END + 2);
for (let i = 0; i <= FALLOFF_END; i++) FALLOFF[i] = 2 ** (-i / FALLOFF_STEPS);

const SEED = 0x5eed1e;

interface Drop {
  slot: number;
  pts: Float64Array;
  alt: Float64Array;
  n: number;
  x0: number;
  y0: number;
  x1: number;
  y1: number;
  fade: number;
}

interface Fall {
  c: Float64Array;
  r2: number;
  t: number;
  done: number;
}

interface Comb {
  bx: number;
  by: number;
  nx: number;
  ny: number;
  mx: number;
  my: number;
  spacing: number;
  inv: number;
  travel: number;
  t: number;
  done: number;
}

const REDUCE_QUERY = "(prefers-reduced-motion: reduce)";

const subscribeReduce = (notify: () => void) => {
  if (typeof window === "undefined" || !window.matchMedia) return () => {};
  const query = window.matchMedia(REDUCE_QUERY);
  query.addEventListener("change", notify);
  return () => query.removeEventListener("change", notify);
};

const readReduce = () =>
  typeof window !== "undefined" &&
  !!window.matchMedia &&
  window.matchMedia(REDUCE_QUERY).matches;

const readReduceOnServer = () => false;

export default function Marbling({
  dropInterval = 0.9,
  dropSize = 48,
  combStrength = 1,
  tineSpacing = 80,
  sharpness = 22,
  stylus = true,
  inkColor1 = "#a855f7",
  inkColor2 = "#3b0764",
  inkColor3 = "#d4a24c",
  paperColor = "#f3ecdf",
  paused = false,
  reducedMotion = false,
  className = "",
}: MarblingProps) {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const canvasRef = useRef<HTMLCanvasElement | null>(null);

  const prefersReduced = useSyncExternalStore(
    subscribeReduce,
    readReduce,
    readReduceOnServer,
  );
  const still = reducedMotion || prefersReduced;

  const live = useRef({
    dropInterval,
    dropSize,
    combStrength,
    tineSpacing,
    sharpness,
    stylus,
    inkColor1,
    inkColor2,
    inkColor3,
    paperColor,
    still,
  });
  useLayoutEffect(() => {
    live.current = {
      dropInterval,
      dropSize,
      combStrength,
      tineSpacing,
      sharpness,
      stylus,
      inkColor1,
      inkColor2,
      inkColor3,
      paperColor,
      still,
    };
  });

  const drawRef = useRef<((dt: number) => void | false) | null>(null);
  const measureRef = useRef<((m: Metrics) => void) | null>(null);

  const loop = useAnimationLoop({
    target: containerRef,
    halted: paused || still,
    dpr: 1,
    onResize: (m) => measureRef.current?.(m),
    onFrame: ({ dt }) => (drawRef.current ? drawRef.current(dt) : false),
  });

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d", { willReadFrequently: true });
    if (!ctx) return;

    let width = 0;
    let height = 0;
    let dpr = 1;
    let scale = 1;
    let offX = 0;
    let offY = 0;
    let viewX0 = 0;
    let viewY0 = 0;
    let viewX1 = 0;
    let viewY1 = 0;
    let fineX0 = 0;
    let fineY0 = 0;
    let fineX1 = 0;
    let fineY1 = 0;
    let lod = 1;

    const rand = mulberry32(SEED);
    const drops: Drop[] = [];
    const spare: Drop[] = [];
    const falls: Fall[] = [];
    const combs: Comb[] = [];
    const strokes = new Float64Array(STROKE_CAP * 4);
    let strokeCount = 0;
    let strokeSlack = 0;
    const spot = new Float64Array(2);
    let nest = 0;
    let baseSlot = -1;
    let warmed = false;
    let clock = 0;
    let made = 0;
    let passes = 0;
    let sinceComb = 0;
    let seenStrength = 0;
    let seenSpacing = 0;
    let seenSharpness = 0;

    const inks = ["#a855f7", "#3b0764", "#d4a24c"];
    let paper = "#f3ecdf";
    const colorInputs = ["", "", "", ""];

    const pointer = { id: -1, x: 0, y: 0 };

    const resolveColor = (value: string, fallback: string): string => {
      const hex = normalizeHex(value);
      if (hex) return hex;
      ctx.fillStyle = fallback;
      ctx.fillStyle = value;
      return String(ctx.fillStyle);
    };

    const syncColors = (): boolean => {
      const cfg = live.current;
      if (
        cfg.inkColor1 === colorInputs[0] &&
        cfg.inkColor2 === colorInputs[1] &&
        cfg.inkColor3 === colorInputs[2] &&
        cfg.paperColor === colorInputs[3]
      ) {
        return false;
      }
      colorInputs[0] = cfg.inkColor1;
      colorInputs[1] = cfg.inkColor2;
      colorInputs[2] = cfg.inkColor3;
      colorInputs[3] = cfg.paperColor;
      inks[0] = resolveColor(cfg.inkColor1, inks[0]);
      inks[1] = resolveColor(cfg.inkColor2, inks[1]);
      inks[2] = resolveColor(cfg.inkColor3, inks[2]);
      paper = resolveColor(cfg.paperColor, paper);
      return true;
    };

    const map = () => {
      scale = Math.max(width, height) / WORLD;
      offX = width / 2 - CENTER * scale;
      offY = height / 2 - CENTER * scale;
      viewX0 = -offX / scale;
      viewY0 = -offY / scale;
      viewX1 = (width - offX) / scale;
      viewY1 = (height - offY) / scale;
      const margin = MARGIN_PX / scale;
      fineX0 = viewX0 - margin;
      fineY0 = viewY0 - margin;
      fineX1 = viewX1 + margin;
      fineY1 = viewY1 + margin;
    };

    const fallAll = (cx: number, cy: number, delta: number) => {
      for (let i = 0; i < drops.length; i++) {
        const d = drops[i];
        fallOn(d.pts, d.n, cx, cy, delta);
      }
      for (let i = 0; i < falls.length; i++) fallOn(falls[i].c, 1, cx, cy, delta);
      fallOn(spot, 1, cx, cy, delta);
    };

    const combAll = (comb: Comb, dz: number) => {
      for (let i = 0; i < drops.length; i++) {
        const d = drops[i];
        combOn(d.pts, d.n, comb, dz);
      }
      for (let i = 0; i < falls.length; i++) combOn(falls[i].c, 1, comb, dz);
      combOn(spot, 1, comb, dz);
    };

    const pullAll = (
      ax: number,
      ay: number,
      bx: number,
      by: number,
      falloff: number,
    ) => {
      const reach = falloff * STYLUS_REACH;
      const loX = Math.min(ax, bx) - reach - strokeSlack;
      const loY = Math.min(ay, by) - reach - strokeSlack;
      const hiX = Math.max(ax, bx) + reach + strokeSlack;
      const hiY = Math.max(ay, by) + reach + strokeSlack;
      for (let i = 0; i < drops.length; i++) {
        const d = drops[i];
        if (d.x1 < loX || d.x0 > hiX || d.y1 < loY || d.y0 > hiY) continue;
        pullOn(d.pts, d.n, ax, ay, bx, by, falloff);
      }
      for (let i = 0; i < falls.length; i++) {
        pullOn(falls[i].c, 1, ax, ay, bx, by, falloff);
      }
      pullOn(spot, 1, ax, ay, bx, by, falloff);
    };

    let clipT0 = 0;
    let clipT1 = 1;

    const clipFine = (x: number, y: number, dx: number, dy: number) => {
      let t0 = 0;
      let t1 = 1;
      if (dx === 0) {
        if (x < fineX0 || x > fineX1) return false;
      } else {
        let a = (fineX0 - x) / dx;
        let b = (fineX1 - x) / dx;
        if (a > b) {
          const t = a;
          a = b;
          b = t;
        }
        if (a > t0) t0 = a;
        if (b < t1) t1 = b;
        if (t0 > t1) return false;
      }
      if (dy === 0) {
        if (y < fineY0 || y > fineY1) return false;
      } else {
        let a = (fineY0 - y) / dy;
        let b = (fineY1 - y) / dy;
        if (a > b) {
          const t = a;
          a = b;
          b = t;
        }
        if (a > t0) t0 = a;
        if (b < t1) t1 = b;
        if (t0 > t1) return false;
      }
      clipT0 = t0;
      clipT1 = t1;
      return true;
    };

    const refine = (
      d: Drop,
      coverX0: number,
      coverY0: number,
      coverX1: number,
      coverY1: number,
    ): boolean => {
      const src = d.pts;
      const n = d.n;
      const edge = (MAX_EDGE_PX / scale) * lod;
      const edge2 = edge * edge;
      const gap = (MIN_GAP_PX / scale) * lod;
      const gap2 = gap * gap;
      const coarse2 = edge2 * COARSE * COARSE;
      const fx0 = fineX0;
      const fy0 = fineY0;
      const fx1 = fineX1;
      const fy1 = fineY1;

      let out = d.alt;
      if (out.length < n * 2 + 64) out = new Float64Array(n * 4 + 256);
      let k = 0;
      let hit = false;
      let x0 = Infinity;
      let y0 = Infinity;
      let x1 = -Infinity;
      let y1 = -Infinity;

      let lx = src[0];
      let ly = src[1];
      out[k++] = lx;
      out[k++] = ly;
      let lin = lx >= fx0 && lx <= fx1 && ly >= fy0 && ly <= fy1;

      for (let i = 1; i <= n; i++) {
        const closing = i === n;
        const j = closing ? 0 : i * 2;
        const qx = src[j];
        const qy = src[j + 1];
        const dx = qx - lx;
        const dy = qy - ly;
        const len2 = dx * dx + dy * dy;
        const qin = qx >= fx0 && qx <= fx1 && qy >= fy0 && qy <= fy1;

        if (!closing && (k >> 1) + (n - 1 - i) >= MERGE_FLOOR) {
          if (len2 < gap2) continue;
          if (!lin && !qin && len2 < coarse2) {
            const nj = i + 1 === n ? 0 : (i + 1) * 2;
            const nx = src[nj];
            const ny = src[nj + 1];
            if (!(nx >= fx0 && nx <= fx1 && ny >= fy0 && ny <= fy1)) continue;
          }
        }

        if (len2 > edge2 && clipFine(lx, ly, dx, dy)) {
          const t0 = clipT0;
          const t1 = clipT1;
          const span = (t1 - t0) * Math.sqrt(len2);
          if (span > edge) {
            const pieces = Math.ceil(span / edge);
            if (k + pieces * 2 + 8 > out.length) {
              const grown = new Float64Array((k + pieces * 2) * 2 + 256);
              grown.set(out.subarray(0, k));
              out = grown;
            }
            if (t0 > 0) {
              out[k++] = lx + dx * t0;
              out[k++] = ly + dy * t0;
            }
            for (let s = 1; s < pieces; s++) {
              const t = t0 + ((t1 - t0) * s) / pieces;
              out[k++] = lx + dx * t;
              out[k++] = ly + dy * t;
            }
            if (t1 < 1) {
              out[k++] = lx + dx * t1;
              out[k++] = ly + dy * t1;
            }
          }
        }
        if (closing) break;

        if (k + 2 > out.length) {
          const grown = new Float64Array(out.length * 2);
          grown.set(out.subarray(0, k));
          out = grown;
        }
        out[k++] = qx;
        out[k++] = qy;
        lx = qx;
        ly = qy;
        lin = qin;
      }

      for (let i = 0; i < k; i += 2) {
        const x = out[i];
        const y = out[i + 1];
        if (x < x0) x0 = x;
        if (x > x1) x1 = x;
        if (y < y0) y0 = y;
        if (y > y1) y1 = y;
        if (
          !hit &&
          x >= coverX0 &&
          x <= coverX1 &&
          y >= coverY0 &&
          y <= coverY1
        ) {
          hit = true;
        }
      }

      d.alt = src;
      d.pts = out;
      d.n = k >> 1;
      d.x0 = x0;
      d.y0 = y0;
      d.x1 = x1;
      d.y1 = y1;
      return hit;
    };

    const recycle = (d: Drop) => {
      if (spare.length < 24) spare.push(d);
    };

    const resample = () => {
      const cfg = live.current;
      const reach =
        (MARGIN_PX +
          Math.max(0, cfg.combStrength) *
            COMB_TRAVEL *
            Math.max(0, cfg.tineSpacing)) /
        scale;
      const coverX0 = viewX0 - reach;
      const coverY0 = viewY0 - reach;
      const coverX1 = viewX1 + reach;
      const coverY1 = viewY1 + reach;
      const keepLo = Math.min(0, coverX0, coverY0);
      const keepHi = Math.max(WORLD, coverX1, coverY1);

      let total = 0;
      let cover = -1;
      for (let i = 0; i < drops.length; i++) {
        const d = drops[i];
        const hit = refine(d, coverX0, coverY0, coverX1, coverY1);
        total += d.n;
        if (
          !hit &&
          d.x0 < CENTER &&
          d.x1 > CENTER &&
          d.y0 < CENTER &&
          d.y1 > CENTER &&
          contains(d.pts, d.n, CENTER, CENTER)
        ) {
          cover = i;
        }
      }

      let w = 0;
      for (let i = 0; i < drops.length; i++) {
        const d = drops[i];
        if (i === cover) baseSlot = d.slot;
        const gone =
          i <= cover ||
          d.fade <= 0 ||
          d.n < 3 ||
          d.x1 < keepLo ||
          d.x0 > keepHi ||
          d.y1 < keepLo ||
          d.y0 > keepHi;
        if (gone) recycle(d);
        else drops[w++] = d;
      }
      drops.length = w;

      let excess = drops.length - MAX_DROPS;
      for (let i = 0; i < drops.length && excess > 0; i++) {
        const d = drops[i];
        excess--;
        if (d.fade < 1) continue;
        const visible = !(
          d.x1 < viewX0 ||
          d.x0 > viewX1 ||
          d.y1 < viewY0 ||
          d.y0 > viewY1
        );
        d.fade = visible ? 0.999 : 0;
      }

      if (total > MAX_VERTS) lod = Math.min(lod * 1.25, 16);
      else if (lod > 1 && total < MAX_VERTS * 0.7) lod = Math.max(1, lod / 1.02);
    };

    const spawn = (instant: boolean, grow: number) => {
      const cfg = live.current;
      const w = viewX1 - viewX0;
      const h = viewY1 - viewY0;
      const zx0 = viewX0 + w * 0.15;
      const zy0 = viewY0 + h * 0.15;
      const zx1 = viewX1 - w * 0.15;
      const zy1 = viewY1 - h * 0.15;
      const radius =
        ((Math.max(1, cfg.dropSize) * grow) / scale) *
        (1 - SIZE_JITTER + 2 * SIZE_JITTER * rand());

      let cx: number;
      let cy: number;
      const inZone =
        spot[0] >= zx0 && spot[0] <= zx1 && spot[1] >= zy0 && spot[1] <= zy1;
      if (made > 0 && nest < NEST_MAX && inZone && rand() < NEST_ODDS) {
        const a = rand() * TAU;
        const off = rand() * radius * 0.25;
        cx = spot[0] + Math.cos(a) * off;
        cy = spot[1] + Math.sin(a) * off;
        nest++;
      } else {
        cx = zx0 + (zx1 - zx0) * rand();
        cy = zy0 + (zy1 - zy0) * rand();
        nest = 0;
      }

      const d =
        spare.pop() ??
        ({
          slot: 0,
          pts: new Float64Array(512),
          alt: new Float64Array(512),
          n: 0,
          x0: 0,
          y0: 0,
          x1: 0,
          y1: 0,
          fade: 1,
        } satisfies Drop);
      d.slot = made % 3;
      d.fade = 1;
      made++;
      const p = d.pts;
      for (let i = 0; i < DROP_VERTS; i++) {
        const a = (i / DROP_VERTS) * TAU;
        p[i * 2] = cx + Math.cos(a) * BIRTH_RADIUS;
        p[i * 2 + 1] = cy + Math.sin(a) * BIRTH_RADIUS;
      }
      d.n = DROP_VERTS;
      d.x0 = cx - BIRTH_RADIUS;
      d.y0 = cy - BIRTH_RADIUS;
      d.x1 = cx + BIRTH_RADIUS;
      d.y1 = cy + BIRTH_RADIUS;
      drops.push(d);
      spot[0] = cx;
      spot[1] = cy;

      const r2 = radius * radius;
      if (instant) {
        fallAll(cx, cy, r2);
        resample();
      } else {
        const c = new Float64Array(2);
        c[0] = cx;
        c[1] = cy;
        falls.push({ c, r2, t: 0, done: 0 });
      }
    };

    const makeComb = (): Comb | null => {
      const cfg = live.current;
      const spacing = Math.max(1, cfg.tineSpacing) / scale;
      const falloff = Math.max(0.5, cfg.sharpness) / scale;
      const travel = Math.max(0, cfg.combStrength) * COMB_TRAVEL * spacing;
      if (!(travel > 0)) return null;
      const k = passes++;
      const vertical = k % 2 === 0;
      const round = Math.floor(k / 2);
      const sign = round % 2 === 0 ? 1 : -1;
      const phase = (round % 2) * spacing * 0.5;
      const nx = vertical ? 1 : 0;
      const ny = vertical ? 0 : 1;
      return {
        bx: CENTER + nx * phase,
        by: CENTER + ny * phase,
        nx,
        ny,
        mx: vertical ? 0 : sign,
        my: vertical ? sign : 0,
        spacing,
        inv: 1 / falloff,
        travel,
        t: 0,
        done: 0,
      };
    };

    const warm = () => {
      const cfg = live.current;
      const size = Math.max(1, cfg.dropSize);
      const areaPx = width * height;
      const need = (WARM_COVER * areaPx) / (Math.PI * size * size);
      const base = WARM_GROUND + WARM_TOP;
      const count = Math.max(base, Math.min(WARM_MAX, Math.round(need)));
      const grow = need > count ? Math.sqrt(need / count) : 1;
      const top = Math.round((count * WARM_TOP) / base);
      for (let i = 0; i < count - top; i++) spawn(true, grow);
      const comb = makeComb();
      if (comb) {
        const steps = Math.min(
          24,
          Math.max(6, Math.ceil((comb.travel * scale) / WARM_COMB_STEP_PX)),
        );
        const dz = comb.travel / steps;
        for (let s = 0; s < steps; s++) {
          combAll(comb, dz);
          resample();
        }
      }
      for (let i = 0; i < top; i++) spawn(true, 1);
      sinceComb = COMB_EVERY - FIRST_COMB_AFTER;
      seenStrength = cfg.combStrength;
      seenSpacing = cfg.tineSpacing;
      seenSharpness = cfg.sharpness;
      warmed = true;
    };

    const applyStrokes = () => {
      const falloff = STYLUS_FALLOFF_PX / scale;
      const step = STYLUS_STEP * falloff;
      strokeSlack = 0;
      for (let s = 0; s < strokeCount; s++) {
        const o = s * 4;
        const ax = strokes[o];
        const ay = strokes[o + 1];
        const sx = strokes[o + 2] - ax;
        const sy = strokes[o + 3] - ay;
        const len = Math.sqrt(sx * sx + sy * sy);
        if (!(len > 1e-9)) continue;
        const pieces = Math.min(256, Math.ceil(len / step));
        for (let p = 0; p < pieces; p++) {
          const t0 = p / pieces;
          const t1 = (p + 1) / pieces;
          pullAll(ax + sx * t0, ay + sy * t0, ax + sx * t1, ay + sy * t1, falloff);
        }
        strokeSlack += len;
      }
      strokeCount = 0;
      strokeSlack = 0;
    };

    const queueStroke = (x: number, y: number) => {
      const ax = pointer.x;
      const ay = pointer.y;
      pointer.x = x;
      pointer.y = y;
      if ((x - ax) * (x - ax) + (y - ay) * (y - ay) < 1e-10) return;
      if (strokeCount >= STROKE_CAP) {
        const o = (strokeCount - 1) * 4;
        strokes[o + 2] = x;
        strokes[o + 3] = y;
        return;
      }
      const o = strokeCount * 4;
      strokes[o] = ax;
      strokes[o + 1] = ay;
      strokes[o + 2] = x;
      strokes[o + 3] = y;
      strokeCount++;
    };

    const onDown = (e: PointerEvent) => {
      if (!live.current.stylus || !warmed || pointer.id !== -1) return;
      if (e.pointerType === "mouse" && e.button !== 0) return;
      const box = canvas.getBoundingClientRect();
      pointer.id = e.pointerId;
      pointer.x = (e.clientX - box.left - offX) / scale;
      pointer.y = (e.clientY - box.top - offY) / scale;
      try {
        canvas.setPointerCapture(e.pointerId);
      } catch {
      }
      e.preventDefault();
    };

    const onMove = (e: PointerEvent) => {
      if (e.pointerId !== pointer.id) return;
      if (!live.current.stylus) {
        onUp(e);
        return;
      }
      const box = canvas.getBoundingClientRect();
      const left = box.left + offX;
      const top = box.top + offY;
      const batch =
        typeof e.getCoalescedEvents === "function" ? e.getCoalescedEvents() : [];
      if (batch.length > 0) {
        for (let i = 0; i < batch.length; i++) {
          queueStroke(
            (batch[i].clientX - left) / scale,
            (batch[i].clientY - top) / scale,
          );
        }
      } else {
        queueStroke((e.clientX - left) / scale, (e.clientY - top) / scale);
      }
      loop.paint();
    };

    const onUp = (e: PointerEvent) => {
      if (e.pointerId !== pointer.id) return;
      pointer.id = -1;
      if (canvas.hasPointerCapture(e.pointerId)) {
        canvas.releasePointerCapture(e.pointerId);
      }
    };

    const render = () => {
      if (width <= 0 || height <= 0) return;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      ctx.globalAlpha = 1;
      ctx.fillStyle = baseSlot < 0 ? paper : inks[baseSlot];
      ctx.fillRect(0, 0, width, height);
      ctx.setTransform(dpr * scale, 0, 0, dpr * scale, dpr * offX, dpr * offY);
      const tol = RENDER_TOLERANCE_PX / scale;
      const reach2 = (RENDER_CHORD_PX / scale) ** 2;
      for (let i = 0; i < drops.length; i++) {
        const d = drops[i];
        if (d.x1 < viewX0 || d.x0 > viewX1 || d.y1 < viewY0 || d.y0 > viewY1) {
          continue;
        }
        ctx.beginPath();
        traceSimplified(ctx, d.pts, d.n, tol, reach2);
        ctx.closePath();
        ctx.fillStyle = inks[d.slot];
        if (d.fade < 1) {
          ctx.globalAlpha = d.fade > 0 ? d.fade : 0;
          ctx.fill();
          ctx.globalAlpha = 1;
        } else {
          ctx.fill();
        }
      }
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };

    const frame = (dt: number): void | false => {
      if (width <= 0 || height <= 0 || !warmed) return;
      const cfg = live.current;
      const step = cfg.still ? 0 : dt;
      let moved = false;

      if (strokeCount > 0) {
        applyStrokes();
        moved = true;
      }

      if (step > 0) {
        if (
          cfg.combStrength !== seenStrength ||
          cfg.tineSpacing !== seenSpacing ||
          cfg.sharpness !== seenSharpness
        ) {
          seenStrength = cfg.combStrength;
          seenSpacing = cfg.tineSpacing;
          seenSharpness = cfg.sharpness;
          sinceComb = Math.max(sinceComb, COMB_EVERY - 1);
        }

        const interval = Math.max(0.05, cfg.dropInterval);
        clock += step;
        if (clock >= interval) {
          clock = clock - interval > interval ? 0 : clock - interval;
          spawn(false, 1);
          moved = true;
          sinceComb++;
          if (sinceComb >= COMB_EVERY) {
            const comb = makeComb();
            if (comb) {
              combs.push(comb);
              sinceComb = 0;
            }
          }
        }

        let w = 0;
        for (let i = 0; i < falls.length; i++) {
          const f = falls[i];
          f.t = Math.min(FALL_SECONDS, f.t + step);
          const target = f.r2 * easeOutCubic(f.t / FALL_SECONDS);
          const delta = target - f.done;
          f.done = target;
          if (delta > 0) {
            fallAll(f.c[0], f.c[1], delta);
            moved = true;
          }
          if (f.t < FALL_SECONDS) falls[w++] = f;
        }
        falls.length = w;

        w = 0;
        for (let i = 0; i < combs.length; i++) {
          const c = combs[i];
          c.t = Math.min(COMB_SECONDS, c.t + step);
          const target = c.travel * easeInOut(c.t / COMB_SECONDS);
          const dz = target - c.done;
          c.done = target;
          if (dz !== 0) {
            combAll(c, dz);
            moved = true;
          }
          if (c.t < COMB_SECONDS) combs[w++] = c;
        }
        combs.length = w;

        for (let i = 0; i < drops.length; i++) {
          const d = drops[i];
          if (d.fade < 1) {
            d.fade -= step / FADE_SECONDS;
            moved = true;
          }
        }
      }

      if (moved) resample();
      const recolored = syncColors();
      if (moved || recolored || dt === 0) render();
    };
    drawRef.current = frame;

    measureRef.current = (m: Metrics) => {
      if (m.width <= 0 || m.height <= 0) return;
      width = m.width;
      height = m.height;
      dpr = m.dpr;
      canvas.width = m.bufferWidth;
      canvas.height = m.bufferHeight;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      map();
      if (!warmed) warm();
      else resample();
      syncColors();
      render();
    };

    canvas.addEventListener("pointerdown", onDown);
    canvas.addEventListener("pointermove", onMove);
    canvas.addEventListener("pointerup", onUp);
    canvas.addEventListener("pointercancel", onUp);

    loop.resize();
    loop.start();

    return () => {
      drawRef.current = null;
      measureRef.current = null;
      canvas.removeEventListener("pointerdown", onDown);
      canvas.removeEventListener("pointermove", onMove);
      canvas.removeEventListener("pointerup", onUp);
      canvas.removeEventListener("pointercancel", onUp);
      if (pointer.id !== -1 && canvas.hasPointerCapture(pointer.id)) {
        canvas.releasePointerCapture(pointer.id);
      }
      drops.length = 0;
      spare.length = 0;
      falls.length = 0;
      combs.length = 0;
    };
  }, [loop]);

  useEffect(() => {
    loop.paint();
  }, [
    dropInterval,
    dropSize,
    combStrength,
    tineSpacing,
    sharpness,
    stylus,
    inkColor1,
    inkColor2,
    inkColor3,
    paperColor,
    loop,
  ]);

  return (
    <div
      ref={containerRef}
      className={`relative h-full w-full overflow-hidden ${className}`.trim()}
      style={{ backgroundColor: paperColor }}
    >
      <canvas
        ref={canvasRef}
        aria-hidden="true"
        className={`absolute inset-0 block size-full${stylus ? " touch-none" : ""}`}
      />
    </div>
  );
}

const mulberry32 = (seed: number) => () => {
  seed |= 0;
  seed = (seed + 0x6d2b79f5) | 0;
  let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
  t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
  return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};

const easeOutCubic = (t: number) => 1 - (1 - t) * (1 - t) * (1 - t);

const easeInOut = (t: number) => t * t * (3 - 2 * t);

const HEX = /^#?([\da-f]{3}|[\da-f]{6})$/i;

const normalizeHex = (value: string): string | null => {
  const m = HEX.exec(value.trim());
  if (!m) return null;
  const h = m[1].toLowerCase();
  return h.length === 3 ? `#${h[0]}${h[0]}${h[1]}${h[1]}${h[2]}${h[2]}` : `#${h}`;
};

function fallOn(
  p: Float64Array,
  n: number,
  cx: number,
  cy: number,
  delta: number,
) {
  for (let i = 0, m = n * 2; i < m; i += 2) {
    const dx = p[i] - cx;
    const dy = p[i + 1] - cy;
    const q = dx * dx + dy * dy;
    if (q < 1e-12) continue;
    const f = Math.sqrt(1 + delta / q);
    p[i] = cx + dx * f;
    p[i + 1] = cy + dy * f;
  }
}

function combOn(p: Float64Array, n: number, comb: Comb, dz: number) {
  const bx = comb.bx;
  const by = comb.by;
  const nx = comb.nx;
  const ny = comb.ny;
  const mx = comb.mx;
  const my = comb.my;
  const spacing = comb.spacing;
  const per = 1 / spacing;
  const half = spacing / 2;
  const toTable = comb.inv * FALLOFF_STEPS;
  for (let i = 0, m = n * 2; i < m; i += 2) {
    let u = (p[i] - bx) * nx + (p[i + 1] - by) * ny;
    u -= Math.floor(u * per) * spacing;
    const x = (half - Math.abs(u - half)) * toTable;
    if (x >= FALLOFF_END) continue;
    const j = x | 0;
    const a = FALLOFF[j];
    const w = dz * (a + (FALLOFF[j + 1] - a) * (x - j));
    p[i] += w * mx;
    p[i + 1] += w * my;
  }
}

function pullOn(
  p: Float64Array,
  n: number,
  ax: number,
  ay: number,
  bx: number,
  by: number,
  falloff: number,
) {
  const sx = bx - ax;
  const sy = by - ay;
  const len2 = sx * sx + sy * sy;
  if (!(len2 > 1e-18)) return;
  const len = Math.sqrt(len2);
  const mx = sx / len;
  const my = sy / len;
  const toTable = FALLOFF_STEPS / falloff;
  const reach = falloff * STYLUS_REACH;
  const loX = Math.min(ax, bx) - reach;
  const loY = Math.min(ay, by) - reach;
  const hiX = Math.max(ax, bx) + reach;
  const hiY = Math.max(ay, by) + reach;
  for (let i = 0, m = n * 2; i < m; i += 2) {
    const px = p[i];
    const py = p[i + 1];
    if (px < loX || px > hiX || py < loY || py > hiY) continue;
    const wx = px - ax;
    const wy = py - ay;
    let t = (wx * sx + wy * sy) / len2;
    t = t < 0 ? 0 : t > 1 ? 1 : t;
    const ex = wx - t * sx;
    const ey = wy - t * sy;
    const d = Math.sqrt(ex * ex + ey * ey);
    if (d > reach) continue;
    const x = d * toTable;
    const j = x | 0;
    const a = FALLOFF[j];
    const w = len * (a + (FALLOFF[j + 1] - a) * (x - j));
    p[i] = px + w * mx;
    p[i + 1] = py + w * my;
  }
}

function traceSimplified(
  ctx: CanvasRenderingContext2D,
  p: Float64Array,
  n: number,
  tol: number,
  reach2: number,
) {
  const tol2 = tol * tol;
  let ax = p[0];
  let ay = p[1];
  ctx.moveTo(ax, ay);
  let open = false;
  let lox = 0;
  let loy = 0;
  let hix = 0;
  let hiy = 0;
  let px = ax;
  let py = ay;
  let pd2 = 0;
  for (let i = 1; i < n; i++) {
    const vx = p[i * 2];
    const vy = p[i * 2 + 1];
    let dx = vx - ax;
    let dy = vy - ay;
    let d2 = dx * dx + dy * dy;
    if (
      open &&
      !(
        d2 >= pd2 &&
        d2 <= reach2 &&
        lox * dy - loy * dx >= 0 &&
        hix * dy - hiy * dx <= 0
      )
    ) {
      ctx.lineTo(px, py);
      ax = px;
      ay = py;
      open = false;
      dx = vx - ax;
      dy = vy - ay;
      d2 = dx * dx + dy * dy;
    }
    px = vx;
    py = vy;
    pd2 = d2;
    if (d2 <= tol2) continue;
    const len = Math.sqrt(d2);
    const s = tol / len;
    const c = Math.sqrt(1 - s * s);
    const ux = dx / len;
    const uy = dy / len;
    const nlx = ux * c + uy * s;
    const nly = uy * c - ux * s;
    const nhx = ux * c - uy * s;
    const nhy = uy * c + ux * s;
    if (!open) {
      lox = nlx;
      loy = nly;
      hix = nhx;
      hiy = nhy;
      open = true;
    } else {
      if (lox * nly - loy * nlx > 0) {
        lox = nlx;
        loy = nly;
      }
      if (hix * nhy - hiy * nhx < 0) {
        hix = nhx;
        hiy = nhy;
      }
    }
  }
  ctx.lineTo(px, py);
}

function contains(p: Float64Array, n: number, x: number, y: number): boolean {
  let inside = false;
  for (let i = 0, j = n - 1; i < n; j = i++) {
    const xi = p[i * 2];
    const yi = p[i * 2 + 1];
    const xj = p[j * 2];
    const yj = p[j * 2 + 1];
    if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) {
      inside = !inside;
    }
  }
  return inside;
}
```

### 2. `hooks/use-animation-loop.ts` — peer hook, required

```tsx
"use client";

import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";

export interface Metrics {
  width: number;
  height: number;
  dpr: number;
  bufferWidth: number;
  bufferHeight: number;
}

export interface FrameInfo {
  now: number;
  dt: number;
  elapsed: number;
  frame: number;
}

export interface AnimationLoopHandle {
  start(): void;
  stop(): void;
  paint(): void;
  resize(): void;
  readonly running: boolean;
}

export interface AnimationLoopOptions {
  target: React.RefObject<HTMLElement | null>;
  halted?: boolean;
  dpr?: number | "auto";
  onResize?(metrics: Metrics): void;
  onFrame?(info: FrameInfo): void | false;
  paintWhenHalted?: boolean;
  resizeDebounceMs?: number;
  gl?(): WebGLRenderingContext | WebGL2RenderingContext | null | undefined;
  onDispose?(): void;
  deps?: unknown[];
}

const MAX_DT = 1 / 15;

export function useAnimationLoop(
  options: AnimationLoopOptions,
): AnimationLoopHandle {
  const opts = useRef(options);
  useLayoutEffect(() => {
    opts.current = options;
  });

  const raf = useRef<number | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const running = useRef(false);
  const disposed = useRef(false);
  const startedAt = useRef(0);
  const last = useRef(0);
  const frame = useRef(0);

  const measure = useCallback((): Metrics | null => {
    const el = opts.current.target.current;
    if (!el) return null;
    const rect = el.getBoundingClientRect();
    const cap = opts.current.dpr ?? "auto";
    const limit = cap === "auto" ? 2 : cap;
    const dpr = Math.min(
      typeof window === "undefined" ? 1 : window.devicePixelRatio || 1,
      limit,
    );
    return {
      width: rect.width,
      height: rect.height,
      dpr,
      bufferWidth: Math.max(1, Math.round(rect.width * dpr)),
      bufferHeight: Math.max(1, Math.round(rect.height * dpr)),
    };
  }, []);

  const tick = useCallback(function tick(now: number) {
    if (disposed.current) return;

    if (startedAt.current === 0) startedAt.current = now;
    const dt = last.current === 0 ? 0 : Math.min((now - last.current) / 1000, MAX_DT);
    last.current = now;

    const info: FrameInfo = {
      now,
      dt,
      elapsed: (now - startedAt.current) / 1000,
      frame: frame.current++,
    };

    const verdict = opts.current.onFrame?.(info);

    if (disposed.current) return;

    if (verdict === false || opts.current.halted) {
      running.current = false;
      raf.current = null;
      return;
    }
    raf.current = requestAnimationFrame(tick);
  }, []);

  const start = useCallback(() => {
    if (disposed.current || running.current) return;
    running.current = true;
    last.current = 0;
    raf.current = requestAnimationFrame(tick);
  }, [tick]);

  const stop = useCallback(() => {
    running.current = false;
    if (raf.current !== null) {
      cancelAnimationFrame(raf.current);
      raf.current = null;
    }
  }, []);

  const paint = useCallback(() => start(), [start]);

  const resize = useCallback(() => {
    const metrics = measure();
    if (!metrics) return;
    opts.current.onResize?.(metrics);
    if (opts.current.paintWhenHalted !== false) paint();
    else if (!opts.current.halted) start();
  }, [measure, paint, start]);

  const deps = options.deps ?? [];

  useEffect(() => {
    disposed.current = false;
    const el = opts.current.target.current;
    if (!el) return;

    const run = () => {
      if (disposed.current) return;
      resize();
    };

    const observer = new ResizeObserver(() => {
      const wait = opts.current.resizeDebounceMs ?? 0;
      if (wait <= 0) {
        run();
        return;
      }
      if (timer.current !== null) clearTimeout(timer.current);
      timer.current = setTimeout(() => {
        timer.current = null;
        run();
      }, wait);
    });
    observer.observe(el);

    resize();
    if (!opts.current.halted) start();

    return () => {
      disposed.current = true;
      running.current = false;
      if (raf.current !== null) {
        cancelAnimationFrame(raf.current);
        raf.current = null;
      }
      if (timer.current !== null) {
        clearTimeout(timer.current);
        timer.current = null;
      }
      observer.disconnect();
      opts.current.onDispose?.();
      const context = opts.current.gl?.();
      context?.getExtension("WEBGL_lose_context")?.loseContext();
      startedAt.current = 0;
      last.current = 0;
      frame.current = 0;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  const halted = options.halted ?? false;
  useEffect(() => {
    if (!halted) start();
  }, [halted, start]);

  return useMemo<AnimationLoopHandle>(
    () => ({
      start,
      stop,
      paint,
      resize,
      get running() {
        return running.current;
      },
    }),
    [start, stop, paint, resize],
  );
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `dropInterval` | `number` | `0.9` | Time between ink drops. Range 0.2–4 s. |
| `dropSize` | `number` | `48` | The radius of a fresh drop. Range 16–160 px. |
| `combStrength` | `number` | `1` | How far each comb pass drags the ink. 0 stops the combing. Range 0–3 ×. |
| `tineSpacing` | `number` | `80` | The gap between the teeth of the comb. Range 30–240 px. Ignored while `combStrength` is `0`. |
| `sharpness` | `number` | `22` | How fast a tooth's pull fades with distance. Small values make thin, sharp feathers. Range 4–80 px. |
| `stylus` | `boolean` | `true` | Let a drag pull the ink. Turn it off to keep touch scrolling on phones. |
| `inkColor1` | `string (hex)` | `"#a855f7"` | The first ink. |
| `inkColor2` | `string (hex)` | `"#3b0764"` | The second ink. |
| `inkColor3` | `string (hex)` | `"#d4a24c"` | The third ink. |
| `paperColor` | `string (hex)` | `"#f3ecdf"` | The paper under the ink. Once the ink covers it all, only the inks show. |

## Usage

```tsx
import Marbling from "@/components/registry/marbling/marbling";

<Marbling
  dropInterval={0.9}
  dropSize={48}
  combStrength={1}
  tineSpacing={80}
  sharpness={22}
  stylus={true}
  inkColor1="#a855f7"
  inkColor2="#3b0764"
  inkColor3="#d4a24c"
  paperColor="#f3ecdf"
/>
```

The import path matches the file path above; change it if you move the component. Every value shown is the documented default — pass only what you actually want to change. The snippet lists the tunable props only: if the component's props type in the source requires others (content, handlers, data), pass those too.

## Integration rules

- Keep the `"use client"` directive. This is a client component and will not render as a Server Component.
- It fills its parent. Give the wrapper an explicit height (or a definite grid area) — against a height-auto parent it collapses to nothing.
- It takes a `reducedMotion` prop and quiesces when true. Wire it to a `prefers-reduced-motion` listener rather than hardcoding `false`.
- It runs a free-running animation loop. Halt it when off-screen or backgrounded if you care about battery.
- The `touch-action: none` on the hit target is load-bearing — without it a finger drag scrolls the page instead of driving the effect. Do not strip it as a stray utility class.
- The peer hook is required, not optional. Copy it to `hooks/use-animation-loop.ts` so the component's `@/hooks/use-animation-loop` import resolves.
- It owns a GPU/canvas context and releases it on unmount. Preserve the cleanup return — leaking contexts kills the tab after a few navigations.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Wire the component into the place I point you at, with sensible props for that context.
4. Flag anything in my setup that conflicts with the stack assumptions above.

Do not restyle the component or alter the animation math unless I ask.
