"""The oloid: its generators, its development and its rolling.

The oloid is the convex hull of two unit circles in perpendicular planes, each
passing through the other's centre: circle A, x^2 + y^2 = 1 in the plane z = 0,
and circle B, (x + 1)^2 + z^2 = 1 in the plane y = 0. Its curved surface is
made of straight line segments, its generators, each from a point P on circle A
to a point Q on circle B. This program unrolls the surface onto a plane, as the
oloid lays it down when it rolls through one cycle, and plots the result.
"""

import matplotlib.pyplot as plt
import numpy as np


def generators(theta, half=1):
    """Return the ends, P and Q, of the generators at the angles theta and the
    outward unit normal, n, to the surface along each, as arrays of shape
    (len(theta), 3), for the upper half of the surface (half=1, z >= 0) or the
    lower half (half=-1)."""
    s, c = np.sin(theta), np.cos(theta)
    D = np.sqrt(1 - 3 * s**2 / 4)  # cos(t/2)
    zero, one = np.zeros_like(s), np.ones_like(s)
    P = np.column_stack((2 * D**2 - 1, np.sqrt(3) * D * s, zero))
    Q = np.column_stack((-one, zero, half * np.sqrt(3) * c)) / (2 * D[:, None]**2)
    n = np.column_stack((2 * D**2 - 1, np.sqrt(3) * D * s,
                         half * np.sqrt(3) * c)) / (2 * D[:, None])
    return P, Q, n


def rolling_cycle(m=1000):
    """Return P, Q and n for the generators in the order in which they touch
    the plane on which the oloid rolls, through one cycle: m + 1 generators of
    the upper half, from theta = -pi/2 to pi/2, then m of the lower half, from
    theta = pi/2 back to -pi/2. The last generator is the first, which begins
    the next cycle."""
    theta = np.linspace(-np.pi / 2, np.pi / 2, m + 1)
    upper = generators(theta, 1)
    lower = generators(theta[::-1], -1)
    return [np.vstack((u, v[1:])) for u, v in zip(upper, lower)]


def place(a, b, ac, bc, side):
    """Return the point c in the plane at distances ac from a and bc from b,
    on the left of the line from a to b if side > 0, else on its right."""
    ab = np.linalg.norm(b - a)
    x = (ab**2 + ac**2 - bc**2) / (2 * ab)
    y = np.sqrt(max(ac**2 - x**2, 0))
    e = (b - a) / ab
    return a + x * e + np.sign(side) * y * np.array((-e[1], e[0]))


def develop(P, Q, n):
    """Unroll the strip of generators from P to Q onto the plane, one triangle
    at a time, and return the ends of the generators there, p and q.

    The surface is laid on the plane with its outward normal pointing down, as
    when the oloid rolls on it, so that a triangle which is anticlockwise seen
    from outside the oloid is clockwise seen from above.
    """
    p, q = np.zeros((len(P), 2)), np.zeros((len(P), 2))
    q[0] = (np.linalg.norm(Q[0] - P[0]), 0)
    for i in range(len(P) - 1):
        # The quadrilateral between neighbouring generators is split into the
        # triangles P[i], Q[i], P[i+1] and P[i+1], Q[i], Q[i+1].
        side = -np.cross(Q[i] - P[i], P[i + 1] - P[i]) @ n[i]
        p[i + 1] = place(p[i], q[i], np.linalg.norm(P[i + 1] - P[i]),
                         np.linalg.norm(P[i + 1] - Q[i]), side)
        side = -np.cross(Q[i] - P[i + 1], Q[i + 1] - P[i + 1]) @ n[i]
        q[i + 1] = place(p[i + 1], q[i], np.linalg.norm(Q[i + 1] - P[i + 1]),
                         np.linalg.norm(Q[i + 1] - Q[i]), side)
    return p, q


def pose(P, Q, n, p, q):
    """Return the rotation matrix R and the translation d that lay the oloid
    on the plane z = 0 along its generator from P to Q, whose image in the
    development runs from p to q: a point X of the oloid moves to R @ X + d."""
    e1 = (Q - P) / np.linalg.norm(Q - P)
    f1 = np.append((q - p) / np.linalg.norm(q - p), 0)
    f3 = np.array((0, 0, -1))
    R = (np.column_stack((f1, np.cross(f3, f1), f3))
         @ np.vstack((e1, np.cross(n, e1), n)))
    return R, np.append(p, 0) - R @ P


def polygon_area(xy):
    """Return the area of the polygon with vertices xy (the shoelace formula)."""
    x, y = xy.T
    return abs(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1))) / 2


if __name__ == "__main__":
    m = 1000
    P, Q, n = rolling_cycle(m)
    p, q = develop(P, Q, n)

    # The development is bounded by the images of the generators at its ends
    # and of the circles' arcs.
    area = polygon_area(np.vstack((p, q[::-1])))
    print(f"Area of the development: {area:.6f} (4 pi = {4 * np.pi:.6f})")
    # One cycle of rolling turns the oloid about the vertical and moves it,
    # carrying the image of the first generator, from p[0] = (0, 0) to q[0],
    # to the image of the last, from p[-1] to q[-1].
    u, v = q[0] - p[0], q[-1] - p[-1]
    angle = np.degrees(np.arctan2(u[0] * v[1] - u[1] * v[0], np.dot(u, v)))
    print(f"In one cycle the oloid turns by {angle:.6f} deg"
          f" and moves by ({p[-1][0]:.6f}, {p[-1][1]:.6f})")

    fig, ax = plt.subplots()
    for i in range(0, len(p), m // 20):
        ax.plot(*np.column_stack((p[i], q[i])), c="0.7", lw=0.8)
    ax.plot(*p.T, label="circle A")
    ax.plot(*q.T, label="circle B")
    ax.set_aspect("equal")
    ax.legend()
    plt.show()
