From 64d9284477a7b08566f415c36ee320f106cf9b89 Mon Sep 17 00:00:00 2001 From: cinnaboot Date: Mon, 12 Jan 2026 11:22:53 -0500 Subject: [PATCH] Fix parent body transition bug in simulation When bodies change gravitational parents, properly update their local coordinates to maintain physics accuracy. This fixes the bug where local positions were never updated when changing parents. Also remove unused variable warning. --- src/simulation.cpp | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/simulation.cpp b/src/simulation.cpp index 679cabb..4c8657e 100644 --- a/src/simulation.cpp +++ b/src/simulation.cpp @@ -85,9 +85,22 @@ void update_simulation(SimulationState* sim) { int new_parent = find_dominant_body(sim, i); if (new_parent != body->parent_index && new_parent != -1) { - // FIXME: there's now a bug here when changing parent bodes - // I think it's that the local position is never updated + // Convert current local coordinates to global coordinates using old parent + if (body->parent_index >= 0 && body->parent_index < sim->body_count) { + CelestialBody* old_parent = &sim->bodies[body->parent_index]; + body->position = vec3_add(body->local_position, old_parent->position); + body->velocity = vec3_add(body->local_velocity, old_parent->velocity); + } + + // Update parent index body->parent_index = new_parent; + + // Convert global coordinates to local coordinates using new parent + if (body->parent_index >= 0 && body->parent_index < sim->body_count) { + CelestialBody* new_parent_body = &sim->bodies[body->parent_index]; + body->local_position = vec3_sub(body->position, new_parent_body->position); + body->local_velocity = vec3_sub(body->velocity, new_parent_body->velocity); + } } if (body->parent_index >= 0 && body->parent_index < sim->body_count) { @@ -109,7 +122,7 @@ static void compute_orbital_velocity_from_vis_viva(CelestialBody* body, CelestialBody* parent) { Vec3 r = vec3_sub(body->position, parent->position); double distance = vec3_magnitude(r); - double e = body->eccentricity; + // double e = body->eccentricity; // FIXME: unused variable double a = body->semi_major_axis; double v_squared = G * parent->mass * (2.0 / distance - 1.0 / a); // FIXME: need error handling here