# Integrate `Rainglass` from Motion Garden

You are helping me add the **Rainglass** 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:** Rainglass
- **Category:** Backgrounds
- **Summary:** Rain on a window with a city somewhere behind it. There is no scene being blurred. The backdrop is built out of focus to begin with, so the drops have something to bend without a render target or a blur pass anywhere in the frame. Each drop is a pure function of time inside its own grid cell, which is why a thousand of them cost the same as one and a resize cannot lose the rain. They descend the way water actually does: holding by surface tension, breaking loose, running fast, stopping again. The trail exists only above the drop that made it.
- **Reference:** https://motion-garden.netlify.app/components/rainglass
- **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
bun add ogl
```

## 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/rainglass/rainglass.tsx`

```tsx
"use client";

import { memo, useEffect, useRef, useState } from "react";
import { Renderer, Program, Mesh, Triangle } from "ogl";
import { useAnimationLoop, type Metrics } from "@/hooks/use-animation-loop";

interface RainglassProps {
  intensity?: number;
  dropScale?: number;
  speed?: number;
  wander?: number;
  refraction?: number;
  fog?: number;
  layers?: number;
  blur?: number;
  tintTop?: string;
  tintBottom?: string;
  glow?: string;
  paused?: boolean;
  reducedMotion?: boolean;
  className?: string;
}

const hexToRgb01 = (hex: string): [number, number, number] => {
  const h = hex.replace("#", "");
  const full = h.length === 3 ? h.split("").map((c) => c + c).join("") : h;
  const n = parseInt(full, 16);
  if (Number.isNaN(n) || full.length !== 6) return [1, 1, 1];
  return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
};

const vertex = `#version 300 es
in vec2 position;
in vec2 uv;
out vec2 vUv;
void main() {
  vUv = uv;
  gl_Position = vec4(position, 0.0, 1.0);
}`;

const fragment = `#version 300 es
precision highp float;
in vec2 vUv;
out vec4 fragColor;

uniform vec2  uRes;
uniform float uTime;
uniform float uIntensity;
uniform float uDropScale;
uniform float uSpeed;
uniform float uWander;
uniform float uRefraction;
uniform float uFog;
uniform float uLayers;
uniform float uBlur;
uniform vec3  uTintTop;
uniform vec3  uTintBottom;
uniform vec3  uGlow;

float hash21(vec2 p) {
  p = fract(p * vec2(127.1, 311.7));
  p += dot(p, p + 34.56);
  return fract(p.x * p.y);
}

// The city, built out of focus rather than blurred into it. Six discs is enough
// to read as depth and few enough to unroll.
vec3 backdrop(vec2 uv) {
  float a = uRes.x / max(uRes.y, 1.0);
  vec3 col = mix(uTintBottom, uTintTop, smoothstep(-0.15, 1.05, uv.y));

  for (int i = 0; i < 6; i++) {
    float fi = float(i);
    vec2 seed = vec2(fi * 3.71 + 1.3, fi * 7.13 + 4.9);
    vec2 c = vec2(hash21(seed), hash21(seed + 19.7));
    c.x = c.x * 1.15 - 0.075;
    c.y = c.y * 0.85 + 0.1;

    float r = (0.10 + hash21(seed + 4.4) * 0.20) * (0.55 + uBlur * 1.25);
    float d = length((uv - c) * vec2(a, 1.0));
    float g = smoothstep(r, 0.0, d);
    // Squared so the falloff is a lens bokeh rather than a linear ramp.
    col += uGlow * g * g * (0.09 + 0.26 * hash21(seed + 31.2));
  }

  // A little vertical smear, the way a long exposure through glass behaves.
  col *= 0.86 + 0.14 * smoothstep(0.0, 0.6, uv.y);
  return col;
}

// One depth plane of rain.
//   xy = refraction offset   z = wet mask (drops)   w = cleared mask (trails)
vec4 rainLayer(vec2 uv, float scale, float seed) {
  float a = uRes.x / max(uRes.y, 1.0);
  vec2 grid = vec2(7.0 * a, 9.0) / max(scale, 0.05);
  vec2 st = uv * grid;
  vec2 id = floor(st);
  st = fract(st) - 0.5;

  float n = hash21(id + seed);
  // Cells are gated, not dimmed. A half-present drop looks like a smudge; a cell
  // either has water in it or it does not.
  float alive = step(1.0 - uIntensity, n);

  float t = uTime * uSpeed * 0.32 + n * 17.0;

  // Horizontal seat in the cell, plus the wander it picks up on the way down.
  float x = (n - 0.5) * 0.62;

  // Stick-slip: three holds per traverse, each released by a smoothstep so the
  // slip is quick and the hold is genuinely still.
  float prog = fract(t);
  float steps = 3.0;
  float stair = (floor(prog * steps) + smoothstep(0.58, 1.0, fract(prog * steps))) / steps;
  float y = 0.62 - stair * 1.28;

  x += sin(stair * 9.0 + n * 6.28) * 0.09 * uWander;

  // The drop itself, aspect-corrected so it is round on any canvas, and slightly
  // taller than wide because a hanging drop is.
  vec2 dp = (st - vec2(x, y)) * vec2(a * grid.y / grid.x, 1.0);
  dp.y *= 0.82;
  float rad = 0.085 + n * 0.055;
  float drop = smoothstep(rad, rad * 0.35, length(dp)) * alive;

  // What it left behind. Quantising y inside the trail band turns one expression
  // into a column of shrinking droplets without a loop.
  float above = smoothstep(-0.02, 0.06, st.y - y);
  vec2 tp = st - vec2(x, 0.0);
  tp.y = (fract(tp.y * 11.0) - 0.5) / 11.0;
  tp *= vec2(a * grid.y / grid.x, 1.0);
  float fade = smoothstep(0.85, 0.05, st.y - y);
  float trail = smoothstep(0.030, 0.008, length(tp)) * above * fade * alive;

  // The swept band. Wider than the droplets so the fog opens ahead of them.
  float cleared = alive * above * fade * smoothstep(0.11, 0.02, abs(st.x - x));

  // Condensation that never ran: fixed, unmoving, and denser than the runners.
  vec2 mp = uv * grid * 3.4;
  vec2 mid = floor(mp);
  vec2 mf = fract(mp) - 0.5;
  float mn = hash21(mid + seed + 61.7);
  float micro = smoothstep(0.30, 0.10, length(mf * vec2(a * grid.y / grid.x, 1.0) * 3.4))
              * step(1.0 - uIntensity * 0.55, mn);

  float wet = clamp(drop + trail * 0.85 + micro * 0.5, 0.0, 1.0);

  // The lens. Offset points out of each droplet's centre, which is what makes it
  // magnify rather than merely smear.
  vec2 off = dp * drop * 0.85 + tp * trail * 1.4 + mf * micro * 0.20;

  return vec4(off, wet, clamp(cleared + drop, 0.0, 1.0));
}

void main() {
  vec2 uv = vUv;

  vec2 off = vec2(0.0);
  float wet = 0.0;
  float cleared = 0.0;

  // Bounded at three and broken early. A loop the compiler can unroll keeps this
  // inside the budget of a software rasteriser, which is what the verifier runs.
  for (int i = 0; i < 3; i++) {
    if (float(i) >= uLayers) break;
    float fi = float(i);
    vec4 l = rainLayer(uv, uDropScale * (1.0 - fi * 0.28), fi * 23.4);
    // Nearer planes refract harder and read wetter; far ones are just texture.
    float w = 1.0 - fi * 0.3;
    off += l.xy * w;
    wet = max(wet, l.z * w);
    cleared = max(cleared, l.w);
  }

  vec3 col = backdrop(uv + off * uRefraction * 0.55);

  // Fog is *removed* by what the water touched, rather than drawn between the
  // drops — so a trail is a clean stripe through the film instead of a shape
  // sitting on top of it.
  float film = uFog * (1.0 - cleared);
  vec3 hazy = mix(col, vec3(dot(col, vec3(0.299, 0.587, 0.114))), 0.55);
  hazy = mix(hazy, hazy + vec3(0.035, 0.030, 0.055), 0.6);
  col = mix(col, hazy, film);

  // Grain, only in the fog. Clean glass should be clean.
  col += (hash21(uv * uRes + uTime) - 0.5) * 0.028 * film;

  // A wet edge catches the light behind it. Cheap, and it is what sells glass.
  col += uGlow * pow(wet, 3.0) * 0.22;

  fragColor = vec4(col, 1.0);
}`;

const Rainglass = memo(
  ({
    intensity = 0.55,
    dropScale = 1,
    speed = 1,
    wander = 0.5,
    refraction = 0.6,
    fog = 0.5,
    layers = 2,
    blur = 0.65,
    tintTop = "#241436",
    tintBottom = "#0b0b12",
    glow = "#a855f7",
    paused = false,
    reducedMotion = false,
    className,
  }: RainglassProps) => {
    const containerRef = useRef<HTMLDivElement>(null);
    const drawRef = useRef<((dt: number) => void | false) | null>(null);
    const measureRef = useRef<((m: Metrics) => void) | null>(null);
    const glRef = useRef<WebGLRenderingContext | WebGL2RenderingContext | null>(null);

    const [fallback, setFallback] = useState(false);

    const loop = useAnimationLoop({
      target: containerRef,
      halted: paused || reducedMotion,
      dpr: "auto",
      onResize: (metrics) => measureRef.current?.(metrics),
      onFrame: ({ dt }) => (drawRef.current ? drawRef.current(dt) : false),
      gl: () => glRef.current,
    });

    const live = useRef({
      intensity, dropScale, speed, wander, refraction, fog, layers, blur,
      tintTop, tintBottom, glow, reducedMotion,
    });
    live.current = {
      intensity, dropScale, speed, wander, refraction, fog, layers, blur,
      tintTop, tintBottom, glow, reducedMotion,
    };

    useEffect(() => {
      const container = containerRef.current;
      if (fallback || !container) return;

      let renderer: Renderer;
      try {
        renderer = new Renderer({
          webgl: 2,
          alpha: false,
          antialias: false,
          dpr: Math.min(window.devicePixelRatio || 1, 2),
        });
        if (!(renderer.gl instanceof WebGL2RenderingContext)) {
          throw new Error("Rainglass requires WebGL2");
        }
      } catch {
        setFallback(true);
        return;
      }

      const glc = renderer.gl;
      glRef.current = glc;

      const canvas = glc.canvas as HTMLCanvasElement;
      canvas.style.display = "block";
      canvas.style.position = "absolute";
      canvas.style.inset = "0";
      canvas.style.width = "100%";
      canvas.style.height = "100%";
      container.appendChild(canvas);

      const program = new Program(glc, {
        vertex,
        fragment,
        depthTest: false,
        depthWrite: false,
        uniforms: {
          uRes: { value: new Float32Array([1, 1]) },
          uTime: { value: 0 },
          uIntensity: { value: intensity },
          uDropScale: { value: dropScale },
          uSpeed: { value: speed },
          uWander: { value: wander },
          uRefraction: { value: refraction },
          uFog: { value: fog },
          uLayers: { value: layers },
          uBlur: { value: blur },
          uTintTop: { value: new Float32Array(hexToRgb01(tintTop)) },
          uTintBottom: { value: new Float32Array(hexToRgb01(tintBottom)) },
          uGlow: { value: new Float32Array(hexToRgb01(glow)) },
        },
      });

      const mesh = new Mesh(glc, { geometry: new Triangle(glc), program });
      const u = program.uniforms as Record<string, { value: number | Float32Array }>;

      let elapsed = 40;

      drawRef.current = (dt) => {
        const l = live.current;
        elapsed = (elapsed + (l.reducedMotion ? 0 : dt)) % 3600;

        u.uTime.value = elapsed;
        u.uIntensity.value = l.intensity;
        u.uDropScale.value = l.dropScale;
        u.uSpeed.value = l.speed;
        u.uWander.value = l.wander;
        u.uRefraction.value = l.refraction;
        u.uFog.value = l.fog;
        u.uLayers.value = Math.round(l.layers);
        u.uBlur.value = l.blur;
        (u.uTintTop.value as Float32Array).set(hexToRgb01(l.tintTop));
        (u.uTintBottom.value as Float32Array).set(hexToRgb01(l.tintBottom));
        (u.uGlow.value as Float32Array).set(hexToRgb01(l.glow));

        renderer.render({ scene: mesh });
      };

      measureRef.current = ({ width, height, dpr }) => {
        renderer.dpr = dpr;
        renderer.setSize(Math.max(1, Math.floor(width)), Math.max(1, Math.floor(height)));
        (u.uRes.value as Float32Array).set([
          Math.max(1, Math.floor(width)),
          Math.max(1, Math.floor(height)),
        ]);
      };

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

      return () => {
        drawRef.current = null;
        measureRef.current = null;
        if (container.contains(canvas)) container.removeChild(canvas);
      };
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [fallback]);

    return (
      <div
        ref={containerRef}
        className={`relative h-full w-full overflow-hidden ${className ?? ""}`}
        style={
          fallback
            ? { background: `linear-gradient(to bottom, ${tintTop}, ${tintBottom})` }
            : undefined
        }
      />
    );
  },
);

Rainglass.displayName = "Rainglass";

export default Rainglass;
```

### 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 |
| --- | --- | --- | --- |
| `intensity` | `number` | `0.55` | How much water is on the glass. Cells are gated by this rather than dimmed by it — a cell either has a drop in it or it does not, because a half-present drop reads as a smudge on the screen rather than as weather. Range 0–1. |
| `dropScale` | `number` | `1` | Drop size, by way of the grid the drops live in. Large drops means fewer, heavier runs and a window you are standing close to; small means a fine spatter that reads as distance. Range 0.5–2. |
| `speed` | `number` | `1` | How often a drop breaks loose, and how fast it runs once it has. Because the descent is a held stair rather than a fall, raising this shortens the holds as much as it quickens the slips. Range 0.2–3. |
| `wander` | `number` | `0.5` | How far a running drop drifts sideways as it goes. At zero they run dead straight down, which is the one thing real water on glass never does. Range 0–1. |
| `refraction` | `number` | `0.6` | How hard each droplet bends the city behind it. The offset points out of the droplet's own centre, so this magnifies rather than smears — turn it off and the drops flatten into stickers on the glass. Range 0–1. |
| `fog` | `number` | `0.5` | Condensation film over the whole pane. It is removed by what the water has touched rather than drawn between the drops, so a trail is a clean stripe cut through the fog instead of a shape sitting on top of it. Range 0–1. |
| `layers` | `number` | `2` | Depth planes of rain, each smaller and refracting less than the one in front. Two is enough to read as depth; the third is texture and costs a full extra evaluation of the drop field per pixel. Range 1–3. |
| `blur` | `number` | `0.65` | How far out of focus the city is. This grows the bokeh discs rather than running a kernel over a rendered scene — there is nothing sharp behind the glass to soften, which is the whole reason this stays a single pass. Range 0–1. |
| `tintTop` | `string (hex)` | `"#241436"` | Sky, at the top of the frame. |
| `tintBottom` | `string (hex)` | `"#0b0b12"` | Ground, at the bottom. |
| `glow` | `string (hex)` | `"#a855f7"` | The out-of-focus lights, and the highlight that catches on a wet edge. |

## Usage

```tsx
import Rainglass from "@/components/registry/rainglass/rainglass";

<Rainglass
  intensity={0.55}
  dropScale={1}
  speed={1}
  wander={0.5}
  refraction={0.6}
  fog={0.5}
  layers={2}
  blur={0.65}
  tintTop="#241436"
  tintBottom="#0b0b12"
  glow="#a855f7"
/>
```

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 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.
