"""Procedural articulated video tripod with leveling bowl and fluid head.

Run with the Blender executable supplied with the task:
    blender -b --python build.py
"""
import math
import os
import sys

import bpy
import bmesh
from mathutils import Matrix, Vector

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4


v4.reset()

# ---- materials ----------------------------------------------------------------------
carbon = v4.metal("satin_black_anodized_tubes", (0.13, 0.15, 0.17), roughness=0.34, brushed=True)
black = v4.painted("charcoal_cast_alloy", (0.075, 0.085, 0.095), roughness=0.34, coat=0.35)
black_poly = v4.plastic("moulded_black_polymer", (0.035, 0.042, 0.048), roughness=0.48, texture=0.12)
silver = v4.metal("machined_satin_aluminum", (0.68, 0.70, 0.72), roughness=0.30, brushed=True)
steel = v4.metal("stainless_steel", (0.78, 0.79, 0.80), roughness=0.25, brushed=False)
dark_steel = v4.metal("black_oxide_steel", (0.21, 0.23, 0.24), roughness=0.32, brushed=False)
rubber = v4.rubber("tripod_foot_rubber", (0.025, 0.028, 0.03), roughness=0.87)
grip = v4.rubber("pan_bar_foam_grip", (0.045, 0.05, 0.052), roughness=0.91)
accent = v4.painted("safety_red", (0.72, 0.10, 0.045), roughness=0.32, coat=0.4)
level_glass = v4.glass("level_window_glass", (0.48, 0.84, 0.87), roughness=0.12)
level_liquid = v4.emissive("level_bubble", (0.20, 0.85, 0.55), strength=0.35)
lettering = v4.metal("warm_white_markings", (0.90, 0.90, 0.86), roughness=0.45, brushed=False)


# ---- small placement helpers ----------------------------------------------------------
def V(p):
    return Vector(p)


def plus(a, b):
    return tuple(V(a) + V(b))


def times(a, s):
    return tuple(V(a) * s)


def basis_from_z(z_axis, x_hint=None):
    z = V(z_axis).normalized()
    if x_hint is None:
        x_hint = (1, 0, 0) if abs(z.x) < 0.88 else (0, 1, 0)
    x = V(x_hint) - V(x_hint).dot(z) * z
    if x.length < 1e-7:
        x_hint = (0, 1, 0) if abs(z.y) < 0.88 else (0, 0, 1)
        x = V(x_hint) - V(x_hint).dot(z) * z
    x.normalize()
    y = z.cross(x).normalized()
    return x, y, z


def rot_for_z(z_axis, x_hint=None):
    x, y, z = basis_from_z(z_axis, x_hint)
    return Matrix((x, y, z)).transposed().to_euler()


def oriented_box(name, size, loc, x_axis, y_axis, z_axis, material, body, bevel=0.001):
    x, y, z = V(x_axis).normalized(), V(y_axis).normalized(), V(z_axis).normalized()
    # Re-orthogonalize to avoid tiny drift from hand-constructed directions.
    z = x.cross(y).normalized()
    y = z.cross(x).normalized()
    rot = Matrix((x, y, z)).transposed().to_euler()
    return v4.box(name, size, loc, rot=rot, bevel=bevel, material=material, body=body)


def cylinder_axis(name, radius, depth, loc, axis, material, body, bevel=0.0006, segments=48, x_hint=None):
    return v4.cylinder(name, radius, depth, loc, rot=rot_for_z(axis, x_hint), segments=segments,
                       bevel=bevel, material=material, body=body)


def torus_axis(name, major, minor, loc, axis, material, body, x_hint=None):
    return v4.torus(name, major, minor, loc, rot=rot_for_z(axis, x_hint), material=material, body=body)


def ring_rod(name, p0, p1, radius, material, body):
    return v4.rod(name, p0, p1, radius, material=material, body=body, bevel=0.00035)


def hollow_tube_between(name, p0, p1, outer_radius, inner_radius, material, body, segments=48):
    """A capped annular tube made in world space for genuinely nested leg stages."""
    p0, p1 = V(p0), V(p1)
    axis = (p1 - p0).normalized()
    x, y, _ = basis_from_z(axis)
    bm = bmesh.new()
    outer, inner = [[], []], [[], []]
    for end_i, p in enumerate((p0, p1)):
        for i in range(segments):
            a = 2 * math.pi * i / segments
            radial = x * math.cos(a) + y * math.sin(a)
            outer[end_i].append(bm.verts.new(p + radial * outer_radius))
            inner[end_i].append(bm.verts.new(p + radial * inner_radius))
    for i in range(segments):
        j = (i + 1) % segments
        bm.faces.new((outer[0][i], outer[0][j], outer[1][j], outer[1][i]))
        bm.faces.new((inner[1][i], inner[1][j], inner[0][j], inner[0][i]))
        bm.faces.new((outer[0][i], inner[0][i], inner[0][j], outer[0][j]))
        bm.faces.new((outer[1][j], inner[1][j], inner[1][i], outer[1][i]))
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    obj = v4._mesh_obj(name, bm)
    v4._finish(obj, body, material, 0.00025, smooth=True)
    return obj


def leg_point(pivot, axis, distance):
    return V(pivot) + V(axis) * distance


# ---- tripod crown and bowl receiver: the single root ----------------------------------
root = v4.body("tripod_crown")
hub_z = 1.31
v4.cylinder("central_cast_spider", 0.083, 0.085, (0, 0, hub_z), bevel=0.004, material=black, body=root)
v4.cylinder("spider_upper_rim", 0.091, 0.018, (0, 0, 1.337), bevel=0.003, material=dark_steel, body=root)
v4.cylinder("spider_lower_rim", 0.078, 0.014, (0, 0, 1.265), bevel=0.002, material=black_poly, body=root)
for z, r in ((1.342, 0.082), (1.273, 0.078)):
    torus_axis(f"hub_seam_{z:.3f}", r, 0.0015, (0, 0, z), (0, 0, 1), silver, root)

PIVOT_Z = 1.38
PIVOT_R = 0.10
REST_LEG_ANGLE = math.radians(18.0)
LEG_LENGTH = 1.433
leg_data = []

# Three cast outriggers and root-side hinge pins; these are fixed to the crown.
for i, degrees in enumerate((0, 120, 240)):
    theta = math.radians(degrees)
    radial = V((math.cos(theta), math.sin(theta), 0))
    hinge_axis = radial.cross(V((0, 0, 1))).normalized()
    down_leg = (radial * math.sin(REST_LEG_ANGLE) + V((0, 0, -math.cos(REST_LEG_ANGLE)))).normalized()
    pivot = radial * PIVOT_R + V((0, 0, PIVOT_Z))
    # The cast arms flow out from the crown to each leg hinge boss.
    root_start = V((0, 0, 1.305)) + radial * 0.038
    root_end = pivot + down_leg * 0.025
    v4.rod(f"crown_outrigger_{i}", root_start, root_end, 0.022, material=black, body=root, bevel=0.002)
    cylinder_axis(f"leg_hinge_boss_{i}", 0.024, 0.072, pivot, hinge_axis, black, root, bevel=0.002)
    ring_rod(f"leg_hinge_pin_{i}", pivot - hinge_axis * 0.047, pivot + hinge_axis * 0.047, 0.008, steel, root)
    for side in (-1, 1):
        cap_loc = pivot + hinge_axis * (side * 0.050)
        cylinder_axis(f"leg_hinge_cap_{i}_{side}", 0.014, 0.006, cap_loc, hinge_axis, silver, root,
                      bevel=0.001, segments=32)
        # Fine circular groove and a dark center make the real pin ends legible.
        torus_axis(f"hinge_cap_groove_{i}_{side}", 0.0105, 0.0008,
                   cap_loc + hinge_axis * (side * 0.0031), hinge_axis, dark_steel, root)
        cylinder_axis(f"hinge_cap_center_{i}_{side}", 0.003, 0.001, cap_loc + hinge_axis * (side * 0.0035),
                      hinge_axis, black, root, bevel=0.0002, segments=20)
    leg_data.append((i, radial, hinge_axis, down_leg, pivot))

# The circular receiver rim surrounds the leveling sphere with a small working clearance.
torus_axis("75mm_bowl_receiver_rim", 0.050, 0.006, (0, 0, 1.395), (0, 0, 1), silver, root)
torus_axis("bowl_receiver_dark_seam", 0.058, 0.0025, (0, 0, 1.376), (0, 0, 1), black_poly, root)
v4.cylinder("bowl_socket_outer_lip", 0.065, 0.016, (0, 0, 1.344), bevel=0.002, material=black, body=root)
for k in range(8):
    a = 2 * math.pi * k / 8
    loc = (0.060 * math.cos(a), 0.060 * math.sin(a), 1.344)
    cylinder_axis(f"bowl_lip_fastener_{k}", 0.0024, 0.002, loc, (0, 0, 1), steel, root,
                  bevel=0.0003, segments=16)

# Bowl clamp knob sits on the crown and faces the operator side.
cylinder_axis("bowl_clamp_stem", 0.006, 0.045, (0.071, -0.010, 1.385), (1, 0, 0), dark_steel, root)
cylinder_axis("bowl_clamp_knob_core", 0.014, 0.018, (0.099, -0.010, 1.385), (1, 0, 0), black_poly, root,
              bevel=0.002)
for q in range(10):
    a = 2 * math.pi * q / 10
    y, z = -0.010 + 0.014 * math.cos(a), 1.385 + 0.014 * math.sin(a)
    ring_rod(f"bowl_knob_flute_{q}", (0.100, y, z), (0.108, y, z), 0.0014, rubber, root)
oriented_box("bowl_clamp_red_index", (0.006, 0.009, 0.009), (0.108, -0.010, 1.385),
             (1, 0, 0), (0, 1, 0), (0, 0, 1), accent, root, bevel=0.001)


# ---- hinged tripod legs and their independently telescoping foot sections -------------
for i, radial, hinge_axis, down_leg, pivot_vec in leg_data:
    pivot = tuple(pivot_vec)
    leg = v4.body(f"leg_{i}")
    section = v4.body(f"leg_section_{i}")
    side_axis = down_leg.cross(hinge_axis).normalized()

    # Twin hinge cheeks in the moving upper leg straddle the crown's pin.
    for side in (-1, 1):
        center = pivot_vec + down_leg * 0.078 + hinge_axis * (side * 0.025)
        oriented_box(f"leg_{i}_hinge_cheek_{side}", (0.009, 0.035, 0.145), center,
                     hinge_axis, side_axis, down_leg, black, leg, bevel=0.002)

    # Carbon-style outer tube, rounded end ferrule, and subtle machined indexing bands.
    hollow_tube_between(f"leg_{i}_upper_tube", leg_point(pivot, down_leg, 0.105),
                        leg_point(pivot, down_leg, 0.825), 0.0185, 0.0140, carbon, leg)
    cylinder_axis(f"leg_{i}_top_ferrule", 0.0215, 0.040, leg_point(pivot, down_leg, 0.124), down_leg,
                  black_poly, leg, bevel=0.0015)
    torus_axis(f"leg_{i}_transition_sleeve", 0.0198, 0.0020, leg_point(pivot, down_leg, 0.786), down_leg,
               black, leg)
    for k, t in enumerate((0.25, 0.52, 0.76)):
        torus_axis(f"leg_{i}_tube_band_{k}", 0.0190, 0.0010, leg_point(pivot, down_leg, t), down_leg,
                   dark_steel if k != 1 else silver, leg)

    # Compact latch guard, cam lever and a red safety insert on the upper stage.
    lock_center = leg_point(pivot, down_leg, 0.785) + side_axis * 0.031
    oriented_box(f"leg_{i}_upper_lock_housing", (0.040, 0.025, 0.044), lock_center,
                 hinge_axis, side_axis, down_leg, black_poly, leg, bevel=0.003)
    lever_base = lock_center + side_axis * 0.0125 + down_leg * 0.005
    lever_end = lever_base + side_axis * 0.048 + down_leg * 0.014
    v4.rod(f"leg_{i}_upper_cam_lever", lever_base, lever_end, 0.0055, material=silver, body=leg)
    oriented_box(f"leg_{i}_upper_lever_paddle", (0.010, 0.028, 0.018), lever_end,
                 hinge_axis, side_axis, down_leg, black, leg, bevel=0.003)
    oriented_box(f"leg_{i}_lock_safety_mark", (0.006, 0.010, 0.004), lever_end + side_axis * 0.014,
                 hinge_axis, side_axis, down_leg, accent, leg, bevel=0.001)

    # Sliding lower stage is nested in the upper tube with a visible overlap.
    v4.rod(f"leg_{i}_lower_telescope", leg_point(pivot, down_leg, 0.685), leg_point(pivot, down_leg, 1.420),
           0.0127, material=silver, body=section, bevel=0.0008)
    cylinder_axis(f"leg_{i}_lower_end_ferrule", 0.0145, 0.036, leg_point(pivot, down_leg, 1.397), down_leg,
                  dark_steel, section, bevel=0.001)
    # Split collar and two narrow ferrule bands remain aligned with the moving tube.
    torus_axis(f"leg_{i}_slide_collar_main", 0.0152, 0.0023, leg_point(pivot, down_leg, 0.805), down_leg,
               black_poly, section)
    torus_axis(f"leg_{i}_slide_collar_trim", 0.0150, 0.0010, leg_point(pivot, down_leg, 0.831), down_leg,
               silver, section)
    torus_axis(f"leg_{i}_foot_ferrule_band", 0.0140, 0.0010, leg_point(pivot, down_leg, 1.392), down_leg,
               silver, section)

    # The lower flip lock is carried by the slider and grabs the upper-stage collar.
    lower_lock = leg_point(pivot, down_leg, 0.835) + side_axis * 0.016
    oriented_box(f"leg_{i}_lower_lock_body", (0.038, 0.026, 0.044), lower_lock,
                 hinge_axis, side_axis, down_leg, black, section, bevel=0.003)
    lower_lever_base = lower_lock + side_axis * 0.014 + down_leg * 0.004
    lower_lever_tip = lower_lever_base + side_axis * 0.045 - down_leg * 0.010
    v4.rod(f"leg_{i}_lower_cam_lever", lower_lever_base, lower_lever_tip, 0.0052,
           material=silver, body=section)
    oriented_box(f"leg_{i}_lower_lever_paddle", (0.010, 0.028, 0.018), lower_lever_tip,
                 hinge_axis, side_axis, down_leg, black_poly, section, bevel=0.003)
    oriented_box(f"leg_{i}_lower_lock_indicator", (0.006, 0.010, 0.004), lower_lever_tip + side_axis * 0.014,
                 hinge_axis, side_axis, down_leg, accent, section, bevel=0.001)

    # Articulated rubber foot: flared tread cap and three shallow tread ribs.
    foot_center = leg_point(pivot, down_leg, 1.432)
    cylinder_axis(f"leg_{i}_rubber_foot", 0.023, 0.042, foot_center, down_leg, rubber, section,
                  bevel=0.003, segments=40)
    cylinder_axis(f"leg_{i}_foot_neck", 0.014, 0.035, leg_point(pivot, down_leg, 1.405), down_leg,
                  black_poly, section, bevel=0.001)
    for t in (1.418, 1.431, 1.444):
        torus_axis(f"leg_{i}_foot_tread_{t:.3f}", 0.0218, 0.0012, leg_point(pivot, down_leg, t), down_leg,
                   rubber, section)

    # Leg opens in the radial/downward plane; the slide axis points back toward the crown.
    v4.joint(f"leg_spread_{i}", "revolute", root, leg, origin=pivot,
             axis=hinge_axis, limits=(-0.03, 0.25))
    slider_origin = leg_point(pivot, down_leg, 0.81)
    v4.joint(f"leg_extend_{i}", "prismatic", leg, section, origin=slider_origin,
             axis=-down_leg, limits=(0.0, 0.18))


# ---- leveling bowl adapter and the scale on its stationary outer flange ----------------
bowl = v4.body("bowl_adapter")
v4.sphere("leveling_ball", 0.044, (0, 0, 1.395), material=dark_steel, body=bowl)
cylinder_axis("ball_neck", 0.018, 0.031, (0, 0, 1.438), (0, 0, 1), black, bowl, bevel=0.002)
v4.cylinder("bowl_adapter_flange", 0.077, 0.018, (0, 0, 1.458), bevel=0.002,
            material=silver, body=bowl)
torus_axis("flange_outer_bead", 0.073, 0.0016, (0, 0, 1.467), (0, 0, 1), dark_steel, bowl)
torus_axis("flange_bottom_seal", 0.063, 0.0022, (0, 0, 1.448), (0, 0, 1), black_poly, bowl)

# Engraved-looking degree marks along the exposed outer edge of the leveling flange.
for k in range(36):
    a = math.radians(k * 10)
    r = 0.0705
    length = 0.008 if k % 3 == 0 else 0.0045
    tick = v4.box(f"level_scale_tick_{k:02d}", (0.0014, length, 0.0008),
                  (r * math.cos(a), r * math.sin(a), 1.4674),
                  rot=(0, 0, a + math.pi / 2), bevel=0.0002, material=lettering, body=bowl)

# Small spirit-level window on the operator-facing edge of the flange.
cylinder_axis("bubble_level_bezel", 0.012, 0.004, (0, -0.075, 1.458), (0, -1, 0), black, bowl)
cylinder_axis("bubble_level_glass", 0.0092, 0.002, (0, -0.078, 1.458), (0, -1, 0), level_glass, bowl,
              bevel=0.0004)
v4.sphere("level_bubble", 0.0025, (0.001, -0.080, 1.458), segments=24, material=level_liquid, body=bowl)

v4.joint("bowl_level", "generic", root, bowl, origin=(0, 0, 1.395), axis=(0, 0, 1), xdir=(1, 0, 0),
         dofs=[("rotX", (-0.17, 0.17)), ("rotY", (-0.17, 0.17))])


# ---- fluid head pan base, tilt yoke, damping hardware ----------------------------------
head = v4.body("fluid_base")
# Pan bearing sits edge-to-edge on the bowl adapter flange.
v4.cylinder("pan_bearing_lower_race", 0.064, 0.014, (0, 0, 1.474), bevel=0.0015,
            material=black_poly, body=head)
torus_axis("pan_bearing_seal", 0.059, 0.0020, (0, 0, 1.480), (0, 0, 1), dark_steel, head)
v4.cylinder("pan_rotor_housing", 0.058, 0.040, (0, 0, 1.501), bevel=0.003,
            material=black, body=head)
for k, z in enumerate((1.484, 1.493, 1.516)):
    torus_axis(f"pan_housing_rib_{k}", 0.0585 if k != 1 else 0.060, 0.0012,
               (0, 0, z), (0, 0, 1), silver if k == 1 else dark_steel, head)

# Pan pointer projects from the rotating housing and touches its front edge.
v4.rod("pan_scale_pointer", (0, -0.052, 1.524), (0, -0.071, 1.524), 0.0028,
       material=accent, body=head, bevel=0.0003)

# Fluid cartridge / damped-pan housing and a projecting front badge.
v4.box("fluid_damper_housing", (0.142, 0.118, 0.056), (0, -0.006, 1.535),
       bevel=0.012, material=black, body=head)
v4.box("front_model_badge", (0.083, 0.003, 0.025), (0, -0.0665, 1.535),
       bevel=0.003, material=dark_steel, body=head)
v4.text("fluid_head_mark", "FLOW 75", 0.012, (0, -0.0682, 1.535), rot=(math.pi / 2, 0, 0),
        material=lettering, body=head, on=bpy.data.objects["front_model_badge"])

# Fixed yoke cheeks are separated to leave room for the tilt carrier.
tilt_z = 1.590
for side in (-1, 1):
    x = side * 0.083
    cheek = v4.box(f"yoke_cheek_{side}", (0.024, 0.122, 0.112), (x, 0.004, 1.548),
                   bevel=0.0015, material=black, body=head)
    cutter = v4.cylinder(f"yoke_bore_cutter_{side}", 0.015, 0.040, (x, 0, tilt_z),
                         rot=rot_for_z((1, 0, 0)), bevel=0, material=None)
    v4.boolean(cheek, cutter)
    torus_axis(f"yoke_trunnion_bushing_{side}", 0.019, 0.003,
               (side * 0.096, 0, tilt_z), (1, 0, 0), silver, head)

# Operator-side tilt lock knob with a castellated hand rim (opposite the pan bar).
cylinder_axis("tilt_lock_shaft", 0.006, 0.030, (-0.112, -0.012, tilt_z), (1, 0, 0), steel, head)
cylinder_axis("tilt_lock_knob", 0.020, 0.018, (-0.132, -0.012, tilt_z), (1, 0, 0), black_poly, head,
              bevel=0.0025)
for k in range(12):
    a = 2 * math.pi * k / 12
    y = -0.012 + 0.019 * math.cos(a)
    z = tilt_z + 0.019 * math.sin(a)
    ring_rod(f"tilt_knob_grip_rib_{k}", (-0.132, y, z), (-0.140, y, z), 0.0015, rubber, head)
oriented_box("tilt_lock_red_index", (0.004, 0.008, 0.008), (-0.141, -0.012, tilt_z),
             (1, 0, 0), (0, 1, 0), (0, 0, 1), accent, head, bevel=0.001)

# Front pan lock knob mounted at the lower part of the damped head housing.
cylinder_axis("pan_lock_stem", 0.0055, 0.030, (0.034, -0.059, 1.516), (0, -1, 0), steel, head)
cylinder_axis("pan_lock_knob", 0.015, 0.018, (0.034, -0.083, 1.516), (0, -1, 0), black_poly, head,
              bevel=0.002)
for k in range(10):
    a = 2 * math.pi * k / 10
    x = 0.034 + 0.014 * math.cos(a)
    z = 1.516 + 0.014 * math.sin(a)
    ring_rod(f"pan_knob_flute_{k}", (x, -0.084, z), (x, -0.091, z), 0.0012, rubber, head)

v4.joint("pan", "continuous", bowl, head, origin=(0, 0, 1.474), axis=(0, 0, 1))


# ---- tilting carrier, quick-release plate, and adjustable pan bar ----------------------
carrier = v4.body("tilt_carrier")
# The moving through-axle passes through real clearance bores in the fixed yoke cheeks.
ring_rod("carrier_tilt_axle", (-0.103, 0, tilt_z), (0.103, 0, tilt_z), 0.012, silver, carrier)
for side in (-1, 1):
    torus_axis(f"carrier_trunnion_washer_{side}", 0.0135, 0.002,
               (side * 0.100, 0, tilt_z), (1, 0, 0), black_poly, carrier)
    cylinder_axis(f"carrier_trunnion_cap_{side}", 0.009, 0.006, (side * 0.106, 0, tilt_z),
                  (1, 0, 0), black_poly, carrier, bevel=0.0008)

# Twin saddle uprights lead into the top receiver platform.
for side in (-1, 1):
    v4.box(f"tilt_saddle_arm_{side}", (0.013, 0.047, 0.079),
           (side * 0.050, 0.007, 1.627), bevel=0.004, material=black, body=carrier)
v4.box("tilt_saddle_crossbar", (0.115, 0.044, 0.016), (0, 0.007, 1.663),
       bevel=0.004, material=black, body=carrier)
v4.box("quick_release_receiver", (0.140, 0.128, 0.014), (0, 0, 1.675),
       bevel=0.003, material=dark_steel, body=carrier)

# Rail channels, locating stops, and the camera plate are separated by a narrow sliding seam.
for side in (-1, 1):
    v4.box(f"quick_release_rail_{side}", (0.007, 0.112, 0.010),
           (side * 0.057, 0, 1.687), bevel=0.0012, material=silver, body=carrier)
    v4.box(f"quick_release_rail_liner_{side}", (0.002, 0.096, 0.003),
           (side * 0.052, 0, 1.6865), bevel=0.0004, material=black_poly, body=carrier)
v4.box("quick_release_plate", (0.101, 0.103, 0.009), (0, 0, 1.687),
       bevel=0.0025, material=carbon, body=carrier)
v4.box("quick_release_front_stop", (0.109, 0.008, 0.013), (0, -0.054, 1.686),
       bevel=0.0015, material=silver, body=carrier)
v4.box("quick_release_rear_stop", (0.109, 0.008, 0.013), (0, 0.054, 1.686),
       bevel=0.0015, material=silver, body=carrier)
# Camera mounting screw and slot.
cylinder_axis("camera_mount_stud", 0.0035, 0.009, (0, -0.016, 1.696), (0, 0, 1), steel, carrier,
              bevel=0.0005, segments=24)
cylinder_axis("camera_mount_screw_head", 0.0075, 0.0025, (0, -0.016, 1.701), (0, 0, 1), silver, carrier,
              bevel=0.0005, segments=32)
v4.box("camera_screw_slot", (0.007, 0.001, 0.0006), (0, -0.016, 1.7024),
       bevel=0, material=black, body=carrier)

# QR plate release cam on the right side, with a visible red witness mark.
cylinder_axis("plate_release_shaft", 0.0045, 0.022, (0.073, -0.012, 1.675), (1, 0, 0), steel, carrier)
cylinder_axis("plate_release_knob", 0.012, 0.012, (0.088, -0.012, 1.675), (1, 0, 0), black_poly, carrier,
              bevel=0.0015)
oriented_box("plate_release_red_mark", (0.002, 0.004, 0.010), (0.095, -0.012, 1.675),
             (1, 0, 0), (0, 1, 0), (0, 0, 1), accent, carrier, bevel=0.0005)

# A single long pan bar pivots on a rosette clamp at the right side of the tilt carrier.
bar = v4.body("pan_bar")
bar_pivot = (0.202, -0.008, tilt_z)
v4.rod("bar_mount_boom", (0.102, -0.008, tilt_z), (0.194, -0.008, tilt_z), 0.017,
       material=black, body=carrier, bevel=0.001)
cylinder_axis("bar_rosette_base", 0.025, 0.010, (0.197, -0.008, tilt_z), (1, 0, 0), dark_steel, carrier,
              bevel=0.0012)
torus_axis("bar_rosette_base_groove", 0.019, 0.0012, (0.202, -0.008, tilt_z), (1, 0, 0), silver, carrier)
cylinder_axis("bar_rosette_clamp", 0.022, 0.010, (0.207, -0.008, tilt_z), (1, 0, 0), silver, bar,
              bevel=0.001)
torus_axis("bar_rosette_outer_rim", 0.019, 0.0014, (0.212, -0.008, tilt_z), (1, 0, 0), black, bar)
cylinder_axis("bar_rosette_center_bolt", 0.006, 0.004, (0.214, -0.008, tilt_z), (1, 0, 0), black_poly, bar,
              bevel=0.0006)

# The alloy arm drops back from the head; the thick foam hand grip sits at its far end.
arm_start = V(bar_pivot) + V((0.020, -0.012, -0.002))
arm_elbow = V((0.222, -0.238, 1.438))
grip_start = V((0.222, -0.235, 1.440))
grip_end = V((0.222, -0.382, 1.350))
v4.rod("pan_bar_alloy_arm", arm_start, arm_elbow, 0.0105, material=silver, body=bar, bevel=0.0008)
v4.rod("pan_bar_foam_grip", grip_start, grip_end, 0.018, material=grip, body=bar, bevel=0.001)
v4.rod("pan_bar_grip_end_cap", grip_end, grip_end + V((0, -0.008, -0.005)), 0.016,
       material=black_poly, body=bar, bevel=0.001)
for k in range(5):
    t = 0.18 + k * 0.12
    p = grip_start.lerp(grip_end, t)
    torus_axis(f"pan_bar_grip_rib_{k}", 0.0176, 0.0009, p, grip_end - grip_start, rubber, bar)

v4.joint("tilt", "revolute", head, carrier, origin=(0, 0, tilt_z), axis=(1, 0, 0),
         limits=(-1.10, 1.10))
v4.joint("pan_bar_pivot", "revolute", carrier, bar, origin=bar_pivot, axis=(1, 0, 0),
         limits=(-0.65, 0.65))


# ---- save an unposed, inspectable rest state -------------------------------------------
asset_path = os.path.join(os.getcwd(), "asset.blend")
v4.save(asset_path)
print(f"saved {asset_path}")
