Real-time 2D incompressible fluid dynamics simulates liquid and gaseous flow governed by the Navier-Stokes equations. Utilizing Jos Stam's Stable Fluids algorithm (1999), the velocity field is solved across an Eulerian staggered grid using semi-Lagrangian advection, implicit diffusion, and Helmholtz-Hodge pressure projection to enforce mass conservation (zero divergence).
[01]Mathematical Architecture & Closed-Form Derivations
KaTeX Mathematical RenderIn modern computational pipelines, this mathematical structure operates at $\mathcal{O}(N)$ to $\mathcal{O}(N \log N)$ complexity per epoch. The interactive sliders above directly alter these parameter coefficients, exposing how physical stability, convergence rates, and non-linear boundaries react to real-time vector adjustments.
[02]Theoretical Foundations & Geometric Intuition
Introduction
For decades, numerical fluid simulation was restricted to scientific supercomputers because explicit time-stepping schemes were constrained by the Courant-Friedrichs-Lewy (CFL) numerical stability limit. In 1999, graphics researcher Jos Stam published the seminal paper *Stable Fluids*, introducing unconditional numerical stability via semi-Lagrangian advection and implicit Poisson pressure projection, enabling real-time interactive fluid physics in gaming and CGI.
Mathematical Derivation
1. Momentum Conservation Equation (Newton\'s 2nd Law for Continuum):
\frac{\partial \mathbf{u}}{\partial t} + (\mathbf{u} \cdot \nabla)\mathbf{u} = -\frac{1}{\rho}\nabla p + \nu \nabla^2 \mathbf{u} + \mathbf{f},
where:
• \mathbf{u} = [u, v]^T: Velocity vector field across the grid.
• (\mathbf{u} \cdot \nabla)\mathbf{u}: Non-linear convective advection term (fluid transporting its own velocity).
• -\frac{1}{\rho}\nabla p: Pressure gradient force driving flow from high to low pressure.
• \nu \nabla^2 \mathbf{u}: Viscous diffusion term (viscosity smoothing velocity differences).
• \mathbf{f}: External body forces (gravity, mouse cursor drag forces).
2. Incompressibility & Mass Conservation (Continuity Equation):
\nabla \cdot \mathbf{u} = \frac{\partial u}{\partial x} + \frac{\partial v}{\partial y} = 0.
Fluid volume cannot compress or expand; the velocity field must remain divergence-free everywhere.
3. Jos Stam\'s Fractional Step Method:
Stam decomposes the simulation into four sequential modular operators per time step dt:
\mathbf{u}_0 \xrightarrow{\text{Add Forces}} \mathbf{u}_1 \xrightarrow{\text{Advect}} \mathbf{u}_2 \xrightarrow{\text{Diffuse}} \mathbf{u}_3 \xrightarrow{\text{Project}} \mathbf{u}_4.
• Semi-Lagrangian Advection: To update velocity at cell x, trace a virtual particle backward in time: x_{prev} = x - \mathbf{u}(x) dt, and interpolate the velocity at x_{prev} via bilinear interpolation. Because interpolation is bounded by neighboring values, this step is unconditionally stable for any arbitrary dt.
• Helmholtz-Hodge Pressure Projection: Any vector field \mathbf{w} can be uniquely decomposed into an divergence-free field \mathbf{u} and the gradient of a scalar potential \nabla p: \mathbf{w} = \mathbf{u} + \nabla p. Taking the divergence yields the Poisson pressure equation:
\nabla^2 p = \nabla \cdot \mathbf{w}.
Solving this sparse linear system using Jacobi or Gauss-Seidel relaxation yields p, and subtracting \nabla p from \mathbf{w} leaves the strictly mass-conserving velocity \mathbf{u} = \mathbf{w} - \nabla p.
Industry Applications
• Video Game Particle & Smoke FX: Real-time interactive smoke, liquid splashing, and atmospheric fog (Unreal Engine Niagara, Unity VFX Graph).
• Aerospace Aerodynamics & Drag Reduction: Simulating laminar airflow and turbulent boundary layer vortices over race car splitters and aircraft wings.
• Industrial Mixing & Chemical Reactor Optimization: Modeling multi-phase viscosity blending and thermal convection in chemical manufacturing.
• Movie Visual Effects (VFX): Hollywood liquid and explosive pyrotechnic simulations in Houdini, Bifrost, and Blender Mantaflow.
When To Use
[03]Interactive Laboratory Walkthrough
Hands-On ExperimentsClick and drag the cursor across the canvas to inject colorful dye pigments and high-velocity vortex currents into the real-time fluid grid.
Experiment 01: Creating Kelvin-Helmholtz Shear Vortices
Watch the shear velocity layer roll up into beautiful spinning spiral vortices.
Experiment 02: Modulating Fluid Viscosity
Notice how high viscosity damps out turbulent swirling motion rapidly, causing dye to behave like thick honey or cold syrup.
Experiment 03: Divergence-Free Incompressibility
Watch the fluid cleanly deflect sideways without accumulating or disappearing, visually verifying the Poisson pressure projection.
[04]Computational Fluid Simulation Matrix
| Simulation Paradigm | Grid / Spatial Type | Numerical Stability | Handles Free Surfaces | Primary Industry Use Case |
|---|---|---|---|---|
| Stable Fluids (Stam) | Eulerian Fixed Staggered Grid | Unconditionally Stable | Poorly (Requires Level-Set) | Real-time game smoke & interactive web canvas |
| SPH (Smoothed Particle) | Lagrangian Meshless Particles | Conditionally Stable (CFL bound) | Naturally Excellent | Splashing liquid droplets & breaking water waves |
| FLIP / PIC Hybrid | Hybrid Grid + Particles | Conditionally Stable | Industry Standard | High-end movie VFX liquids (Houdini, Bifrost) |
| Lattice Boltzmann (LBM) | Discrete Velocity Lattice | Conditionally Stable | Moderate | Aerodynamic wind tunnel testing & porous rock flow |
| Finite Volume Method (FVM) | Unstructured 3D Polyhedral Mesh | Conditionally Stable | Complex Interface Tracking | Aerospace engineering CFD (ANSYS Fluent, OpenFOAM) |
[05]Critical Pitfalls, Numerical Traps & Engineering Solutions
Semi-Lagrangian advection relies on bilinear interpolation at every time step, which acts as an implicit low-pass filter, rapidly damping out tiny swirls and making water look like oil.
Running too few Jacobi relaxation iterations (< 10) to solve the Poisson pressure equation leaves residual divergence, causing fluid to visibly lose mass or compress like an elastic sponge.
Failing to enforce no-slip (u = 0, v = 0) or free-slip boundary conditions on obstacle borders causes fluid to bleed through walls.
[06]Multi-Platform Production Implementation
Python • NumPy • PyTorch • Vectorizedimport numpy as np
class FluidGrid2D:
def __init__(self, size=64, dt=0.1, diff=0.0001, visc=0.0001):
self.size = size
self.dt = dt
self.diff = diff
self.visc = visc
self.u = np.zeros((size, size))
self.v = np.zeros((size, size))
self.density = np.zeros((size, size))
def project(self, u, v):
"""Helmholtz-Hodge divergence-free projection via Jacobi relaxation."""
N = self.size
p = np.zeros((N, N))
div = np.zeros((N, N))
# Compute divergence of current velocity field
div[1:-1, 1:-1] = -0.5 * (u[2:, 1:-1] - u[:-2, 1:-1] +
v[1:-1, 2:] - v[1:-1, :-2]) / N
# 20 iterations of Jacobi relaxation for Poisson equation
for _ in range(20):
p[1:-1, 1:-1] = (div[1:-1, 1:-1] + p[2:, 1:-1] + p[:-2, 1:-1] +
p[1:-1, 2:] + p[1:-1, :-2]) / 4.0
# Subtract pressure gradient to enforce zero divergence
u[1:-1, 1:-1] -= 0.5 * N * (p[2:, 1:-1] - p[:-2, 1:-1])
v[1:-1, 1:-1] -= 0.5 * N * (p[1:-1, 2:] - p[1:-1, :-2])
return u, v
grid = FluidGrid2D(size=64)
grid.u[30:35, 30:35] = 5.0 # Inject horizontal velocity pulse
grid.u, grid.v = grid.project(grid.u, grid.v)
div_after = np.max(np.abs(grid.u[2:, 1:-1] - grid.u[:-2, 1:-1] + grid.v[1:-1, 2:] - grid.v[1:-1, :-2]))
print(f"Residual Divergence after projection: {div_after:.6f}")
[07]Industrial AI & Engineering Applications
Applied in obstacle avoidance, feature spatial registration, and SLAM trajectory mapping.
Governs forward propagation, backpropagation gradient descent, and latent space manifold routing.
Used across high-frequency algorithmic arbitrage, physics game engines, and structural engineering simulations.
[09]Frequently Asked Technical Questions
What is the physical meaning of the Courant-Friedrichs-Lewy (CFL) condition?
The CFL condition states that in explicit numerical simulation of partial differential equations, the simulation time step dt must be smaller than the time it takes for fluid information to travel across a single grid cell: dt ≤ dx / |u_max|. If dt violates this bound, numerical errors explode exponentially. Jos Stam's semi-Lagrangian advection bypasses the CFL condition by tracing backward, guaranteeing stability for arbitrarily large time steps.
What is the difference between Eulerian and Lagrangian fluid simulation?
In a Lagrangian approach (particle-based), the observer follows individual fluid particles as they move through space (like tracking individual water molecules). In an Eulerian approach (grid-based), the observer stays at fixed points in space and monitors how fluid velocity, pressure, and density change as fluid flows through those fixed grid cells (like an anemometer measuring wind speed).
Why must the divergence of the velocity field be equal to zero?
According to Gauss's Divergence Theorem, the divergence ∇·u represents the net volume flux of fluid exiting an infinitesimal volume. In an incompressible fluid (such as water or low-speed air), the volume of fluid entering any region must precisely equal the volume exiting. A non-zero divergence would imply that mass is being spontaneously created (positive divergence) or destroyed (negative divergence).
What is Vorticity Confinement and why is it needed?
Because numerical advection across discrete grids introduces artificial numerical dissipation (blurring), small swirling vortices lose their energy and die out unnaturally. Vorticity confinement computes the curl of the velocity field (ω = ∇ × u), locates vortex centers, and applies a tiny corrective artificial force in the direction of spin, preserving crisp swirling eddies in smoke and fire.