// Pooled billboard-free particles (tiny meshes in one InstancedMesh): sparkles, hearts, confetti, fluff. import * as THREE from 'three'; interface P { x: number; y: number; z: number; vx: number; vy: number; vz: number; life: number; max: number; size: number; grav: number; spin: number; r: number; g: number; b: number; drag: number } export class Particles { mesh: THREE.InstancedMesh; private ps: P[] = []; private m = new THREE.Matrix4(); private q = new THREE.Quaternion(); private e = new THREE.Euler(); private v = new THREE.Vector3(); private sc = new THREE.Vector3(); private c = new THREE.Color(); constructor(private max = 900) { const geo = new THREE.OctahedronGeometry(1, 0); this.mesh = new THREE.InstancedMesh(geo, new THREE.MeshBasicMaterial({ color: '#ffffff' }), max); this.mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(max * 3), 3); this.mesh.frustumCulled = false; this.mesh.count = 0; } emit(pos: THREE.Vector3, n: number, o: { color?: string | string[]; speed?: number; up?: number; size?: number; life?: number; grav?: number; spread?: number; drag?: number } = {}) { for (let i = 0; i < n && this.ps.length < this.max; i++) { const cols = Array.isArray(o.color) ? o.color : [o.color ?? '#fff6a8']; this.c.set(cols[(Math.random() * cols.length) | 0]); const sp = (o.speed ?? 3) * (0.4 + Math.random() * 0.8); const a = Math.random() * Math.PI * 2; const el = (Math.random() - 0.2) * Math.PI * 0.6; const life = (o.life ?? 1) * (0.6 + Math.random() * 0.6); const sprd = o.spread ?? 0.2; this.ps.push({ x: pos.x + (Math.random() - 0.5) * sprd, y: pos.y + (Math.random() - 0.5) * sprd, z: pos.z + (Math.random() - 0.5) * sprd, vx: Math.cos(a) * Math.cos(el) * sp, vy: Math.sin(el) * sp + (o.up ?? 2), vz: Math.sin(a) * Math.cos(el) * sp, life, max: life, size: (o.size ?? 0.12) * (0.6 + Math.random() * 0.8), grav: o.grav ?? 4, spin: Math.random() * 10, r: this.c.r, g: this.c.g, b: this.c.b, drag: o.drag ?? 0.5 }); } } update(dt: number) { let n = 0; for (let i = this.ps.length - 1; i >= 0; i--) { const p = this.ps[i]; p.life -= dt; if (p.life <= 0) { this.ps[i] = this.ps[this.ps.length - 1]; this.ps.pop(); continue; } p.vy -= p.grav * dt; const d = Math.exp(-p.drag * dt); p.vx *= d; p.vz *= d; p.vy *= d; p.x += p.vx * dt; p.y += p.vy * dt; p.z += p.vz * dt; p.spin += dt * 6; } for (const p of this.ps) { const k = p.life / p.max; const s = p.size * Math.min(1, k * 3) * (k < 0.2 ? k * 5 : 1); this.e.set(p.spin, p.spin * 0.7, 0); this.q.setFromEuler(this.e); this.m.compose(this.v.set(p.x, p.y, p.z), this.q, this.sc.set(s, s, s)); this.mesh.setMatrixAt(n, this.m); this.mesh.setColorAt(n, this.c.setRGB(p.r, p.g, p.b)); n++; } this.mesh.count = n; this.mesh.instanceMatrix.needsUpdate = true; if (this.mesh.instanceColor) this.mesh.instanceColor.needsUpdate = true; } }