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

v4.reset()
# Materials: salon equipment in warm ivory, satin chrome and charcoal.
ivory = v4.plastic('warm_ivory_abs', (0.88, 0.84, 0.73), roughness=0.24, texture=0.07)
inner = v4.plastic('warm_grey_inner_liner', (0.22, 0.25, 0.25), roughness=0.48, texture=0.08)
charcoal = v4.plastic('charcoal_molded_base', (0.12, 0.14, 0.15), roughness=0.34, texture=0.12)
black = v4.rubber('black_tire_rubber', (0.025, 0.028, 0.03))
chrome = v4.metal('satin_chrome', (0.68, 0.72, 0.74), roughness=0.24, brushed=True)
steel = v4.metal('bright_fastener_steel', (0.78, 0.79, 0.78), roughness=0.2, brushed=False)
control = v4.plastic('control_panel_graphite', (0.075, 0.09, 0.095), roughness=0.28, texture=0.06)
red = v4.plastic('selector_red', (0.72, 0.12, 0.075), roughness=0.25, texture=0.04)
label = v4.mat('warm_white_print', (0.94, 0.89, 0.74), roughness=0.52)
copper = v4.metal('heater_element_copper', (0.72, 0.36, 0.16), roughness=0.32, brushed=False)
vent_dark = v4.plastic('recessed_vent_shadow', (0.045, 0.052, 0.052), roughness=0.55, texture=0.1)
visor_mat = v4.glass('smoke_clear_visored_acrylic', (0.38, 0.48, 0.49), roughness=0.18)

# Convenient mesh builder for a hollow rounded dome shell, open at the bottom.
def dome_surface(theta, phi, inner_side=False):
    # Parametric ellipsoidal shell, elongated toward the rear (+Y).
    rr=0.230 if inner_side else 0.242
    hh=0.291 if inner_side else 0.300
    zbase=1.514 if inner_side else 1.51
    s=math.sin(theta); c=math.cos(theta)
    rear=max(0.0,math.sin(phi))**4
    drop=0.028*rear*c*c
    pt=Vector((rr*c*math.cos(phi), rr*c*1.12*math.sin(phi), zbase+hh*s-drop))
    # Approximate outward surface normal of the stretched dome.
    n=Vector((c*math.cos(phi), c*math.sin(phi)/1.12, (rr/hh)*s))
    n.normalize()
    return pt,n

def dome_shell(name, center, outer_r, outer_h, thick, material, body, seg=96, rings=28):
    cx, cy, z0 = center
    ro, ho = outer_r, outer_h
    ri, hi = outer_r-thick, outer_h-thick*0.72
    verts=[]; faces=[]; profiles=[]
    for j in range(rings+1):
        theta=(math.pi/2)*j/rings
        profiles.append((ro*math.cos(theta), z0+ho*math.sin(theta), theta, False))
    for j in range(rings+1):
        theta=(math.pi/2)*(rings-j)/rings
        profiles.append((ri*math.cos(theta), z0+thick*0.35+hi*math.sin(theta), theta, True))
    for rr, zz, theta, inside in profiles:
        for i in range(seg):
            phi=2*math.pi*i/seg
            rear=max(0.0,math.sin(phi))**4
            fade=math.cos(theta)**2
            yscale=1.12
            verts.append((cx+rr*math.cos(phi),cy+rr*yscale*math.sin(phi),zz-0.028*rear*fade))
    nr=len(profiles)
    for j in range(nr-1):
        for i in range(seg):
            a=j*seg+i; b=j*seg+(i+1)%seg; c=(j+1)*seg+(i+1)%seg; d=(j+1)*seg+i
            faces.append((a,b,c,d))
    for i in range(seg):
        faces.append((i,(i+1)%seg,(nr-1)*seg+(i+1)%seg,(nr-1)*seg+i))
    me=bpy.data.meshes.new(name); me.from_pydata(verts,[],faces); me.update()
    ob=bpy.data.objects.new(name,me); v4._link(ob)
    for p in me.polygons: p.use_smooth=True
    ob.data.materials.append(material); ob.data.materials.append(inner)
    # The inner half of the double wall is molded in dark graphite to frame the fan.
    for j in range(rings,2*rings):
        for i in range(seg):
            me.polygons[j*seg+i].material_index=1
    v4.part(ob,body)
    return ob

def elliptical_rim(name, center_z, rx, ry, minor, drop, material, body, seg=128, tube_seg=12):
    verts=[]; faces=[]
    for i in range(seg):
        phi=2*math.pi*i/seg
        rear=max(0.0,math.sin(phi))**4
        radial=Vector((math.cos(phi),math.sin(phi)/1.12,0)); radial.normalize()
        center=Vector((rx*math.cos(phi),ry*math.sin(phi),center_z-drop*rear))
        for j in range(tube_seg):
            beta=2*math.pi*j/tube_seg
            p=center+radial*(minor*math.cos(beta))+Vector((0,0,minor*math.sin(beta)))
            verts.append(tuple(p))
    for i in range(seg):
        for j in range(tube_seg):
            a=i*tube_seg+j; b=((i+1)%seg)*tube_seg+j
            c=((i+1)%seg)*tube_seg+(j+1)%tube_seg; d=i*tube_seg+(j+1)%tube_seg
            faces.append((a,b,c,d))
    me=bpy.data.meshes.new(name); me.from_pydata(verts,[],faces); me.update()
    ob=bpy.data.objects.new(name,me); v4._link(ob)
    for f in me.polygons: f.use_smooth=True
    me.materials.append(material); v4.part(ob,body)
    return ob

def surface_frame(normal):
    n=Vector(normal).normalized()
    x=Vector((0,1,0)); x=(x-x.dot(n)*n).normalized()
    y=n.cross(x).normalized()
    return Matrix((x,y,n)).transposed().to_euler()

def yoke_plate(name, xmid, thickness, material, body):
    # Broad forged clevis cheek, extruded along X; the rising curved arm visibly
    # carries load from the column tube to the transverse hood hinge.
    yz=[(-0.018,1.382),(0.025,1.397),(0.105,1.435),(0.166,1.478),
        (0.207,1.515),(0.224,1.535),(0.207,1.555),(0.173,1.548),
        (0.124,1.516),(0.070,1.484),(0.015,1.457),(-0.018,1.440)]
    verts=[(xmid-thickness/2,y,z) for y,z in yz]+[(xmid+thickness/2,y,z) for y,z in yz]
    n=len(yz); faces=[tuple(range(n-1,-1,-1)),tuple(range(n,2*n))]
    for i in range(n): faces.append((i,(i+1)%n,(i+1)%n+n,i+n))
    me=bpy.data.meshes.new(name); me.from_pydata(verts,[],faces); me.update()
    ob=bpy.data.objects.new(name,me); v4._link(ob); v4.part(ob,body)
    ob.data.materials.append(material)
    bevel=ob.modifiers.new('soft forged edges','BEVEL'); bevel.width=0.004; bevel.segments=3
    ob.modifiers.new('weighted corner normals','WEIGHTED_NORMAL')
    return ob

base=v4.body('base')
# Broad five spoke base with subtle swept end caps and central molded receiver.
v4.cylinder('base_hub_lower',0.102,0.075,(0,0,0.105),bevel=0.012,material=charcoal,body=base)
v4.cylinder('base_hub_upper',0.079,0.105,(0,0,0.182),bevel=0.012,material=charcoal,body=base)
v4.cylinder('base_chrome_hub_cap',0.054,0.008,(0,0,0.238),bevel=0.003,material=chrome,body=base)
v4.torus('hub_cap_seam',0.052,0.0018,(0,0,0.243),material=steel,body=base)
for i in range(5):
    a=2*math.pi*i/5
    ux,uy=math.cos(a),math.sin(a)
    p0=(ux*0.055,uy*0.055,0.095); p1=(ux*0.255,uy*0.255,0.072)
    v4.rod(f'base_spoke_core_{i}',p0,p1,0.031,segments=24,bevel=0.007,material=charcoal,body=base,square=True)
    # flattened molded shell on each spoke, aligned radially
    length=0.224
    v4.box(f'spoke_cap_{i}',(0.068,length,0.034), (ux*0.163,uy*0.163,0.079), rot=(0,0,a-math.pi/2), bevel=0.016,material=charcoal,body=base)
    v4.cylinder(f'caster_socket_{i}',0.036,0.055,(ux*0.285,uy*0.285,0.076),bevel=0.008,material=charcoal,body=base)
# Upright socket and height lock collar are part of the base.
receiver=v4.cylinder('receiver_tube',0.041,0.45,(0,0,0.375),bevel=0.004,material=charcoal,body=base)
bore=v4.cylinder('receiver_bore',0.0355,0.454,(0,0,0.375),bevel=0,material=None,body=None)
v4.boolean(receiver,bore)
v4.torus('receiver_rim',0.043,0.006,(0,0,0.52),material=charcoal,body=base)
v4.torus('column_lock_ring',0.039,0.003,(0,0,0.526),material=chrome,body=base)
# Five swivel caster yokes, each with a wheel body.
casters=[]; wheels=[]
for i in range(5):
    a=2*math.pi*i/5
    ux,uy=math.cos(a),math.sin(a)
    x,y=ux*0.285,uy*0.285
    c=v4.body(f'caster_{i}'); casters.append(c)
    # swivel stem, fork cheeks and axle at the true wheel centre
    v4.cylinder(f'caster_stem_{i}',0.014,0.048,(x,y,0.061),bevel=0.003,material=steel,body=c)
    v4.cylinder(f'caster_race_{i}',0.023,0.012,(x,y,0.091),bevel=0.003,material=chrome,body=c)
    # wheel axis follows local X; offset each yoke in radial direction
    side=( -uy, ux)
    cx=x+ux*0.090; cy=y+uy*0.090; wz=0.054
    tang=(-uy,ux)
    for s in (-1,1):
        v4.rod(f'caster_fork_{i}_{s}',(cx+s*tang[0]*0.014,cy+s*tang[1]*0.014,0.11),
               (cx+s*tang[0]*0.014,cy+s*tang[1]*0.014,wz),0.002,material=chrome,body=c)
    for s in (-1,1):
        v4.rod(f'caster_yoke_arm_{i}_{s}',(x,y,0.095),(cx+s*tang[0]*0.014,cy+s*tang[1]*0.014,0.11),0.0045,material=chrome,body=c)
    # Small stamped brake paddle and its hinge bridge touch the fork at the tire crown.
    if i in (0,2,4):
        pedal=(cx-ux*0.022,cy-uy*0.022,0.108)
        v4.rod(f'caster_brake_link_{i}',(cx,cy,0.105),pedal,0.0035,material=steel,body=c)
        v4.box(f'caster_brake_pedal_{i}',(0.034,0.014,0.006),pedal,rot=(0,0,a),bevel=0.003,material=charcoal,body=c)
        v4.box(f'caster_brake_grip_{i}',(0.021,0.010,0.002), (pedal[0],pedal[1],pedal[2]+0.004),rot=(0,0,a),bevel=0.002,material=steel,body=c)
    # The hub cover on the wheel body hides the axle end; fork cheeks stop at the tire shoulders.
    v4.joint(f'caster_swivel_{i}','continuous',base,c,origin=(x,y,0.095),axis=(0,0,1))
    w=v4.body(f'wheel_{i}'); wheels.append(w)
    # wide black tire and inset chrome hubs; cylinders along X
    v4.torus(f'tire_{i}',0.039,0.011,(cx,cy,wz),rot=(math.pi/2,0,a),material=black,body=w)
    v4.cylinder(f'wheel_core_{i}',0.031,0.036,(cx,cy,wz),rot=(math.pi/2,0,a),bevel=0.003,material=black,body=w)
    for s in (-1,1):
        v4.cylinder(f'wheel_hub_{i}_{s}',0.020,0.002,(cx+s*tang[0]*0.019,cy+s*tang[1]*0.019,wz),rot=(math.pi/2,0,a),bevel=0.001,material=chrome,body=w)
        v4.cylinder(f'wheel_cap_{i}_{s}',0.008,0.003,(cx+s*tang[0]*0.021,cy+s*tang[1]*0.021,wz),rot=(math.pi/2,0,a),bevel=0.001,material=steel,body=w)
    v4.joint(f'wheel_spin_{i}','continuous',c,w,origin=(cx,cy,wz),axis=(-uy,ux,0))

column=v4.body('column')
# Dark outer mast, exposed chrome sliding tube and a compression lock at the sleeve mouth.
v4.cylinder('lower_column_sleeve',0.034,0.48,(0,0,0.54),bevel=0.004,material=charcoal,body=column)
v4.cylinder('upper_telescoping_tube',0.025,0.82,(0,0,0.99),bevel=0.002,material=chrome,body=column)
v4.cylinder('telescoping_collar',0.039,0.052,(0,0,0.785),bevel=0.006,material=charcoal,body=column)
v4.torus('collar_chrome_band',0.039,0.0025,(0,0,0.801),material=chrome,body=column)
v4.torus('lock_grip_lower',0.038,0.002,(0,0,0.761),material=black,body=column)
v4.torus('lock_grip_upper',0.038,0.002,(0,0,0.809),material=black,body=column)
v4.cylinder('height_lock_knob',0.011,0.018,(0,-0.042,0.785),rot=(math.pi/2,0,0),bevel=0.003,material=charcoal,body=column)
v4.cylinder('height_lock_screw',0.004,0.003,(0,-0.052,0.785),rot=(math.pi/2,0,0),bevel=0.001,material=steel,body=column)
# Flexible rubber power lead follows the telescoping column and ends exactly on its hood pivot axis.
v4.tube('hood_power_cord',[(0.052,0.22,1.535),(0.052,0.17,1.505),(0.048,0.12,1.47),(0.043,0.06,1.425),(0.039,0.03,1.38),(0.038,0,1.30),(0.038,0,0.60),(0.048,0,0.47),(0.066,0,0.36)],0.0045,material=black,body=column,resolution=12)
v4.cylinder('cord_grommet',0.008,0.014,(0.052,0.22,1.535),rot=(math.pi/2,0,0),bevel=0.002,material=charcoal,body=column)
# Molded cable saddles retain the lead against the mast at regular intervals.
for i,z in enumerate((1.28,1.08,0.92,0.60)):
    v4.box(f'cord_clip_{i}',(0.018,0.012,0.012),(0.030,0,z),bevel=0.004,material=charcoal,body=column)
    v4.box(f'cord_clip_inlay_{i}',(0.006,0.014,0.008),(0.039,0,z),bevel=0.003,material=steel,body=column)
# Two broad forged cheeks form a U yoke; a transverse foot bridges them above the column.
v4.rod('yoke_crossbar',(-0.040,-0.005,1.407),(0.040,-0.005,1.407),0.014,material=charcoal,body=column)
for s in (-1,1):
    yoke_plate(f'yoke_cheek_{s}',s*0.040,0.018,charcoal,column)
    v4.cylinder(f'tilt_tension_knob_{s}',0.020,0.014,(s*0.051,0.22,1.535),rot=(0,math.pi/2,0),bevel=0.004,material=charcoal,body=column)
    v4.cylinder(f'tilt_pivot_cap_{s}',0.010,0.003,(s*0.060,0.22,1.535),rot=(0,math.pi/2,0),bevel=0.001,material=chrome,body=column)
v4.joint('column_slide','prismatic',base,column,origin=(0,0,0.30),axis=(0,0,1),limits=(0,0.26))

hood=v4.body('hood')
# Hollow two-wall dome with rolled opening and interior liner.
dome_shell('hood_outer_shell',(0,0,1.51),0.242,0.300,0.012,ivory,hood)
elliptical_rim('rolled_hood_lip',1.51,0.242,0.271,0.012,0.028,ivory,hood)
# Thin distinct inner rim reinforces the opening and visible wall thickness.
elliptical_rim('inner_liner_rim',1.514,0.229,0.256,0.0028,0.028,inner,hood)
# Clear wraparound brow shield: a gently curved visor hanging from the front lip.
visor_verts=[]; visor_faces=[]; nvis=40
start,end=math.radians(206),math.radians(334)
for z in (1.507,1.445):
    for rad in (0.237,0.233):
        for i in range(nvis+1):
            phi=start+(end-start)*i/nvis
            visor_verts.append((rad*math.cos(phi),rad*1.12*math.sin(phi),z))
for i in range(nvis):
    visor_faces.append((i,i+1,2*(nvis+1)+i+1,2*(nvis+1)+i))
    visor_faces.append((nvis+1+i,nvis+2+i,3*(nvis+1)+i+1,3*(nvis+1)+i))
for i in range(nvis):
    a=i; b=i+1; visor_faces.append((a,b,2*(nvis+1)+b,2*(nvis+1)+a))
me=bpy.data.meshes.new('curved_clear_visor'); me.from_pydata(visor_verts,[],visor_faces); me.update()
visor=bpy.data.objects.new('curved_clear_visor',me); v4._link(visor); me.materials.append(visor_mat); v4.part(visor,hood)
for poly in me.polygons: poly.use_smooth=True
# A rear crown band of small inset-look cooling slots follows the shell curvature.
for i,phi in enumerate((0.62,0.91,1.20,1.49,1.78,2.07,2.36,2.65)):
    vp,vn=dome_surface(0.66,phi)
    v4.box(f'crown_vent_{i}',(0.009,0.034,0.003),tuple(vp+vn*0.001),rot=surface_frame(vn),bevel=0.004,material=vent_dark,body=hood)
# Rear hinge bosses and chrome pin. These touch the column clevis in the rest pose.
for s in (-1,1):
    v4.cylinder(f'hood_hinge_ear_{s}',0.024,0.018,(s*0.031,0.22,1.535),rot=(0,math.pi/2,0),bevel=0.003,material=ivory,body=hood)
v4.cylinder('hood_hinge_pin',0.008,0.095,(0,0.22,1.535),rot=(0,math.pi/2,0),bevel=0.001,material=chrome,body=hood)
# Motor assembly mounted under crown, attached to hood. Fan sits beneath this housing.
v4.cylinder('motor_bell',0.050,0.140,(0,0,1.738),bevel=0.008,material=charcoal,body=hood)
v4.cylinder('motor_cap',0.039,0.012,(0,0,1.797),bevel=0.004,material=chrome,body=hood)
v4.torus('motor_seam',0.050,0.002,(0,0,1.688),material=steel,body=hood)
v4.cylinder('motor_spindle',0.009,0.050,(0,0,1.655),bevel=0.001,material=chrome,body=hood)
v4.torus('heater_element_ring',0.151,0.006,(0,0,1.615),material=copper,body=hood)
for i in range(36):
    phi=2*math.pi*i/36
    hp,hn=dome_surface(0.70,phi,inner_side=True)
    # Small dark apertures sit half embedded in the inner liner surface.
    v4.cylinder(f'liner_perforation_{i}',0.0022,0.0015,tuple(hp-hn*0.0005),rot=surface_frame(-hn),segments=12,bevel=0,material=vent_dark,body=hood)
# Four support struts connect motor bell to the domed inner shell.
for i in range(4):
    a=2*math.pi*i/4+math.pi/4
    v4.rod(f'motor_stator_{i}',(0,0,1.66),(0.225*math.cos(a),0.225*math.sin(a),1.59),0.006,material=chrome,body=hood)
# Safety grille follows the hood opening: concentric rings and radial tie wires.
for k,r in enumerate((0.055,0.092,0.132,0.174,0.207)):
    v4.torus(f'grille_ring_{k}',r,0.0021,(0,0,1.558),material=chrome,body=hood)
for i in range(16):
    a=2*math.pi*i/16
    v4.rod(f'grille_spoke_{i}',(0,0,1.558),(0.211*math.cos(a),0.211*math.sin(a),1.558),0.0017,segments=12,bevel=0,material=steel,body=hood)
# Four metal brackets tie the grille ring back to the inner shell.
for i in range(4):
    a=math.pi*i/2
    v4.rod(f'grille_mount_{i}',(0.236*math.cos(a),0.236*math.sin(a),1.556),(0.205*math.cos(a),0.205*math.sin(a),1.558),0.003,material=chrome,body=hood)
# Small stamped maker badge on the front slope of the bonnet.
bp,bn=dome_surface(0.80,-math.pi/2)
v4.cylinder('maker_badge',0.017,0.003,tuple(bp+bn*0.001),rot=surface_frame(bn),bevel=0.001,material=chrome,body=hood)
v4.cylinder('maker_badge_inset',0.011,0.001,tuple(bp+bn*0.003),rot=surface_frame(bn),bevel=0.0005,material=control,body=hood)
# Side selector fascia sits tangent to the rounded right flank.
# Side selector fascia on the right flank, with printed positions.
control_point,control_normal=dome_surface(0.76,-0.07)
control_rot=surface_frame(control_normal)
control_mount=control_point+control_normal*0.003
v4.box('selector_fascia',(0.050,0.064,0.008),control_mount,rot=control_rot,bevel=0.014,material=charcoal,body=hood)
v4.box('selector_inset',(0.036,0.047,0.002),control_mount+control_normal*0.004,rot=control_rot,bevel=0.009,material=control,body=hood)
# Paired timer and heat dials on a flush, curved right-front fascia.
panel_pt,panel_n=dome_surface(1.12,-1.03)
panel_rot=surface_frame(panel_n)
panel_x=panel_rot.to_matrix() @ Vector((1,0,0))
panel_mount=panel_pt+panel_n*0.004
v4.box('timer_heat_panel',(0.092,0.051,0.008),tuple(panel_mount),rot=panel_rot,bevel=0.012,material=charcoal,body=hood)
v4.box('timer_heat_panel_inset',(0.077,0.039,0.002),tuple(panel_mount+panel_n*0.004),rot=panel_rot,bevel=0.008,material=control,body=hood)
for i,offset in enumerate((-0.022,0.022)):
    dial=panel_mount+panel_n*0.007+panel_x*offset
    v4.cylinder(f'control_dial_bezel_{i}',0.013,0.004,tuple(dial),rot=panel_rot,bevel=0.001,material=chrome,body=hood)
    v4.cylinder(f'control_dial_{i}',0.0085,0.008,tuple(dial+panel_n*0.005),rot=panel_rot,bevel=0.002,material=ivory,body=hood)
# Product badge on front edge and fine molding seam near crown.
# Switch knob has its own hinge body; an arrow mark points toward the selected detent.
switch=v4.body('switch')
pivot=Vector((0.181,-0.012,1.672))
# The rocker spindle stays coaxial with the unchanged X-axis hinge and seats into the pod.
v4.cylinder('selector_shaft',0.006,0.018,(0.188,-0.012,1.672),rot=(0,math.pi/2,0),bevel=0.002,material=chrome,body=switch)
v4.cylinder('selector_knob',0.013,0.016,(0.204,-0.012,1.672),rot=(0,math.pi/2,0),bevel=0.004,material=red,body=switch)
v4.cylinder('selector_index',0.003,0.002,(0.213,-0.012,1.672),rot=(0,math.pi/2,0),bevel=0.0005,material=label,body=switch)

# Impeller: four curved, swept blades on a separate continuous body.
fan=v4.body('fan')
v4.cylinder('fan_hub',0.031,0.025,(0,0,1.616),bevel=0.007,material=chrome,body=fan)
v4.cylinder('fan_hub_nose',0.019,0.012,(0,0,1.634),bevel=0.005,material=ivory,body=fan)
for i in range(4):
    a=2*math.pi*i/4+0.22
    # swept paddle using curved centerline; broad enough to read through the protective grille
    pts=[]
    for j in range(6):
        t=j/5
        r=0.027+0.112*t
        ang=a+0.28*t
        pts.append((r*math.cos(ang),r*math.sin(ang),1.615+0.006*t))
    v4.tube(f'fan_blade_{i}',pts,0.013,material=charcoal,body=fan,resolution=10)
    # bright leading edge accent
    q0=pts[0]; q1=pts[-1]
    v4.rod(f'blade_leading_edge_{i}',q0,q1,0.0014,material=chrome,body=fan)
v4.joint('fan_spin','continuous',hood,fan,origin=(0,0,1.616),axis=(0,0,1))
v4.joint('hood_tilt','revolute',column,hood,origin=(0,0.22,1.535),axis=(1,0,0),limits=(-math.radians(25),math.radians(35)))
v4.joint('selector','revolute',hood,switch,origin=(0.181,-0.012,1.672),axis=(1,0,0),limits=(-math.radians(45),math.radians(45)))

# Save at rest. Camera and lighting are supplied by the checking pipeline.
v4.save(os.path.join(os.getcwd(),'asset.blend'))
print('saved asset.blend')
