"""Detailed adjustable piano stool. Run with Blender in background."""
import math, os, sys
import bpy
from mathutils import Vector
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4

v4.reset()
# Materials
walnut = v4.wood("satin_walnut", light=(0.40, 0.22, 0.12), dark=(0.19, 0.085, 0.04), grain_scale=5.5, roughness=0.31, coat=0.32)
walnut_edge = v4.wood("walnut_endgrain", light=(0.32, 0.16, 0.075), dark=(0.15, 0.06, 0.025), grain_scale=8, roughness=0.36)
steel = v4.metal("satin_nickel", color=(0.72, 0.75, 0.78), roughness=0.30)
black_steel = v4.metal("blackened_steel", color=(0.16, 0.17, 0.18), roughness=0.36, brushed=False)
brass = v4.metal("aged_brass", color=(0.62, 0.39, 0.16), roughness=0.3, brushed=False)
leather = v4.mat("oxblood_leatherette", (0.12, 0.018, 0.025), roughness=0.72)
felt = v4.fabric("music_well_felt", (0.12, 0.105, 0.09), weave_scale=140)
rubber = v4.rubber("glide_rubber", (0.055, 0.052, 0.048))

base = v4.body("base")
carriage = v4.body("lift_carriage")
seat = v4.body("seat")
lid = v4.body("lid")

# Cabriole leg sweep with a bowed knee and tapered ankle, plus turned bun feet.
def cabriole_leg(name,sx,sy,body,material):
    # A tapered cabriole sweep enters the hub sideways; radii run from 30 mm at the foot
    # to 45 mm at the socket, with a restrained knee swell.
    p0=Vector((sx*0.205,sy*0.155,0.044))
    p1=Vector((sx*0.205,sy*0.155,0.108))
    p2=Vector((sx*0.176,sy*0.132,0.218))
    # The hidden end stops inside the side wall of the hub, below its top shoulder.
    p3=Vector((sx*0.050,sy*0.040,0.235))
    knots=((0.0,0.015),(0.14,0.017),(0.47,0.026),(0.76,0.023),(1.0,0.0225))
    rings=[]
    for i in range(41):
        t=i/40.0; u=1.0-t
        c=p0*u**3+3*p1*u*u*t+3*p2*u*t*t+p3*t**3
        tangent=(3*u*u*(p1-p0)+6*u*t*(p2-p1)+3*t*t*(p3-p2)).normalized()
        reference=Vector((0,0,1))
        if abs(tangent.dot(reference))>0.98:
            reference=Vector((1,0,0))
        side=tangent.cross(reference).normalized()
        normal=tangent.cross(side).normalized()
        radius=knots[-1][1]
        for (ta,ra),(tb,rb) in zip(knots,knots[1:]):
            if ta<=t<=tb:
                q=(t-ta)/(tb-ta); radius=ra*(1-q)+rb*q; break
        ring=[]
        for j in range(24):
            a=2*math.pi*j/24
            ring.append(tuple(c+radius*(math.cos(a)*side+math.sin(a)*normal)))
        rings.append(ring)
    verts=[v for ring in rings for v in ring]; faces=[]
    for i in range(len(rings)-1):
        for j in range(24):
            a=i*24+j; b=i*24+(j+1)%24; faces.append((a,b,b+24,a+24))
    faces.append(tuple(reversed(range(24))))
    faces.append(tuple((len(rings)-1)*24+j for j in range(24)))
    mesh=bpy.data.meshes.new(name+"_mesh"); mesh.from_pydata(verts,[],faces); mesh.update()
    obj=bpy.data.objects.new(name,mesh); v4._link(obj); v4.assign(obj,material); v4.part(obj,body)
    for poly in mesh.polygons: poly.use_smooth=True
    return obj

for sx in (-1,1):
    for sy in (-1,1):
        idx=(1 if sx>0 else 0)+(2 if sy>0 else 0)
        fx,fy=sx*0.205,sy*0.155
        v4.cylinder(f"glide_{idx}",0.029,0.008,(fx,fy,0.004),bevel=0.001,material=rubber,body=base)
        v4.lathe(f"bun_foot_{idx}",[(0,0.008),(0.024,0.008),(0.034,0.014),(0.038,0.025),(0.034,0.038),(0.016,0.051),(0,0.053)],loc=(fx,fy,0),material=walnut,body=base)
        cabriole_leg(f"cabriole_leg_{idx}",sx,sy,base,walnut_edge)
        # Brass sockets sit over each leg's side entry into the turned central hub.
        socket_axis=Vector((-sx*0.126,-sy*0.092,0.017)).normalized()
        socket_rot=socket_axis.to_track_quat('Z','Y').to_euler()
        socket_loc=(sx*0.073,sy*0.054,0.230)
        v4.cylinder(f"hub_leg_socket_{idx}",0.024,0.020,loc=socket_loc,rot=socket_rot,bevel=0.0015,material=brass,body=base)
# The four legs remain unobstructed between the floor and central hub; no short braces.
v4.lathe("central_hub",[(0,0.18),(0.070,0.18),(0.084,0.19),(0.094,0.205),(0.096,0.224),(0.089,0.237),(0.086,0.245),(0.090,0.252),(0.096,0.267),(0.093,0.280),(0.084,0.290),(0,0.290)],material=walnut,body=base)
# Fixed screw spindle; fine close-pitch helical ridge gives the coarse adjustment screw its readable profile.
v4.cylinder("fixed_screw_core",0.014,0.12,loc=(0,0,0.345),bevel=0.001,material=black_steel,body=base)
v4.cylinder("screw_lower_anchor",0.021,0.006,loc=(0,0,0.290),material=steel,body=base)
v4.cylinder("screw_upper_stop",0.023,0.014,loc=(0,0,0.394),material=steel,body=base)
helix=[]
for i in range(1200):
    t=i/1199
    a=t*2*math.pi*15
    z=0.285+t*0.12
    helix.append((0.016*math.cos(a),0.016*math.sin(a),z))
v4.tube("coarse_thread",helix,0.0030,material=steel,body=base,resolution=6)
# Small spindle end cap and anchor bolts.
v4.cylinder("spindle_cap",0.017,0.012,loc=(0,0,0.394),material=black_steel,body=base)
for i in range(4):
    a=math.pi/4+i*math.pi/2
    x,y=0.060*math.cos(a),0.060*math.sin(a)
    v4.cylinder(f"hub_bolt_{i}",0.004,0.004,loc=(x,y,0.290),material=steel,body=base)

# Lift carriage: compact threaded nut housing and a machined swivel thrust bearing.
# Its lowest skirt moves around the fixed spindle; the seat sits on the upper race.
v4.cylinder("nut_housing",0.036,0.052,loc=(0,0,0.346),material=black_steel,body=carriage)
v4.cylinder("nut_collar_lower",0.043,0.009,loc=(0,0,0.320),material=steel,body=carriage)
v4.cylinder("nut_collar_upper",0.043,0.009,loc=(0,0,0.372),material=steel,body=carriage)
v4.cylinder("carriage_neck",0.028,0.022,loc=(0,0,0.375),material=black_steel,body=carriage)
v4.cylinder("thrust_bearing_lower",0.083,0.018,loc=(0,0,0.372),material=black_steel,body=carriage)
v4.torus("bearing_race",0.067,0.006,loc=(0,0,0.383),material=steel,body=carriage)
v4.cylinder("bearing_top_plate",0.078,0.012,loc=(0,0,0.391),material=steel,body=carriage)
for i in range(8):
    a=2*math.pi*i/8
    v4.sphere(f"bearing_ball_{i}",0.004,loc=(0.067*math.cos(a),0.067*math.sin(a),0.384),material=steel,body=carriage)
v4.joint("height_adjustment","prismatic",base,carriage,origin=(0,0,0.30),axis=(0,0,1),limits=(0,0.12))

# Seat carcass and real shallow sheet-music well. All pieces below are rigid with seat.
# Outer size 460 x 360 mm, seat frame floor at z=.405 and top rim at z=.488.
# Board floor and walls fit edge to edge around the 320 x 245 mm lined cavity.
v4.box("seat_bearing_pad",(0.12,0.12,0.030),loc=(0,0,0.415),bevel=0.002,material=walnut,body=seat)
v4.box("well_floor",(0.330,0.267,0.012),loc=(0,0,0.436),bevel=0.001,material=walnut_edge,body=seat)
# Felt liner slightly proud of the well bottom.
v4.box("well_lining",(0.320,0.257,0.002),loc=(0,0,0.443),bevel=0.001,material=felt,body=seat)
# Well walls, 10 mm thick, terminate exactly at the floor and perimeter frame.
for x in (-0.166,0.166):
    v4.box(f"well_side_{x}",(0.010,0.267,0.050),loc=(x,0,0.459),bevel=0.001,material=walnut_edge,body=seat)
for y in (-0.1335,0.1335):
    v4.box(f"well_end_{y}",(0.330,0.010,0.050),loc=(0,y,0.459),bevel=0.001,material=walnut_edge,body=seat)
# Outer apron surrounds the open well with a broad, rounded hardwood frame.
# Rails fit corner-to-corner; a subtle lower bead follows each apron side.
for x in (-0.222,0.222):
    v4.box(f"seat_apron_side_{x}",(0.016,0.326,0.050),loc=(x,0,0.458),bevel=0,material=walnut,body=seat)
for y in (-0.155,0.155):
    v4.box(f"seat_apron_frontback_{y}",(0.460,0.016,0.050),loc=(0,y,0.458),bevel=0,material=walnut,body=seat)
# Narrow brass corner guards finish the apron rail joins and protect the exposed end grain.
for sx in (-1,1):
    for sy in (-1,1):
        v4.box(f"apron_corner_guard_front_{sx}_{sy}",(0.014,0.003,0.044),loc=(sx*0.222,sy*0.1615,0.458),bevel=0.001,material=brass,body=seat)
        v4.box(f"apron_corner_guard_side_{sx}_{sy}",(0.003,0.014,0.044),loc=(sx*0.2285,sy*0.155,0.458),bevel=0.001,material=brass,body=seat)
# Lip around lid opening, leaving a narrow shadow line; hardwood support ledges beneath lid.
for x in (-0.190,0.190):
    v4.box(f"lid_landing_side_{x}",(0.040,0.324,0.014),loc=(x,-0.002,0.487),bevel=0.001,material=walnut,body=seat)
for y in (-0.150,0.146):
    v4.box(f"lid_landing_end_{y}",(0.380,0.036,0.014),loc=(0,y,0.487),bevel=0.001,material=walnut,body=seat)
# Seat-side hinge leaves and screw heads are mounted to the seat body at the rear edge.
hinge_y=0.164

# Hinged lid: thin hardwood core, upholstered cushion, piping, and matching hinge leaves.
v4.box("lid_board",(0.420,0.332,0.016),loc=(0,-0.002,0.501),bevel=0.004,material=walnut,body=lid)
v4.box("cushion_core",(0.406,0.314,0.036),loc=(0,-0.002,0.527),bevel=0.012,material=leather,body=lid)
# Rounded rectangular leather dome, backed into the cushion core as one padded assembly.
dome_a,dome_b=0.198,0.153
dome_edge_z,dome_rise=0.545,0.015
dome_nr,dome_na=24,96
dome_verts=[(0.0,0.0,dome_edge_z+dome_rise)]
def dome_boundary(theta):
    c,s=math.cos(theta),math.sin(theta)
    return (abs(c)**8+abs(s)**8)**(-1.0/8.0)
for ir in range(1,dome_nr+1):
    rho=ir/dome_nr
    for j in range(dome_na):
        theta=2*math.pi*j/dome_na
        edge=dome_boundary(theta)
        x=dome_a*rho*edge*math.cos(theta)
        y=dome_b*rho*edge*math.sin(theta)
        z=dome_edge_z+dome_rise*(1-rho*rho)
        dome_verts.append((x,y,z))
dome_faces=[]
for j in range(dome_na):
    dome_faces.append((0,1+j,1+(j+1)%dome_na))
for ir in range(1,dome_nr):
    inner=1+(ir-1)*dome_na; outer=1+ir*dome_na
    for j in range(dome_na):
        jn=(j+1)%dome_na
        dome_faces.append((inner+j,outer+j,outer+jn,inner+jn))
outer=1+(dome_nr-1)*dome_na
bottom=len(dome_verts)
for j in range(dome_na):
    theta=2*math.pi*j/dome_na; edge=dome_boundary(theta)
    dome_verts.append((dome_a*edge*math.cos(theta),dome_b*edge*math.sin(theta),0.543))
bottom_center=len(dome_verts); dome_verts.append((0,0,0.543))
for j in range(dome_na):
    jn=(j+1)%dome_na
    dome_faces.append((outer+j,bottom+j,bottom+jn,outer+jn))
    dome_faces.append((bottom_center,bottom+jn,bottom+j))
dome_mesh=bpy.data.meshes.new("upholstery_dome_mesh")
dome_mesh.from_pydata(dome_verts,[],dome_faces); dome_mesh.update()
dome_obj=bpy.data.objects.new("upholstery_dome",dome_mesh); v4._link(dome_obj)
v4.assign(dome_obj,leather); v4.part(dome_obj,lid)
for poly in dome_mesh.polygons: poly.use_smooth=True
# Piping follows the domed cushion's soft superelliptic perimeter.
piping_path=[]
for j in range(dome_na):
    theta=2*math.pi*j/dome_na; edge=dome_boundary(theta)
    piping_path.append((dome_a*edge*math.cos(theta),dome_b*edge*math.sin(theta),dome_edge_z))
v4.tube("cushion_piping",piping_path,0.0018,material=brass,body=lid,cyclic=True)
# Five leather-covered upholstery buttons sit slightly proud of the padded surface.
button_mat=v4.mat("tuft_button_leather",(0.065,0.009,0.014),roughness=0.72)
for i,(x,y) in enumerate(((0,0),(-0.105,-0.070),(0.105,-0.070),(-0.105,0.070),(0.105,0.070))):
    rho=(abs(x/dome_a)**8+abs(y/dome_b)**8)**(1.0/8.0)
    surface=dome_edge_z+dome_rise*(1-rho*rho)
    v4.sphere(f"tuft_button_{i}",0.0048,loc=(x,y,surface-0.0025),material=button_mat,body=lid)
v4.box("lid_finger_pull",(0.050,0.008,0.012),loc=(0,-0.169,0.498),bevel=0.003,material=brass,body=lid)
# Underside lid battens prevent cupping and stay within lid's rigid body.
v4.box("lid_underfelt",(0.416,0.328,0.004),loc=(0,-0.002,0.493),bevel=0.002,material=felt,body=lid)
for x in (-0.13,0.13):
    v4.box(f"lid_batten_{x}",(0.012,0.218,0.012),loc=(x,-0.001,0.486),bevel=0.001,material=walnut,body=lid)
# Fixed knuckles alternate with the lid knuckles along their shared steel pin axis.
for x in (-0.06,0.06):
    v4.cylinder(f"hinge_knuckle_seat_{x}",0.006,0.045,loc=(x,hinge_y,0.493),rot=(0,math.pi/2,0),material=brass,body=seat)
# Hinge barrels centered on the pivot line (parallel X). Two short knuckles and pins.
for x in (-0.12,0.12):
    v4.cylinder(f"hinge_knuckle_{x}",0.006,0.045,loc=(x,hinge_y,0.493),rot=(0,math.pi/2,0),material=brass,body=lid)
    v4.cylinder(f"hinge_pin_{x}",0.0018,0.049,loc=(x,hinge_y,0.493),rot=(0,math.pi/2,0),material=steel,body=lid)
# Front lift tab lets the lid open without a conspicuous handle.

# Small brass maker badge on front apron; raised lettering is mounted on the same seat body.
v4.box("maker_badge",(0.068,0.0018,0.022),loc=(0,-0.164,0.458),bevel=0.002,material=brass,body=seat)
# maker badge kept unlettered for clean, attached geometry
# Small decorative apron fasteners in all four corners.

# Seat swivel rotates continuously; rear-edge lid hinge opens to show the lined music well.
v4.joint("seat_swivel","continuous",carriage,seat,origin=(0,0,0.400),axis=(0,0,1))
v4.joint("lid_hinge","revolute",seat,lid,origin=(0,hinge_y,0.493),axis=(1,0,0),limits=(-math.radians(105),0))

# Join each rigid body's meshes so attached hardware is one collision-aware assembly.
for b in v4.bodies():
    pieces=[o for o in bpy.context.scene.objects if o.type=="MESH" and o.parent==b]
    if len(pieces)>1:
        bpy.ops.object.select_all(action="DESELECT")
        for o in pieces: o.select_set(True)
        bpy.context.view_layer.objects.active=pieces[0]
        bpy.ops.object.join()
        pieces[0].name=f"{b['v4_name']}_assembly"

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