Particle Simulation
A fluid and particle simulator in C++: smoothed-particle hydrodynamics for the Navier-Stokes equations, with a spatial hash for neighbor search and collisions.
╌╌╌╌
A C++ simulator for fluids and particle systems. Fluids follow the Navier-Stokes equations, discretized with smoothed-particle hydrodynamics (SPH); a uniform spatial hash keeps neighbor search and collision detection near-linear as particle counts grow.
SPH represents a fluid as particles that each carry mass and sample the field around them. Any field quantity at a point is a kernel-weighted sum over nearby particles,
where is a smoothing kernel of support radius and the density at particle . Density is the same sum applied to mass, ; pressure and viscosity forces come from the gradient and Laplacian of .
Each particle obeys the momentum form of Navier-Stokes,
a balance of pressure, viscosity, and gravity. Pressure follows an equation of state from density, , which resists compression and keeps the fluid roughly incompressible.
Every kernel sum ranges only over particles within , but finding them naively is , and that search dominates the cost. Positional indexing hashes each particle into a grid of cell size ; then only the particle's own cell and the cells bordering it can hold interactions, so each query touches a constant number of cells:
- 1input: particle , cell size , table mapping cell particles
- 2; result
- 3for each cell bordering , and itself, do
- 4for each particle do
- 5if then add to result
- 6return result
The same grid detects particle collisions and propagates contact forces: particles that share or border a cell are the only ones close enough to touch, so contact resolution never compares far-apart pairs. A contact between two particles of radius is an overlap; resolution separates the pair and, if they are still approaching, reflects the normal component of their relative velocity with restitution :
- 1input: particles with radius , restitution , cell table
- 2rebuild : insert every particle into its cell
- 3for each particle do
- 4for each with do
- 5
- 6if then
- 7
- 8move and apart by along
- 9
- 10if then
- 11apply impulse along to and
References
- Project repository
- Reference notes: Spatial Data Structures
- Reference notes: Hash Tables
╌╌ END ╌╌