# Instanced Wind Foliage, Object-Pooled Particles & Spring Feel in Three.js

> Single-draw-call THREE.InstancedMesh wind foliage with player bend, zero-GC pooled burst particles, and dt-invariant second-order springs that keep 60 Hz steps under 2 ms.

- **Canonical page:** https://gamecrew.ai/techniques/three/instanced-foliage-springs
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Three.js
- **Category:** optimization
- **Tags:** `instancing`, `foliage`, `grass`, `wind`, `springs`, `game-feel`, `particles`, `object-pool`, `onbeforecompile`
- **Verification:** Compile-verified pattern

## When to Use & Field Best Practices

Browser games must keep fixed-step simulation (`STEP = 1/60 s`) well under `2 ms` with zero per-frame garbage-collection spikes, especially during fast-forwarded `play` tests. Three patterns unlock rich visual density at near-zero CPU cost:
1. **`THREE.InstancedMesh` + GPU Vertex Wind**: Populate instance matrices once at level build time (`mesh.instanceMatrix.needsUpdate = true`), and animate all 3,000 grass blades or crystals on the GPU via a single `uTime` and `uPlayerPos` uniform!
2. **Pre-Allocated Instanced Particle Pool**: Never `new THREE.Mesh(...)` + `scene.add(...)` on every jump, dash, or coin pickup; update slots inside one `THREE.InstancedMesh` ring buffer (`setColorAt`, `setMatrixAt`, `count`).
3. **$\Delta t$-Invariant Springs & $T^2$ Trauma**: Drive visual squash-stretch and rotational camera shake cleanly without touching `CollisionWorld` capsule dimensions.

## Mathematical & Algorithmic Core

- **Second-Order Spring**: $a = -\omega^2(x - x_{\text{target}}) - 2\zeta\omega v$, substepped at $h \le 1/60\text{ s}$.
- **GPU Instance Wind**: Read world root from `instanceMatrix[3].xyz`, weight horizontal gust by $h^2$, and push away when `distance(posWS, uPlayerPos) < radius`.

## Engine Implementation

### Strict TypeScript Instanced Foliage + Springs (`Assets/Game/foliage-and-feel.ts`)

```ts
import * as THREE from 'three';
import type { Game } from 'ccgd';

export class Spring1D {
  value: number;
  velocity = 0;

  constructor(initial = 0) {
    this.value = initial;
  }

  step(target: number, freqHz: number, damping: number, dt: number): number {
    if (dt <= 0) return this.value;
    const omega = Math.PI * 2 * Math.max(0.1, freqHz);
    const maxH = Math.min(0.016, 0.5 / Math.max(1, omega));
    let rem = Math.min(dt, 0.2);
    while (rem > 1e-5) {
      const h = Math.min(rem, maxH);
      const acc = -omega * omega * (this.value - target) - 2 * damping * omega * this.velocity;
      this.velocity += acc * h;
      this.value += this.velocity * h;
      rem -= h;
    }
    return this.value;
  }

  impulse(dv: number): void {
    this.velocity += dv;
  }
}

export function applySquashStretch(visual: THREE.Object3D, scaleY: number, base = 1): void {
  const sy = THREE.MathUtils.clamp(scaleY, 0.45, 1.85);
  const inv = 1 / Math.sqrt(sy);
  visual.scale.set(base * inv, base * sy, base * inv);
}

export function createWindMeadow(
  game: Game,
  placements: ReadonlyArray<{ x: number; y: number; z: number; scale?: number; yaw?: number }>,
  getPlayerPos?: () => THREE.Vector3
) {
  const count = placements.length;
  const blade = new THREE.BufferGeometry();
  const hw = 0.07;
  const bh = 0.85;
  blade.setAttribute(
    'position',
    new THREE.Float32BufferAttribute(
      [-hw, 0, 0, hw, 0, 0, -hw * 0.65, bh * 0.5, 0.02, hw * 0.65, bh * 0.5, 0.02, 0, bh, 0.06],
      3
    )
  );
  blade.setIndex([0, 2, 1, 1, 2, 3, 2, 4, 3]);
  blade.computeVertexNormals();

  const uniforms = {
    uTime: { value: 0 },
    uPlayer: { value: new THREE.Vector4(0, -999, 0, 1.35) },
    uRootColor: { value: new THREE.Color(0x1f5229) },
    uTipColor: { value: new THREE.Color(0x7ac743) },
  };

  const mat = new THREE.ShaderMaterial({
    uniforms,
    side: THREE.DoubleSide,
    vertexShader: /* glsl */ `
      uniform float uTime;
      uniform vec4 uPlayer;
      varying float vH;
      varying float vGust;

      void main() {
        float h = clamp(position.y / 0.85, 0.0, 1.0);
        float w = h * h;
        vec4 worldPos = modelMatrix * instanceMatrix * vec4(position, 1.0);
        vec3 rootWS = (modelMatrix * instanceMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;

        float gust = sin(dot(rootWS.xz, vec2(0.24, 0.17)) - uTime * 2.2) * 0.65
                   + sin(dot(rootWS.xz, vec2(0.63, -0.51)) - uTime * 3.9) * 0.35;
        vec2 sway = vec2(0.85, 0.52) * ((gust * 0.5 + 0.5) * 0.28 * w);

        vec3 diff = worldPos.xyz - uPlayer.xyz;
        float dist = length(diff);
        if (dist < uPlayer.w) {
          float push = 1.0 - dist / uPlayer.w;
          vec2 dir = normalize(diff.xz + vec2(1e-4, 1e-4));
          sway += dir * (push * push * 0.6 * w);
        }

        worldPos.xz += sway;
        worldPos.y -= length(sway) * 0.35;
        vH = h;
        vGust = clamp(gust * 0.5 + 0.5, 0.0, 1.0);
        gl_Position = projectionMatrix * viewMatrix * worldPos;
      }
    `,
    fragmentShader: /* glsl */ `
      precision highp float;
      uniform vec3 uRootColor;
      uniform vec3 uTipColor;
      varying float vH;
      varying float vGust;

      void main() {
        vec3 tip = mix(uTipColor, vec3(0.86, 0.94, 0.46), vGust * 0.38);
        vec3 col = mix(uRootColor, tip, vH);
        gl_FragColor = vec4(col, 1.0);
        #include <colorspace_fragment>
      }
    `,
  });

  const mesh = new THREE.InstancedMesh(blade, mat, Math.max(1, count));
  mesh.frustumCulled = false;
  mesh.castShadow = false;
  const dummy = new THREE.Object3D();
  for (let i = 0; i < count; i++) {
    const p = placements[i];
    dummy.position.set(p.x, p.y, p.z);
    dummy.rotation.set(0, p.yaw ?? (i * 1.6180339) % (Math.PI * 2), 0);
    const s = p.scale ?? 1;
    dummy.scale.set(s, s, s);
    dummy.updateMatrix();
    mesh.setMatrixAt(i, dummy.matrix);
  }
  mesh.count = count;
  mesh.instanceMatrix.needsUpdate = true;
  game.scene.add(mesh);

  game.onUpdate(() => {
    uniforms.uTime.value = game.time;
    if (getPlayerPos) {
      const p = getPlayerPos();
      uniforms.uPlayer.value.set(p.x, p.y, p.z, 1.35);
    }
  });

  return mesh;
}
```

## Browser, Mobile & Software-Renderer Budgets

- **`frustumCulled = false` or `mesh.computeBoundingSphere()`**: Three.js computes `InstancedMesh` frustum culling from the base single-blade geometry unless you call `mesh.computeBoundingSphere()` after `setMatrixAt` or disable `frustumCulled`! Forgetting this causes grass fields to vanish when the camera turns away from `(0, 0, 0)`.

## Verification Checklist

1. Run `compile` and `test` to ensure zero step-time regressions and clean TypeScript compilation.
2. Check `Captures/*.png` from elevated and player-level views to verify grass coverage never pops out of the frustum.

## Official references

- Kévin Boulanger (GPU Gems Ch. 7 — Waving Grass)
- Squirrel Eiserloh (GDC 2016 — Camera Trauma)
- Three.js InstancedMesh & Shader Injection Best Practices
