Skip to content

Joints

A joint holds two bodies together, or a body to the world, and leaves free only the motion it allows. Each mechanism below is built around one joint and moved through it by a joint drive:

A door on a hinge, a slider knob in a slot, a rod on a ball and two drive shafts coupled at a bend

A revolute joint is a hinge: the door turns about the line through two points.

door = add_body(world, scene, "hinge", leaf)
joint = trusty.affine.add_revolute_joint(world, door, o - 0.1 * EZ, o + 0.1 * EZ)

A prismatic joint is a slider: the knob moves along one direction.

knob = add_body(world, scene, "slider", knob)
joint = trusty.affine.add_prismatic_joint(world, knob, o, EX)

A spherical joint is a ball: the rod turns any way about one point.

rod = add_body(world, scene, "ball", rod)
joint = trusty.affine.add_spherical_joint(world, rod, o)

A universal joint turns about two perpendicular axes, one fixed in each body, which is how a drive shaft carries its spin around a bend.

shaft_in = add_body(world, scene, "input shaft", shaft_with_yoke(d_in, pin_in))
shaft_out = add_body(world, scene, "output shaft", shaft_with_yoke(-d_out, pin_out))
# Each shaft turns in a bearing fixed in space along its own axis.
bearing = trusty.affine.add_revolute_joint(
    world, shaft_in, o - length * d_in, o - 0.5 * length * d_in)
trusty.affine.add_revolute_joint(
    world, shaft_out, o + 0.5 * length * d_out, o + length * d_out)
# The universal joint pins the yokes together and keeps their pins perpendicular.
trusty.affine.add_universal_joint(
    world, shaft_in, shaft_out, o, axis_i=pin_in, axis_j=pin_out)

Leave out body_j and a joint holds its body to the world. Affine bodies gives each joint's arguments and angles, and how to drive and limit them.

Full script: python examples/affine/joints.py
"""One of each moving joint: a door hinge, a slider, a ball joint and a universal joint.

Four mechanisms stand in a row, each built around one joint and moved through
it by a joint drive. A door leaf swings on a hinge (revolute joint) between two
knuckles fixed in place. A slider knob runs back and forth along the slot of a
fixed panel (prismatic joint). A rod hangs from a ball (spherical joint) under a
fixed mount and circles around. Two shafts, each turning in a bearing fixed in
space, meet at a bend, where a universal joint couples their yokes, so spinning
the first shaft turns the second.

Usage:
    python examples/affine/joints.py                # polyscope
    python examples/affine/joints.py --no-viewer    # headless
"""

from __future__ import annotations

import argparse
import math
import sys
from pathlib import Path

import numpy as np

import trusty

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from utils import make_lathe  # noqa: E402

DT = 0.01
EX, EY, EZ = np.eye(3)
STEEL = (0.6, 0.6, 0.62)
SLOT = (0.15, 0.15, 0.17)
COLORS = {"hinge": (0.85, 0.45, 0.2), "slider": (0.3, 0.65, 0.35),
          "ball": (0.25, 0.5, 0.85), "input shaft": (0.85, 0.45, 0.2),
          "output shaft": (0.25, 0.5, 0.85)}


# -- Meshes ------------------------------------------------------------------

def box(center, half, frame=np.eye(3)):
    """Box with half-extents `half` along the columns of `frame`."""
    signs = np.array(
        [[-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1],
         [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]], dtype=np.float64)
    V = (signs * np.asarray(half, dtype=np.float64)) @ frame.T + center
    F = np.array(
        [[4, 5, 6], [4, 6, 7], [0, 3, 2], [0, 2, 1],
         [1, 2, 6], [1, 6, 5], [0, 4, 7], [0, 7, 3],
         [3, 7, 6], [3, 6, 2], [0, 1, 5], [0, 5, 4]], dtype=np.int32)
    return V, F


def frame_along(d):
    """A rotation taking z to the unit vector `d`."""
    d = d / np.linalg.norm(d)
    a = EX if abs(d[0]) < 0.9 else EY
    u = np.cross(a, d)
    u /= np.linalg.norm(u)
    return np.column_stack([u, np.cross(d, u), d])


def cylinder(p0, p1, r, n=24):
    V, F = make_lathe([(0.0, 0.0), (r, 0.0), (r, 1.0), (0.0, 1.0)], n)
    V[:, 2] *= np.linalg.norm(np.subtract(p1, p0))
    return V @ frame_along(np.subtract(p1, p0)).T + p0, F


def sphere(center, r, n=24):
    a = np.linspace(0.0, math.pi, n // 2 + 1)[1:-1]
    ring = [(r * math.sin(t), -r * math.cos(t)) for t in a]
    V, F = make_lathe([(0.0, -r)] + ring + [(0.0, r)], n)
    return V + center, F


def merge(*parts):
    offsets = np.cumsum([0] + [len(V) for V, _ in parts[:-1]])
    return (np.vstack([V for V, _ in parts]),
            np.vstack([F + o for (_, F), o in zip(parts, offsets)]))


# -- The four mechanisms -------------------------------------------------------

def add_body(world, scene, name, mesh):
    body = trusty.affine.add_affine_body(world, *mesh, density=1000.0, stiffness=1e8)
    scene["bodies"][name] = body
    return body


def hinge(world, scene, o):
    """A door leaf swinging on a vertical hinge through `o`."""
    r, z0, z1 = 0.025, o[2] - 0.3, o[2] + 0.3
    knuckles = [cylinder(o + (z0 - o[2]) * EZ, o - 0.1 * EZ, r),
                cylinder(o + 0.1 * EZ, o + (z1 - o[2]) * EZ, r)]
    scene["fixed"]["hinge frame"] = merge(*knuckles, box(o - 0.13 * EX, (0.1, 0.008, 0.3)))
    leaf = merge(cylinder(o - 0.098 * EZ, o + 0.098 * EZ, r),
                 box(o + 0.25 * EX, (0.23, 0.008, 0.28)))
    door = add_body(world, scene, "hinge", leaf)
    joint = trusty.affine.add_revolute_joint(world, door, o - 0.1 * EZ, o + 0.1 * EZ)
    drive = trusty.actuators.add_joint_drive(world, joint, stiffness=200.0, damping=10.0)
    scene["drives"]["hinge"] = lambda t: trusty.actuators.set_joint_target(
        world, drive, 1.1 * math.sin(2.0 * math.pi * 0.4 * t))


def slider(world, scene, o):
    """A knob sliding along the slot of a panel facing -y, like a fader."""
    scene["fixed"]["slider panel"] = box(o + 0.02 * EY, (0.35, 0.012, 0.07))
    scene["fixed"]["slider slot"] = box(o + 0.006 * EY, (0.3, 0.004, 0.012))
    knob = merge(box(o - 0.02 * EY, (0.012, 0.02, 0.01)),
                 box(o - 0.065 * EY, (0.04, 0.025, 0.065)))
    knob = add_body(world, scene, "slider", knob)
    joint = trusty.affine.add_prismatic_joint(world, knob, o, EX)
    drive = trusty.actuators.add_joint_drive(world, joint, stiffness=100.0, damping=5.0)
    scene["drives"]["slider"] = lambda t: trusty.actuators.set_joint_target(
        world, drive, 0.25 * math.sin(2.0 * math.pi * 0.4 * t))


def ball(world, scene, o):
    """A rod hanging from a ball under a fixed mount, swept around a cone."""
    scene["fixed"]["ball mount"] = merge(box(o + 0.09 * EZ, (0.09, 0.09, 0.02)),
                                         cylinder(o + 0.03 * EZ, o + 0.08 * EZ, 0.02))
    rod = merge(sphere(o, 0.045), cylinder(o, o - 0.5 * EZ, 0.014))
    rod = add_body(world, scene, "ball", rod)
    joint = trusty.affine.add_spherical_joint(world, rod, o)
    drive = trusty.actuators.add_joint_drive(world, joint, stiffness=50.0, damping=2.0)

    def target(t):
        # Tilt the rod by `tilt` toward a direction that turns about the vertical.
        tilt = 0.5 * min(1.0, t / 0.5)
        phi = 2.0 * math.pi * 0.5 * t
        c, s = math.cos(phi), math.sin(phi)
        Rz = np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]])
        Rx = np.array([[1.0, 0.0, 0.0], [0.0, math.cos(tilt), -math.sin(tilt)],
                       [0.0, math.sin(tilt), math.cos(tilt)]])
        trusty.actuators.set_joint_target(world, drive, Rz @ Rx @ Rz.T)

    scene["drives"]["ball"] = target


def universal(world, scene, o, bend=math.radians(30.0)):
    """Two shafts meeting at a bend at `o`, coupled by a universal joint."""
    length, half, fork = 0.55, 0.03, 0.075
    d_in = EX                                            # input shaft, toward the cross
    d_out = math.cos(bend) * EX - math.sin(bend) * EZ    # output shaft, away from it
    pin_in = EY
    pin_out = np.cross(d_out, pin_in)    # perpendicular to the output shaft and to pin_in

    def shaft_with_yoke(d, pin):
        """A shaft along -`d` up to a yoke whose prongs straddle `o` along `pin`."""
        frame = np.column_stack([d, pin, np.cross(d, pin)])
        end = o - 1.6 * fork * d
        prongs = [box(o + s * fork * pin + (0.5 * half - 0.5 * fork) * d,
                      (1.1 * fork - 0.5 * half, 0.5 * half, half), frame) for s in (-1, 1)]
        return merge(box(end - 0.5 * (length - 1.6 * fork) * d,
                         (0.5 * (length - 1.6 * fork), half, half), frame),
                     box(end + 0.5 * half * d, (0.5 * half, fork + half, half), frame),
                     *prongs)

    shaft_in = add_body(world, scene, "input shaft", shaft_with_yoke(d_in, pin_in))
    shaft_out = add_body(world, scene, "output shaft", shaft_with_yoke(-d_out, pin_out))
    # Each shaft turns in a bearing fixed in space along its own axis.
    bearing = trusty.affine.add_revolute_joint(
        world, shaft_in, o - length * d_in, o - 0.5 * length * d_in)
    trusty.affine.add_revolute_joint(
        world, shaft_out, o + 0.5 * length * d_out, o + length * d_out)
    # The universal joint pins the yokes together and keeps their pins perpendicular.
    trusty.affine.add_universal_joint(
        world, shaft_in, shaft_out, o, axis_i=pin_in, axis_j=pin_out)
    scene["fixed"]["bearings"] = merge(
        box(o - 0.8 * length * d_in, (0.03, 0.07, 0.07)),
        box(o + 0.8 * length * d_out, (0.03, 0.07, 0.07), frame_along(d_out)[:, [2, 1, 0]]))
    drive = trusty.actuators.add_joint_drive(world, bearing, stiffness=2e3, damping=20.0)
    scene["drives"]["universal"] = lambda t: trusty.actuators.set_joint_target(
        world, drive, 2.0 * math.pi * 0.5 * t)
    scene["cross"] = dict(anchor=o, fork=fork, shafts=(shaft_in, shaft_out),
                          axes=(d_in, d_out), pins=(pin_in, pin_out))


def build(backend):
    world = trusty.World(backend=backend, timestep=DT)
    scene = dict(world=world, bodies={}, fixed={}, drives={})
    for x, add in zip((0.0, 1.2, 2.4, 3.75), (hinge, slider, ball, universal)):
        add(world, scene, np.array([x, 0.0, 1.0]))
    scene["rest"] = {b: np.asarray(trusty.affine.surface_positions(world, b))
                     for b in scene["bodies"].values()}
    print("Left to right: hinge (revolute), slider (prismatic), ball (spherical), "
          "drive shafts (universal).")
    return scene


# -- Running -------------------------------------------------------------------

def advance(scene, step):
    for set_target in scene["drives"].values():
        set_target(step * DT)
    scene["world"].step()


def rotation(scene, body):
    """The body's current linear map, fitted from its rest to current surface."""
    rest = scene["rest"][body]
    now = np.asarray(trusty.affine.surface_positions(scene["world"], body))
    M, *_ = np.linalg.lstsq(np.hstack([rest, np.ones((len(rest), 1))]), now, rcond=None)
    return M[:3].T


def readout(scene):
    """Hinge angle, slide, ball tilt and the two shafts' turns (deg, m)."""
    b = scene["bodies"]
    door = rotation(scene, b["hinge"]) @ EX
    hinge = math.degrees(math.atan2(door[1], door[0]))
    slide = float(np.mean(np.asarray(trusty.affine.surface_positions(scene["world"], b["slider"]))
                          - scene["rest"][b["slider"]], axis=0)[0])
    tilt = math.degrees(math.acos(np.clip(rotation(scene, b["ball"])[2, 2], -1.0, 1.0)))
    c = scene["cross"]
    turns = []
    for body, d, p in zip(c["shafts"], c["axes"], c["pins"]):
        q = rotation(scene, body) @ p
        turns.append(math.degrees(math.atan2(np.dot(np.cross(p, q), d), np.dot(p, q))))
    return hinge, slide, tilt, *turns


def cross_points(scene):
    """The cross between the yokes: the two pins, turned with their shafts."""
    c = scene["cross"]
    ends = []
    for body, p in zip(c["shafts"], c["pins"]):
        q = rotation(scene, body) @ p
        ends += [c["anchor"] - c["fork"] * q, c["anchor"] + c["fork"] * q]
    return np.array(ends)


def run_headless(scene, steps):
    print("  step  hinge(deg)  slide(m)  ball tilt(deg)  input shaft(deg)  output shaft(deg)")
    for i in range(1, steps + 1):
        advance(scene, i)
        if i % 25 == 0:
            h, s, t, a, b = readout(scene)
            print(f"  {i:4d}  {h:+10.1f}  {s:+8.3f}  {t:14.1f}  {a:+16.1f}  {b:+17.1f}")


def run_polyscope(scene, steps):
    try:
        import polyscope as ps
        import polyscope.imgui as psim
    except ImportError:
        print("polyscope not installed (pip install polyscope); running headless.")
        run_headless(scene, steps)
        return

    ps.init()
    ps.set_up_dir("z_up")
    ps.set_ground_plane_mode("shadow_only")
    world = scene["world"]
    for name, (V, F) in scene["fixed"].items():
        ps.register_surface_mesh(name, V, F).set_color(SLOT if name == "slider slot" else STEEL)
    meshes = []
    for name, body in scene["bodies"].items():
        V = trusty.affine.surface_positions(world, body)
        _, F = trusty.surface.mesh(world, body)
        m = ps.register_surface_mesh(name, np.asarray(V), np.asarray(F))
        m.set_color(COLORS[name])
        meshes.append((body, m))
    cross = ps.register_curve_network("cross", cross_points(scene), np.array([[0, 1], [2, 3]]))
    cross.set_radius(0.01, relative=False)
    cross.set_color(STEEL)

    state = {"i": 0, "playing": False}

    def step():
        if state["i"] < steps:
            state["i"] += 1
            advance(scene, state["i"])
            for body, m in meshes:
                m.update_vertex_positions(np.asarray(trusty.affine.surface_positions(world, body)))
            cross.update_node_positions(cross_points(scene))

    def callback():
        _, state["playing"] = psim.Checkbox("play", state["playing"])
        psim.SameLine()
        if psim.Button("step") or state["playing"]:
            step()
        psim.Text(f"step {state['i']} / {steps}")

    ps.set_user_callback(callback)
    ps.show()


def main():
    p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    p.add_argument("--steps", type=int, default=500)
    p.add_argument("--backend", choices=["auto", "cpu", "accelerate", "cuda"], default="auto")
    p.add_argument("--no-viewer", action="store_true")
    args = p.parse_args()

    scene = build(args.backend)
    if args.no_viewer:
        run_headless(scene, args.steps)
    else:
        run_polyscope(scene, args.steps)


if __name__ == "__main__":
    main()