Fluid simulation

A volumetric incompressible-flow solver on a staggered grid, run through ECS - fluid volumes are components, effectors stir them, and gameplay reads the velocity field back out.

Meep ships a real-time volumetric fluid solver - incompressible flow on a MAC (staggered) grid, with stable semi-Lagrangian or MacCormack transport and an exact pressure projection. It’s built for gameplay fluid: wind over a field, the wake of something fast, smoke drifting through a corridor - a velocity field your entities can both stir and read.

Like the rest of the engine, you use it through ECS: a volume is a component, the simulation is a system, and sources of motion are effector objects on entities.

The two-minute version

import { FluidComponent } from "@woosh/meep-engine/src/engine/physics/fluid/ecs/FluidComponent.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 { FluidSystem } from "@woosh/meep-engine/src/engine/physics/fluid/ecs/FluidSystem.js";
import { WakeFluidEffector } from "@woosh/meep-engine/src/engine/physics/fluid/effector/WakeFluidEffector.js";

// once, at startup - the effectors' system first
em.addSystem(new FluidEffectorsSystem());
em.addSystem(new FluidSystem());

// a static volume of air over the scene
const fluid = new FluidComponent();
fluid.field.setResolution(51, 11, 34);          // cells
fluid.field.build();
fluid.cell_size = 0.6;                          // world units per cell
fluid.origin = [-15, 0, -10];                   // world position of cell (0,0,0)
new Entity().add(fluid).build(ecd);

// something that stirs it: a wake towed by a moving entity
const wake = new WakeFluidEffector();
wake.radius = 2;                                // world units
const effectors = new FluidEffectorsComponent();
effectors.addEffector(wake);
new Entity().add(transform).add(effectors).build(ecd);   // the moving thing

// something that reads it: sample anywhere, in world space
const v = new Float32Array(3);
fluid.sampleVelocityAtWorld(v, x, y, z);

That’s the whole loop: the system steps every enabled volume on the fixed timestep - effector splats, advection, pressure projection - and anything in your game can sample the result. The wake-field example is exactly this: one volume, one wake effector on a flying ball, and 140 trees bending to sampleVelocityAtWorld every frame.

The pieces

FluidComponent is the volume: a velocity grid plus its placement in the world. The mapping is uniform and axis-aligned - origin is the world position of cell (0,0,0), cells are cell_size apart. Placement comes in two flavours:

  • Static - the entity has no Transform64; you set origin once and the system never touches it.
  • Moving - pair the component with a Transform64 and the system re-anchors the grid to the entity every fixed tick, shifting the field by whole cells so the fluid appears to stay put in world space while the grid follows the entity. A hysteresis deadband stops a transform sitting on a cell boundary from re-shifting every frame. Use this for a volume that follows the player through a large world.

FluidEffectorsComponent holds the things that stir. Effectors are deliberately decoupled from any specific volume: the system gathers all of them and applies each to every field whose bounds it overlaps (a cheap AABB broad-phase filters the rest). Pair the component with a Transform64 and position-bearing effectors follow the entity automatically.

FluidEffectorsSystem gives every effector its per-tick life, once a fixed step however many fluid systems read them: it syncs position-bearing effectors from their entity’s Transform64, advances each effector, and folds every GlobalFluidEffector into one far field. FluidSystem and WorkerFluidSystem require it; register it first.

FluidSystem is the pump. It runs on fixedUpdate - fluid stability and the warm-started pressure solve both want a constant dt - and owns one simulator that services every volume.

Effectors

EffectorWhat it does
WakeFluidEffectorSplats the momentum of a moving source along its swept path - the wake of an agent passing through air or water. Transform-managed when its entity has a Transform64; works at any radius down to sub-cell.
ImpulseFluidEffectorA velocity splat in a spherical region with a smooth quadratic falloff - fans, jets, point explosions.
GlobalFluidEffectorThe atmosphere: every cell integrates dv/dt = force + drag · (wind − v), with turbulence carried on top of the wind (turbulence_intensity, turbulence_length - see the scene’s wind). A bare force is a body force (note it grows without bound unless something dissipates it); wind + drag gives relaxation toward an ambient flow with a real terminal velocity. Globals act only through the far field FluidEffectorsSystem folds them into, so several act as one.

One sharp edge worth knowing: a teleporting wake source must call wake.reset_trail() after the jump, or the effector treats the teleport as one giant swept segment and splats a wall of momentum across the whole field. (The wake-field example does this on every loop wrap.)

Custom effectors are a small class: extend AbstractFluidEffector, implement apply(field, dt, world_to_grid) and getBoundingBox(out).

The scene’s wind

The far field is also the scene’s wind for everything that is not a CPU field. GPUFluidSystem (engine/graphics3/GPUFluidSystem.js) publishes it every frame as the scene’s wind field, which water waves, cloth, particles and volumetric fog sample. Without a domain it publishes the far field alone; an entity with a GPUFluidComponent and a Transform64 adds nested GPU fluid cascades around that entity, forced by the scene’s wake, impulse and vortex effectors and FluidObstacles.

import { GPUFluidSystem } from "@woosh/meep-engine/src/engine/graphics3/GPUFluidSystem.js";
import { GlobalFluidEffector } from "@woosh/meep-engine/src/engine/physics/fluid/effector/GlobalFluidEffector.js";

em.addSystem(new FluidEffectorsSystem());
em.addSystem(new GPUFluidSystem(engine.graphics, scene));

const weather = new GlobalFluidEffector();
weather.wind = [4, 0, 0];               // m/s
weather.drag = 1;                       // per second: how quickly the air returns to `wind`
weather.turbulence_intensity = 0.15;    // eddies' rms, as a share of the mean speed
const effectors = new FluidEffectorsComponent();
effectors.addEffector(weather);
new Entity().add(effectors).build(ecd);

Mean and turbulence

The far field is a mean wind plus a field of eddies the mean carries along. FluidEffectorsSystem folds every global into it once a tick: the drags sum, and the winds, the turbulence intensities and the length scales each fold to their drag-weighted mean, so several globals act as one whatever order they are in. The mean relaxes toward the folded wind at the summed drag; a scene that starts with its globals starts in steady state.

FieldDefaultMeaning
turbulence_intensity0The eddies’ rms on each axis as a share of the mean speed. 0 is no turbulence; near-ground wind over grass and crops measures 0.15 to 0.2. A far field with no mean speed has no turbulence.
turbulence_length58.6The von Kármán length scale L, in world units, above 0. The most energetic eddies are about 4.05·L long. The eddies come from one repeating tile, 16·L across and 4·L up, holding wavelengths down to L/4.

The eddies are isotropic turbulence, frozen and carried by the mean wind (Taylor’s hypothesis): a gust travels downwind at the wind’s speed, and two points a few metres apart feel it at different times. A smaller turbulence_length reaches down to a canopy’s own eddies at the cost of a shorter repeat. Changing it rescales the eddies about the world’s origin, so the air jumps: it is a property of a scene’s weather, set once. How far the mean has carried the eddies is the system’s own state and starts at zero, so a scene loaded from a save starts the eddies over.

Who sees the turbulence: every GPU reader of the wind field, both cloth winds, and the GPU fluid, which steps every cascade toward the whole far field, so the ground, a wall or a canopy shapes the eddies. CPU fields (FluidSystem, WorkerFluidSystem) are brought to the mean alone.

gpu_fluid_system.far_field(out) answers the far field’s mean in m/s, and gpu_fluid_system.far_field_at(out, x, y, z) the far field at a world point, its turbulence included. Both are synchronous and deterministic, with or without a device - what gameplay should read. request(...) reads a lattice of the published wind back from the GPU, a frame or more late, for presentation only.

A ClothSystem reads this wind by default: ClothGPUFluidWind while the scene has a GPU fluid domain, otherwise ClothFluidWind over the CPU fields and the far field outside them, and no air when there is neither. Both read the far field at the point they sample, turbulence included. Assigning cloth_system.wind overrides the choice; null keeps cloth out of the air.

GlobalFluidEffector serializes through GlobalFluidEffectorSerializationAdapter at version 1: force, wind, drag, turbulence_intensity and turbulence_length. A host that loads version-0 streams registers GlobalFluidEffectorSerializationUpgrader_0_1 (engine/physics/fluid/effector/GlobalFluidEffectorSerializationUpgrader_0_1.js) beside the adapter.

Obstacles

An entity with a FluidObstacle (engine/physics/fluid/ecs/FluidObstacle.js), a Collider, a RigidBody and a Transform64 stands in the wind: its collider’s shape is the obstacle and its body’s velocity is what the air takes at it. inflation (world units, default 0) grows or shrinks the shape.

drag (per metre, default 0) says how it stops the wind. At 0 the obstacle is solid. Above 0 it is porous: the air passes through it and is slowed toward its velocity by drag · |u − v| · (u − v) each second, u the air’s velocity and v the obstacle’s. For something made of leaves or blades - a field of grass, a crop, a hedge, the crown of a tree - it is their drag coefficient times their one-sided area per cubic metre of the volume. Only the GPU fluid has porous obstacles; FluidObstacleSystem, which voxelizes obstacles into CPU fields, leaves them out.

Reading the field

sampleVelocityAtWorld(out, x, y, z) returns trilinearly-interpolated velocity in grid cells per second, deliberately not rescaled by cell_size: read-side consumers like vegetation sway and dust drift want a consistent “wind strength” regardless of grid resolution. Multiply by cell_size if you need world-units-per-second. There’s also sampleScalarAtWorld(name, x, y, z) for passive scalars (smoke density, dye) declared on the field with field.addScalar(name) before build().

Reading is cheap - a few hundred samples per frame is nothing - and it’s the intended coupling point between the simulation and your game: trees bend, particles drift, cloth flutters, all without feeding anything back into the solver.

Tuning the simulator

The system’s simulator is shared by all volumes; its knobs are engine-level:

const sim = em.getSystem(FluidSystem).simulator;
sim.velocity_damping = 1.5;       // exponential decay, per second - gusts die back to calm
sim.advection_scheme = AdvectionScheme.SEMI_LAGRANGIAN;   // or MACCORMACK (default)
sim.vorticity_confinement = 0;    // ε, per second - sharpens vortex cores; adds energy

Guidance that took us some trial and error in the wake-field example:

  • velocity_damping is the knob for “how far does a disturbance travel”. The solver’s incompressible projection has no propagating pressure wave - what travels is the shed vortices, and damping decides how long they live. 0 (the default) never settles under sustained forcing.
  • advection_scheme: MacCormack (default) is second-order and nearly energy-conserving - great for smoke plumes, but sustained stirring keeps ricocheting around the volume. Semi-Lagrangian smears small structures away, which for ambience-style wind is a feature: the gust passes, the field calms.
  • vorticity_confinement re-sharpens vortices that coarse grids smear. On the MAC grid it’s rarely needed - the staggered discretization already preserves rotation well - and pairing it with low damping keeps a field churning indefinitely. Reach for it for visual smoke, not gameplay wind.

Scalars: velocity_diffusion_rate / scalar_diffusion_rate add physical diffusion; the pressure solver can be switched from SOR to preconditioned conjugate-gradient (pressure_solver = PressureSolver.MICPCG) for large grids.

Sizing and cost

The solver is pure JavaScript and steps on the fixed timestep, so budget by cell count: the wake-field example runs a 51×11×34 grid (~19k cells) alongside rendering, trails, and 140 sampling consumers without drama. Coarse grids are usually the right call - gameplay reads the field through its consumers (bending trees, drifting particles), which forgive far lower resolution than direct volumetric rendering would. Solid cells (field.setSolidAt) let flow route around level geometry.

For splashy, free-surface liquids - water you can pour, mud, granular material - the grid solver is the wrong tool; that’s the domain of the separate MLS-MPM material-point solver under engine/physics/mls-mpm/.

Running the solve off-thread

WorkerFluidSystem is a drop-in alternative to FluidSystem that moves the expensive half of the step - diffusion, projection, transport, scalars - onto a worker thread. It’s built on WorkerSystem, so the field lives in a SharedArrayBuffer the worker steps in place: nothing is copied, and a fixed-step gate keeps the simulation deterministic.

import { WorkerFluidSystem } from "@woosh/meep-engine/src/engine/physics/fluid/ecs/WorkerFluidSystem.js";
import { makeFluidWorker }   from "@woosh/meep-engine/src/engine/physics/fluid/ecs/makeFluidWorker.js";

fluid.field.shared_memory = true;   // before build()
fluid.field.build();

em.addSystem(new FluidEffectorsSystem());
em.addSystem(new WorkerFluidSystem({ worker_factory: makeFluidWorker }));

Re-anchoring, the AABB broad-phase, and effector.apply(...) stay on the main thread, as does FluidEffectorsSystem’s effector sync - effectors are arbitrary user classes, and keeping them here is what makes the swap transparent. The worker runs the same simulator.step over the same data in the same order, so results are bit-for-bit identical to FluidSystem’s.

What changes:

  • The page must be cross-origin isolated (Cross-Origin-Opener-Policy: same-origin + Cross-Origin-Embedder-Policy: require-corp), or SharedArrayBuffer doesn’t exist and startup throws.
  • The worker owns the field outside the fixed pass. Reading a field from update() or at render time is not supported - which rules out exactly the render-time sampleVelocityAtWorld reads (vegetation sway, dust drift) that most scenes use fluid for. Systems that touch fields must be registered before this one so they run earlier in the fixed pass.
  • Results lag by one tick: at tick T the field holds step T - 1. The sequence of states is unchanged, it’s observed one tick later.
  • A newly linked field isn’t stepped until the worker acknowledges it (a cold-plane round trip - at least one tick, in practice a few). It’s still re-anchored in that window.

So: reach for it when fluid is consumed inside the fixed pass and the pressure solve is your frame budget’s problem. Stay on FluidSystem when anything samples the field from rendering - which today is most scenes, including the wake-field example.

  • Wake field example - the full loop: volume, wake effector, 140 read-side consumers
  • Physics overview - the rigid-body side of the physics package
  • Source: engine/physics/fluid/ - FluidSimulator.js carries extensive doc comments on every knob