// Prevailing wind — a Meep example for the GPU fluid simulation + global
// effector + solid obstacles + GPU particles.
//
// One GlobalFluidEffector blows a steady, wheeling, gusting breeze across a
// meadow of ~60,000 GPU particles inside a 2-cascade GPUFluidComponent domain.
// The particles spawn across the 18×12 grid where the plantation stands and
// sample the live GPU wind field each frame via `SAMPLE_WIND` — streaming
// coherently with the breeze.
//
// Standing in the field are a long WINDBREAK wall and two BOULDERS tagged with
// FluidObstacle: GPUFluidSystem packs their colliders into the GPU LBVH forcing
// pass, so the breeze genuinely parts around and over them. Particles born in
// the wall's lee linger in a calm sheltered pocket while the open meadow
// streams past; the boulders trail their own calm wakes downwind.
//
// The pieces and who does what:
//
// - GPUFluidComponent the domain: nested, two-way coupled 3D cascades
// centred on its entity's Transform64.
// - GlobalFluidEffector the atmosphere: position-free. Relaxes the far
// field toward `wind` at rate `drag`. We steer
// `wind` per-frame to wheel and gust the breeze.
// - FluidObstacle the wall marker: rides a (Collider, RigidBody,
// Transform64) tuple read directly by GPUFluidSystem.
// - FluidEffectorsSystem folds the atmosphere into one far field each tick.
// - GPUFluidSystem steps the cascade stack on the GPU and publishes
// the velocity field to `GPUSceneContext#wind`.
// - GPUParticleEmitterSystem spawns and simulates ~60k particles on the GPU,
// sampling `wind` at each particle's world position.
//
// Sections:
// §1 Tuning constants
// §2 Shade materials & particle sprite
// §3 Engine bootstrap
// §4 Ground
// §5 The GPU fluid volume
// §6 The particle field ~60k GPU particles arranged across the 18×12 grid
// §7 The wind + the shelter the global effector · the wall + boulders
// §8 Per-frame steer the wind, HUD
import { EngineHarness } from "@woosh/meep-engine/src/engine/EngineHarness.js";
import TopDownCameraController from "@woosh/meep-engine/src/engine/graphics/ecs/camera/topdown/TopDownCameraController.js";
import { Light } from "@woosh/meep-engine/src/engine/graphics/ecs/light/Light.js";
import { LightType } from "@woosh/meep-engine/src/engine/graphics/ecs/light/LightType.js";
import Entity from "@woosh/meep-engine/src/engine/ecs/Entity.js";
import { Transform64 } from "@woosh/meep-engine/src/engine/ecs/transform/Transform64.js";
import { ShadedGeometry } from "@woosh/meep-engine/src/engine/graphics/ecs/mesh-v2/ShadedGeometry.js";
import { ShadedGeometrySystem } from "@woosh/meep-engine/src/engine/graphics3/ShadedGeometrySystem.js";
import { make_box_geometry } from "@woosh/meep-engine/src/shade/renderer/geometry/primitives/make_box_geometry.js";
import { make_octahedron_geometry } from "@woosh/meep-engine/src/shade/renderer/geometry/primitives/make_octahedron_geometry.js";
import { meshlet_geometry_build_from_geometry } from "@woosh/meep-engine/src/shade/renderer/geometry/meshlet_geometry_build_from_geometry.js";
import { StandardShadeMaterial } from "@woosh/meep-engine/src/shade/renderer/material/StandardShadeMaterial.js";
import { Color } from "@woosh/meep-engine/src/core/color/Color.js";
import { PhysicsSystem } from "@woosh/meep-engine/src/engine/physics/ecs/PhysicsSystem.js";
import { ColliderObserverSystem } from "@woosh/meep-engine/src/engine/physics/ecs/ColliderObserverSystem.js";
import { RigidBody } from "@woosh/meep-engine/src/engine/physics/ecs/RigidBody.js";
import { Collider } from "@woosh/meep-engine/src/engine/physics/ecs/Collider.js";
import { BodyKind } from "@woosh/meep-engine/src/engine/physics/ecs/BodyKind.js";
import { BoxShape3D } from "@woosh/meep-engine/src/core/geom/3d/shape/BoxShape3D.js";
import { SphereShape3D } from "@woosh/meep-engine/src/core/geom/3d/shape/SphereShape3D.js";
import { NodeGraph } from "@woosh/meep-engine/src/core/model/node-graph/NodeGraph.js";
import { ParticleEffect } from "@woosh/meep-engine/src/engine/graphics/ecs/particles/ParticleEffect.js";
import { GPUParticleEmitterSystem } from "@woosh/meep-engine/src/engine/graphics3/GPUParticleEmitterSystem.js";
import {
EMITTER_BLEND,
EMITTER_PROJECTION,
} from "@woosh/meep-engine/src/shade/renderer/particles/data/PARTICLE_EMITTER_STRUCT.js";
import {
particle_node,
particle_wire,
} from "@woosh/meep-engine/src/shade/renderer/particles/graph/particle_graph_authoring.js";
import { VM_BUILTIN } from "@woosh/meep-engine/src/shade/renderer/particles/isa/ParticleVMISA.js";
import { ParticleLayout } from "@woosh/meep-engine/src/shade/renderer/particles/layout/ParticleLayout.js";
import { create_particle_effect } from "@woosh/meep-engine/src/shade/renderer/particles/runtime/create_particle_effect.js";
import { GPUFluidComponent } from "@woosh/meep-engine/src/engine/physics/fluid/ecs/GPUFluidComponent.js";
import { GPUFluidSystem } from "@woosh/meep-engine/src/engine/graphics3/GPUFluidSystem.js";
import { FluidEffectorsComponent } from "@woosh/meep-engine/src/engine/physics/fluid/ecs/FluidEffectorsComponent.js";
import { FluidEffectorsSystem } from "@woosh/meep-engine/src/engine/physics/fluid/ecs/FluidEffectorsSystem.js";
import { FluidObstacle } from "@woosh/meep-engine/src/engine/physics/fluid/ecs/FluidObstacle.js";
import { GlobalFluidEffector } from "@woosh/meep-engine/src/engine/physics/fluid/effector/GlobalFluidEffector.js";
import Vector3 from "@woosh/meep-engine/src/core/geom/Vector3.js";
// ─── §1 Tuning constants ────────────────────────────────────────────────────
// The spawn volume: spans the 18 × 12 plantation footprint (28.8 m × 19.2 m).
const SITES_X = 18;
const SITES_Z = 12;
const SITE_SPACING = 1.6;
const SPAWN_HALF_X = (SITES_X * SITE_SPACING) * 0.5;
const SPAWN_HALF_Z = (SITES_Z * SITE_SPACING) * 0.5;
const SPAWN_Y_MIN = 0.15;
const SPAWN_Y_MAX = 2.85;
// ~60,000 average live particles by Little's Law: 24,000/s × 2.5 s mean life = 60,000.
const PARTICLE_SPAWN_RATE = 24000;
const PARTICLE_LIFE_MIN = 2.3;
const PARTICLE_LIFE_MAX = 2.7;
// Ground footprint.
const FIELD_SIZE_X = 32;
const FIELD_SIZE_Z = 22;
// The GPU fluid cascade stack: 2 cascades of 64 × 32 × 64 cells, finest cell 0.65 m.
// Centred at Y = 6.5 m so cascade 0 (41.6 × 20.8 × 41.6 m) captures the entire
// ground footprint and 16.9 m above the ground, while cascade 1 reaches
// 83.2 × 41.6 × 83.2 m.
const FLUID_RESOLUTION = [64, 32, 64];
const FLUID_CELL_SIZE = 0.65;
const FLUID_CASCADES = 2;
const FLUID_CENTER_Y = 6.5;
// The wind. `wind` is the ambient velocity the air relaxes toward (world
// units/s); `drag` is the relaxation rate (1/s).
const WIND_SPEED = 6.0;
const WIND_DRAG = 1.1;
const WIND_SWING = 0.34; // rad — how far the heading wheels off +X
const WIND_SWING_PERIOD = 16; // seconds for one full heading sweep
const WIND_GUST = 0.7; // ± fraction the speed gusts by
const WIND_GUST_PERIOD = 3.5; // seconds per gust cycle
// The windbreak wall: thin across the flow, long across the lanes, tall enough
// to deflect air around its ends and up over its coping while sheltering the lee.
const WALL_X = -5;
const WALL_W = 0.7;
const WALL_D = 7.4;
const WALL_H = 3.8;
// Two boulders downwind of the wall, off to the sides, each trailing a small
// calm wake of its own. [x, z, radius].
const BOULDERS = [
[5.5, 3.0, 1.5],
[8.5, -3.5, 1.3],
];
const OBSTACLE_INFLATION = FLUID_CELL_SIZE * 0.5;
const GROUND_COLOR = "#161c24";
const WALL_COLOR = "#4a4640";
const BOULDER_COLOR = "#6b7079";
// 7-stop velocity LUT in HDR linear RGB (emerald → teal → cobalt → violet → magenta → coral → gold),
// indexed by normalized wind speed (`excitement ∈ [0, 1]`).
const PLASMA_LUT_STOPS = [
{ position: 0.00, color: [0.10, 0.52, 0.34, 0.70] },
{ position: 0.10, color: [0.08, 0.64, 0.68, 0.73] },
{ position: 0.22, color: [0.14, 0.38, 0.98, 0.76] },
{ position: 0.36, color: [0.44, 0.16, 0.92, 0.80] },
{ position: 0.50, color: [0.71, 0.15, 0.40, 0.84] },
{ position: 0.75, color: [1.11, 0.43, 0.14, 0.90] },
{ position: 1.00, color: [1.40, 1.16, 0.27, 0.96] },
];
// ─── §2 Shade materials & particle sprite ───────────────────────────────────
function standardMaterial(hexColor, roughness) {
const material = new StandardShadeMaterial();
material.diffuse_color.copy(Color.from_sRGB_to_linear(Color.parse(hexColor)));
material.roughness_factor = roughness;
material.metallic_factor = 0;
return material;
}
function makeMoteSprite() {
const size = 48;
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
const img = ctx.createImageData(size, size);
const data = img.data;
for (let iy = 0; iy < size; iy++) {
for (let ix = 0; ix < size; ix++) {
const x = ((ix + 0.5) / size) * 2 - 1;
const y = ((iy + 0.5) / size) * 2 - 1;
const r = Math.hypot(x, y);
const offset = (iy * size + ix) * 4;
data[offset] = 255;
data[offset + 1] = 255;
data[offset + 2] = 255;
if (r >= 1) {
data[offset + 3] = 0;
} else {
const falloff = 1 - r;
const core = Math.max(0, 1 - r * 1.65);
const alpha = Math.min(1, falloff * falloff * 0.65 + core * core * 0.55);
data[offset + 3] = Math.round(alpha * 255);
}
}
}
ctx.putImageData(img, 0, 0);
return canvas.toDataURL("image/png");
}
// ─── §3 Engine bootstrap ────────────────────────────────────────────────────
const engine = await EngineHarness.bootstrap({
configuration: (config, engine) => {
const shadeScene = EngineHarness.shadeScene(engine);
config.addSystem(new ShadedGeometrySystem(engine.graphics, shadeScene));
// Static rigid bodies for the windbreak wall and boulders (`FluidObstacle`).
const physics = new PhysicsSystem();
config.addSystem(physics);
config.addSystem(new ColliderObserverSystem(physics));
// Folds the GlobalFluidEffector into the far field and steps the
// 2-cascade 3D fluid domain on the GPU.
config.addSystem(new FluidEffectorsSystem());
config.addSystem(new GPUFluidSystem(engine.graphics, shadeScene));
config.addSystem(new GPUParticleEmitterSystem(engine.graphics, shadeScene, engine.assetManager));
},
});
await EngineHarness.buildBasics({
engine,
enableTerrain: false,
enableWater: false,
enableLights: true,
enableShadows: true,
focus: new Vector3(0, 1.5, 0),
distance: 28,
pitch: 0.88,
yaw: 0,
cameraFarDistance: 84,
showFps: false,
});
engine.entityManager.dataset.getAnyComponent(TopDownCameraController).component.distanceMax = 56;
engine.graphics.renderer.feature_automatic_exposure_enabled = false;
engine.entityManager.dataset.traverseEntities([Light], (light) => {
if (light.type.getValue() === LightType.DIRECTION) {
light.intensity.set(6);
}
});
const ecd = engine.entityManager.dataset;
// ─── §4 Ground ──────────────────────────────────────────────────────────────
{
const t = new Transform64();
t.setTranslation(0, -0.25, 0);
new Entity()
.add(t)
.add(ShadedGeometry.from(
meshlet_geometry_build_from_geometry(
make_box_geometry(FIELD_SIZE_X + 10, 0.5, FIELD_SIZE_Z + 8),
),
standardMaterial(GROUND_COLOR, 1),
))
.build(ecd);
}
// ─── §5 The GPU fluid volume ────────────────────────────────────────────────
const fluid = new GPUFluidComponent();
fluid.resolution = FLUID_RESOLUTION;
fluid.cell_size = FLUID_CELL_SIZE;
fluid.cascade_count = FLUID_CASCADES;
const fluidTransform = new Transform64();
fluidTransform.setTranslation(0, FLUID_CENTER_Y, 0);
new Entity().add(fluidTransform).add(fluid).build(ecd);
// ─── §6 The particle field (~60k GPU particles) ─────────────────────────────
//
// Particles spawn across the 18 × 12 grid where the trees stood and sample the
// GPU fluid velocity via `wind` (`SAMPLE_WIND`). Particles in the calm lee
// behind the windbreak wall and boulders glow deep forest-teal and drift
// gently, while particles in the open breeze and accelerating around/over the
// wall stretch into sunlit meadow-green and gold streaks.
function node(graph, type, inputs = {}, parameters = {}) {
const id = particle_node(graph, type, parameters);
for (const [port, source] of Object.entries(inputs)) {
particle_wire(graph, id, port, source);
}
return id;
}
const read = (graph, name) => node(graph, "particleField", {}, { name });
const write = (graph, name, value) => node(graph, "setParticleField", { value }, { name });
function randomRange(graph, min, max) {
if (min === max) return [min];
const r = node(graph, "random", {}, { components: 1 });
return node(graph, "mad", { a: r, b: [max - min], c: [min] });
}
function scaleCurve(stops) {
const slope = (a, b) => (b[1] - a[1]) / (b[0] - a[0]);
return {
keys: stops.map(([time, value], i) => ({
time,
value,
inTangent: i === 0 ? 0 : slope(stops[i - 1], stops[i]),
outTangent: i === stops.length - 1 ? 0 : slope(stops[i], stops[i + 1]),
})),
};
}
function buildPrevailingWindParticleEffect(spriteUrl) {
const layout = new ParticleLayout([
{ name: "position", components: 3 },
{ name: "velocity", components: 3 },
{ name: "streak", components: 3 },
{ name: "age", components: 1 },
{ name: "life", components: 1 },
{ name: "size0", components: 1 },
{ name: "size", components: 1 },
{ name: "color", components: 4, type: "color" },
]);
const init = new NodeGraph();
const px = randomRange(init, -SPAWN_HALF_X, SPAWN_HALF_X);
const py = randomRange(init, SPAWN_Y_MIN, SPAWN_Y_MAX);
const pz = randomRange(init, -SPAWN_HALF_Z, SPAWN_HALF_Z);
write(init, "position", node(init, "vec3", { x: px, y: py, z: pz }));
const vy = randomRange(init, 0.06, 0.16);
write(init, "velocity", node(init, "vec3", { x: [0], y: vy, z: [0] }));
write(init, "streak", [0, 0, 0]);
write(init, "age", [0]);
write(init, "life", randomRange(init, PARTICLE_LIFE_MIN, PARTICLE_LIFE_MAX));
write(init, "size0", randomRange(init, 0.032, 0.056));
write(init, "size", [0]);
write(init, "color", [0.10, 0.52, 0.34, 0]);
const update = new NodeGraph();
const dt = node(update, "builtin", {}, { id: VM_BUILTIN.DELTA_TIME });
const age = node(update, "add", { a: read(update, "age"), b: dt });
const life = read(update, "life");
write(update, "age", age);
const expired = node(update, "compare", { a: age, b: life }, { op: "ge" });
node(update, "kill", { condition: expired });
const pos = read(update, "position");
const vel = read(update, "velocity");
const rawWind = node(update, "wind", { position: pos });
const speed = node(update, "length", { x: rawWind });
const gain = node(update, "div", {
a: [0.65],
b: node(update, "mad", { a: speed, b: [0.05], c: [1.0] }),
});
const w = node(update, "scale", { v: rawWind, s: gain });
const targetVel = node(update, "add", { a: w, b: [0, 0.1, 0] });
const dragT = node(update, "saturate", {
x: node(update, "mul", { a: dt, b: [7.5] }),
});
const velNext = node(update, "mix", { a: vel, b: targetVel, t: dragT });
const posNext = node(update, "add", {
a: pos,
b: node(update, "scale", { v: velNext, s: dt }),
});
write(update, "velocity", velNext);
write(update, "position", posNext);
write(update, "streak", node(update, "scale", { v: velNext, s: [0.38] }));
const u = node(update, "saturate", {
x: node(update, "div", { a: age, b: life }),
});
const excitement = node(update, "saturate", {
x: node(update, "mul", { a: speed, b: [0.095] }),
});
const env = node(
update,
"curveLiteral",
{ t: u },
{
curve: scaleCurve([
[0.0, 0.0],
[0.12, 1.0],
[0.78, 1.0],
[1.0, 0.0],
]),
},
);
const boost = node(update, "add", {
a: [1.0],
b: node(update, "mul", { a: excitement, b: [0.35] }),
});
write(
update,
"size",
node(update, "mul", {
a: read(update, "size0"),
b: node(update, "mul", { a: env, b: boost }),
}),
);
const plasmaColor = node(
update,
"gradientRGBA",
{ t: excitement },
{ stops: PLASMA_LUT_STOPS },
);
const ageFade = node(update, "vec4", { x: [1], y: [1], z: [1], w: env });
write(
update,
"color",
node(update, "mul", { a: plasmaColor, b: ageFade }),
);
return ParticleEffect.from({
...create_particle_effect({ layout, init, update }),
texture: spriteUrl,
spawn_rate: PARTICLE_SPAWN_RATE,
prewarm: PARTICLE_LIFE_MAX,
flags: {
soft_depth: true,
blend: EMITTER_BLEND.ALPHA,
projection: EMITTER_PROJECTION.STRETCHED,
},
render: {
position: "position",
velocity: "streak",
size: "size",
color: "color",
},
});
}
new Entity()
.add(new Transform64())
.add(buildPrevailingWindParticleEffect(makeMoteSprite()))
.build(ecd);
// ─── §7 The wind + the shelter ──────────────────────────────────────────────
const wind = new GlobalFluidEffector();
wind.wind = [WIND_SPEED, 0, 0];
wind.drag = WIND_DRAG;
const effectors = new FluidEffectorsComponent();
effectors.addEffector(wind);
new Entity().add(effectors).build(ecd);
// THE WINDBREAK WALL: Static BoxShape3D body tagged with FluidObstacle.
{
const transform = new Transform64();
transform.setTranslation(WALL_X, WALL_H / 2, 0);
const body = new RigidBody();
body.kind = BodyKind.Static;
const collider = new Collider();
collider.shape = BoxShape3D.from_size(WALL_W, WALL_H, WALL_D);
const obstacle = new FluidObstacle();
obstacle.inflation = OBSTACLE_INFLATION;
new Entity()
.add(transform)
.add(body)
.add(collider)
.add(obstacle)
.add(ShadedGeometry.from(
meshlet_geometry_build_from_geometry(make_box_geometry(WALL_W, WALL_H, WALL_D)),
standardMaterial(WALL_COLOR, 0.95),
))
.build(ecd);
}
// THE BOULDERS: Static SphereShape3D bodies tagged with FluidObstacle.
const boulderMaterial = standardMaterial(BOULDER_COLOR, 0.9);
for (let i = 0; i < BOULDERS.length; i++) {
const [x, z, r] = BOULDERS[i];
const transform = new Transform64();
transform.setTranslation(x, r, z);
const body = new RigidBody();
body.kind = BodyKind.Static;
const collider = new Collider();
collider.shape = SphereShape3D.from(r);
const obstacle = new FluidObstacle();
obstacle.inflation = OBSTACLE_INFLATION;
new Entity()
.add(transform)
.add(body)
.add(collider)
.add(obstacle)
.add(ShadedGeometry.from(
meshlet_geometry_build_from_geometry(make_octahedron_geometry(r, 12)),
boulderMaterial,
))
.build(ecd);
}
// ─── §8 Per-frame: steer the wind, HUD ──────────────────────────────────────
const fpsEl = document.getElementById("fps");
const SWING_OMEGA = (2 * Math.PI) / WIND_SWING_PERIOD;
const GUST_OMEGA = (2 * Math.PI) / WIND_GUST_PERIOD;
let elapsed = 0;
let fpsWindow = 0, fpsFrames = 0;
let lastFrameMs = performance.now();
engine.graphics.on.postRender.add(() => {
const nowMs = performance.now();
const dt = Math.min((nowMs - lastFrameMs) / 1000, 0.1);
lastFrameMs = nowMs;
elapsed += dt;
const heading = WIND_SWING * Math.sin(SWING_OMEGA * elapsed);
const speed = WIND_SPEED * (1 + WIND_GUST * Math.sin(GUST_OMEGA * elapsed));
wind.wind[0] = speed * Math.cos(heading);
wind.wind[2] = speed * Math.sin(heading);
// — HUD
fpsWindow += dt;
fpsFrames++;
if (fpsWindow >= 0.5) {
fpsEl.textContent = (fpsFrames / fpsWindow).toFixed(0);
fpsWindow = 0;
fpsFrames = 0;
}
});