WebGL Fluid Simulation from Scratch
The Goal
Implement a real-time 2D fluid simulation that runs in the browser. The user can click and drag to push dye through the fluid, watching it swirl and dissipate. Everything runs on the GPU via WebGL.
The Navier-Stokes Equations
At the heart of fluid simulation are two partial differential equations:
- Conservation of mass — fluid can't appear or disappear
- Conservation of momentum — forces cause acceleration
In practice, we solve these in discrete steps on a grid: advection, diffusion, pressure projection, and forcing.
GPU Implementation
The fluid state lives in floating-point textures. Each simulation step runs as a fragment shader that reads from the current state and writes to the next. A separate visualization shader maps the dye field to colors.
Mouse Forcing
The mouse injects both dye and velocity. Click to add a burst of color; drag to push the surrounding fluid. The velocity dissipates over several seconds, creating natural-looking flow patterns.