vibe coding an orbital mechanics simulation to try out claude code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

7.0 KiB

Orbital Mechanics Simulation - Technical Reference

Overview

3D orbital mechanics simulation using 2-body gravitational model with sphere of influence (SOI) transitions. Built with C-style C++ and raylib.

Technical Constraints

  • C-style C++ only: structs and functions, no classes or templates
  • RK4 (Runge-Kutta 4th order) integration for physics
  • Simple rotations (quaternions deferred)
  • raylib for 3D visualization
  • Single root body systems only (parent_index = -1 for exactly one body)

Core Data Structures

Vec3 (physics.h)

struct Vec3 {
    double x, y, z;
};

CelestialBody (simulation.h)

struct CelestialBody {
    char name[64];
    double mass;              // kg
    double radius;            // meters
    Vec3 position;            // meters from origin
    Vec3 velocity;            // m/s
    double soi_radius;        // sphere of influence radius (meters)
    int parent_index;         // index of gravitational parent (-1 for root)
    float color[3];           // RGB for rendering
    double eccentricity;      // orbital eccentricity (0 = circular)
    double semi_major_axis;   // meters
};

SimulationState (simulation.h)

struct SimulationState {
    CelestialBody* bodies;
    int body_count;
    int max_bodies;
    double time;              // simulation time (seconds)
    double dt;                // time step (seconds)
};

RenderState (renderer.h)

struct RenderState {
    Camera3D camera;
    double distance_scale;    // Scale factor for distances
    double size_scale;        // Scale factor for body sizes
    bool show_info;           // Display simulation info
};

OrbitalElements (simulation.h)

struct OrbitalElements {
    double time_days;
    double semi_major_axis_au;
    double eccentricity;
    double specific_energy;
    double distance_to_sun_au;
    double distance_to_ref_body_au;
    double velocity_magnitude;
};

AccelerationContext (physics.h)

struct AccelerationContext {
    SimulationState* sim;
    CelestialBody* current_body;
    int body_index;
};

Module Overview

Physics (physics.cpp/h)

Vector math and gravity calculations. RK4 (Runge-Kutta 4th order) integration with rk4_step().

Simulation (simulation.cpp/h)

Simulation state management and updates. SOI detection using Hill sphere: r_soi = a * (m/M)^(2/5).

Key functions:

  • find_dominant_body() - determines which body has gravitational dominance
  • update_soi() - calculates sphere of influence radius using Hill sphere
  • update_simulation() - runs one physics step: finds dominant parent, calculates gravity, applies RK4 integration
  • Dynamic parent switching when bodies cross SOI boundaries (with hysteresis)

Config Loader (config_loader.cpp/h)

TOML-based config parser using tomlc17 library. Auto-calculates circular orbit velocities and SOI radii.

Key functions:

  • parse_toml_body() - parses individual body entries
  • calculate_initial_velocities() - sets circular orbit velocities using vis-viva equation
  • calculate_soi_radii() - computes sphere of influence for all bodies

Config format details:

  • TOML array of tables: [[bodies]]
  • Comments start with #
  • parent_index = -1 indicates root body (star)

Config format (TOML):

[[bodies]]
name = "Sun"
mass = 1.989e30
radius = 6.96e8
position = { x = 0.0, y = 0.0, z = 0.0 }
parent_index = -1
color = { r = 1.0, g = 1.0, b = 0.0 }
eccentricity = 0.0
semi_major_axis = 0.0

[[bodies]]
name = "Earth"
mass = 5.972e24
radius = 6.371e6
position = { x = 1.496e11, y = 0.0, z = 0.0 }
parent_index = 0
color = { r = 0.0, g = 0.5, b = 1.0 }
eccentricity = 0.0
semi_major_axis = 1.496e11

Renderer (renderer.cpp/h)

Raylib 3D visualization with logarithmic distance scaling and size scaling for visibility.

Main Program (main.cpp)

GUI-only application with interactive 3D visualization.

  • Initializes simulation with MAX_BODIES=100, TIME_STEP=60 seconds
  • Runs 100 physics steps per frame (adjustable with speed multiplier)
  • Game loop: input handling → camera update → physics update (if not paused) → rendering
  • Supports speed multiplier (2x/0.5x per keypress, min 0.125x)

Controls:

  • Arrow keys: Rotate and zoom camera
  • Space: Pause/Resume
  • +/-: Speed up/slow down simulation
  • I: Toggle info display
  • ESC: Quit

Data Flow

Initialization Sequence

  1. Configuration file → load_system_config() → populates SimulationState
  2. calculate_initial_velocities() → sets circular orbit velocities for all bodies
  3. calculate_soi_radii() → computes sphere of influence for each body

Main Simulation Loop

  1. update_simulation() → for each body:
    • find_dominant_body() → determine gravitational parent based on SOI
    • evaluate_acceleration() → compute gravitational force from parent
    • rk4_step() → update position/velocity using Runge-Kutta 4th order
  2. render_simulation() → for each body:
    • scale_position() → convert to render coordinates using logarithmic scaling
    • scale_radius() → convert to render size using exponential scaling
    • render_body() → draw sphere with color

SOI Transition Mechanics

  • Bodies dynamically switch gravitational parents when crossing SOI boundaries
  • Uses 0.5x distance hysteresis to prevent oscillation between parents
  • find_dominant_body() checks all bodies and selects most dominant influence

Implementation Status

Completed

  • Phase 1-4: Core physics, simulation, config loading, and rendering
  • Raylib integration with 3D camera
  • Distance and size scaling for visualization
  • TOML config file system with solar_system.toml and test_simple.toml
  • RK4 (Runge-Kutta 4th order) integration for improved accuracy
  • Time scaling controls (speed up/slow down simulation)
  • Pause/resume functionality
  • Orbital elements calculation

🔨 Remaining/Future Work

  • More accurate integration methods (Newton-Raphson propagation)
  • Interactive body selection
  • Reference frame switching

Technical Notes

Code Style and Architecture

  • C-style C++: structs and functions only, no classes or templates
  • All headers use include guards
  • Memory management uses malloc/free
  • Layer separation: Physics, Simulation, Configuration, Rendering layers

Scaling for Visualization

  • Distance: logarithmic/power-law scaling for solar system scale
  • Size: minimum visible radius to prevent tiny bodies from disappearing
  • Origin at Sun for simplicity
  • Both distance_scale and size_scale are configurable in RenderState

Physics Considerations

  • Timestep: 60 seconds for solar system scale
  • Circular orbit velocity: v = sqrt(G * M / r)
  • Physics steps per frame: 100 (default) with speed multiplier adjustment
  • Simulation time per frame: 60s * 100 = 6000 seconds at 1x speed
  • SOI (Sphere of Influence) uses Hill sphere approximation: r_soi = a * (m/M)^(2/5)
  • SOI transitions use 0.5x distance hysteresis to prevent oscillation

Future Enhancements

  • More accurate integration methods (Newton-Raphson propagation)
  • Interactive body selection
  • Reference frame switching
  • 3D orbital visualization with inclination