"""Lecture 2, the merry-go-round: a ball rolls outwards at 1 m/s from the centre of a platform that turns once
every 4 s. Left: seen from the ground, a straight line, while the painted stripe turns. Right: seen by a rider,
the same ball curves; the arrow is the Coriolis term -2 w x v_B. Components in the platform frame come from the
engine's rotation matrix (frames.rot_z). Writes img/anim-02-merry-go-round.gif."""
import numpy as np
from _visual import plt, save_anim, INK, MAROON, BLUE, GREEN, GREY
from matplotlib.patches import Circle
from flight.frames import rot_z

OMEGA, V, RAD = 2 * np.pi / 4.0, 1.0, 2.5
T = RAD / V
t_all = np.linspace(0, T, 300)
r_I = np.vstack([V * t_all, 0 * t_all, 0 * t_all])                     # inertial: straight along x
r_B = np.array([rot_z(OMEGA * t) @ r_I[:, i] for i, t in enumerate(t_all)]).T   # platform components

if __name__ == "__main__":
    fig, axs = plt.subplots(1, 2, figsize=(10, 5.2))
    N, fps = 110, 16

    def frame(k):
        i = int(round(k / (N - 1) * (len(t_all) - 1)))
        t = t_all[i]
        for ax, title in zip(axs, ("seen from the ground", "seen by a rider on the platform")):
            ax.clear()
            ax.add_patch(Circle((0, 0), RAD, facecolor="#efe9dd", edgecolor=GREY, lw=1))
            ax.set_xlim(-2.9, 2.9)
            ax.set_ylim(-2.9, 2.9)
            ax.set_aspect("equal")
            ax.axis("off")
            ax.set_title(title, fontsize=12)
        a = OMEGA * t                                                    # stripe angle in the ground view
        axs[0].plot([0, RAD * np.cos(a)], [0, RAD * np.sin(a)], color=GREEN, lw=4, alpha=0.6)
        axs[0].plot(r_I[0, :i + 1], r_I[1, :i + 1], color=MAROON, lw=2.4)
        axs[0].plot(r_I[0, i], r_I[1, i], "o", color=MAROON, ms=10)
        axs[0].text(-2.8, -2.8, f"t = {t:.1f} s", fontsize=11)
        axs[1].plot([0, RAD], [0, 0], color=GREEN, lw=4, alpha=0.6)        # the stripe does not move for the rider
        axs[1].plot(r_B[0, :i + 1], r_B[1, :i + 1], color=MAROON, lw=2.4)
        axs[1].plot(r_B[0, i], r_B[1, i], "o", color=MAROON, ms=10)
        if i > 0:
            j = min(i, len(t_all) - 2)
            vB = (r_B[:, j + 1] - r_B[:, j - 1]) / (t_all[j + 1] - t_all[j - 1])
            cor = -2 * np.cross([0, 0, OMEGA], vB)
            sc = 0.12
            axs[1].annotate("", xy=r_B[:2, i] + sc * cor[:2], xytext=r_B[:2, i],
                            arrowprops=dict(arrowstyle="-|>", color=BLUE, lw=2, mutation_scale=14))
        axs[1].text(-2.8, -2.8, "arrow: sideways push", fontsize=11, color=BLUE)
        axs[0].annotate("", xy=(2.2 * np.cos(0.9), 2.2 * np.sin(0.9)), xytext=(2.2 * np.cos(0.3), 2.2 * np.sin(0.3)),
                        arrowprops=dict(arrowstyle="->", color=GREY, connectionstyle="arc3,rad=0.25"))
        return []

    save_anim(fig, frame, N, fps, "anim-02-merry-go-round")
