"""Detailed articulated electric flapping-wing aerial robot."""
import math, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4

v4.reset()
# Product palette
shell = v4.painted("Graphite polymer", (0.105, 0.13, 0.15), roughness=0.32)
charcoal = v4.plastic("Dark carbon", (0.055, 0.07, 0.08), roughness=0.3)
orange = v4.painted("Safety orange", (0.95, 0.25, 0.035), roughness=0.29)
steel = v4.metal("Anodized aluminum", (0.68, 0.72, 0.74), roughness=0.26, brushed=True)
blacksteel = v4.metal("Blackened steel", (0.18, 0.21, 0.22), roughness=0.3, brushed=False)
rubber = v4.rubber("Grip rubber")
film = v4.fabric("Amber wing film", (0.72, 0.42, 0.17), weave_scale=220)
white = v4.mat("Ivory label", (0.91, 0.91, 0.83), roughness=0.55)
lens = v4.glass("Smoke glass", color=(0.12, 0.24, 0.28), roughness=0.16)
led = v4.emissive("Status green", (0.15, 0.9, 0.35), strength=2.0)

# A lightly transmissive orange polymer skin separate from the carbon wing frame.
film_bsdf = film.node_tree.nodes.get("Principled BSDF")
if film_bsdf:
    film_bsdf.inputs["Roughness"].default_value = 0.34
    film_bsdf.inputs["Alpha"].default_value = 0.68
film.surface_render_method = "DITHERED"
# A shader-level blend keeps the thin wing film see-through in both render engines.
if film_bsdf:
    nt = film.node_tree
    output = next(n for n in nt.nodes if n.type == "OUTPUT_MATERIAL")
    for link in list(nt.links):
        if link.to_node == output and link.to_socket.name == "Surface": nt.links.remove(link)
    clear = nt.nodes.new("ShaderNodeBsdfTransparent")
    blend = nt.nodes.new("ShaderNodeMixShader")
    blend.inputs[0].default_value = 0.58
    nt.links.new(clear.outputs[0], blend.inputs[1])
    nt.links.new(film_bsdf.outputs[0], blend.inputs[2])
    nt.links.new(blend.outputs[0], output.inputs["Surface"])

def loft_shell(name, sections, body, material):
    """Closed longitudinal fuselage loft. Sections are y, half-width, half-height, z-center."""
    import bpy
    verts, faces = [], []
    n = 32
    for y, rx, rz, zc in sections:
        for i in range(n):
            a = 2 * math.pi * i / n
            verts.append((rx * math.cos(a), y, zc + rz * math.sin(a)))
    faces.append(tuple(reversed(range(n))))
    for k in range(len(sections)-1):
        for i in range(n):
            a = k*n+i; b = k*n+(i+1)%n
            faces.append((a,a+n,b+n,b))
    faces.append(tuple((len(sections)-1)*n+i for i in range(n)))
    mesh = bpy.data.meshes.new(name+"Mesh")
    mesh.from_pydata(verts, [], faces); mesh.update()
    obj = bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.children.get("Asset").objects.link(obj)
    for poly in mesh.polygons: poly.use_smooth = True
    v4.part(obj, body)
    mesh.materials.append(material)
    return obj

def cambered_membrane(name, sx, body):
    """Thin closed membrane with a shallow camber and a flexible-looking trailing edge."""
    import bpy, bmesh
    stations = [(0.0,-.027,.083),(.22,-.022,.072),(.48,-.015,.060),(.74,-.009,.047),(1.0,-.002,.036)]
    chord_steps = (0.0,.25,.5,.75,1.0)
    top, bottom = [], []
    for t, y_le, y_te in stations:
        x = sx*(.165 + .261*t)
        for u in chord_steps:
            y = y_le*(1-u)+y_te*u
            camber = .0036*math.sin(math.pi*u)*(1-.38*t) + .0009*u*u*(.4+t)
            z = z_h + .0005 + camber
            top.append((x,y,z)); bottom.append((x,y,z-.0006))
    nst, nch = len(stations), len(chord_steps)
    n = nst*nch
    verts = top + bottom
    faces = []
    for i in range(nst-1):
        for j in range(nch-1):
            a=i*nch+j; b=a+1; c=a+nch+1; d=a+nch
            faces.append((a,b,c,d))
            faces.append((n+d,n+c,n+b,n+a))
    boundary = list(range(nch))
    boundary += [i*nch+nch-1 for i in range(1,nst)]
    boundary += [ (nst-1)*nch+j for j in range(nch-2,-1,-1)]
    boundary += [i*nch for i in range(nst-2,0,-1)]
    for k,a in enumerate(boundary):
        b=boundary[(k+1)%len(boundary)]
        faces.append((a,b,n+b,n+a))
    mesh=bpy.data.meshes.new(name+"Mesh")
    mesh.from_pydata(verts,[],faces); mesh.update()
    bm=bmesh.new(); bm.from_mesh(mesh); bmesh.ops.recalc_face_normals(bm,faces=bm.faces); bm.to_mesh(mesh); bm.free()
    obj=bpy.data.objects.new(name,mesh)
    bpy.context.scene.collection.children.get("Asset").objects.link(obj)
    v4.part(obj,body); mesh.materials.append(film)
    return obj

# Coordinates: nose -Y, wings +/-X, Z up. Hinge centerline at z=.285.
z_h = .285
root_x = .165
root = v4.body("gearbox_housing")
# Streamlined shell tapers from nose to boom instead of ending in a blunt box.
loft_shell("molded_fuselage", [(-.112,.026,.023,.246),(-.088,.048,.039,.246),(-.040,.064,.050,.246),
           (.035,.063,.047,.245),(.090,.052,.037,.244),(.135,.034,.025,.245),(.166,.008,.008,.248)], root, shell)
v4.lathe("nose_cone", [(0,0),(.008,.003),(.020,.014),(.031,.032),(.034,.046),(.030,.052),(0,.053)],
         loc=(0,-.151,.246), rot=(-math.pi/2,0,0), material=shell, body=root)
v4.box("gearbox_cover", (0.148, 0.105, 0.077), (0, -0.052, 0.267), bevel=0.022, material=charcoal, body=root)
# Orange seam around the gearbox face.
v4.box("gearbox_orange_brow", (0.112, 0.008, 0.012), (0, -0.106, 0.295), bevel=0.004, material=orange, body=root)
# Motor can set transverse in the rear of the gearbox pod, with end bell and slots.
v4.cylinder("motor_can", 0.028, 0.074, (0, 0.094, 0.278), rot=(math.pi/2, 0, 0), material=steel, body=root)
v4.cylinder("motor_endbell", 0.024, 0.006, (0, 0.134, 0.278), rot=(math.pi/2, 0, 0), material=blacksteel, body=root)
v4.cylinder("motor_axle", 0.006, 0.020, (0, 0.142, 0.278), rot=(math.pi/2, 0, 0), material=steel, body=root)
for yy in (.072,.094,.116):
    v4.torus("motor_band", .027,.0012,(0,yy,.278),rot=(math.pi/2,0,0),material=blacksteel,body=root)
# Exposed reduction-gear housings and crank discs at both wing roots.
for sx in (-1,1):
    xg = sx*.082
    # A hollow bearing boss lets the eccentric pin visibly pass through the root gearbox.
    v4.torus("root_gear_housing", .017, .007, (xg,-.029,z_h), rot=(math.pi/2,0,0), material=blacksteel, body=root)
    v4.torus("gear_housing_bead", .020, .002, (xg,-.036,z_h), rot=(math.pi/2,0,0), material=steel, body=root)
    v4.torus("crank_disc", .014, .003, (xg,-.041,z_h), rot=(math.pi/2,0,0), material=orange, body=root)
    v4.torus("crank_bearing_cap", .008, .0015, (xg,-.047,z_h), rot=(math.pi/2,0,0), material=steel, body=root)
    for a in range(4):
        t = math.pi*a/2
        v4.cylinder("gear_tooth", .0028, .006, (xg+.021*math.cos(t),-.034,z_h+.021*math.sin(t)),
                    rot=(math.pi/2,0,0), segments=12, material=orange, body=root)
# Recessed looking circular gearbox cap and radial screw detail on forward face.
v4.cylinder("gearbox_bearing_rim", 0.026, 0.004, (0, -0.1085, 0.264), rot=(math.pi/2,0,0), material=steel, body=root)
v4.cylinder("gearbox_bearing", 0.016, 0.005, (0, -0.1125, 0.264), rot=(math.pi/2,0,0), material=blacksteel, body=root)
v4.cylinder("gearbox_center", 0.006, 0.006, (0, -0.117, 0.264), rot=(math.pi/2,0,0), material=orange, body=root)
for a in range(8):
    t = 2*math.pi*a/8
    x,z = .022*math.cos(t), .264+.022*math.sin(t)
    v4.cylinder("cover_screw", .0025, .002, (x,-.112,z), rot=(math.pi/2,0,0), segments=16, material=steel, body=root)
# Tiny exterior fasteners on each side, mounted flush to the side panels.
# A small ranging optic occupies the center of the nose cone tip.
v4.cylinder("sensor_bezel", .009, .004, (0,-.153,.246), rot=(math.pi/2,0,0), material=steel, body=root)
v4.sphere("forward_sensor", .006, (0,-.156,.246), material=lens, body=root)
# Battery lid and latch on aft top of fuselage.
v4.box("battery_lid", (.082,.070,.009), (0,-.052,.310), bevel=.004, material=blacksteel, body=root)
v4.box("battery_latch", (.022,.014,.006), (0,-.081,.317), bevel=.002, material=orange, body=root)
v4.box("battery_label", (.045,.025,.001), (0,-.038,.3151), bevel=.0001, material=white, body=root)
# Status light atop the side of the casing.
v4.sphere("status_led", .0045, (.046,-.077,.306), material=led, body=root)
# Removable underbelly battery on saddles, with straps and a service connector.
v4.box("battery_pod", (.078,.105,.036), (0,.012,.161), bevel=.012, material=charcoal, body=root)
v4.box("battery_nose_cap", (.072,.018,.032), (0,-.042,.161), bevel=.007, material=orange, body=root)
for yy in (-.019,.043):
    v4.box("battery_saddle", (.086,.012,.018), (0,yy,.187), bevel=.004, material=steel, body=root)
    v4.box("battery_strap", (.084,.008,.044), (0,yy,.163), bevel=.003, material=orange, body=root)
v4.cylinder("battery_connector", .005, .014, (.022,.067,.161), rot=(math.pi/2,0,0), material=steel, body=root)
# Paired insulated leads route from the fuselage underside to the pod connector.
wire_red = v4.mat("Battery lead vermilion", (.82,.16,.07), roughness=.42)
wire_black = v4.mat("Battery lead black", (.025,.03,.035), roughness=.48)
v4.tube("battery_positive_lead", [(.016,.040,.197),(.022,.050,.190),(.030,.060,.180),(.022,.066,.166)], .0018,
        material=wire_red, body=root)
v4.tube("battery_negative_lead", [(.009,.040,.197),(.015,.051,.190),(.023,.060,.180),(.029,.066,.166)], .0018,
        material=wire_black, body=root)
# Radio whip on a raised foot and a small camera gimbal below the nose.
v4.cylinder("antenna_foot", .009,.007,(.030,-.030,.318), material=blacksteel, body=root)
v4.rod("antenna_whip", (.030,-.030,.321), (.030,-.017,.391), .0017, material=charcoal, body=root)
v4.box("gimbal_mount", (.025,.029,.026), (0,-.074,.201), bevel=.006, material=steel, body=root)
v4.sphere("camera_gimbal", .023, (0,-.078,.164), material=charcoal, body=root)
v4.torus("gimbal_yoke", .021,.0025,(0,-.078,.164), rot=(math.pi/2,0,0), material=steel, body=root)
v4.cylinder("gimbal_lens_rim", .014,.004,(0,-.099,.164),rot=(math.pi/2,0,0),material=orange,body=root)
v4.sphere("gimbal_lens", .010,(0,-.102,.164),material=lens,body=root)
# Rear tapered tail boom with small empennage; all mounted in root body.
v4.rod("tail_boom", (0,.135,.245), (0,.333,.258), .006, material=charcoal, body=root)
v4.lathe("tail_boom_fairing", [(0,0),(.008,.005),(.018,.021),(.015,.043),(.008,.059),(0,.062)],
         loc=(0,.112,.246), rot=(-math.pi/2,0,0), material=shell, body=root)
# horizontal tail plane with a subtle swept outline
v4.extrude("tailplane", [(-.115,.31),(-.105,.275),(0,.292),(.105,.275),(.115,.31),(0,.345)], .004,
           loc=(0,0,.251), bevel=.002, material=shell, body=root)
# bright elevator trim / separation marking
v4.rod("elevator_trim_L", (-.102,.306,.256), (0,.323,.256), .0018, material=orange, body=root)
v4.rod("elevator_trim_R", (0,.323,.256), (.102,.306,.256), .0018, material=orange, body=root)
for sx in (-1,1):
    # Twin vertical fins land directly on the tailplane, with thick molded roots.
    v4.box("tail_fin", (.046,.012,.062), (sx*.078,.314,.286), bevel=.004, material=charcoal, body=root)
    v4.box("fin_root_fillet", (.052,.020,.009), (sx*.078,.314,.2595), bevel=.003, material=shell, body=root)
    v4.rod("elevator_horn", (sx*.069,.303,.257), (sx*.069,.303,.279), .0025, material=orange, body=root)
    v4.cylinder("elevator_horn_pin", .0032,.005,(sx*.069,.300,.279),rot=(math.pi/2,0,0),material=steel,body=root)
    v4.rod("tail_pushrod", (sx*.069,.300,.279), (0,.205,.251), .0015, material=steel, body=root)

# Paired independent crank-rocker links. Their eyelets are exactly at body pivots.
link_bodies = {}
hinge_bodies = {}
wing_bodies = {}
for side, sx in (("L",-1),("R",1)):
    x0, x1, x2 = sx*.082, sx*.145, sx*root_x
    link = v4.body("linkage_"+side); link_bodies[side]=link
    # twin slim plates fore/aft around the gearbox side, connected by an outer cross web
    for yy in (-.018,.018):
        v4.rod("rocker_carbon_bar", (x0,yy,z_h), (x1,yy,z_h), .0042, material=charcoal, body=link)
        for xx in (x0,x1):
            v4.cylinder("rocker_eyelet", .009, .004, (xx,yy,z_h), rot=(math.pi/2,0,0), material=orange, body=link)
            v4.cylinder("eyelet_bushing", .0042, .005, (xx,yy+(-.003 if yy<0 else .003),z_h), rot=(math.pi/2,0,0), material=steel, body=link)
    v4.rod("rocker_crossbar", (x0,-.018,z_h), (x0,.018,z_h), .004, material=steel, body=link)
    v4.rod("rocker_crossbar_outer", (x1,-.018,z_h), (x1,.018,z_h), .004, material=steel, body=link)
    v4.box("connecting_rod_web", (.063,.028,.012), ((x0+x1)/2,0,z_h), bevel=.004, material=orange, body=link)
    for xx in (x0,x1):
        v4.cylinder("protruding_link_pin", .006,.032,(xx,-.031,z_h),rot=(math.pi/2,0,0),material=steel,body=link)
        v4.cylinder("pin_cap_groove", .008,.004,(xx,-.048,z_h),rot=(math.pi/2,0,0),material=orange,body=link)

    hinge = v4.body("wing_hinge_"+side); hinge_bodies[side]=hinge
    # fork plates run outward from linkage eye to the spar hinge; the spar-root barrel spans Y.
    for yy in (-.022,.022):
        v4.rod("hinge_fork_rail", (x1,yy,z_h), (x2,yy,z_h), .0045, material=steel, body=hinge)
        v4.torus("fork_root_boss", .009,.002,(x1,yy,z_h),rot=(math.pi/2,0,0),material=orange,body=hinge)
    v4.rod("clevis_crossbridge", ((x1+x2)/2,-.022,z_h), ((x1+x2)/2,.022,z_h), .0045, material=steel, body=hinge)
    # The wing-root rocker carries an X-axis pitch bearing for passive feathering.
    # Clevis cheeks flank the axle while leaving a clear bore through its center.
    for yy in (-.020,.020):
        v4.box("pitch_bearing_cheek", (.012,.010,.032), (x2-sx*.010,yy,z_h), bevel=.003, material=blacksteel, body=hinge)
    v4.torus("spar_hinge_barrel", .012,.003,(x2,-.005,z_h),rot=(0,math.pi/2,0),material=steel,body=hinge)
    for xx in (x2-sx*.005,x2+sx*.005):
        v4.torus("pitch_pin_washer", .0085,.0015,(xx,-.005,z_h),rot=(0,math.pi/2,0),material=orange,body=hinge)

    wing = v4.body("wing_spar_"+side); wing_bodies[side]=wing
    # root shoe and long tapered leading/trailing spars
    clamp = [(sx*.177,-.035),(sx*.220,-.022),(sx*.218,.064),(sx*.177,.083)]
    if sx < 0: clamp=list(reversed(clamp))
    v4.extrude("tapered_root_clamp",clamp,.012,loc=(0,0,z_h-.006),bevel=.002,material=orange,body=wing)
    v4.cylinder("pitch_axle", .0065,.022,(x2,-.005,z_h),rot=(0,math.pi/2,0),material=blacksteel,body=wing)
    v4.cylinder("pitch_pin_cap", .009,.004,(x2+sx*.012,-.005,z_h),rot=(0,math.pi/2,0),material=steel,body=wing)
    v4.rod("carbon_leading_spar", (sx*.165,-.027,z_h+.003), (sx*.426,-.002,z_h+.003), .0035, material=charcoal, body=wing)
    v4.rod("carbon_trailing_edge", (sx*.165,.083,z_h+.002), (sx*.414,.038,z_h+.002), .0018, material=charcoal, body=wing)
    # Membrane tapered to a softly clipped wingtip. Its thin polymer surface is carried by the spar body.
    cambered_membrane("amber_wing_membrane",sx,wing)
    # Three visible chord ribs and one root rib support the skin.
    for xx, ylead, ytrail in ((.205,-.023,.076),(.27,-.017,.064),(.335,-.011,.052),(.39,-.006,.043)):
        xx *= sx
        v4.rod("wing_rib", (xx,ylead,z_h+.006), (xx,ytrail,z_h+.006), .0012, material=steel, body=wing)
        v4.cylinder("rib_tip_cap", .0022, .004, (xx,ylead,z_h+.006), rot=(math.pi/2,0,0), segments=16, material=orange, body=wing)
    # Narrow orange root tape and two understated film seam lines.
    v4.rod("root_tape_edge", (sx*.17,-.019,z_h+.001), (sx*.17,.078,z_h+.001), .0015, material=orange, body=wing)
    v4.rod("film_seam_outer", (sx*.27,-.016,z_h+.001), (sx*.27,.064,z_h+.001), .0008, material=orange, body=wing)

# Retained hinge chain. All pivots are aligned with visible metal barrels and eyelets.
for side,sx in (("L",-1),("R",1)):
    v4.joint("crank_"+side, "revolute", root, link_bodies[side], origin=(sx*.082,-.005,z_h), axis=(0,1 if sx < 0 else -1,0),
             limits=(-math.radians(35), math.radians(35)))
    v4.joint("root_hinge_"+side, "revolute", link_bodies[side], hinge_bodies[side], origin=(sx*.145,-.005,z_h), axis=(0,1 if sx < 0 else -1,0),
             limits=(-math.radians(25), math.radians(25)))
    v4.joint("spar_hinge_"+side, "revolute", hinge_bodies[side], wing_bodies[side], origin=(sx*root_x,-.005,z_h), axis=(sx,0,0),
             limits=(-math.radians(35), math.radians(35)))

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