"""Animation of Example 1 of patched-conics.qmd: the whole Earth-Mars Hohmann transfer, conic by conic.

Four panels, all in the same non-rotating axes (the Sun-Earth line at launch is the x axis, the planets move
anticlockwise):
  1  the Earth's sphere of influence: half a turn of the 300 km parking orbit, the burn at periapsis, and the
     departure hyperbola out to the sphere of influence (the view zooms out with the spacecraft);
  2  the Sun's frame: the Earth, Mars and the spacecraft over the 258.9-day transfer ellipse;
  3  the last 3.6 days before periapsis at Mars, close up and still in the Sun's frame: Mars, faster, catches up
     with the spacecraft, and its sphere of influence sweeps over it from in front.  Outside the sphere the
     spacecraft is propagated about the Sun alone (backwards from the entry point); inside, its position is
     Mars's plus the arrival hyperbola's, so this panel runs on the same clock as panel 4;
  4  Mars's sphere of influence: the arrival hyperbola from the sphere of influence in to periapsis (the view
     zooms in), the capture burn, and one turn of the 300 km circular orbit.
Each conic runs on its own clock, as the method itself does; the speed of each phase is not to scale with the
others.  Inside the spheres the frames are uniform in the hyperbolic anomaly F, so the spacecraft is slowed near
periapsis and hurried far out; in the Sun's frame the frames are uniform in time, so the spacecraft visibly
slows from perihelion to aphelion.

Run from the sfm-slides directory:   python3 codes/anim-pc-earth-mars.py
Writes img/anim-pc-earth-mars.gif.
"""
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 CREAM, INK, MAROON, BLUE, GREEN, AMBER
from _gif import save_gif

muS, AU, DAY = 1.327124e11, 1.495979e8, 86400.0
muE, RE = 398600.4, 6378.1
muM, RMa, TM, TE = 42828.4, 3396.2, 686.98, 365.256
r1, r2 = AU, 1.52368*AU

# ------------------------------------------------------------------ the numbers of Example 1
at = (r1 + r2)/2
VE, VM = np.sqrt(muS/r1), np.sqrt(muS/r2)
Vt1, Vt2 = np.sqrt(muS*(2/r1 - 1/at)), np.sqrt(muS*(2/r2 - 1/at))
t12 = np.pi*np.sqrt(at**3/muS)/DAY
vi1, vi2 = Vt1 - VE, VM - Vt2
phi0 = np.pi - 2*np.pi*t12/TM
rsE, rsM = r1*(muE/muS)**0.4, r2*(muM/muS)**0.4


class Hyperbola:
    """Planet-centred hyperbola with periapsis radius rp, excess speed vi, periapsis direction w (rad)."""
    def __init__(s, mu, rp, vi, w):
        s.mu, s.rp, s.w = mu, rp, w
        s.a = mu/vi**2                                    # |a|
        s.e = 1 + rp*vi**2/mu
        s.vp = np.sqrt(vi**2 + 2*mu/rp)
        s.finf = np.arccos(-1/s.e)

    def F_at(s, r):
        return np.arccosh((1 + r/s.a)/s.e)

    def time(s, F):
        return np.sqrt(s.a**3/s.mu)*(s.e*np.sinh(F) - F)

    def xy(s, F):
        F = np.asarray(F, float)
        r = s.a*(s.e*np.cosh(F) - 1)
        f = 2*np.arctan(np.sqrt((s.e + 1)/(s.e - 1))*np.tanh(F/2))
        return np.stack([r*np.cos(f + s.w), r*np.sin(f + s.w)], axis=-1)

    def centre(s):
        return s.a*s.e*np.array([np.cos(s.w), np.sin(s.w)])


rp1, rp2 = RE + 300, RMa + 300
# departure: outgoing asymptote along +y (the Earth's velocity at launch), so periapsis is f_inf before +y
dep = Hyperbola(muE, rp1, vi1, np.pi/2 - np.arccos(-1/(1 + rp1*vi1**2/muE)))
# arrival: Mars is at aphelion of the transfer, on the -x axis, moving towards -y.  v_inf2 points backwards (+y),
# so the spacecraft comes in from the -y side (in front of Mars), on the Sun's side (+x), anticlockwise.
arr = Hyperbola(muM, rp2, vi2, np.arccos(-1/(1 + rp2*vi2**2/muM)) - np.pi/2)
F1, F2 = dep.F_at(rsE), arr.F_at(rsM)
vc1, vc2 = np.sqrt(muE/rp1), np.sqrt(muM/rp2)
dv1, dv2 = dep.vp - vc1, arr.vp - vc2
b2 = rp2*np.sqrt(1 + 2*muM/(rp2*vi2**2))

# the arrival asymptote must be the line x = +b (Sun's side), travelled towards +y
far = arr.xy(-F2*1.5)
assert far[1] < -10*b2 and abs(far[0] - b2) < 0.05*b2, far
for val, ref, tol in ((vi1, 2.945, 1e-3), (vi2, 2.649, 1e-3), (t12, 258.9, 0.05), (np.degrees(phi0), 44.3, 0.05),
                      (dv1, 3.590, 1e-3), (dv2, 2.091, 1e-3), (np.degrees(dep.finf), 150.8, 0.05),
                      (b2, 7667, 1.0), (dep.time(F1)/DAY, 3.2, 0.05)):
    assert abs(val - ref) < tol, (val, ref)
print(f"t12 = {t12:.1f} d, phi0 = {np.degrees(phi0):.1f} deg, v_inf = {vi1:.3f}, {vi2:.3f} km/s")
print(f"Earth SOI {rsE:.0f} km, exit after {dep.time(F1)/DAY:.2f} d;  Mars SOI {rsM:.0f} km, "
      f"entry {arr.time(F2)/DAY:.2f} d before periapsis")


# ------------------------------------------------------------------ the close-up of the arrival (Sun's frame)
# t is time from periapsis at Mars (s); Mars is at aphelion of the transfer, (-r2, 0), at t = 0.  Local
# coordinates: X = x + r2, Y = y, in millions of km.
nM = np.sqrt(muS/r2**3)
T_NEAR = 3.6*DAY


def mars_at(t):
    th = np.pi + nM*t
    return r2*np.array([np.cos(th), np.sin(th)]), r2*nM*np.array([-np.sin(th), np.cos(th)])


def sc_inside(F):
    """Sun-frame position of the spacecraft inside Mars's sphere: Mars's position plus the hyperbola's."""
    return np.moveaxis(mars_at(arr.time(F))[0], 0, -1) + arr.xy(F)


t_entry = arr.time(-F2)                                    # negative: entry 2.4 days before periapsis
h = 1e-6
v_rel = (arr.xy(-F2 + h) - arr.xy(-F2 - h))/(arr.time(-F2 + h) - arr.time(-F2 - h))
y = np.concatenate([sc_inside(-F2), mars_at(t_entry)[1] + v_rel])


def rhs(y):
    return np.concatenate([y[2:], -muS*y[:2]/np.linalg.norm(y[:2])**3])


N_RK = 2000                                                # RK4 backwards, Sun only, from entry to -T_NEAR
dt = (-T_NEAR - t_entry)/N_RK
t_out, xy_out = [t_entry], [y[:2]]
for _ in range(N_RK):
    k1 = rhs(y); k2 = rhs(y + dt/2*k1); k3 = rhs(y + dt/2*k2); k4 = rhs(y + dt*k3)
    y = y + dt/6*(k1 + 2*k2 + 2*k3 + k4)
    t_out.append(t_out[-1] + dt); xy_out.append(y[:2])
t_out, xy_out = np.array(t_out[::-1]), np.array(xy_out[::-1])   # increasing time, -T_NEAR .. t_entry


def sc_outside(t):
    return np.array([np.interp(t, t_out, xy_out[:, 0]), np.interp(t, t_out, xy_out[:, 1])])


def local(P):
    P = np.atleast_2d(P)
    return np.stack([(P[:, 0] + r2)/1e6, P[:, 1]/1e6], axis=-1)


# outside the sphere the spacecraft trails Mars along the same line: it is ahead of Mars and slower
d0 = xy_out[0] - mars_at(-T_NEAR)[0]
assert d0[1] < -rsM and abs(d0[0]) < 0.05*rsM, d0
assert np.linalg.norm(rhs(y)[2:] - rhs(np.concatenate([mars_at(-T_NEAR)[0], [0, 0]]))[2:]) < 1e-8
print(f"close-up: at -{T_NEAR/DAY:.1f} d the spacecraft is {-d0[1]:.0f} km ahead of Mars "
      f"({-d0[1]/rsM:.2f} sphere radii); it enters {-t_entry/DAY:.2f} d before periapsis")


def helio(td):
    """Sun-frame positions (AU) of the Earth, Mars and the spacecraft td days after launch (td in [0, t12])."""
    E = np.array([np.cos(2*np.pi*td/TE), np.sin(2*np.pi*td/TE)])
    thM = phi0 + 2*np.pi*td/TM
    M = r2/AU*np.array([np.cos(thM), np.sin(thM)])
    et = (r2 - r1)/(r2 + r1)
    Mt = np.pi*td/t12                                      # mean anomaly on the transfer ellipse
    Ek = Mt
    for _ in range(30):
        Ek -= (Ek - et*np.sin(Ek) - Mt)/(1 - et*np.cos(Ek))
    f = 2*np.arctan2(np.sqrt(1 + et)*np.sin(Ek/2), np.sqrt(1 - et)*np.cos(Ek/2))
    rr = at*(1 - et**2)/(1 + et*np.cos(f))/AU
    return E, M, rr*np.array([np.cos(f), np.sin(f)])


# ------------------------------------------------------------------ frame schedule
N_PARK, N_BURN1, N_DEP, N_HELIO, N_NEAR, N_ARR, N_BURN2, N_CAP, N_END = 40, 14, 90, 170, 70, 90, 14, 40, 40
starts = np.cumsum([0, N_PARK, N_BURN1, N_DEP, N_HELIO, N_NEAR, N_ARR, N_BURN2, N_CAP, N_END])
N_TOTAL = starts[-1]

fig = plt.figure(figsize=(18.6, 6.2))
gs = fig.add_gridspec(1, 4, width_ratios=[1, 1.35, 0.42, 1], wspace=0.08)
aE, aS, aN, aM = [fig.add_subplot(gs[0, k]) for k in range(4)]
for ax in (aE, aS, aN, aM):
    ax.set_aspect("equal"); ax.axis("off")
tt = np.linspace(0, 2*np.pi, 400)


def fixed_arrow(ax, xy0, xy1, col, txt, tx):
    ax.annotate("", xy=xy1, xytext=xy0, xycoords="axes fraction",
                arrowprops=dict(arrowstyle="-|>", color=col, lw=1.8, shrinkA=0, shrinkB=0))
    ax.text(*tx, txt, transform=ax.transAxes, color=col, fontsize=9.5, ha="center", va="center")


# left: the Earth's sphere of influence
aE.add_patch(Circle((0, 0), RE, color=BLUE, alpha=0.55, lw=0))
aE.plot(0, 0, "o", color=BLUE, ms=4)
aE.plot(rp1*np.cos(tt), rp1*np.sin(tt), color=INK, lw=0.9, ls=":")
aE.plot(rsE*np.cos(tt), rsE*np.sin(tt), color=INK, lw=1.0, ls=(0, (5, 4)))
aE.text(0, rsE*1.03, "sphere of influence", ha="center", va="bottom", fontsize=9, color=INK, clip_on=True)
cE = dep.centre()
aE.plot([cE[0], cE[0]], [cE[1], cE[1] + 3*rsE], color=GREEN, lw=0.9, ls="--", alpha=0.7)
trE, = aE.plot([], [], color=GREEN, lw=2.2)
scE, = aE.plot([], [], "o", color=INK, ms=7, mec=CREAM, zorder=6)
burnE, = aE.plot([], [], "*", color=AMBER, ms=20, mec=MAROON, zorder=7)
fixed_arrow(aE, (0.08, 0.10), (0.08, 0.24), INK, r"$\mathbf{V}_\oplus$", (0.13, 0.17))
fixed_arrow(aE, (0.28, 0.06), (0.14, 0.06), AMBER, "to the Sun", (0.21, 0.025))
infoE = aE.text(0.5, -0.02, "", transform=aE.transAxes, ha="center", va="top", fontsize=10.5, color=INK)
scaleE = aE.text(0.98, 0.02, "", transform=aE.transAxes, ha="right", va="bottom", fontsize=9, color=INK)
ttlE = aE.set_title("", fontsize=12)

# centre: the Sun's frame
aS.plot(np.cos(tt), np.sin(tt), color=BLUE, lw=0.9, ls=(0, (4, 3)))
aS.plot(r2/AU*np.cos(tt), r2/AU*np.sin(tt), color=MAROON, lw=0.9, ls=(0, (4, 3)))
et_ = (r2 - r1)/(r2 + r1)
fT = np.linspace(0, 2*np.pi, 400)
rT = at*(1 - et_**2)/(1 + et_*np.cos(fT))/AU
aS.plot(rT*np.cos(fT), rT*np.sin(fT), color=GREEN, lw=0.8, ls=":", alpha=0.6)
aS.plot(0, 0, "o", color=AMBER, ms=16, mec=MAROON, mew=0.8)
M0 = r2/AU*np.array([np.cos(phi0), np.sin(phi0)])
aS.plot([0, 1.62], [0, 0], color=INK, lw=0.7, alpha=0.6)
aS.plot([0, 1.08*M0[0]], [0, 1.08*M0[1]], color=INK, lw=0.7, alpha=0.6)
arc = np.linspace(0, phi0, 40)
aS.plot(0.42*np.cos(arc), 0.42*np.sin(arc), color=MAROON, lw=1.2)
aS.text(0.53*np.cos(phi0/2), 0.53*np.sin(phi0/2), rf"$\phi_0={np.degrees(phi0):.1f}^\circ$", color=MAROON,
        fontsize=10.5, ha="left", va="center")
aS.plot(*M0, "o", color=MAROON, ms=7, alpha=0.3)
aS.plot(-r2/AU, 0, "x", color=MAROON, ms=9, mew=1.6, alpha=0.6)
aS.text(-r2/AU, -0.13, "arrival\n(aphelion)", ha="center", va="top", fontsize=9, color=MAROON)
trS, = aS.plot([], [], color=GREEN, lw=2.4)
trEarth, = aS.plot([], [], color=BLUE, lw=1.6, alpha=0.6)
trMars, = aS.plot([], [], color=MAROON, lw=1.6, alpha=0.6)
pE, = aS.plot([], [], "o", color=BLUE, ms=11, mec=INK, mew=0.6, zorder=5)
pM, = aS.plot([], [], "o", color=MAROON, ms=9, mec=INK, mew=0.6, zorder=5)
pS, = aS.plot([], [], "o", color=INK, ms=5.5, mec=CREAM, zorder=6)
lE = aS.text(0, 0, "Earth", color=BLUE, fontsize=10.5, ha="center", va="center")
lM = aS.text(0, 0, "Mars", color=MAROON, fontsize=10.5, ha="center", va="center")
# the window of panel 3, to scale (a thin box about the arrival point)
XN, YN = (-1.5, 1.8), (-3.0, 8.4)
aS.add_patch(plt.Rectangle((-r2/AU + XN[0]*1e6/AU, YN[0]*1e6/AU), (XN[1] - XN[0])*1e6/AU,
                           (YN[1] - YN[0])*1e6/AU, fill=False, ec=INK, lw=0.9))
aS.text(-r2/AU + 0.03, 0.16, "3", fontsize=9, color=INK, ha="left", va="center")
aS.set_xlim(-1.78, 1.78); aS.set_ylim(-1.66, 1.66)
infoS = aS.text(0.5, -0.02, "", transform=aS.transAxes, ha="center", va="top", fontsize=10.5, color=INK)
ttlS = aS.set_title("", fontsize=12)

# panel 3: the arrival, close up, in the Sun's frame
tN = np.linspace(-T_NEAR - 0.3*DAY, 0.2*DAY, 200)
aN.plot(*local(np.array([mars_at(t)[0] for t in tN])).T, color=MAROON, lw=0.9, ls=(0, (4, 3)))
aN.set_xlim(*XN); aN.set_ylim(*YN)
soiN = Circle((0, 0), rsM/1e6, fill=False, ec=MAROON, lw=1.1, ls=(0, (5, 3)))
aN.add_patch(soiN)
ghostN = Circle((0, 0), rsM/1e6, fill=False, ec=MAROON, lw=0.8, ls=":", alpha=0.0)
aN.add_patch(ghostN)
trN, = aN.plot([], [], color=GREEN, lw=2.2)
pMN, = aN.plot([], [], "o", color=MAROON, ms=9, mec=INK, mew=0.6, zorder=5)
pSN, = aN.plot([], [], "o", color=INK, ms=5.5, mec=CREAM, zorder=6)
entN, = aN.plot([], [], "x", color=INK, ms=8, mew=1.6, zorder=7)
entNt = aN.text(0, 0, "", fontsize=8.5, color=INK, ha="left", va="center")
lMN = aN.text(0, 0, "Mars", fontsize=9, color=MAROON, ha="right", va="center")
lSN = aN.text(0, 0, "spacecraft", fontsize=9, color=INK, ha="left", va="center")
fixed_arrow(aN, (0.30, 0.06), (0.68, 0.06), AMBER, "to the Sun", (0.50, 0.025))
aN.plot([-0.5, 0.5], [YN[0] + 0.15*(YN[1] - YN[0])]*2, color=INK, lw=1.4)
aN.text(0, YN[0] + 0.16*(YN[1] - YN[0]), "1 million km", fontsize=8.5, color=INK, ha="center", va="bottom")
infoN = aN.text(0.5, -0.02, "", transform=aN.transAxes, ha="center", va="top", fontsize=10, color=INK)
ttlN = aN.set_title("", fontsize=12)

# panel 4: Mars's sphere of influence
aM.add_patch(Circle((0, 0), RMa, color=MAROON, alpha=0.5, lw=0))
aM.plot(0, 0, "o", color=MAROON, ms=4)
aM.plot(rp2*np.cos(tt), rp2*np.sin(tt), color=INK, lw=0.9, ls=":")
aM.plot(rsM*np.cos(tt), rsM*np.sin(tt), color=INK, lw=1.0, ls=(0, (5, 4)))
cM = arr.centre()
aM.plot([cM[0], cM[0]], [cM[1], cM[1] - 3*rsM], color=GREEN, lw=0.9, ls="--", alpha=0.7)
aM.text(0, rsM*1.03, "sphere of influence", ha="center", va="bottom", fontsize=9, color=INK, clip_on=True)
trM, = aM.plot([], [], color=GREEN, lw=2.2)
capM, = aM.plot([], [], color=MAROON, lw=2.2)
scM, = aM.plot([], [], "o", color=INK, ms=7, mec=CREAM, zorder=6)
burnM, = aM.plot([], [], "*", color=AMBER, ms=20, mec=MAROON, zorder=7)
fixed_arrow(aM, (0.08, 0.24), (0.08, 0.10), INK, r"$\mathbf{V}_{\rm M}$", (0.14, 0.17))
fixed_arrow(aM, (0.14, 0.06), (0.28, 0.06), AMBER, "to the Sun", (0.21, 0.025))
infoM = aM.text(0.5, -0.02, "", transform=aM.transAxes, ha="center", va="top", fontsize=10.5, color=INK)
scaleM = aM.text(0.98, 0.02, "", transform=aM.transAxes, ha="right", va="bottom", fontsize=9, color=INK)
ttlM = aM.set_title("", fontsize=12)

clock = fig.text(0.5, 0.955, "", ha="center", fontsize=13.5, color=INK, family="monospace")
fig.subplots_adjust(left=0.01, right=0.99, top=0.86, bottom=0.13)

TITLES = (("1. Earth's sphere of influence (Earth only)", BLUE), ("2. heliocentric ellipse (Sun only)", GREEN),
          ("3. arrival, close up\n(Sun's frame)", INK), ("4. Mars's sphere of influence (Mars only)", MAROON))


def titles(active):
    for k, (ttl, (txt, col)) in enumerate(zip((ttlE, ttlS, ttlN, ttlM), TITLES)):
        ttl.set_text(txt); ttl.set_color(col if k == active else "#9a948b")
        ttl.set_fontweight("bold" if k == active else "normal")


def zoom(ax, half, label):
    ax.set_xlim(-half, half); ax.set_ylim(-half, half)
    w = 2*half
    label.set_text(f"panel width {w:,.0f} km".replace(",", " ") if w < 1e5 else
                   f"panel width {w/1e6:.2f} million km")


def zoom_E(r):
    zoom(aE, max(3.2*RE, 1.25*r), scaleE)


def zoom_M(r):
    zoom(aM, max(4.2*RMa, 1.25*r), scaleM)


def km(x):
    return f"{x:,.0f}".replace(",", r"\,")


def show_helio(td):
    E, M, S = helio(td)
    tdd = np.linspace(0, td, max(2, int(td) + 2))
    pts = np.array([helio(x) for x in tdd])
    trS.set_data(pts[:, 2, 0], pts[:, 2, 1])
    trEarth.set_data(pts[:, 0, 0], pts[:, 0, 1]); trMars.set_data(pts[:, 1, 0], pts[:, 1, 1])
    pE.set_data([E[0]], [E[1]]); pM.set_data([M[0]], [M[1]]); pS.set_data([S[0]], [S[1]])
    for lab, P in ((lE, E), (lM, M)):
        lab.set_position(P*(1 + 0.2/np.linalg.norm(P)))


def show_near(t, F=None):
    """Panel 3 at time t from periapsis; inside the sphere pass the hyperbolic anomaly F as well."""
    M = local(mars_at(t)[0])[0]
    soiN.set_center(M); pMN.set_data([M[0]], [M[1]])
    k = np.searchsorted(t_out, min(t, t_entry))
    pts = list(xy_out[:k]) + ([sc_outside(t)] if F is None else list(sc_inside(np.linspace(-F2, F, 60))))
    pts = local(np.array(pts))
    trN.set_data(pts[:, 0], pts[:, 1]); pSN.set_data([pts[-1, 0]], [pts[-1, 1]])
    lMN.set_position((M[0] - 0.25, M[1])); lSN.set_position((pts[-1, 0] + 0.25, pts[-1, 1]))
    lSN.set_alpha(1.0 if M[1] - pts[-1, 1] > 0.35 else 0.0)
    inside = F is not None
    E = local(sc_inside(-F2))[0]
    entN.set_data(*(([E[0]], [E[1]]) if inside else ([], [])))
    entNt.set_position((E[0] + 0.2, E[1] - 0.45)); entNt.set_text("entry,\nin front\nof Mars" if inside else "")
    ghostN.set_center(local(mars_at(t_entry)[0])[0]); ghostN.set_alpha(0.6 if inside else 0.0)


def dep_path(F):
    pts = dep.xy(np.linspace(0, F, 400))
    trE.set_data(pts[:, 0], pts[:, 1]); scE.set_data([pts[-1, 0]], [pts[-1, 1]])
    return np.hypot(*pts[-1])


def arr_path(F):                                          # F runs from -F2 (entry) up to 0 (periapsis)
    pts = arr.xy(np.linspace(-F2, F, 400))
    trM.set_data(pts[:, 0], pts[:, 1]); scM.set_data([pts[-1, 0]], [pts[-1, 1]])
    return np.hypot(*pts[-1])


def frame(i):
    for art in (burnE, burnM):
        art.set_data([], [])
    if i < starts[1]:                                      # parking orbit, half a turn up to the burn point
        s = i/N_PARK
        th = dep.w - np.pi*(1 - s)
        th_ = np.linspace(dep.w - np.pi, th, 100)
        trE.set_data(rp1*np.cos(th_), rp1*np.sin(th_)); trE.set_color(BLUE)
        scE.set_data([rp1*np.cos(th)], [rp1*np.sin(th)])
        zoom_E(rp1); titles(0); show_helio(0.0)
        tmin = (1 - s)*np.pi*np.sqrt(rp1**3/muE)/60
        clock.set_text(f"in the 300 km parking orbit, {tmin:4.1f} min before the burn")
        infoE.set_text(f"parking orbit: $v_c={vc1:.3f}$ km/s")
        infoS.set_text("the spacecraft is at the Earth: the sphere of influence is a point")
        infoM.set_text("Mars, waiting")
        infoN.set_text(f"the last\n{T_NEAR/DAY:.1f} days")
    elif i < starts[2]:                                    # departure burn
        trE.set_color(GREEN); trE.set_data([], [])
        p0 = dep.xy(0.0)
        burnE.set_data([p0[0]], [p0[1]]); scE.set_data([p0[0]], [p0[1]])
        zoom_E(rp1); titles(0); show_helio(0.0)
        clock.set_text("burn at periapsis:  t = 0")
        infoE.set_text(rf"$\Delta v_1={dep.vp:.3f}-{vc1:.3f}={dv1:.3f}$ km/s")
    elif i < starts[3]:                                    # departure hyperbola, uniform in F, zooming out
        s = (i - starts[2] + 1)/N_DEP
        F = F1*s
        r = dep_path(F)
        zoom_E(r)
        t = dep.time(F)
        clock.set_text(f"departure hyperbola:  t = {t/3600:6.2f} h after the burn" if t < 2*DAY else
                       f"departure hyperbola:  t = {t/DAY:6.2f} days after the burn")
        v = np.sqrt(vi1**2 + 2*muE/r)
        infoE.set_text(f"$r={km(r)}$ km,  $v={v:.3f}$ km/s  ($v_{{\\infty1}}={vi1:.3f}$)")
    elif i < starts[4]:                                    # heliocentric ellipse
        s = (i - starts[3] + 1)/N_HELIO
        td = t12*s
        titles(1); show_helio(td)
        clock.set_text(f"transfer ellipse:  day {td:5.1f} of {t12:.1f}")
        _, _, S = helio(td)
        Vs = np.sqrt(muS*(2/(np.linalg.norm(S)*AU) - 1/at))
        infoS.set_text(f"spacecraft at {np.linalg.norm(S):.3f} AU, {Vs:.3f} km/s")
        infoE.set_text(f"left the sphere after {dep.time(F1)/DAY:.1f} days")
        infoM.set_text(f"Mars, waiting: $v_{{\\infty2}}={vi2:.3f}$ km/s will point backwards")
    elif i < starts[5]:                                    # close-up in the Sun's frame, up to the entry
        s = (i - starts[4] + 1)/N_NEAR
        t = -T_NEAR + s*(t_entry + T_NEAR)
        titles(2); show_helio(t12); show_near(t)
        clock.set_text(f"close up, Sun's frame:  {-t/DAY:5.2f} days before periapsis at Mars")
        gap = np.linalg.norm(sc_outside(t) - mars_at(t)[0])
        infoN.set_text(f"{gap/1e6:.2f} million km\napart")
        infoS.set_text(f"Mars {VM:.2f} km/s, spacecraft {Vt2:.2f} km/s: Mars catches up")
        infoM.set_text("Mars, waiting")
    elif i < starts[6]:                                    # arrival hyperbola, uniform in F, zooming in
        s = (i - starts[5] + 1)/N_ARR
        F = -F2*(1 - s)
        r = arr_path(F)
        zoom_M(r); titles(3); show_helio(t12); show_near(arr.time(F), F)
        t = abs(arr.time(F))
        clock.set_text(f"arrival hyperbola:  {t/3600:6.2f} h before periapsis" if t < 2*DAY else
                       f"arrival hyperbola:  {t/DAY:6.2f} days before periapsis")
        v = np.sqrt(vi2**2 + 2*muM/r)
        infoM.set_text(f"$r={km(r)}$ km,  $v={v:.3f}$ km/s")
        infoS.set_text(f"arrived after {t12:.1f} days, at aphelion")
        infoN.set_text("inside the\nsphere")
    elif i < starts[7]:                                    # capture burn
        p0 = arr.xy(0.0)
        burnM.set_data([p0[0]], [p0[1]]); scM.set_data([p0[0]], [p0[1]])
        arr_path(0.0); zoom_M(rp2)
        clock.set_text("capture burn at periapsis")
        infoN.set_text("captured: it now\nmoves with Mars")
        infoM.set_text(rf"$\Delta v_2={arr.vp:.3f}-{vc2:.3f}={dv2:.3f}$ km/s")
    else:                                                  # one turn of the 300 km capture orbit, then hold
        s = min(1.0, (i - starts[7] + 1)/N_CAP)
        th_ = arr.w + np.linspace(0, 2*np.pi*s, 200)
        capM.set_data(rp2*np.cos(th_), rp2*np.sin(th_))
        scM.set_data([rp2*np.cos(th_[-1])], [rp2*np.sin(th_[-1])])
        clock.set_text("captured into the 300 km circular orbit about Mars" if s < 1 else
                       f"total: {dv1:.3f} + {dv2:.3f} = {dv1 + dv2:.3f} km/s,  {t12:.0f} days")
        infoM.set_text(f"circular orbit: $v_c={vc2:.3f}$ km/s")


# all three panels start fully set up, so frame 0 is already a complete picture
zoom_M(rsM*1.02); titles(0); show_near(-T_NEAR)
save_gif(fig, frame, N_TOTAL, 20, "img/anim-pc-earth-mars.gif", dpi=90, colors=128)
