"""Detailed articulated video tripod and fluid head."""
import math
import os
import sys
import bpy
from mathutils import Vector

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

v4.reset()

# Finishes: satin black castings, anodized tubes, and elastomer controls.
black = v4.painted("Satin graphite powder coat", (0.055, 0.065, 0.075), roughness=0.31)
head_paint = v4.painted("Fluid head satin enamel", (0.035, 0.045, 0.055), roughness=0.26, coat=0.72)
dark = v4.plastic("Textured charcoal polymer", (0.105, 0.115, 0.12), roughness=0.48)
silver = v4.metal("Brushed anodized aluminum", (0.64, 0.68, 0.70), roughness=0.3)
steel = v4.metal("Stainless fasteners", (0.77, 0.78, 0.78), roughness=0.24, brushed=False)
rubber = v4.rubber("Black rubber", (0.025, 0.03, 0.032))
white = v4.mat("Leg scale ivory", (0.86, 0.84, 0.76), roughness=0.58)
amber = v4.mat("Safety amber", (0.9, 0.32, 0.035), roughness=0.36)
glass = v4.glass("Level vial glass", (0.7, 0.92, 0.78), roughness=0.08)

def unit(p):
    return Vector(p).normalized()

def cylinder_between(name, p0, p1, radius, material, body, radius_top=None, bevel=0.0007, segments=40):
    p0, p1 = Vector(p0), Vector(p1)
    direction = p1 - p0
    q = direction.to_track_quat('Z', 'Y')
    return v4.cylinder(name, radius, direction.length, (p0 + p1) * 0.5,
                       rot=q.to_euler(), radius_top=radius_top, bevel=bevel,
                       segments=segments, material=material, body=body)

def rod(name, p0, p1, radius, material, body, square=False):
    return v4.rod(name, p0, p1, radius, material=material, body=body, square=square)

def radial_point(theta, r, z):
    return Vector((math.cos(theta) * r, math.sin(theta) * r, z))

def ring_axis(name, center, axis, major, minor, material, body):
    q = Vector(axis).to_track_quat('Z', 'Y')
    return v4.torus(name, major, minor, loc=center, rot=q.to_euler(), material=material, body=body)

# The root casting carries the leveling bowl receiver and three leg hinge clevises.
base = v4.body("tripod_base")
v4.lathe("Crown casting with bowl socket", [
    (0.055, 1.175), (0.105, 1.175), (0.128, 1.195), (0.132, 1.232),
    (0.113, 1.260), (0.086, 1.275), (0.078, 1.30), (0.071, 1.30),
    (0.071, 1.275), (0.054, 1.26), (0.0, 1.26)], material=black, body=base)
# Bowl receiver and visible leveling shell, fixed to the crown.
v4.lathe("Levelling bowl shell", [(0.052, 1.29), (0.056, 1.30), (0.057, 1.315),
                                    (0.049, 1.326), (0.032, 1.333), (0.052, 1.334)],
         material=silver, body=base)
# Bowl clamp screw and cam handle on the front.
v4.cylinder("Bowl clamp pivot", 0.009, 0.025, (0.063, 0, 1.287), rot=(0, math.pi/2, 0), material=steel, body=base)
rod("Bowl clamp handle", (0.073, 0, 1.287), (0.112, -0.006, 1.287), 0.005, dark, base)
v4.sphere("Bowl clamp knob", 0.011, (0.116, -0.006, 1.287), material=black, body=base)

leg_bodies, section_bodies = [], []
leg_data = []
for i in range(3):
    theta = i * 2 * math.pi / 3
    radial = Vector((math.cos(theta), math.sin(theta), 0))
    tangent = Vector((-math.sin(theta), math.cos(theta), 0))
    hinge = radial * 0.125 + Vector((0, 0, 1.225))
    foot = radial * 0.610 + Vector((0, 0, 0.048))
    # The leg axis and the upper/lower stage junction are derived from the actual endpoints.
    axis_vec = unit(foot - hinge)
    junction = hinge.lerp(foot, 0.52)
    upper_end = hinge.lerp(foot, 0.56)
    lower_top = hinge.lerp(foot, 0.22)
    leg = v4.body("leg_%d" % i)
    leg_bodies.append(leg)
    leg_data.append((theta, radial, tangent, hinge, foot, axis_vec, junction, upper_end, lower_top))
    # Main outer tube and the die-cast crown hinge lug.
    rod("Leg %d upper anodized tube" % i, hinge + axis_vec * 0.055, upper_end, 0.034, silver, leg)
    rod("Leg %d hinge lug" % i, hinge - axis_vec * 0.018, hinge + axis_vec * 0.082, 0.044, black, leg)
    # Rubber friction inserts where leg meets crown, plus metallic pivot caps.
    for side in (-1, 1):
        cap_center = hinge + tangent * side * 0.044
        cylinder_between("Leg %d hinge cap %d" % (i, side), cap_center - tangent * 0.004,
                         cap_center + tangent * 0.004, 0.019, steel, leg)
        v4.cylinder("Leg %d hinge socket %d" % (i, side), 0.008, 0.002,
                     cap_center + tangent * side * 0.004, rot=(0, 0, 0), material=dark, body=leg)
    # Two stage leg: a narrower inner tube runs inside the fixed outer tube.
    section = v4.body("leg_section_%d" % i)
    section_bodies.append(section)
    rod("Leg %d telescoping inner tube" % i, lower_top, foot + axis_vec * 0.050, 0.022, silver, section)
    # Clamp collar around the inner stage at the bottom of the overlap.
    collar_center = hinge.lerp(foot, 0.78)
    cylinder_between("Leg %d twist-lock outer sleeve" % i, collar_center - axis_vec * 0.046,
                     collar_center + axis_vec * 0.046, 0.040, dark, section, radius_top=0.035)
    ring_axis("Leg %d lock collar lip" % i, collar_center + axis_vec * 0.039, axis_vec, 0.036, 0.003, black, section)
    # A low-profile cam lever on the outside of the collar.
    lever_start = collar_center + radial * 0.028
    lever_end = lever_start + tangent * 0.045 + axis_vec * 0.012
    rod("Leg %d stage lock lever" % i, lever_start, lever_end, 0.006, black, section)
    v4.sphere("Leg %d lever grip" % i, 0.008, lever_end, material=dark, body=section)
    # Foot socket and broad rubber pad remain fixed to the sliding stage.
    foot_top = foot + Vector((0, 0, 0.008))
    v4.cylinder("Leg %d rubber ground pad" % i, 0.035, 0.014, (foot.x, foot.y, 0.007),
                material=rubber, body=section)
    # Indexed leg scale, laser etched on the forward face of each upper tube.
    for k in range(4):
        p = hinge.lerp(foot, 0.25 + k * 0.055) + radial * 0.033
        rod("Leg %d length index %d" % (i, k), p - tangent * (0.010 if k % 2 == 0 else 0.006),
            p + tangent * (0.010 if k % 2 == 0 else 0.006), 0.0012, dark, leg)
    # User-facing alignment label on the collar.
    v4.cylinder("Leg %d collar rivet" % i, 0.003, 0.002, collar_center + radial * 0.032,
                rot=(0, math.pi / 2, theta), segments=16, material=steel, body=section)

    # Three black clevises on the root casting receive the spread hinges.
    v4.box("Crown clevis %d" % i, (0.064, 0.036, 0.085),
           tuple(hinge + Vector((0, 0, -0.005))), rot=(0, 0, theta), bevel=0.008,
           material=black, body=base)
    v4.joint("leg_spread_%d" % i, "revolute", base, leg, origin=hinge,
             axis=tangent, limits=(-math.radians(18), math.radians(18)))
    # Positive travel slides the lower section up the inclined leg; negative travel extends it.
    v4.joint("leg_extend_%d" % i, "prismatic", leg, section,
             origin=junction, axis=-axis_vec, limits=(-0.16, 0.0))

# A spherical carrier levels in the fixed crown bowl about two horizontal axes.
carrier = v4.body("bowl_carrier")
v4.lathe("Spherical leveling carrier and pan mounting flange", [
    (0, 1.299), (0.025, 1.299), (0.032, 1.310), (0.035, 1.334),
    (0.032, 1.355), (0.020, 1.369), (0.020, 1.384),
    (0.055, 1.384), (0.0, 1.384)], material=silver, body=carrier)
v4.joint("bowl_level", "generic", base, carrier, origin=(0, 0, 1.334), axis=(0, 0, 1),
         xdir=(1, 0, 0), dofs=[("rotX", (-math.radians(15), math.radians(15))),
                               ("rotY", (-math.radians(15), math.radians(15)))])

# Fluid head pan assembly sits on the level carrier and pans independently.
pan = v4.body("pan_base")
v4.lathe("Fluid head rotating pan base and yoke stem", [
    (0, 1.334), (0.055, 1.334), (0.072, 1.346), (0.075, 1.36),
    (0.064, 1.374), (0.038, 1.386), (0.026, 1.398),
    (0.026, 1.414), (0.0, 1.414)], loc=(0, 0, 0.05), material=black, body=pan)
# Broad, knurled pan drag dial and separate lock lever are fixed to the pan stage.
v4.cylinder("Pan drag dial", 0.019, 0.020, (0.064, -0.037, 1.405),
            rot=(math.pi / 2, 0, 0), material=dark, body=pan)
v4.torus("Pan drag dial bezel", 0.015, 0.002, loc=(0.064, -0.048, 1.405),
         rot=(math.pi / 2, 0, 0), material=steel, body=pan)
v4.cylinder("Pan lock pivot", 0.006, 0.012, (0.041, -0.028, 1.395),
            rot=(math.pi / 2, 0, 0), material=steel, body=pan)
rod("Pan lock cam lever", (0.041, -0.036, 1.395), (0.059, -0.045, 1.389), 0.0045, black, pan)
v4.sphere("Pan lock lever grip", 0.0065, (0.059, -0.045, 1.389), material=dark, body=pan)
v4.joint("pan_swivel", "continuous", carrier, pan, origin=(0, 0, 1.334), axis=(0, 0, 1))

# Tilt drum and camera plate are one connected turned assembly inside the yoke.
head = v4.body("head_tilt")
v4.lathe("Damped tilt housing with integrated QR platform", [
    (0, 1.405), (0.018, 1.405), (0.070, 1.414),
    (0.067, 1.445), (0.055, 1.46), (0.052, 1.478),
    (0.066, 1.478), (0.048, 1.48), (0, 1.48)],
    loc=(0, 0, 0.05), material=head_paint, body=head)
# Tilt trunnion caps flank the housing on the existing horizontal pivot axis.
for sx in (-1, 1):
    v4.cylinder("Tilt axle cap %d" % sx, 0.018, 0.014, (sx * 0.073, 0.018, 1.464),
                rot=(0, math.pi / 2, 0), material=black, body=head)
    v4.cylinder("Tilt axle cap fastener %d" % sx, 0.0055, 0.004, (sx * 0.081, 0.018, 1.464),
                rot=(0, math.pi / 2, 0), segments=20, material=steel, body=head)
# Tilt drag control on the front side of the painted housing.
v4.cylinder("Tilt drag dial", 0.017, 0.018, (0.0, -0.071, 1.491),
            rot=(math.pi / 2, 0, 0), material=dark, body=head)
v4.torus("Tilt dial bezel", 0.013, 0.002, loc=(0.0, -0.081, 1.491),
         rot=(math.pi / 2, 0, 0), material=steel, body=head)
# Long camera plate, two visible slide rails and its side cam lock.
v4.box("Elongated quick release plate", (0.078, 0.145, 0.010), (0, 0, 1.534),
       bevel=0.003, material=black, body=head)
for sx in (-1, 1):
    v4.box("QR slide rail %d" % sx, (0.009, 0.132, 0.008), (sx * 0.031, 0, 1.543),
           bevel=0.0018, material=silver, body=head)
v4.cylinder("Captive camera screw", 0.0055, 0.009, (0, 0, 1.544),
            segments=24, material=steel, body=head)
v4.cylinder("QR lock pivot", 0.0055, 0.009, (0.039, -0.035, 1.543),
            rot=(math.pi / 2, 0, 0), material=steel, body=head)
rod("QR side locking lever", (0.039, -0.038, 1.543), (0.054, -0.054, 1.543),
    0.0035, black, head)
v4.sphere("QR lever grip", 0.006, (0.054, -0.054, 1.543), material=dark, body=head)
v4.joint("tilt", "revolute", pan, head, origin=(0, 0, 1.464), axis=(1, 0, 0),
         limits=(-math.radians(45), math.radians(45)))

# Two detachable style pan bars pivot on the head's sides and carry textured grips.
bars = []
for i, sx in enumerate((-1, 1)):
    bar = v4.body("pan_bar_%s" % ("left" if sx < 0 else "right"))
    bars.append(bar)
    pivot = Vector((sx * 0.060, -0.005, 1.464))
    # Clamp hub and a short bent stainless handle with a moulded rubber hand grip.
    v4.cylinder("Pan bar %d clamp hub" % i, 0.023, 0.020, tuple(pivot),
                rot=(0, math.pi/2, 0), material=dark, body=bar)
    v4.cylinder("Pan bar %d clamp bolt" % i, 0.008, 0.026, tuple(pivot + Vector((sx * 0.004, 0, 0))),
                rot=(0, math.pi/2, 0), material=steel, body=bar)
    p1 = Vector((sx * 0.075, 0.09, 1.465))
    p2 = Vector((sx * 0.095, 0.165, 1.465))
    p3 = Vector((sx * 0.105, 0.235, 1.465))
    v4.tube("Pan bar %d formed arm" % i, [pivot, p1, p2, p3], 0.009, material=silver, body=bar, resolution=12)
    cylinder_between("Pan bar %d rubber grip" % i, p2, p3, 0.018, rubber, bar, bevel=0.001)
    v4.torus("Pan bar %d grip end ring" % i, 0.018, 0.002, loc=p3, rot=(math.pi/2, 0, 0), material=dark, body=bar)
    v4.joint("pan_bar_%s" % ("left" if sx < 0 else "right"), "revolute", head, bar,
             origin=tuple(pivot), axis=(1, 0, 0), limits=(-math.radians(15), math.radians(20)))

# Joint-facing pivot washers and small scale marks on the fluid head's pan ring.
for k in range(12):
    a = 2 * math.pi * k / 12
    p0 = Vector((math.cos(a) * 0.068, math.sin(a) * 0.068, 1.416))
    p1 = p0 + Vector((math.cos(a) * 0.006, math.sin(a) * 0.006, 0))
    rod("Pan scale tick %02d" % k, p0, p1, 0.0011, white, pan)

v4.save(os.path.join(os.getcwd(), "asset.blend"))
print("saved asset.blend")
