# Tactiverge Academy — companion code for "Coordinate frames and homogeneous transforms"
# Lesson: https://tactiverge.win/academy/robotics-foundations/mathematical-foundations-of-movement/frames-and-transforms/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
import math

def transform(theta_deg, tx, ty):
    """3x3 homogeneous transform: rotate by theta, then shift by (tx, ty)."""
    c, s = math.cos(math.radians(theta_deg)), math.sin(math.radians(theta_deg))
    return [[c, -s, tx], [s, c, ty], [0.0, 0.0, 1.0]]

def matmul(A, B):
    return [[sum(A[i][k] * B[k][j] for k in range(3)) for j in range(3)] for i in range(3)]

def chain(*Ts):
    result = transform(0, 0, 0)          # identity
    for T in Ts:
        result = matmul(result, T)
    return result

L1, L2, tool = 10, 8, 3
T_base_hand = chain(transform(30, 0, 0), transform(0, L1, 0),
                    transform(45, 0, 0), transform(0, L2, 0))
T_base_tool = matmul(T_base_hand, transform(0, tool, 0))
T_world_base = transform(90, 50, 20)
T_world_tool = matmul(T_world_base, T_base_tool)

for name, T in [("hand in base", T_base_hand), ("tool in base", T_base_tool),
                ("tool in world", T_world_tool)]:
    heading = math.degrees(math.atan2(T[1][0], T[0][0]))
    print(f"{name:13s}: ({T[0][2]:6.2f}, {T[1][2]:6.2f}) cm, facing {heading:5.1f} deg")
