"""Lecture 28: three rockets with the same propellant (fraction 0.8, V_E = 3000 m/s) fired straight up in a vacuum
with uniform gravity, at initial thrust-to-weight ratios 1.2, 2 and 5 (constant thrust). Height against time up to
each peak; a filled marker while the engine burns, a hollow one while coasting. Writes img/anim-28-gravity.gif."""
import numpy as np
from _visual import plt, save_anim, despine, MAROON, BLUE, GREEN, INK
from flight import rocket as R, performance as PF
from flight.constants import G0

ZETA, VE = 0.8, 3000.0
CASES = []
for tau, c in ((1.2, MAROON), (2.0, BLUE), (5.0, GREEN)):
    d = R.vertical_constant_thrust(ZETA, tau)
    tb = d["theta_c"] * VE / G0
    tf = tb + d["u_c"] * VE / G0
    t = np.linspace(0, tf, 600)
    thp = np.minimum(t, tb) * G0 / VE
    hp = np.array([R.vertical_constant_thrust(tau * th, tau)["eta_c"] if th > 0 else 0.0 for th in thp]) * VE**2 / G0
    s = np.maximum(t - tb, 0.0)
    h = hp + PF.zero_g_arc(d["u_c"] * VE, np.pi / 2, s)[1]       # the coast
    CASES.append(dict(tau=tau, c=c, t=t, h=h, tb=tb, tf=tf, hc=d["eta_c"] * VE**2 / G0, hf=d["eta_f"] * VE**2 / G0,
                      uc=d["u_c"] * VE))

N = 90
TMAX = max(cs["tf"] for cs in CASES)

if __name__ == "__main__":
    fig, ax = plt.subplots(figsize=(10, 5.0))
    ax.set_xlim(0, TMAX * 1.02); ax.set_ylim(0, max(cs["hf"] for cs in CASES) / 1e3 * 1.38)
    ax.set_xlabel("time (s)"); ax.set_ylabel("height (km)"); despine(ax)
    lines, dots = [], []
    for cs in CASES:
        lines.append(ax.plot([], [], color=cs["c"], lw=2.4, label=f"T/W {cs['tau']}: burns {cs['tb']:.0f} s, peak {cs['hf'] / 1e3:.0f} km")[0])
        dots.append(ax.plot([], [], "o", color=cs["c"], ms=9)[0])
    ax.legend(handles=lines, frameon=False, fontsize=10, loc="upper left")
    fig.subplots_adjust(left=0.1, right=0.98, bottom=0.15, top=0.97)

    def frame(k):
        now = TMAX * k / (N - 1)
        for cs, ln, dt in zip(CASES, lines, dots):
            m = cs["t"] <= now
            ln.set_data(cs["t"][m], cs["h"][m] / 1e3)
            if m.any():
                dt.set_data([cs["t"][m][-1]], [cs["h"][m][-1] / 1e3])
                dt.set_markerfacecolor(cs["c"] if now < cs["tb"] else "none")
    save_anim(fig, frame, N, 15, "anim-28-gravity")
