"""Lecture 18, two ceilings: the Tejas-class fighter at 8500 kg with full afterburner, climbing from 15 to 19.6 km.
Left: thrust and drag per unit weight against Mach number with the level-flight solutions. Right: the Mach numbers of
the solutions against altitude, traced as the climb goes on, with the heights where four solutions appear (17.49 km),
the subsonic ceiling (17.91 km) and the supersonic ceiling (19.28 km) from fig-18-envelope. The last frame is the
complete picture. Writes img/anim-18-ceilings.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREEN, INK, GREY
import _fighter as F
from _scripts import load

V, MASS = F.TEJ, F.M_REF
M = np.linspace(0.4, 2.2, 400)
HS = np.linspace(15000.0, 19600.0, 93)
ROOTS = [F.level_machs(V, MASS, h, lo=0.4, hi=2.2) for h in HS]
E = load("fig-18-envelope")
MARKS = [(E.H_FOUR, "four solutions", -0.15), (E.H_SUBSONIC_CEILING, "subsonic ceiling", 0.05), (E.H_SUPERSONIC_CEILING, "supersonic ceiling", 0.0)]

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 5), gridspec_kw=dict(width_ratios=[1.25, 1]))
    fig.subplots_adjust(wspace=0.28, bottom=0.14, right=0.83)

    def frame(k):
        a1.clear(); a2.clear()
        h = HS[k]
        w = F.omega(V, MASS, h)
        a1.plot(M, [F.tau_r(V, x, MASS, h) / w for x in M], color=MAROON, lw=2.6, label="drag / weight")
        a1.plot(M, [F.tau_a(V, x, h) / w for x in M], color=BLUE, lw=2.2, ls="--", label="thrust / weight")
        r = ROOTS[k]
        a1.plot(r, [F.tau_r(V, x, MASS, h) / w for x in r], "o", color=INK, ms=8, zorder=5)
        a1.set_xlim(0.4, 2.2); a1.set_ylim(0, 0.6); a1.set_xlabel("Mach number"); a1.set_ylabel("$D/W$, $T/W$")
        a1.set_title(f"{h / 1e3:.2f} km: {len(r)} level-flight solutions", fontsize=13, loc="left")
        a1.legend(frameon=False, fontsize=12, loc="upper left")
        for j in range(k + 1):
            a2.plot(ROOTS[j], [HS[j] / 1e3] * len(ROOTS[j]), "o", color=GREEN, ms=3.5)
        for hm, lab, dy in MARKS:
            if hm <= h:
                a2.axhline(hm / 1e3, color=GREY, lw=1, ls=":")
                a2.text(2.03, hm / 1e3 + dy, f"{lab}\n{hm / 1e3:.2f} km", fontsize=11, color=INK, ha="left", va="center", clip_on=False)
        a2.set_xlim(0.4, 2.0); a2.set_ylim(15, 19.8); a2.set_xlabel("Mach number of the solutions"); a2.set_ylabel("altitude (km)")
        for a in (a1, a2):
            for s in ("top", "right"):
                a.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, len(HS), 10, "anim-18-ceilings", dpi=90, hold=3.0)
