"""Detailed articulated tow-behind lawn sweeper. Run with Blender -b --python build.py."""
import math, os, sys
import bpy
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4

v4.reset()

# Powder-coated steel, stamped hardware, moulded tyres and woven collection bag.
green = v4.painted("sweeper_green_enamel", (0.055, 0.24, 0.105), roughness=0.26, coat=0.72)
green_dark = v4.painted("deep_green_brackets", (0.025, 0.105, 0.047), roughness=0.32)
steel = v4.metal("zinc_plated_steel", (0.69, 0.72, 0.74), roughness=0.27)
black_steel = v4.metal("blackened_steel", (0.07, 0.08, 0.075), roughness=0.32, brushed=False)
tire = v4.rubber("moulded_black_rubber", (0.025, 0.028, 0.026))
plastic = v4.plastic("hub_polymer", (0.12, 0.14, 0.12), roughness=0.37)
bag = v4.fabric("forest_green_hopper_canvas", (0.08, 0.19, 0.10), weave_scale=220)
bag_edge = v4.fabric("hopper_reinforcement", (0.035, 0.095, 0.05), weave_scale=260)
bristle = v4.rubber("black_polypropylene_brush", (0.035, 0.040, 0.038))
yellow = v4.painted("safety_yellow", (0.93, 0.57, 0.045), roughness=0.3)

XROT = (0, math.pi/2, 0)  # cylinder axis +X
root = v4.body("chassis")

# Main pressed channel rails and square-tube upper hopper frame.
for side in (-1, 1):
    x = side * 0.405
    v4.rod(f"lower_side_rail_{side}", (x, -0.34, 0.29), (x, 0.43, 0.32), 0.018, material=green, body=root)
    v4.rod(f"hopper_upright_{side}", (x, 0.18, 0.31), (x, 0.48, 0.72), 0.014, material=green, body=root)
    v4.rod(f"hopper_lower_diagonal_{side}", (side*0.37, 0.05, 0.32), (side*0.405, 0.48, 0.57), 0.011, material=green_dark, body=root)
    # Forward brush bearing pedestal and protective side cheeks.
    v4.box(f"brush_bearing_pedestal_{side}", (0.035, 0.09, 0.15), (side*0.435, -0.22, 0.23), bevel=0.008, material=green, body=root)
    v4.cylinder(f"brush_bearing_outer_{side}", 0.026, 0.020, (side*0.443, -0.23, 0.135), rot=XROT, material=black_steel, body=root)
    # Height-adjustment perforated plates and index bolts.
    v4.box(f"height_adjust_plate_{side}", (0.012, 0.14, 0.10), (side*0.432, -0.22, 0.27), bevel=0.005, material=steel, body=root)
    for k in range(4):
        v4.cylinder(f"height_index_{side}_{k}", 0.007, 0.004, (side*0.44, -0.27 + k*0.032, 0.265), rot=(0, math.pi/2, 0), segments=20, material=black_steel, body=root)
    # Fixed adjustment selector with a comfortable knob, mounted beside the end plate.
    v4.rod(f"brush_height_selector_{side}", (side*0.441,-0.27,0.265), (side*0.441,-0.315,0.345), 0.006, material=black_steel, body=root)
    v4.sphere(f"brush_height_grip_{side}", 0.014, (side*0.441,-0.315,0.345), material=plastic, body=root)

# Chassis crossmembers, axle and rear mouth support.
for name, y, z, r in (("front_crossbar", -0.31, 0.32, 0.014), ("mid_crossbar", 0.04, 0.31, 0.016), ("hopper_hinge_crossbar", 0.47, 0.57, 0.014)):
    v4.rod(name, (-0.405, y, z), (0.405, y, z), r, material=green, body=root)
v4.rod("fixed_wheel_axle", (-0.49, 0.02, 0.235), (0.49, 0.02, 0.235), 0.016, material=steel, body=root)
for side in (-1, 1):
    v4.rod(f"axle_mount_brace_{side}", (side*0.42,0.02,0.235), (side*0.405,0.02,0.29), 0.014, material=green_dark, body=root)
v4.rod("rear_bag_mouth_hoop_top", (-0.405, 0.48, 0.72), (0.405, 0.48, 0.72), 0.012, material=green, body=root)

# Tow tongue, gussets and a recognisable latch-style hitch coupler.
v4.rod("tow_tongue_left", (-0.27, -0.30, 0.32), (-0.065, -0.78, 0.29), 0.022, material=green, body=root)
v4.rod("tow_tongue_right", (0.27, -0.30, 0.32), (0.065, -0.78, 0.29), 0.022, material=green, body=root)
v4.box("tongue_gusset", (0.22, 0.17, 0.012), (0, -0.39, 0.32), bevel=0.004, material=steel, body=root)
v4.box("hitch_coupler_socket", (0.105, 0.15, 0.065), (0, -0.82, 0.29), bevel=0.02, material=steel, body=root)
v4.box("coupler_latch_handle", (0.026, 0.12, 0.014), (0, -0.81, 0.329), rot=(0.12, 0, 0), bevel=0.006, material=black_steel, body=root)
v4.cylinder("hitch_pin", 0.009, 0.15, (0, -0.77, 0.28), rot=XROT, material=steel, body=root)
# Coupler clevis ears and a transverse retaining pin with a bent keeper.
for side in (-1,1):
    v4.box(f"hitch_clevis_ear_{side}", (0.014,0.065,0.072), (side*0.056,-0.835,0.295), bevel=0.006, material=steel, body=root)
v4.cylinder("hitch_clevis_pin", 0.008, 0.145, (0,-0.835,0.295), rot=XROT, material=black_steel, body=root)
v4.tube("hitch_pin_keeper", [(0.073,-0.835,0.295),(0.088,-0.835,0.31),(0.088,-0.835,0.335)], 0.0025, material=steel, body=root)
# Tow-bar pull handle for the hopper dump cord; cord is routed along the tongue.
v4.tube("hopper_dump_cord", [(0.0,-0.42,0.326),(0.0,-0.49,0.34),(0.0,-0.555,0.35)], 0.0025, material=black_steel, body=root)
v4.rod("tow_dump_pull_handle", (-0.045,-0.555,0.35),(0.045,-0.555,0.35),0.008, material=plastic, body=root)

# Hopper hinge hardware is on the fixed frame; the matching barrels travel with the bag.
for side in (-1, 1):
    x = side * 0.39
    v4.cylinder(f"hinge_frame_knuckle_{side}", 0.018, 0.052, (x, 0.47, 0.57), rot=XROT, material=steel, body=root)
    v4.box(f"hinge_frame_leaf_{side}", (0.018, 0.09, 0.055), (x, 0.42, 0.57), bevel=0.003, material=green_dark, body=root)

# Two wheels: individual sidewall, tread lugs, pressed rim, dished hub and cap.
for side, name in ((-1, "left_wheel"), (1, "right_wheel")):
    wb = v4.body(name)
    cx, cy, cz = side*0.48, 0.02, 0.235
    # Torus cross-section gives a rounded tire carcass around the stamped wheel.
    v4.torus(f"{name}_tire", 0.184, 0.050, (cx, cy, cz), rot=XROT, material=tire, body=wb)
    # Discrete shoulder bars over outer tread, with alternating chevron-like lean.
    for i in range(28):
        a = 2*math.pi*i/28
        for row in (-1, 1):
            x = cx + side*row*0.025
            y = cy + 0.213*math.sin(a)
            z = cz + 0.213*math.cos(a)
            v4.box(f"{name}_tread_{i}_{row}", (0.036, 0.043, 0.022), (x, y, z), rot=(a*0.18, 0, side*0.12), bevel=0.006, material=tire, body=wb)
    # Rim lies inside tire; hubs and fasteners sit proud of the outer side.
    v4.cylinder(f"{name}_rim", 0.147, 0.050, (cx, cy, cz), rot=XROT, material=steel, body=wb)
    v4.torus(f"{name}_rim_lip", 0.133, 0.009, (cx + side*0.029, cy, cz), rot=XROT, material=black_steel, body=wb)
    v4.cylinder(f"{name}_hub_boss", 0.052, 0.035, (cx + side*0.043, cy, cz), rot=XROT, material=green, body=wb)
    v4.cylinder(f"{name}_dust_cap", 0.031, 0.012, (cx + side*0.065, cy, cz), rot=XROT, material=steel, body=wb)
    v4.cylinder(f"{name}_drive_gearcase", 0.059, 0.014, (cx + side*0.078, cy, cz), rot=XROT, material=green_dark, body=wb)
    v4.cylinder(f"{name}_gearcase_cover", 0.044, 0.015, (cx + side*0.0925, cy, cz), rot=XROT, material=green, body=wb)
    for bolt in range(6):
        a = 2*math.pi*bolt/6
        v4.cylinder(f"{name}_cover_bolt_{bolt}", 0.0045, 0.005, (cx+side*0.0875, cy+0.051*math.sin(a), cz+0.051*math.cos(a)), rot=XROT, segments=12, material=steel, body=wb)
    for k in range(5):
        a = 2*math.pi*k/5
        v4.cylinder(f"{name}_lug_{k}", 0.008, 0.009, (cx+side*0.029, cy+0.082*math.sin(a), cz+0.082*math.cos(a)), rot=XROT, segments=16, material=black_steel, body=wb)
    v4.joint(f"{name}_spin", "continuous", root, wb, (cx, cy, cz), (1,0,0))

# Brush body: long tube core with end plates, comb-like nylon tufts in eight helical rows.
reel = v4.body("brush_reel")
v4.cylinder("brush_core_tube", 0.040, 0.82, (0, -0.23, 0.135), rot=XROT, material=black_steel, body=reel)
for side in (-1, 1):
    x = side*0.405
    v4.cylinder(f"reel_end_plate_{side}", 0.105, 0.014, (x, -0.23, 0.135), rot=XROT, material=green_dark, body=reel)
    v4.cylinder(f"reel_journal_{side}", 0.022, 0.024, (side*0.421, -0.23, 0.135), rot=XROT, material=steel, body=reel)
    v4.cylinder(f"reel_bearing_collar_{side}", 0.031, 0.018, (side*0.414, -0.23, 0.135), rot=XROT, material=black_steel, body=reel)
# Dense nylon bundles, spiralled around the full reel circumference. Five fine fibres per tuft
# keep the silhouette soft and brush-like instead of reading as stiff metal teeth.
fiber_curve = bpy.data.curves.new("spiral_nylon_tufts", "CURVE")
fiber_curve.dimensions = "3D"
fiber_curve.resolution_u = 1
fiber_curve.bevel_depth = 0.0009
fiber_curve.bevel_resolution = 2
fiber_curve.use_fill_caps = True
for row in range(10):
    row_phase = 2*math.pi*row/10
    for i in range(42):
        x0 = -0.38 + i*(0.76/41)
        phase = row_phase + 0.42*(x0/0.76)
        # An eight-strand, slightly bowed fan in each tuft gives a flexible swept-back silhouette.
        for f in range(8):
            spread = f-3.5
            fan = spread*0.003
            xx = x0 + spread*0.0012
            theta = phase + fan*0.2
            root_y = -0.23 + 0.034*math.sin(theta)
            root_z = 0.135 + 0.034*math.cos(theta)
            length = 0.093 + 0.004*((i*7 + row*3 + f*5) % 7)
            mid_theta = phase + fan*0.55
            mid_y = -0.23 + 0.083*math.sin(mid_theta)
            mid_z = 0.135 + 0.083*math.cos(mid_theta)
            tip_theta = phase + fan
            tip_y = -0.23 + (0.034+length)*math.sin(tip_theta)
            tip_z = 0.135 + (0.034+length)*math.cos(tip_theta)
            spline = fiber_curve.splines.new("POLY")
            spline.points.add(2)
            spline.points[0].co = (xx, root_y, root_z, 1)
            spline.points[1].co = (xx, mid_y, mid_z, 1)
            spline.points[2].co = (xx, tip_y, tip_z, 1)
nylon_obj = bpy.data.objects.new("spiral_nylon_bristle_tufts", fiber_curve)
bpy.data.collections["Asset"].objects.link(nylon_obj)
fiber_curve.materials.append(bristle)
v4.part(nylon_obj, reel)
# Drive-end pulley / ribbed rim rotates with the brush.
v4.cylinder("brush_drive_pulley_web", 0.074, 0.012, (0.408, -0.23, 0.135), rot=XROT, material=black_steel, body=reel)
v4.joint("brush_rotation", "continuous", root, reel, (0,-0.23,0.135), (1,0,0))

# Curved sheet-metal deflector catches grass lifted by the brush and guides it through the low hopper mouth.
hood_section = [(-0.135,0.290),(-0.112,0.330),(-0.080,0.370),(-0.035,0.400),(0.015,0.425),(0.060,0.445)]
hood_verts = []
for x in (-0.385,0.385):
    hood_verts.extend([(x,y,z) for y,z in hood_section])
hood_faces = []
nsec = len(hood_section)
for i in range(nsec-1):
    hood_faces.append((i,i+1,nsec+i+1,nsec+i))
hood_mesh = bpy.data.meshes.new("curved_sweeper_deflector_mesh")
hood_mesh.from_pydata(hood_verts, [], hood_faces)
hood_mesh.materials.append(steel)
hood_obj = bpy.data.objects.new("curved_brush_deflector", hood_mesh)
bpy.data.collections["Asset"].objects.link(hood_obj)
solid = hood_obj.modifiers.new("stamped_sheet_thickness", "SOLIDIFY")
solid.thickness = 0.002
solid.offset = 0
bevel = hood_obj.modifiers.new("soft_rolled_edges", "BEVEL")
bevel.width = 0.002
bevel.segments = 2
v4.part(hood_obj, root)
# Brackets land on the curved sheet sides and the mid crossbar.
for side in (-1,1):
    v4.rod(f"deflector_support_{side}", (side*0.385,0.015,0.425),(side*0.405,0.04,0.31),0.008,material=green_dark,body=root)

# Hopper is a framed woven bag. It pivots on the rear crossbar and opens down at the lip.
hopper = v4.body("hopper")
# Main fabric walls: wide bottom and slightly flared opening, with reinforced piping.
v4.box("hopper_floor_panel", (0.75,0.43,0.018), (0,0.245,0.414), bevel=0.008, material=bag, body=hopper)
# Raise the front fabric wall to leave a receiving mouth aligned with the deflector.
v4.box("hopper_front_wall", (0.76,0.018,0.17), (0,0.035,0.625), rot=(-0.06,0,0), bevel=0.012, material=bag, body=hopper)
v4.box("hopper_rear_wall", (0.78,0.018,0.30), (0,0.465,0.565), rot=(0.06,0,0), bevel=0.012, material=bag, body=hopper)
for side in (-1,1):
    x=side*0.38
    v4.box(f"hopper_side_panel_{side}", (0.018,0.43,0.30), (x,0.25,0.565), rot=(0,0,side*0.025), bevel=0.01, material=bag, body=hopper)
    # Corner webbing, rim tubes, and reinforcement strips.
    v4.tube(f"hopper_corner_piping_{side}", [(x,0.035,0.42),(x,0.035,0.71),(x,0.465,0.71),(x,0.465,0.42)], 0.009, material=bag_edge, body=hopper)
    v4.rod(f"hopper_side_rim_{side}", (side*0.38,0.035,0.715),(side*0.38,0.465,0.715),0.010, material=green_dark, body=hopper)
v4.rod("hopper_front_lip",(-0.38,0.035,0.715),(0.38,0.035,0.715),0.016,material=green,body=hopper)
v4.rod("hopper_hinge_rail",(-0.39,0.465,0.57),(0.39,0.465,0.57),0.014,material=green,body=hopper)
for side in (-1,1):
    x=side*0.39
    v4.cylinder(f"hopper_hinge_barrel_{side}",0.017,0.05,(x,0.47,0.57),rot=XROT,material=green_dark,body=hopper)
    v4.cylinder(f"hopper_hinge_pin_cap_{side}",0.009,0.006,(x+side*0.029,0.47,0.57),rot=XROT,segments=20,material=steel,body=hopper)
# Dump handle and two over-centre latch tabs at mouth.
v4.rod("hopper_dump_handle",(-0.15,0.035,0.73),(0.15,0.035,0.73),0.012,material=plastic,body=hopper)
for side in (-1,1):
    v4.rod(f"hopper_latch_strap_{side}",(side*0.31,0.02,0.71),(side*0.31,-0.02,0.63),0.006,material=steel,body=hopper)
    v4.cylinder(f"hopper_latch_rivet_{side}",0.006,0.004,(side*0.31,-0.014,0.64),rot=(math.pi/2,0,0),segments=16,material=steel,body=hopper)
v4.joint("hopper_dump", "revolute", root, hopper, (0,0.47,0.57), (1,0,0), limits=(0,1.15))

# Raised product badge on the flat front canvas panel.
badge = v4.box("brand_patch", (0.30,0.006,0.075), (0,0.023,0.61), bevel=0.012, material=green_dark, body=hopper)
v4.text("brand_text", "YARD PRO", 0.031, (0,0.018,0.612), rot=(math.pi/2,0,0), on=badge, material=yellow, body=hopper)

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