Animations108 / 118
Pixel Grove
A tree of white light that builds itself out of pixels: the branches grow from the roots, then thousands of leaves fly in from a pixel grid, with now and then a digital glitch. Your cursor is a breeze through the leaves, dragging turns it, and a click bursts the canopy into pixel blocks that rebuild leaf by leaf.
three.jsthree.jsProceduralProceduralInstancingInstancingBloomBloomSpringsSpringsGSAPGSAP
Sweep through the leaves, drag to turnClick to scatter it into pixels
Tweak
LIVELIVETree
#f4f4f6
7
12000
1.00
Usage
Follows your tweaks.
usage.tsx
import { PixelGrove } from "@/components/inreact/pixel-grove";
export function Hero() {
return (
<section className="h-[700px] bg-[#09090b]">
<PixelGrove seed={7} color="#f4f4f6" leaves={12000} glow={1} />
</section>
);
}Install with the CLI
TS + Tailwind
npx shadcn@latest add https://inreact.vercel.app/r/pixel-grove.jsonOr copy the source
Install the dependencies, then save this as components/inreact/pixel-grove.tsx.
terminal
npm install gsap threecomponents/inreact/pixel-grove.tsx
"use client";
import { gsap } from "gsap";
import { useEffect, useRef } from "react";
import * as THREE from "three";
import { EffectComposer } from "three/addons/postprocessing/EffectComposer.js";
import { OutputPass } from "three/addons/postprocessing/OutputPass.js";
import { RenderPass } from "three/addons/postprocessing/RenderPass.js";
import { UnrealBloomPass } from "three/addons/postprocessing/UnrealBloomPass.js";
import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js";
/**
* Pixel Grove: a tree of white light that builds itself out of pixels, rendered live in three.js.
*
* - A real, procedurally grown tree: tapered branches, roots spread over the ground, and a canopy
* of thousands of leaves, lit white with a soft bloom.
* - It grows on arrival: the branches climb out of the roots, then the canopy flies in from
* blocks snapped to a pixel grid. Now and then a digital glitch slices through the leaves.
* - The cursor is a breeze: leaves near it blow along your movement and spring back.
* - Drag to turn the tree; it coasts on.
* - Click (or Enter / Space): the canopy gathers in, bursts into pixel blocks, and reassembles.
*
* <div className="h-[600px] bg-black"><PixelGrove /></div>
*/
export type PixelGroveProps = {
/** Seed for the tree's shape. */
seed?: number;
/** Colour of the light (leaves and bark). */
color?: string;
/** Number of leaves, 2000 to 14000. */
leaves?: number;
/** Strength of the glow, 0 to 2. */
glow?: number;
/** Background colour. */
background?: string;
/** Called when the canopy bursts. */
onBurst?: () => void;
className?: string;
};
const reduced = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
function rng(seed: number) {
let a = seed >>> 0 || 1;
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;
};
}
type Chain = { pts: THREE.Vector3[]; r: number[]; t0: number; t1: number; flare: boolean };
// grow the tree: a gently bending trunk that forks into ever finer branches spreading into a dome.
// Each branch is one chain of points, later swept into a single seamless tube.
function growTree(rand: () => number) {
const chains: Chain[] = [];
const tips: THREE.Vector3[] = [];
const up = new THREE.Vector3(0, 1, 0);
const branch = (start: THREE.Vector3, dir: THREE.Vector3, len: number, r: number, depth: number, t0: number) => {
const pts = [start.clone()];
const rs = [r];
let p = start.clone();
const d = dir.clone();
const steps = depth === 0 ? 5 : 4;
for (let i = 0; i < steps; i++) {
// bend a little toward the light and a little at random
d.add(new THREE.Vector3(rand() - 0.5, rand() * 0.3, rand() - 0.5).multiplyScalar(0.36)).normalize();
if (depth > 1) d.lerp(new THREE.Vector3(d.x, d.y * 0.6, d.z).normalize(), 0.12).normalize();
p = p.clone().addScaledVector(d, len / steps);
pts.push(p);
rs.push(r * (1 - 0.32 * ((i + 1) / steps)));
}
chains.push({ pts, r: rs, t0, t1: t0 + 0.17, flare: depth === 0 });
if (depth >= 6 || r < 0.004) {
tips.push(p);
return;
}
const n = depth < 2 ? 3 : 2 + (rand() < 0.45 ? 1 : 0);
const base = Math.atan2(d.z, d.x);
for (let k = 0; k < n; k++) {
const yaw = base + (k / n) * Math.PI * 2 + rand() * 0.9;
const tilt = (depth === 0 ? 0.45 : 0.34) + rand() * 0.3; // how far it leans from its parent
const side = new THREE.Vector3(Math.cos(yaw), 0, Math.sin(yaw));
const nd = d.clone().multiplyScalar(Math.cos(tilt)).addScaledVector(side, Math.sin(tilt)).normalize();
if (nd.y < 0.05) nd.y = 0.05 + rand() * 0.15;
nd.lerp(up, depth < 2 ? 0.15 : 0.02).normalize();
// children start a touch back inside the parent, so the fork is one continuous form
const from = pts[pts.length - 2].clone().lerp(p, 0.75);
branch(from, nd, len * (0.72 + rand() * 0.12), rs[rs.length - 1] * 0.82, depth + 1, t0 + 0.16);
}
if (depth >= 3) tips.push(p);
};
branch(new THREE.Vector3(0, -0.02, 0), up.clone(), 0.95, 0.08, 0, 0);
// roots: spread low over the ground, forking as they go, thick where they leave the trunk
const root = (start: THREE.Vector3, dir: THREE.Vector3, len: number, r: number, depth: number, t0: number) => {
const pts = [start.clone()];
const rs = [r];
let p = start.clone();
const d = dir.clone();
for (let i = 0; i < 4; i++) {
d.add(new THREE.Vector3(rand() - 0.5, 0, rand() - 0.5).multiplyScalar(0.45)).normalize();
d.y = -0.05 - rand() * 0.05;
d.normalize();
p = p.clone().addScaledVector(d, len / 4);
p.y = Math.max(-0.06, p.y);
pts.push(p);
rs.push(r * (1 - (i + 1) * 0.2));
}
chains.push({ pts, r: rs, t0, t1: t0 + 0.12, flare: false });
if (depth < 2)
for (let k = 0; k < 2; k++) {
const yaw = Math.atan2(d.z, d.x) + (k ? 0.6 : -0.6) * (0.5 + rand());
root(pts[2].clone().lerp(p, 0.6), new THREE.Vector3(Math.cos(yaw), 0, Math.sin(yaw)), len * 0.62, r * 0.45, depth + 1, t0 + 0.12);
}
};
const roots = 8;
for (let i = 0; i < roots; i++) {
const yaw = (i / roots) * Math.PI * 2 + rand() * 0.5;
root(new THREE.Vector3(Math.cos(yaw) * 0.04, 0.08, Math.sin(yaw) * 0.04), new THREE.Vector3(Math.cos(yaw), -0.6, Math.sin(yaw)), 0.6 + rand() * 0.3, 0.04, 0, 0);
}
return { chains, tips };
}
// sweep a chain into one seamless tube: a smooth spline, tapering radius, gnarled cross-section
function chainTube(c: Chain, rand: () => number) {
const curve = new THREE.CatmullRomCurve3(c.pts, false, "centripetal");
const segs = (c.pts.length - 1) * (c.flare ? 10 : 5);
const radial = c.flare ? 14 : c.r[0] > 0.012 ? 9 : 6;
const frames = curve.computeFrenetFrames(segs, false);
const pos: number[] = [], nor: number[] = [], at: number[] = [], ang: number[] = [], idx: number[] = [];
const seed = rand() * 10;
const P = new THREE.Vector3(), N = new THREE.Vector3(), V = new THREE.Vector3();
for (let i = 0; i <= segs; i++) {
const u = i / segs;
curve.getPointAt(u, P);
const f = u * (c.r.length - 1), k = Math.min(c.r.length - 2, Math.floor(f));
let r = THREE.MathUtils.lerp(c.r[k], c.r[k + 1], f - k);
if (c.flare) r *= 1 + 1.6 * Math.exp(-u * 9); // the trunk swells into its roots
for (let j = 0; j <= radial; j++) {
const a = (j / radial) * Math.PI * 2;
N.copy(frames.normals[i]).multiplyScalar(Math.cos(a)).addScaledVector(frames.binormals[i], Math.sin(a));
// gnarl: buttresses and twisting lumps in the cross-section
const lump = 1 + 0.13 * Math.sin(a * 3 + u * 6 + seed) + 0.07 * Math.sin(a * 7 - u * 15 + seed * 2) + (c.flare ? 0.22 * Math.max(0, Math.sin(a * 5 + seed)) * Math.exp(-u * 6) : 0);
V.copy(P).addScaledVector(N, r * lump);
pos.push(V.x, V.y, V.z);
nor.push(N.x, N.y, N.z);
at.push(THREE.MathUtils.lerp(c.t0, c.t1, u));
ang.push(a);
}
}
for (let i = 0; i < segs; i++)
for (let j = 0; j < radial; j++) {
const a0 = i * (radial + 1) + j, b0 = a0 + radial + 1;
idx.push(a0, b0, a0 + 1, b0, b0 + 1, a0 + 1);
}
const g = new THREE.BufferGeometry();
g.setAttribute("position", new THREE.Float32BufferAttribute(pos, 3));
g.setAttribute("normal", new THREE.Float32BufferAttribute(nor, 3));
g.setAttribute("aT", new THREE.Float32BufferAttribute(at, 1));
g.setAttribute("aAng", new THREE.Float32BufferAttribute(ang, 1));
g.setIndex(idx);
return g;
}
export function PixelGrove({ seed = 7, color = "#f4f4f6", leaves = 12000, glow = 1, background = "#09090b", onBurst, className }: PixelGroveProps) {
const rootRef = useRef<HTMLDivElement>(null);
const live = useRef({ glow, onBurst });
live.current = { glow, onBurst };
useEffect(() => {
const root = rootRef.current;
if (!root) return;
const still = reduced();
const rand = rng(seed);
const NL = Math.max(2000, Math.min(14000, Math.round(leaves)));
const col = new THREE.Color(color);
const canvas = document.createElement("canvas");
canvas.style.cssText = "position:absolute;inset:0;width:100%;height:100%;display:block;";
root.appendChild(canvas);
let renderer: THREE.WebGLRenderer;
try {
renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: false, powerPreference: "high-performance" });
} catch {
canvas.remove();
return;
}
const dpr = Math.min(2, Math.max(1.25, window.devicePixelRatio || 1));
renderer.setPixelRatio(dpr);
renderer.setClearColor(new THREE.Color(background), 1);
renderer.toneMapping = THREE.NeutralToneMapping;
renderer.outputColorSpace = THREE.SRGBColorSpace;
const scene = new THREE.Scene();
const uni = {
uT: { value: 0 },
uGrow: { value: still ? 1.2 : 0 },
uAssemble: { value: still ? 1 : 0 },
uWindC: { value: new THREE.Vector3(0, 1.2, 0) },
uWindD: { value: new THREE.Vector3() },
uWindS: { value: 0 },
uGlitch: { value: 0 },
uColor: { value: col },
uCrownY: { value: 1.6 },
uCrownR: { value: 1 },
};
// ---- the wood: every branch one seamless tube, merged into one mesh ----
const { chains, tips } = growTree(rand);
const parts = chains.map((c) => chainTube(c, rand));
const woodGeo = mergeGeometries(parts)!;
parts.forEach((g) => g.dispose());
const woodMat = new THREE.ShaderMaterial({
uniforms: uni,
vertexShader: `
attribute float aT;
attribute float aAng;
uniform float uT;
varying float vT;
varying vec3 vN;
varying vec3 vP;
varying float vAng;
varying vec3 vV;
void main(){
vT = aT;
vAng = aAng;
vec3 p = position;
// the fine branches sway a touch with the breeze
p.x += sin(uT * 1.1 + p.y * 2.0) * 0.006 * smoothstep(0.8, 2.0, p.y);
vP = p;
vN = normalize(mat3(modelMatrix) * normal);
vec4 wp = modelMatrix * vec4(p, 1.0);
vV = normalize(cameraPosition - wp.xyz);
gl_Position = projectionMatrix * viewMatrix * wp;
}`,
fragmentShader: `
uniform float uGrow;
uniform vec3 uColor;
varying float vT;
varying vec3 vN;
varying vec3 vP;
varying float vAng;
varying vec3 vV;
float h3(vec3 p){ return fract(sin(dot(p, vec3(127.1, 311.7, 74.7))) * 43758.5453); }
float vnoise(vec3 p){
vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
return mix(mix(mix(h3(i), h3(i + vec3(1,0,0)), f.x), mix(h3(i + vec3(0,1,0)), h3(i + vec3(1,1,0)), f.x), f.y),
mix(mix(h3(i + vec3(0,0,1)), h3(i + vec3(1,0,1)), f.x), mix(h3(i + vec3(0,1,1)), h3(i + vec3(1,1,1)), f.x), f.y), f.z);
}
void main(){
if (vT > uGrow) discard; // it grows out of its roots
vec3 n = normalize(vN);
// bark: long furrows running along the wood, broken by knots
float warp = vnoise(vP * vec3(9.0, 3.0, 9.0)) * 2.5;
float furrow = abs(sin(vAng * 6.0 + warp + vP.y * 1.5));
float knots = smoothstep(0.72, 0.9, vnoise(vP * 14.0));
float bark = mix(0.45, 1.0, smoothstep(0.15, 0.85, furrow)) * (1.0 - 0.35 * knots);
float key = max(0.0, dot(n, normalize(vec3(-0.45, 0.75, 0.55))));
float rim = pow(1.0 - max(0.0, dot(n, normalize(vV))), 2.4);
float fill = 0.5 + 0.5 * n.y;
vec3 c = uColor * (0.02 + 0.17 * key * bark + 0.03 * fill * bark + 0.5 * rim * bark);
gl_FragColor = vec4(c, 1.0);
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`,
});
const wood = new THREE.Mesh(woodGeo, woodMat);
// ---- the canopy: thousands of leaves round the branch tips ----
const leafGeo = new THREE.PlaneGeometry(1, 1);
const leafMat = new THREE.ShaderMaterial({
uniforms: uni,
side: THREE.DoubleSide,
vertexShader: `
attribute vec4 aRand; // xyz: scatter, w: delay
uniform float uT;
uniform float uAssemble;
uniform vec3 uWindC;
uniform vec3 uWindD;
uniform float uWindS;
uniform float uGlitch;
uniform float uCrownY;
uniform float uCrownR;
varying vec2 vUv;
varying float vShade;
varying float vSq;
varying float vRim;
varying float vTone;
void main(){
vUv = uv;
vec3 base = (instanceMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;
vec4 wp = instanceMatrix * vec4(position, 1.0);
// idle rustle, stronger toward the crown
float h = smoothstep(0.9, 2.2, base.y);
vec3 sway = vec3(sin(uT * 1.4 + base.x * 3.0 + aRand.x * 6.28), 0.4 * sin(uT * 2.1 + aRand.y * 6.28), cos(uT * 1.2 + base.z * 3.0 + aRand.z * 6.28)) * (0.006 + 0.012 * h);
// a gust from the cursor: leaves near it blow along its movement, fluttering
vec3 dw = base - uWindC;
float g = exp(-dot(dw, dw) / 0.09) * uWindS;
vec3 gust = uWindD * g * 0.22 + normalize(dw + 1e-4) * g * 0.04 + vec3(0.0, g * 0.03 * sin(uT * 14.0 + aRand.x * 40.0), 0.0);
// assembly: from blocks snapped to a pixel grid, each leaf in its own time
float a = clamp(uAssemble * 1.7 - aRand.w * 0.7, 0.0, 1.0);
a = a * a * (3.0 - 2.0 * a);
vec3 scat = base + (aRand.xyz - 0.5) * vec3(2.0, 1.3, 1.0);
scat = floor(scat / 0.085 + 0.5) * 0.085;
vec3 off = (scat - base) * (1.0 - a);
// the glitch: a few horizontal bands of leaves jump sideways for a moment
float row = floor(base.y * 16.0);
float hit = step(0.82, fract(sin(row * 91.31 + floor(uT * 9.0) * 17.7) * 43758.5453)) * uGlitch;
off.x += hit * (fract(sin(row * 12.9) * 4375.5) - 0.5) * 0.35;
vec3 p = wp.xyz - base + base + sway + gust + off;
// while scattered they are square pixels; settled, they are leaves
vSq = 1.0 - a;
vec3 n = normalize(mat3(instanceMatrix) * vec3(0.0, 0.0, 1.0));
// light from above: the top of the crown is bright, the inside and underside fall into shade
// light falls on the outside of the crown (from above and in front); the inside sits in shade
vec3 ov = (base - vec3(0.0, uCrownY * 0.72, 0.0)) / vec3(uCrownR, uCrownY * 0.4, uCrownR);
float shell = smoothstep(0.35, 1.0, length(ov));
float lit = smoothstep(-0.35, 0.75, dot(normalize(ov), normalize(vec3(0.25, 0.75, 0.6))));
vShade = (0.45 + 0.55 * abs(dot(n, normalize(vec3(0.3, 0.9, 0.5))))) * mix(0.16, 1.45, lit * (0.35 + 0.65 * shell)) * (0.78 + 0.34 * aRand.x);
// a backlit glow on the leaves round the crown's silhouette
vec3 vd = normalize(cameraPosition - (modelMatrix * vec4(base, 1.0)).xyz);
vRim = shell * pow(1.0 - abs(dot(normalize(mat3(modelMatrix) * normalize(ov)), vd)), 2.0);
vTone = aRand.y;
gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
}`,
fragmentShader: `
uniform vec3 uColor;
varying vec2 vUv;
varying float vShade;
varying float vSq;
varying float vRim;
varying float vTone;
void main(){
vec2 q = vUv * 2.0 - 1.0;
// a pointed leaf with a slight curl, morphing into a square pixel while scattered
float x = q.x - 0.12 * q.y * q.y;
float leaf = abs(x) / (1.0 - pow(abs(q.y), 1.4) * 0.92 + 0.001);
float sq = max(abs(q.x), abs(q.y));
float d = mix(leaf, sq, vSq);
if (d > 0.95) discard;
float settled = 1.0 - vSq;
// midrib and side veins, a soft darker edge, light glowing through the middle
float rib = smoothstep(0.07, 0.0, abs(x)) * 0.22;
float veins = smoothstep(0.06, 0.0, abs(fract((q.y - abs(x) * 0.9) * 4.0) - 0.5) * 0.4) * 0.08 * smoothstep(0.1, 0.3, abs(x));
float edge = smoothstep(0.55, 0.95, d) * 0.3;
float body = 1.0 - (rib + veins + edge) * settled;
vec3 tone = mix(vec3(0.94, 0.96, 1.0), vec3(1.0, 0.98, 0.95), vTone);
vec3 c = uColor * tone * vShade * body + uColor * vRim * 0.65 * settled;
gl_FragColor = vec4(c, 1.0);
#include <tonemapping_fragment>
#include <colorspace_fragment>
}`,
});
const leavesMesh = new THREE.InstancedMesh(leafGeo, leafMat, NL);
const aRand = new Float32Array(NL * 4);
const m = new THREE.Matrix4(), qq = new THREE.Quaternion(), sc = new THREE.Vector3(), pos = new THREE.Vector3();
const e = new THREE.Euler();
let maxY = 1, crownR = 0.5;
tips.forEach((p) => ((maxY = Math.max(maxY, p.y)), (crownR = Math.max(crownR, Math.hypot(p.x, p.z)))));
for (let i = 0; i < NL; i++) {
const tip = tips[Math.floor(rand() * tips.length)];
// a soft cluster round the tip, flattened into the dome of the crown
const r = 0.03 + Math.pow(rand(), 0.6) * 0.22;
const th = rand() * Math.PI * 2, ph = Math.acos(2 * rand() - 1);
pos.set(tip.x + Math.sin(ph) * Math.cos(th) * r * 1.3, tip.y + Math.cos(ph) * r * 1.05, tip.z + Math.sin(ph) * Math.sin(th) * r * 1.3);
e.set(rand() * Math.PI, rand() * Math.PI, rand() * Math.PI);
qq.setFromEuler(e);
const s = 0.05 + rand() * 0.035;
sc.set(s * 0.62, s, s);
m.compose(pos, qq, sc);
leavesMesh.setMatrixAt(i, m);
// stagger: the crown arrives first, the lower leaves after
aRand.set([rand(), rand(), rand(), 1 - Math.min(1, pos.y / maxY) * 0.7 + rand() * 0.3], i * 4);
}
uni.uCrownY.value = maxY;
uni.uCrownR.value = crownR;
leafGeo.setAttribute("aRand", new THREE.InstancedBufferAttribute(aRand, 4));
leavesMesh.instanceMatrix.needsUpdate = true;
leavesMesh.frustumCulled = false;
const tree = new THREE.Group();
tree.add(wood, leavesMesh);
// a soft haze of light behind the crown and a pool of light on the ground: depth, not a void
const hazeMat = new THREE.ShaderMaterial({
uniforms: { uColor: uni.uColor, uCrownY: uni.uCrownY, uK: { value: 1 } },
transparent: true,
depthWrite: false,
blending: THREE.AdditiveBlending,
vertexShader: "varying vec2 vUv;\nvoid main(){ vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }",
fragmentShader: `
uniform vec3 uColor;
uniform float uK;
varying vec2 vUv;
void main(){
vec2 q = (vUv - vec2(0.5, 0.62)) * vec2(1.0, 1.25);
float halo = exp(-dot(q, q) * 10.0) * 0.035;
vec2 g = (vUv - vec2(0.5, 0.17)) * vec2(1.0, 5.5);
float pool = exp(-dot(g, g) * 7.0) * 0.03;
gl_FragColor = vec4(uColor * (halo + pool) * uK, 1.0);
}`,
});
const haze = new THREE.Mesh(new THREE.PlaneGeometry(8, 6), hazeMat);
haze.position.set(0, 1.2, -1.6);
scene.add(haze);
// motes drifting up through the light
const NM = 260;
const moteGeo = new THREE.BufferGeometry();
const mp = new Float32Array(NM * 3), mr = new Float32Array(NM);
for (let i = 0; i < NM; i++) {
mp.set([(rand() - 0.5) * 3.2, rand() * 2.8, (rand() - 0.5) * 1.6], i * 3);
mr[i] = rand();
}
moteGeo.setAttribute("position", new THREE.BufferAttribute(mp, 3));
moteGeo.setAttribute("aR", new THREE.BufferAttribute(mr, 1));
const moteMat = new THREE.ShaderMaterial({
uniforms: { uT: uni.uT, uColor: uni.uColor, uPx: { value: 1 } },
transparent: true,
depthWrite: false,
blending: THREE.AdditiveBlending,
vertexShader: `
attribute float aR;
uniform float uT;
uniform float uPx;
varying float vA;
void main(){
vec3 p = position;
p.y = mod(p.y + uT * (0.04 + 0.05 * aR), 2.8);
p.x += sin(uT * 0.4 + aR * 30.0) * 0.08;
vec4 mv = modelViewMatrix * vec4(p, 1.0);
gl_PointSize = uPx * (1.5 + 2.5 * aR) / -mv.z;
vA = (0.25 + 0.75 * (0.5 + 0.5 * sin(uT * (1.0 + aR * 2.0) + aR * 40.0))) * smoothstep(0.0, 0.4, p.y) * smoothstep(2.8, 2.2, p.y);
gl_Position = projectionMatrix * mv;
}`,
fragmentShader: `
uniform vec3 uColor;
varying float vA;
void main(){
float r = length(gl_PointCoord - 0.5) * 2.0;
gl_FragColor = vec4(uColor * pow(max(0.0, 1.0 - r), 2.0) * vA * 0.6, 1.0);
}`,
});
const motes = new THREE.Points(moteGeo, moteMat);
motes.frustumCulled = false;
tree.add(motes);
const holder = new THREE.Group(); // squash
holder.add(tree);
scene.add(holder);
const camera = new THREE.PerspectiveCamera(30, 1, 0.1, 100);
const composer = new EffectComposer(renderer, new THREE.WebGLRenderTarget(4, 4, { type: THREE.HalfFloatType, samples: 4 }));
composer.addPass(new RenderPass(scene, camera));
const bloom = new UnrealBloomPass(new THREE.Vector2(4, 4), 0.35, 0.5, 0.82);
composer.addPass(bloom);
composer.addPass(new OutputPass());
// frame the whole tree, roots to crown
const box = new THREE.Box3().setFromObject(wood);
for (let i = 0; i < NL; i++) {
leavesMesh.getMatrixAt(i, m);
box.expandByPoint(pos.setFromMatrixPosition(m));
}
const centre = box.getCenter(new THREE.Vector3());
const sizeV = box.getSize(new THREE.Vector3());
let W = 0, H = 0;
const resize = () => {
const w = root.clientWidth, h = root.clientHeight;
if (w < 2 || h < 2 || (w === W && h === H)) return;
W = w;
H = h;
renderer.setSize(W, H, false);
composer.setPixelRatio(dpr);
composer.setSize(W, H);
moteMat.uniforms.uPx.value = H * dpr * 0.012;
camera.aspect = W / H;
const t = Math.tan(THREE.MathUtils.degToRad(15));
const spanH = sizeV.y * 1.42, spanW = Math.max(sizeV.x, sizeV.z) * 1.25;
camera.position.set(0, centre.y, Math.max(spanH / (2 * t), spanW / (2 * t * camera.aspect)));
camera.lookAt(0, centre.y, 0);
camera.updateProjectionMatrix();
};
resize();
const ro = new ResizeObserver(resize);
ro.observe(root);
// ---- motion ----
type Spring = { x: number; v: number; t: number; k: number; c: number };
const sp = (x: number, k: number, c: number): Spring => ({ x, v: 0, t: x, k, c });
const step = (s: Spring, dt: number) => {
const h = dt / 2;
for (let i = 0; i < 2; i++) {
s.v += (s.k * (s.t - s.x) - s.c * s.v) * h;
s.x += s.v * h;
}
};
const assemble = sp(still ? 1 : 0, 9, 5.2);
const squash = sp(1, 170, 8.5);
const windS = sp(0, 40, 9);
const windD = new THREE.Vector3();
let yaw = 0, yawV = still ? 0 : 0.12;
let pointer: { x: number; y: number } | null = null, prevP: { x: number; y: number } | null = null;
let drag: { x: number; t: number; sx: number; sy: number; t0: number; id: number } | null = null;
let busy = false;
let glitchUntil = 0, nextGlitch = 3.5;
const calls: gsap.core.Tween[] = [];
let t = 0;
// arrival: the wood grows, then the canopy flies in
if (!still) {
const g = { v: 0 };
calls.push(gsap.to(g, { v: 1.2, duration: 2.0, ease: "power2.inOut", onUpdate: () => (uni.uGrow.value = g.v) }) as unknown as gsap.core.Tween);
calls.push(gsap.delayedCall(1.1, () => (assemble.t = 1)));
}
const burst = () => {
if (busy) return;
busy = true;
live.current.onBurst?.();
if (still) {
busy = false;
return;
}
squash.t = 0.92; // anticipation: it draws in
calls.push(
gsap.delayedCall(0.14, () => {
squash.t = 1;
squash.v += 2;
assemble.k = 30;
assemble.t = 0; // the canopy bursts into pixels
glitchUntil = t + 0.4;
}),
gsap.delayedCall(0.95, () => {
assemble.k = 9;
assemble.t = 1; // and builds itself back, leaf by leaf
}),
gsap.delayedCall(2.6, () => (busy = false)),
);
};
const ray = new THREE.Raycaster();
const plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
const ndc = new THREE.Vector2(), hit = new THREE.Vector3();
const worldAt = (x: number, y: number) => {
ndc.set((x / W) * 2 - 1, -(y / H) * 2 + 1);
ray.setFromCamera(ndc, camera);
return ray.ray.intersectPlane(plane, hit) ? hit.clone() : null;
};
let visible = true;
const io = new IntersectionObserver(([en]) => (visible = en.isIntersecting), { rootMargin: "80px" });
io.observe(root);
const tick = (_time: number, dms: number) => {
const dt = Math.min(0.05, Math.max(0.001, dms / 1000));
t += dt;
uni.uT.value = still ? 0 : t;
// the breeze from the cursor, measured in the tree's own frame
if (pointer && !still) {
const p = worldAt(pointer.x, pointer.y);
if (p) {
tree.worldToLocal(p);
uni.uWindC.value.lerp(p, 1 - Math.exp(-dt * 14));
if (prevP) {
const a = worldAt(prevP.x, prevP.y);
if (a) {
tree.worldToLocal(a);
const v = p.clone().sub(a).divideScalar(dt);
windD.lerp(v.clampLength(0, 4).multiplyScalar(0.25), 1 - Math.exp(-dt * 10));
windS.t = Math.min(1.4, v.length() * 0.4);
}
}
}
prevP = pointer;
} else {
windS.t = 0;
prevP = null;
}
[assemble, squash, windS].forEach((s) => step(s, dt));
uni.uAssemble.value = Math.max(0, assemble.x);
uni.uWindS.value = Math.max(0, windS.x);
uni.uWindD.value.copy(windD);
// turn: drag spins it, then it settles back to a slow turn
if (!drag) yawV += ((still ? 0 : 0.12) - yawV) * (1 - Math.exp(-dt * 0.8));
yaw += yawV * dt;
tree.rotation.y = yaw;
const q = Math.max(0.8, squash.x);
holder.scale.set(1 / Math.sqrt(q), q, 1 / Math.sqrt(q));
// an occasional glitch slicing through the canopy
if (!still && t > nextGlitch) {
glitchUntil = t + 0.12 + Math.random() * 0.15;
nextGlitch = t + 3 + Math.random() * 4;
}
uni.uGlitch.value = t < glitchUntil ? 1 : 0;
bloom.strength = 0.38 * live.current.glow;
if (visible && W) composer.render(dt);
};
gsap.ticker.add(tick);
const local = (ev: PointerEvent) => {
const r = root.getBoundingClientRect();
return { x: ev.clientX - r.left, y: ev.clientY - r.top };
};
const onMove = (ev: PointerEvent) => {
pointer = local(ev);
if (!drag) return;
const now = performance.now();
const ddt = Math.max(8, now - drag.t) / 1000;
yawV = THREE.MathUtils.lerp(yawV, ((ev.clientX - drag.x) / root.clientWidth / ddt) * 5, 0.5);
drag.x = ev.clientX;
drag.t = now;
};
const onDown = (ev: PointerEvent) => {
if (ev.button !== 0) return;
const now = performance.now();
drag = { x: ev.clientX, t: now, sx: ev.clientX, sy: ev.clientY, t0: now, id: ev.pointerId };
try {
root.setPointerCapture(ev.pointerId);
} catch {
/* synthetic pointers can't be captured */
}
};
const onUp = (ev: PointerEvent) => {
if (!drag) return;
const moved = Math.hypot(ev.clientX - drag.sx, ev.clientY - drag.sy);
const quick = performance.now() - drag.t0 < 450;
try {
root.releasePointerCapture(drag.id);
} catch {
/* not captured */
}
drag = null;
if (moved < 7 && quick) burst();
};
const onLeave = () => {
if (!drag) pointer = null;
};
const onKey = (ev: KeyboardEvent) => {
if (ev.key === "Enter" || ev.key === " ") {
ev.preventDefault();
burst();
} else if (ev.key === "ArrowLeft" || ev.key === "ArrowRight") {
ev.preventDefault();
yawV += ev.key === "ArrowLeft" ? -1.2 : 1.2;
}
};
root.addEventListener("pointermove", onMove);
root.addEventListener("pointerdown", onDown);
root.addEventListener("pointerup", onUp);
root.addEventListener("pointercancel", onUp);
root.addEventListener("pointerleave", onLeave);
root.addEventListener("keydown", onKey);
return () => {
gsap.ticker.remove(tick);
calls.forEach((c) => c.kill());
io.disconnect();
ro.disconnect();
root.removeEventListener("pointermove", onMove);
root.removeEventListener("pointerdown", onDown);
root.removeEventListener("pointerup", onUp);
root.removeEventListener("pointercancel", onUp);
root.removeEventListener("pointerleave", onLeave);
root.removeEventListener("keydown", onKey);
[woodGeo, leafGeo, moteGeo, haze.geometry].forEach((g) => g.dispose());
[woodMat, leafMat, moteMat, hazeMat].forEach((mm) => mm.dispose());
leavesMesh.dispose();
composer.dispose();
renderer.dispose();
canvas.remove();
};
}, [seed, color, leaves, background]);
return (
<div
ref={rootRef}
tabIndex={0}
role="button"
aria-label="Tree of light. Move to blow its leaves, drag to turn it, press to scatter it into pixels."
className={["relative h-full min-h-[280px] w-full cursor-grab touch-none overflow-hidden outline-none select-none active:cursor-grabbing", className].filter(Boolean).join(" ")}
style={{ background }}
/>
);
}
export default PixelGrove;
One prompt, any AI agent
Paste into Claude Code, Codex, Cursor or Windsurf. It carries your tweaks and the full source, so the agent installs it exactly.
Props
7 propsseednumberSeed for the tree's shape.default 7default 7colorstringColour of the light.default "#f4f4f6"default "#f4f4f6"leavesnumberNumber of leaves, 2000 to 14000.default 12000default 12000glownumberStrength of the glow, 0 to 2.default 1default 1backgroundstringBackground colour.default "#09090b"default "#09090b"onBurst() => voidCalled when the canopy bursts.classNamestringExtra classes (it fills its parent).