"""Lecture 1, Newton's cannon: horizontal shots from the top of an imaginary mountain half an Earth radius high
(Newton's own thought experiment exaggerated the mountain too), with no air and the point-mass gravity of the
engine, at 0.5, 0.7, 0.8, 0.85, 1.0 and 1.05 times the circular speed there. The slow shots fall back, the
circular one goes round, the fastest rises on an ellipse. Writes img/anim-01-cannon.gif."""
import numpy as np
from scipy.integrate import solve_ivp
from _visual import plt, save_anim, earth_disc, INK, MAROON, BLUE, GREEN, AMBER, PURPLE, GREY
from flight.gravity import point_mass
from flight.constants import A_EARTH as R, MU

H = 0.5 * R
r0 = R + H
VC = np.sqrt(MU / r0)
FRACS = [0.5, 0.7, 0.8, 0.85, 1.0, 1.05]
COLS = [MAROON, AMBER, GREEN, PURPLE, BLUE, INK]
T_END = 2 * np.pi * np.sqrt(((r0 + r0 * 1.05**2 / (2 - 1.05**2)) / 2) ** 3 / MU)   # one period of the largest orbit


def fly(f):
    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
    s = solve_ivp(rhs, (0, T_END), [0.0, r0, f * VC, 0.0], events=hit, rtol=1e-10, atol=1e-3, dense_output=True)
    return s


SOL = [fly(f) for f in FRACS]

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 8.2))
    N, fps = 150, 18
    times = np.linspace(0, T_END, N)

    def frame(k):
        ax.clear()
        earth_disc(ax, R / 1e3)
        ax.plot([0, 0], [R / 1e3, r0 / 1e3], color=GREY, lw=6, solid_capstyle="butt")       # the mountain
        ax.plot([0], [r0 / 1e3], marker=(3, 0, -90), ms=16, color=INK)
        t = times[k]
        for f, s, c in zip(FRACS, SOL, COLS):
            te = min(t, s.t[-1])
            tt = np.linspace(0, te, 500)
            x, y = s.sol(tt)[0] / 1e3, s.sol(tt)[1] / 1e3
            ax.plot(x, y, color=c, lw=2.4)
            ax.plot(x[-1], y[-1], "o", color=c, ms=8)
            if s.t[-1] < T_END * 0.999 and te >= s.t[-1]:                  # landed: label at the impact point
                u = np.array([x[-1], y[-1]]) / np.hypot(x[-1], y[-1])
                ax.annotate(f"{f:g} $v_c$", (x[-1], y[-1]), xytext=(26 * u[0], 26 * u[1]), textcoords="offset points",
                            fontsize=12, color=c, ha="center", va="center")
        if k == N - 1:
            th = np.radians(205)
            ax.annotate("$v_c$: a circle", (r0 / 1e3 * np.cos(th), r0 / 1e3 * np.sin(th)), xytext=(-14, 0),
                        textcoords="offset points", fontsize=12, color=BLUE, ha="right", va="center")
            ya = SOL[-1].sol(T_END / 2)[1] / 1e3
            ax.annotate("$1.05\\,v_c$: an ellipse", (0, ya), xytext=(0, -16), textcoords="offset points",
                        fontsize=12, color=INK, ha="center", va="top")
        ax.set_aspect("equal")
        ax.set_xlim(-1.75 * R / 1e3, 1.75 * R / 1e3)
        ax.set_ylim(-2.05 * R / 1e3, 1.9 * R / 1e3)
        ax.axis("off")
        ax.text(0.0, 1.0, "Horizontal shots from a mountain half an Earth radius high, no air", transform=ax.transAxes,
                fontsize=12, va="top")
        ax.text(1.0, 0.93, f"t = {t / 60:3.0f} min", transform=ax.transAxes, fontsize=12, ha="right", va="top")
        return []

    save_anim(fig, frame, N, fps, "anim-01-cannon")
