"""Detailed articulated marine porthole, authored with v4lib."""
import math
import os
import sys

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

v4.reset()

# Dimensions in metres. The frame rests on z=0; the glazed face points toward -Y.
CZ = 0.220
R_OUT = 0.220
R_FRAME_IN = 0.158
R_PANEL = 0.154
R_GLASS = 0.128
Y_FRAME = 0.004

bronze = v4.metal("polished_sash_brass", (0.86, 0.61, 0.27), roughness=0.20, brushed=False)
frame_bronze = v4.metal("deep_cast_bronze", (0.39, 0.24, 0.13), roughness=0.34, brushed=False)
bronze_dark = v4.metal("recessed_bronze", (0.30, 0.17, 0.075), roughness=0.42, brushed=False)
steel = v4.metal("polished_stainless", (0.78, 0.81, 0.83), roughness=0.22, brushed=True)
black = v4.rubber("marine_gasket", (0.035, 0.045, 0.05), roughness=0.72)
glass = v4.glass("blue_clear_glazing", (0.72, 0.86, 0.94), roughness=0.055)
letter = v4.metal("lettering_bronze", (0.9, 0.68, 0.38), roughness=0.25, brushed=False)


def annulus(name, outer, inner, y_front, y_back, body, material, bevel=0.0015, n=96):
    """A solid annular plate lying in XZ, with thickness along Y."""
    bm = bmesh.new()
    # Four loops: outer/inner, front/back. Faces wind around the aperture.
    loops = []
    for radius, y in ((outer, y_front), (outer, y_back), (inner, y_back), (inner, y_front)):
        loops.append([bm.verts.new((radius * math.cos(2*math.pi*i/n), y,
                                    CZ + radius * math.sin(2*math.pi*i/n))) for i in range(n)])
    for i in range(n):
        j = (i+1) % n
        for k in range(4):
            bm.faces.new((loops[k][i], loops[k][j], loops[(k+1)%4][j], loops[(k+1)%4][i]))
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    me = bpy.data.meshes.new(name)
    bm.to_mesh(me)
    bm.free()
    ob = bpy.data.objects.new(name, me)
    bpy.context.scene.collection.objects.link(ob)
    if material:
        ob.data.materials.append(material)
    for p in ob.data.polygons:
        p.use_smooth = True
    if bevel:
        mod=ob.modifiers.new("Cast edge radii", "BEVEL")
        mod.width=bevel; mod.segments=3; mod.limit_method="ANGLE"; mod.angle_limit=math.radians(28)
        ob.modifiers.new("Weighted casting normals", "WEIGHTED_NORMAL")
    v4.part(ob, body)
    return ob


def y_cylinder(name, radius, depth, x, y, z, body, material, bevel=0.0006, segments=32):
    return v4.cylinder(name, radius, depth, (x,y,z), rot=(math.pi/2,0,0), segments=segments,
                       bevel=bevel, material=material, body=body)


def radial_point(radius, angle, y):
    return (radius*math.cos(angle), y, CZ+radius*math.sin(angle))


ring = v4.body("ring_frame")
panel = v4.body("panel")
dog_top = v4.body("clamp_dog_top")
dog_right = v4.body("clamp_dog_right")
dog_bottom = v4.body("clamp_dog_bottom")
handle = v4.body("handle")

# ---- fixed cast frame: broad annular flange, stepped inner/outer beads ----------------
frame_plate = annulus("one_piece_cast_frame", R_OUT, R_FRAME_IN, -0.025, 0.032, ring, frame_bronze, 0.0022)
# Clearance pockets let the sash knuckles sit on the external hinge line without
# intruding into the cast aperture edge.
for k,zoff in enumerate((-0.030,0.030)):
    pocket=v4.box(f"hinge_clearance_cutter_{k}",(0.023,0.032,0.043),(-0.166,-0.015,CZ+zoff),bevel=0)
    v4.boolean(frame_plate,pocket)
# The flange's outside lip is cast directly into the frame profile. Keep this
# perimeter clear so the sash can sweep past it at the full opening angle.
v4.torus("aperture_bead", 0.162, 0.004, (0,-0.028,CZ), rot=(math.pi/2,0,0), material=letter, body=ring)
v4.torus("back_seal_land", 0.171, 0.003, (0,0.033,CZ), rot=(math.pi/2,0,0), material=bronze_dark, body=ring)
# Recessed inner well, represented by a dark narrow lip behind the sash.
v4.torus("inner_shadow_line", 0.1575, 0.0018, (0,-0.018,CZ), rot=(math.pi/2,0,0), material=bronze_dark, body=ring)
# Black continuous seal in the close sash-to-frame clearance.
v4.torus("sash_perimeter_gasket",0.156,0.00145,(0,-0.027,CZ),rot=(math.pi/2,0,0),material=black,body=ring)

# Rear bulkhead flange and a short spigot sleeve through the mounting surface.
annulus("rear_mounting_flange",0.220,0.160,0.031,0.045,ring,frame_bronze,0.0015)
annulus("bulkhead_spigot",0.169,0.143,0.044,0.094,ring,bronze_dark,0.0012)
# Rear face bolts and their broad washers visibly secure the flange.
for i in range(8):
    a=2*math.pi*i/8+math.pi/8
    x,y,z=radial_point(0.190,a,0.047)
    y_cylinder(f"rear_mount_washer_{i+1:02d}",0.009,0.002,x,y,z,ring,bronze_dark,0.0004)
    bpy.ops.mesh.primitive_cylinder_add(vertices=6,radius=0.0055,depth=0.004,location=(x,0.050,z),rotation=(math.pi/2,0,0))
    bolt=bpy.context.object; bolt.name=f"rear_mount_hex_bolt_{i+1:02d}"
    v4._link(bolt); v4.assign(bolt,steel); v4.part(bolt,ring)

# Eight evenly spaced mounting bosses and slotted stainless fasteners.
for i in range(8):
    a=2*math.pi*i/8 + math.pi/8
    x,y,z=radial_point(0.190,-a,-0.028)
    # small circular seat is shallow and follows the front face
    y_cylinder(f"frame_screw_seat_{i+1:02d}",0.010,0.002,x,y,z,ring,bronze_dark,0.0004)
    y_cylinder(f"frame_screw_{i+1:02d}",0.0067,0.003,x,-0.031,z,ring,steel,0.0006)
    # narrow slot over the head; rotated in the face plane
    v4.box(f"screw_slot_{i+1:02d}",(0.0075,0.0008,0.0012),(x,-0.033,z),
           rot=(0,0,a),bevel=0.00025,material=bronze_dark,body=ring)


# ---- sash / deadlight -----------------------------------------------------------------
annulus("bronze_sash", R_PANEL, R_GLASS+0.002, -0.036, 0.004, panel, bronze, 0.0015)
v4.torus("sash_front_roll", 0.145, 0.003, (0,-0.036,CZ), rot=(math.pi/2,0,0), material=letter, body=panel)
v4.torus("glass_gasket", R_GLASS+0.001, 0.0032, (0,-0.024,CZ), rot=(math.pi/2,0,0), material=black, body=panel)
# Cylinder axis is Y. Glass seats against the gasket with a thin exposed edge.
y_cylinder("single_glazed_lens", R_GLASS, 0.016, 0,-0.020,CZ,panel,glass,0.0012,96)
# A slim inner retaining ring sits on the glass rim, secured by six tiny screws.
v4.torus("glazing_retainer", R_GLASS-0.004, 0.0015, (0,-0.025,CZ), rot=(math.pi/2,0,0), material=bronze, body=panel)
for i in range(6):
    a=2*math.pi*i/6
    x,y,z=radial_point(0.137,a,-0.0375)
    y_cylinder(f"sash_retainer_screw_{i+1}",0.0022,0.003,x,y,z,panel,steel,0.00025,20)

# External hinge: alternating barrels on the accepted hinge axis, with visible
# cast leaves and short offset straps joining the front plates to the knuckles.
hinge_x=-0.166
for k,zoff in enumerate((-0.083,0.083)):
    z=CZ+zoff
    v4.cylinder(f"frame_hinge_knuckle_{k}",0.006,0.044,(hinge_x,-0.007,z),
                segments=32,bevel=0.0006,material=bronze,body=ring)
    v4.box(f"frame_hinge_leaf_{k}",(0.040,0.006,0.052),(-0.177,-0.028,z),
           bevel=0.002,material=frame_bronze,body=ring)
    v4.box(f"frame_hinge_neck_{k}",(0.014,0.020,0.020),(hinge_x,-0.019,z),
           bevel=0.002,material=frame_bronze,body=ring)
    for sx in (-1,1):
        y_cylinder(f"frame_hinge_bolt_{k}_{sx}",0.0032,0.002,-0.188,-0.033,z+sx*0.015,ring,steel,0.0004,20)
for k,zoff in enumerate((-0.030,0.030)):
    z=CZ+zoff
    v4.cylinder(f"sash_hinge_knuckle_{k}",0.0057,0.036,(hinge_x,-0.007,z),
                segments=32,bevel=0.0005,material=bronze,body=panel)
    v4.box(f"sash_hinge_leaf_{k}",(0.019,0.006,0.031),(hinge_x+0.010,-0.033,z),
           bevel=0.0012,material=bronze,body=panel)
    v4.box(f"sash_hinge_neck_{k}",(0.014,0.021,0.020),(hinge_x-0.006,-0.019,z),
           bevel=0.0015,material=bronze,body=panel)
    v4.rod(f"sash_hinge_offset_strap_{k}",(hinge_x-0.006,-0.021,z),(-0.161,-0.030,z),
           0.0022,bevel=0.0003,material=bronze,body=panel)
    for sx in (-1,1):
        y_cylinder(f"sash_hinge_bolt_{k}_{sx}",0.0028,0.002,-0.156,-0.037,z+sx*0.010,panel,steel,0.00035,20)
# visible hinge pin head and lower cap
y_cylinder("hinge_pin_top",0.004,0.004,hinge_x,-0.014,CZ+0.108,ring,steel)
y_cylinder("hinge_pin_bottom",0.004,0.004,hinge_x,-0.014,CZ-0.108,ring,steel)

# ---- four threaded swing-bolt dogs ------------------------------------------------------
def build_dog(body, name, angle):
    # A radial stud swings off a shouldered frame pin; its rounded toe laps the sash.
    ux,uz=math.cos(angle),math.sin(angle)
    tx,tz=0.142*ux,CZ+0.142*uz
    px,pz=0.184*ux,CZ+0.184*uz
    py=-0.047
    boss_y=-0.029
    v4.cylinder(f"{name}_pivot_boss",0.013,0.013,(px,boss_y,pz),rot=(math.pi/2,0,0),
                segments=40,bevel=0.0013,material=frame_bronze,body=ring)
    washer_y=-0.038
    pin_y=-0.041
    y_cylinder(f"{name}_pivot_washer",0.009,0.002,px,washer_y,pz,ring,bronze_dark,0.0005)
    y_cylinder(f"{name}_pivot_pin",0.0055,0.004,px,pin_y,pz,ring,steel,0.0005)
    v4.rod(f"{name}_threaded_stud",(px,py,pz),(tx,py,tz),0.0045,bevel=0.0007,
           material=steel,body=body)
    # A fine helical crest on the shank reads clearly as a threaded adjuster.
    vx,vz=-uz,ux
    helix=[]
    turns=5.0
    for j in range(121):
        q=j/120
        a=2*math.pi*turns*q
        r=0.0045
        helix.append((px+(tx-px)*q+vx*r*math.cos(a), py+0.0045*math.sin(a),
                      pz+(tz-pz)*q+vz*r*math.cos(a)))
    v4.tube(f"{name}_thread_crest",helix,0.00055,material=bronze_dark,body=body,resolution=12)
    # Hooked contact toe: the pad reaches onto the sash face and carries a dark wear insert.
    shoe_rot=(0,angle,0)
    front_y=-0.040
    v4.box(f"{name}_hook_toe",(0.024,0.008,0.016),(tx,front_y,tz),
           rot=shoe_rot,bevel=0.0038,material=bronze,body=body)
    v4.box(f"{name}_toe_lip",(0.019,0.006,0.008),(0.146*ux,front_y+0.002,CZ+0.146*uz),
           rot=shoe_rot,bevel=0.0025,material=bronze,body=body)
    # T-wing tightening handle at the stud end, perpendicular to the stud in the sash plane.
    wx,wz=0.137*ux,CZ+0.137*uz
    tyx,tyz=-uz,ux
    wy=-0.059
    nut_y=-0.052
    v4.rod(f"{name}_wing_handle",(wx-tyx*0.014,wy,wz-tyz*0.014),
           (wx+tyx*0.014,wy,wz+tyz*0.014),0.0032,bevel=0.0007,material=bronze,body=body)
    v4.sphere(f"{name}_wing_grip_l",0.004,(wx-tyx*0.014,wy,wz-tyz*0.014),material=bronze,body=body)
    v4.sphere(f"{name}_wing_grip_r",0.004,(wx+tyx*0.014,wy,wz+tyz*0.014),material=bronze,body=body)
    v4.cylinder(f"{name}_wing_nut",0.006,0.009,(wx,nut_y,wz),rot=(0,math.pi/2-angle,0),
                segments=6,bevel=0.0007,material=bronze,body=body)

for dog,name,angle in ((dog_top,"top_dog",math.pi/2),(dog_right,"right_dog",0),
                       (dog_bottom,"bottom_dog",-math.pi/2)):
    build_dog(dog,name,angle)

# ---- folding center handle and latch hub ------------------------------------------------
y_cylinder("latch_hub",0.012,0.012,0.136,-0.032,CZ+0.052,panel,bronze_dark,0.001)
y_cylinder("handle_axle",0.005,0.015,0.136,-0.040,CZ+0.052,panel,steel,0.0005)
# A compact folding pull sits on the outer sash lug opposite the hinge.
v4.torus("folding_grab_ring",0.016,0.0035,(0.136,-0.050,CZ+0.052),rot=(math.pi/2,0,0),
         material=bronze,body=handle)
y_cylinder("handle_lug_cap",0.006,0.006,0.136,-0.050,CZ+0.052,handle,steel,0.0004)
for side in (-1,1):
    v4.rod(f"handle_spoke_{side}",(0.136+side*0.003,-0.050,CZ+0.052),
           (0.136+side*0.012,-0.050,CZ+0.052),0.0025,bevel=0.00035,material=bronze,body=handle)

# ---- articulation ----------------------------------------------------------------------
v4.joint("panel_hinge","revolute",ring,panel,origin=(hinge_x,-0.007,CZ),axis=(0,0,1),
         limits=(-math.radians(100),0))
for name,body,angle,lo,hi in (
    ("top_dog_hinge",dog_top,math.pi/2,0,math.radians(75)),
    ("right_dog_hinge",dog_right,0,0,math.radians(75)),
    ("bottom_dog_hinge",dog_bottom,-math.pi/2,0,math.radians(75))):
    px,pz=0.184*math.cos(angle),CZ+0.184*math.sin(angle)
    v4.joint(name,"revolute",ring,body,origin=(px,-0.047,pz),axis=(0,1,0),limits=(lo,hi))
v4.joint("handle_hinge","revolute",panel,handle,origin=(0.136,-0.050,CZ+0.052),axis=(0,1,0),
         limits=(-math.radians(90),math.radians(90)))

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