"""Detailed articulated 20 ft roll-off container. Run with Blender -b --python build.py."""
import math, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4

v4.reset()

# Industrial finishes
blue = v4.painted("container_blue_enamel", (0.075, 0.20, 0.34), roughness=0.34, coat=0.42)
blue_dark = v4.painted("reinforcement_blue", (0.045, 0.105, 0.17), roughness=0.4, coat=0.25)
frame = v4.painted("charcoal_frame", (0.105, 0.12, 0.13), roughness=0.42, coat=0.2)
yellow = v4.painted("safety_yellow", (0.95, 0.57, 0.055), roughness=0.34, coat=0.35)
steel = v4.metal("galvanized_steel", (0.62, 0.66, 0.69), roughness=0.3, brushed=False)
bright = v4.metal("polished_pin_steel", (0.78, 0.81, 0.82), roughness=0.24, brushed=True)
rubber = v4.rubber("roller_tread", (0.075, 0.08, 0.085), roughness=0.72)
label = v4.mat("stencil_cream", (0.9, 0.84, 0.65), roughness=0.68)
rust = v4.painted("aged_oxide", (0.32, 0.105, 0.035), roughness=0.78, coat=0.04)

# Principal dimensions: 6.10 x 2.44 x 1.55 m, open-top
L, W = 6.10, 2.44
xwall = W/2 - 0.035
yrear, yfront = -3.03, 3.03
floor_z = 0.31
top_z = 1.82
root = v4.body("container")

def bx(n, s, p, m, b=root, bevel=0.004, rot=(0,0,0)):
    return v4.box(n, s, p, rot=rot, bevel=bevel, material=m, body=b)
def cy(n, r, d, p, m, b=root, rot=(0,0,0), bevel=0.001):
    return v4.cylinder(n, r, d, p, rot=rot, segments=32, bevel=bevel, material=m, body=b)
def rod(n,p0,p1,r,m,b=root): return v4.rod(n,p0,p1,r,material=m,body=b)

def stencil_row(text, side, cy_y, z, char_h, matl, prefix):
    """Industrial block stencil from attached rectangular strokes on the side plaque."""
    segs={
        "0":"abcdef", "1":"bc", "2":"abged", "3":"abgcd", "4":"fgbc", "5":"afgcd",
        "6":"afgecd", "7":"abc", "8":"abcdefg", "9":"abfgcd",
        "A":"abcefg", "B":"fgecd", "C":"afed", "D":"bgecd", "E":"afged", "F":"afge",
        "G":"afedcg", "H":"fgebc", "I":"ad", "J":"bcd", "K":"fge", "L":"fed",
        "M":"abcef", "N":"fceg", "O":"abcdef", "P":"abfge", "R":"abfgec", "S":"afgcd",
        "T":"fed", "U":"febcd", "V":"fec", "W":"fbdc", "Y":"fgbcd", "Z":"abged",
        "-":"g", "+":"g",
    }
    ch=char_h; sw=ch*0.12; seg_l=ch*0.66; pitch=ch*0.82
    chars=list(text.upper()); total=max(0,len(chars)-1)*pitch+seg_l
    start=cy_y-total/2+seg_l/2
    for ci,c in enumerate(chars):
        if c==" ": continue
        yy=start+ci*pitch
        for s in segs.get(c,""):
            if s in "adg":
                zz=z+({"a":ch*.40,"g":0,"d":-ch*.40}[s])
                bx(f"{prefix}_{ci}_{s}",(0.009,seg_l,sw),(side*1.256,yy,zz),matl,root,0.0015)
            else:
                sign=-1 if s in "ef" else 1
                zz=z+sign*ch*.20
                dy=-ch*.34 if s in "ef" else ch*.34
                bx(f"{prefix}_{ci}_{s}",(0.009,sw,ch*.34),(side*1.256,yy+dy,zz),matl,root,0.0015)

# Floor and the open, ribbed steel tub.
bx("heavy_gauge_floor", (2.30,5.94,0.085), (0,0,floor_z), frame, bevel=0.008)
for i in range(19):
    x=-1.09+i*0.121
    bx(f"floor_raised_tread_{i:02d}",(0.018,5.82,0.012),(x,0,floor_z+0.048),steel,bevel=0.003)

# Solid front bulkhead, side sheets, and vertical corrugations.
bx("front_bulkhead",(2.34,0.065,1.40),(0,2.94,1.08),blue,bevel=0.006)
for side in (-1,1):
    x=side*xwall
    bx(f"side_sheet_{side}",(0.045,5.90,1.42),(x,0,1.085),blue,bevel=0.004)
    # Longitudinally spaced side ribs with a formed industrial section.
    for i in range(18):
        y=-2.78+i*0.325
        bx(f"side_corrugation_{side}_{i:02d}",(0.035,0.075,1.31),(side*(xwall+0.040),y,1.10),blue_dark,bevel=0.009)
    # Continuous bottom and upper side rails, with corner posts.
    bx(f"side_bottom_channel_{side}",(0.09,5.98,0.13),(side*1.16,0,0.44),frame,bevel=0.012)
    bx(f"side_top_rail_{side}",(0.125,6.04,0.14),(side*1.16,0,1.77),steel,bevel=0.025)
    for y in (2.91,):
        bx(f"corner_post_{side}_{y}",(0.13,0.14,1.48),(side*1.16,y,1.10),frame,bevel=0.012)
    # Reinforced lower side sill and diagonal corner gussets.
    for y in (-2.65,2.65):
        rod(f"side_sill_gusset_{side}_{y}",(side*1.205,y,0.48),(side*1.205,y+0.28*(1 if y<0 else -1),0.77),0.026,steel)

# Perimeter lip, with a visible inner return around the open mouth.
bx("front_top_rim",(2.38,0.11,0.12),(0,2.94,1.79),steel,bevel=0.012)
bx("rear_top_rim",(2.38,0.11,0.12),(0,-2.94,1.79),steel,bevel=0.012)
for side in (-1,1):
    bx(f"rim_inner_return_{side}",(0.045,5.84,0.06),(side*1.105,0,1.72),steel,bevel=0.006)

# Underbody crossmembers and full-length skid rails.
for i,y in enumerate((-2.55,-1.72,-0.86,0.0,0.86,1.72,2.55)):
    bx(f"crossmember_{i}",(2.22,0.12,0.15),(0,y,0.20),frame,bevel=0.012)
for side in (-1,1):
    x=side*0.82
    bx(f"rail_skid_{side}",(0.20,6.02,0.20),(x,0,0.12),frame,bevel=0.025)
    bx(f"skid_wear_strip_{side}",(0.15,5.98,0.025),(x,0,0.0075),steel,bevel=0.008)
    # Short axle support cheeks flank the roller, anchored to the rail end.
    for sx in (-1,1):
        xx=x+sx*0.105
        bx(f"roller_cheek_{side}_{sx}",(0.045,0.20,0.18),(xx,-2.92,0.20),steel,bevel=0.012)
        cy(f"axle_boss_{side}_{sx}",0.034,0.012,(xx,-2.92,0.12),bright,rot=(0,math.pi/2,0))

# Front winch hook bar and formed hook, attached to the front bulkhead structure.
bx("front_hook_backer",(0.62,0.13,0.36),(0,3.015,1.39),frame,bevel=0.025)
bx("hook_bar",(0.52,0.10,0.105),(0,3.11,1.46),steel,bevel=0.02)
for x in (-0.205,0.205):
    cy(f"hook_bar_bolt_{x}",0.027,0.018,(x,3.17,1.46),bright,rot=(math.pi/2,0,0))
# Heavy curved J hook, made from a sequence of tangent rods.
hook_pts=[(0,3.17,1.49),(0,3.25,1.39),(0,3.26,1.22),(0,3.19,1.12),(0,3.08,1.12),(0,3.015,1.19)]
for i in range(len(hook_pts)-1): rod(f"forged_hook_segment_{i}",hook_pts[i],hook_pts[i+1],0.047,steel)
cy("hook_throat_pin",0.018,0.12,(0,3.13,1.17),bright,rot=(0,math.pi/2,0))
# Heavy A-frame hook tower: paired sloping webs tie the elevated hook crossbar
# down into the front sill, with cheek plates at each welded foot.
for side in (-1,1):
    rod(f"hook_tower_strut_{side}",(side*0.49,3.045,0.43),(side*0.20,3.14,1.58),0.072,frame)
    rod(f"hook_tower_inner_brace_{side}",(side*0.37,3.055,0.48),(side*0.06,3.13,1.35),0.038,steel)
    bx(f"hook_tower_foot_{side}",(0.31,0.13,0.25),(side*0.43,3.055,0.43),steel,bevel=0.025)
    for dx in (-0.085,0.085):
        cy(f"hook_foot_bolt_{side}_{dx}",0.022,0.015,(side*0.43+dx,3.126,0.43),bright,rot=(math.pi/2,0,0))
bx("hook_tower_crosshead",(0.72,0.16,0.15),(0,3.13,1.59),frame,bevel=0.025)
bx("hook_tower_face_plate",(0.54,0.035,0.24),(0,3.225,1.42),steel,bevel=0.018)

# Rear jambs with alternating vertical hinge knuckles and a continuous visible pin.
for side in (-1,1):
    x=side*1.20
    # One turned mesh makes the fixed pin and alternating jamb-side sleeves a
    # continuous, visibly vertical hinge assembly.
    hinge_profile=[(0,0),(0.012,0),(0.012,0.04),(0.036,0.04),(0.036,0.24),
        (0.012,0.24),(0.012,0.44),(0.036,0.44),(0.036,0.64),(0.012,0.64),
        (0.012,0.84),(0.036,0.84),(0.036,1.04),(0.012,1.04),(0.012,1.20),
        (0.036,1.20),(0.036,1.40),(0.012,1.40),(0.012,1.44),(0,1.44)]
    v4.lathe(f"hinge_pin_and_fixed_knuckles_{side}",hinge_profile,loc=(x,-3.055,0.35),material=bright,body=root)
    # Upper tie strap anchors the pin carrier to the cap rail above the door leaf.
    rod(f"hinge_head_tie_{side}",(x,-3.055,1.70),(side*1.16,-3.005,1.85),0.027,steel)

# Rear doors: two leaves, closed in the rest pose, swinging outboard and rearward.
doors=[]
for side,name in ((-1,"left"),(1,"right")):
    door=v4.body(f"rear_door_{name}"); doors.append((side,name,door))
    cx=side*0.60
    bx(f"{name}_door_plate",(1.19,0.055,1.43),(cx,-3.035,1.08),blue,door,0.008)
    # Folded perimeter returns and three horizontal stiffener channels.
    bx(f"{name}_door_inner_return",(0.045,0.075,1.39),(side*0.035,-3.035,1.08),blue_dark,door,0.006)
    bx(f"{name}_door_outer_return",(0.045,0.075,1.39),(side*1.165,-3.035,1.08),blue_dark,door,0.006)
    for k,z in enumerate((0.53,1.08,1.63)):
        bx(f"{name}_door_stiffener_{k}",(1.11,0.085,0.105),(cx,-3.085,z),frame,door,0.012)
        bx(f"{name}_stiffener_accent_{k}",(1.00,0.012,0.012),(cx,-3.132,z+0.025),steel,door,0.004)
    # Three hinge knuckles attached to the leaf, offset into gaps between fixed barrels.
    for k,z in enumerate((0.69,1.09,1.49)):
        cy(f"{name}_hinge_knuckle_{k}",0.030,0.16,(side*1.20,-3.055,z),steel,door,bevel=0.002)
        bx(f"{name}_hinge_leaf_{k}",(0.09,0.05,0.14),(side*1.165,-3.055,z),steel,door,0.004)
    # Hinge limits open each leaf away from the centre of the opening.
    origin=(side*1.20,-3.055,1.08)
    limits=(0,math.radians(105)) if side<0 else (math.radians(-105),0)
    v4.joint(f"{name}_door_hinge","revolute",root,door,origin,(0,0,1),limits=limits)

    # Leaf-mounted over-centre cam handle with a compact hooked nose.
    cam=v4.body(f"cam_lever_{name}")
    pivot_x=side*0.42
    # Hub and stout lever lie on the rear face; the curled nose catches a fixed keeper.
    cy(f"{name}_cam_hub",0.055,0.045,(pivot_x,-3.16,1.065),steel,cam,(math.pi/2,0,0),0.003)
    v4.rod(f"{name}_cam_handle",(pivot_x,-3.19,1.065),(pivot_x-side*0.30,-3.19,1.065),0.024,material=yellow,body=cam)
    cy(f"{name}_grip",0.026,0.10,(pivot_x-side*0.32,-3.19,1.065),frame,cam,(0,math.pi/2,0),0.006)
    # Small cam nose at the handle end engages a fixed keeper plate when shut.
    bx(f"{name}_cam_nose",(0.075,0.045,0.045),(pivot_x-side*0.30,-3.19,1.065),steel,cam,0.012)
    v4.joint(f"{name}_cam_pivot","revolute",door,cam,(pivot_x,-3.16,1.065),(0,1,0),
             limits=(-math.radians(55),math.radians(55)))

# Cam keepers are fixed to the opposite leaf. Each is an open, forked keeper:
# the upper and lower rails frame the grip with clearance, and an outboard stop
# catches the cam nose without putting a solid bar through the handle.
for side,name,door in doors:
    other=next(d for s,n,d in doors if s == -side)
    # Place the fork root outside the sweep of the opposite cam's long handle.
    mount_x=-side*0.60
    stop_x=side*0.20
    keeper_y=-3.235-(0.025 if side>0 else 0.0)
    bx(f"keeper_backing_{name}",(0.105,0.09,0.22),(mount_x,-3.10,1.065),steel,other,0.008)
    # Project the keeper outward from the door skin to the cam lever plane.
    rod(f"keeper_standoff_{name}",(mount_x,-3.14,1.065),(mount_x,keeper_y,1.065),0.022,bright,other)
    # A short web ties the standoff to both fork rails while staying beyond the
    # cam lever's sweep at the closed pose.
    bx(f"keeper_web_{name}",(0.035,0.03,0.12),(mount_x,keeper_y,1.065),steel,other,0.005)
    rail_width=abs(stop_x-mount_x)+0.06
    rail_center=(stop_x+mount_x)/2
    for zoff,rail in ((-0.052,"lower"),(0.052,"upper")):
        bx(f"keeper_bridge_{name}_{rail}",(rail_width,0.018,0.018),
           (rail_center,keeper_y,1.065+zoff),yellow,other,0.005)

# Two independent, continuously rotating rear rollers on transverse skid axles.
for side,name in ((-1,"left"),(1,"right")):
    wheel=v4.body(f"roller_wheel_{name}")
    x=side*1.04; yc=-2.92; zc=0.12
    cy(f"{name}_roller_tread",0.115,0.16,(x,yc,zc),rubber,wheel,(0,math.pi/2,0),0.006)
    cy(f"{name}_roller_hub_outer",0.067,0.172,(x,yc,zc),steel,wheel,(0,math.pi/2,0),0.004)
    for sx in (-1,1):
        cy(f"{name}_roller_hub_cap_{sx}",0.038,0.012,(x+sx*0.089,yc,zc),bright,wheel,(0,math.pi/2,0),0.003)
    axis=(x,yc,zc)
    v4.joint(f"{name}_roller_axle","continuous",root,wheel,axis,(1,0,0))

# Commercial hauler identification, capacity and phone number on side plaques.
for side in (-1,1):
    id_plate=bx(f"id_placard_{side}",(0.018,0.94,0.25),(side*1.244,0.13,1.48),yellow,root,0.014)
    cap_plate=bx(f"capacity_placard_{side}",(0.018,0.94,0.17),(side*1.244,0.13,0.70),frame,root,0.01)
    text_rot=(math.pi/2,0,math.pi/2) if side>0 else (math.pi/2,0,-math.pi/2)
    v4.text(f"hauler_name_{side}","NORTHSTAR",0.11,(side*1.253,0.13,1.48),text_rot,
            material=frame,body=root,on=id_plate,height=0.002)
    v4.text(f"capacity_text_{side}","20 YD3",0.068,(side*1.253,-0.08,0.735),text_rot,
            material=label,body=root,on=cap_plate,height=0.0015)
    v4.text(f"phone_text_{side}","555-010-2040",0.041,(side*1.253,0.30,0.665),text_rot,
            material=label,body=root,on=cap_plate,height=0.0012)
    # Fastener heads and oxide-toned hardware break up the clean enamel.
    for k,yy in enumerate((-0.31,0.55)):
        cy(f"placard_rivet_{side}_{k}",0.012,0.012,(side*1.257,yy,1.48),bright,rot=(0,math.pi/2,0),bevel=0.001)

# Save at the closed, unlatched rest pose.
v4.save(os.path.join(os.getcwd(),"asset.blend"))
print("saved asset.blend")
