"""Detailed articulated bass clarinet asset. Run with Blender: blender -b --python build.py"""
import math
import os
import sys

import bpy
from mathutils import Vector, Matrix

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

v4.reset()

# Materials: a nearly black African blackwood barrel, satin nickel mechanism, and
# restrained black rubber/felt with a small warm reed and maker's marks.
wood = v4.wood("African_blackwood", light=(0.105, 0.085, 0.066), dark=(0.019, 0.018, 0.017),
                grain_scale=7.0, roughness=0.26, coat=0.38)
nickel = v4.metal("satin_nickel_silver", color=(0.77, 0.79, 0.82), roughness=0.24)
bright = v4.metal("polished_nickel_edges", color=(0.88, 0.89, 0.91), roughness=0.17, brushed=False)
black = v4.rubber("mouthpiece_ebonite", color=(0.018, 0.019, 0.02), roughness=0.28)
port_black = v4.mat("tone_hole_shadow", (0.012, 0.014, 0.016), roughness=0.82)
padmat = v4.rubber("pad_felt", color=(0.15, 0.15, 0.14), roughness=0.88)
reedmat = v4.mat("cane_reed", (0.43, 0.23, 0.095), roughness=0.43)
pearl = v4.mat("key_pearl", (0.78, 0.73, 0.60), roughness=0.22, coat=0.25)

instrument = v4.body("instrument")

# Centreline profile of the hollow upper/lower clarinet joints.  The profile runs
# up the outer wall, back down the bore, then closes the bottom annulus.
body_profile = [
    (0.032, 0.160), (0.034, 0.178), (0.035, 0.205), (0.036, 0.275),
    (0.036, 0.395), (0.036, 0.565), (0.039, 0.590), (0.040, 0.605),
    (0.040, 0.635), (0.037, 0.650), (0.034, 0.665), (0.033, 0.690),
    (0.033, 0.850), (0.033, 1.075), (0.036, 1.095), (0.038, 1.112),
    (0.038, 1.145), (0.035, 1.163), (0.032, 1.180),
    # bore wall, descending from the top opening
    (0.0255, 1.180), (0.0255, 1.163), (0.0275, 1.145), (0.029, 1.112),
    (0.027, 1.095), (0.026, 0.850), (0.026, 0.690), (0.029, 0.665),
    (0.034, 0.635), (0.034, 0.605), (0.033, 0.590), (0.030, 0.565),
    (0.030, 0.395), (0.030, 0.275), (0.029, 0.205), (0.026, 0.178),
    (0.026, 0.160), (0.032, 0.160)
]
barrel = v4.lathe("hollow_blackwood_upper_and_lower_joints", body_profile, segments=96,
                  material=wood, body=instrument)

# Smooth body-radius estimate, used to place rings, tone holes, and posts at the
# actual turned surface rather than at a generic cylinder.
profile_r = [(0.160, .032), (.178, .034), (.205, .035), (.275, .036),
             (.565, .036), (.605, .040), (.635, .040), (.665, .034),
             (.850, .033), (1.075, .033), (1.112, .038), (1.145, .038),
             (1.180, .032)]
def body_radius(z):
    if z <= profile_r[0][0]: return profile_r[0][1]
    for (za, ra), (zb, rb) in zip(profile_r[:-1], profile_r[1:]):
        if za <= z <= zb:
            t = (z-za)/(zb-za)
            return ra + (rb-ra)*t
    return profile_r[-1][1]

def rot_axis(direction):
    return Vector(direction).normalized().to_track_quat("Z", "Y").to_euler()

def annular_collar(name, z0, z1, inner, outer, material, body=instrument, segments=64, loc=(0,0,0)):
    prof = [(outer, z0), (outer, z1), (inner, z1), (inner, z0), (outer, z0)]
    return v4.lathe(name, prof, loc=loc, segments=segments, material=material, body=body)

def radial_collar(name, center, axis, z0, z1, inner, outer, material, body, segments=48):
    """Turned sleeve around an arbitrary axis; z0/z1 are distances along axis."""
    prof = [(inner,z0),(outer-.00035,z0),(outer,z0+.00045),
            (outer,z1-.00045),(outer-.00035,z1),(inner,z1),(inner,z0)]
    return v4.lathe(name,prof,loc=tuple(center),rot=rot_axis(axis),segments=segments,
                    material=material,body=body)

def add_body_band(name, z, width, material=nickel, extra=0.0013):
    rr = body_radius(z)
    annular_collar(name, z-width/2, z+width/2, rr-0.0002, rr+extra, material)

# Bright turned ferrules and fine seam rings make the two long wooden joints read
# as assembled sections rather than one featureless tube.
for i, (z, width, extra) in enumerate(((.195,.004,.0010), (.277,.003,.0008),
                                       (.585,.006,.0014), (.642,.004,.0012),
                                       (.674,.003,.0008), (1.090,.004,.0012),
                                       (1.146,.006,.0016), (1.172,.003,.0010))):
    add_body_band("turned_nickel_tenon_band_%02d" % i, z, width, nickel, extra)
for i, z in enumerate((.205, .281, .591, .638, .680, 1.086, 1.098, 1.151, 1.168)):
    rr = body_radius(z) + .0007
    v4.torus("hairline_joint_seam_%02d" % i, rr, .00038, loc=(0,0,z), material=bright, body=instrument)

# Small knurled collars around selected ferrules, represented as repeated fine
# relief ribs, all attached to the fixed body.
for z, radius in ((.588,.0408), (1.147,.0393)):
    for k in range(32):
        a = 2*math.pi*k/32
        n = Vector((math.cos(a), math.sin(a), 0))
        p0 = n * (radius - .00015); p0.z = z - .0015
        p1 = n * (radius + .00030); p1.z = z + .0015
        v4.rod("ferrule_knurl_rib", p0, p1, .00028, segments=8, bevel=0, material=bright, body=instrument)

# A shell sweep produces a watertight hollow round tube along a bent centreline.
# The end rings are open bores with a real annular lip; interior faces are darkened.
def swept_hollow(name, points, radii, wall, outer_mat, inner_mat, body, sides=48, steps=8):
    # The drawn centreline is a sparse design curve. Resample it with a Catmull-
    # Rom spline before meshing, then carry the radial frame by parallel transport.
    # This keeps bent brass profiles smooth without the twist caused by projecting
    # the same world-up vector independently at every ring.
    controls = [Vector(p) for p in points]
    def catmull(a, b, c, d, t):
        t2, t3 = t*t, t*t*t
        return .5*((2*b) + (-a+c)*t + (2*a-5*b+4*c-d)*t2 + (-a+3*b-3*c+d)*t3)
    pts, rs = [], []
    for i in range(len(controls)-1):
        p0 = controls[max(0, i-1)]
        p1, p2 = controls[i], controls[i+1]
        p3 = controls[min(len(controls)-1, i+2)]
        r0, r1 = radii[max(0, i-1)], radii[i]
        r2, r3 = radii[i+1], radii[min(len(radii)-1, i+2)]
        for k in range(steps):
            t = k/steps
            pts.append(catmull(p0, p1, p2, p3, t))
            rv = catmull(Vector((r0,0,0)), Vector((r1,0,0)), Vector((r2,0,0)), Vector((r3,0,0)), t).x
            rs.append(max(wall+.001, rv))
    pts.append(controls[-1]); rs.append(radii[-1])
    frames = []
    tangents = []
    for i in range(len(pts)):
        if i == 0: tangent = (pts[1]-pts[0]).normalized()
        elif i == len(pts)-1: tangent = (pts[-1]-pts[-2]).normalized()
        else: tangent = (pts[i+1]-pts[i-1]).normalized()
        tangents.append(tangent)
    tangent = tangents[0]
    ref = Vector((0, 1, 0))
    if abs(tangent.dot(ref)) > .94: ref = Vector((1, 0, 0))
    normal = (ref - tangent*ref.dot(tangent)).normalized()
    frames.append((normal, tangent.cross(normal).normalized()))
    for i in range(1, len(pts)):
        prev_t, tangent = tangents[i-1], tangents[i]
        normal = prev_t.rotation_difference(tangent) @ normal
        normal = (normal - tangent*normal.dot(tangent)).normalized()
        frames.append((normal, tangent.cross(normal).normalized()))
    verts, faces, mat_ids = [], [], []
    outer_rings, inner_rings = [], []
    for i, (p, ro) in enumerate(zip(pts, rs)):
        n,b = frames[i]
        rout, rin = [], []
        for j in range(sides):
            a = 2*math.pi*j/sides
            q = n*math.cos(a) + b*math.sin(a)
            rout.append(len(verts)); verts.append(tuple(p + q*ro))
        for j in range(sides):
            a = 2*math.pi*j/sides
            q = n*math.cos(a) + b*math.sin(a)
            rin.append(len(verts)); verts.append(tuple(p + q*max(.001, ro-wall)))
        outer_rings.append(rout); inner_rings.append(rin)
    for i in range(len(pts)-1):
        for j in range(sides):
            jp=(j+1)%sides
            faces.append((outer_rings[i][j], outer_rings[i][jp], outer_rings[i+1][jp], outer_rings[i+1][j])); mat_ids.append(0)
            faces.append((inner_rings[i+1][j], inner_rings[i+1][jp], inner_rings[i][jp], inner_rings[i][j])); mat_ids.append(1)
    for j in range(sides):
        jp=(j+1)%sides
        faces.append((outer_rings[0][jp], outer_rings[0][j], inner_rings[0][j], inner_rings[0][jp])); mat_ids.append(0)
        k=len(pts)-1
        faces.append((outer_rings[k][j], outer_rings[k][jp], inner_rings[k][jp], inner_rings[k][j])); mat_ids.append(0)
    mesh=bpy.data.meshes.new(name+"Mesh")
    mesh.from_pydata(verts, [], faces); mesh.materials.append(outer_mat); mesh.materials.append(inner_mat); mesh.update()
    for poly, mid in zip(mesh.polygons, mat_ids):
        poly.material_index=mid; poly.use_smooth=True
    obj=bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.objects.link(obj)
    v4.part(obj, body)
    return obj

# Lower swept bell: it leaves the bottom bore, curves forward/right, and opens
# upward on the side like a standard bass-clarinet bell. The first annular rim
# mates to the body shell's bottom annulus.
bell_path = [(0,0,.160), (0,-.002,.134), (.009,-.007,.111), (.031,-.014,.096),
             (.063,-.022,.094), (.096,-.032,.102), (.126,-.040,.119),
             (.149,-.046,.141), (.160,-.050,.164), (.163,-.051,.174)]
bell_r = [.032,.028,.023,.0185,.0155,.015,.019,.030,.047,.052]
bell = swept_hollow("swept_silver_lower_bell", bell_path, bell_r, .0032,
                     nickel, port_black, instrument, sides=48)
# Fine rolled mouth rim at the upward bell flare; the torus lies perpendicular to
# the opening axis and sits on its lip.
bell_axis = Vector(bell_path[-1])-Vector(bell_path[-2])
bell_rot = rot_axis(bell_axis)
bell_center = Vector(bell_path[-1])
# A small rolled rim follows the last, nearly vertical bell section.
v4.torus("bell_rolled_lip", .0506, .0016, loc=tuple(bell_center), rot=bell_rot,
         material=bright, body=instrument)

# A second fine bead just below the flare break catches a narrow highlight on
# the continuously swept bell throat without interrupting its curved profile.
bell_shoulder=Vector(bell_path[-2])
v4.torus("bell_flare_shoulder_bead",.0455,.00085,loc=tuple(bell_shoulder),
         rot=bell_rot,material=nickel,body=instrument)

# Upper neck receiver ferrule: broad outside edge seats over the wooden rim while
# its small central bore accepts the curved crook.
# The broad ferrule only covers the wood-to-metal joint. A narrow receiver tube
# continues to the crook spigot so the top does not read as one oversized socket.
annular_collar("upper_neck_receiver_socket", 1.165, 1.194, .0090, .0332, nickel)
annular_collar("receiver_lower_bead", 1.171, 1.177, .0324, .0344, bright)
annular_collar("receiver_socket_shank", 1.192, 1.226, .0088, .0118, nickel)
annular_collar("receiver_upper_bead", 1.216, 1.222, .0091, .0127, bright)
# Silver gooseneck/crook with a dark bore. Its first end meets the receiver bore.
crook_path = [(0,0,1.226), (0,.015,1.253), (0,.042,1.282), (0,.053,1.315),
              (-.004,.051,1.343), (-.016,.038,1.365), (-.034,.012,1.375),
              (-.052,-.010,1.367)]
crook_r = [.0090,.0090,.0090,.0090,.0090,.0090,.0090,.0090]
swept_hollow("curved_silver_neck_crook", crook_path, crook_r, .0018,
             bright, port_black, instrument, sides=48)

# Mouthpiece shank/bite and reed follow the terminal direction of the crook.
mp_axis = (Vector(crook_path[-1])-Vector(crook_path[-2])).normalized()
mp_origin = Vector(crook_path[-1])
mp_rot = rot_axis(mp_axis)
# A bass-clarinet beak has a rounded square section and a flat reed table. Sweep
# those sections along the mouthpiece axis instead of using a pointed round lathe.
mp_sections=[(-.002,.016,.014),(.000,.017,.015),(.010,.018,.016),
             (.022,.020,.018),(.036,.023,.020),(.052,.024,.0205),
             (.070,.024,.020),(.083,.0215,.018),(.096,.017,.014),
             (.105,.013,.010),(.108,.010,.008)]
section_outline=[(-.42,.42),(-.48,.34),(-.50,0),(-.48,-.34),(-.42,-.42),
                 (0,-.46),(.42,-.42),(.48,-.34),(.50,0),(.48,.34),
                 (.42,.42),(.34,.49),(0,.50),(-.34,.49)]
def mp_section(z):
    if z<=mp_sections[0][0]: return mp_sections[0][1:]
    for a,b in zip(mp_sections[:-1],mp_sections[1:]):
        if a[0]<=z<=b[0]:
            t=(z-a[0])/(b[0]-a[0])
            return (a[1]+(b[1]-a[1])*t,a[2]+(b[2]-a[2])*t)
    return mp_sections[-1][1:]
mp_vertices=[]; mp_rings=[]
for z,w,h in mp_sections:
    ring=[]
    for x,y in section_outline:
        # Broad flat at +Y receives the reed; the opposite wall stays rounded.
        if y>.35 and abs(x)<.43: y=.42
        ring.append(len(mp_vertices)); mp_vertices.append((x*w,y*h,z))
    mp_rings.append(ring)
mp_faces=[tuple(reversed(mp_rings[0])),tuple(mp_rings[-1])]
for k in range(len(mp_rings)-1):
    for j in range(len(section_outline)):
        jn=(j+1)%len(section_outline)
        mp_faces.append((mp_rings[k][j],mp_rings[k][jn],mp_rings[k+1][jn],mp_rings[k+1][j]))
mp_mesh=bpy.data.meshes.new("BassClarinetMouthpieceMesh")
mp_mesh.from_pydata(mp_vertices,[],mp_faces); mp_mesh.materials.append(black); mp_mesh.update()
for poly in mp_mesh.polygons: poly.use_smooth=True
mp_obj=bpy.data.objects.new("black_ebonite_bass_clarinet_mouthpiece",mp_mesh)
bpy.context.scene.collection.objects.link(mp_obj)
mp_obj.location=tuple(mp_origin-mp_axis*.002); mp_obj.rotation_euler=mp_rot
v4.part(mp_obj,instrument)
# Tapered cane reed sits directly on the mouthpiece's flattened table. Its lower
# face follows the table height, narrowing to the reed tip without hovering.
mp_q = Vector(mp_axis).to_track_quat("Z", "Y")
reed_normal = (mp_q @ Vector((0,1,0))).normalized()
reed_rows=[(.028,.0070),(.040,.0088),(.056,.0096),(.074,.0093),
           (.088,.0082),(.099,.0064),(.106,.0035),(.108,.0005)]
reed_vertices=[]; reed_rings=[]; reed_thick=.0008
for z,w in reed_rows:
    _,h=mp_section(z)
    y=.42*h
    ring=[]
    for x,yy in ((-w/2,y),(w/2,y),(w/2,y+reed_thick),(-w/2,y+reed_thick)):
        ring.append(len(reed_vertices)); reed_vertices.append((x,yy,z))
    reed_rings.append(ring)
reed_faces=[tuple(reversed(reed_rings[0])),tuple(reed_rings[-1])]
for k in range(len(reed_rings)-1):
    for j in range(4): reed_faces.append((reed_rings[k][j],reed_rings[k][(j+1)%4],
                                         reed_rings[k+1][(j+1)%4],reed_rings[k+1][j]))
reed_mesh=bpy.data.meshes.new("CaneReedMesh"); reed_mesh.from_pydata(reed_vertices,[],reed_faces)
reed_mesh.materials.append(reedmat); reed_mesh.update()
reed_obj=bpy.data.objects.new("tapered_amber_cane_reed",reed_mesh)
bpy.context.scene.collection.objects.link(reed_obj)
reed_obj.location=tuple(mp_origin-mp_axis*.002); reed_obj.rotation_euler=mp_rot
v4.part(reed_obj,instrument)
# Two ligature bands bind the reed against the mouthpiece.
for i, (zloc,band_radius) in enumerate(((.025,.0107),(.040,.0115))):
    p = mp_origin + mp_axis*zloc
    v4.torus("reed_ligature_band_%d" % i, band_radius, .00058, loc=tuple(p), rot=mp_rot,
             material=bright, body=instrument)
# Tiny pair of ligature screws facing out from the side.
for i, zloc in enumerate((.025,.040)):
    _,h=mp_section(zloc)
    p = mp_origin + mp_axis*zloc + reed_normal*(.42*h+.00075)
    v4.cylinder("ligature_screw_%d" % i, .0018, .0016, loc=tuple(p), rot=rot_axis(reed_normal),
                segments=20, material=nickel, body=instrument)

# Surface tone holes: the small raised nickel chimneys and black openings are
# distributed around all sides. Holes under moving cups remain correctly seated.
def radial_front(x, z, lift=.001):
    r=body_radius(z)+lift
    ux=max(-.93,min(.93,x/r))
    uy=-math.sqrt(max(.05,1-ux*ux))
    return Vector((ux,uy,0)), r

def add_port(name, x, z, aperture=.0034, rim=.0047, material=nickel):
    u,r=radial_front(x,z,.0000)
    loc=u*r; loc.z=z
    rr = rot_axis(u)
    # Hollow raised riser and a recessed dark throat: the annular foot rests on
    # the blackwood, while the top aligns with the moving pad felt at rest.
    radial_collar(name+"_tone_hole_chimney",loc,u,0,.0026,aperture,rim,material,
                  instrument,segments=48)
    v4.cylinder(name+"_dark_bore",aperture-.00015,.00022,
                loc=tuple(loc+u*.00249),rot=rr,segments=40,bevel=0,
                material=port_black,body=instrument)
    return u,r

# Tone-hole pattern follows the conventional long register/tone-hole layout.
port_points = [
    # Ten front holes are centred directly under the articulated pad cups.
    (-.004,.325), (.009,.438), (-.008,.548), (.009,.665), (-.007,.785),
    (.018,.745), (.006,.842), (.020,.936), (.007,1.035), (.017,1.125),
    # Additional uncovered front tone/register vents between the key stations.
    (.010,.385), (-.010,.490), (.008,.605), (-.012,.710),
    (.013,.895), (-.006,.990), (.018,1.075),
    # Side/rear tone holes remain distributed around the long body.
    (-.024,.345), (.026,.420), (-.025,.500), (.026,.570),
    (-.024,.720), (.025,.790), (-.023,.875), (.024,.950),
    (-.022,1.025), (.020,1.085),
]
for i,(x,z) in enumerate(port_points):
    add_port("tone_hole_%02d"%i,x,z,aperture=.0031 if z>.65 else .0035,
             rim=.0060 if z>.65 else .0062)

# A handful of fixed keys on the far side and side flank enrich the keywork. They
# are attached to the fixed instrument, while the large front linkages remain free.
static_angles_degrees = (18, 162, -12, 198, 42, 138)
static_heights = (.36,.48,.62,.77,.93,1.04)
for i,(adeg,z) in enumerate(zip(static_angles_degrees,static_heights)):
    a=math.radians(adeg); u=Vector((math.cos(a),math.sin(a),0)); rr=body_radius(z)
    ctr=u*(rr+.0012); ctr.z=z
    v4.cylinder("fixed_keycup_%02d"%i,.0084,.0020,loc=tuple(ctr+u*.0012),rot=rot_axis(u),
                segments=40,material=nickel,body=instrument)
    v4.torus("fixed_keycup_rim_%02d"%i,.0082,.00085,loc=tuple(ctr+u*.0022),rot=rot_axis(u),
             material=bright,body=instrument)
    # Short lever and a post base to make this a supported mechanism, not a loose disc.
    q=Vector((-math.sin(a),math.cos(a),0))
    p0=u*(rr+.0020)+Vector((0,0,z-.008)); p1=p0+q*.017+u*.003
    v4.rod("fixed_key_lever_%02d"%i,p0,p1,.0019,material=nickel,body=instrument)
    v4.rod("fixed_key_post_%02d"%i,u*(rr+.0005)+Vector((0,0,z-.008)),
           u*(rr+.006)+Vector((0,0,z-.008)),.0018,material=nickel,body=instrument)
    v4.cylinder("fixed_key_pivot_screw_%02d"%i,.0021,.0010,loc=tuple(u*(rr+.0075)+Vector((0,0,z-.008))),
                rot=rot_axis(u),segments=24,material=bright,body=instrument)
    finger=p1+u*.0025
    v4.cylinder("fixed_key_finger_touch_%02d"%i,.0053,.0014,loc=tuple(finger),
                rot=rot_axis(u),segments=36,material=pearl,body=instrument)
    v4.torus("fixed_key_finger_bezel_%02d"%i,.00525,.00055,
             loc=tuple(finger+u*.0007),rot=rot_axis(u),segments=40,
             ring_segments=10,material=bright,body=instrument)

# Key post / long-rod support geometry. There are 16 real bearing stanchions for
# the articulated rails plus 8 additional fixed posts for subsidiary levers.
shaft_radius=.0032
rail_specs = [
    ("lower_key_rod",(-.030,-.030),.285,.865,[(-.004,.325),(.009,.438),(-.008,.548),(.009,.665),(-.007,.785)]),
    ("upper_key_rod",(.030,-.030),.705,1.165,[(.018,.745),(.006,.842),(.020,.936),(.007,1.035),(.017,1.125)]),
]
# Support points are evenly spaced so each long rod is carried at short intervals.
rail_supports = {}
for nm,(px,py),z0,z1,pads in rail_specs:
    rail_supports[nm]=[z0+.018 + i*(z1-z0-.036)/7 for i in range(8)]
    D=math.hypot(px,py); u=Vector((px/D,py/D,0))
    for i,z in enumerate(rail_supports[nm]):
        r=body_radius(z)
        # Foot washer sits flush on the turned tube; a radial stanchion reaches the
        # inner tangent of the moving rod. Tiny clearance in its journal avoids a
        # visibly fused ring while remaining within physical contact tolerance.
        base=u*(r+.0010); base.z=z
        v4.cylinder(nm+"_post_foot_%02d"%i,.0058,.0020,loc=tuple(base),rot=rot_axis(u),
                    segments=40,material=nickel,body=instrument)
        p0=u*(r+.0017); p0.z=z
        p1=u*(D-shaft_radius); p1.z=z
        v4.rod(nm+"_post_stem_%02d"%i,p0,p1,.0020,segments=20,bevel=.00022,
               material=nickel,body=instrument)
        # A full-height metal post and a dark-lined journal form a visible bearing
        # saddle around the bright axle. The bore clears the moving rod by .15 mm.
        annular_collar(nm+"_bearing_sleeve_%02d"%i,z-.00125,z+.00125,
                       shaft_radius+.00015,shaft_radius+.00205,nickel,
                       loc=(px,py,0),segments=48)
        # A visible slotted screw at the center of the post foot.
        head=u*(r+.0020); head.z=z
        v4.cylinder(nm+"_foot_screw_%02d"%i,.0020,.0008,loc=tuple(head),rot=rot_axis(u),
                    segments=24,material=bright,body=instrument)

# Eight auxiliary fixed posts on side/back surfaces (24 total posts including the
# 16 rail supports). They have short flattened brackets and exposed adjustment caps.
for i,(adeg,z) in enumerate(zip((-5,25,155,205,70,110,-35,215),(.31,.40,.51,.60,.76,.88,1.00,1.105))):
    a=math.radians(adeg); u=Vector((math.cos(a),math.sin(a),0)); r=body_radius(z)
    loc=u*(r+.001); loc.z=z
    v4.cylinder("aux_key_post_base_%02d"%i,.0037,.0018,loc=tuple(loc),rot=rot_axis(u),
                segments=28,material=nickel,body=instrument)
    v4.rod("aux_key_post_stem_%02d"%i,u*(r+.0018)+Vector((0,0,z)),
           u*(r+.009)+Vector((0,0,z)),.00145,material=nickel,body=instrument)
    v4.cylinder("aux_post_cap_%02d"%i,.0020,.0010,loc=tuple(u*(r+.010)+Vector((0,0,z))),
                rot=rot_axis(u),segments=20,material=bright,body=instrument)

# Two longitudinal key assemblies. Each carries its own axle, offset arms, pad
# cups, pressed metal rims, and pearl touchpiece; each rotates on the long rod axis.
keys={}
for nm,(px,py),z0,z1,pads in rail_specs:
    kb=v4.body(nm)
    keys[nm]=kb
    axis_loc=(px,py,(z0+z1)/2)
    v4.rod(nm+"_long_pivot_rod",(px,py,z0),(px,py,z1),shaft_radius,
           segments=24,bevel=.0002,material=bright,body=kb)
    D=math.hypot(px,py)
    for i,z in enumerate(rail_supports[nm]):
        # Polished split collars belong to the rotating axle and sit immediately
        # outside each fixed journal, making the hinge axis legible in close views.
        for side_sign in (-1,1):
            annular_collar(nm+"_axle_split_collar_%02d_%s"%(i,"lo" if side_sign<0 else "hi"),
                           z+side_sign*.00185-.00028,z+side_sign*.00185+.00028,
                           shaft_radius-.00005,shaft_radius+.00065,bright,body=kb,
                           segments=40,loc=(px,py,0))
    # Turned axle collars just above/below the bearing travel.
    for j,z in enumerate((z0+.006,z1-.006)):
        v4.torus(nm+"_axle_end_collar_%d"%j,shaft_radius+.00045,.00055,
                 loc=(px,py,z),material=nickel,body=kb,segments=32,ring_segments=10)
    for k,(target_x,z) in enumerate(pads):
        u,R=radial_front(target_x,z,.0015)
        p=u*R; p.z=z
        # Angled, double-bent arm from the pivot rod to the pad cup. Each centerline
        # ends inside the cup backplate so the part is physically united.
        shaft_p=Vector((px,py,z))
        # Route each arm around the barrel surface. A straight chord would pass
        # through the hollow wooden body; the radial arc follows the outer keywork.
        a0=math.atan2(py,px); a1=math.atan2(u.y,u.x)
        da=(a1-a0+math.pi)%(2*math.pi)-math.pi
        amid=a0+da*.52
        rail_clearance=max(math.hypot(px,py),body_radius(z)+.0060)
        mid=Vector((math.cos(amid)*rail_clearance,math.sin(amid)*rail_clearance,z))
        v4.tube(nm+"_swept_key_arm_%02d"%k,
                [tuple(shaft_p),tuple(mid),tuple(p)],.00205,material=nickel,body=kb,resolution=10)
        # Hollow pad cup has a rolled outer wall around a replaceable felt insert;
        # its wide skirt gives the lower joint the proportions of real keywork.
        cup_center=p
        radial_collar(nm+"_pad_cup_%02d"%k,cup_center,u,.0007,.0030,
                      .0077,.0100,nickel,kb,segments=48)
        v4.torus(nm+"_pad_cup_rolled_edge_%02d"%k,.00955,.00062,
                 loc=tuple(p+u*.0019),rot=rot_axis(u),material=bright,body=kb,
                 segments=48,ring_segments=12)
        # A transverse cup yoke joins the swept key arm to opposite sides of the
        # annular cup skirt; the replaceable pad face seats squarely on its chimney.
        side=Vector((-u.y,u.x,0))
        v4.rod(nm+"_pad_cup_yoke_%02d"%k,p+u*.0004-side*.0090,
               p+u*.0004+side*.0090,.00075,segments=20,bevel=.00010,
               material=nickel,body=kb)
        # Dark felt face is the contact surface at rest and closes the raised bore.
        v4.cylinder(nm+"_felt_pad_%02d"%k,.0078,.0006,
                    loc=tuple(p+u*.0014),rot=rot_axis(u),segments=40,
                    bevel=0,material=padmat,body=kb)
        screw=p+u*.0030
        v4.cylinder(nm+"_cup_screw_%02d"%k,.00155,.00075,
                    loc=tuple(screw),rot=rot_axis(u),segments=20,
                    material=bright,body=kb)
        # A transverse touch arm branches from each lower-joint cup. Its ivory
        # button sits just beyond the shell with a turned nickel bezel; the whole
        # assembly rides with the existing long key rod and its accepted hinge.
        # Lower- and upper-joint fingers alternate sides so every pad has a
        # visible cross-arm and an ivory touchpiece without crowding its neighbour.
        side = Vector((-u.y, u.x, 0))
        side_sign = 1 if k % 2 == 0 else -1
        dz_touch = .003 if side_sign > 0 else -.003
        root = p + u*.0025 + Vector((0,0,dz_touch))
        elbow = p + u*.0060 + side*(side_sign*.0075) + Vector((0,0,dz_touch))
        touch = p + u*.0080 + side*(side_sign*.0140) + Vector((0,0,dz_touch))
        v4.tube(nm+"_transverse_finger_arm_%02d"%k,
                [tuple(root),tuple(elbow),tuple(touch)],.00175,
                material=nickel,body=kb,resolution=8)
        v4.cylinder(nm+"_finger_touch_%02d"%k,.0058,.0018,
                    loc=tuple(touch+u*.0011),rot=rot_axis(u),segments=40,
                    material=pearl,body=kb)
        v4.torus(nm+"_finger_touch_bezel_%02d"%k,.00585,.00060,
                 loc=tuple(touch+u*.0018),rot=rot_axis(u),segments=40,
                 ring_segments=10,material=bright,body=kb)
        # A slim secondary spring/link runs beside the main arm and lands under the cup.
        spring_start=Vector((px,py,z)) + Vector((.003 if px<0 else -.003,0,0))
        spring_end=p + u*.001 + Vector((0,0,.002))
        v4.rod(nm+"_return_link_%02d"%k,spring_start,spring_end,.0010,
               segments=12,bevel=0,material=bright,body=kb)
    # Touchpiece at the lower end of each rail, mounted via a short transverse arm.
    touch_z=z0+.018
    D=math.hypot(px,py); u=Vector((px/D,py/D,0)); side=Vector((-u.y,u.x,0))
    tcenter=Vector((px,py,touch_z)) + side*.020 - u*.002
    v4.rod(nm+"_touchpiece_arm",(px,py,touch_z),tuple(tcenter),.0024,material=nickel,body=kb)
    tnormal=Vector((tcenter.x,tcenter.y,0)).normalized()
    v4.cylinder(nm+"_pearl_touchpiece",.0100,.0028,
                loc=tuple(tcenter+tnormal*.0020),rot=rot_axis(tnormal),segments=40,
                material=pearl,body=kb)
    v4.torus(nm+"_touchpiece_bezel",.0099,.00090,
             loc=tuple(tcenter+tnormal*.0027),rot=rot_axis(tnormal),material=bright,body=kb)

# Adjustable side-mounted floor peg. Its socket sits inside the lower bore, offset
# 18 mm from the body axis, and two small braces seat it into the resonator wall.
# This also leaves the curved bell's central throat unobstructed during travel.
peg_xy=(0.0,-.041)
annular_collar("fixed_floor_peg_socket",.157,.183,.0045,.0100,nickel,loc=(peg_xy[0],peg_xy[1],0))
for side_name,side in (("left",-1),("right",1)):
    v4.rod("peg_socket_brace_"+side_name,
           (side*.0085,-.0315,.171),(side*.0085,-.041,.171),.0014,
           segments=16,bevel=.0001,material=nickel,body=instrument)
peg=v4.body("floor_peg")
v4.rod("floor_peg_steel_shaft",(peg_xy[0],peg_xy[1],.010),(peg_xy[0],peg_xy[1],.190),.0040,
       segments=24,bevel=.00025,material=bright,body=peg)
# Knurled threaded adjuster just below the socket exit.
annular_collar("peg_height_adjuster",.132,.149,.0037,.0078,nickel,body=peg,segments=48,loc=(peg_xy[0],peg_xy[1],0))
annular_collar("peg_adjuster_lower_ridge",.129,.133,.0038,.0085,bright,body=peg,segments=48,loc=(peg_xy[0],peg_xy[1],0))
annular_collar("peg_adjuster_upper_ridge",.148,.152,.0038,.0085,bright,body=peg,segments=48,loc=(peg_xy[0],peg_xy[1],0))
for i in range(28):
    a=2*math.pi*i/28
    # Short diagonal knurl cuts around the adjuster shoulder.
    p0=Vector((peg_xy[0]+math.cos(a)*.0073,peg_xy[1]+math.sin(a)*.0073,.135))
    p1=Vector((peg_xy[0]+math.cos(a+.08)*.0075,peg_xy[1]+math.sin(a+.08)*.0075,.146))
    v4.rod("peg_adjuster_knurl_%02d"%i,p0,p1,.00032,segments=8,bevel=0,
           material=bright,body=peg)
v4.lathe("rubber_floor_tip",[(0,0),(.010,0),(.013,.002),(.013,.006),(.009,.011),(.004,.014),(0,.014)],
         loc=(peg_xy[0],peg_xy[1],0),segments=48,material=black,body=peg)
# A shallow steel ferrule on the bottom foot protects the rubber-to-shaft joint.
annular_collar("peg_foot_ferrule",.010,.017,.0038,.0057,bright,body=peg,segments=40,loc=(peg_xy[0],peg_xy[1],0))

# Small enamel maker plaque, seated against the front of the lower-to-upper joint
# transition. A raised model mark and tiny instrument legend make the bare wood
# between the long rails read as a finished, branded instrument.
badge_y = -.03445
v4.box("engraved_badge_nickel_frame",(.027,.010,.0020),loc=(0,badge_y,.724),
       rot=(math.pi/2,0,0),bevel=.0012,material=bright,body=instrument)
v4.box("engraved_badge_black_enamel",(.0215,.0065,.0008),
       loc=(0,badge_y-.00125,.724),rot=(math.pi/2,0,0),bevel=.00065,
       material=black,body=instrument)
for i,x in enumerate((-.0111,.0111)):
    v4.cylinder("badge_rivet_%d"%i,.0010,.00065,
                loc=(x,badge_y-.0015,.724),rot=(math.pi/2,0,0),segments=20,
                material=nickel,body=instrument)
v4.text("instrument_model_mark", "Bb", .0047, loc=(0,-.03618,.7221),
        rot=(math.pi/2,0,0),extrude_depth=.00018,material=bright,body=instrument,on=None)
v4.text("instrument_name_mark", "BASS CLARINET", .0020,
        loc=(0,-.03618,.7261),rot=(math.pi/2,0,0),extrude_depth=.00012,
        material=bright,body=instrument,on=None)

# A thumb rest on the upper rear side: nickel saddle, black contact pad and two
# screw heads. It is fixed to the upper joint like a real thumb support.
thumb_u=Vector((.78,.625,0)).normalized(); thumb_z=.905; thumb_r=body_radius(thumb_z)
thumb_base=thumb_u*(thumb_r+.001); thumb_base.z=thumb_z
v4.box("thumb_rest_saddle",(.019,.006,.012),loc=tuple(thumb_base),
       rot=(0,0,math.atan2(thumb_u.y,thumb_u.x)),bevel=.002,material=nickel,body=instrument)
v4.box("thumb_rest_black_contact",(.013,.004,.008),
       loc=tuple(thumb_base+thumb_u*.004),rot=(0,0,math.atan2(thumb_u.y,thumb_u.x)),
       bevel=.0015,material=padmat,body=instrument)
for k,dx in enumerate((-.006,.006)):
    p=thumb_base+thumb_u*.006+Vector((dx,0,.006))
    v4.cylinder("thumb_rest_screw_%d"%k,.0017,.0012,loc=tuple(p),rot=rot_axis(thumb_u),
                segments=20,material=bright,body=instrument)

# Joint declarations. Axis directions and pivots follow the physical long rod and
# sliding socket; zero is the polished rest pose with cups seated and peg deployed.
for nm,(px,py),z0,z1,pads in rail_specs:
    v4.joint(nm+"_hinge","revolute",instrument,keys[nm],
             origin=(px,py,(z0+z1)/2),axis=(0,0,1),limits=(-.12,0.0))
v4.joint("floor_peg_slide","prismatic",instrument,peg,
         origin=(peg_xy[0],peg_xy[1],.172),axis=(0,0,1),limits=(0.0,.09))

# Add a neutral studio only when the final check renders; the saved file stays a
# clean asset with exactly one root instrument body.
out=os.path.join(os.getcwd(),"asset.blend")
v4.save(out)
print("saved",out)

# Paired macro views make the rod travel and the felt pads' seating readable at
# instrument scale. The saved asset remains at rest; these are reproducible PNG
# previews generated from the same script and accepted joints.
preview_dir=os.path.join(os.getcwd(),"appearance_renders")
os.makedirs(preview_dir,exist_ok=True)
macro_views=(
    ("lower", .300, .510, (-.065,-.084,.02), (.065,.015,.02), (0.45,-1.0,.18), "lower_key_rod_hinge"),
    ("upper", .820, 1.030, (-.065,-.084,.02), (.065,.015,.02), (0.45,-1.0,.18), "upper_key_rod_hinge"),
)
for label,zlo,zhi,xylo,xyhi,view,joint_name in macro_views:
    lo=Vector((xylo[0],xylo[1],zlo)); hi=Vector((xyhi[0],xyhi[1],zhi))
    v4.pose({joint_name:0.0})
    v4.render(os.path.join(preview_dir,label+"_pads_seated.png"),view=view,
              res=900,samples=32,lo=lo,hi=hi)
    v4.pose({joint_name:-.12})
    v4.render(os.path.join(preview_dir,label+"_pads_open.png"),view=view,
              res=900,samples=32,lo=lo,hi=hi)
v4.rest()
