-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
479 lines (381 loc) · 15.4 KB
/
main.cpp
File metadata and controls
479 lines (381 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
#include <iostream>
#include <cmath>
#include <fstream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <omp.h>
#include <random>
// Define G
const double GRAVITATIONAL_CONSTANT = 6.67430e-11;
// Define dt - 1 day
const double DT = 86400.0;
// Theta (MAC ratio)
const double THETA = 0.5;
// Softening parameter
const double EPSILON = 10.0;
struct Vector3 {
double x;
double y;
double z;
};
struct Planet {
Vector3 position;
Vector3 acceleration;
Vector3 velocity;
double mass;
double density;
bool isActive = true;
};
struct BoundingBox {
double x;
double y;
double z;
double halfDimension;
bool contains(Planet* p) {
double rightBoundary = x + halfDimension;
double leftBoundary = x - halfDimension;
double topBoundary = y + halfDimension;
double bottomBoundary = y - halfDimension;
double frontBoundary = z + halfDimension;
double backBoundary = z - halfDimension;
if (p->position.x >= leftBoundary && p->position.x < rightBoundary
&& p->position.y >= bottomBoundary && p->position.y < topBoundary
&& p->position.z >= backBoundary && p->position.z < frontBoundary) {
return true;
}
return false;
}
};
struct OctreeNode {
BoundingBox boundary;
Planet* planet;
double totalMass;
Vector3 centerOfMass;
OctreeNode* topNorthWest; OctreeNode* bottomNorthWest;
OctreeNode* topNorthEast; OctreeNode* bottomNorthEast;
OctreeNode* topSouthWest; OctreeNode* bottomSouthWest;
OctreeNode* topSouthEast; OctreeNode* bottomSouthEast;
OctreeNode(BoundingBox b) {
boundary = b;
planet = nullptr;
totalMass = 0.0;
centerOfMass.x = 0.0; centerOfMass.y = 0.0; centerOfMass.z = 0.0;
topNorthWest = nullptr; topNorthEast = nullptr;
topSouthWest = nullptr; topSouthEast = nullptr;
bottomNorthWest = nullptr; bottomNorthEast = nullptr;
bottomSouthWest = nullptr; bottomSouthEast = nullptr;
}
void free() {
if (topNorthWest != nullptr) {
topNorthWest->free(); topNorthEast->free();
topSouthWest->free(); topSouthEast->free();
bottomNorthWest->free(); bottomNorthEast->free();
bottomSouthWest->free(); bottomSouthEast->free();
}
delete topNorthWest; delete topNorthEast;
delete topSouthWest; delete topSouthEast;
delete bottomNorthWest; delete bottomNorthEast;
delete bottomSouthWest; delete bottomSouthEast;
}
void update(Planet* p) {
// Insert the new planet and calculate new center of mass and total mass
centerOfMass.x = ((totalMass * centerOfMass.x) + (p->mass * p->position.x)) / (totalMass + p->mass);
centerOfMass.y = ((totalMass * centerOfMass.y) + (p->mass * p->position.y)) / (totalMass + p->mass);
centerOfMass.z = ((totalMass * centerOfMass.z) + (p->mass * p->position.z)) / (totalMass + p->mass);
totalMass = totalMass + p->mass;
}
bool insert(Planet* p) {
// 1. First we check if the current Quadtree contains the planet
if (!boundary.contains(p)) {
return false;
}
// 2. Then, we update the Quadtree
update(p);
// 3. We check if no children and no planet first
if (topNorthWest == nullptr && planet == nullptr) {
planet = p;
return true;
}
// 4. We check if no children and planet and push the old planet down
if (topNorthWest == nullptr && planet != nullptr) {
subdivide();
if (topNorthWest->insert(planet)) { /* Success, do nothing else */ }
else if (topNorthEast->insert(planet)) { }
else if (topSouthWest->insert(planet)) { }
else if (topSouthEast->insert(planet)) { }
else if (bottomNorthWest->insert(planet)) { }
else if (bottomNorthEast->insert(planet)) { }
else if (bottomSouthWest->insert(planet)) { }
else if (bottomSouthEast->insert(planet)) { }
planet = nullptr;
}
// 5. Push the new planet down
if (topNorthWest->insert(p)) return true;
if (topNorthEast->insert(p)) return true;
if (topSouthWest->insert(p)) return true;
if (topSouthEast->insert(p)) return true;
if (bottomNorthWest->insert(p)) return true;
if (bottomNorthEast->insert(p)) return true;
if (bottomSouthWest->insert(p)) return true;
if (bottomSouthEast->insert(p)) return true;
return false;
}
void subdivide() {
// We cut the size of the box in half for the children
double newHalf = boundary.halfDimension / 2.0;
BoundingBox tnw;
tnw.x = boundary.x - newHalf; tnw.y = boundary.y + newHalf; tnw.z = boundary.z + newHalf;
tnw.halfDimension = newHalf;
topNorthWest = new OctreeNode(tnw);
BoundingBox tne;
tne.x = boundary.x + newHalf; tne.y = boundary.y + newHalf; tne.z = boundary.z + newHalf;
tne.halfDimension = newHalf;
topNorthEast = new OctreeNode(tne);
BoundingBox tsw;
tsw.x = boundary.x - newHalf; tsw.y = boundary.y - newHalf; tsw.z = boundary.z + newHalf;
tsw.halfDimension = newHalf;
topSouthWest = new OctreeNode(tsw);
BoundingBox tse;
tse.x = boundary.x + newHalf; tse.y = boundary.y - newHalf; tse.z = boundary.z + newHalf;
tse.halfDimension = newHalf;
topSouthEast = new OctreeNode(tse);
BoundingBox bnw;
bnw.x = boundary.x - newHalf; bnw.y = boundary.y + newHalf; bnw.z = boundary.z - newHalf;
bnw.halfDimension = newHalf;
bottomNorthWest = new OctreeNode(bnw);
BoundingBox bne;
bne.x = boundary.x + newHalf; bne.y = boundary.y + newHalf; bne.z = boundary.z - newHalf;
bne.halfDimension = newHalf;
bottomNorthEast = new OctreeNode(bne);
BoundingBox bsw;
bsw.x = boundary.x - newHalf; bsw.y = boundary.y - newHalf; bsw.z = boundary.z - newHalf;
bsw.halfDimension = newHalf;
bottomSouthWest = new OctreeNode(bsw);
BoundingBox bse;
bse.x = boundary.x + newHalf; bse.y = boundary.y - newHalf; bse.z = boundary.z - newHalf;
bse.halfDimension = newHalf;
bottomSouthEast = new OctreeNode(bse);
}
};
double calculateDistance(const Vector3& pA, const Vector3& pB) {
double dx = pB.x - pA.x;
double dy = pB.y - pA.y;
double dz = pB.z - pA.z;
// d = sqrt(dx^2 + dy^2 + dz^2)
double distance = std::sqrt((dx * dx) + (dy * dy) + (dz * dz));
return distance;
}
// Passing a const ref to the original memory blocks
Vector3 calculateGravitationalForceVector(const Planet& pA, const Planet& pB) {
// Find the difference in each axis
double dx = pB.position.x - pA.position.x;
double dy = pB.position.y - pA.position.y;
double dz = pB.position.z - pA.position.z;
// Calculate the distance squared
// (no need to square because we need to use r^2 so they cancel each other)
double distanceSquared = (dx * dx) + (dy * dy) + (dz * dz);
// Safety check to avoid dividing by zero
// plus two planets can't be at the exact same point
if (distanceSquared == 0.0) {
Vector3 zeroForce;
zeroForce.x = 0.0; zeroForce.y = 0.0; zeroForce.z = 0.0;
return zeroForce;
}
double epsilonSquared = EPSILON * EPSILON;
// Newton's Formula (F = G * (m1 * m2) / r^2)
double force = GRAVITATIONAL_CONSTANT * (pA.mass * pB.mass) / (distanceSquared + epsilonSquared);
// Find distance between pA and pB
double distance = std::sqrt(distanceSquared);
// Normalize the vector and multiply by the force magnitude
Vector3 forceVector;
forceVector.x = (dx / distance) * force;
forceVector.y = (dy / distance) * force;
forceVector.z = (dz / distance) * force;
return forceVector;
}
Vector3 calculateTreeForce(Planet* p, OctreeNode* node) {
Vector3 totalForce = {0.0, 0.0, 0.0};
if (node->totalMass == 0.0) {
return totalForce;
}
if (node->topNorthWest == nullptr && node->planet != nullptr) {
if (p == node->planet) {
return totalForce;
}
return calculateGravitationalForceVector(*p, *(node->planet));
}
if (node->topNorthWest != nullptr) {
// find d
double distance = calculateDistance(p->position, node->centerOfMass);
// find s
double size = node->boundary.halfDimension * 2;
// check if s/d is less than theta (0.5)
// if true, far away
if (size / distance < THETA) {
Planet superPlanet;
superPlanet.position = node->centerOfMass;
superPlanet.mass = node->totalMass;
Vector3 force = calculateGravitationalForceVector(*p, superPlanet);
totalForce = force;
} else {
Vector3 tnwForce = calculateTreeForce(p, node->topNorthWest);
Vector3 tneForce = calculateTreeForce(p, node->topNorthEast);
Vector3 tswForce = calculateTreeForce(p, node->topSouthWest);
Vector3 tseForce = calculateTreeForce(p, node->topSouthEast);
Vector3 bnwForce = calculateTreeForce(p, node->bottomNorthWest);
Vector3 bneForce = calculateTreeForce(p, node->bottomNorthEast);
Vector3 bswForce = calculateTreeForce(p, node->bottomSouthWest);
Vector3 bseForce = calculateTreeForce(p, node->bottomSouthEast);
double totalForceX = tnwForce.x + tneForce.x + tswForce.x + tseForce.x + bnwForce.x + bneForce.x + bswForce.x + bseForce.x;
double totalForceY = tnwForce.y + tneForce.y + tswForce.y + tseForce.y + bnwForce.y + bneForce.y + bswForce.y + bseForce.y;
double totalForceZ = tnwForce.z + tneForce.z + tswForce.z + tseForce.z + bnwForce.z + bneForce.z + bswForce.z + bseForce.z;
totalForce = {totalForceX, totalForceY, totalForceZ};
}
}
return totalForce;
}
double randomDouble(double min, double max) {
double fraction = (double)rand() / RAND_MAX;
return min + fraction * (max - min);
}
double getDensity(double mass) {
if (mass < 1e26) return 5000.0; // rocky
if (mass < 1e28) return 1300.0; // gas giant
return 1400.0; // stellar
}
int main() {
srand(time(NULL));
std::vector<Planet> universe;
// Generate our first object:
// the "Black Hole"
Planet blackHole;
blackHole.position.x = 0.0; blackHole.position.y = 0.0; blackHole.position.z = 0.0;
blackHole.velocity.x = 0.0; blackHole.velocity.y = 0.0; blackHole.velocity.z = 0.0;
blackHole.mass = 8.54e36;
universe.push_back(blackHole);
std::random_device rd;
// Mersenne Twister prime-number
std::mt19937 gen(rd());
// then we define the Log-Normal probability curve
std::lognormal_distribution<double> massDistribution(0.0, 3.5);
// Generate 1,000 planets
for (int i = 0; i < 1000; i++) {
Planet planet;
double randomPositionX = (rand() % 400000000) - 200000000;
double randomPositionY = (rand() % 400000000) - 200000000;
double randomPositionZ = (rand() % 400000000) - 200000000;
planet.position.x = randomPositionX;
planet.position.y = randomPositionY;
planet.position.z = randomPositionZ;
double massMultiplier = massDistribution(gen);
planet.mass = 5.972e24 * massMultiplier;
planet.density = getDensity(planet.mass);
// Calculate the exact distance (r) from the Black Hole (0,0,0)
// Using the Pythagorean theorem: r = sqrt(x^2 + y^2 + z^2)
double r = std::sqrt(randomPositionX * randomPositionX + randomPositionY * randomPositionY + randomPositionZ * randomPositionZ);
// Prevent division by zero just in case a planet spawns exactly at 0,0
if (r == 0) r = 1.0;
// Calculate the exact Orbital Velocity (v)
// Formula: v = sqrt((G * M) / r)
double blackHoleMass = 8.54e36;
double v = std::sqrt((GRAVITATIONAL_CONSTANT * blackHoleMass) / r);
// Calculate the Tangential Unit Vector (-y/r, x/r) and multiply by v
planet.velocity.x = v * (-randomPositionY / r);
planet.velocity.y = v * (randomPositionX / r);
planet.velocity.z = 0.0; // Keep the disk flat
universe.push_back(planet);
}
std::ofstream trajectoryFile("orbit.csv");
trajectoryFile << "Step,PlanetID,X,Y,Z,Mass\n";
int step = 0;
while (step < 360000) {
std::vector<Vector3> totalForces(universe.size());
for (size_t i = 0; i < totalForces.size(); i++) {
totalForces[i].x = 0.0; totalForces[i].y = 0.0; totalForces[i].z = 0.0;
}
BoundingBox baseBoundary;
baseBoundary.x = 0.0; baseBoundary.y = 0.0; baseBoundary.z = 0.0;
baseBoundary.halfDimension = 400000000.0;
OctreeNode root(baseBoundary);
for (size_t i = 0; i < universe.size(); i++) {
if (!universe[i].isActive) continue;
root.insert(&universe[i]);
}
#pragma omp parallel for
for (size_t i = 0; i < universe.size(); i++) {
if (!universe[i].isActive) continue;
totalForces[i] = calculateTreeForce(&universe[i], &root);
}
// free the memory
root.free();
#pragma omp parallel for
for (size_t i = 0; i < universe.size(); i++) {
if (!universe[i].isActive) continue;
// Calculate Acceleration (a = F / m)
double accelX = totalForces[i].x / universe[i].mass;
double accelY = totalForces[i].y / universe[i].mass;
double accelZ = totalForces[i].z / universe[i].mass;
// Update Velocity (v = v + a * dt)
universe[i].velocity.x = universe[i].velocity.x + (accelX * DT);
universe[i].velocity.y = universe[i].velocity.y + (accelY * DT);
universe[i].velocity.z = universe[i].velocity.z + (accelZ * DT);
// Update Position (p = p + v * dt)
universe[i].position.x = universe[i].position.x + (universe[i].velocity.x * DT);
universe[i].position.y = universe[i].position.y + (universe[i].velocity.y * DT);
universe[i].position.z = universe[i].position.z + (universe[i].velocity.z * DT);
}
// Accretion physics
for (size_t i = 0; i < universe.size(); i++) {
if (!universe[i].isActive) continue;
for (size_t j = i + 1; j < universe.size(); j++) {
if (!universe[j].isActive) continue;
Planet& p1 = universe[i];
Planet& p2 = universe[j];
// Find the difference in each axis
double dx = p2.position.x - p1.position.x;
double dy = p2.position.y - p1.position.y;
double dz = p2.position.z - p1.position.z;
// Calculate the distance squared
// We square both so we can avoid using a heavy sqrt() on distance
double distanceSquared = (dx * dx) + (dy * dy) + (dz * dz);
double r1 = std::cbrt(3.0 * p1.mass / (4.0 * M_PI * p1.density));
double r2 = std::cbrt(3.0 * p2.mass / (4.0 * M_PI * p2.density));
double thresholdSquared = (r1 + r2) * (r1 + r2);
// Collision Check
if (distanceSquared < thresholdSquared) {
// Conservation of Mass
double combinedMass = p1.mass + p2.mass;
// Conservation of Momentum
// v_f = (m1*v1 + m2*v2) / (m1 + m2)
double finalVx = (p1.mass * p1.velocity.x + p2.mass * p2.velocity.x) / combinedMass;
double finalVy = (p1.mass * p1.velocity.y + p2.mass * p2.velocity.y) / combinedMass;
double finalVz = (p1.mass * p1.velocity.z + p2.mass * p2.velocity.z) / combinedMass;
// Apply the new physics to the surviving planet (p1)
p1.velocity.x = finalVx;
p1.velocity.y = finalVy;
p1.velocity.z = finalVz;
p1.mass = combinedMass;
p1.density = getDensity(combinedMass);
// Bury the dead planet
p2.isActive = false;
}
}
}
// Print the position every hour of the simulation time
if (step % 3600 == 0) {
for (size_t i = 0; i < universe.size(); i++) {
trajectoryFile << step << ","
<< i << ","
<< universe[i].position.x << ","
<< universe[i].position.y << ","
<< universe[i].position.z << ","
<< universe[i].mass << "\n";
}
}
step++;
}
trajectoryFile.close();
std::cout << "Simulation complete. Data saved to orbit.csv" << std::endl;
return 0;
}