A real-time 3D gravitational N-body simulation implemented in C++ with an interactive educational visualization of the Barnes-Hut algorithm.
๐ Features
- Algorithm Walkthrough Mode: Step-by-step visual demonstration of how Barnes-Hut algorithm works
- 4 Educational Modes:
- Brute Force O(nยฒ): Visualize all pairwise particle interactions
- Octree Construction: Watch the octree being built step-by-step as particles are added
- Octree Structure: Explore the complete hierarchical tree structure
- Barnes-Hut Calculation: See how the algorithm approximates forces using the octree
- 2D QuadTree Demo: Interactive 2D visualization of spatial partitioning
- Multiple Computation Methods:
- CPU Brute Force O(nยฒ) - Direct pairwise calculation
- Barnes-Hut O(n log n) - Optimized octree approximation
- 5 Astrophysical Scenarios:
- Grid (simple 3D grid for testing)
- Binary Stars (orbital dynamics)
- Big Bang (explosive particle expansion)
- Stable Globular Cluster (virial equilibrium)
- Keplerian Disk (protoplanetary disks)
- Black Hole Accretion Disk
- Galaxy Collision (two galaxies colliding)
| Keplerian Disk | Big Bang |
|---|---|
![]() |
![]() |
- Real-time method switching (Brute Force โ Barnes-Hut)
- Adjustable theta parameter for accuracy tuning
- Simulation speed control (1x-10x)
- Particle trails visualization
- Full 3D camera controls (rotate, pan, zoom)
- Progressive octree building demonstration
- UI overlay toggle
๐ How It Works
The N-body problem involves simulating the gravitational interactions between N particles. Each particle exerts a gravitational force on every other particle according to Newton's law of gravitation.
The naive approach calculates forces between every pair of particles:
- For N particles, requires Nร(N-1)/2 calculations
- Exact but becomes extremely slow as N increases
- 1,000 particles = 499,500 calculations per timestep!
An intelligent approximation that groups distant particles:
-
Build Octree: Divide 3D space into a hierarchical tree structure
- Root node contains all particles
- Recursively subdivide into 8 octants (children)
- Stop when each cell contains โค1 particle
-
Calculate Center of Mass: For each node, compute:
- Total mass of all particles in that region
- Center of mass position
-
Force Calculation: For each particle:
- Traverse the octree from root
- If a node is "far enough" (size/distance < ฮธ), treat all its particles as a single point mass
- If too close, recurse into children
- This reduces calculations from O(nยฒ) to O(n log n)
-
Time Integration: Update particle positions and velocities using Euler method
Controls the accuracy-speed tradeoff:
- Low ฮธ (0.3-0.5): More accurate, closer to brute force
- High ฮธ (1.0-2.0): Faster, more approximation
- Default: 0.7
๐ Project Structure
nbody/
โโโ src/
โ โโโ algorithms/
โ โ โโโ octree3d.cpp # Barnes-Hut 3D (flat vector, implicit indexing)
โ โ โโโ quadtree2d.cpp # Barnes-Hut 2D (educational demo)
โ โโโ demos/
โ โโโ main.cpp, simulation.cpp, renderer.cpp, scenarios.cpp, menu.cpp
โ
โโโ include/
โ โโโ algorithms/
โ โโโ demos/
โ โโโ particle.h, simulation.h, renderer.h, scenarios.h, menu.h
โ
โโโ CMakeLists.txt, build.sh, run.sh
๐ ๏ธ Libraries & Dependencies
What it is: A simple and easy-to-use library to enjoy videogames programming
What it provides:
- 3D rendering (spheres, lines, cubes for visualization)
- Camera system (perspective projection, orbit controls)
- Input handling (mouse, keyboard)
- Text rendering for UI
Installation (Linux):
# Ubuntu/Debian - Install raylib dependencies
sudo apt install libasound2-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev libglu1-mesa-dev libxcursor-dev libxinerama-dev libwayland-dev libxkbcommon-devWhat it is: Cross-platform build system generator
๐ Quick Start
# Ubuntu/Debian - Install build tools and raylib dependencies
sudo apt install cmake g++ libasound2-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev libglu1-mesa-dev libxcursor-dev libxinerama-dev libwayland-dev libxkbcommon-dev# Make scripts executable (first time only)
chmod +x build.sh run.sh
# Build
./build.sh
# Run
./run.sh# Create build directory
mkdir build
cd build
# Configure with CMake
cmake .. -DCMAKE_BUILD_TYPE=Release
# Build
make
# Run
./nbody๐ฎ Controls
- Left Click + Drag: Rotate camera
- Mouse Wheel: Zoom in/out
- Number keys (1-7): Select scenario
- A: 3D Octree Demo
- B: 2D QuadTree Demo
- M: Toggle method (Brute Force โ Barnes-Hut)
- T: Toggle trails
- H: Hide UI
- R: Reset
- Q: Return to menu
- +/-: Theta parameter - Lower values = more accurate but slower, higher = faster but less accurate
- UP/DOWN: Simulation speed (1x-10x) - Run multiple physics steps per frame for faster evolution
- [/]: Tree rebuild interval - How often the octree is reconstructed (lower = more accurate, higher = faster)
- SPACE: Step through demonstration / Add next particle
- 1-4: Switch visualization mode (3D Octree Demo only)
- R: Reset
๐ Performance Comparison
For 1,000 particles:
| Method | Calculations per Frame | Speedup |
|---|---|---|
| Brute Force | ~500,000 | 1x |
| Barnes-Hut (ฮธ=0.7) | ~15,000 | ~33x |
The Barnes-Hut algorithm becomes even more advantageous as particle count increases!
๐ License
This project is open source and available under the MIT License.



