"""Detailed torpedo hull survey AUV, authored with v4lib."""
import math
import os
import sys

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

v4.reset()

# Materials: a restrained commercial survey-vehicle palette.
navy = v4.painted("AUV deep navy polyurethane", (0.045, 0.15, 0.24), roughness=0.29, coat=0.48)
ivory = v4.painted("Warm white nose fairing", (0.82, 0.84, 0.78), roughness=0.27, coat=0.5)
metal = v4.metal("Satin titanium", (0.57, 0.64, 0.68), roughness=0.26)
dark_metal = v4.metal("Dark anodized hardware", (0.13, 0.18, 0.20), roughness=0.3, brushed=False)
rubber = v4.rubber("Black elastomer seals", (0.018, 0.025, 0.028))
glass = v4.glass("Smoked optical glass", (0.10, 0.18, 0.21), roughness=0.08)
sensor_glass = v4.glass("Blue green transducer glass", (0.25, 0.42, 0.48), roughness=0.13)
amber = v4.painted("Safety amber", (0.95, 0.35, 0.035), roughness=0.31, coat=0.35)
led = v4.emissive("Status green", (0.14, 0.8, 0.32), strength=1.1)
strobe_mat = v4.emissive("Amber strobe lens", (1.0, 0.31, 0.025), strength=2.2)

Z = 0.38
hull = v4.body("hull")

def axis_rotation(axis):
    return Vector(axis).normalized().to_track_quat("Z", "Y").to_euler()

# A continuous turned pressure hull and fairing profile. The profile closes to the
# centerline at both ends and avoids coincident nose/tail solids.
profile = [
    (0.0, -1.20), (0.035, -1.19), (0.072, -1.15), (0.108, -1.09),
    (0.137, -1.00), (0.153, -0.89), (0.160, -0.77), (0.160, -0.70),
    (0.160, 0.59), (0.170, 0.69), (0.170, 0.78), (0.145, 0.84),
    (0.116, 0.89), (0.082, 0.94), (0.050, 0.985), (0.0, 1.000),
]
v4.lathe("pressure_hull_and_fairings", profile, loc=(0, 0, Z), rot=(0, math.pi / 2, 0),
         material=navy, body=hull)

# White ceramic nose cap as a thin surface-following band, plus dark optical window.
# The cap follows the nose contour and meets the navy shell at its aft seam.
v4.lathe("nose_white_band", [(0.108, -1.09), (0.119, -1.075), (0.137, -1.00),
                            (0.148, -0.93), (0.153, -0.89)],
         loc=(0, 0, Z), rot=(0, math.pi / 2, 0), material=ivory, body=hull)
v4.sphere("forward_optical_window", 0.054, loc=(-1.139, 0, Z), material=glass, body=hull)
v4.torus("optical_window_retainer", 0.056, 0.003, loc=(-1.139, 0, Z),
         rot=(0, math.pi / 2, 0), material=dark_metal, body=hull)
# Fine gasket seam at the nose cap / forward pressure hull joint.
v4.torus("forward_hull_seam", 0.153, 0.0025, (-0.89, 0, Z),
         rot=(0, math.pi / 2, 0), material=rubber, body=hull)
v4.torus("forward_hull_seam_bead", 0.154, 0.0012, (-0.881, 0, Z),
         rot=(0, math.pi / 2, 0), material=metal, body=hull)
# Oblique forward camera port in the white nose fairing.
cam_normal = Vector((0, -0.80, 0.60))
cam_center = Vector((-1.05, 0, Z)) + cam_normal * 0.125
v4.torus("nose_camera_bezel", 0.025, 0.003, cam_center,
         rot=axis_rotation(cam_normal), material=dark_metal, body=hull)
v4.cylinder("nose_camera_window", 0.021, 0.005, cam_center + cam_normal * 0.001,
            rot=axis_rotation(cam_normal), material=sensor_glass, body=hull)
v4.sphere("nose_camera_lens", 0.007, cam_center + cam_normal * 0.004,
         material=glass, body=hull)

# Pressure-hull service rings and axial trim lines.
for i, x in enumerate((-0.68, -0.63, 0.48, 0.53, 0.62, 0.70)):
    radius = 0.159 if x < 0.59 else (0.162 if x < 0.69 else 0.170)
    v4.torus(f"pressure_joint_seal_{i}", radius, 0.0022, loc=(x, 0, Z),
             rot=(0, math.pi / 2, 0), material=rubber, body=hull)
    if i in (0, 3):
        v4.torus(f"metal_joint_bead_{i}", radius + 0.002, 0.0012, loc=(x + 0.006, 0, Z),
                 rot=(0, math.pi / 2, 0), material=metal, body=hull)

# Side acoustic transducer windows, pressure ports and their small retaining bezels.
for side in (-1, 1):
    for j, x in enumerate((-0.40, -0.22, 0.18, 0.36)):
        y = side * 0.158
        if j in (0, 2):
            # Two acoustic windows with distinct sizes and bright metal bezels.
            radius = 0.020 if j == 0 else 0.024
            v4.cylinder(f"sonar_port_rim_{side}_{j}", radius, 0.005, (x, y, Z + 0.015),
                        rot=(math.pi / 2, 0, 0), material=metal, body=hull)
            v4.cylinder(f"sonar_port_glass_{side}_{j}", radius * 0.68, 0.006,
                        (x, y + side * 0.003, Z + 0.015),
                        rot=(math.pi / 2, 0, 0), material=sensor_glass, body=hull)
            v4.cylinder(f"sonar_port_core_{side}_{j}", radius * 0.25, 0.0015,
                        (x, y + side * 0.006, Z + 0.015),
                        rot=(math.pi / 2, 0, 0), material=dark_metal, body=hull)
        else:
            # Alternate positions carry small flush titanium pressure plugs.
            v4.cylinder(f"pressure_plug_{side}_{j}", 0.009 if j == 1 else 0.012,
                        0.004, (x, y, Z + 0.015), rot=(math.pi / 2, 0, 0),
                        segments=8, material=dark_metal if j == 1 else metal, body=hull)
    # two flush pressure-sensor plugs under the forward third
    for j, x in enumerate((-0.48, -0.34)):
        v4.cylinder(f"pressure_sensor_{side}_{j}", 0.008, 0.004,
                    (x, side * 0.152, Z - 0.055), rot=(math.pi / 2, 0, 0),
                    material=metal, body=hull)

# GPS / Iridium mast with an identifiable radome, whip antenna and separate strobe.
v4.lathe("antenna_fairing", [(0.0, 0), (0.035, 0), (0.035, 0.045), (0.025, 0.09), (0, 0.10)],
         loc=(-0.47, 0, Z + 0.151), material=ivory, body=hull)
v4.cylinder("antenna_base_collar", 0.028, 0.009, (-0.47, 0, Z + 0.157),
            material=dark_metal, body=hull)
v4.cylinder("satcom_head_collar", 0.024, 0.012, (-0.47, 0, 0.637),
            material=metal, body=hull)
gps_dome = v4.sphere("gps_iridium_radome", 1.0, (-0.47, 0, 0.654), material=ivory, body=hull)
gps_dome.scale = (0.022, 0.022, 0.014)
v4.torus("radome_lower_seam", 0.020, 0.0015, (-0.47, 0, 0.641),
         material=dark_metal, body=hull)
v4.rod("satcom_whip_antenna", (-0.47, 0, 0.666), (-0.47, 0, 0.750), 0.0028,
       material=dark_metal, body=hull)
v4.sphere("satcom_whip_tip", 0.004, (-0.47, 0, 0.750), material=metal, body=hull)
v4.rod("strobe_mount", (-0.455, 0, 0.626), (-0.425, 0, 0.645), 0.0035,
       material=dark_metal, body=hull)
v4.cylinder("strobe_base", 0.010, 0.008, (-0.425, 0, 0.647),
            material=metal, body=hull)
v4.sphere("strobe_lens", 0.009, (-0.425, 0, 0.654), material=strobe_mat, body=hull)

# A low, blended ventral instrument keel replaces the old loose service tab.
# Its upper half merges into the pressure hull; a flush acoustic window sits below it.
keel = v4.sphere("ventral_dvl_fairing", 1.0, (0.13, 0, 0.200), material=navy, body=hull)
keel.scale = (0.17, 0.061, 0.026)
v4.torus("ventral_dvl_seal", 0.035, 0.0025, (0.13, 0, 0.176),
         material=rubber, body=hull)
v4.cylinder("ventral_dvl_window", 0.032, 0.004, (0.13, 0, 0.176),
            material=glass, body=hull)
v4.cylinder("ventral_dvl_inner_lens", 0.018, 0.0015, (0.13, 0, 0.173),
            material=dark_metal, body=hull)

# Downward looking forward sonar/DVL transducer window, flush to the nose shoulder.
v4.torus("forward_sonar_window_seal", 0.039, 0.0025, (-0.55, 0, 0.222),
         material=rubber, body=hull)
v4.cylinder("forward_sonar_window", 0.036, 0.004, (-0.55, 0, 0.222),
            material=glass, body=hull)
v4.cylinder("forward_sonar_core", 0.018, 0.0015, (-0.55, 0, 0.219),
            material=dark_metal, body=hull)

# Recessed crown lifting eye with a rounded stainless bail and two backed feet.
for x in (-0.17, -0.005):
    v4.sphere(f"lifting_eye_foot_{x}", 0.018, (x, 0, 0.532), material=dark_metal, body=hull)
v4.tube("lifting_eye_bail", [(-0.17, 0, 0.532), (-0.17, 0, 0.565),
                              (-0.15, 0, 0.582), (-0.025, 0, 0.582),
                              (-0.005, 0, 0.565), (-0.005, 0, 0.532)],
        0.006, material=metal, body=hull)

# Side service connectors: gasketed bulkhead sockets with knurled metal dust caps.
for side in (-1, 1):
    conn = (-0.08, side * 0.164, Z + 0.018)
    v4.cylinder(f"bulkhead_connector_flange_{side}", 0.019, 0.008, conn,
                rot=(math.pi / 2, 0, 0), material=dark_metal, body=hull)
    v4.torus(f"bulkhead_connector_seal_{side}", 0.014, 0.002, conn,
             rot=(math.pi / 2, 0, 0), material=rubber, body=hull)
    cap = (-0.08, side * 0.171, Z + 0.018)
    v4.cylinder(f"bulkhead_connector_cap_{side}", 0.012, 0.013, cap,
                rot=(math.pi / 2, 0, 0), segments=12, material=metal, body=hull)
    v4.cylinder(f"connector_cap_center_{side}", 0.004, 0.002,
                (-0.08, side * 0.179, Z + 0.018),
                rot=(math.pi / 2, 0, 0), material=dark_metal, body=hull)

# Fine socket-head bolts around the two main pressure section rings.
for ring_i, (x, rad) in enumerate(((-0.63, 0.160), (0.53, 0.160), (0.70, 0.170))):
    for k in range(8):
        a = 2 * math.pi * k / 8
        normal = Vector((0, math.cos(a), math.sin(a)))
        loc = (x + 0.004, normal.y * (rad + 0.001), Z + normal.z * (rad + 0.001))
        v4.cylinder(f"section_bolt_{ring_i}_{k}", 0.004, 0.003, loc,
                    rot=axis_rotation(normal), segments=12, material=metal, body=hull)

# Soft amber hazard bands around the tail fairing (surface rings).
for idx, x in enumerate((0.73, 0.755)):
    rad = 0.170
    v4.torus(f"tail_hazard_band_{idx}", rad, 0.004, (x, 0, Z), rot=(0, math.pi / 2, 0),
             material=amber, body=hull)

# Four independent foil control surfaces. Each extrusion has axial chord in local X,
# radial span in local Y, and a thin tangential section in local Z.
fin_specs = [
    ("top", (0, 0, 0.170), math.pi / 2, (0, 0, 1)),
    ("bottom", (0, 0, -0.170), -math.pi / 2, (0, 0, -1)),
    ("port", (0, -0.170, 0), math.pi, (0, -1, 0)),
    ("starboard", (0, 0.170, 0), 0.0, (0, 1, 0)),
]
fin_root_x = 0.770
fin_outline = [(-0.043, 0.0), (0.043, 0.0), (0.041, 0.050),
               (0.034, 0.120), (0.030, 0.180), (0.024, 0.225),
               (-0.004, 0.225), (-0.012, 0.180), (-0.025, 0.120), (-0.037, 0.050)]
for name, radial, rot_x, axis in fin_specs:
    body = v4.body(f"fin_{name}")
    pivot = (fin_root_x, radial[1], Z + radial[2])
    v4.extrude(f"{name}_rudder_foil", fin_outline, 0.018, loc=pivot,
               rot=(rot_x, 0, 0), bevel=0.006, material=navy, body=body)
    # Flush amber tip strip on the outer foil edge, kept within the foil outline.
    tip_poly = [(-0.002, 0.196), (0.029, 0.196), (0.024, 0.222), (-0.003, 0.222)]
    v4.extrude(f"{name}_amber_tip", tip_poly, 0.019, loc=pivot,
               rot=(rot_x, 0, 0), bevel=0.002, material=amber, body=body)
    # Hinge axes run spanwise. A substantial bearing barrel sits proud of the shell.
    hinge_axis = Vector(axis).normalized()
    v4.rod(f"{name}_hinge_stock", pivot, Vector(pivot) + hinge_axis * 0.060, 0.0055,
           material=metal, body=body)
    v4.rod(f"{name}_root_bearing", Vector(pivot) + hinge_axis * 0.008,
           Vector(pivot) + hinge_axis * 0.050, 0.014, material=dark_metal, body=body)
    v4.torus(f"{name}_root_seal", 0.014, 0.002,
             Vector(pivot) + hinge_axis * 0.012, rot=axis_rotation(hinge_axis),
             material=rubber, body=body)
    v4.sphere(f"{name}_hinge_pin_cap", 0.008,
              Vector(pivot) + hinge_axis * 0.060, material=dark_metal, body=body)
    v4.joint(f"{name}_fin_hinge", "revolute", hull, body, origin=pivot, axis=axis,
             limits=(-math.radians(20), math.radians(20)))

# Propeller: one axial hub and three broad swept blades on its rotating body.
prop = v4.body("propeller")
v4.cylinder("propeller_hub", 0.043, 0.095, (1.0475, 0, Z), rot=(0, math.pi / 2, 0),
            bevel=0.006, material=metal, body=prop)
v4.cylinder("propeller_nut", 0.026, 0.025, (1.1075, 0, Z), rot=(0, math.pi / 2, 0),
            bevel=0.004, material=dark_metal, body=prop)
v4.torus("hub_cone_gap_seal", 0.045, 0.0025, (1.003, 0, Z), rot=(0, math.pi / 2, 0),
         material=rubber, body=prop)
# Tapered spinner fairing covers the aft hub and nut while remaining part of the
# rotating propeller assembly.
v4.lathe("propeller_hub_spinner", [(0.0, 1.055), (0.036, 1.055), (0.041, 1.063),
                                  (0.037, 1.077), (0.030, 1.096), (0.020, 1.120),
                                  (0.007, 1.145), (0.0, 1.151)],
         loc=(0, 0, Z), rot=(0, math.pi / 2, 0), material=metal, body=prop)

def make_blade(index, angle):
    """Create a slightly pitched swept blade in a plane normal to the shaft."""
    radial = Vector((0.0, math.cos(angle), math.sin(angle)))
    tangent = Vector((0.0, -math.sin(angle), math.cos(angle)))
    # leading/trailing coordinates (radial distance, tangential sweep)
    outline = [(0.025, -0.020), (0.070, -0.040), (0.155, -0.034),
               (0.205, -0.006), (0.190, 0.028), (0.105, 0.038), (0.045, 0.020)]
    verts = []
    for dx in (-0.010, 0.010):
        for r, t in outline:
            p = Vector((1.0475 + dx, 0, Z)) + radial * r + tangent * t
            verts.append(tuple(p))
    n = len(outline)
    faces = [tuple(range(n)), tuple(range(n, 2*n))]
    for k in range(n):
        faces.append((k, (k+1) % n, (k+1) % n + n, k+n))
    mesh = bpy.data.meshes.new(f"propeller_blade_{index}_mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.update()
    obj = bpy.data.objects.new(f"propeller_blade_{index}", mesh)
    bpy.context.scene.collection.objects.link(obj)
    obj.data.materials.append(metal)
    bevel = obj.modifiers.new("Blade edge radius", "BEVEL")
    bevel.width = 0.004
    bevel.segments = 3
    obj.modifiers.new("Blade weighted normals", "WEIGHTED_NORMAL")
    v4.part(obj, prop)

for k in range(3):
    make_blade(k, 2 * math.pi * k / 3 + 0.18)

def make_fixed_duct():
    """Fixed airfoil-section Kort duct with a 90 mm chord and hull-borne supports."""
    # (axial station, radius) profile: rounded leading lip, parallel throat,
    # and a tapered trailing edge. The minimum throat radius leaves clearance
    # around the bevelled 205 mm blade tips.
    section = [(0.990, 0.221), (0.998, 0.228), (1.012, 0.231),
               (1.055, 0.231), (1.073, 0.226), (1.080, 0.220),
               (1.073, 0.215), (1.055, 0.214), (1.012, 0.214),
               (0.998, 0.216)]
    segments = 96
    verts = []
    for x, r in section:
        for k in range(segments):
            a = 2 * math.pi * k / segments
            verts.append((x, r * math.cos(a), Z + r * math.sin(a)))
    faces = []
    for q in range(len(section)):
        q2 = (q + 1) % len(section)
        for k in range(segments):
            k2 = (k + 1) % segments
            faces.append((q * segments + k, q * segments + k2,
                          q2 * segments + k2, q2 * segments + k))
    mesh = bpy.data.meshes.new("fixed_propeller_duct_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("fixed_propeller_duct", mesh)
    bpy.context.scene.collection.objects.link(obj)
    obj.data.materials.append(navy)
    for poly in mesh.polygons:
        poly.use_smooth = True
    bevel = obj.modifiers.new("Duct lip radius", "BEVEL")
    bevel.width = 0.0015
    bevel.segments = 3
    obj.modifiers.new("Duct weighted normals", "WEIGHTED_NORMAL")
    v4.part(obj, hull)

    # Four stout swept struts touch the tail fairing and enter the duct's forward
    # shoulder, well ahead of the rotating blade plane.
    for i in range(4):
        a = 2 * math.pi * i / 4 + math.pi / 4
        radial = Vector((0, math.cos(a), math.sin(a)))
        p0 = Vector((0.86, 0, Z)) + radial * 0.132
        p1 = Vector((0.998, 0, Z)) + radial * 0.221
        v4.rod(f"duct_support_strut_{i}", p0, p1, 0.014,
               material=navy, body=hull)

make_fixed_duct()

v4.joint("propeller_spin", "continuous", hull, prop, origin=(1.00, 0, Z), axis=(1, 0, 0))

# Tail details attached to the fixed hull: shaft bearing rim and small status lamp.
v4.torus("shaft_bearing_lip", 0.082, 0.003, (0.94, 0, Z), rot=(0, math.pi / 2, 0),
         material=dark_metal, body=hull)
v4.sphere("aft_status_lamp", 0.009, (0.79, -0.136, Z + 0.02), material=led, body=hull)

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