"""Procedural, articulated erhu-style spike fiddle. Run with Blender in background."""
import math
import os
import sys

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

v4.reset()

# Materials
walnut = v4.wood("Oiled walnut", light=(0.44, 0.24, 0.12), dark=(0.10, 0.035, 0.016), grain_scale=5.5,
                  roughness=0.3, coat=0.32)
walnut_edge = v4.wood("Walnut end grain", light=(0.31, 0.14, 0.065), dark=(0.10, 0.035, 0.018), grain_scale=8,
                       roughness=0.36, coat=0.25)
ebony = v4.wood("Ebony fittings", light=(0.075, 0.055, 0.043), dark=(0.018, 0.012, 0.01), grain_scale=4,
                roughness=0.24, coat=0.4)
skin = v4.fabric("Natural parchment skin", (0.72, 0.62, 0.44), weave_scale=220)
steel = v4.metal("Brushed steel", color=(0.53, 0.56, 0.59), roughness=0.25)
string_steel = v4.metal("Polished string steel", color=(0.76, 0.79, 0.82), roughness=0.18)
brass = v4.metal("Warm brass", color=(0.68, 0.43, 0.18), roughness=0.28)
ivory = v4.mat("Aged ivory", (0.83, 0.76, 0.58), roughness=0.32, coat=0.18)
hair = v4.fabric("Bow horsehair ribbon", (0.78, 0.72, 0.56), weave_scale=520)
dark = v4.mat("String and groove shadow", (0.025, 0.018, 0.014), roughness=0.68)
wrap = v4.fabric("Bow grip wrap", (0.28, 0.09, 0.035), weave_scale=300)

# Dimensions: overall height ~0.82 m. Front of instrument is toward -Y.
base = v4.body("resonator")
neck = v4.body("spike_neck")

# Pointed floor spike, ferrule, and hexagonal soundbox shell.
v4.lathe("Tapered end spike", [(0, 0), (.0006, 0), (.0035, .018), (.0052, .11), (.007, .19), (.007, .21), (0, .21)],
         loc=(0, .025, 0), material=steel, body=base)
v4.cylinder("Spike socket ferrule", .009, .02, (0, .025, .205), material=brass, body=base)
v4.torus("Ferrule turned bead", .0088, .001, (0, .025, .202), material=ivory, body=base)
hex_outline = [(-.047, -.032), (-.047, .032), (0, .055), (.047, .032), (.047, -.032), (0, -.055)]
v4.extrude("Faceted hardwood resonator", hex_outline, .060, loc=(0, .025, .265), rot=(math.pi / 2, 0, 0),
           bevel=.004, material=walnut_edge, body=base)
# A hexagonal parchment head follows the shell outline and is tensioned under a dark binding.
head_outline = [(x*.84, z*.84) for x, z in hex_outline]
v4.extrude("Taut hexagonal skin soundboard", head_outline, .004, loc=(0, -.0345, .265),
           rot=(math.pi/2, 0, 0), bevel=.0007, material=skin, body=base)
for name, scale, y, radius, mat in (("Skin edge binding", .88, -.0387, .0018, ebony),
                                    ("Inner skin inlay rim", .78, -.0402, .0009, brass)):
    rim_points = [(x*scale, y, .265+z*scale) for x, z in hex_outline]
    v4.tube(name, rim_points, radius, material=mat, body=base, cyclic=True)
# Brass tacks sit at even intervals around the hexagonal membrane perimeter.
for edge in range(6):
    a = hex_outline[edge]
    b = hex_outline[(edge+1) % 6]
    for j in range(2):
        t = (j+0.5)/2
        x = (a[0]*(1-t) + b[0]*t) * .86
        z = .265 + (a[1]*(1-t) + b[1]*t) * .86
        v4.sphere(f"Skin tack {edge*2+j+1:02d}", .0017, (x, -.0398, z), segments=16, material=brass, body=base)
# Small dark rear sound vent and a thin brass lip sit on the back face.
v4.torus("Rear sound window rim", .021, .002, (0, .026, .265), rot=(math.pi / 2, 0, 0), material=brass, body=base)
v4.cylinder("Rear sound window", .019, .002, (0, .026, .265), rot=(math.pi / 2, 0, 0),
            bevel=0, material=dark, body=base)
# Decorative grille bars cross the recessed dark window and meet its brass rim.
for i, x in enumerate((-.012, -.006, 0, .006, .012), start=1):
    half = math.sqrt(max(0.0, .018 ** 2 - x ** 2))
    v4.rod(f"Sound window vertical grille {i}", (x, .0272, .265-half), (x, .0272, .265+half), .0007,
           material=brass, body=base)

# Wide, low ebony bridge foot supports the two strings at separate depths on the membrane.
v4.box("Bridge foot", (.026, .026, .008), (0, -.057, .304), bevel=.002, material=ebony, body=base)
for idx, (sx, sy) in enumerate(((-.004, -.050), (.004, -.060)), start=1):
    v4.rod(f"Bridge string saddle {idx}", (sx, sy, .306), (sx, sy, .322), .0024,
           material=walnut_edge, body=base)
    v4.sphere(f"Bridge groove bead {idx}", .0018, (sx, sy, .322), segments=16, material=ivory, body=base)

# Hardwood neck is one tapered board; narrow pegbox head is integrated with it.
neck_outline = [(-.014, .295), (-.018, .322), (-.013, .365), (-.011, .49), (-.012, .62),
                (-.014, .674), (-.019, .692), (-.026, .704),
                (-.026, .773), (-.019, .788), (.019, .788), (.026, .773), (.026, .704),
                (.019, .692), (.014, .674), (.012, .62), (.011, .49), (.013, .365),
                (.018, .322), (.014, .295)]
v4.extrude("One-piece neck and pegbox", neck_outline, .032, loc=(0, .008, 0), rot=(math.pi/2, 0, 0),
           bevel=.008, material=walnut, body=neck)
# Pegbox side cheeks and subtle open-slot dark inset on the front.
v4.box("Pegbox face inset", (.036, .0015, .061), (0, -.0255, .743), bevel=.002, material=ebony, body=neck)
v4.box("Pegbox slot highlight", (.004, .001, .045), (0, -.0267, .743), bevel=.0005, material=walnut_edge, body=neck)
# A turned carved finial completes the pegbox crown.
v4.lathe("Carved pegbox finial", [(0, 0), (.010, 0), (.013, .004), (.011, .009), (.007, .015),
        (.011, .021), (.009, .027), (.005, .033), (0, .038)],
        loc=(0, .008, .786), material=walnut_edge, body=neck)
# Two individually visible steel strings, 7 mm apart across X and 10 mm apart in depth
# at the bowing point. Each runs from a tailpiece knot, over its own bridge saddle, to a peg.
string_anchors = [(-.004, -.050, -.0223, .755), (.004, -.060, -.0302, .715)]
peg_info = [("peg_left", -.022, .755, -1), ("peg_right", .022, .715, 1)]
for idx, (sx, bridge_y, top_y, peg_z) in enumerate(string_anchors, start=1):
    tail = (sx, -.058, .294)
    bridge = (sx, bridge_y, .322)
    nut = (sx, top_y, .653)
    shaft_contact = (sx, .002, peg_z)
    v4.rod(f"Steel string {idx} lower run", tail, bridge, .0018,
           segments=16, bevel=0, material=string_steel, body=base)
    v4.rod(f"Steel string {idx} neck run", bridge, nut, .0018,
           segments=16, bevel=0, material=string_steel, body=base)
    v4.rod(f"Steel string {idx} peg lead", nut, shaft_contact, .0018,
           segments=16, bevel=0, material=string_steel, body=base)
    v4.sphere(f"Tailpiece string knot {idx}", .002, tail, segments=20, material=brass, body=base)
v4.box("Tailpiece", (.026, .020, .014), (0, -.049, .297), bevel=.002, material=ebony, body=base)

# Two turning pegs, staggered vertically and fitted through the pegbox on X axes.
peg_bodies = []
for name, pivot_x, z, knob_side in peg_info:
    pb = v4.body(name)
    peg_bodies.append(pb)
    v4.rod(f"{name} hardwood shaft", (-.066, .008, z), (.066, .008, z), .0055,
           material=walnut_edge, body=pb)
    # Ivory bushings where the spindle exits each side of the pegbox.
    for side in (-1, 1):
        v4.cylinder(f"{name} pegbox collar {side}", .0095, .006, (side*.0285, .008, z),
                    rot=(0, math.pi/2, 0), material=ivory, body=pb)
        v4.cylinder(f"{name} collar brass lip {side}", .010, .0015, (side*.032, .008, z),
                    rot=(0, math.pi/2, 0), material=brass, body=pb)
    # Carved pear-shaped tuning head, turned along the peg's X axis.
    kx = knob_side*.066
    v4.lathe(f"{name} carved tuning button", [(0, 0), (.006, 0), (.008, .004), (.011, .009),
            (.014, .015), (.013, .020), (.010, .025), (.007, .031), (.005, .038), (0, .041)], loc=(kx, .008, z),
            rot=(0, knob_side*math.pi/2, 0), material=ebony, body=pb)
    v4.sphere(f"{name} end pearl", .0035, (knob_side*.107, .008, z), segments=20, material=ivory, body=pb)

# Peg string windings belong to the rotating peg assemblies so they turn with each shaft.
for idx, ((name, pivot_x, peg_z, knob_side), (sx, bridge_y, top_y, _)) in enumerate(zip(peg_info, string_anchors), start=1):
    coil_points = []
    turns, steps, coil_r = 2.0, 48, .006
    for j in range(steps + 1):
        t = j / steps
        a = math.pi + t * turns * 2 * math.pi
        coil_points.append((sx + .012*t, .008 + coil_r*math.cos(a), peg_z + coil_r*math.sin(a)))
    v4.tube(f"Peg winding {idx}", coil_points, .001, material=string_steel, body=peg_bodies[idx-1])

# A small ebony qianjin guide with ivory string contact beads holds spacing on the upper neck.
guide_z = .585
guide_strings = []
for sx, bridge_y, top_y, _ in string_anchors:
    t = (guide_z-.322)/(.653-.322)
    guide_strings.append((sx, bridge_y*(1-t) + top_y*t, guide_z))
v4.rod("Upper neck qianjin saddle", guide_strings[0], guide_strings[1], .0025,
       material=ebony, body=neck)
for i, p in enumerate(guide_strings, start=1):
    # Short ebony stays seat the guide against the neck face while meeting each string.
    v4.rod(f"Qianjin neck stay {i}", (p[0], -.009, guide_z), p, .0015,
           material=walnut_edge, body=neck)
    v4.sphere(f"Qianjin string guide bead {i}", .003, p, segments=20, material=ivory, body=neck)

# Captive bow: horizontal curved walnut stick, taut horizontal horsehair, and end ties.
bow = v4.body("captive_bow")
hair_y = -.0412
bow_z = .475
half_span = .32  # 64 cm bow, with enough hair remaining across both strings at full travel
hair_width_y = .010
hair_front_y = hair_y + hair_width_y / 2
hair_back_y = hair_y - hair_width_y / 2
v4.tube("Curved bow stick", [(-half_span, -.095, bow_z), (-.16, -.106, bow_z),
                              (0, -.113, bow_z), (.16, -.106, bow_z),
                              (half_span, -.095, bow_z)], .0042, material=walnut_edge, body=bow)
# Fine parallel horsehair strands make a clearly visible ribbon between the two strings.
for i in range(9):
    yy = hair_back_y + hair_width_y * i / 8
    v4.rod(f"Bow hair ribbon strand {i+1}", (-half_span, yy, bow_z),
           (half_span, yy, bow_z), .00048, segments=12, bevel=0, material=hair, body=bow)
# End ties join the whole ribbon to the stick, keeping every strand captured in the bow.
for sx in (-half_span, half_span):
    v4.rod(f"Bow end tie {sx}", (sx, -.095, bow_z), (sx, hair_front_y, bow_z), .0016, material=wrap, body=bow)
# Ebony frog and a woven grip sit near the hair anchor at the left end; the opposite end is the tip.
v4.box("Ebony bow frog", (.038, .016, .016), (-.274, -.098, bow_z), bevel=.003, material=ebony, body=bow)
v4.tube("Wound leather frog grip", [(-.292, -.097, bow_z), (-.268, -.098, bow_z), (-.244, -.099, bow_z)],
        .0055, material=wrap, body=bow)
for sx in (-half_span, half_span):
    v4.cylinder(f"Bow end ferrule {sx}", .005, .009, (sx, -.095, bow_z),
                rot=(0, math.pi/2, 0), material=brass, body=bow)
# A compact turned tension screw projects from the frog end of the stave.
v4.lathe("Bow hair tension screw", [(0, 0), (.003, 0), (.004, .002), (.004, .006), (.005, .008), (0, .009)],
         loc=(-half_span-.003, -.095, bow_z), rot=(0, -math.pi/2, 0), material=brass, body=bow)

# Joint tree: soundbox is the single root, neck fixed at its real mortise, pegs turn,
# and the captive bow slides along its own hair span across the strings.
v4.joint("neck_mount", "fixed", base, neck, origin=(0, 0, .29), axis=(0, 0, 1))
v4.joint("peg_left_turn", "continuous", neck, peg_bodies[0], origin=(-.022, .008, .755), axis=(1, 0, 0))
v4.joint("peg_right_turn", "continuous", neck, peg_bodies[1], origin=(.022, .008, .715), axis=(1, 0, 0))
v4.joint("bow_stroke", "prismatic", neck, bow, origin=(0, hair_y, bow_z), axis=(1, 0, 0), limits=(-.20, .20))

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