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.
- instancing
- foliage
- grass
- wind
- springs
- game-feel
- particles
- object-pool
- onbeforecompile
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:
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 singleuTimeanduPlayerPosuniform!- Pre-Allocated Instanced Particle Pool: Never
new THREE.Mesh(...)+scene.add(...)on every jump, dash, or coin pickup; update slots inside oneTHREE.InstancedMeshring buffer (setColorAt,setMatrixAt,count). Δ t-Invariant Springs &T^2Trauma: Drive visual squash-stretch and rotational camera shake cleanly without touchingCollisionWorldcapsule dimensions.
Mathematical & Algorithmic Core
- Second-Order Spring:
a = -ω^2(x - x_target) - 2zetaω v, substepped ath ≤ 1/60 s. - GPU Instance Wind: Read world root from
instanceMatrix[3].xyz, weight horizontal gust byh^2, and push away whendistance(posWS, uPlayerPos) < radius.
Engine Implementation
Strict TypeScript Instanced Foliage + Springs (Assets/Game/foliage-and-feel.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 = falseormesh.computeBoundingSphere(): Three.js computesInstancedMeshfrustum culling from the base single-blade geometry unless you callmesh.computeBoundingSphere()aftersetMatrixAtor disablefrustumCulled! Forgetting this causes grass fields to vanish when the camera turns away from(0, 0, 0).
Verification Checklist
- Run
compileandtestto ensure zero step-time regressions and clean TypeScript compilation. - Check
Captures/*.pngfrom 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
Playable Three.js games made with GameCrew
Launch a real browser build using this engine and inspect its controls or fork its project tree.
More Three.js techniques
Raymarched Volumetric Clouds & Atmospheric Sky Shaders in Three.js (WebGL 2) →
Self-contained THREE.ShaderMaterial sky dome in GLSL ES 3.0 raymarching a height-bounded cloud layer with 3D value-Worley FBM, Beer-Powder silver lining, interleaved gradient noise, and mobile step scaling.
BVH Mesh & Character Capsule Collision in Three.js →
Fast capsule-vs-triangle pushout and slope resolution using three-mesh-bvh shapecasts, pre-allocated scratch vectors, and CollisionWorld.
Zero-Allocation Context Steering, Patrol Loops & Telegraphed AI in Three.js →
Deterministic 60 Hz enemy and companion AI in Three.js using 8-slot context steering against CollisionWorld, level.json patrol loops, attack-token pacing, and telegraphed strikes.
Multiplayer Room State Sync & 60 Hz Avatars in Three.js →
Solo-first multiplayer with smooth 60 Hz remote avatars, host-owned shared state, reliable host claims, and deterministic two-peer room tests.
Use verified techniques inside a real game
Describe your game idea for free or connect an MCP assistant to search and contribute techniques.
