"""Detailed articulated raise boring rig. Run with Blender -b --python build.py."""
import math
import os
import sys
import bpy

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4

v4.reset()

# Materials
yellow = v4.painted("mine_safety_yellow", (0.92, 0.53, 0.035), roughness=0.28, coat=0.45)
yellow_dark = v4.painted("ochre_edge_paint", (0.57, 0.29, 0.025), roughness=0.38)
frame_mat = v4.painted("graphite_frame", (0.12, 0.15, 0.17), roughness=0.4)
black = v4.rubber("track_rubber", (0.025, 0.029, 0.03))
steel = v4.metal("machined_steel", (0.68, 0.72, 0.74), roughness=0.23, brushed=True)
darksteel = v4.metal("dark_steel", (0.19, 0.22, 0.23), roughness=0.34, brushed=False)
bronze = v4.metal("hydraulic_brass", (0.55, 0.38, 0.17), roughness=0.32, brushed=False)
glass = v4.glass("cab_glass", (0.08, 0.18, 0.21), roughness=0.16)
red = v4.emissive("red_lamp", (1.0, 0.06, 0.015), strength=2.0)
white = v4.emissive("work_lamp", (0.82, 0.9, 1.0), strength=2.5)
label = v4.mat("lettering", (0.95, 0.91, 0.72), roughness=0.55)

base = v4.body("base")
head = v4.body("rotary_head")
spindle = v4.body("drive_spindle")
string = v4.body("drill_string")
arm = v4.body("rod_handling_arm")

# Carrier chassis, front at -Y. Main welded frame and belly pan.
for sx in (-1, 1):
    # Split belly and chassis beams leave a real central bore for the descending drill string.
    v4.box(f"central_chassis_{sx}", (0.91, 5.6, 0.62), (sx*0.76, 0.05, 0.83), bevel=0.1, material=frame_mat, body=base)
for sx in (-1, 1):
    v4.box(f"longitudinal_girder_{sx}", (0.19, 6.1, 0.42), (sx*1.13, 0.1, 1.02), bevel=0.045, material=yellow, body=base)
    # Continuous crawler belts with articulated-looking grousers and visible rollers.
    tx, cy, cz, radius = sx*1.48, 0.0, 0.48, 0.33
    path = []
    path += [(tx, -1.80+i*0.30, cz-radius) for i in range(13)]
    path += [(tx, 1.80+radius*math.cos(a), cz+radius*math.sin(a))
             for a in [(-math.pi/2)+i*math.pi/8 for i in range(1, 9)]]
    path += [(tx, 1.80-i*0.30, cz+radius) for i in range(1, 13)]
    path += [(tx, -1.80+radius*math.cos(a), cz+radius*math.sin(a))
             for a in [(math.pi/2)+i*math.pi/8 for i in range(1, 9)]]
    v4.tube(f"crawler_belt_{sx}", path, 0.085, material=black, body=base, resolution=1, cyclic=True)
    # Molded traction shoes around the straight runs and rounded idler ends.
    for k in range(13):
        y = -1.80+k*0.30
        v4.box(f"crawler_grouser_top_{sx}_{k}", (0.44, 0.17, 0.085), (tx, y, cz+radius+0.05),
               bevel=0.025, material=darksteel, body=base)
        v4.box(f"crawler_grouser_bottom_{sx}_{k}", (0.44, 0.17, 0.085), (tx, y, cz-radius-0.05),
               bevel=0.025, material=darksteel, body=base)
    for side in (-1, 1):
        yc = side*1.80
        for k in range(1, 6):
            theta = -math.pi/2 + k*math.pi/6
            yy, zz = yc+side*radius*math.cos(theta), cz+radius*math.sin(theta)
            angle = theta+math.pi/2 if side > 0 else math.pi/2-theta
            v4.box(f"crawler_grouser_end_{sx}_{side}_{k}", (0.44, 0.16, 0.085),
                   (tx, yy+side*0.045*math.cos(theta), zz+0.045*math.sin(theta)),
                   rot=(angle, 0, 0), bevel=0.022, material=darksteel, body=base)
        v4.cylinder(f"track_sprocket_{sx}_{side}", 0.26, 0.38,
                    (tx, yc, cz), rot=(0, math.pi/2, 0), segments=40, material=darksteel, body=base)
        v4.cylinder(f"track_sprocket_hub_{sx}_{side}", 0.14, 0.41,
                    (tx, yc, cz), rot=(0, math.pi/2, 0), segments=32, material=yellow_dark, body=base)
        for i in range(8):
            a = i*math.tau/8
            v4.cylinder(f"track_hub_bolt_{sx}_{side}_{i}", 0.022, 0.025,
                        (sx*1.69, yc+0.19*math.cos(a), cz+0.19*math.sin(a)),
                        rot=(0, math.pi/2, 0), segments=12, material=steel, body=base)
    for k, y in enumerate((-1.20, -0.60, 0.0, 0.60, 1.20)):
        v4.cylinder(f"track_road_roller_{sx}_{k}", 0.26, 0.38, (tx, y, cz),
                    rot=(0, math.pi/2, 0), segments=32, material=frame_mat, body=base)
        v4.cylinder(f"track_roller_cap_{sx}_{k}", 0.12, 0.405, (sx*1.685, y, cz),
                    rot=(0, math.pi/2, 0), segments=24, material=yellow_dark, body=base)
        v4.rod(f"track_suspension_link_{sx}_{k}", (sx*1.19, y, 0.88),
               (sx*1.34, y, cz), 0.065, material=yellow_dark, body=base)

# Four telescopic stabilizer legs with broad ground pads and welded cross outriggers.
for sx in (-1, 1):
    for sy, y in ((-1, -2.85), (1, 3.35)):
        v4.box(f"outrigger_crossbeam_{sx}_{sy}", (0.96, 0.34, 0.30), (sx*1.38, y, 0.73),
               bevel=0.045, material=frame_mat, body=base)
        v4.cylinder(f"outrigger_barrel_{sx}_{sy}", 0.15, 0.56, (sx*1.68, y, 0.93),
                    segments=40, material=darksteel, body=base)
        v4.cylinder(f"outrigger_chrome_ram_{sx}_{sy}", 0.085, 0.53, (sx*1.68, y, 0.39),
                    segments=32, material=steel, body=base)
        v4.box(f"outrigger_foot_{sx}_{sy}", (0.58, 0.58, 0.12), (sx*1.68, y, 0.06),
               bevel=0.035, material=yellow_dark, body=base)

# Open operator platform: exposed controls and seat, with no forklift-style canopy.
v4.box("operator_floor", (2.25, 1.5, 0.16), (0, -2.0, 1.42), bevel=0.035, material=yellow, body=base)
for sx in (-1, 1):
    for y in (-2.35, -1.50):
        v4.rod(f"operator_floor_support_{sx}_{y}", (sx*1.08, y, 0.96),
               (sx*1.08, y, 1.44), 0.10, material=yellow_dark, body=base)
v4.rod("operator_rear_guard", (-1.0, -1.40, 1.84), (1.0, -1.40, 1.84), 0.045,
       material=yellow_dark, body=base)
for sx in (-1, 1):
    # Welded front operator-rail uprights carry the platform guard loads into the
    # longitudinal chassis girders instead of leaving the open station floating.
    v4.rod(f"operator_guard_to_girder_{sx}", (sx*1.13, -2.50, 1.20),
           (sx*1.0, -2.50, 1.68), 0.075, material=yellow_dark, body=base)
    v4.rod(f"operator_side_guard_{sx}", (sx*1.0, -2.50, 1.68), (sx*1.0, -1.40, 1.84), 0.045,
           material=yellow_dark, body=base)
v4.box("dash_console", (1.65, 0.34, 0.26), (0, -1.63, 2.12), bevel=0.045, material=frame_mat, body=base)
for i in range(5):
    x = -0.58 + i*0.29
    v4.cylinder(f"control_knob_{i}", 0.045, 0.10, (x, -1.76, 2.30), segments=20, material=yellow_dark, body=base)
for i, x in enumerate((-0.48, -0.16, 0.16, 0.48)):
    lean = (i-1.5)*0.035
    v4.rod(f"operator_control_lever_{i}", (x, -1.76, 2.23),
           (x+lean, -1.82, 2.48), 0.025, material=steel, body=base)
    v4.sphere(f"operator_control_grip_{i}", 0.060, (x+lean, -1.82, 2.49),
              material=black if i % 2 else yellow_dark, body=base)
v4.box("operator_seat_base", (0.42, 0.42, 0.15), (0, -1.91, 1.72), bevel=0.06, material=darksteel, body=base)
v4.box("operator_seat_pedestal", (0.34, 0.34, 0.16), (0, -1.91, 1.57), bevel=0.025,
       material=darksteel, body=base)
v4.box("operator_seat", (0.56, 0.48, 0.16), (0, -1.91, 1.89), bevel=0.07, material=black, body=base)
v4.box("seat_back", (0.56, 0.15, 0.52), (0, -1.69, 2.17), bevel=0.07, material=black, body=base)

# Rear power-pack and hydraulic service enclosure.
v4.box("power_pack_lower", (2.05, 1.55, 1.04), (0, 2.25, 1.25), bevel=0.075, material=yellow, body=base)
v4.box("power_pack_top", (2.12, 1.58, 0.18), (0, 2.25, 1.85), bevel=0.055, material=yellow_dark, body=base)
for sx in (-1, 1):
    v4.box(f"service_door_{sx}", (0.012, 1.08, 0.65), (sx*1.034, 2.25, 1.30), bevel=0.01, material=yellow, body=base)
    v4.box(f"service_id_plate_{sx}", (0.020, 0.54, 0.20), (sx*1.048, 2.52, 1.70),
           bevel=0.018, material=darksteel, body=base)
    v4.box(f"service_id_inlay_{sx}", (0.006, 0.36, 0.065), (sx*1.061, 2.52, 1.70),
           bevel=0.006, material=label, body=base)
    for j in range(7):
        v4.box(f"vent_slit_{sx}_{j}", (0.018, 0.62, 0.025), (sx*1.046, 2.25, 1.12+j*0.065),
               bevel=0.01, material=darksteel, body=base)
    for j in range(4):
        v4.cylinder(f"service_latch_{sx}_{j}", 0.022, 0.025, (sx*1.05, 1.84+j*0.27, 1.52),
                    rot=(0, math.pi/2, 0), segments=16, material=steel, body=base)
v4.box("rear_radiator", (1.18, 0.035, 0.64), (0, 3.035, 1.42), bevel=0.02, material=darksteel, body=base)
for j in range(13):
    v4.box(f"radiator_fin_{j}", (0.045, 0.04, 0.58), (-0.54+j*0.09, 3.005, 1.42), bevel=0.01,
           material=steel, body=base)
v4.cylinder("hydraulic_reservoir", 0.29, 1.12, (0.76, 1.98, 2.10), segments=48, material=darksteel, body=base)
v4.cylinder("reservoir_cap", 0.10, 0.05, (0.76, 1.98, 2.685), segments=32, material=steel, body=base)
for sx in (-1, 1):
    # Feed pump manifold and high-pressure lines routed along the chassis to each barrel foot.
    v4.box(f"hydraulic_manifold_{sx}", (0.30, 0.20, 0.24), (sx*0.86, 1.39, 1.78),
           bevel=0.025, material=darksteel, body=base)
    for k in range(3):
        v4.cylinder(f"manifold_port_{sx}_{k}", 0.045, 0.06,
                    (sx*(0.72+k*0.14), 1.275, 1.77), rot=(math.pi/2, 0, 0),
                    segments=20, material=bronze, body=base)
    v4.tube(f"power_to_feed_hoses_{sx}",
            [(sx*0.78, 1.27, 1.78), (sx*0.90, 1.20, 1.67),
             (sx*1.08, 1.17, 1.50), (sx*1.25, 1.22, 1.36),
             (sx*1.28, 1.35, 1.29)], 0.035, material=black, body=base, resolution=2)

# Tall rigid feed assembly. Twin box beams with cross ties, gussets, guide rails and cylinder barrels.
for sx in (-1, 1):
    v4.box(f"feed_frame_foot_{sx}", (1.48, 1.15, 0.42), (sx*1.25, 0.55, 1.67), bevel=0.09, material=yellow, body=base)
    v4.box(f"feed_frame_foot_support_{sx}", (0.20, 0.22, 0.50), (sx*0.90, 0.55, 1.30),
           bevel=0.025, material=yellow_dark, body=base)
for sx in (-1, 1):
    x = sx*1.72
    v4.box(f"feed_channel_{sx}", (0.30, 0.42, 5.72), (x, 0.48, 4.55), bevel=0.045, material=frame_mat, body=base)
    # Machined guide faces on the inner and front sides of each feed column.
    v4.box(f"feed_guide_wear_rail_{sx}", (0.04, 0.26, 5.30), (sx*1.57, 0.48, 4.55),
           bevel=0.012, material=steel, body=base)
    v4.box(f"feed_front_wear_strip_{sx}", (0.19, 0.045, 5.28), (sx*1.72, 0.247, 4.55),
           bevel=0.012, material=steel, body=base)
    # Lower diagonal terminates below the full-retraction cheek envelope.
    v4.rod(f"lower_frame_brace_{sx}", (sx*0.55, 0.47, 1.82), (x, 0.48, 2.30), 0.105,
           material=yellow_dark, body=base)
    # Keep the tall brace on the rear side of the carriage sweep while it still
    # triangulates the guide post back to the chassis foot.
    v4.rod(f"upper_frame_brace_{sx}", (sx*0.92, 1.00, 1.85), (sx*1.72, 1.00, 4.18), 0.12,
           material=yellow, body=base)
    v4.box(f"frame_brace_foot_plate_{sx}", (0.36, 0.42, 0.16), (sx*0.92, 1.00, 1.86),
           bevel=0.025, material=yellow_dark, body=base)
    v4.box(f"frame_brace_upper_gusset_{sx}", (0.30, 0.60, 0.20), (sx*1.72, 0.76, 4.18),
           bevel=0.025, material=yellow_dark, body=base)
    # Fixed hydraulic cylinder barrels seated on the foot.
    cx = sx*1.28
    # Hollow steel barrel with clearance around the chrome piston rod.
    barrel_len = 2.52
    v4.lathe(f"feed_cylinder_barrel_{sx}",
             [(0.145, 0.0), (0.145, barrel_len), (0.102, barrel_len), (0.102, 0.0)],
             loc=(cx, 1.35, 1.15), material=darksteel, body=base)
    v4.lathe(f"cylinder_base_cap_{sx}", [(0.18, 0.0), (0.18, 0.16), (0.102, 0.16), (0.102, 0.0)],
             loc=(cx, 1.35, 1.07), material=yellow_dark, body=base)
    v4.box(f"feed_cylinder_base_clevis_{sx}", (0.30, 0.44, 0.32), (cx, 1.16, 1.37),
           bevel=0.035, material=yellow_dark, body=base)
    for lx in (-1, 1):
        v4.box(f"feed_base_clevis_ear_{sx}_{lx}", (0.07, 0.23, 0.36), (cx+lx*0.19, 1.20, 1.40),
               bevel=0.025, material=yellow, body=base)
    v4.cylinder(f"feed_base_clevis_pin_{sx}", 0.055, 0.48, (cx, 1.24, 1.30),
                rot=(math.pi/2, 0, 0), segments=24, material=steel, body=base)
    v4.lathe(f"cylinder_gland_{sx}", [(0.17, 0.0), (0.17, 0.10), (0.102, 0.10), (0.102, 0.0)],
             loc=(cx, 1.35, 3.57), material=steel, body=base)
    v4.torus(f"gland_seal_{sx}", 0.145, 0.018, (cx, 1.35, 3.67), material=black, body=base)
for z in (6.9, 7.38):
    v4.box(f"frame_cross_tie_{z}", (3.14, 0.23, 0.18), (0, 0.48, z), bevel=0.02,
           material=yellow_dark, body=base)
# Small fixed details: tie bolts, warning lamps, plates, branding and steps.
for sx in (-1, 1):
    for z in (2.0, 3.6, 5.3, 6.9):
        v4.cylinder(f"frame_bolt_{sx}_{z}", 0.043, 0.04, (sx*1.72, 0.25, z),
                    rot=(math.pi/2, 0, 0), segments=16, material=steel, body=base)
for sx in (-1, 1):
    # Raised work-light stalks tie the lamps into the operator guard structure.
    v4.rod(f"front_work_lamp_stalk_{sx}", (sx*1.0, -2.50, 1.68),
           (sx*0.73, -2.51, 2.65), 0.055, material=yellow_dark, body=base)
    v4.cylinder(f"front_work_lamp_{sx}", 0.105, 0.09, (sx*0.73, -2.51, 2.70), rot=(math.pi/2, 0, 0),
                material=white, body=base)
    v4.cylinder(f"rear_beacon_{sx}", 0.085, 0.08, (sx*0.82, 2.94, 2.0), material=red, body=base)
v4.box("rear_counterweight", (2.35, 0.48, 0.54), (0, 3.08, 0.93), bevel=0.10, material=yellow_dark, body=base)

# Sliding rotary head carriage. Rods are carried by the carriage and telescope into base barrels.
head_z = 4.78
# Twin cheek plates carry the gearbox while leaving a true central spindle aperture.
for sx in (-1, 1):
    v4.box(f"head_carriage_cheek_{sx}", (1.14, 0.48, 1.42), (sx*0.88, 0.54, head_z),
           bevel=0.09, material=yellow, body=head)
    # Four-sided slide shoes closely capture the channel with a narrow running gap.
    v4.box(f"head_wrap_inner_{sx}", (0.12, 0.56, 1.20), (sx*1.49, 0.48, head_z),
           bevel=0.018, material=yellow_dark, body=head)
    v4.box(f"head_wrap_outer_{sx}", (0.12, 0.80, 1.20), (sx*1.93, 0.57, head_z),
           bevel=0.018, material=yellow_dark, body=head)
    for yf in (0.20, 0.95):
        v4.box(f"head_wrap_bridge_{sx}_{yf}", (0.58, 0.06, 1.20), (sx*1.715, yf, head_z),
               bevel=0.018, material=yellow_dark, body=head)
# Captured bearing race bridges the cheek plates and retains the rotating spindle.
v4.torus("spindle_bearing_race", 0.28, 0.05, (0, 0.43, 4.10),
         material=darksteel, body=head)
for sx in (-1, 1):
    v4.box(f"head_guide_shoe_{sx}", (0.14, 0.30, 1.18), (sx*1.49, 0.48, head_z), bevel=0.025,
           material=yellow_dark, body=head)
    v4.box(f"slide_wear_pad_{sx}", (0.08, 0.20, 0.92), (sx*1.49, 0.48, head_z), bevel=0.015,
           material=black, body=head)
    # Long chrome rods remain telescoped in their hollow barrels through the whole feed stroke.
    # The rods are nested about 1.0 m at rest, retain 0.49 m at full lift, and remain
    # above the barrel bottom at full retraction.
    rod_len = 2.25
    rod_top = head_z + 0.10
    v4.cylinder(f"feed_piston_rod_{sx}", 0.100, rod_len,
                (sx*1.28, 1.35, rod_top-rod_len/2),
                segments=40, material=steel, body=head)
    # Crosshead lug meets the carriage side and the piston rod end.
    v4.box(f"feed_crosshead_lug_{sx}", (0.34, 0.82, 0.08), (sx*1.28, 1.12, head_z+0.10),
           bevel=0.012, material=yellow_dark, body=head)
    v4.box(f"feed_head_lug_plate_{sx}", (0.18, 0.50, 0.25), (sx*1.35, 0.78, head_z+0.14),
           bevel=0.035, material=yellow, body=head)
    v4.box(f"feed_rod_end_yoke_{sx}", (0.26, 0.70, 0.10), (sx*1.28, 1.16, head_z+0.15),
           bevel=0.025, material=yellow_dark, body=head)
    v4.cylinder(f"feed_clevis_pin_{sx}", 0.060, 0.42, (sx*1.28, 1.35, head_z+0.15),
                rot=(0, math.pi/2, 0), segments=24, material=steel, body=head)
    # Captured guide rollers just kiss the fixed feed channel faces across full travel.
    for k, zoff in enumerate((-0.40, 0.40)):
        v4.cylinder(f"head_guide_roller_{sx}_{k}", 0.090, 0.20,
                    (sx*1.47, 0.48, head_z+zoff), rot=(math.pi/2, 0, 0),
                    segments=32, material=darksteel, body=head)
# Gearbox housing and bolted access covers.
v4.box("rotary_gearbox", (1.36, 0.83, 1.06), (0, 0.43, head_z+0.05), bevel=0.15,
       material=yellow, body=head)
for sx in (-1, 1):
    v4.box(f"gearbox_side_cover_{sx}", (0.025, 0.62, 0.72), (sx*0.694, 0.43, head_z+0.05),
           bevel=0.07, material=yellow_dark, body=head)
    for i in range(4):
        for j in range(3):
            v4.cylinder(f"gearbox_cover_bolt_{sx}_{i}_{j}", 0.024, 0.025,
                        (sx*0.714, 0.20+i*0.15, head_z-0.18+j*0.22), rot=(0, math.pi/2, 0),
                        segments=12, material=steel, body=head)
# Triple hydraulic drive motors and flexible head-mounted pressure hoses.
for mi, mx in enumerate((-0.44, 0.0, 0.44)):
    v4.cylinder(f"rotary_motor_flange_{mi}", 0.19, 0.08, (mx, 0.43, 5.40),
                segments=40, material=darksteel, body=head)
    v4.cylinder(f"rotary_hydraulic_motor_{mi}", 0.145, 0.27, (mx, 0.43, 5.535),
                segments=40, material=frame_mat, body=head)
    v4.cylinder(f"rotary_motor_cap_{mi}", 0.12, 0.06, (mx, 0.43, 5.70),
                segments=32, material=yellow_dark, body=head)
    for b in range(4):
        a = b*math.tau/4
        v4.cylinder(f"rotary_motor_bolt_{mi}_{b}", 0.022, 0.025,
                    (mx+0.16*math.cos(a), 0.43+0.16*math.sin(a), 5.40),
                    segments=12, material=steel, body=head)
for sx in (-1, 1):
    v4.cylinder(f"head_hose_bulkhead_{sx}", 0.065, 0.12, (sx*0.70, 0.65, 5.37),
                rot=(0, math.pi/2, 0), segments=24, material=bronze, body=head)
    for h in range(2):
        dy = (h-0.5)*0.09
        v4.tube(f"rotary_motor_hose_{sx}_{h}",
                [(sx*0.56, 0.43+dy, 5.56), (sx*0.68, 0.45+dy, 5.68),
                 (sx*0.80, 0.53+dy, 5.61), (sx*0.81, 0.64+dy, 5.48),
                 (sx*0.70, 0.65, 5.37)], 0.025, material=black, body=head, resolution=2)
    v4.cylinder(f"motor_hose_crimp_{sx}", 0.043, 0.09, (sx*0.58, 0.43, 5.56),
                rot=(0, math.pi/2, 0), segments=20, material=steel, body=head)
v4.box("head_warning_panel", (0.76, 0.025, 0.19), (0, 0.0025, head_z+0.28), bevel=0,
       material=yellow_dark, body=head)
v4.box("gearbox_front_bearing_cover", (0.82, 0.035, 0.34), (0, 0.002, head_z-0.10),
       bevel=0.045, material=darksteel, body=head)
v4.cylinder("gearbox_front_output_flange", 0.18, 0.055, (0, -0.025, head_z-0.10),
            rot=(math.pi/2, 0, 0), segments=48, material=steel, body=head)
for sx in (-1, 1):
    for zoff in (-0.22, 0.02):
        v4.cylinder(f"gearbox_front_cover_bolt_{sx}_{zoff}", 0.025, 0.035,
                    (sx*0.34, -0.02, head_z+zoff), rot=(math.pi/2, 0, 0),
                    segments=16, material=yellow_dark, body=head)
for zoff in (-0.48, 0.47):
    v4.cylinder(f"head_clamp_ring_{zoff}", 0.34, 0.15, (0, 0.43, head_z+zoff), segments=48,
                material=darksteel, body=head)
    v4.torus(f"clamp_ring_edge_{zoff}", 0.31, 0.025, (0, 0.43, head_z+zoff+0.078),
             material=steel, body=head)
v4.torus("spindle_gear_guard", 0.38, 0.04, (0, 0.43, 4.24), material=yellow_dark, body=head)

# Rotating drive spindle, mounted on head's central vertical output shaft.
v4.cylinder("spindle_upper_coupling", 0.248, 0.22, (0, 0.43, 4.10), segments=48, material=steel, body=spindle)
v4.cylinder("spindle_shaft", 0.17, 0.60, (0, 0.43, 3.69), segments=48, material=steel, body=spindle)
v4.cylinder("spindle_lower_chuck", 0.31, 0.32, (0, 0.43, 3.23), segments=48, material=darksteel, body=spindle)
v4.torus("chuck_lip", 0.275, 0.035, (0, 0.43, 3.06), material=yellow_dark, body=spindle)
for i in range(8):
    a = i*math.tau/8
    v4.cylinder(f"chuck_jaw_bolt_{i}", 0.035, 0.045, (0.27*math.cos(a), 0.43+0.27*math.sin(a), 3.22),
                segments=16, material=steel, body=spindle)

# Drill string: 1.5 m extension below the carrier, threaded collars and a four-wing pilot.
# Keep the rod's upper end fixed while extending its lower end and pilot.
v4.cylinder("drill_rod", 0.13, 4.30, (0, 0.43, 0.845), segments=48, material=steel, body=string)
# Upper drive sub plus standardized 280 mm tool joints at 1.5 m intervals.
for z, radius, depth in ((3.00, 0.205, 0.22), (2.58, 0.18, 0.10),
                         (1.495, 0.14, 0.22), (-0.005, 0.14, 0.22), (-0.98, 0.14, 0.22)):
    v4.cylinder(f"drill_rod_coupling_{z}", radius, depth, (0, 0.43, z), segments=48,
                material=darksteel, body=string)
for i, z in enumerate((1.36, 1.42, 1.48, -0.14, -0.08, -0.02, -1.08, -1.02)):
    v4.torus(f"rod_thread_band_{i}", 0.126, 0.006, (0, 0.43, z), material=yellow_dark, body=string)
v4.lathe("pilot_bit", [(0.10, 0.00), (0.14, 0.07), (0.17, 0.18), (0.16, 0.34), (0.13, 0.45), (0, 0.45)],
         loc=(0, 0.43, -1.30), material=darksteel, body=string)
for i in range(4):
    a = math.tau*i/4
    v4.rod(f"pilot_cutter_{i}", (0.085*math.cos(a), 0.43+0.085*math.sin(a), -1.25),
           (0.18*math.cos(a), 0.43+0.18*math.sin(a), -1.13), 0.028, material=steel, body=string)
    v4.cylinder(f"pilot_carbide_tip_{i}", 0.035, 0.10,
                (0.18*math.cos(a), 0.43+0.18*math.sin(a), -1.14),
                rot=(0, math.pi/2, 0), segments=16, material=yellow_dark, body=string)

# Side rod-handling arm with a chunky hydraulic-looking pivot and cradle.
arm_pivot = (1.50, 3.40, 1.60)
# Low outboard bracket meets the counterweight below the arm sweep; the clevis boss
# and vertical hinge pin sit clear of the body flank.
v4.rod("arm_mount_outboard_tie", (1.10, 3.10, 1.17), (1.50, 3.40, 1.27), 0.10,
       material=yellow_dark, body=base)
v4.cylinder("arm_mount_pedestal", 0.13, 0.32, (1.50, 3.40, 1.31), segments=32,
            material=yellow_dark, body=base)
v4.cylinder("rod_arm_pivot_housing", 0.19, 0.28, arm_pivot, segments=40,
            material=yellow_dark, body=base)
v4.cylinder("arm_hinge_pin", 0.12, 0.46, arm_pivot, segments=40,
            material=steel, body=base)
v4.torus("arm_pivot_bearing_race", 0.23, 0.04, (1.50, 3.40, 1.79),
         material=darksteel, body=base)
v4.cylinder("arm_rotating_hinge_plate", 0.35, 0.12, (1.50, 3.40, 1.89), segments=40,
            material=yellow, body=arm)
v4.rod("arm_main_link", (1.82, 3.40, 1.82), (2.88, 3.28, 2.45), 0.11, material=yellow, body=arm)
v4.rod("arm_lower_link", (1.82, 3.40, 1.82), (2.83, 3.28, 2.19), 0.07, material=frame_mat, body=arm)
v4.box("rod_cradle", (0.60, 0.55, 0.18), (2.98, 3.28, 2.45), bevel=0.07, material=yellow_dark, body=arm)
for sx in (-1, 1):
    v4.box(f"cradle_ear_{sx}", (0.13, 0.42, 0.34), (2.98+sx*0.28, 3.28, 2.64), bevel=0.055,
           material=yellow, body=arm)
# Articulated hierarchy. Feed frame and power pack are part of fixed base rigid body.
v4.joint("head_feed", "prismatic", base, head, origin=(0, 0.48, head_z), axis=(0, 0, 1), limits=(-1.1, 0.55))
v4.joint("spindle_rotation", "continuous", head, spindle, origin=(0, 0.43, 3.95), axis=(0, 0, 1))
v4.joint("string_rotation", "continuous", spindle, string, origin=(0, 0.43, 2.92), axis=(0, 0, 1))
v4.joint("rod_arm_swing", "revolute", base, arm, origin=arm_pivot, axis=(0, 0, 1),
         limits=(-0.15, 1.10))

# Drill-string deck opening and centralizer bushing. The 350 mm bore stays clear of
# the 230 mm drill rod as the carriage feeds down through the chassis.
deck_plate = v4.box("string_deck_plate", (0.61, 0.80, 0.14), (0, 0.43, 0.46),
                     bevel=0.015, material=frame_mat, body=base)
cutter = v4.cylinder("temporary_bore_cutter", 0.175, 0.30, (0, 0.43, 0.46),
                      segments=64, material=frame_mat, body=base)
v4.boolean(deck_plate, cutter)
v4.torus("string_centralizer", 0.20, 0.025, (0, 0.43, 0.545), material=steel, body=base)
# Heavy slips table / breakout ring around the centralizer, with two bolted torque lugs.
v4.torus("deck_slips_table_ring", 0.29, 0.045, (0, 0.43, 0.63), material=darksteel, body=base)
for sx in (-1, 1):
    v4.box(f"deck_slips_inner_jaw_{sx}", (0.12, 0.34, 0.16), (sx*0.235, 0.43, 0.72),
           bevel=0.025, material=steel, body=base)
    v4.cylinder(f"deck_slips_inner_jaw_pin_{sx}", 0.045, 0.40, (sx*0.31, 0.43, 0.76),
                rot=(math.pi/2, 0, 0), segments=20, material=yellow_dark, body=base)
    v4.box(f"deck_slips_wrench_jaw_{sx}", (0.20, 0.34, 0.18), (sx*0.39, 0.43, 0.58),
           bevel=0.035, material=yellow_dark, body=base)
    v4.cylinder(f"deck_slips_jaw_pin_{sx}", 0.035, 0.06, (sx*0.39, 0.43, 0.69),
                segments=20, material=steel, body=base)

# Weld tiny intersecting static fittings into the chassis surface so the fixed
# assembly is one physically continuous mesh, while sampling back its original materials.
import bmesh
from mathutils.bvhtree import BVHTree
# Convert swept belts and hydraulic lines to mesh so the fixed welded chassis fuses them.
base_curves = [o for o in bpy.data.objects if o.type == "CURVE" and o.parent == base]
if base_curves:
    bpy.ops.object.select_all(action="DESELECT")
    for o in base_curves:
        o.select_set(True)
    bpy.context.view_layer.objects.active = base_curves[0]
    bpy.ops.object.convert(target="MESH")
base_meshes = [o for o in bpy.data.objects if o.type == "MESH" and o.parent == base]
if len(base_meshes) > 1:
    bpy.ops.object.select_all(action="DESELECT")
    for o in base_meshes:
        o.select_set(True)
    bpy.context.view_layer.objects.active = base_meshes[0]
    bpy.ops.object.join()
base_mesh = base_meshes[0]
bm = bmesh.new()
bm.from_mesh(base_mesh.data)
bm.faces.ensure_lookup_table()
source_materials = [f.material_index for f in bm.faces]
source_tree = BVHTree.FromBMesh(bm)
bm.free()
base_mesh.data.remesh_voxel_size = 0.050
bpy.context.view_layer.objects.active = base_mesh
bpy.ops.object.voxel_remesh()
base_mesh.name = "base_integrated_mesh"
for poly in base_mesh.data.polygons:
    hit = source_tree.find_nearest(poly.center)
    if hit and hit[2] >= 0:
        poly.material_index = source_materials[hit[2]]

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