Skip to content

About

C++20 & raylib N-body simulator, developed for a research project (Austrian ABA)

Topics

Resources

Stars

7 stars

Watchers

1 watching

Forks

Latest commit

 

History

178 Commits

Folders and files

Repository files navigation

Orbit simulation

C++20 & raylib N-body simulator, developed for a research project

Features • Running the C++ simulator • Analysis • Research status • Attribution


▶ Try it out yourselves in the browser!

1. Features

  • Double-precision Newtonian gravity for 38 bodies, using Velocity Verlet integration
  • Optional planetary J2, barycentric planet-system approximations, and interaction pruning
  • Interactive 2D/3D views with textures, orbit trails, physical-size/schematic modes, and camera following
  • Runtime editing of mass, position, and velocity in absolute or body-relative coordinates
  • Customizable graphs with selectable axes, bodies, and reference frames
  • Orbital elements: Semi-major/minor axes, eccentricity, linear eccentricity, period, and inclination
  • Checkpoints, simulation reset, and single/N-step execution
  • Energy, linear-momentum, and barycentre-drift diagnostics
  • Desktop and browser support, headless runs with sampled CSV export
  • Endpoint and time-series comparisons against reference runs and NASA/JPL Horizons

1.1 Initial conditions

Initial positions and velocities represent:

  • Epoch: 1800-01-03
  • Origin: Solar-system barycentre
  • Frame: J2000 ecliptic

A project year is defined as exactly 365 days: 1 year = 365 * 86,400 seconds

1.2 Model limitations

The model currently omits:

  • General relativity
  • Higher gravity harmonics (e.g. J4, J6)
  • Asteroids, comets, and many natural satellites (It includes 28 moons but omits many other known natural satellites)
  • Tides
  • Radiation pressure
  • Atmospheric effects
  • Collisions and finite-size gravitational interactions
  • Planetary spin evolution and back-reaction torques

1.3 Accuracy and validation

Three different sources of deviation are evaluated separately:

  • Numerical error: Deviation introduced by the finite timestep and floating-point arithmetic. The timestep-dependent integration error is estimated through convergence tests and comparisons with smaller-timestep runs of the same physical model. Floating-point roundoff is present but is not currently isolated or quantified separately.
  • Approximation error: Error introduced by optimizations such as removing moons or replacing planet–moon systems with barycentric point masses. These configurations are compared with the full 38-body simulation using identical initial conditions, timesteps, and sampling intervals.
  • Model error: The difference between the simulated trajectories and NASA/JPL Horizons ephemerides. This includes missing physical effects and bodies, so it must not be interpreted as numerical integration error alone.

Planetary errors are normally measured relative to the Sun, while moon errors are measured relative to their parent planet. Planet-system approximations are compared using their GM-weighted barycentres. The analysis tools report endpoint errors as well as maximum and RMS time-series errors; moon comparisons additionally include radial, along-track, cross-track, and unwrapped phase errors.

The current results should be considered provisional. Final validated accuracy results and their exact reproduction settings will accompany the completed research project.

2. Running the C++ simulator

2.1 Requirements

C++ Simulator:

  • CMake 3.25 or newer
  • A recent C++20 compiler (with std::format support)
  • OpenGL (--headless does not open a window, but still builds and links raylib/OpenGL dependencies)

Analyze script (analyze.py):

  • Python 3.12 or newer
  • Python package requests

2.2 Building

By default, CMake downloads and builds raylib 6.0:

cmake -S . -B cmake-build-release -DCMAKE_BUILD_TYPE=Release
cmake --build cmake-build-release --parallel

To use an installed raylib 6.0 or newer with its CMake package configuration instead:

cmake -S . -B cmake-build-system -DCMAKE_BUILD_TYPE=Release -DUSE_SYSTEM_RAYLIB=ON
cmake --build cmake-build-system --parallel

For a custom installation, add -DCMAKE_PREFIX_PATH=/path/to/raylib-prefix or -Draylib_DIR=/path/to/raylib-prefix/lib/cmake/raylib to the configure command. The installed library must include JPEG support to load the bundled textures. With USE_SYSTEM_RAYLIB=ON, configuration fails if a compatible package is missing; there is no download fallback. The option defaults to OFF.

For building with Emscripten see section 2.7.

2.3 CLI options

Available CLI options:

./cmake-build-release/simulation-orbit --help

2.4 Running

Runtime assets require repository-relative paths, so launch the program from the repository root.

Start the simulator visualization:

./cmake-build-release/simulation-orbit

2.5 Interactive controls

Input Action
Space Pause or resume
T Switch between 2D and 3D
L Collapse or expand the legend
O Toggle all orbit trails
M Toggle moon trails while orbit trails are enabled
R Reset the view, including zoom and camera following
0–9 Set the coordinate origin to the Sun, a planet, or Pluto
^ (QWERTZ; key code 161) Return to the stored inertial coordinate frame
Mouse wheel Zoom; anchored to the cursor in 2D
Trackpad / touch Browser-only; Zoom (anchored to the position in 2D)
+ / - (QWERTZ; key codes ] / /) Zoom using the keyboard
Left-click body or legend name Open or close its inspector
Left-click legend circle Show or hide the body and its trails
Left-drag on empty scene space Pan in 2D; rotate in 3D
Arrow keys / WASD Rotate the 3D camera
Shift Accelerate zoom and keyboard camera rotation
F3 Toggle the developer debug overlay

The toolbar provides pause/resume, view reset, 2D/3D switching, body-size modes, marker scaling, and an ORIGIN selector.

Open Tools to:

  • Toggle orbit trails and adjust simulation speed
  • Save or restore Checkpoints, or reset the simulation to its initial state
  • Open Diagnostics for energy, linear momentum, and barycentre drift
  • Create customizable Graphs
  • Orbital elements can include a planet's bound moons ("Include moons")
  • Advance one or N simulation steps while paused

Body inspectors provide:

  • Edit relative to: Choose absolute or body-relative position and velocity
  • Enter or the inline checkmark: Commit an edited field
  • Escape while editing: Discard the current draft
  • Copy values: Copy the current simulation values in the selected reference frame
  • Go to (2D), Follow, and Stop following: Control the camera
  • Set origin: Change the coordinate frame used by the scene and trails
  • New graph: Open a graph for the selected body

Camera following, the scene's coordinate origin, and the inspector's editing reference are independent. Reset view (R) changes the camera; Reset simulation under Checkpoints restores the physical state.

2.6 CLI arguments

Illustrated by examples runs, can also be retrieved via ./cmake-build-release/simulation-orbit --help:

# Help & version
./cmake-build-release/simulation-orbit --version # Show version
./cmake-build-release/simulation-orbit --help # List more specific help for each CLI argument

# Basic commands
./cmake-build-release/simulation-orbit # Simulate planets + Pluto for infinite years with 15 minute step size (default)
./cmake-build-release/simulation-orbit --headless --years 20 # Simulate 20 years in headless mode
./cmake-build-release/simulation-orbit --dt 100 --years 10 # Simulate 10 years with 100 seconds step size
./cmake-build-release/simulation-orbit --speed 5 # Limit speed to 5 years/second

# Configure body set
./cmake-build-release/simulation-orbit --dt 900 --years 100 --j2 --body-set planets # Simulate planets for 100 years with 15 minutes step size, planetary oblateness (J2) enabled
./cmake-build-release/simulation-orbit --dt 7200 --years 50 --body-set planet-systems # Simulate planet systems using barycentric approximation for 50 years with 2 hours step size 
./cmake-build-release/simulation-orbit --years 20 --body-set all # Simulate 20 years with all (38) celestial bodies enabled
./cmake-build-release/simulation-orbit --headless --years 20 --body-set dwarf # Simulate planets + Pluto for 20 years in headless mode
./cmake-build-release/simulation-orbit --years 2000 --body-set dwarf --disable-body Sun --disable-body Jupiter # Simulate planets + Pluto for 2000 years with Sun & Jupiter explicitly disabled

# CSV output
# Note: --csv, --sample-every-seconds and --csv-live require --headless
./cmake-build-release/simulation-orbit --headless --csv positions_and_velocities.csv --sample-every-seconds 2592000 --years 100 --dt 3600 # Simulate 100 years with 1 hour step size headlessly; sample positions & velocities every month into positions_and_velocities.csv
./cmake-build-release/simulation-orbit --headless --csv positions_and_velocities.csv --sample-every-seconds 2592000 --years 100 --dt 3600 --csv-live # Same as previous command; Also stream CSV rows during simulation instead of writing at the end

# SIMD
./cmake-build-release/simulation-orbit --body-set all --simd  # Enable platform-specific SIMD optimization (only available on some platforms)

2.7 Running in the browser (Emscripten)

Requires an activated emsdk (source /path/to/emsdk/emsdk_env.sh).

emcmake cmake -S . -B build-web -DCMAKE_BUILD_TYPE=Release
cmake --build build-web --parallel
emrun build-web/simulation-orbit.html

CLI arguments are passed as URL query parameters separated by & (or after -- when using emrun):

emrun build-web/simulation-orbit.html -- --dt 900 --body-set planets
# equivalent URL: http://localhost:6931/simulation-orbit.html?--dt&900&--body-set&planets

They also work on the live site (ex. https://icewizard7.github.io/simulation-orbit/?--body-set&planets).

--simd is unavailable in the browser. --headless and --csv are not useful there, because files are written to Emscripten's in-memory filesystem.

3. Analysis

List available commands:

python3 analyze.py

3.1 Comparing simulation endpoints against NASA/JPL Horizons data

Capture output:

./cmake-build-release/simulation-orbit --headless --years 1 --dt 900 > run.txt

Analyze:

python3 analyze.py analyze run.txt

If no input file is specified, analyze.py will read from standard input:

./cmake-build-release/simulation-orbit --headless --years 1 --dt 900 | python3 analyze.py analyze

3.2 Comparing simulator runs

Compare body-centre endpoints:

python3 analyze.py compare reference.txt candidate.txt

Compare CSV time series:

python3 analyze.py compare-csv reference.csv candidate.csv

3.3 Comparing planetary-system barycentres

When comparing the full 38-body simulation with models that remove the moons or replace each planet–moon system with a single barycentric point mass, use the system-aware commands:

python3 analyze.py analyze-systems run.txt
python3 analyze.py compare-systems reference.txt candidate.txt
python3 analyze.py compare-systems-csv reference.csv candidate.csv

4. Research status

Important

This project is being developed as part of an Austrian Abschließende Arbeit (ABA). The completed paper and final research results are expected to be made available around March 2028.

5. Attribution and licensing

5.1 Scientific data

Initial positions, velocities, and most standard gravitational parameters (GM) were obtained from the NASA/JPL Horizons System, operated by the Jet Propulsion Laboratory Solar System Dynamics Group.

Planetary equatorial radii are taken from the JPL Planetary Physical Parameters. Sources for the J2 coefficients and pole orientations are documented alongside the corresponding values in analyze.py.

A small number of gravitational parameters unavailable directly from Horizons use documented fallback values or estimates. These are identified in analyze.py.

NASA and JPL do not endorse this project.

5.2 Software and font

5.3 Visual assets

The following runtime textures are provided by Solar System Scope under the Creative Commons Attribution 4.0 International license:

  • Sun
  • Mercury
  • Venus surface
  • Earth
  • Mars
  • Jupiter
  • Saturn
  • Uranus
  • Neptune
  • Moon
  • Milky Way background
  • (unused) Stars background

Required attribution:

Planetary textures © Solar System Scope, licensed under CC BY 4.0.

The Io, Europa, Ganymede, and Callisto textures are © James Hastings-Trew / Planet Pixel Emporium. They are used under the website’s texture-map usage terms, which permit their use for real-time rendering but restrict redistribution of the unmodified maps as a standalone texture collection.

5.4 Additional code

  • coi-serviceworker by Guido Zuidhof (MIT, see web/licenses/coi-serviceworker-MIT.txt): Enables cross-origin isolation (needed for pthreads) on GitHub Pages.

5.5 License scope

The project’s source code is licensed under the Apache License 2.0. This license does not automatically apply to bundled fonts, textures, scientific data, or other third-party material; those resources remain subject to their respective terms.

About

C++20 & raylib N-body simulator, developed for a research project (Austrian ABA)

Topics

Resources

Stars

7 stars

Watchers

1 watching

Forks

Releases

Contributors

Languages