"""Lecture 6, what dropping a term costs: shots at 45 deg with no air at 1, 3 and 5 km/s, over a flat Earth with
constant g = mu/R_E^2 (dashed) and over a spherical Earth with g = mu/r^2 (solid, flown with the engine's
point-mass gravity), drawn as height above the ground against distance along the ground. All shots share one
clock. Writes img/anim-06-ballistic.gif."""
import numpy as np
from scipy.integrate import solve_ivp
from _visual import plt, save_anim, despine, MAROON, BLUE, GREEN, GREY
from flight.gravity import point_mass
from flight.constants import A_EARTH as R, MU

G = MU / R**2
SPEEDS = [1000.0, 3000.0, 5000.0]
COLS = [GREEN, BLUE, MAROON]
GAM = np.radians(45)


def sphere(V0):
    def rhs(t, y):
        g = point_mass(np.array([y[0], y[1], 0.0]))
        return [y[2], y[3], g[0], g[1]]
    hit = lambda t, y: np.hypot(y[0], y[1]) - R
    hit.terminal, hit.direction = True, -1
    y0 = [0.0, R, V0 * np.cos(GAM), V0 * np.sin(GAM)]
    s = solve_ivp(rhs, (0, 1e5), y0, events=hit, rtol=1e-11, atol=1e-4, dense_output=True)
    return s


SPH = [sphere(v) for v in SPEEDS]
T_END = max(s.t[-1] for s in SPH)


def sphere_xy(s, t):
    x, y = s.sol(t)[0], s.sol(t)[1]
    return R * np.arctan2(x, y) / 1e3, (np.hypot(x, y) - R) / 1e3     # ground distance, height (km)


def flat_xy(V0, t):
    tf = 2 * V0 * np.sin(GAM) / G
    t = np.minimum(t, tf)
    return V0 * np.cos(GAM) * t / 1e3, (V0 * np.sin(GAM) * t - 0.5 * G * t**2) / 1e3


if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.6))
    N = 120
    times = np.linspace(0, T_END, N)

    def frame(k):
        ax.clear()
        t = times[k]
        for V0, s, c in zip(SPEEDS, SPH, COLS):
            tt = np.linspace(0, min(t, s.t[-1]), 300)
            x, h = sphere_xy(s, tt)
            ax.plot(x, h, color=c, lw=2.4)
            xf, hf = flat_xy(V0, np.linspace(0, t, 300))
            ax.plot(xf, hf, color=c, lw=1.8, ls="--")
            if k == N - 1:
                ax.text(x[-1] + 25, 15, f"{V0 / 1e3:.0f} km/s\n{x[-1]:.0f} km", color=c, fontsize=11, ha="left")
                ax.text(xf[-1], -25, f"flat\n{xf[-1]:.0f} km", color=c, fontsize=10, ha="center", va="top")
        ax.axhline(0, color=GREY, lw=1)
        ax.set_xlim(-50, 3550)
        ax.set_ylim(-170, 1000)
        ax.set_xlabel("distance along the ground (km)")
        ax.set_ylabel("height above the ground (km)")
        ax.text(1500, 930, "solid: spherical Earth, $g=\\mu/r^2$     dashed: flat Earth, constant $g$", fontsize=11,
                ha="center")
        ax.text(3500, 860, f"t = {t / 60:4.1f} min", fontsize=11, ha="right")
        despine(ax)
        return []

    save_anim(fig, frame, N, 15, "anim-06-ballistic", hold=2.5)
