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

# Finishes
black = v4.plastic('satin_black_moulded', (0.025,0.028,0.034), roughness=.34)
charcoal = v4.fabric('charcoal_woven_upholstery', (0.035,0.039,0.045))
red = v4.painted('racing_red', (0.52,0.018,0.028), roughness=.28, coat=.7)
red_fabric = v4.fabric('deep_red_fabric', (0.20,0.012,0.020))
seam = v4.mat('seam_thread', (0.72,0.035,0.045), roughness=.8)
steel = v4.metal('brushed_steel', (0.62,0.66,0.7), roughness=.24)
gunmetal = v4.metal('gunmetal', (0.12,0.14,0.16), roughness=.32, brushed=False)
rubber = v4.rubber('caster_tread', (0.018,0.02,0.022))
soft = v4.fabric('armrest_soft_touch', (0.045,0.048,0.052))

def curved_panel(name, profile, z0, center_y, edge_bow, thickness, material, body):
    """Closed padded loft; the front bows rearward at center for a bucket contour."""
    ncol=16; verts=[]; row_count=len(profile); stride=ncol+1
    for layer in (0,1):
        for h, halfw in profile:
            for j in range(stride):
                u=-1+2*j/ncol
                verts.append((halfw*u,center_y+edge_bow*u*u+layer*thickness,z0+h))
    layer_offset=row_count*stride; faces=[]
    for r in range(row_count-1):
        for c in range(ncol):
            a=r*stride+c; b=a+1; d=(r+1)*stride+c; e=d+1
            faces.append((a,b,e,d)); faces.append((layer_offset+a,layer_offset+d,layer_offset+e,layer_offset+b))
    for r in range(row_count-1):
        a=r*stride; b=(r+1)*stride
        faces.append((a,b,layer_offset+b,layer_offset+a))
        a=r*stride+ncol; b=(r+1)*stride+ncol
        faces.append((a,layer_offset+a,layer_offset+b,b))
    for c in range(ncol):
        a=c; b=c+1; faces.append((a,layer_offset+a,layer_offset+b,b))
        a=(row_count-1)*stride+c; b=a+1; faces.append((a,b,layer_offset+b,layer_offset+a))
    mesh=bpy.data.meshes.new(name); mesh.from_pydata(verts,[],faces); mesh.update()
    obj=bpy.data.objects.new(name,mesh); bpy.context.collection.objects.link(obj)
    v4.part(obj,body); v4.assign(obj,material)
    for poly in mesh.polygons: poly.use_smooth=True
    bevel=obj.modifiers.new('soft upholstered shell edges','BEVEL'); bevel.width=.004; bevel.segments=3
    obj.modifiers.new('weighted upholstery normals','WEIGHTED_NORMAL')
    return obj

def bucket_wing(name, sx, profile, material, body):
    """Elliptical loft padded into the side edge and projecting forward."""
    seg=16; verts=[]
    for h, halfw, rx, ry in profile:
        cx=sx*(halfw-.045)
        cy=.095
        for k in range(seg):
            a=2*math.pi*k/seg
            verts.append((cx+sx*rx*math.cos(a),cy+ry*math.sin(a),.60+h))
    faces=[]
    for r in range(len(profile)-1):
        for k in range(seg):
            a=r*seg+k; b=r*seg+(k+1)%seg; c=(r+1)*seg+(k+1)%seg; d=(r+1)*seg+k
            faces.append((a,b,c,d))
    faces.extend([tuple(range(seg-1,-1,-1)),tuple((len(profile)-1)*seg+k for k in range(seg))])
    mesh=bpy.data.meshes.new(name); mesh.from_pydata(verts,[],faces); mesh.update()
    obj=bpy.data.objects.new(name,mesh); bpy.context.collection.objects.link(obj)
    v4.part(obj,body); v4.assign(obj,material)
    for poly in mesh.polygons: poly.use_smooth=True
    bevel=obj.modifiers.new('rounded bolster profile','BEVEL'); bevel.width=.004; bevel.segments=3
    obj.modifiers.new('wing normals','WEIGHTED_NORMAL')
    return obj

# Tree root: stationary star base and fixed lower gas-cylinder housing.
base = v4.body('base')
v4.cylinder('central_star_hub', .078, .15, (0,0,.177), material=gunmetal, body=base, bevel=.006)
v4.lathe('gas_cylinder_outer_sleeve', [(0,.20),(.043,.20),(.050,.23),(.050,.37),(.043,.40),(0,.40)], loc=(0,0,0), material=black, body=base)
v4.cylinder('gas_sleeve_rim', .052, .014, (0,0,.386), material=gunmetal, body=base)
# Five broad, flat cast spokes taper from the raised hub toward the twin-wheel ends.
spoke_outline=[(-.055,0),(.055,0),(.047,.075),(.035,.19),(.024,.275),
               (-.024,.275),(-.035,.19),(-.047,.075)]
for i in range(5):
    a = 2*math.pi*i/5 + math.pi/2
    ux,uy=math.cos(a),math.sin(a)
    v4.extrude(f'star_spoke_{i}',spoke_outline,.045,loc=(0,0,.105),rot=(0,0,a-math.pi/2),bevel=.009,material=gunmetal,body=base)
    v4.box(f'spoke_top_inlay_{i}',(.022,.16,.003), (ux*.195,uy*.195,.137), rot=(0,0,a-math.pi/2), bevel=.002, material=steel, body=base)
# Support joint geometry, columns and casters
caster_data=[]
for i in range(5):
    a=2*math.pi*i/5+math.pi/2; x,y=.285*math.cos(a),.285*math.sin(a)
    caster_data.append((x,y,a))
    cb=v4.body(f'caster_{i}')
    v4.cylinder(f'caster_stem_{i}',.012,.055,(x,y,.094), material=steel,body=cb,bevel=.002)
    v4.cylinder(f'caster_socket_{i}',.027,.035,(x,y,.075),material=black,body=cb,bevel=.005)
    # Fork cheeks and curved bridge surround the two independently rolling wheels.
    for sx in (-1,1):
        side = 'L' if sx < 0 else 'R'
        v4.box(f'caster_fork_{i}_{side}',(.010,.083,.104),(x+sx*.063,y,.067),bevel=.003,material=black,body=cb)
        wb=v4.body(f'wheel_{i}_{side}')
        v4.torus(f'wheel_tire_{i}_{side}',.036,.014,(x+sx*.041,y,.046),rot=(0,math.pi/2,0),material=rubber,body=wb)
        v4.cylinder(f'wheel_hub_{i}_{side}',.021,.012,(x+sx*.041,y,.046),rot=(0,math.pi/2,0),material=gunmetal,body=wb,bevel=.002)
        v4.cylinder(f'wheel_badge_{i}_{side}',.010,.014,(x+sx*.041,y,.046),rot=(0,math.pi/2,0),material=steel,body=wb,bevel=.001)
        v4.joint(f'wheel_axle_{i}_{side}','continuous',cb,wb,(x+sx*.041,y,.046),(1,0,0))
    hood=v4.sphere(f'caster_twinwheel_hood_{i}',1.0,(x,y,.123),material=black,body=cb)
    hood.scale=(.070,.049,.021)
    v4.joint(f'caster_swivel_{i}','continuous',base,cb,(x,y,.105),(0,0,1))

# Telescoping lift member. The outer shroud is stationary; polished piston travels with seat.
lift=v4.body('lift_column')
v4.lathe('polished_lift_piston',[(0,.37),(.025,.37),(.026,.42),(.026,.57),(.035,.59),(.035,.61),(0,.61)], material=steel,body=lift)
v4.cylinder('upper_lift_collarette',.052,.018,(0,0,.593),material=gunmetal,body=lift,bevel=.003)
v4.joint('column_lift','prismatic',base,lift,(0,0,.38),(0,0,1),limits=(0,.10))

seat=v4.body('seat')
# Under-seat stamped tilt plate and seat shell
v4.box('tilt_mechanism_pan',(.34,.34,.045),(0,.04,.555),bevel=.018,material=gunmetal,body=seat)
v4.box('tilt_mechanism_cover',(.30,.27,.038),(0,.045,.518),bevel=.014,material=black,body=seat)
v4.cylinder('tilt_tension_knob_stem',.014,.050,(.181,-.035,.535),rot=(0,math.pi/2,0),material=steel,body=seat,bevel=.002)
v4.cylinder('tilt_tension_knob',.032,.024,(.215,-.035,.535),rot=(0,math.pi/2,0),material=black,body=seat,bevel=.006)
for k in range(8):
    ang=2*math.pi*k/8
    v4.box(f'tilt_knob_grip_{k}',(.006,.007,.020),(.229,-.035+.027*math.cos(ang),.535+.027*math.sin(ang)),rot=(ang,0,0),bevel=.002,material=gunmetal,body=seat)
v4.box('seat_shell_bucket',(.49,.48,.075),(0,-.005,.615),bevel=.055,material=black,body=seat)
v4.box('seat_cushion_main',(.475,.45,.085),(0,-.025,.675),bevel=.065,material=charcoal,body=seat)
# Rounded waterfall front and contrast side skins complete the upholstered bucket.
v4.rod('seat_waterfall_front',(-.205,-.235,.665),(.205,-.235,.665),.038,material=charcoal,body=seat)
# Raised bucket wings along both sides, with red outer piping.
for sx in (-1,1):
    v4.rod(f'seat_bolster_{sx}',(sx*.205,-.18,.68),(sx*.235,.14,.72),.043,material=black,body=seat)
    v4.rod(f'seat_bolster_red_bead_{sx}',(sx*.229,-.17,.703),(sx*.255,.13,.743),.005,material=red,body=seat)
    v4.box(f'seat_red_side_panel_{sx}',(.026,.31,.055),(sx*.235,-.035,.675),bevel=.014,material=red,body=seat)
# Seat center panel and stitched transverse breaks
v4.box('seat_center_insert',(.25,.34,.008),(0,-.035,.72),bevel=.04,material=soft,body=seat)
for yy in (-.145,-.075,-.005,.065):
    v4.tube(f'seat_stitch_{yy}',[(-.115,yy,.725),(.115,yy,.725)],.0012,material=seam,body=seat)
# Rear hinge plates and cover, plus visible pivot caps
for sx in (-1,1):
    v4.box(f'recline_hinge_plate_{sx}',(.045,.085,.115),(sx*.225,.15,.615),rot=(0,0,sx*.08),bevel=.009,material=gunmetal,body=seat)
    v4.cylinder(f'recline_pivot_bolt_{sx}',.018,.012,(sx*.228,.16,.60),rot=(0,math.pi/2,0),material=steel,body=seat,bevel=.002)
# Gas lift swivel joint at center; seat body is child of lift column.
v4.joint('seat_swivel','continuous',lift,seat,(0,0,.59),(0,0,1))

# Reclining back shell, attached on a left-right hinge at rear seat edge.
back=v4.body('back')
shell_profile=[(0,.215),(.12,.235),(.30,.245),(.48,.235),(.62,.207),(.72,.184),(.79,.158)]
pad_profile=[(.025,.18),(.14,.205),(.32,.216),(.50,.205),(.64,.181),(.72,.155),(.75,.13)]
curved_panel('back_moulded_shell',shell_profile,.60,.145,-.045,.060,black,back)
curved_panel('back_padded_face',pad_profile,.60,.125,-.070,.055,charcoal,back)
# Racing center insert and tailored center ventilation panel.
v4.box('back_center_red_panel',(.205,.060,.55),(0,.155,1.00),bevel=.026,material=red_fabric,body=back)
v4.box('back_center_mesh',(.145,.030,.24),(0,.125,1.045),bevel=.018,material=soft,body=back)
# Deep rounded bucket wings are fused into the shell edge and flare at shoulder height.
wing_profile=[(.07,.225,.027,.055),(.20,.235,.032,.070),(.36,.245,.034,.075),
              (.52,.225,.031,.070),(.65,.198,.027,.064),(.74,.175,.022,.055),(.79,.158,.018,.045)]
for sx in (-1,1):
    bucket_wing(f'back_upholstered_wing_{sx}',sx,wing_profile,charcoal,back)
# Low-profile harness pass-throughs sit behind the neck cushion, below the back crown.
for sx in (-1,1):
    cx=sx*.095
    v4.box(f'harness_slot_lip_{sx}',(.039,.012,.048),(cx,.100,1.105),bevel=.008,material=gunmetal,body=back)
    v4.box(f'harness_opening_{sx}',(.026,.014,.036),(cx,.097,1.105),bevel=.007,material=black,body=back)
# Integral hinge ears overlap the lower shell edge, avoiding loose pin-like islands.
for sx in (-1,1):
    v4.box(f'back_hinge_ear_{sx}',(.11,.10,.10),(sx*.19,.175,.64),bevel=.012,material=gunmetal,body=back)
    v4.cylinder(f'back_hinge_cap_{sx}',.018,.014,(sx*.235,.16,.60),rot=(0,math.pi/2,0),material=steel,body=back,bevel=.002)
v4.joint('back_recline','revolute',seat,back,(0,.16,.60),(1,0,0),limits=(-1.50,0))

# Puffy neck pillow with flat 25 mm webbing leading into the lower shell slots.
neck=v4.body('neck_pad')
v4.box('neck_cushion_core',(.270,.130,.140),(0,.035,1.225),bevel=.064,material=black,body=neck)
v4.box('neck_cushion_face',(.230,.060,.105),(0,-.035,1.225),bevel=.047,material=red_fabric,body=neck)
for sx in (-1,1):
    strap_x=sx*.095
    # Flat 25 mm webbing runs from the upper pillow corners down the shell into the lower slots.
    strap_len=math.sqrt(.185**2+.114**2)
    strap_angle=math.degrees(math.atan2(.114,.185))
    v4.box(f'neck_strap_run_{sx}',(.025,.003,strap_len),(strap_x,.039,1.1925),rot=(math.radians(strap_angle),0,0),bevel=.002,material=red,body=neck)
    v4.tube(f'neck_pillow_stitch_{sx}',[(sx*.087,-.066,1.19),(sx*.087,-.066,1.26)],.0015,material=seam,body=neck)
v4.joint('neck_cushion_hinge','revolute',back,neck,(0,.100,1.295),(1,0,0),limits=(-.22,.22))

lumbar=v4.body('lumbar_pad')
v4.box('lumbar_cushion_core',(.31,.09,.16),(0,.055,.80),bevel=.06,material=black,body=lumbar)
v4.box('lumbar_cushion_face',(.275,.012,.125),(0,.005,.80),bevel=.052,material=red_fabric,body=lumbar)
v4.tube('lumbar_top_stitch',[(-.11,-.004,.85),(.11,-.004,.85)],.0015,material=seam,body=lumbar)
for sx in (-1,1):
    v4.box(f'lumbar_strap_{sx}',(.03,.22,.014),(sx*.105,.125,.80),bevel=.004,material=black,body=lumbar)
    v4.box(f'lumbar_buckle_{sx}',(.035,.012,.025),(sx*.105,.215,.80),bevel=.004,material=steel,body=lumbar)
v4.joint('lumbar_cushion_hinge','revolute',back,lumbar,(0,.100,.88),(1,0,0),limits=(-.18,.18))

# Height-adjustable arm assemblies on either side of seat.
for sx,label in [(-1,'L'),(1,'R')]:
    arm=v4.body(f'arm_{label}')
    x=sx*.30
    v4.box(f'arm_post_{label}',(.034,.055,.30),(x,-.005,.715),bevel=.008,material=gunmetal,body=arm)
    pad_x=sx*.32
    v4.box(f'arm_cap_{label}',(.115,.245,.052),(pad_x,-.005,.875),bevel=.024,material=black,body=arm)
    v4.box(f'arm_pad_{label}',(.102,.22,.020),(pad_x,-.005,.911),bevel=.012,material=soft,body=arm)
    v4.box(f'arm_post_bridge_{label}',(.050,.055,.045),(sx*.31,-.005,.852),bevel=.009,material=gunmetal,body=arm)
    v4.cylinder(f'arm_height_clamp_{label}',.018,.012,(x-sx*.020,-.01,.80),rot=(0,math.pi/2,0),material=red,body=arm,bevel=.003)
    v4.cylinder(f'arm_clamp_button_{label}',.009,.014,(x-sx*.030,-.01,.80),rot=(0,math.pi/2,0),material=steel,body=arm,bevel=.002)
    # Matched L-shaped under-seat brackets and a hollow four-wall post receiver.
    for side in (-1,1):
        bx=x+side*.040
        v4.box(f'arm_bracket_foot_{label}_{side}',(.032,.115,.014),(bx,-.005,.578),bevel=.004,material=gunmetal,body=seat)
        v4.box(f'arm_bracket_upright_{label}_{side}',(.012,.070,.145),(x+side*.026,-.005,.645),bevel=.004,material=gunmetal,body=seat)
        v4.box(f'arm_guide_side_{label}_{side}',(.006,.092,.105),(x+side*.021,-.005,.716),bevel=.002,material=black,body=seat)
        for yy in (-.040,.030):
            v4.cylinder(f'arm_bracket_bolt_{label}_{side}_{yy}',.006,.004,(bx,yy,.569),material=steel,body=seat,bevel=.001)
    for side in (-1,1):
        v4.box(f'arm_guide_front_{label}_{side}',(.050,.006,.105),(x,-.005+side*.035,.716),bevel=.002,material=black,body=seat)
    v4.joint(f'arm_height_{label}','prismatic',seat,arm,(sx*.30,-.005,.69),(0,0,1),limits=(0,.075))

# Functional under-seat tilt-lock lever with a reachable red polymer grip.
# A narrow transverse pivot boss meets the lever shaft at the pin's outboard end.
v4.box('tilt_lever_pivot_mount',(.095,.050,.022),(.185,-.10,.55),bevel=.006,material=gunmetal,body=seat)
v4.cylinder('tilt_lever_pivot_boss',.0095,.040,(.22,-.10,.55),rot=(0,math.pi/2,0),material=steel,body=seat,bevel=.001)
lever=v4.body('tilt_lever')
v4.rod('tilt_lever_shaft',(.24,-.10,.55),(.31,-.19,.49),.008,material=steel,body=lever)
v4.box('tilt_lever_grip',(.035,.12,.035),(.31,-.235,.485),rot=(0,.55,0),bevel=.014,material=red,body=lever)
v4.joint('tilt_lock','revolute',seat,lever,(.22,-.10,.55),(1,0,0),limits=(-.18,.18))

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