"""Detailed articulated wall fan. Run with Blender's background Python."""
import math, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import bpy
import v4lib as v4

v4.reset()
ivory = v4.painted("warm_ivory_enamel", color=(0.86, 0.83, 0.73), roughness=0.26)
ivory_hi = v4.painted("highlight_enamel", color=(0.94, 0.91, 0.82), roughness=0.22)
steel = v4.metal("nickel_wire", color=(0.67, 0.71, 0.73), roughness=0.28, brushed=False)
steel_dark = v4.metal("darkened_steel", color=(0.26, 0.29, 0.30), roughness=0.38, brushed=True)
charcoal = v4.plastic("graphite_molded_plastic", color=(0.12, 0.14, 0.15), roughness=0.42)
black = v4.rubber("cord_rubber", color=(0.075, 0.07, 0.06), roughness=0.65)
badge = v4.mat("badge_black", (0.055, 0.065, 0.065), roughness=0.34)
blade_tint = v4.painted("smoke_blue_blade_enamel", color=(0.40, 0.53, 0.59), roughness=0.31, coat=0.28)
tassel_gold = v4.metal("pull_weight_chrome", color=(0.72, 0.70, 0.61), roughness=0.26, brushed=False)
gold = v4.metal("badge_lettering", color=(0.76, 0.57, 0.28), roughness=0.31, brushed=False)

bracket = v4.body("wall_bracket")
head = v4.body("head")
guard = head  # the fixed wire cage is part of the head's single rigid assembly
rotor = v4.body("rotor")
left = v4.body("left_switch")
right = v4.body("right_switch")
ZC, YC = 1.65, -0.185
ROTOR_SHIFT = .065
SWITCH_Z = .020

# Wall plate and cast, reinforced short reach arm (root fixed to the wall).
v4.box("wall_mount_plate", (0.115, 0.025, 0.30), (0, 0.108, 1.69), bevel=0.012, material=ivory, body=bracket)
v4.box("plate_recess", (0.077, 0.002, 0.235), (0, 0.094, 1.69), bevel=0.006, material=ivory_hi, body=bracket)
for sx in (-1,1):
    for zz in (1.575,1.805):
        v4.cylinder(f"mount_screw_{sx}_{zz}", .006, .003, (sx*.040,.094,zz), rot=(math.pi/2,0,0), segments=24, material=steel, body=bracket)
        v4.cylinder(f"screw_cap_cover_{sx}_{zz}",.010,.004,(sx*.040,.0935,zz),rot=(math.pi/2,0,0),segments=32,material=ivory_hi,body=bracket)
        v4.cylinder(f"screw_cap_center_{sx}_{zz}",.0025,.002,(sx*.040,.0905,zz),rot=(math.pi/2,0,0),segments=16,material=steel,body=bracket)
# Captive mains lead with a molded strain relief at the lower wall-plate edge.
v4.torus("mains_cord_grommet",.010,.0025,loc=(0,.094,1.555),rot=(math.pi/2,0,0),segments=40,ring_segments=10,material=charcoal,body=bracket)
v4.tube("mains_cord_strain_relief",[(0,.093,1.555),(0,.087,1.535),(0,.082,1.515)],.006,material=black,body=bracket)
v4.tube("mains_cord",[(0,.082,1.515),(0,.079,1.475),(0,.074,1.445)],.0035,material=black,body=bracket)
# arm neck, tapered shoulder and top/bottom reinforcing gussets
v4.box("arm_bridge", (.126,.080,.082), (0,.038,1.655), bevel=.020, material=ivory, body=bracket)
# Raised tapered cast neck, with a rounded shoulder at the bracket end.
v4.cylinder("tapered_neck_arm",.027,.205,(0,.010,1.655),rot=(math.pi/2,0,0),radius_top=.018,segments=48,material=ivory_hi,body=bracket)
# Paired yoke ears straddle the head's rear tilt pin.
for sx in (-1,1):
    # The fork flares around the motor's rear bearing and meets the knuckle.
    v4.tube(f"yoke_cheek_{sx}",[(sx*.045,.025,ZC),(sx*.095,-.018,ZC),(sx*.135,-.055,ZC),(sx*.135,-.075,ZC),(sx*.084,-.110,ZC)],.010,material=ivory,body=bracket)

# Motor shell and yoke, all attached to tilting head.
v4.box("rear_tilt_yoke",(.105,.040,.062),(0,-.110,ZC),bevel=.012,material=ivory,body=head)
# Sculpted U-shaped motor cradle wraps the upper rear motor can.
for sx in (-1,1):
    v4.tube(f"motor_cradle_side_{sx}",[(sx*.045,YC+.100,ZC+.040),(sx*.066,YC+.075,ZC+.020),(sx*.068,YC+.060,ZC-.010),(sx*.055,YC+.045,ZC-.040)],.006,material=ivory,body=head)
    v4.cylinder(f"cradle_bolt_{sx}",.006,.004,(sx*.058,YC+.055,ZC-.010),rot=(0,math.pi/2,0),segments=24,material=steel,body=head)
# Paired pivot bosses and hex tension caps make the yoke's tilt axis legible.
for sx in (-1,1):
    v4.cylinder(f"tilt_pivot_boss_{sx}",.020,.012,(sx*.055,-.110,ZC),rot=(0,math.pi/2,0),segments=48,material=ivory_hi,body=head)
    v4.cylinder(f"tilt_tension_knob_{sx}",.013,.010,(sx*.066,-.110,ZC),rot=(0,math.pi/2,0),segments=12,material=steel_dark,body=head)
    v4.cylinder(f"tilt_knob_bolt_{sx}",.004,.002,(sx*.072,-.110,ZC),rot=(0,math.pi/2,0),segments=6,material=steel,body=head)
# The two-axis knuckle is a forked bearing collar around the rear motor bell.
v4.torus("bracket_knuckle_bearing",.084,.003,loc=(0,-.110,ZC),rot=(math.pi/2,0,0),segments=64,ring_segments=12,material=steel_dark,body=bracket)
# Main axial motor barrel, axis Y.
v4.cylinder("motor_barrel",.056,.070,(0,YC+.035,ZC),rot=(math.pi/2,0,0),segments=64,material=ivory,body=head)
v4.cylinder("rear_end_bell",.065,.029,(0,YC+.080,ZC),rot=(math.pi/2,0,0),segments=64,material=ivory,body=head)
# Closed rear motor cap and bright seam make the casing read as a solid appliance motor.
v4.lathe("motor_rear_cap",[(0,0),(.056,0),(.061,.003),(.060,.007),(.052,.012),(.038,.016),(.018,.019),(0,.020)],loc=(0,YC+.094,ZC),rot=(-math.pi/2,0,0),material=ivory_hi,body=head)
v4.torus("motor_rear_cap_seam",.058,.0015,loc=(0,YC+.094,ZC),rot=(math.pi/2,0,0),segments=64,ring_segments=10,material=ivory,body=head)
v4.cylinder("rear_cap_center_medallion",.016,.002,(0,YC+.113,ZC),rot=(math.pi/2,0,0),segments=48,material=ivory,body=head)
# The hollow inner race leaves the fan shaft and pull-chain envelope clear.
v4.torus("head_knuckle_race",.080,.004,loc=(0,-.110,ZC),rot=(math.pi/2,0,0),segments=64,ring_segments=12,material=ivory_hi,body=head)
v4.torus("front_end_bell_trim",.050,.005,loc=(0,YC+.007,ZC),rot=(math.pi/2,0,0),segments=64,ring_segments=10,material=ivory_hi,body=head)
# Twin cast standoffs bridge the tilt yoke into the rear motor cap.
for sx in (-1,1):
    v4.rod(f"yoke_to_motor_standoff_{sx}",(sx*.035,YC+.115,ZC),(sx*.035,YC+.094,ZC),.008,material=ivory,body=head)
# Cooling ribs are slim annular moldings around the motor casing.
for j, yy in enumerate((YC+.006,YC+.026,YC+.046,YC+.066)):
    v4.torus(f"motor_cooling_rib_{j}",.056,.0025,loc=(0,yy,ZC),rot=(math.pi/2,0,0),segments=48,ring_segments=8,material=ivory_hi,body=head)
# Rear vent slots: a circumferential row of dark narrow vents on the back end bell.
for k in range(14):
    a=2*math.pi*k/14
    x,z=math.cos(a)*.047,ZC+math.sin(a)*.047
    v4.box(f"rear_vent_{k}",(.012,.001,.0025),(x,YC+.108,z),rot=(0,-a,0),bevel=0,material=badge,body=head)
# Raised motor ID plate on top of shell.
v4.box("motor_nameplate",(.065,.003,.023),(0,YC+.025,ZC+.056),bevel=.004,material=badge,body=head)
v4.text("motor_label","NORTHWIND 16\n3 SPEED • 55W",.006,loc=(-.028,YC+.022,ZC+.069),rot=(math.pi/2,0,0),extrude_depth=.0003,material=gold,body=head)

# Twin downward pull-chain rotary switches on a narrow molded bridge above the motor.
v4.box("switch_mounting_bridge",(.190,.032,.012),(0,YC+.075,ZC+.080+SWITCH_Z),bevel=.005,material=ivory,body=head)
# Compact curved switch yoke follows the motor sides and carries trim fasteners.
# Two short molded risers secure the raised switch bridge to the motor shell.
for sx in (-1,1):
    v4.rod(f"switch_bridge_riser_{sx}",(sx*.015,YC+.075,ZC+.050),(sx*.015,YC+.075,ZC+.080+SWITCH_Z-.006),.006,material=ivory,body=head)
for nm,x,b in (("left",-.082,left),("right",.082,right)):
    v4.cylinder(f"{nm}_switch_socket",.014,.030,(x,YC+.075,ZC+.068+SWITCH_Z),rot=(math.pi/2,0,0),material=charcoal,body=head)
    v4.rod(f"{nm}_hinge_support",(x,YC+.062,ZC+.079+SWITCH_Z),(x,YC+.042,ZC+.079+SWITCH_Z),.008,material=steel_dark,body=head)
    v4.cylinder(f"{nm}_hinge_axle",.007,.030,(x,YC+.042,ZC+.079+SWITCH_Z),rot=(0,math.pi/2,0),segments=32,material=steel,body=head)
    # Lever pivots about X; chain hangs from the small lever tip in the rest pose.
    v4.cylinder(f"{nm}_lever_hub",.010,.016,(x,YC+.042,ZC+.079+SWITCH_Z),rot=(0,math.pi/2,0),material=steel,body=b)
    v4.rod(f"{nm}_lever",(x,YC+.042,ZC+.079+SWITCH_Z),(x,YC+.038,ZC+.044+SWITCH_Z),.005,material=ivory_hi,body=b)
    chain_y=YC+.038
    chain_top=ZC+.044+SWITCH_Z
    chain_end=chain_top-.120
    pts=[(x,chain_y,chain_top),(x,chain_y,chain_top-.055),(x,chain_y,chain_end)]
    v4.tube(f"{nm}_pull_chain",pts,.0016,material=steel,body=b)
    for n in range(13):
        zz=chain_top-.012-n*.009
        v4.sphere(f"{nm}_chain_bead_{n}",.0042,(x,chain_y,zz),segments=12,material=steel,body=b)
    v4.torus(f"{nm}_pull_weight_eye",.006,.0015,loc=(x,chain_y,chain_end),rot=(math.pi/2,0,0),material=tassel_gold,body=b)
    v4.lathe(f"{nm}_chain_pull",[(0,0),(.006,0),(.010,.004),(.010,.010),(.008,.022),(.006,.030),(0,.030)],
             loc=(x,chain_y,chain_end-.030),material=tassel_gold,body=b)
    v4.torus(f"{nm}_tassel_grip_ring",.008,.001,loc=(x,chain_y,chain_end-.012),rot=(math.pi/2,0,0),material=steel_dark,body=b)

# The front and rear grille faces are separated by a shallow 20 mm rim band.
# Each face uses four concentric hoops and 24 radial wires; the rim ties run only
# around the circumference, leaving the guard free of crossing chord wires.
R=.205
FRONT_GRILLE_Y=YC-.044
REAR_GRILLE_Y=FRONT_GRILLE_Y+.023
for face, yy in (("front",FRONT_GRILLE_Y),("rear",REAR_GRILLE_Y)):
    for j,r in enumerate((.045,.075,.105,.135,.165,R)):
        v4.torus(f"{face}_grille_ring_{j}",r,.0018,loc=(0,yy,ZC),rot=(math.pi/2,0,0),segments=96,ring_segments=8,material=steel,body=guard)
    for k in range(32):
        a=2*math.pi*k/32
        v4.rod(f"{face}_grille_radial_{k}",(0,yy,ZC),
               (R*math.cos(a),yy,ZC+R*math.sin(a)),.0012,material=steel,body=guard)
# The shallow rim band is held by short circumferentially spaced axial struts.
v4.torus("rolled_outer_rim_bead",R+.002,.0022,loc=(0,(FRONT_GRILLE_Y+REAR_GRILLE_Y)*.5,ZC),rot=(math.pi/2,0,0),segments=128,ring_segments=10,material=steel_dark,body=guard)
for k in range(16):
    a=2*math.pi*k/16
    v4.rod(f"guard_rim_band_strut_{k}",(R*math.cos(a),FRONT_GRILLE_Y,ZC+R*math.sin(a)),
           (R*math.cos(a),REAR_GRILLE_Y,ZC+R*math.sin(a)),.0018,material=steel,body=guard)
# Stainless rim keeper clip and hinge block at the 2 o'clock position.
clip_a=math.radians(32)
clip_x,clip_z=R*math.cos(clip_a),ZC+R*math.sin(clip_a)
v4.tube("rim_keeper_clip",[(clip_x-.012,FRONT_GRILLE_Y-.002,clip_z),(clip_x-.010,FRONT_GRILLE_Y-.006,clip_z+.008),(clip_x,FRONT_GRILLE_Y-.006,clip_z+.010),(clip_x+.010,FRONT_GRILLE_Y-.006,clip_z+.008),(clip_x+.012,FRONT_GRILLE_Y-.002,clip_z)],.0028,material=steel_dark,body=guard)
v4.box("rim_keeper_latch",(.016,.006,.008),(clip_x,FRONT_GRILLE_Y-.004,clip_z+.008),bevel=.002,material=steel,body=guard)
# Four short rear mounts tie the guard frame into the motor's front bell.
for k in range(4):
    a=math.pi/4+k*math.pi/2
    x,z=math.cos(a)*.055,ZC+math.sin(a)*.055
    v4.rod(f"rear_guard_motor_mount_{k}",(x,REAR_GRILLE_Y,z),(x,YC+.003,z),.003,material=steel,body=guard)
# Domed rear guard bows back from the cage rim, protecting the blade sweep around the motor.
rear_dome_profile=((R,REAR_GRILLE_Y),(.175,REAR_GRILLE_Y+.018),(.140,REAR_GRILLE_Y+.042))
for ring_i,(rad,yy) in enumerate(rear_dome_profile[1:-1]):
    v4.torus(f"rear_dome_concentric_{ring_i}",rad,.0014,loc=(0,yy,ZC),rot=(math.pi/2,0,0),segments=96,ring_segments=8,material=steel,body=guard)
for k in range(32):
    a=2*math.pi*k/32
    pts=[(rad*math.cos(a),yy,ZC+rad*math.sin(a)) for rad,yy in rear_dome_profile]
    v4.tube(f"rear_dome_radial_{k}",pts,.00135,material=steel,body=guard)
# Eight short stays carry the centre grille medallion forward from the inner ring.
for k in range(8):
    a=2*math.pi*k/8
    v4.rod(f"front_badge_stay_{k}",(.030*math.cos(a),FRONT_GRILLE_Y,ZC+.030*math.sin(a)),
           (.026*math.cos(a),YC-.075,ZC+.026*math.sin(a)),.0015,material=steel,body=guard)
# Enamelled central guard badge, concentric face trim and lettering.
v4.lathe("guard_centre_cap",[(0,0),(.030,0),(.034,.003),(.033,.008),(.027,.013),(.018,.017),(.008,.019),(0,.020)],loc=(0,YC-.073,ZC),rot=(math.pi/2,0,0),material=ivory_hi,body=guard)
v4.cylinder("guard_logo_inset",.016,.002,(0,YC-.092,ZC),rot=(math.pi/2,0,0),material=badge,body=guard)
v4.torus("guard_cap_trim",.033,.0017,loc=(0,YC-.077,ZC),rot=(math.pi/2,0,0),material=gold,body=guard)
v4.text("guard_brand","NW",.012,loc=(-.008,YC-.094,ZC-.004),rot=(math.pi/2,0,0),extrude_depth=.0005,material=gold,body=guard)

# Four molded blades with a swept planform, 22–27 degree pitch, and a shallow cupped section.
def blade_mesh(name, angle, body):
    radii=(.014,.050,.086,.122,.157,.181)
    chord_widths=(.018,.020,.023,.025,.024,.018)
    ybase=YC-.036  # blade plane sits inside the shallow front and rear guard faces
    verts=[]; faces=[]; across=5
    for side in (1,-1):
        for r,w in zip(radii,chord_widths):
            sweep=.24*(r-.014)/.167
            th=angle+sweep
            pitch=math.radians(18-3*(r-.014)/.167)
            for j in range(across):
                q=-1+2*j/(across-1)
                tang=q*w*.5
                rr=r
                px=rr*math.cos(th)-tang*math.sin(th)
                pz=rr*math.sin(th)+tang*math.cos(th)
                # Cupped camber across the chord with a small rounded leading edge.
                cup=.0012*(1-q*q)
                axial=(q+1)*w*.5*math.tan(pitch)+cup
                verts.append((px,ybase+axial+side*.0028,pz+ZC))
    nr=len(radii)
    layer=nr*across
    for layer_id in (0,1):
        off=layer_id*layer
        for i in range(nr-1):
            for j in range(across-1):
                a=off+i*across+j; b=a+across
                faces.append((a,b,b+1,a+1) if layer_id==0 else (a,a+1,b+1,b))
    for i in range(nr-1):
        a=i*across; b=(i+1)*across
        faces.append((a,b,layer+b,layer+a))
        a=i*across+across-1; b=(i+1)*across+across-1
        faces.append((a,layer+a,layer+b,b))
    for j in range(across-1):
        a=j; b=j+1; faces.append((a,layer+a,layer+b,b))
        a=(nr-1)*across+j; b=a+1; faces.append((a,b,layer+b,layer+a))
    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.objects.link(obj)
    v4.part(obj,body); v4.assign(obj,blade_tint)
    for poly in mesh.polygons: poly.use_smooth=True
    mod=obj.modifiers.new("soft molded blade edges","BEVEL"); mod.width=.0015; mod.segments=3
for i in range(4): blade_mesh(f"swept_blade_{i}",i*math.pi/2,rotor)
v4.cylinder("rotor_hub",.035,.025,(0,YC-.018,ZC),rot=(math.pi/2,0,0),material=ivory,body=rotor)
v4.cylinder("rotor_drive_axle",.009,.0085,(0,YC-.00475,ZC),rot=(math.pi/2,0,0),material=steel_dark,body=rotor)
v4.lathe("rotor_nose_cap",[(0,0),(.022,0),(.027,.006),(.025,.012),(.018,.020),(0,.024)],
         loc=(0,YC-.0205,ZC),rot=(math.pi/2,0,0),material=ivory_hi,body=rotor)

# Tree articulation: all four moving bodies directly attach to their mechanical host.
v4.joint("head_tilt_oscillation","generic",bracket,head,origin=(0,-.110,ZC),axis=(0,0,1),xdir=(1,0,0),
         dofs=[("rotX",(-math.radians(25),math.radians(25))),
               ("rotZ",(-math.radians(45),math.radians(45)))])
v4.joint("rotor_spin","continuous",head,rotor,origin=(0,YC-.018,ZC),axis=(0,-1,0))
v4.joint("left_pull_switch","revolute",head,left,origin=(-.082,YC+.042,ZC+.079+SWITCH_Z),axis=(1,0,0),limits=(-math.radians(15),math.radians(15)))
v4.joint("right_pull_switch","revolute",head,right,origin=(.082,YC+.042,ZC+.079+SWITCH_Z),axis=(1,0,0),limits=(-math.radians(15),math.radians(15)))
v4.save(os.path.join(os.getcwd(),"asset.blend"))
print("saved asset.blend")
