# Integrate `SakuraTree` from Motion Garden

You are helping me add the **SakuraTree** 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:** SakuraTree
- **Category:** Backgrounds
- **Summary:** A painterly toon-shaded 3D cherry-blossom scene with wind-driven falling petals.
- **Reference:** https://motion-garden.netlify.app/components/sakura-tree
- **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 three @react-three/fiber clsx tailwind-merge
```

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

```tsx
"use client";

import { Canvas, useFrame, useLoader, useThree } from "@react-three/fiber";
import { Suspense, useEffect, useMemo, useRef, useState } from "react";
import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { cn } from "@/lib/utils";

export type SakuraWeather = "clear" | "breezy" | "overcast" | "storm";

export interface SakuraTreeProps {
  windSpeed?: number;
  fallingPetals?: number;
  bloomAmount?: number;
  weather?: SakuraWeather;
  windDirection?: number;
  cameraDistance?: number;
  paused?: boolean;
  className?: string;
}

const PETAL_POOL = 300;
const TREE_X = 1.7;
const TREE_Y = -0.24;
const TREE_SCALE = 2.1;
const TREE_URL = "/models/sakura_tree-slim.glb";
const FIELD_URL = "/models/green_field.glb";

const FIELD_TILE_X = 15.2;
const FIELD_TILE_Z = 15.0;
const FIELD_RECENTER: [number, number, number] = [2.45, 0, 1.7];
const FIELD_CENTER_X = 0.58;
const FIELD_CENTER_Z = -0.56;

const WEATHER: Record<
  SakuraWeather,
  { windMul: number; sky: string; ground: string; fogNear: number; fogFar: number; ambient: number; sun: number }
> = {
  clear: { windMul: 1, sky: "#ecdfdf", ground: "#b6c0a8", fogNear: 10, fogFar: 30, ambient: 1.0, sun: 0.9 },
  breezy: { windMul: 1.8, sky: "#e7dde2", ground: "#b1bba5", fogNear: 10, fogFar: 28, ambient: 0.95, sun: 0.85 },
  overcast: { windMul: 1.3, sky: "#ced2d6", ground: "#a6b09d", fogNear: 8, fogFar: 24, ambient: 0.75, sun: 0.55 },
  storm: { windMul: 3, sky: "#a9afb9", ground: "#97a193", fogNear: 6, fogFar: 18, ambient: 0.55, sun: 0.4 },
};

const PETAL_COLORS = ["#ffffff", "#ffe4ef", "#f2cfdd", "#ffd3e2"];

const WHITE = new THREE.Color("#ffffff");
const DISC_SHADOW = new THREE.Color("#3f4a3a");

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

function makeRamp(stops: number[]): THREE.DataTexture {
  const data = new Uint8Array(stops);
  const tex = new THREE.DataTexture(data, stops.length, 1, THREE.RedFormat);
  tex.minFilter = THREE.NearestFilter;
  tex.magFilter = THREE.NearestFilter;
  tex.needsUpdate = true;
  return tex;
}

function makeSoftAlpha(squash: number, feather = 0.55): THREE.CanvasTexture {
  const size = 64;
  const canvas = document.createElement("canvas");
  canvas.width = size;
  canvas.height = size;
  const ctx = canvas.getContext("2d")!;
  ctx.translate(size / 2, size / 2);
  ctx.scale(1, squash);
  const grad = ctx.createRadialGradient(0, 0, 0, 0, 0, size / 2);
  grad.addColorStop(0, "rgba(255,255,255,1)");
  grad.addColorStop(feather, "rgba(255,255,255,0.85)");
  grad.addColorStop(1, "rgba(255,255,255,0)");
  ctx.fillStyle = grad;
  ctx.fillRect(-size / 2, -size / (2 * squash), size, size / squash);
  const tex = new THREE.CanvasTexture(canvas);
  tex.needsUpdate = true;
  return tex;
}

interface PetalState {
  x: Float32Array;
  y: Float32Array;
  z: Float32Array;
  phase: Float32Array;
  speed: Float32Array;
  scale: Float32Array;
}

function createPetalState(rng: () => number): PetalState {
  const n = PETAL_POOL;
  const state: PetalState = {
    x: new Float32Array(n), y: new Float32Array(n), z: new Float32Array(n),
    phase: new Float32Array(n), speed: new Float32Array(n), scale: new Float32Array(n),
  };
  for (let i = 0; i < n; i++) {
    state.x[i] = -5.5 + rng() * 10;
    state.z[i] = -1.2 + rng() * 2.6;
    state.y[i] = 0.15 + rng() * 4.4;
    state.phase[i] = rng() * Math.PI * 2;
    state.speed[i] = 0.5 + rng();
    state.scale[i] = 0.8 + rng() * 0.8;
  }
  return state;
}

function makeTintedTexture(
  src: THREE.Texture,
  ops: { sat?: string; screen?: string },
): THREE.CanvasTexture {
  const img = src.image as HTMLImageElement | ImageBitmap;
  const canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  const ctx = canvas.getContext("2d")!;
  ctx.drawImage(img, 0, 0);
  if (ops.sat) {
    ctx.globalCompositeOperation = "saturation";
    ctx.fillStyle = ops.sat;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
  }
  if (ops.screen) {
    ctx.globalCompositeOperation = "screen";
    ctx.fillStyle = ops.screen;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
  }
  ctx.globalCompositeOperation = "destination-in";
  ctx.drawImage(img, 0, 0);
  const tex = new THREE.CanvasTexture(canvas);
  tex.flipY = src.flipY;
  tex.wrapS = src.wrapS;
  tex.wrapT = src.wrapT;
  tex.repeat.copy(src.repeat);
  tex.offset.copy(src.offset);
  tex.rotation = src.rotation;
  tex.center.copy(src.center);
  tex.colorSpace = THREE.SRGBColorSpace;
  tex.needsUpdate = true;
  return tex;
}

function BlossomTree({
  wind,
  windVec,
  bloomAmount,
  petalCount,
  paused,
  barkRamp,
  petalGeo,
  petalMat,
}: {
  wind: number;
  windVec: { x: number; z: number };
  bloomAmount: number;
  petalCount: number;
  paused: boolean;
  barkRamp: THREE.DataTexture;
  petalGeo: THREE.BufferGeometry;
  petalMat: THREE.Material;
}) {
  const gltf = useLoader(GLTFLoader, TREE_URL);
  const swayRef = useRef<THREE.Group>(null);
  const petalsRef = useRef<THREE.InstancedMesh>(null);
  const petalState = useRef<PetalState | null>(null);
  const petalFade = useRef(bloomAmount > 0 ? 1 : 0);
  const dummy = useMemo(() => new THREE.Object3D(), []);

  const model = useMemo(() => {
    const scene = gltf.scene.clone(true);
    const created: (THREE.Material | THREE.Texture)[] = [];
    const bushes: THREE.Object3D[] = [];
    const dusty = new Map<THREE.Texture, THREE.CanvasTexture>();
    const rng = mulberry32(31);
    const toneDark = new THREE.Color("#e2b7c9");
    const toneLight = new THREE.Color("#ffffff");
    scene.traverse((obj) => {
      if (obj.name.startsWith("bush")) bushes.push(obj);
      if (obj instanceof THREE.Mesh) {
        const old = obj.material as THREE.MeshStandardMaterial;
        if (old.name === "Material") {
          let tex: THREE.CanvasTexture | undefined;
          if (old.map) {
            tex = dusty.get(old.map);
            if (!tex) {
              tex = makeTintedTexture(old.map, { screen: "rgba(146, 92, 66, 0.4)" });
              dusty.set(old.map, tex);
              created.push(tex);
            }
          }
          const mat = new THREE.MeshToonMaterial({ map: tex ?? old.map, gradientMap: barkRamp });
          created.push(mat);
          obj.material = mat;
        } else if (old.map) {
          let tex = dusty.get(old.map);
          if (!tex) {
            tex = makeTintedTexture(old.map, { sat: "hsl(330, 32%, 60%)", screen: "rgba(255, 228, 238, 0.4)" });
            dusty.set(old.map, tex);
            created.push(tex);
          }
          const mat = new THREE.MeshBasicMaterial({
            map: tex,
            alphaTest: 0.27,
            side: THREE.DoubleSide,
            color: toneDark.clone().lerp(toneLight, rng()),
          });
          created.push(mat);
          obj.material = mat;
        }
      }
    });
    scene.updateMatrixWorld(true);
    const clones: THREE.Object3D[] = [];
    const yaw = new THREE.Matrix4();
    for (const b of bushes) {
      for (let k = 0; k < 2; k++) {
        const c = b.clone(true);
        c.applyMatrix4(b.parent!.matrixWorld);
        c.applyMatrix4(yaw.makeRotationY((rng() - 0.5) * 0.3));
        c.position.x += (rng() - 0.5) * 0.22;
        c.position.y += (rng() - 0.5) * 0.14 + 0.03;
        c.position.z += (rng() - 0.5) * 0.22;
        scene.add(c);
        clones.push(c);
      }
    }
    scene.updateMatrixWorld(true);
    for (let i = bushes.length - 1; i > 0; i--) {
      const j = Math.floor(rng() * (i + 1));
      [bushes[i], bushes[j]] = [bushes[j], bushes[i]];
    }
    for (let i = clones.length - 1; i > 0; i--) {
      const j = Math.floor(rng() * (i + 1));
      [clones[i], clones[j]] = [clones[j], clones[i]];
    }
    bushes.push(...clones);
    const box = new THREE.Box3();
    const center = new THREE.Vector3();
    const anchors = bushes.map((b) => {
      box.setFromObject(b).getCenter(center);
      return new THREE.Vector3(
        center.x * TREE_SCALE + TREE_X,
        center.y * TREE_SCALE + TREE_Y,
        center.z * TREE_SCALE,
      );
    });
    return { scene, bushes, anchors, dispose: () => created.forEach((m) => m.dispose()) };
  }, [gltf, barkRamp]);
  useEffect(() => () => model.dispose(), [model]);

  useEffect(() => {
    const visible = Math.round(model.bushes.length * bloomAmount);
    model.bushes.forEach((b, i) => {
      b.visible = i < visible;
    });
  }, [model, bloomAmount]);

  useEffect(() => {
    const mesh = petalsRef.current;
    if (!mesh) return;
    const color = new THREE.Color();
    for (let i = 0; i < PETAL_POOL; i++) {
      mesh.setColorAt(i, color.set(PETAL_COLORS[i % PETAL_COLORS.length]));
    }
    if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
    (mesh.material as THREE.Material).needsUpdate = true;
  }, []);

  useFrame((state, delta) => {
    const t = state.clock.elapsedTime;
    const dt = Math.min(delta, 0.05);
    const sway = paused ? 0 : 1;

    if (swayRef.current) {
      swayRef.current.rotation.z = Math.sin(t * 0.9) * 0.006 * (1 + wind * 0.3) * sway;
      swayRef.current.rotation.x = Math.sin(t * 0.7 + 1.3) * 0.004 * (1 + wind * 0.3) * sway;
    }

    const mesh = petalsRef.current;
    if (!mesh) return;
    if (!petalState.current) petalState.current = createPetalState(mulberry32(9001));
    const petals = petalState.current;
    const fadeTarget = bloomAmount > 0 ? 1 : 0;
    if (paused) {
      petalFade.current = fadeTarget;
    } else {
      petalFade.current += (fadeTarget - petalFade.current) * Math.min(1, dt * 2.2);
      if (Math.abs(fadeTarget - petalFade.current) < 0.01) petalFade.current = fadeTarget;
      else state.invalidate();
    }
    (mesh.material as THREE.MeshBasicMaterial).opacity = petalFade.current;
    const liveCount = petalFade.current === 0 ? 0 : petalCount;
    mesh.count = liveCount;
    const anchors = model.anchors;
    for (let i = 0; i < liveCount; i++) {
      if (!paused) {
        petals.y[i] -= (0.35 + petals.speed[i] * 0.35) * (0.4 + wind * 0.1) * dt;
        petals.x[i] += windVec.x * wind * 0.18 * (0.5 + petals.speed[i] * 0.4) * dt;
        petals.z[i] += windVec.z * wind * 0.11 * (0.5 + petals.speed[i] * 0.4) * dt;
        if (petals.y[i] < 0.02 || Math.abs(petals.x[i]) > 11) {
          if (anchors.length && Math.random() < 0.65) {
            const a = anchors[(Math.random() * anchors.length) | 0];
            petals.x[i] = a.x + (Math.random() - 0.5) * 1.6;
            petals.z[i] = a.z + (Math.random() - 0.5) * 1.4;
            petals.y[i] = Math.max(1.8, a.y) + Math.random() * 1.2;
          } else {
            petals.x[i] = -5.5 + Math.random() * 10 - windVec.x * Math.random() * 3;
            petals.z[i] = -1.2 + Math.random() * 2.6;
            petals.y[i] = 2.5 + Math.random() * 2.5;
          }
        }
      }
      const swayX = Math.sin(t * 1.7 + petals.phase[i]) * (0.1 + wind * 0.035) * sway;
      dummy.position.set(petals.x[i] + swayX, petals.y[i], petals.z[i]);
      dummy.rotation.set(
        t * petals.speed[i] * 2.1 * sway + petals.phase[i],
        t * petals.speed[i] * 1.5 * sway + petals.phase[i] * 2,
        petals.phase[i] * 3,
      );
      const s = petals.scale[i];
      dummy.scale.set(s, s, s);
      dummy.updateMatrix();
      mesh.setMatrixAt(i, dummy.matrix);
    }
    mesh.instanceMatrix.needsUpdate = true;
  });

  return (
    <>
      <group ref={swayRef} position={[TREE_X, TREE_Y, 0]} scale={TREE_SCALE}>
        <primitive object={model.scene} />
      </group>
      <instancedMesh
        ref={petalsRef}
        args={[petalGeo, petalMat, PETAL_POOL]}
        frustumCulled={false}
        renderOrder={3}
      />
    </>
  );
}

function GreenField({
  tint,
  grassMats,
}: {
  tint: string;
  grassMats: { current: THREE.MeshBasicMaterial[] };
}) {
  const gltf = useLoader(GLTFLoader, FIELD_URL);
  const model = useMemo(() => {
    const base = gltf.scene.clone(true);
    const created: (THREE.Material | THREE.Texture)[] = [];
    const mats: THREE.MeshBasicMaterial[] = [];
    base.traverse((obj) => {
      if (obj instanceof THREE.Mesh) {
        const old = obj.material as THREE.MeshStandardMaterial;
        const tex = old.map ? makeTintedTexture(old.map, { sat: "hsl(100, 14%, 55%)" }) : null;
        if (tex) created.push(tex);
        const mat = new THREE.MeshBasicMaterial({ map: tex, alphaTest: 0.6, side: THREE.DoubleSide });
        created.push(mat);
        mats.push(mat);
        obj.material = mat;
      }
    });
    const tiles: { obj: THREE.Object3D; ix: number; iz: number }[] = [];
    for (let ix = -1; ix <= 1; ix++) {
      for (let iz = -1; iz <= 1; iz++) {
        tiles.push({ obj: ix === 0 && iz === 0 ? base : base.clone(true), ix, iz });
      }
    }
    return { tiles, mats, dispose: () => created.forEach((r) => r.dispose()) };
  }, [gltf]);
  useEffect(() => () => model.dispose(), [model]);

  useEffect(() => {
    const c = new THREE.Color(tint).lerp(WHITE, 0.3);
    model.mats.forEach((m) => m.color.copy(c));
    grassMats.current = model.mats;
    return () => {
      grassMats.current = [];
    };
  }, [model, tint, grassMats]);

  return (
    <>
      {model.tiles.map(({ obj, ix, iz }) => (
        <group
          key={`${ix},${iz}`}
          position={[
            FIELD_CENTER_X + ix * FIELD_TILE_X,
            -0.18 - 0.002 * (ix + 1) - 0.005 * (iz + 1),
            FIELD_CENTER_Z + iz * FIELD_TILE_Z,
          ]}
          rotation={[0, ((ix + iz) & 1) ? Math.PI : 0, 0]}
          scale={[(ix & 1) ? -1.6 : 1.6, 0.45, 1.6]}
        >
          <group position={FIELD_RECENTER}>
            <primitive object={obj} />
          </group>
        </group>
      ))}
    </>
  );
}

function WeatherRig({
  weather,
  paused,
  hemi,
  sun,
  discMat,
  grassMats,
}: {
  weather: SakuraWeather;
  paused: boolean;
  hemi: { current: THREE.HemisphereLight | null };
  sun: { current: THREE.DirectionalLight | null };
  discMat: { current: THREE.MeshBasicMaterial | null };
  grassMats: { current: THREE.MeshBasicMaterial[] };
}) {
  const scene = useThree((s) => s.scene);
  const invalidate = useThree((s) => s.invalidate);
  const live = useRef<{
    sky: THREE.Color;
    ground: THREE.Color;
    near: number;
    far: number;
    ambient: number;
    sun: number;
    tmp: THREE.Color;
    target: THREE.Color;
  } | null>(null);

  useEffect(() => invalidate(), [weather, invalidate]);

  useFrame((_, delta) => {
    const w = WEATHER[weather];
    let l = live.current;
    if (!l) {
      l = live.current = {
        sky: new THREE.Color(w.sky),
        ground: new THREE.Color(w.ground),
        near: w.fogNear,
        far: w.fogFar,
        ambient: w.ambient,
        sun: w.sun,
        tmp: new THREE.Color(),
        target: new THREE.Color(),
      };
    }
    const k = paused ? 1 : Math.min(1, delta * 2.4);
    l.target.set(w.sky);
    const drift =
      Math.abs(l.target.r - l.sky.r) +
      Math.abs(l.target.g - l.sky.g) +
      Math.abs(l.target.b - l.sky.b) +
      Math.abs(w.fogNear - l.near) / 20 +
      Math.abs(w.fogFar - l.far) / 20;
    l.sky.lerp(l.target, k);
    l.ground.lerp(l.target.set(w.ground), k);
    l.near += (w.fogNear - l.near) * k;
    l.far += (w.fogFar - l.far) * k;
    l.ambient += (w.ambient - l.ambient) * k;
    l.sun += (w.sun - l.sun) * k;

    scene.background = l.sky;
    const fog = scene.fog as THREE.Fog | null;
    if (fog) {
      fog.color.copy(l.sky);
      fog.near = l.near;
      fog.far = l.far;
    }
    if (hemi.current) hemi.current.intensity = l.ambient * 1.15;
    if (sun.current) sun.current.intensity = l.sun * 0.7;
    if (discMat.current) discMat.current.color.copy(l.ground).lerp(DISC_SHADOW, 0.35);
    const grass = l.tmp.copy(l.ground).lerp(WHITE, 0.3);
    for (const m of grassMats.current) m.color.copy(grass);

    if (drift > 0.004) invalidate();
  });

  return null;
}

const PIVOT = { x: 0.55, y: 2.15 };
const ORBIT_BASE = Math.atan2(-0.2 - PIVOT.x, 6.9);

function CameraRig({ paused, distance }: { paused: boolean; distance: number }) {
  const gl = useThree((s) => s.gl);
  const invalidate = useThree((s) => s.invalidate);
  const azimuth = useRef({ current: 0, target: 0 });
  const radius = useRef(distance);

  useEffect(() => invalidate(), [distance, invalidate]);

  useEffect(() => {
    const el = gl.domElement;
    let dragging = false;
    let lastX = 0;
    const down = (e: PointerEvent) => {
      dragging = true;
      lastX = e.clientX;
      el.setPointerCapture(e.pointerId);
    };
    const move = (e: PointerEvent) => {
      if (!dragging) return;
      azimuth.current.target -= (e.clientX - lastX) * 0.006;
      lastX = e.clientX;
      invalidate();
    };
    const up = (e: PointerEvent) => {
      dragging = false;
      if (el.hasPointerCapture(e.pointerId)) el.releasePointerCapture(e.pointerId);
    };
    el.addEventListener("pointerdown", down);
    el.addEventListener("pointermove", move);
    el.addEventListener("pointerup", up);
    el.addEventListener("pointercancel", up);
    return () => {
      el.removeEventListener("pointerdown", down);
      el.removeEventListener("pointermove", move);
      el.removeEventListener("pointerup", up);
      el.removeEventListener("pointercancel", up);
    };
  }, [gl, invalidate]);

  useFrame((state, delta) => {
    const az = azimuth.current;
    const ease = Math.min(1, delta * 8);
    az.current += (az.target - az.current) * ease;
    radius.current += (distance - radius.current) * ease;
    if (Math.abs(az.target - az.current) > 0.0005 || Math.abs(distance - radius.current) > 0.005) {
      invalidate();
    }
    const a = ORBIT_BASE + az.current;
    const y = 1.9 + (paused ? 0 : state.pointer.y * 0.09);
    state.camera.position.set(PIVOT.x + radius.current * Math.sin(a), y, radius.current * Math.cos(a));
    state.camera.lookAt(PIVOT.x, PIVOT.y, 0);
  });

  return null;
}

function SakuraScene({
  windSpeed = 3,
  fallingPetals = 129,
  bloomAmount = 0.85,
  weather = "clear",
  windDirection = 45,
  cameraDistance = 8,
  paused = false,
}: Omit<SakuraTreeProps, "className">) {
  const wx = WEATHER[weather];
  const wind = windSpeed * wx.windMul;

  const resources = useMemo(() => {
    const barkRamp = makeRamp([130, 185, 235]);
    const stoneRamp = makeRamp([80, 150, 220]);
    const discAlpha = makeSoftAlpha(1, 0.4);
    const petalAlpha = makeSoftAlpha(0.55);

    const petalGeo = new THREE.PlaneGeometry(0.1, 0.066);
    const petalMat = new THREE.MeshBasicMaterial({
      color: "#d795b2",
      alphaMap: petalAlpha,
      transparent: true,
      depthWrite: false,
      side: THREE.DoubleSide,
    });
    const stoneMat = new THREE.MeshToonMaterial({ color: "#5a5a60", gradientMap: stoneRamp });
    const glowMat = new THREE.MeshBasicMaterial({ color: "#ffd39b" });
    const groundPetalMat = new THREE.MeshBasicMaterial({
      color: "#e5b7ca",
      alphaMap: discAlpha,
      transparent: true,
      opacity: 0.15,
      depthWrite: false,
    });
    const shadowMat = new THREE.MeshBasicMaterial({
      color: "#3f4a3a",
      alphaMap: discAlpha,
      transparent: true,
      opacity: 0.42,
      depthWrite: false,
    });

    return {
      barkRamp, petalGeo, petalMat, stoneMat, glowMat, groundPetalMat, shadowMat,
      dispose() {
        petalGeo.dispose();
        [petalMat, stoneMat, glowMat, groundPetalMat, shadowMat].forEach((m) => m.dispose());
        [barkRamp, stoneRamp, discAlpha, petalAlpha].forEach((t) => t.dispose());
      },
    };
  }, []);
  useEffect(() => () => resources.dispose(), [resources]);

  const windVec = useMemo(() => {
    const rad = (windDirection * Math.PI) / 180;
    return { x: -Math.cos(rad), z: Math.sin(rad) };
  }, [windDirection]);

  const groundColor = useMemo(
    () => new THREE.Color(wx.ground).lerp(new THREE.Color("#3f4a3a"), 0.35),
    [wx.ground],
  );

  const petalCount = Math.max(0, Math.min(PETAL_POOL, Math.round(fallingPetals)));

  const hemiRef = useRef<THREE.HemisphereLight>(null);
  const sunRef = useRef<THREE.DirectionalLight>(null);
  const discMatRef = useRef<THREE.MeshBasicMaterial>(null);
  const grassMatsRef = useRef<THREE.MeshBasicMaterial[]>([]);

  return (
    <>
      <CameraRig paused={paused} distance={cameraDistance} />
      <WeatherRig
        weather={weather}
        paused={paused}
        hemi={hemiRef}
        sun={sunRef}
        discMat={discMatRef}
        grassMats={grassMatsRef}
      />
      <color attach="background" args={[wx.sky]} />
      <fog attach="fog" args={[wx.sky, wx.fogNear, wx.fogFar]} />
      <hemisphereLight ref={hemiRef} args={["#fbf3f0", "#c0b2ae", wx.ambient * 1.15]} />
      <directionalLight
        ref={sunRef}
        position={[-2, 8, 6]}
        intensity={wx.sun * 0.7}
        color="#fff4ec"
      />

      <Suspense fallback={null}>
        <mesh rotation={[-Math.PI / 2, 0, 0]}>
          <circleGeometry args={[60, 48]} />
          <meshBasicMaterial ref={discMatRef} color={groundColor} />
        </mesh>

        <GreenField tint={wx.ground} grassMats={grassMatsRef} />
        <BlossomTree
          wind={wind}
          windVec={windVec}
          bloomAmount={bloomAmount}
          petalCount={petalCount}
          paused={paused}
          barkRamp={resources.barkRamp}
          petalGeo={resources.petalGeo}
          petalMat={resources.petalMat}
        />

      <mesh
        rotation={[-Math.PI / 2, 0, 0]}
        position={[TREE_X - 0.25, 0.065, 0.2]}
        material={resources.shadowMat}
      >
        <circleGeometry args={[2.3, 24]} />
      </mesh>
      <mesh
        rotation={[-Math.PI / 2, 0, 0]}
        position={[TREE_X, 0.07, 0.15]}
        scale={[1.25, 1, 1]}
        material={resources.shadowMat}
      >
        <circleGeometry args={[0.85, 20]} />
      </mesh>
      <mesh
        rotation={[-Math.PI / 2, 0, 0]}
        position={[-1.15, 0.07, 0.5]}
        material={resources.shadowMat}
      >
        <circleGeometry args={[0.5, 16]} />
      </mesh>
      <mesh
        rotation={[-Math.PI / 2, 0, 0]}
        position={[TREE_X - 1, 0.075, 0.7]}
        material={resources.groundPetalMat}
      >
        <circleGeometry args={[1.5, 20]} />
      </mesh>
      <mesh
        rotation={[-Math.PI / 2, 0, 0]}
        position={[0.2, 0.075, -0.4]}
        material={resources.groundPetalMat}
      >
        <circleGeometry args={[1, 20]} />
      </mesh>

      <group position={[-1.15, 0, 0.5]}>
        <mesh position={[0, 0.07, 0]} material={resources.stoneMat}>
          <boxGeometry args={[0.4, 0.14, 0.4]} />
        </mesh>
        <mesh position={[0, 0.45, 0]} material={resources.stoneMat}>
          <boxGeometry args={[0.11, 0.62, 0.11]} />
        </mesh>
        <mesh position={[0, 0.8, 0]} material={resources.stoneMat}>
          <boxGeometry args={[0.26, 0.07, 0.26]} />
        </mesh>
        <mesh
          position={[0, 0.93, 0]}
          material={[
            resources.glowMat, resources.glowMat,
            resources.stoneMat, resources.stoneMat,
            resources.glowMat, resources.glowMat,
          ]}
        >
          <boxGeometry args={[0.19, 0.2, 0.19]} />
        </mesh>
        <mesh position={[0, 1.12, 0]} rotation={[0, Math.PI / 4, 0]} material={resources.stoneMat}>
          <coneGeometry args={[0.3, 0.2, 4]} />
        </mesh>
        <mesh position={[0, 1.25, 0]} material={resources.stoneMat}>
          <sphereGeometry args={[0.04, 8, 8]} />
        </mesh>
        <pointLight position={[0, 0.95, 0]} color="#ffb066" intensity={0.7} distance={2.2} decay={2} />
      </group>
      </Suspense>
    </>
  );
}

export default function SakuraTree({ className, weather = "clear", paused = false, ...props }: SakuraTreeProps) {
  const [canvasEpoch, setCanvasEpoch] = useState(0);
  useEffect(() => () => setCanvasEpoch((e) => e + 1), []);

  return (
    <div
      className={cn(
        "relative h-full w-full select-none transition-[background-color] duration-700 [&_canvas]:cursor-grab [&_canvas]:touch-none [&_canvas:active]:cursor-grabbing",
        className,
      )}
      style={{ backgroundColor: WEATHER[weather].sky }}
    >
      <Canvas
        key={canvasEpoch}
        flat
        dpr={[1, 1.75]}
        frameloop={paused ? "demand" : "always"}
        camera={{ position: [-0.2, 1.9, 6.9], fov: 45 }}
      >
        <SakuraScene weather={weather} paused={paused} {...props} />
      </Canvas>
    </div>
  );
}
```

### 2. `lib/utils.ts` — peer util, required

```tsx
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `windSpeed` | `number` | `3` | Branch sway and petal drift speed. Range 0–10. |
| `fallingPetals` | `number` | `129` | Number of petals drifting through the air. Fades out and disables when bloom is zero. Range 0–300. Ignored while `bloomAmount` is `0`. |
| `bloomAmount` | `number` | `0.85` | Canopy fullness, bare branches to full blossom. Range 0–1. |
| `weather` | `"clear" | "breezy" | "overcast" | "storm"` | `"clear"` | Bundles ambient light, fog density and a wind multiplier. |
| `windDirection` | `number` | `45` | Compass direction the petals drift toward. Range 0–360 °. |
| `cameraDistance` | `number` | `8` | Orbit radius — how far the camera sits from the tree. Range 4–12. |

## Usage

```tsx
import SakuraTree from "@/components/registry/sakura-tree/sakura-tree";

<SakuraTree
  windSpeed={3}
  fallingPetals={129}
  bloomAmount={0.85}
  weather="clear"
  windDirection={45}
  cameraDistance={8}
/>
```

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 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.
- `lib/utils.ts` is required, not optional. It exports the `cn` helper the component imports from `@/lib/utils` — keep it at that path, or rewrite every `cn` import to wherever you already keep yours. If your project is shadcn-based you almost certainly have this file already; keep yours and drop mine.
- 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.
