"""Lecture 11, sound waves from a moving source at Mach 0.5, 1 and 2. A wave sent out at time t_i from the position
V t_i is, at time t, a circle of radius a (t - t_i). Below Mach 1 the waves run ahead of the source; at Mach 1 they
pile up at its nose; above Mach 1 they fill a cone of half-angle mu, sin mu = 1/M (flight.gasdynamics.mach_angle).
Writes img/anim-11-waves.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, GREEN, INK, GREY
from flight import gasdynamics as GD

MACHS = (0.5, 1.0, 2.0)
T_END, DT_EMIT = 6.0, 0.5          # in units where a = 1
EMITS = np.arange(0.0, T_END + 1e-9, DT_EMIT)
MU2 = GD.mach_angle(2.0)


def draw(ax, M, t):
    ax.clear()
    xs = M * t
    for ti in EMITS[EMITS <= t]:
        r = t - ti
        th = np.linspace(0, 2 * np.pi, 200)
        ax.plot(M * ti + r * np.cos(th), r * np.sin(th), color=BLUE, lw=1.1, alpha=0.8)
    ax.plot(xs, 0, "o", color=MAROON, ms=9, zorder=5)
    if M > 1 and t > 1.5:
        L = t * M
        for s in (1, -1):
            ax.plot([xs, xs - L * np.cos(MU2)], [0, s * L * np.sin(MU2)], color=MAROON, lw=1.6, ls="--")
        ax.text(xs - 3.2, 2.9, f"$\\mu={np.degrees(MU2):.0f}^\\circ$", color=MAROON, fontsize=14,
                bbox=dict(facecolor="#faf8f2", edgecolor="none", pad=1))
    name = GD.regime(M) if M != 1.0 else "sonic"
    ax.set_title(f"$M={M:g}$  ({name})", fontsize=14)
    ax.set_xlim(-T_END - 0.5, max(M * T_END, T_END) + 0.8)
    ax.set_ylim(-T_END - 0.5, T_END + 0.5)
    ax.set_aspect("equal")
    ax.axis("off")


if __name__ == "__main__":
    fig, axs = plt.subplots(1, 3, figsize=(12, 4.4), gridspec_kw=dict(width_ratios=[13.3, 13.3, 19.3]))
    fig.subplots_adjust(left=0.01, right=0.99, top=0.88, bottom=0.02, wspace=0.05)
    N = 54
    ts = np.linspace(0.01, T_END, N)

    def frame(k):
        for ax, M in zip(axs, MACHS):
            draw(ax, M, ts[k])
        return []

    save_anim(fig, frame, N, 10, "anim-11-waves", dpi=80, hold=2.5)
