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

v4.reset()
# Palette: classic black grenadilla with nickel silver keywork.
wood = v4.wood('Grenadilla ebony', light=(0.10,0.095,0.083), dark=(0.025,0.024,0.022), grain_scale=7, roughness=0.27, coat=0.55)
wood2 = v4.wood('Grenadilla end grain', light=(0.13,0.12,0.105), dark=(0.035,0.032,0.028), grain_scale=10, roughness=0.3, coat=0.5)
ni = v4.metal('Polished nickel silver', color=(0.78,0.80,0.82), roughness=0.24, brushed=True)
steel = v4.metal('Darkened steel', color=(0.34,0.37,0.39), roughness=0.3, brushed=False)
ivory = v4.plastic('Cream key ring', (0.82,0.76,0.62), roughness=0.3, texture=0.08)
padmat = v4.rubber('Buff leather pads', (0.48,0.36,0.22), roughness=0.82)
black = v4.plastic('Mouthpiece ebonite', (0.018,0.018,0.017), roughness=0.24, texture=0.05)
cane = v4.wood('Reed cane', light=(0.72,0.50,0.27), dark=(0.40,0.23,0.10), grain_scale=15, roughness=0.48, coat=0.12)

body = v4.body('body')
# Turned grenadilla body; the lower bore feeds a separate upturned bell elbow.
v4.lathe('lower_joint', [(0,.255),(.035,.255),(.0355,.28),(.036,.30),(.0348,.52),(.0348,.58),(.036,.60),(.036,.615),(.0345,.63),(.0345,.80),(.035,.82),(.036,.84),(.0345,1.015),(.0345,1.12),(.036,1.14),(.036,1.16),(.034,1.18),(.034,1.305),(.032,1.325),(0,1.325)], material=wood, body=body)
# Curved lower elbow descends from the bore, sweeps to the player's right, then rises into an open bell.
bell_path=[(0,0,.27),(0,0,.225),(0,0,.18),(.012,0,.14),(.040,0,.115),(.075,0,.115),(.058,0,.116),(.0763,0,.1271)]
v4.tube('grenadilla_bell_elbow',bell_path,.027,material=wood2,body=body,resolution=18)
bell_axis_angle=math.atan2(.86,.51)
bell_axis=(math.sin(bell_axis_angle),0,math.cos(bell_axis_angle))
bell_origin=(.115,0,.15)
bell_profile=[(.028,-.045),(.034,-.045),(.043,-.026),(.060,.005),(.075,.035),(.081,.058),(.080,.065),(.073,.064),(.064,.043),(.052,.012),(.038,-.023),(.026,-.045)]
v4.lathe('upturned_bell_flare',bell_profile,loc=bell_origin,rot=(0,bell_axis_angle,0),material=wood2,body=body)
bell_mouth=(bell_origin[0]+bell_axis[0]*.061,0,bell_origin[2]+bell_axis[2]*.061)
v4.torus('bell_rolled_rim',.077,.003,loc=bell_mouth,rot=(0,bell_axis_angle,0),material=ni,body=body)
bell_throat=(bell_origin[0]-bell_axis[0]*.045,0,bell_origin[2]-bell_axis[2]*.045)
v4.torus('bell_throat_band',.032,.002,loc=bell_throat,rot=(0,bell_axis_angle,0),material=ni,body=body)
# Joining rings and decorative tenon ferrules.
for i,z in enumerate((.265,.585,.612,.825,.848,1.125,1.15,1.305,1.323)):
    v4.torus(f'tenon_ring_{i}', .035 if z>.4 else .036, .0021, loc=(0,0,z), material=ni, body=body)
for i,z in enumerate((.265,.592,.842,1.142,1.315)):
    v4.torus(f'ivory_joint_pinstripe_{i}', .0355 if z>.4 else .0365, .00065, loc=(0,0,z+.004), material=ivory, body=body)
# Lower-joint foot socket and thumb-rest assembly.
v4.cylinder('foot_socket', .012, .042, (-.045,.018,.245), material=ni, body=body)
v4.torus('foot_socket_bead', .0215,.002, loc=(-.045,.018,.228), material=steel, body=body)
# thumb rest: boss touching shell and curved saddle plate on rear side
v4.cylinder('thumb_rest_boss', .009,.018, (0,.036,.97), rot=(math.pi/2,0,0), material=ni, body=body)
v4.box('thumb_rest_saddle',(0.035,.010,.052),(0,.048,.982),rot=(0,0,math.radians(-8)),bevel=.006,material=ni,body=body)
v4.box('thumb_rest_black_insert',(0.024,.003,.036),(0,.054,.982),rot=(0,0,math.radians(-8)),bevel=.004,material=black,body=body)

# Raised tone-hole chimneys and staggered fixed post rails around the long body.
tone_z = [.335,.385,.438,.493,.55,.635,.69,.745,.80,.875,.93,.985,1.045,1.095,1.18,1.23,1.27]
for i,z in enumerate(tone_z):
    sx = -1 if i%2==0 else 1
    x = sx*(.021 if i%3 else .026)
    # chimney axis points toward player; tops touch the body contour
    v4.cylinder(f'tone_hole_chimney_{i:02}', .0065 if i%3 else .008, .012, (x,-.025,z), rot=(math.pi/2,0,0), material=wood2, body=body)
    v4.cylinder(f'tone_hole_rim_{i:02}', .008 if i%3 else .0095, .002, (x,-.033,z), rot=(math.pi/2,0,0), material=ni, body=body)
# 24 posts, screw towers and fixed short key arms make a dense Boehm mechanism.
for i in range(24):
    z=.325+i*.039
    side = -1 if i%2==0 else 1
    x=side*(.027 if i%4<2 else .018)
    y=-.028
    v4.cylinder(f'post_base_{i:02}',.0048,.016,(x,y,z),rot=(math.pi/2,0,0),material=ni,body=body)
    v4.cylinder(f'post_stem_{i:02}',.0024,.014,(x,y-.013,z),rot=(math.pi/2,0,0),material=steel,body=body)
    v4.cylinder(f'post_screw_{i:02}',.003,.002,(x,y-.023,z),rot=(math.pi/2,0,0),segments=16,material=ni,body=body)
    # fixed short touch/bridge bars in two alternating tracks
    if i%3==0:
        x2=-x*.56
        v4.rod(f'fixed_key_bar_{i:02}',(x,y-.024,z),(x2,y-.024,z+.019),.0017,material=ni,body=body)
        v4.sphere(f'fixed_touch_{i:02}',.006,(x2,y-.026,z+.019),material=ni,body=body)
# Larger raised key cups and connecting levers make the Boehm keywork readable at full-instrument scale.
for i,z in enumerate((.36,.445,.52,.605,.69,.775,.86,.945,1.03,1.115,1.20,1.275)):
    side=-1 if i%2==0 else 1
    x=side*(.021 if i%3 else .027)
    r=.011 if i%4 else .013
    # Long mounting arm reaches from an attached post to the tone-hole cup.
    v4.rod(f'cup_mount_arm_{i:02}',(x*.68,-.026,z+.010),(x,-.046,z),.0022,material=ni,body=body)
    v4.cylinder(f'fixed_key_cup_{i:02}',r,.004,(x,-.048,z),rot=(math.pi/2,0,0),material=ni,body=body)
    v4.torus(f'fixed_cup_rim_{i:02}',r*.84,.0015,loc=(x,-.051,z),rot=(math.pi/2,0,0),material=steel,body=body)
    v4.cylinder(f'fixed_cup_pad_{i:02}',r*.65,.0018,(x,-.051,z),rot=(math.pi/2,0,0),material=padmat,body=body)
    # Small actuator tongue and touch at the outside edge, like a conventional long key lever.
    tx=x+side*.026
    v4.rod(f'cup_touch_arm_{i:02}',(x,-.047,z),(tx,-.047,z+.018),.0018,material=ni,body=body)
    v4.sphere(f'cup_touch_{i:02}',.0055,(tx,-.047,z+.018),material=ni,body=body)

# Swan-neck crook, socket and tenon ferrules, all fixed to the wood body.
crook_pts=[(0.0,0,1.29),(0,0,1.34),(0,0,1.39),(.006,0,1.435),(.024,0,1.468),(.055,0,1.482),(.083,0,1.475),(.104,0,1.45),(.115,0,1.414),(.119,0,1.385)]
v4.tube('silver_neck_crook',crook_pts,.009,material=ni,body=body,resolution=16)
v4.torus('crook_tenon_band',.010,.002,loc=(0,0,1.332),material=steel,body=body)
v4.torus('crook_socket_bead',.010,.0017,loc=(.119,0,1.385),rot=(0,math.pi/2,0),material=ni,body=body)
v4.lathe('neck_socket',[(0,-.018),(.010,-.018),(.011,-.014),(.011,.014),(.010,.018),(0,.018)],loc=(.119,0,1.385),rot=(0,math.pi/2,0),material=ni,body=body)
# Ebonite mouthpiece and visible tapered cane reed, mounted to crook outlet. Outlet angles slightly down.
v4.lathe('mouthpiece',[(0,0),(.009,0),(.010,.018),(.008,.045),(.006,.072),(.004,.081),(0,.081)],loc=(.119,0,1.385),rot=(math.pi,0,0),material=black,body=body)
# ligature around lower mouthpiece and two tiny fastening screws
v4.torus('mouthpiece_ligature',.009,.0015,loc=(.119,0,1.405),rot=(math.pi,0,0),material=ni,body=body)
v4.cylinder('ligature_screw',.0023,.004,(.130,0,1.405),rot=(0,math.pi/2,0),segments=16,material=steel,body=body)
# reed lies on player-facing side (negative Y), narrow triangular cane blade
v4.extrude('cane_reed',[(.119-.005,0),(.119+.005,0),(.119+.001,0.050),(.119-.001,0.050)],.0012,loc=(0,-.008,1.395),rot=(0,0,0),bevel=.0004,material=cane,body=body)

# Adjustable-style floor peg shown extended and clamped to the lower joint; the
# reference allows this detail to be fixed, so it is part of the root assembly.
v4.cylinder('floor_peg_socket',.012,.042,(-.045,.018,.245),material=ni,body=body)
v4.torus('floor_peg_socket_bead',.0115,.0017,loc=(-.045,.018,.228),material=steel,body=body)
v4.lathe('floor_peg_steel_rod',[(0,.012),(.004,.012),(.004,.245),(0,.245)],loc=(-.045,.018,0),material=steel,body=body)
v4.lathe('floor_peg_rubber_tip',[(0,0),(.005,0),(.0055,.006),(.0045,.013),(0,.013)],loc=(-.045,.018,0),material=black,body=body)

# Long articulated linkage: satin-silver rod and lever arms riding just clear of shell.
# The long operating axle spins on its own vertical axis in three fixed bearing saddles.
rod_x,rod_y=-.008,-.038
for i,z in enumerate((.43,.82,1.18)):
    v4.torus(f'long_axle_bearing_{i}',.00335,.0009,loc=(rod_x,rod_y,z),material=ni,body=body)
    # Short stay reaches from the bearing's body-facing edge into the wood shell.
    v4.rod(f'long_axle_bearing_stay_{i}',(rod_x,rod_y+.0033,z),(rod_x,rod_y+.006,z),.0012,material=ni,body=body)
key=v4.body('key_rod')
v4.rod('long_trill_rod',(rod_x,rod_y,.405),(rod_x,rod_y,1.205),.0022,material=ni,body=key)
# Radial crank arms orbit the vertical axle and carry two pad cups toward/away from their seats.
for z,dx in ((.48,.026),(1.13,.026)):
    cup_x=rod_x+dx
    v4.torus(f'cup_outer_rim_{z:.2f}',.012,.002,loc=(cup_x,rod_y,z),rot=(math.pi/2,0,0),material=ni,body=key)
    v4.rod(f'key_cup_arm_{z:.2f}',(rod_x,rod_y,z),(cup_x,rod_y,z),.0028,material=ni,body=key)
    v4.rod(f'cup_neck_{z:.2f}',(cup_x,rod_y,z),(cup_x,rod_y-.002,z),.003,material=ni,body=key)
    v4.rod(f'pad_hinge_ear_{z:.2f}',(cup_x+.014,rod_y,z),(cup_x-.022,-.060,z),.0024,material=ni,body=key)
# spring wire and articulated adjustment screw details on the moving assembly
v4.tube('key_return_spring', [(rod_x,rod_y-.002,.74),(rod_x+.012,rod_y-.002,.74),(rod_x+.018,rod_y-.002,.76),(rod_x+.018,rod_y-.002,.79),(rod_x+.006,rod_y-.002,.80)], .0008, material=steel, body=key)
v4.cylinder('key_adjuster',.0028,.006,(rod_x,rod_y-.004,.67),rot=(math.pi/2,0,0),material=steel,body=key)
v4.joint('long_key_hinge','revolute',body,key,origin=(rod_x,rod_y,.82),axis=(0,0,1),limits=(0,.18))
# Separate leather pads and cups pivot at each key cup; hinge axes parallel to body face.
for nm,z,dx in [('low',.48,.026),('high',1.13,.026)]:
    pad=v4.body('pad_'+nm)
    x=rod_x+dx
    # brass-toned cushion backing and leather face, at the end of cup arm
    v4.cylinder(f'{nm}_pad_backing',.011,.004,(x,-.037,z),rot=(math.pi/2,0,0),material=ni,body=pad)
    v4.cylinder(f'{nm}_leather_face',.009,.003,(x,-.041,z),rot=(math.pi/2,0,0),material=padmat,body=pad)
    v4.torus(f'{nm}_pad_edge',.0095,.001,loc=(x,-.042,z),rot=(math.pi/2,0,0),material=ivory,body=pad)
    # A real pivot pin and offset crank bridge the movable pad cup to its key ring.
    v4.rod(f'{nm}_pad_hinge_pin',(x-.022,-.060,z),(x+.014,-.060,z),.0018,material=steel,body=pad)
    v4.rod(f'{nm}_pad_crank',(x+.014,-.060,z),(x,-.037,z),.0024,material=ni,body=pad)
    v4.joint(f'{nm}_pad_hinge','revolute',key,pad,origin=(x-.022,-.060,z),axis=(1,0,0),limits=(-.10,.10))

# Camera and studio setup; pure generated backdrop, no visible floor geometry.
v4.pose({})
# Create a clean portrait studio render setup.
import bpy
scene=bpy.context.scene
scene.render.engine='CYCLES'
scene.cycles.samples=48
scene.render.resolution_x=1100
scene.render.resolution_y=1500
scene.render.resolution_percentage=100
scene.world=bpy.data.worlds.new('Studio World')
scene.world.color=(0.055,0.055,0.055)
# ground plane is studio-only and not part of asset
bpy.ops.mesh.primitive_plane_add(size=200, location=(0,0,-.006))
floor=bpy.context.object; floor.name='StudioFloor'; floor.data.materials.append(v4.mat('Studio charcoal',(0.065,0.075,0.085),roughness=.72))
# studio item should not be articulated asset collection
for c in list(floor.users_collection): c.objects.unlink(floor)
studio=bpy.data.collections.get('Studio') or bpy.data.collections.new('Studio')
scene.collection.children.link(studio); studio.objects.link(floor)
# camera from front-left and elevated enough to show bell opening and mouthpiece
bpy.ops.object.camera_add(location=(2.15,-3.65,1.08))
cam=bpy.context.object; cam.name='Camera'; cam.data.lens=58
cam.rotation_euler=(Vector((0,0,0.76))-cam.location).to_track_quat('-Z','Y').to_euler()
for c in list(cam.users_collection): c.objects.unlink(cam)
studio.objects.link(cam); scene.camera=cam
# lights
for name,loc,power,size,color in [('Key',(1.4,-2.5,2.4),850,1.35,(0.82,0.9,1.0)),('Fill',(-1.6,-1.4,1.1),600,1.1,(1.0,.78,.56)),('Rim',(0.5,1.2,1.8),1000,1.0,(.66,.8,1.0))]:
    bpy.ops.object.light_add(type='AREA',location=loc)
    l=bpy.context.object;l.name='Studio_'+name;l.data.energy=power;l.data.shape='DISK';l.data.size=size;l.data.color=color
    l.rotation_euler=(Vector((0,0,.78))-l.location).to_track_quat('-Z','Y').to_euler()
    for c in list(l.users_collection): c.objects.unlink(l)
    studio.objects.link(l)
scene.render.image_settings.file_format='PNG'
scene.render.film_transparent=False
scene.view_settings.view_transform='AgX'
scene.camera.data.dof.use_dof=False
v4.save(os.path.join(os.getcwd(),'asset.blend'))
print('saved asset.blend')
