Resolved that annoying gravity bug and added trajectories, a grid, keyboard navigation and logarithimic scale

This commit is contained in:
2024-07-12 16:07:49 +02:00
parent a93080b371
commit 2afc695aba
10 changed files with 284 additions and 50 deletions
+16 -9
View File
@@ -4,6 +4,7 @@
#include "Simulator.h"
#include <glm/glm.hpp>
#include <iostream>
#include <algorithm>
Simulator::Simulator() {}
@@ -11,7 +12,12 @@ void Simulator::addBody(const CelestialBody& body) {
bodies.push_back(body);
}
void Simulator::update(float dt) {
void Simulator::update(double dt) {
// Sort bodies by mass (descending order)
std::sort(bodies.begin(), bodies.end(), [](const CelestialBody& a, const CelestialBody& b) {
return a.getMass() > b.getMass();
});
// Calculate and apply gravitational forces
for (size_t i = 0; i < bodies.size(); ++i) {
glm::vec3 totalForce(0.0f);
@@ -25,14 +31,15 @@ void Simulator::update(float dt) {
}
// Update positions and velocities
for (auto& body : bodies) {
body.update(dt);
for (size_t i = 1; i < bodies.size(); ++i) { // Start from 1 to skip the Sun
bodies[i].update(dt);
bodies[i].addToTrajectory(bodies[i].getPosition());
}
}
glm::vec3 Simulator::calculateGravitationalForce(const CelestialBody& body1, const CelestialBody& body2) {
glm::vec3 direction = body2.getPosition() - body1.getPosition();
float distance = glm::length(direction);
glm::dvec3 Simulator::calculateGravitationalForce(const CelestialBody& body1, const CelestialBody& body2) {
glm::dvec3 direction = body2.getPosition() - body1.getPosition();
double distance = glm::length(direction);
// Avoid division by zero and unrealistic forces at very small distances
if (distance < 1e9) {
@@ -41,13 +48,13 @@ glm::vec3 Simulator::calculateGravitationalForce(const CelestialBody& body1, con
}
// Use the actual G value
const float G = 6.67430e-11f;
float forceMagnitude = G * (body1.getMass() * body2.getMass()) / (distance * distance);
const double G = 6.67430e-11;
double forceMagnitude = G * (body1.getMass() * body2.getMass()) / (distance * distance);
if (std::isnan(forceMagnitude) || std::isinf(forceMagnitude)) {
std::cout << "Warning: Invalid force magnitude calculated. Distance: " << distance
<< ", Masses: " << body1.getMass() << ", " << body2.getMass() << std::endl;
return glm::vec3(0.0f);
return glm::dvec3(0.0);
}
return glm::normalize(direction) * forceMagnitude;