"""Lecture 11, the sonic boom: a Tejas at Mach 1.8 at an assumed 12 km (Mach 1.8 from Raol & Singh, App. A12) in air
of uniform temperature, with its Mach cone trailing behind. An observer on the ground hears nothing when the aircraft
passes overhead; the cone reaches them cone_ground_distance(h, M) later (flight.gasdynamics), with the double bang
of the N-wave. The real atmosphere bends the cone, so this is the uniform-air picture. Writes img/anim-11-boom.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREEN, INK, GREY
from flight import gasdynamics as GD, atmosphere as A

M, H = 1.8, 12000.0
A12 = A.speed_of_sound(A.isa(H)[0])
V = M * A12
MU = GD.mach_angle(M)
X_BEHIND = GD.cone_ground_distance(H, M)
T_DELAY = X_BEHIND / V
T = np.linspace(-10.0, 60.0, 141)           # s, time since the aircraft passed over the observer at x = 0

if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(2, 1, figsize=(11, 6.4), gridspec_kw=dict(height_ratios=[2.2, 1]))
    fig.subplots_adjust(hspace=0.45, top=0.93, bottom=0.1)

    def frame(k):
        t = T[k]
        a1.clear(); a2.clear()
        xa = V * t / 1e3
        a1.axhline(0, color=INK, lw=2, zorder=3)
        a1.axhspan(-4, 0, color="#e9e2d0", zorder=2)
        L = 140.0
        a1.fill([xa, xa - L * np.cos(MU), xa - L * np.cos(MU)], [H / 1e3, H / 1e3 + L * np.sin(MU), H / 1e3 - L * np.sin(MU)],
                color="#f1dcdc", zorder=0)
        for s in (1, -1):
            a1.plot([xa, xa - L * np.cos(MU)], [H / 1e3, H / 1e3 + s * L * np.sin(MU)], color=MAROON, lw=1.8, zorder=1)
        a1.plot(xa, H / 1e3, ">", color=INK, ms=12)
        heard = t >= T_DELAY
        a1.plot(0, 0.25, "o", color=MAROON if heard else BLUE, ms=11, zorder=5)
        a1.text(0, -2.6, "observer", ha="center", fontsize=12, zorder=4)
        if heard:
            a1.text(1.2, 1.0, "boom!", color=MAROON, fontsize=15, weight="bold")
        a1.set_xlim(-25, 35); a1.set_ylim(-3.5, 16)
        a1.set_xlabel("distance (km)"); a1.set_ylabel("height (km)")
        a1.set_title(f"$M={M}$ at {H / 1e3:.0f} km: {t:5.1f} s after passing overhead", fontsize=13, loc="left")
        for s_ in ("top", "right"):
            a1.spines[s_].set_visible(False)
        tt = np.linspace(-10, 60, 2000)
        dp = np.where((tt >= T_DELAY) & (tt <= T_DELAY + 1.2), 1 - 2 * (tt - T_DELAY) / 1.2, 0.0)
        show = tt <= t
        a2.plot(tt[show], dp[show], color=MAROON, lw=2)
        a2.axvline(0, color=GREY, ls=":", lw=1); a2.text(0.5, 0.75, "overhead", color=GREY, fontsize=11)
        a2.set_xlim(-10, 60); a2.set_ylim(-1.3, 1.3)
        a2.set_yticks([]); a2.set_xlabel("time at the observer (s)")
        a2.set_ylabel("pressure")
        a2.set_title("the N-wave (shape only, not to scale in time)", fontsize=12, loc="left")
        for s_ in ("top", "right"):
            a2.spines[s_].set_visible(False)
        return []

    save_anim(fig, frame, len(T), 12, "anim-11-boom", dpi=90, hold=2.5)
