# Orbital Mechanics Simulation - Implementation Plan ## Project Overview A 3D orbital mechanics simulation using 2-body gravitational model with sphere of influence (SOI) transitions. Real-time visualization of the solar system (Sun, planets, moons) using raylib with C-style C++. ## Technical Constraints - C-style C++ only: structs and functions, no classes or templates - Small, focused functions - Simple rotations (Euler angles / axis-angle) - quaternions deferred for later - Euler integration for physics - raylib for 3D visualization ## Project Structure ``` claudes_game/ ├── src/ │ ├── main.cpp │ ├── physics.cpp │ ├── physics.h │ ├── bodies.cpp │ ├── bodies.h │ ├── renderer.cpp │ ├── renderer.h │ ├── config_loader.cpp │ └── config_loader.h ├── configs/ │ ├── solar_system.txt │ └── example_binary_star.txt ├── Makefile └── README.md ``` ## Core Data Structures ### Vec3 (physics.h) ```cpp struct Vec3 { double x, y, z; }; ``` ### CelestialBody (bodies.h) ```cpp struct CelestialBody { char name[64]; double mass; // kg double radius; // meters Vec3 position; // meters from solar system origin Vec3 velocity; // m/s double soi_radius; // sphere of influence radius (meters) int parent_index; // index of gravitational parent (-1 for Sun) float color[3]; // RGB for rendering }; ``` ### SimulationState (bodies.h) ```cpp struct SimulationState { CelestialBody* bodies; int body_count; double time; // simulation time (seconds) double dt; // time step (seconds) }; ``` ## Key Components ### 1. Physics Module (physics.c/h) **Functions:** - `Vec3 vec3_add(Vec3 a, Vec3 b)` - vector addition - `Vec3 vec3_sub(Vec3 a, Vec3 b)` - vector subtraction - `Vec3 vec3_scale(Vec3 v, double s)` - scalar multiplication - `double vec3_magnitude(Vec3 v)` - vector length - `double vec3_distance(Vec3 a, Vec3 b)` - distance between points - `Vec3 vec3_normalize(Vec3 v)` - unit vector - `Vec3 calculate_gravity_force(CelestialBody* body, CelestialBody* parent)` - 2-body force - `Vec3 calculate_acceleration(Vec3 force, double mass)` - F = ma - `void euler_step(CelestialBody* body, Vec3 acceleration, double dt)` - Euler integration ### 2. Bodies Module (bodies.c/h) **Functions:** - `SimulationState* create_simulation(int max_bodies)` - allocate simulation - `void destroy_simulation(SimulationState* sim)` - cleanup - `void add_body(SimulationState* sim, const char* name, double mass, double radius, Vec3 pos, Vec3 vel, float r, float g, float b)` - add celestial body - `int find_dominant_body(SimulationState* sim, int body_index)` - determine which body has gravitational dominance - `void update_soi(CelestialBody* body, CelestialBody* parent)` - calculate sphere of influence radius - `void update_simulation(SimulationState* sim)` - single time step update **SOI Calculation:** Using Hill sphere approximation: `r_soi = a * (m/M)^(2/5)` where a = semi-major axis, m = body mass, M = parent mass ### 3. Config Loader Module (config_loader.cpp/h) **Functions:** - `bool load_system_config(SimulationState* sim, const char* filepath)` - load bodies from config file - `bool parse_body_line(const char* line, CelestialBody* body)` - parse single body definition - `void calculate_initial_velocities(SimulationState* sim)` - compute circular orbit velocities from positions **Config File Format (simple text):** ``` # Comment lines start with # # Format: name mass(kg) radius(m) x(m) y(m) z(m) parent_index r g b Sun 1.989e30 6.96e8 0 0 0 -1 1.0 1.0 0.0 Earth 5.972e24 6.371e6 1.496e11 0 0 0 0.0 0.5 1.0 Moon 7.342e22 1.737e6 1.4996e11 0 0 1 0.7 0.7 0.7 # Velocity is calculated automatically for circular orbits ``` **Example configs to provide:** - `configs/solar_system.txt` - Our solar system with Sun, 8 planets, major moons - `configs/example_binary_star.txt` - Binary star system with planets ### 4. Renderer Module (renderer.c/h) **Functions:** - `void init_renderer(int width, int height, const char* title)` - initialize raylib window - `void setup_camera(Camera3D* camera)` - configure 3D camera - `void render_body(CelestialBody* body, double scale)` - draw sphere for body - `void render_simulation(SimulationState* sim, Camera3D* camera)` - render all bodies - `void draw_orbit_trail(Vec3* positions, int count, Color color)` - draw orbit path (future enhancement) - `void close_renderer()` - cleanup raylib **Rendering approach:** - Use logarithmic scaling for distances (solar system is huge) - Use exponential scaling for body sizes (make small bodies visible) - Simple camera controls (rotate around Sun, zoom in/out) - Display FPS and simulation time ### 5. Main Loop (main.cpp) ```cpp 1. Parse command line arguments (config file path, default to configs/solar_system.txt) 2. Initialize raylib window and camera 3. Create simulation and load system from config file 4. Main loop: a. Handle input (camera controls, pause/resume, speed adjustment) b. Update physics (multiple sub-steps per frame for stability) c. Check for SOI transitions d. Render scene e. Update camera 5. Cleanup and exit ``` ## Implementation Steps ### Phase 1: Foundation 1. Create project structure and Makefile 2. Implement Vec3 and basic vector math functions (physics.c/h) 3. Define CelestialBody and SimulationState structs (bodies.h) 4. Create basic simulation functions (create, destroy, add_body) ### Phase 2: Physics Core 5. Implement 2-body gravity calculation 6. Implement Euler integration step 7. Implement SOI detection and parent switching logic 8. Create update_simulation() function ### Phase 3: Config Loading System 9. Implement config file parser (parse_body_line, skip comments/empty lines) 10. Implement load_system_config() to read and populate simulation 11. Create configs/solar_system.txt with our solar system data 12. Implement calculate_initial_velocities() for circular orbits 13. Calculate SOI radii for all bodies after loading ### Phase 4: Visualization 14. Initialize raylib window and 3D camera 15. Implement render_body() with scaling 16. Implement render_simulation() to draw all bodies 17. Add basic camera controls (orbital rotation, zoom) ### Phase 5: Integration and Refinement 18. Integrate rendering with physics loop in main.cpp 19. Add command line argument parsing for config file selection 20. Add time scaling controls (speed up/slow down simulation) 21. Add pause/resume functionality 22. Display simulation info (time, FPS, body count, current config) 23. Create example_binary_star.txt config for testing 24. Test and tune time step for stability ## Technical Notes ### Config File System Benefits - **Flexibility**: Easily create any star system without recompiling - **Testing**: Quickly test different scenarios (binary stars, close encounters, etc.) - **Sharing**: Users can share interesting system configurations - **Debugging**: Simplified test cases with just 2-3 bodies - **Education**: Learn about different orbital configurations by experimenting ### Scaling for Visualization - **Distance scale**: Use logarithmic or power-law scaling (e.g., `display_pos = sign(pos) * pow(abs(pos), 0.3)`) - **Size scale**: Make minimum visible radius (e.g., max(actual_radius * scale, min_visible_radius)) - Keep Sun at origin for simplicity ### Time Step Considerations - Solar system scale requires small time steps (try dt = 60 seconds initially) - May need multiple physics updates per render frame - Allow user to adjust simulation speed multiplier ### SOI Transition Logic ``` For each body (except Sun): 1. Calculate distance to current parent 2. Calculate distance to all other potential parents 3. Check if body is within SOI of a different parent 4. If yes, switch parent_index and recalculate relative state ``` ### Initial Conditions - Use Keplerian orbital elements or simplified circular orbits - Ensure velocity is perpendicular to position vector for circular orbits - Circular orbit velocity: v = sqrt(G * M / r) ## Files to Create 1. `src/physics.h` - Vector math and physics declarations 2. `src/physics.cpp` - Vector math and physics implementations 3. `src/bodies.h` - Body and simulation data structures 4. `src/bodies.cpp` - Body management and simulation update 5. `src/config_loader.h` - Config file parsing declarations 6. `src/config_loader.cpp` - Config file loading implementation 7. `src/renderer.h` - Rendering declarations 8. `src/renderer.cpp` - raylib rendering implementation 9. `src/main.cpp` - Main loop and program entry 10. `configs/solar_system.txt` - Our solar system configuration 11. `configs/example_binary_star.txt` - Example binary star system 12. `Makefile` - Build configuration 13. `README.md` - Project documentation and config format docs ## Future Enhancements (Not in Initial Implementation) - Quaternion-based rotations - Orbit trail rendering - N-body simulation mode - Patched conic approximation - More accurate integration (RK4, Verlet) - Save/load simulation state - Interactive body selection and info display - Reference frame switching