"""Lecture 13, Newton's model of hypersonic flow: air particles travel in straight lines, hit the windward surface,
lose the velocity component normal to it and slide along it; the shadow side feels nothing. The pressure is the
lost normal momentum flux, C_p = 2 sin^2(theta) (flight.aero.newtonian_cp). A flat plate at 20 deg.
Writes img/anim-13-newton.gif."""
import numpy as np
from _visual import plt, save_anim, MAROON, BLUE, INK, GREY
from flight import aero as AE

ALPHA = np.radians(20.0)
T_ = np.array([np.cos(ALPHA), -np.sin(ALPHA)])       # along the plate, nose at the origin, trailing edge down-right
N_ = np.array([np.sin(ALPHA), np.cos(ALPHA)])        # normal, pointing up (to the shadow side)
YS = np.linspace(-0.55, 0.25, 15)
N_FRAMES = 60
DT = 0.05


def particle(x0, y0, t):
    """Position at time t of a particle that starts at (x0, y0) with unit speed to the right. If its straight path
    meets the windward (lower) face of the plate, it keeps only its tangential velocity, cos(alpha) along the plate,
    and leaves at the trailing edge."""
    sa, ca = np.sin(ALPHA), np.cos(ALPHA)
    t_c = -(x0 * sa + y0 * ca) / sa                 # time at which the path crosses the plate's line
    p_c = np.array([x0 + t_c, y0])
    s_c = np.dot(p_c, T_)                            # where along the plate it would land
    if t >= t_c and 0.0 <= s_c <= 1.0:
        return p_c + T_ * ca * (t - t_c), True
    return np.array([x0 + t, y0]), False


L_LOOP = 3.0                                     # each particle re-enters at the left after this distance
PARTICLES = [(y0, ((7 * i + 3 * j) % 11) / 11 * L_LOOP / 6 + j * L_LOOP / 6) for i, y0 in enumerate(YS) for j in range(6)]


def position(y0, phase, t):
    """A particle of a steady stream: it entered at x = -1.25 a time ((phase + t) mod L_LOOP) ago."""
    age = (phase + t) % L_LOOP
    return particle(-1.25, y0, age)


if __name__ == "__main__":
    fig, (a1, a2) = plt.subplots(1, 2, figsize=(11, 5.0), gridspec_kw=dict(width_ratios=[1.3, 1]))
    fig.subplots_adjust(wspace=0.25, bottom=0.14)
    al = np.radians(np.linspace(0, 60, 200))

    def frame(k):
        a1.clear(); a2.clear()
        a1.plot([0, T_[0]], [0, T_[1]], color=INK, lw=4)
        for y0, ph in PARTICLES:
            pp, hh = position(y0, ph, k * DT)
            if -1.25 <= pp[0] < 1.6 and pp[1] > -1.0:
                a1.plot(*pp, "o", color=MAROON if hh else BLUE, ms=3.5)
        a1.set_xlim(-1.25, 1.6); a1.set_ylim(-1.0, 0.6); a1.set_aspect("equal"); a1.axis("off")
        a1.set_title("particles lose their normal velocity", fontsize=13, loc="left")
        a2.plot(np.degrees(al), AE.newtonian_cp(al), color=MAROON, lw=2.5)
        a2.plot(20, AE.newtonian_cp(ALPHA), "o", color=MAROON, ms=8)
        a2.text(23, AE.newtonian_cp(ALPHA) - 0.05, f"$C_p={float(AE.newtonian_cp(ALPHA)):.3f}$ at $20^\\circ$", fontsize=12)
        a2.set_xlabel("surface angle $\\theta$ (deg)"); a2.set_ylabel("$C_p=2\\sin^2\\theta$")
        a2.set_xlim(0, 60); a2.set_ylim(0, 1.6)
        for s in ("top", "right"):
            a2.spines[s].set_visible(False)
        return []

    save_anim(fig, frame, N_FRAMES, 12, "anim-13-newton", dpi=90, hold=1.5)
