"""Compact manual cigarette roller with bed-mounted rollers and side crank."""
import math, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import bpy
import v4lib as v4

v4.reset()
enamel = v4.painted("graphite_blue_enamel", (0.17,0.22,0.25), roughness=0.28, coat=0.7)
steel = v4.metal("satin_stainless", (0.72,0.75,0.76), roughness=0.29, brushed=True)
bright = v4.metal("polished_edge", (0.83,0.84,0.82), roughness=0.2, brushed=False)
rubber = v4.rubber("black_nitrile", (0.035,0.043,0.046), roughness=0.76)
canvas = v4.fabric("tobacco_canvas", (0.42,0.30,0.17), weave_scale=220)
apron_edge = v4.fabric("apron_edge_binding", (0.24,0.16,0.085), weave_scale=150)
drive_belt = v4.rubber("drive_belt", (0.055,0.062,0.064), roughness=0.68)
bronze = v4.metal("warm_bearing_bronze", (0.55,0.38,0.20), roughness=0.32, brushed=False)
ink = v4.metal("engraved_badge_ink", (0.77,0.78,0.73), roughness=0.35, brushed=False)

bed = v4.body("roller_bed")
lever = v4.body("side_lever_front_roller")
upper = v4.body("upper_roller")

# Cigarette-scale footprint: 90 mm across the rollers and 65 mm front to back.
BED_X, BED_Y = 0.090, 0.065
zbase = 0.004
base_top = 0.008
front_c = (0.0,-0.018,0.018)
rear_c = (0.0,0.018,0.018)
roller_r = 0.007
roller_len = 0.080

# Folded base and four low rubber feet.
v4.box("pressed_base_pan",(BED_X,BED_Y,0.008),(0,0,zbase),bevel=0.002,material=enamel,body=bed)
for sx in (-1,1):
    for sy in (-1,1):
        v4.cylinder(f"rubber_foot_{sx}_{sy}",0.006,0.004,(sx*0.035,sy*0.023,0.002),bevel=0.0007,material=rubber,body=bed)

# Fixed side cheeks act as the trough walls and carry both roller axles.
for sx in (-1,1):
    x=sx*0.044
    v4.box(f"bearing_cheek_{sx}",(0.006,0.058,0.024),(x,0,0.020),bevel=0.0015,material=enamel,body=bed)
    v4.box(f"cheek_top_fold_{sx}",(0.006,0.054,0.0015),(x,0,0.03275),bevel=0.0005,material=bright,body=bed)
# Small paper insertion lip in front of the front roller. The 2 mm mouth is visible.
v4.box("paper_insert_lip",(0.080,0.003,0.003),(0,-0.030,0.0095),bevel=0.0007,material=bright,body=bed)
# Mounting screws on the exposed base corners.
for sx in (-1,1):
    for sy in (-1,1):
        v4.cylinder(f"base_screw_{sx}_{sy}",0.0023,0.0012,(sx*0.037,sy*0.025,0.0086),bevel=0.0003,material=bright,body=bed)
        v4.box(f"screw_slot_{sx}_{sy}",(0.0026,0.00045,0.00025),(sx*0.037,sy*0.025,0.00925),bevel=0.0001,material=rubber,body=bed)

# Front drive roller and side lever are one rigid rotor around the front roller axle.
v4.cylinder("front_drive_shaft",0.0028,0.100,front_c,rot=(0,math.pi/2,0),bevel=0.0004,material=steel,body=lever)
v4.cylinder("front_drive_roller",roller_r,roller_len,front_c,rot=(0,math.pi/2,0),bevel=0.0008,material=rubber,body=lever)
for sx in (-1,1):
    v4.cylinder(f"front_roller_end_washer_{sx}",0.008,0.0015,(sx*0.041,front_c[1],front_c[2]),rot=(0,math.pi/2,0),bevel=0.0003,material=bright,body=lever)
# A single 64 mm crank arm sits outside the right cheek; a ball knob marks its end.
lever_x=0.050
v4.rod("side_crank_arm",(lever_x,front_c[1],front_c[2]),(lever_x,front_c[1]-0.060,front_c[2]),0.0026,material=steel,body=lever)
v4.cylinder("crank_neck",0.003,0.008,(lever_x,front_c[1]-0.060,front_c[2]),rot=(math.pi/2,0,0),bevel=0.0004,material=bright,body=lever)
v4.sphere("crank_knob",0.006,loc=(lever_x,front_c[1]-0.065,front_c[2]),material=rubber,body=lever)
v4.cylinder("knob_end_button",0.003,0.002,(lever_x,front_c[1]-0.065,front_c[2]),rot=(math.pi/2,0,0),bevel=0.0003,material=bright,body=lever)

# Raised crank hub, bearing washer and visible stop pins on the drive side cheek.
v4.cylinder("crank_hub_boss",0.0072,0.003,(0.050,front_c[1],front_c[2]),
            rot=(0,math.pi/2,0),bevel=0.0005,material=steel,body=lever)
v4.torus("crank_hub_washer",0.0054,0.00065,(0.052,front_c[1],front_c[2]),
         rot=(0,math.pi/2,0),material=bright,body=lever)
# Stops and a small rotating lug make the limited throw legible at the pivot.
stop_r=0.009
stop_start=(front_c[1],front_c[2]+stop_r)
stop_end=(front_c[1]+stop_r*math.sin(math.radians(120)),front_c[2]-stop_r*0.5)
for nm,(sy,sz) in (("start",stop_start),("end",stop_end)):
    v4.cylinder(f"lever_stop_pin_{nm}",0.00115,0.003,(0.049,sy,sz),rot=(0,math.pi/2,0),
                bevel=0.00025,material=bronze,body=bed)
    v4.cylinder(f"lever_stop_pin_cap_{nm}",0.00155,0.0007,(0.051,sy,sz),rot=(0,math.pi/2,0),
                bevel=0.0002,material=bright,body=bed)
v4.sphere("rotating_stop_lug",0.0010,loc=(0.052,front_c[1],front_c[2]+0.0065),material=bronze,body=lever)

# Rear idler roller, fixed in location but free to rotate in the bed cheeks.
v4.cylinder("upper_roller_shaft",0.0025,0.098,rear_c,rot=(0,math.pi/2,0),bevel=0.0004,material=steel,body=upper)
v4.cylinder("upper_idler_roller",roller_r,roller_len,rear_c,rot=(0,math.pi/2,0),bevel=0.0008,material=rubber,body=upper)
for sx in (-1,1):
    v4.cylinder(f"upper_roller_end_washer_{sx}",0.008,0.0015,(sx*0.041,rear_c[1],rear_c[2]),rot=(0,math.pi/2,0),bevel=0.0003,material=bright,body=upper)

# Fine toothed sprockets on the exposed far side and a close-fitting rubber timing
# belt visually connect both roller shafts while keeping the accepted joint tree intact.
def toothed_wheel(name,cy,body_ref):
    teeth=12; root=0.0067; tip=0.0084; depth=0.0026; x0=-0.050; x1=x0+depth
    yz=[]
    for k in range(teeth):
        a=2*math.pi*k/teeth
        for off,r in ((0.00,root),(0.22,root),(0.34,tip),(0.66,tip),(0.78,root)):
            ang=a+off*2*math.pi/teeth
            yz.append((cy+r*math.cos(ang),front_c[2]+r*math.sin(ang)))
    m=len(yz); verts=[(x,y,z) for x in (x0,x1) for y,z in yz]
    faces=[tuple(range(m-1,-1,-1)),tuple(range(m,2*m))]
    for i in range(m):
        j=(i+1)%m; faces.append((i,j,m+j,m+i))
    mesh=bpy.data.meshes.new(name+"_mesh"); mesh.from_pydata(verts,[],faces); mesh.update()
    obj=bpy.data.objects.new(name,mesh); v4._finish(obj,body_ref,steel,0.00025,segments=2,smooth=False)
    v4.torus(name+"_hub_ring",0.0041,0.00055,(x0-0.0001,cy,front_c[2]),
             rot=(0,math.pi/2,0),material=bright,body=body_ref)
    return obj
toothed_wheel("front_timing_sprocket",front_c[1],lever)
toothed_wheel("upper_timing_sprocket",rear_c[1],upper)

# Two-piece bearing collars sit over each shaft opening at both side cheeks.
for sx in (-1,1):
    if sx < 0: # the far-side shaft bushings are integrated into the exposed sprocket hubs
        continue
    bx=sx*0.048
    for nm,cy in (("front",front_c[1]),("rear",rear_c[1])):
        v4.torus(f"{nm}_shaft_bushing_{sx}",0.0038,0.0008,(bx,cy,front_c[2]),
                 rot=(0,math.pi/2,0),material=bronze,body=bed)

# Thin rubber belt band follows two smooth capsule arcs around the sprockets.
belt_r=0.00925; belt_z=front_c[2]; belt_path=[]
for k in range(17):
    a=math.pi/2-math.pi*k/16
    belt_path.append((rear_c[1]+belt_r*math.cos(a),belt_z+belt_r*math.sin(a)))
for k in range(17):
    a=-math.pi/2-math.pi*k/16
    belt_path.append((front_c[1]+belt_r*math.cos(a),belt_z+belt_r*math.sin(a)))
bv=[]
for x in (-0.0497,-0.0487):
    bv.extend((x,y,z) for y,z in belt_path)
bn=len(belt_path); bf=[]
for i in range(bn):
    j=(i+1)%bn; bf.append((i,j,bn+j,bn+i))
belt_mesh=bpy.data.meshes.new("timing_belt_band_mesh"); belt_mesh.from_pydata(bv,[],bf); belt_mesh.update()
belt_obj=bpy.data.objects.new("closed_dark_timing_belt",belt_mesh)
v4._finish(belt_obj,bed,drive_belt,0.00015,smooth=True)

# Thin fabric apron spans the bed as a separate sheet, sagging into a loading trough
# with an open free edge before the rear roller. A short wrapped tip on the front rotor
# turns with it, making the apron movement visible without sweeping the whole sheet down.
profile=[(-0.0123,0.0226),(-0.010,0.020),(-0.006,0.0165),(-0.001,0.0145),
         (0.004,0.015),(0.008,0.017),(0.010,0.020)]
def open_path(points,steps=5):
    out=[]
    for i in range(len(points)-1):
        p0=points[max(0,i-1)]; p1=points[i]; p2=points[i+1]; p3=points[min(len(points)-1,i+2)]
        for k in range(steps):
            t=k/steps; t2=t*t; t3=t2*t
            y=0.5*(2*p1[0]+(-p0[0]+p2[0])*t+(2*p0[0]-5*p1[0]+4*p2[0]-p3[0])*t2+(-p0[0]+3*p1[0]-3*p2[0]+p3[0])*t3)
            z=0.5*(2*p1[1]+(-p0[1]+p2[1])*t+(2*p0[1]-5*p1[1]+4*p2[1]-p3[1])*t2+(-p0[1]+3*p1[1]-3*p2[1]+p3[1])*t3)
            out.append((y,z))
    out.append(points[-1]); return out
loop=open_path(profile); n=len(loop); width=0.078; thick=0.0007
outside=[];inside=[]
for i,(y,z) in enumerate(loop):
    prev=loop[(i-1)%n]; nxt=loop[(i+1)%n]
    dy,dz=nxt[0]-prev[0],nxt[1]-prev[1]; length=max(1e-9,math.hypot(dy,dz))
    ny,nz=-dz/length,dy/length
    outside.append((y+ny*thick/2,z+nz*thick/2))
    inside.append((y-ny*thick/2,z-nz*thick/2))
verts=[]
for x in (-width/2,width/2):
    for layer in (outside,inside):
        verts.extend((x,y,z) for y,z in layer)
faces=[]
for i in range(n-1):
    j=i+1
    faces.extend(((i,j,2*n+j,2*n+i),
                  (n+i,3*n+i,3*n+j,n+j),
                  (i,n+i,n+j,j),
                  (2*n+i,2*n+j,3*n+j,3*n+i)))
faces.extend(((0,2*n,3*n,n),(n-1,2*n-1,3*n-1,4*n-1)))
apron_mesh=bpy.data.meshes.new("thin_loading_apron_mesh")
apron_mesh.from_pydata(verts,[],faces);apron_mesh.update()
apron=bpy.data.objects.new("separate_free_edge_loading_apron",apron_mesh)
v4._finish(apron,bed,canvas,0.0001,smooth=True)
for sx in (-1,1):
    pts=[(sx*(width/2-0.0004),y,z) for y,z in loop]
    v4.tube(f"apron_edge_stitch_{sx}",pts,0.00022,material=apron_edge,body=bed,resolution=8)
v4.rod("apron_free_edge_hem",(-width/2,loop[-1][0],loop[-1][1]),(width/2,loop[-1][0],loop[-1][1]),
       0.00035,material=apron_edge,body=bed)

# Independent short wrap section follows the front roller crown and stays inside its
# 7.4 mm radius as the crank swings through its full range.
wrap_path=[]; wrap_radius=0.0074
for k in range(42):
    a=math.pi-(math.pi-0.68)*k/41
    wrap_path.append((front_c[1]+wrap_radius*math.cos(a),front_c[2]+wrap_radius*math.sin(a)))
wn=len(wrap_path); wthick=0.00055; wwidth=width
wout=[]; win=[]
for i,(y,z) in enumerate(wrap_path):
    prev=wrap_path[max(0,i-1)]; nxt=wrap_path[min(wn-1,i+1)]
    dy,dz=nxt[0]-prev[0],nxt[1]-prev[1]; length=max(1e-9,math.hypot(dy,dz))
    ny,nz=-dz/length,dy/length
    wout.append((y+ny*wthick/2,z+nz*wthick/2)); win.append((y-ny*wthick/2,z-nz*wthick/2))
wverts=[]
for x in (-wwidth/2,wwidth/2):
    for layer in (wout,win): wverts.extend((x,y,z) for y,z in layer)
wfaces=[]
for i in range(wn-1):
    j=i+1
    wfaces.extend(((i,j,2*wn+j,2*wn+i),(wn+i,3*wn+i,3*wn+j,wn+j),
                   (i,wn+i,wn+j,j),(2*wn+i,2*wn+j,3*wn+j,3*wn+i)))
wfaces.extend(((0,2*wn,3*wn,wn),(wn-1,2*wn-1,3*wn-1,4*wn-1)))
wrap_mesh=bpy.data.meshes.new("front_roller_apron_wrap_mesh"); wrap_mesh.from_pydata(wverts,[],wfaces); wrap_mesh.update()
wrap_obj=bpy.data.objects.new("moving_front_apron_wrap",wrap_mesh); v4._finish(wrap_obj,lever,canvas,0.0001,smooth=True)
for sx in (-1,1):
    pts=[(sx*(wwidth/2-0.0004),y,z) for y,z in wrap_path]
    v4.tube(f"moving_apron_edge_stitch_{sx}",pts,0.0002,material=apron_edge,body=lever,resolution=8)

# Fixed pivot axis and free rear idler axis. The front roller and crank are the
# same rotor, so moving the 64 mm side lever directly turns that roller.
v4.joint("front_roller_axle","revolute",bed,lever,origin=front_c,axis=(1,0,0),limits=(-math.radians(120),0.0))
v4.joint("upper_roller_axle","continuous",bed,upper,origin=rear_c,axis=(1,0,0))

# A small stamped maker's legend finishes the loading-facing panel.
v4.text("roller_front_badge","ROLL-EZ  /  80",0.0032,loc=(0,-0.03255,0.004),rot=(math.pi/2,0,0),
        extrude_depth=0.0002,material=ink,body=bed)

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