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

v4.reset()
# Materials
hullmat = v4.plastic('deep_ocean_polymer', (0.075, 0.16, 0.20), roughness=0.34)
blue = v4.painted('blue_anodized_trim', (0.10, 0.25, 0.31), roughness=0.27, coat=0.45)
black = v4.rubber('black_elastomer', (0.018, 0.023, 0.025))
prop_mat = v4.plastic('propeller_graphite', (0.055, 0.065, 0.068), roughness=0.3)
steel = v4.metal('stainless', (0.70, 0.73, 0.74), roughness=0.25)
darkmetal = v4.metal('dark_hard_anodized', (0.11, 0.13, 0.14), roughness=0.32)
white = v4.mat('warm_white_marking', (0.88, 0.90, 0.86), roughness=0.55)
orange = v4.painted('safety_orange', (0.95, 0.24, 0.035), roughness=0.28)
green = v4.emissive('green_status_led', (0.12, 0.95, 0.38), strength=2)
red = v4.emissive('red_status_led', (1.0, 0.035, 0.012), strength=1.8)

hull = v4.body('hull')
# Main pressure tube and rounded motor casing, axis X
battery_tube = v4.cylinder('battery_pressure_tube', 0.094, 0.47, (-0.005, 0, 0.27), rot=(0, math.pi/2, 0), bevel=0.014, material=hullmat, body=hull)
v4.cylinder('aft_motor_pod', 0.103, 0.19, (0.165, 0, 0.27), rot=(0, math.pi/2, 0), bevel=0.018, material=blue, body=hull)
# Circumferential joints and captive fasteners
for x, r in [(-0.245,0.096), (-0.205,0.096), (0.205,0.104)]:
    v4.torus('hull_seam_bead', r, 0.0025, (x,0,0.27), rot=(0,math.pi/2,0), material=darkmetal, body=hull)
for x in (-0.17, 0.16):
    for i in range(8):
        a = 2*math.pi*i/8
        y, z = 0.095*math.cos(a), 0.27+0.095*math.sin(a)
        v4.cylinder('flush_case_screw', 0.0032, 0.0018, (x,y,z), rot=(math.pi/2-a,0,0), segments=16, bevel=0.0003, material=steel, body=hull)
# Aft cooling louvers along pod, with body-integral vent recess look
for i in range(6):
    x = 0.207 + i*0.010
    v4.box('motor_vent_slot', (0.006, 0.009, 0.042), (x,-0.103,0.27), rot=(0,0,0), bevel=0.001, material=darkmetal, body=hull)
# Short open cylindrical propeller duct, axis X, 120 mm long with a 6 mm annular wall.
# The inner radius leaves 8 mm nominal tip clearance to the enlarged rotor.
duct_profile = [(0.128,-0.060),(0.134,-0.060),(0.134,-0.052),(0.134,0.052),
                 (0.134,0.060),(0.128,0.060),(0.128,0.052),(0.128,-0.052),(0.128,-0.060)]
v4.lathe('propeller_guard_duct', duct_profile, loc=(0.315,0,0.27), rot=(0,math.pi/2,0),
         material=blue, body=hull)
# Reinforced inlet and exit lips; subtle dark wear rings on the inner bore.
v4.torus('duct_inlet_bead',0.131,0.0025,(0.255,0,0.27),rot=(0,math.pi/2,0),material=darkmetal,body=hull)
v4.torus('duct_exit_bead',0.131,0.0025,(0.375,0,0.27),rot=(0,math.pi/2,0),material=darkmetal,body=hull)
v4.torus('duct_inner_wear_lip',0.128,0.0015,(0.315,0,0.27),rot=(0,math.pi/2,0),material=darkmetal,body=hull)
# Four short stator vanes tie the fixed duct inlet to the motor pod, forward of the rotor plane.
for i in range(4):
    a=2*math.pi*i/4
    v4.rod('duct_stator_vane',(0.259,0.040*math.cos(a),0.27+0.040*math.sin(a)),
           (0.259,0.133*math.cos(a),0.27+0.133*math.sin(a)),0.0035,material=blue,body=hull)
# Protective intake grill: a light radial wire grid just behind the inlet lip.
for r in (0.045,0.085,0.127):
    v4.torus('intake_grill_ring',r,0.0018,(0.267,0,0.27),rot=(0,math.pi/2,0),material=darkmetal,body=hull)
for i in range(12):
    a=2*math.pi*i/12
    v4.rod('intake_grill_spoke',(0.267,0.025*math.cos(a),0.27+0.025*math.sin(a)),
           (0.267,0.129*math.cos(a),0.27+0.129*math.sin(a)),0.0018,material=darkmetal,body=hull)
# Nose receiver collar on the hull; cap meets this at the shoulder
v4.cylinder('battery_receiver_collar', 0.099, 0.025, (-0.247,0,0.27), rot=(0,math.pi/2,0), bevel=0.003, material=darkmetal, body=hull)
# Underside skids
for y in (-0.052,0.052):
    v4.box('keel_skid', (0.36,0.018,0.012), (0.015,y,0.168), bevel=0.005, material=black, body=hull)
    for x in (-0.12,0.015,0.15):
        v4.box('skid_saddle_standoff',(0.028,0.022,0.024),(x,y,0.184),bevel=0.004,material=darkmetal,body=hull)
        v4.box('skid_saddle_foot',(0.038,0.026,0.004),(x,y,0.171),bevel=0.001,material=steel,body=hull)
# Raised controls deck and markings, small status display atop forward body
control_deck = v4.box('control_deck', (0.17,0.12,0.012), (-0.035,0,0.371), bevel=0.012, material=darkmetal, body=hull)
v4.box('status_window', (0.052,0.026,0.003), (-0.084,-0.002,0.379), bevel=0.003, material=black, body=hull)
for i,m in enumerate((green,green,red)):
    v4.sphere('status_lamp', 0.004, (-0.101+i*0.017,-0.002,0.382), material=m, body=hull)
v4.text('hull_brand_mark','AQUA  /  DPV',0.010,(-0.015,-0.094,0.285),rot=(math.pi/2,0,0),material=white,body=hull,on=battery_tube)
v4.text('control_speed_label','SPEED',0.007,(-0.035,0.050,0.377),material=white,body=hull,on=control_deck)
# Hull labels and orange safety bands
v4.torus('aft_safety_band', 0.105, 0.003, (0.19,0,0.27), rot=(0,math.pi/2,0), material=orange, body=hull)
# Side detail buttons / latch screws
for sy in (-1,1):
    v4.cylinder('service_bolt', 0.009, 0.003, (0.05,sy*0.096,0.27), rot=(math.pi/2,0,0), material=darkmetal, body=hull)
    v4.cylinder('bolt_center', 0.003, 0.0035, (0.05,sy*0.098,0.27), rot=(math.pi/2,0,0), segments=16, material=steel, body=hull)

# Screw-on battery nose, lathed along X
nose = v4.body('nose_cone')
v4.lathe('battery_nose_shell', [(0,0),(0.083,0),(0.094,0.015),(0.092,0.045),(0.085,0.10),(0.066,0.145),(0.038,0.174),(0,0.185)], loc=(-0.247,0,0.27), rot=(0,-math.pi/2,0), material=hullmat, body=nose)
v4.torus('nose_grip_collar', 0.094, 0.006, (-0.262,0,0.27), rot=(0,math.pi/2,0), material=darkmetal, body=nose)
for x in (-0.276,-0.284):
    v4.torus('nose_thread_groove',0.091,0.0016,(x,0,0.27),rot=(0,math.pi/2,0),material=steel,body=nose)
for i in range(18):
    a=2*math.pi*i/18
    v4.rod('nose_knurl', (-0.268,0.094*math.cos(a),0.27+0.094*math.sin(a)), (-0.257,0.094*math.cos(a),0.27+0.094*math.sin(a)), 0.0014, material=steel, body=nose)
v4.joint('nose_thread','continuous',hull,nose,origin=(-0.247,0,0.27),axis=(-1,0,0))

# Rotor body with three sculpted, twisted airfoil blades and a rounded spinner fairing.
rotor = v4.body('rotor')
v4.cylinder('rotor_hub', 0.036, 0.060, (0.340,0,0.27), rot=(0,math.pi/2,0), bevel=0.006, material=prop_mat, body=rotor)
v4.lathe('hub_fairing_cap',[(0,0),(0.025,0),(0.026,0.004),(0.024,0.010),(0.018,0.019),(0.010,0.025),(0,0.028)],
         loc=(0.37,0,0.27),rot=(0,math.pi/2,0),material=steel,body=rotor)
def make_blade(name, angle):
    # A swept blade surface with chordwise camber and spanwise twist. X is the prop axis.
    radii=[0.028,0.045,0.065,0.085,0.105,0.120]
    leads=[-0.30,-0.29,-0.27,-0.24,-0.21,-0.19]
    trails=[0.24,0.24,0.23,0.21,0.18,0.14]
    chord_u=[0.0,0.25,0.5,0.75,1.0]
    nr,nc=len(radii),len(chord_u)
    verts=[]
    for layer in (-1,1):
        for ir,r in enumerate(radii):
            span=(r-radii[0])/(radii[-1]-radii[0])
            for u in chord_u:
                theta=angle+leads[ir]+u*(trails[ir]-leads[ir])
                chord_camber=0.004*math.sin(math.pi*u)
                axial_pitch=0.018*(u-0.5) + 0.016*span
                thickness=0.0045*math.sin(math.pi*u)*(0.82+0.18*span)
                x=0.324+axial_pitch+chord_camber+layer*thickness*0.5
                verts.append((x,r*math.cos(theta),0.27+r*math.sin(theta)))
    def idx(layer,ir,iu): return layer*nr*nc+ir*nc+iu
    faces=[]
    for ir in range(nr-1):
        for iu in range(nc-1):
            faces.append((idx(0,ir,iu),idx(0,ir+1,iu),idx(0,ir+1,iu+1),idx(0,ir,iu+1)))
            faces.append((idx(1,ir,iu+1),idx(1,ir+1,iu+1),idx(1,ir+1,iu),idx(1,ir,iu)))
    # Close root, tip, leading edge and trailing edge.
    for ir in range(nr-1):
        faces.append((idx(0,ir,0),idx(1,ir,0),idx(1,ir+1,0),idx(0,ir+1,0)))
        faces.append((idx(0,ir+1,nc-1),idx(1,ir+1,nc-1),idx(1,ir,nc-1),idx(0,ir,nc-1)))
    for iu in range(nc-1):
        faces.append((idx(0,0,iu+1),idx(1,0,iu+1),idx(1,0,iu),idx(0,0,iu)))
        faces.append((idx(0,nr-1,iu),idx(1,nr-1,iu),idx(1,nr-1,iu+1),idx(0,nr-1,iu+1)))
    me=bpy.data.meshes.new(name); me.from_pydata(verts,[],faces); me.update()
    bm=bmesh.new(); bm.from_mesh(me); bmesh.ops.recalc_face_normals(bm,faces=bm.faces); bm.to_mesh(me); bm.free()
    ob=bpy.data.objects.new(name,me); bpy.context.scene.collection.objects.link(ob)
    ob.data.materials.append(prop_mat); v4._finish(ob,rotor,prop_mat,0.0015,segments=2,smooth=True)
for i in range(3): make_blade('twisted_airfoil_propeller_blade',2*math.pi*i/3)
v4.rod('rotor_drive_shaft',(0.255,0,0.27),(0.311,0,0.27),0.009,material=steel,body=rotor)
v4.joint('prop_axle','continuous',hull,rotor,origin=(0.255,0,0.27),axis=(1,0,0))

# Fixed molded top handle yoke and twin fore-aft grips
for sy in (-1,1):
    for x in (-0.075,0.045):
        v4.rod('handle_stalk', (x,sy*0.03,0.35), (x,sy*0.105,0.505), 0.010, material=blue, body=hull)
    v4.rod('rubber_handgrip', (-0.105,sy*0.105,0.50), (0.075,sy*0.105,0.50), 0.015, material=black, body=hull)


# Two independent squeeze levers beneath the grips
triggers=[]
for side, sy in [('left',-1),('right',1)]:
    trig=v4.body('trigger_'+side); triggers.append(trig)
    px,py,pz=-0.06,sy*0.105,0.477
    v4.cylinder('trigger_hinge_boss',0.014,0.018,(px,py,pz),rot=(math.pi/2,0,0),material=darkmetal,body=trig)
    v4.cylinder('trigger_pin_head',0.006,0.021,(px,py,pz),rot=(math.pi/2,0,0),segments=24,material=steel,body=trig)
    # Curved finger blade sweeps beneath the grip; its upper edge follows the bar.
    outline=[(-0.071,0.464),(-0.065,0.477),(-0.042,0.475),(-0.015,0.470),
             (0.012,0.465),(0.040,0.462),(0.060,0.463),(0.063,0.451),
             (0.048,0.446),(0.020,0.445),(-0.010,0.449),(-0.040,0.456),(-0.067,0.455)]
    verts=[]
    for yy in (py-0.008,py+0.008):
        verts.extend([(x,yy,z) for x,z in outline])
    n=len(outline)
    faces=[tuple(range(n-1,-1,-1)),tuple(range(n,2*n))]
    for j in range(n): faces.append((j,(j+1)%n,(j+1)%n+n,j+n))
    me=bpy.data.meshes.new('curved_trigger_blade'); me.from_pydata(verts,[],faces); me.update()
    bm=bmesh.new(); bm.from_mesh(me); bmesh.ops.recalc_face_normals(bm,faces=bm.faces); bm.to_mesh(me); bm.free()
    blade=bpy.data.objects.new('curved_trigger_blade',me); bpy.context.scene.collection.objects.link(blade)
    v4._finish(blade,trig,darkmetal,0.002,segments=3,smooth=True)
    v4.joint('trigger_'+side,'revolute',hull,trig,origin=(px,py,pz),axis=(0,1,0),limits=(-0.10,0.48))

# Continuous speed dial seated in the deck
selector=v4.body('speed_selector')
v4.torus('selector_recess_rim',0.033,0.0035,(-0.035,0,0.381),material=steel,body=hull)
v4.cylinder('selector_bezel',0.033,0.008,(-0.035,0,0.382),material=darkmetal,bevel=0.002,body=selector)
v4.cylinder('selector_knob',0.026,0.018,(-0.035,0,0.395),material=black,bevel=0.004,body=selector)
v4.box('selector_pointer', (0.004,0.015,0.002),(-0.035,-0.006,0.405),bevel=0.001,material=orange,body=selector)
for i in range(7):
    a=math.radians(-135+i*45)
    x,y=-0.035+0.041*math.cos(a),0.041*math.sin(a)
    v4.box('selector_detent_mark',(0.008,0.002,0.001),(x,y,0.3785),rot=(0,0,a),bevel=0.0004,material=white,body=hull)
for i,label in enumerate(('1','2','3')):
    a=math.radians(-90+i*45)
    tx,ty=-0.035+0.050*math.cos(a),0.050*math.sin(a)
    v4.text('selector_speed_number_'+label,label,0.006,(tx,ty,0.377),material=white,body=hull,on=control_deck)
v4.joint('selector_turn','continuous',hull,selector,origin=(-0.035,0,0.382),axis=(0,0,1))

# Pivoting accessory mount clamp, a compact U-frame above aft motor pod
clamp=v4.body('mount_clamp')
pivot=(0.105,0,0.385)
# Hinge barrel and two arms, with crown crossbar as a real accessory saddle
v4.cylinder('clamp_hinge_barrel',0.012,0.19,pivot,rot=(math.pi/2,0,0),material=steel,body=clamp)
for sy in (-1,1):
    v4.rod('clamp_arm',(0.105,sy*0.082,0.39),(0.155,sy*0.082,0.475),0.009,material=darkmetal,body=clamp)
v4.rod('clamp_saddle',(0.155,-0.082,0.475),(0.155,0.082,0.475),0.012,material=black,body=clamp)
v4.box('clamp_latch_tab',(0.034,0.028,0.009),(0.155,0,0.487),bevel=0.003,material=orange,body=clamp)
v4.joint('clamp_pivot','revolute',hull,clamp,origin=pivot,axis=(0,1,0),limits=(-0.12,0.82))

# Warning stripe on duct, integrated narrow mark
# Warning stripe on duct outer side, integrated narrow mark
v4.box('duct_warning_marker',(0.048,0.004,0.012),(0.315,-0.137,0.27),bevel=0.002,material=orange,body=hull)

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