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

v4.reset()
# materials
steel = v4.metal('satin_stainless', (0.72, 0.76, 0.79), roughness=0.28)
leg_steel = v4.metal('brushed_leg_steel', (0.48, 0.52, 0.55), roughness=0.34)
bright = v4.metal('polished_steel', (0.88, 0.90, 0.92), roughness=0.18, brushed=False)
brass = v4.metal('warm_brass', (0.78, 0.52, 0.22), roughness=0.26, brushed=False)
darksteel = v4.metal('darkened_steel', (0.18, 0.20, 0.21), roughness=0.35)
graphite = v4.mat('graphite', (0.045, 0.04, 0.035), metallic=0.08, roughness=0.72)

P = (0.0, 0.0, 0.190)
H = v4.body('hinge_fixed')
HM = v4.body('hinge_swing')
LN = v4.body('leg_needle')
LL = v4.body('leg_lead')
S = v4.body('adjust_screw')

# helpers
def cyl_y(name, r, depth, loc, material, body, bevel=0.0004):
    return v4.cylinder(name, r, depth, loc, rot=(math.pi/2,0,0), segments=48,
                       bevel=bevel, material=material, body=body)

def box_rot(name,size,loc,angle,material,body,bevel=0.0008):
    return v4.box(name,size,loc,rot=(0,angle,0),bevel=bevel,material=material,body=body)

def pin(name, a, b, r, material, body):
    return v4.rod(name,a,b,r,segments=32,bevel=0.00025,material=material,body=body)


def tapered_bar(name,p0,p1,r0,r1,material,body):
    p0,p1=Vector(p0),Vector(p1)
    d=p1-p0
    o=v4.cylinder(name,r0,d.length,(p0+p1)/2,radius_top=r1,segments=32,bevel=0.00025,material=material)
    o.rotation_euler=d.to_track_quat('Z','Y').to_euler()
    v4.part(o,body)
    return o

# Precision double-disc knuckle. The two cheeks occupy separate Y layers.
v4.cylinder('fixed_knuckle_disc',0.008,0.0035,(0,0.0025,0.190),rot=(math.pi/2,0,0),segments=64,bevel=0.0008,material=steel,body=H)
v4.cylinder('moving_knuckle_disc',0.008,0.0035,(0,-0.0025,0.190),rot=(math.pi/2,0,0),segments=64,bevel=0.0008,material=steel,body=HM)
# Small neck seated on the upper rim supports the rotating top grip.
v4.cylinder('handle_neck',0.003,0.006,(0,0,0.201),segments=40,bevel=0.0005,material=steel,body=H)
# Through-pivot screw heads are flush with the outer face of each cheek.
cyl_y('pivot_screw_back',0.0032,0.0012,(0,0.00485,0.190),bright,H,0.00025)
cyl_y('pivot_screw_front',0.0032,0.0012,(0,-0.00485,0.190),bright,HM,0.00025)
# Shallow slots identify these as fasteners rather than decorative dots.
v4.box('pivot_slot_back',(0.0028,0.00035,0.00045),(0,0.00555,0.190),bevel=0.0001,material=darksteel,body=H)
v4.box('pivot_slot_front',(0.0028,0.00035,0.00045),(0,-0.00555,0.190),bevel=0.0001,material=darksteel,body=HM)

# Compass legs: narrow tapered steel bars, with forked upper hinge knuckles.
# Define practical open resting spread; tapered cylindrical shanks are built as contiguous sections.
top = Vector((0,0,0.178))
tipz = 0.012
for sign, body, label in [(-1,LN,'needle'),(1,LL,'lead')]:
    ylayer = -0.004 if sign > 0 else 0.004
    tip = Vector((sign*0.038,ylayer,tipz))
    # A continuous forged taper narrows toward the drawing point.
    start = Vector((sign*0.006,ylayer,0.169))
    shaft_end = tip+Vector((0,0,0.008))
    tapered_bar(label+'_tapered_shank',start,shaft_end,0.0025,0.00135,leg_steel,body)
    # Forked tang arms flank the round knuckle disc on its two faces, forming a compact clevis.
    outside_y = 0.00495 if sign < 0 else -0.00495
    inside_y = 0.0
    pin(label+'_fork_bridge',(sign*0.006,outside_y,0.169),(sign*0.006,inside_y,0.169),0.0009,leg_steel,body)
    for side,yfork in [('outer',outside_y),('inner',inside_y)]:
        tapered_bar(label+'_fork_'+side,
                    (sign*0.006,yfork,0.169),(sign*0.0055,yfork,0.196),
                    0.00065,0.00065,leg_steel,body)
    # Fine seam ring marks the sliding extension collar partway down each leg.
    axis=(shaft_end-start).normalized()
    mid_collar=start.lerp(shaft_end,0.56)
    rot=axis.to_track_quat('Z','Y').to_euler()
    v4.torus(label+'_extension_seam',0.00195,0.0004,loc=mid_collar,rot=rot,segments=48,ring_segments=12,material=bright,body=body)

# Needle point: tapered steel cone extends from the lower end of left leg toward paper.
# The fine point is almost vertical in the open pose, joined into the leg socket.
v4.cylinder('needle_socket',0.0028,0.008,(-0.038,0.004,0.016),rot=(0,math.pi,0),radius_top=0.0018,
            segments=40,bevel=0.0003,material=bright,body=LN)
v4.cylinder('needle_chuck_shoulder',0.0035,0.002,(-0.038,0.004,0.011),segments=40,bevel=0.0003,material=leg_steel,body=LN)
pin('needle_chuck_screw_stem',(-0.038,0.004,0.014),(-0.038,0.0008,0.014),0.0010,bright,LN)
cyl_y('needle_chuck_screw_head',0.0018,0.0016,(-0.038,0.0004,0.014),bright,LN,0.0002)
v4.box('needle_chuck_screw_slot',(0.0013,0.0003,0.0003),(-0.038,-0.00055,0.014),bevel=0.00008,material=darksteel,body=LN)
v4.cylinder('needle_point',0.00012,0.012,(-0.038,0.004,0.004),rot=(0,0,0),radius_top=0.0017,
            segments=24,bevel=0,material=bright,body=LN)

# Lead holder at right leg: brass split clamp and pencil lead, angled to follow compass leg.
# Collar and fork grip a short graphite stub; small tightening screw faces camera.
ang = math.atan2(0.038, -(0.190-tipz))
# Hold the pencil just outboard of leg; its axis parallels the leg.
v4.rod('holder_neck', (0.035,-0.006,0.030),(0.041,-0.006,0.010),0.0030,material=brass,body=LL)
# split fork side rails around the graphite, fit and meet the collar
v4.rod('clamp_fork_left',(0.038,-0.008,0.019),(0.042,-0.008,0.009),0.0012,material=brass,body=LL)
v4.rod('clamp_fork_right',(0.038,0.000,0.019),(0.042,0.000,0.009),0.0012,material=brass,body=LL)
# collar along pencil axis
v4.cylinder('brass_lead_collar',0.0042,0.008,(0.042,-0.004,0.009),rot=(0,ang,0),radius_top=0.0035,segments=40,bevel=0.0004,material=brass,body=LL)
tapered_bar('graphite_lead',(0.042,-0.004,0.008),(0.0455,-0.004,-0.0003),0.00135,0.00008,graphite,LL)
# side clamp screw, radial to the holder collar
pin('lead_clamp_screw',(0.042,-0.0082,0.009),(0.042,-0.012,0.009),0.0014,bright,LL)
cyl_y('lead_clamp_head',0.0022,0.0016,(0.042,-0.0126,0.009),brass,LL,0.0003)
v4.box('lead_clamp_slot',(0.0018,0.00035,0.00035),(0.042,-0.01345,0.009),bevel=0.00008,material=darksteel,body=LL)

# Compact central adjuster: a short stem and a 4 mm by 15 mm vertical knurled handle.
v4.cylinder('screw_stem',0.0018,0.005,(0,0,0.2045),segments=32,bevel=0.0002,material=bright,body=S)
v4.cylinder('handle_shoulder',0.003,0.0015,(0,0,0.2068),segments=40,bevel=0.00025,material=brass,body=S)
v4.cylinder('thumbwheel_core',0.00175,0.015,(0,0,0.2135),radius_top=0.0020,segments=48,bevel=0.00035,material=brass,body=S)
# Crossed helical lines cut the grip into a fine diamond knurl.
z0,z1=0.2065,0.2205
for direction in (-1,1):
    for band in range(12):
        pts=[]
        for k in range(49):
            t=k/48
            z=z0+(z1-z0)*t
            core_r=0.00175+0.00025*(z-0.206)/0.015
            theta=2*math.pi*band/12+direction*2*math.pi*9*t
            r=core_r+0.000045
            pts.append((r*math.cos(theta),r*math.sin(theta),z))
        v4.tube('handle_diamond_knurl_%s_%02d'%('p' if direction>0 else 'm',band),pts,0.000085,material=bright,body=S,resolution=2)

# Limiting arcs; all zero poses retain the modeled open stance.
v4.joint('hinge_pivot','revolute',H,HM,origin=P,axis=(0,-1,0),limits=(-math.radians(12),math.radians(40)))
v4.joint('needle_leg_hinge','revolute',H,LN,origin=P,axis=(0,1,0),limits=(-math.radians(12),math.radians(40)))
v4.joint('lead_leg_hinge','fixed',HM,LL,origin=P,axis=(0,1,0))
v4.joint('thumb_screw','revolute',H,S,origin=(0,0,0.202),axis=(0,0,1),limits=(-math.radians(150),math.radians(150)))

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