"""Figure for ballistic-trajectories-bates.qmd (img/fig-bal-paths.png): families of free-flight arcs from one launch point.

(a) Q = 0.8: flight-path angles from 8 to 70 degrees. The range first grows, peaks at gamma = 45 - psi_max/4 = 24.1 deg, then shrinks again.
(b) Q = 1.2: every arc reaches beyond 90 degrees; the flat ones go more than half way round (psi > 180 deg, 'the long way').
Burnout at the surface (r_bo = R); the launch point is at the top, the flight runs clockwise.

Run from the sfm-slides directory:   python3 codes/fig-bal-paths.py
"""
import numpy as np
import _figfont                                # all figure text at one scale
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from _manstyle import INK, MAROON, BLUE, GREEN, AMBER, PURPLE
from _ballistic import psi_of, ecc, psi_max

D = np.pi / 180


def arc(Q, g):
    e = ecc(Q, g); a = 1 / (2 - Q); p = a * (1 - e * e)
    psi = psi_of(Q, g); fbo = np.pi - psi / 2
    f = np.linspace(fbo, 2 * np.pi - fbo, 400)
    r = p / (1 + e * np.cos(f)); ang = np.pi / 2 - (f - fbo)
    return r * np.cos(ang), r * np.sin(ang), psi


fig, ax = plt.subplots(1, 2, figsize=(12.6, 6.0))
for k, (Q, gl, ttl) in enumerate(((0.8, [8, 15, 24.095, 35, 50, 70], "(a)  $Q=0.8$"), (1.2, [8, 15, 30, 50, 70], "(b)  $Q=1.2$"))):
    A = ax[k]
    A.add_patch(Circle((0, 0), 1.0, color="#dfe9f3", ec=BLUE, lw=1.4, zorder=1))
    cols = [BLUE, "#4b7bb8", PURPLE, GREEN, AMBER, MAROON]
    for j, gd in enumerate(gl):
        x, y, psi = arc(Q, gd * D)
        mx = abs(gd - 24.095) < 1e-3 and Q < 1
        A.plot(x, y, color=PURPLE if mx else cols[j % len(cols)], lw=3.0 if mx else 1.8, zorder=4,
               label=f"$\\gamma={gd:.1f}^\\circ$ (max range), $\\psi={np.degrees(psi):.1f}^\\circ$" if mx else f"$\\gamma={gd:.0f}^\\circ$, $\\psi={np.degrees(psi):.1f}^\\circ$")
        A.scatter([x[-1]], [y[-1]], color=INK, s=14, zorder=6)
        print(f"Q={Q} gamma={gd:6.2f}: psi={np.degrees(psi):7.2f}")
    A.scatter([0], [1.0], color=AMBER, s=55, zorder=7); A.text(-0.45, 1.06, "launch", color=AMBER, fontsize=10.5)
    A.set_aspect("equal"); A.axis("off")
    if Q < 1:
        A.set_xlim(-1.25, 1.6); A.set_ylim(-1.15, 1.9)
    else:
        A.set_xlim(-2.6, 3.0); A.set_ylim(-2.6, 3.4)
    A.legend(loc="lower left" if Q < 1 else "upper left", fontsize=9.5, frameon=False)
    A.set_title(ttl, fontsize=12, loc="left")
fig.tight_layout()
fig.savefig("img/fig-bal-paths.png", dpi=150, bbox_inches="tight")
