How Fluid Simulations Work: The Math and Physics Behind Digital Water
A deep dive into the computational physics that powers realistic fluid simulations in your browser, from the Navier-Stokes equations to GPU-accelerated rendering.
The Beauty and Complexity of Fluids
Fluids are among the most visually captivating phenomena in nature. From ocean waves crashing against cliffs to cream swirling in coffee, the behavior of liquids and gases produces endlessly fascinating patterns and motions. Simulating this behavior in a computer is one of the grand challenges of computational physics — and one of the most rewarding, because even approximate simulations can produce stunningly beautiful results.
The interactive fluid simulations you can play with on OddlySatisfying and similar platforms are the result of decades of research in computational fluid dynamics (CFD), a field that spans physics, mathematics, and computer science. What makes modern browser-based fluid simulations remarkable is that they achieve visually convincing results in real time, running at 60 frames per second on consumer hardware — a feat that would have required a supercomputer just twenty years ago.
Understanding how these simulations work requires a journey through some of the most elegant mathematics in physics. But do not worry — while the underlying equations are complex, the core concepts are intuitive and accessible. By the end of this article, you will have a deeper appreciation for the computational magic happening behind every swirl and splash in your browser.
The Navier-Stokes Equations
At the heart of fluid simulation are the Navier-Stokes equations, a set of partial differential equations that describe how the velocity field of a fluid evolves over time. Named after Claude-Louis Navier and George Gabriel Stokes, who independently derived them in the 19th century, these equations are so fundamental to physics that proving whether smooth solutions always exist is one of the seven Millennium Prize Problems, with a one million dollar reward for a solution.
The Navier-Stokes equations express three fundamental principles. First, conservation of momentum: the fluid accelerates in response to pressure gradients, viscous forces, and external forces like gravity. Second, conservation of mass (incompressibility): for liquids, the fluid cannot be compressed, meaning that the total volume entering any region must equal the total volume leaving it. Third, the relationship between pressure and velocity: pressure adjusts to ensure that the incompressibility condition is satisfied.
In mathematical terms, the momentum equation states that the rate of change of velocity at any point equals the sum of advection (the fluid carrying itself along), pressure gradient forces, viscous diffusion, and external forces. The incompressibility condition states that the divergence of the velocity field is zero — meaning there are no sources or sinks of fluid.
Solving these equations exactly is generally impossible for anything but the simplest cases. Instead, computational methods approximate the solution by discretizing space and time — dividing the continuous fluid into a grid of cells and advancing the simulation in small time steps.
Grid-Based vs. Particle-Based Methods
There are two main approaches to simulating fluids computationally: grid-based (Eulerian) methods and particle-based (Lagrangian) methods. Each has strengths and weaknesses, and many modern simulations use hybrid approaches that combine elements of both.
Grid-based methods divide the simulation space into a fixed grid of cells. Each cell stores fluid properties like velocity, pressure, and density. The Navier-Stokes equations are solved on this grid using numerical methods. The most popular grid-based approach for real-time applications is the Stable Fluids method developed by Jos Stam in 1999, which guarantees numerical stability regardless of the time step size — a crucial property for interactive applications where frame rates may vary.
The Stable Fluids algorithm proceeds in four steps each frame. First, external forces are applied (like the user's mouse input). Second, advection moves the velocity field along itself using a technique called semi-Lagrangian advection, which traces each grid cell backward in time to find where its fluid came from. Third, diffusion spreads the velocity to simulate viscosity. Fourth, projection enforces the incompressibility condition by solving a pressure equation and subtracting the pressure gradient from the velocity field.
Particle-based methods, such as Smoothed Particle Hydrodynamics (SPH), represent the fluid as a collection of discrete particles. Each particle carries properties like position, velocity, and density, and interacts with nearby particles through kernel functions. SPH methods naturally handle free surfaces, splashing, and mixing, making them popular for visual effects. However, they can be more computationally expensive and may produce noisy results without careful tuning.
Many of the fluid simulations you encounter on the web use grid-based methods because they are well-suited to GPU acceleration — the regular grid structure maps naturally onto the parallel processing architecture of graphics hardware.
GPU Acceleration: The Key to Real-Time Performance
The reason you can interact with fluid simulations in real time in your browser is GPU acceleration. Modern graphics processing units contain thousands of small processing cores that can perform calculations in parallel, making them ideal for the kind of regular, data-parallel computations that fluid simulation requires.
In a grid-based fluid simulation, each cell of the grid can be updated independently (or nearly so) in each step of the algorithm. This means that a GPU with 1,000 cores can update 1,000 grid cells simultaneously, achieving speedups of 100x or more compared to a single CPU core. WebGL, the browser API for accessing GPU hardware, allows JavaScript code to run custom shader programs on the GPU, enabling real-time fluid simulation directly in the browser.
The typical implementation uses framebuffer objects (FBOs) to store the fluid state as textures on the GPU. Each step of the simulation algorithm is implemented as a fragment shader that reads from one texture and writes to another. The velocity field, pressure field, and dye (color) field are each stored as separate textures, and the simulation alternates between reading and writing textures (a technique called ping-pong buffering) to avoid reading and writing the same data simultaneously.
This GPU-based approach is what makes it possible to simulate fluids on grids of 512x512 or even 1024x1024 cells at 60 frames per second in a web browser — a remarkable achievement that brings research-grade fluid simulation to anyone with a modern web browser.
Making It Interactive: From Simulation to Experience
A fluid simulation becomes an interactive experience when user input is incorporated into the simulation loop. In most interactive fluid experiments, mouse or touch input is translated into forces that are applied to the fluid at the beginning of each simulation step.
When you drag your mouse across a fluid simulation, the application calculates the velocity of your mouse movement and applies a force to the fluid in the corresponding direction at the corresponding location. This force is typically implemented as a Gaussian splat — a smooth, bell-shaped force distribution centered on the mouse position — which produces natural-looking fluid disturbance without sharp discontinuities.
Color (dye) is typically injected along with the force, so that your mouse movements leave colorful trails in the fluid. The dye is advected (carried along) by the fluid velocity, creating the swirling, mixing patterns that make fluid simulations so visually appealing. Different implementations use different strategies for dye injection — some use a fixed color, others cycle through a rainbow palette, and some use the mouse velocity to determine the color.
Additional interactive features might include the ability to place obstacles in the fluid, adjust viscosity and diffusion parameters, change the simulation resolution, or switch between different visualization modes (velocity magnitude, pressure, vorticity, etc.). These controls allow users to explore the rich parameter space of fluid dynamics and discover how different physical properties affect fluid behavior.
Beyond Simple Fluids: Advanced Techniques
While the basic Stable Fluids algorithm produces convincing results, many advanced techniques have been developed to improve visual quality and physical accuracy.
Vorticity confinement is a technique that counteracts the numerical dissipation inherent in grid-based methods. Without it, small-scale vortices and turbulent details tend to disappear over time, making the fluid look overly smooth. Vorticity confinement detects areas of high rotation and adds a small force to amplify them, preserving the fine-scale turbulent structures that make fluid motion look realistic.
Multi-phase simulation allows different fluids to coexist and interact — for example, oil and water, or hot and cold fluids with different densities. These simulations produce fascinating visual effects as the different fluids push against each other, form boundaries, and create complex mixing patterns.
Free surface simulation tracks the boundary between fluid and air, enabling effects like splashing, dripping, and pouring. This is significantly more complex than simulating a fully filled domain, as the boundary conditions at the free surface must be carefully handled to prevent artifacts.
Coupling with rigid body physics allows solid objects to float on, sink in, or be pushed by the fluid, creating interactive scenarios where users can drop objects into the fluid and watch them interact. This requires solving the fluid equations and the rigid body equations simultaneously, with forces exchanged between the fluid and the solid objects at each time step.
The Future of Browser-Based Fluid Simulation
The future of browser-based fluid simulation is bright, driven by advances in both hardware and web standards. WebGPU, the next-generation graphics API for the web, provides more direct access to GPU compute capabilities than WebGL, enabling more efficient and flexible simulation algorithms. With WebGPU, developers can use compute shaders for simulation steps that do not involve rendering, avoiding the overhead of the graphics pipeline.
Machine learning is also beginning to influence fluid simulation. Neural network-based approaches can learn to approximate fluid behavior from training data, potentially achieving real-time performance for simulations that would be too expensive to compute directly. While these approaches are still in their early stages, they show promise for enabling more complex and realistic fluid effects in interactive applications.
As mobile devices continue to increase in processing power, the gap between desktop and mobile fluid simulation quality will continue to narrow. Already, many fluid simulations run smoothly on recent smartphones and tablets, and this trend will only accelerate as mobile GPUs become more capable.
The combination of advancing hardware, improving web standards, and innovative algorithms means that the interactive fluid simulations of the future will be even more beautiful, more realistic, and more responsive than what we can achieve today. And they will all be accessible to anyone with a web browser — no downloads, no installations, just pure, satisfying interaction.
Ready to explore?
Discover hundreds of interactive visual experiments on OddlySatisfying. From fluid simulations to particle generators, every experience is free and runs directly in your browser.
Explore Experiments →