"""Detailed articulated threshing flail. Run with Blender's Python interpreter."""
import math
import os
import sys
from mathutils import Vector

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

v4.reset()

# Materials
ash = v4.wood("seasoned_ash", light=(0.72, 0.54, 0.34), dark=(0.40, 0.25, 0.13), grain_scale=7)
ash_upper = v4.wood("ash_scarf_grain", light=(0.63, 0.45, 0.27), dark=(0.31, 0.18, 0.09), grain_scale=10)
oak = v4.wood("dark_oak", light=(0.35, 0.21, 0.11), dark=(0.14, 0.065, 0.03), grain_scale=8)
endgrain = v4.wood("oak_endgrain", light=(0.58, 0.39, 0.23), dark=(0.26, 0.15, 0.08), grain_scale=11)
leather = v4.mat("oiled_harness_leather", (0.22, 0.075, 0.035), roughness=0.72)
leather_edge = v4.mat("leather_edge", (0.12, 0.035, 0.018), roughness=0.8)
rawhide = v4.mat("worn_rawhide", (0.34, 0.20, 0.105), roughness=0.82)
steel = v4.metal("forged_steel", (0.40, 0.43, 0.45), roughness=0.34)
dark_steel = v4.metal("blackened_steel", (0.13, 0.15, 0.16), roughness=0.4, brushed=False)
brass = v4.metal("aged_brass", (0.38, 0.27, 0.12), roughness=0.48, brushed=False)

# Bodies: staff is deliberately made in two hinged sections, followed by a short
# two-axis thong and a freely hanging striking stick.
staff_a = v4.body("handstaff_lower")
staff_b = v4.body("handstaff_upper")
thong = v4.body("thong_link")
swipple = v4.body("swipple")

def tapered_shaft(name, p0, p1, r0, r1, material, body, bevel=0.001):
    p0, p1 = Vector(p0), Vector(p1)
    d = p1 - p0
    obj = v4.cylinder(name, r0, d.length, loc=(p0+p1)/2, radius_top=r1,
                      bevel=bevel, segments=48, material=material, body=body)
    obj.rotation_mode = "QUATERNION"
    obj.rotation_quaternion = d.to_track_quat("Z", "Y")
    return obj

def cylinder_on_axis(name, center, axis, radius, depth, material, body, bevel=0.0006, segments=40):
    axis = Vector(axis).normalized()
    obj = v4.cylinder(name, radius, depth, loc=center, bevel=bevel, segments=segments,
                      material=material, body=body)
    obj.rotation_mode = "QUATERNION"
    obj.rotation_quaternion = axis.to_track_quat("Z", "Y")
    return obj

def torus_axis(name, center, axis, major, minor, material, body):
    axis = Vector(axis).normalized()
    obj = v4.torus(name, major, minor, loc=center, material=material, body=body)
    obj.rotation_mode = "QUATERNION"
    obj.rotation_quaternion = axis.to_track_quat("Z", "Y")
    return obj

P0 = Vector((0.0, 0.0, 0.025))
P1 = Vector((0.10, 0.0, 0.59))
P2 = Vector((0.19, 0.0, 1.12))
P3 = Vector((0.211, 0.0, 0.98))
P4 = Vector((0.211, 0.0, 0.46))
axis_staff = P1 - P0
axis_upper = P2 - P1
axis_thong = P3 - P2
axis_swipple = P4 - P3

# Lower handstaff: straight, full-sized ash with a quiet rawhide palm wrap.
tapered_shaft("lower_staff_ash", P0, P1-axis_staff.normalized()*0.012, 0.017, 0.017, ash, staff_a, 0.0015)
cylinder_on_axis("butt_end_cap", P0 + axis_staff.normalized()*0.008, axis_staff, 0.017, 0.016,
                 endgrain, staff_a, 0.0008)
# A dark rawhide keeper is the only accent below the grip; no bright ferrule band.
ferrule_axis = axis_staff.normalized()
grip_a = P0 + ferrule_axis*0.205
grip_b = P0 + ferrule_axis*0.335
tapered_shaft("rawhide_hand_wrap", grip_a, grip_b, 0.019, 0.0185, rawhide, staff_a, 0.0015)
for k in range(8):
    t = k/7
    p = grip_a.lerp(grip_b, t)
    torus_axis("grip_wrap_seam_%02d" % k, p, ferrule_axis, 0.0188, 0.00055,
               leather, staff_a)
for end, pos in enumerate((grip_a, grip_b)):
    cylinder_on_axis("rawhide_grip_binding_%d" % end, pos, ferrule_axis, 0.019, 0.005,
                     leather, staff_a, 0.0005)
# Upper staff section with a timber scarf and restrained iron reinforcing straps.
tapered_shaft("upper_staff_ash", P1+axis_upper.normalized()*0.012, P2, 0.017, 0.017, ash_upper, staff_b, 0.0015)
# Forged sleeves wrap the newly relieved timber ends and terminate at the pivot knuckles.
cylinder_on_axis("lower_hinge_collar", P1-axis_staff.normalized()*0.0375,
                 axis_staff, 0.0185, 0.035, dark_steel, staff_a, 0.001)
cylinder_on_axis("upper_hinge_collar", P1+axis_upper.normalized()*0.0375,
                 axis_upper, 0.0185, 0.035, dark_steel, staff_b, 0.001)
# Alternating barrel knuckles meet at the joint's centre plane and rotate about the Y pin.
v4.cylinder("lower_hinge_knuckle", 0.020, 0.020, (P1.x, -0.010, P1.z),
            rot=(math.pi/2, 0, 0), material=dark_steel, body=staff_a)
v4.cylinder("upper_hinge_knuckle", 0.020, 0.020, (P1.x, 0.010, P1.z),
            rot=(math.pi/2, 0, 0), material=dark_steel, body=staff_b)
# Long iron strap leaves follow the grain along the scarf, rather than forming a clamp.
for side in (-1, 1):
    side_tag = "L" if side < 0 else "R"
    y = side*0.017
    lower_center = P1 - axis_staff.normalized()*0.025
    upper_center = P1 + axis_upper.normalized()*0.025
    lower_angle = math.atan2(axis_staff.x, axis_staff.z)
    upper_angle = math.atan2(axis_upper.x, axis_upper.z)
    v4.box("scarf_iron_strap_lower_" + side_tag, (0.020, 0.003, 0.080),
           (lower_center.x, y, lower_center.z), rot=(0, lower_angle, 0),
           bevel=0.002, material=dark_steel, body=staff_a)
    v4.box("scarf_iron_strap_upper_" + side_tag, (0.020, 0.003, 0.080),
           (upper_center.x, y, upper_center.z), rot=(0, upper_angle, 0),
           bevel=0.002, material=dark_steel, body=staff_b)
    # Four small flush rivets pin the straps into the scarfed timber.
    for k, offset in enumerate((-0.027, 0.027)):
        lower_rivet = lower_center + axis_staff.normalized()*offset + Vector((0, side*0.003, 0))
        upper_rivet = upper_center + axis_upper.normalized()*offset + Vector((0, side*0.003, 0))
        v4.sphere("scarf_rivet_lower_%s_%d" % (side_tag,k), 0.003, lower_rivet,
                  segments=20, material=brass, body=staff_a)
        v4.sphere("scarf_rivet_upper_%s_%d" % (side_tag,k), 0.003, upper_rivet,
                  segments=20, material=brass, body=staff_b)
# Pin hardware centered precisely on the hinge line.
v4.cylinder("staff_hinge_pin", 0.006, 0.044, P1, rot=(math.pi/2, 0, 0),
            material=steel, body=staff_b)
for side in (-1, 1):
    side_tag = "L" if side < 0 else "R"
    v4.cylinder("hinge_pin_washer_" + side_tag, 0.010, 0.003, (P1.x, side*0.0215, P1.z),
                rot=(math.pi/2, 0, 0), material=brass, body=staff_b)
    v4.cylinder("hinge_pin_rivet_" + side_tag, 0.005, 0.002, (P1.x, side*0.024, P1.z),
                rot=(math.pi/2, 0, 0), segments=32, material=dark_steel, body=staff_b)

# Two visible, interlocked leather eyelet loops make the flexible connector read as a chain.
strap_axis = (P3-P2).normalized()
def loop_points(center, u, v, ru, rv, count=40, phase=0.0):
    center, u, v = Vector(center), Vector(u).normalized(), Vector(v).normalized()
    pts = []
    for i in range(count):
        t = 2*math.pi*i/count
        handforged = 1.0 + 0.045*math.sin(3*t+phase) + 0.022*math.sin(7*t-phase)
        pts.append(center + ru*handforged*math.cos(t)*u + rv*handforged*math.sin(t)*v)
    return pts

chain_centers = [P2 + Vector((dx, 0, dz)) for dx, dz in (
    (0.045, -0.030), (0.055, -0.075), (0.065, -0.120))]
for i, center in enumerate(chain_centers):
    center = center + Vector((0, 0.030, 0))
    # Three small, alternating forged links hang nearly vertically from the eye.
    if i % 2 == 0:
        u, v, ru, rv = (1,0,0), (0,0,1), 0.017, 0.030
    else:
        u, v, ru, rv = (0,1,0), (0,0,1), 0.017, 0.030
    v4.tube("forged_chain_loop_%02d" % i,
            loop_points(center, u, v, ru, rv, phase=0.3+i*0.71),
            0.0055, material=dark_steel, body=thong, cyclic=True)
torus_axis("upper_thong_eyelet", P2, axis_upper, 0.022, 0.005, dark_steel, staff_b)
# A short shackle passes through the staff eyelet and joins the first hanging link.
eye_contact = P2 + Vector((0.015, 0.020, 0))
chain_contact = chain_centers[0] + Vector((0, 0.030, 0.030))
v4.tube("upper_swivel_shackle", [P2, eye_contact, chain_contact], 0.0045,
        material=dark_steel, body=thong, resolution=8)
cylinder_on_axis("lower_eyelet_grommet", P3, strap_axis, 0.012, 0.030,
                 dark_steel, thong, 0.0005)
# A short leather tail ties the final forged loop into the lower bored eyelet.
tail_start = chain_centers[-1] + Vector((0,0.030,-0.025))
tail_end = P3 - strap_axis*0.015
v4.rod("lower_eyelet_leather_tail", tail_start, tail_end, 0.0045,
       material=leather, body=thong, bevel=0.0005)

# Bored swivel cap fixed to the upper staff; the leather loop bears on its rounded nose.
cylinder_on_axis("upper_staff_swivel_cap", P2-axis_upper.normalized()*0.015,
                 axis_upper, 0.017, 0.030, dark_steel, staff_b, 0.001)
cylinder_on_axis("swivel_cap_lip", P2-axis_upper.normalized()*0.001,
                 axis_upper, 0.0235, 0.004, brass, staff_b, 0.0006)
for k, along in enumerate((0.029, 0.044, 0.059)):
    torus_axis("swivel_leather_wrap_%d" % k, P2-axis_upper.normalized()*along,
               axis_upper, 0.0175, 0.0022, leather, staff_b)

# Short, heavy, dark oak swipple with a rawhide capping at the thong end.
tapered_shaft("swipple_oak_body", P3, P4, 0.0225, 0.0225, oak, swipple, 0.003)
swip_axis = axis_swipple.normalized()
# A short rawhide hood is lashed over the head; the turns are irregular bindings.
cap_start = P3 + swip_axis*0.006
cap_end = P3 + swip_axis*0.074
tapered_shaft("swipple_rawhide_capping", cap_start, cap_end, 0.0245, 0.0235,
              rawhide, swipple, 0.0018)
for k, along in enumerate((0.016, 0.048, 0.071)):
    center = P3 + swip_axis*along
    v4.torus("swipple_capping_tie_%d" % k, 0.0237, 0.0018,
             loc=center, material=leather, body=swipple)
# The striking end is rounded, exposed hardwood rather than a machined metal shoe.
v4.sphere("worn_rounded_striking_end", 0.0225, P4-swip_axis*0.014,
          segments=32, material=endgrain, body=swipple)

# Articulation tree. Generic joints add two real rotational DOFs for loose, spatial swing.
v4.joint("staff_hinge", "revolute", staff_a, staff_b, origin=P1, axis=(0,1,0),
         limits=(-math.radians(22), math.radians(22)))
v4.joint("thong_hinge", "generic", staff_b, thong, origin=P2, axis=(0,0,1),
         dofs=[("rotX",(-math.radians(75),math.radians(75))),
               ("rotY",(-math.radians(75),math.radians(75)))], xdir=(1,0,0))
v4.joint("swipple_hinge", "generic", thong, swipple, origin=P3, axis=(0,0,1),
         dofs=[("rotX",(-math.radians(60),math.radians(60))),
               ("rotY",(-math.radians(60),math.radians(8)))], xdir=(1,0,0))

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