// The three-body physics, shared by sim.comp and lookahead.comp so the live // system and its futures move alike: gravity with softening, and leapfrog // (kick, drift, kick), symplectic and time-reversible, split finer through // close passes, about 2 % of the local dynamical time a part: too coarse // and a close pass gains energy and flings a body out. void accelerations(vec2 p[3], vec3 m, float softening, out vec2 a[3]) { float eps2 = softening * softening; a[0] = vec2(0.0); a[1] = vec2(0.0); a[2] = vec2(0.0); for (int i = 0; i < 3; i++) { for (int j = i + 1; j < 3; j++) { vec2 d = p[j] - p[i]; float inv = inversesqrt(dot(d, d) + eps2); vec2 f = d * (inv * inv * inv); a[i] += m[j] * f; a[j] -= m[i] * f; } } } // One step of `dt`, in up to `most` parts; `a` holds the accelerations at // `p`, before and after. void leapfrog(inout vec2 p[3], inout vec2 v[3], inout vec2 a[3], float dt, vec3 m, float softening, float most) { float near = min(min(distance(p[0], p[1]), distance(p[0], p[2])), distance(p[1], p[2])) + softening; float local = sqrt(near * near * near / (m.x + m.y + m.z)); uint k = uint(clamp(ceil(abs(dt) / (0.02 * local)), 1.0, most)); float h = dt / float(k); for (uint j = 0u; j < k; j++) { for (int i = 0; i < 3; i++) v[i] += 0.5 * h * a[i]; for (int i = 0; i < 3; i++) p[i] += h * v[i]; accelerations(p, m, softening, a); for (int i = 0; i < 3; i++) v[i] += 0.5 * h * a[i]; } }