import Foundation
private let G: Double = 6.6743e-11 // gravity, number found from an apple, update me when we find a graviton
private let T: Double = 21600 // 1 step = this time (in seconds (six hours))
// not using 3rd axis, but we could!
// simd because i cba writing a 2d/3d vector type
typealias Vec3 = SIMD3<Double>
struct Body {
var name: String
var mass: Double
var pos: Vec3
var vel: Vec3
public mutating func imp(_ i: Vec3) {
vel += i * T
pos += vel * T
}
public func mag(_ other: Self) -> Vec3 {
let r = other.pos - pos // distance
let d = sqrt(r.x * r.x + r.y * r.y + r.z * r.z) // length
let f = G * ((mass * other.mass) / (d * d)) // newton's headache
let n = r / d // normalize
return f * n // distance to vector
}
}
// note: without the sol and jupiter, terra will slowly approach luna
// but i am too lazy to look up the values for other bodies
// also; this doesn't have axis inclination
// so it's going to be inaccurate to real life regardless
// but pretend it's real and earth is slowly going sideways
var bodies = [
Body(
name: "terra",
mass: 5.972e+24,
pos: Vec3(repeating: 0),
vel: Vec3(repeating: 0)),
Body(
name: "luna",
mass: 7.348e+22,
pos: Vec3(3.844e+8, 0, 0),
vel: Vec3(0, 1022, 0)),
]
// tsv we can plot~
print("index\tbody\tx\ty\tz")
for t in 0..<500 {
var f = [Vec3](repeating: Vec3(repeating: 0), count: bodies.count)
for i in 0..<bodies.count {
let body = bodies[i]
for j in 0..<bodies.count where i != j {
f[i] += body.mag(bodies[j]) / body.mass
}
}
for i in 0..<bodies.count {
bodies[i].imp(f[i])
print("\(t)\t\(bodies[i].name)\t\(bodies[i].pos.x)\t\(bodies[i].pos.y)\t\(bodies[i].pos.z)")
}
}
post a comment