"""Detailed articulated commercial Smith machine. Run with Blender in background."""
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: powder coat, chrome rails/bar, dark machined hardware, and polymer liners.
coat = v4.painted("Graphite powder coat", (0.105, 0.12, 0.14), roughness=0.27, coat=0.48)
coat_light = v4.painted("Frame accent graphite", (0.19, 0.21, 0.23), roughness=0.29, coat=0.4)
chrome = v4.metal("Polished chrome", (0.78, 0.81, 0.83), roughness=0.19, brushed=False)
steel = v4.metal("Machined steel", (0.43, 0.47, 0.5), roughness=0.3, brushed=True)
dark_steel = v4.metal("Dark steel", (0.16, 0.18, 0.2), roughness=0.33, brushed=False)
rubber = v4.rubber("Black rubber", (0.035, 0.04, 0.045))
liner = v4.plastic("Bearing polymer", (0.08, 0.09, 0.095), roughness=0.38, texture=0.12)
red = v4.painted("Safety red", (0.72, 0.035, 0.025), roughness=0.29)
white = v4.mat("Warm white lettering", (0.88, 0.89, 0.86), roughness=0.48)
plate_mat = v4.painted("Cast iron plate", (0.075, 0.08, 0.085), roughness=0.52, coat=0.12)

frame = v4.body("frame")
carriage = v4.body("carriage")
barbell = v4.body("barbell")

# Overall envelope: 1.45 W x 1.25 D x 2.25 H. Four 80 mm square posts.
post_x = (-0.66, 0.66)
front_y, rear_y = -0.49, 0.49
post_bottom, post_top = 0.08, 2.17
post_h = post_top - post_bottom
post_z = (post_top + post_bottom) / 2

# Structural floor runners with welded rounded end caps and feet.
for sy, y in (("front", front_y), ("rear", rear_y)):
    v4.box(f"{sy}_floor_runner", (1.47, 0.12, 0.12), (0, y, 0.085), bevel=0.025, material=coat, body=frame)
    for sx, x in (("left", post_x[0]), ("right", post_x[1])):
        v4.box(f"{sy}_{sx}_foot_pad", (0.22, 0.18, 0.025), (x, y, 0.0125), bevel=0.012, material=rubber, body=frame)
        v4.box(f"{sy}_{sx}_post", (0.082, 0.082, post_h), (x, y, post_z), bevel=0.009, material=coat, body=frame)
        # Base and top collars emphasize welded structural joints.
        v4.box(f"{sy}_{sx}_base_gusset", (0.15, 0.13, 0.045), (x, y, 0.16), bevel=0.008, material=coat_light, body=frame)
        # Top face plates and socket heads make the four corner joints read as
        # bolted structural nodes instead of plain intersecting tubes.
        v4.box(f"{sy}_{sx}_foot_plate", (0.15, 0.14, 0.018), (x, y, 0.188),
               bevel=0.006, material=steel, body=frame)
        for bx in (-0.05, 0.05):
            for by in (-0.045, 0.045):
                v4.cylinder(f"{sy}_{sx}_foot_bolt_{bx}_{by}", 0.008, 0.012,
                            (x+bx, y+by, 0.200), segments=16, bevel=0.001,
                            material=dark_steel, body=frame)
        v4.box(f"{sy}_{sx}_top_cap_plate", (0.14, 0.14, 0.016), (x, y, 2.235),
               bevel=0.006, material=steel, body=frame)
        for bx in (-0.045, 0.045):
            for by in (-0.045, 0.045):
                v4.cylinder(f"{sy}_{sx}_top_bolt_{bx}_{by}", 0.007, 0.010,
                            (x+bx, y+by, 2.248), segments=16, bevel=0.001,
                            material=dark_steel, body=frame)

# Cross-bracing and top header: the rear tie is intentionally below the bar travel.
for x in post_x:
    v4.box(f"side_foot_tie_{x}", (0.10, 0.98, 0.09), (x, 0, 0.09), bevel=0.016, material=coat, body=frame)
v4.box("rear_mid_stabilizer", (1.24, 0.075, 0.12), (0, 0.49, 0.31), bevel=0.012, material=coat_light, body=frame)
v4.box("top_front_header", (1.47, 0.13, 0.14), (0, front_y, 2.17), bevel=0.018, material=coat, body=frame)
v4.box("top_rear_header", (1.47, 0.13, 0.14), (0, rear_y, 2.17), bevel=0.018, material=coat, body=frame)
for x in post_x:
    v4.box(f"top_side_tie_{x}", (0.09, 0.98, 0.11), (x, 0, 2.17), bevel=0.015, material=coat, body=frame)

# Wide knurled pull-up grip above the front header, carried by welded box brackets.
v4.cylinder("pullup_bar", 0.024, 1.20, (0, -0.64, 2.31),
            rot=(0, math.pi/2, 0), segments=48, bevel=0.002,
            material=steel, body=frame)
for side in (-1, 1):
    v4.box(f"pullup_mount_bracket_{side}", (0.16, 0.15, 0.10),
           (side*0.48, -0.59, 2.25), bevel=0.012, material=coat_light, body=frame)
    v4.cylinder(f"pullup_bar_mount_collar_{side}", 0.036, 0.03,
                (side*0.48, -0.64, 2.31), rot=(0, math.pi/2, 0),
                segments=32, bevel=0.003, material=dark_steel, body=frame)
for side in (-1, 1):
    v4.cylinder(f"pullup_grip_{side}", 0.031, 0.25,
                (side*0.23, -0.64, 2.31), rot=(0, math.pi/2, 0),
                segments=40, bevel=0.002, material=rubber, body=frame)
    for k in range(9):
        xx = side*(0.12 + 0.027*k)
        v4.torus(f"pullup_grip_ring_{side}_{k}", 0.031, 0.0012,
                 (xx, -0.64, 2.31), rot=(0, math.pi/2, 0),
                 segments=20, ring_segments=6, material=steel, body=frame)

# Low spotter arms sit just below the carriage's permitted travel, ready to catch
# a bar if a stop pin or carriage restraint fails. Their thick root plates overlap
# the front posts and their capped ends remain clear of the bar in normal travel.
for side, x in ((-1, post_x[0]), (1, post_x[1])):
    arm_x = side*0.55
    v4.box(f"safety_arm_root_{side}", (0.19, 0.12, 0.070), (side*0.61, -0.55, 0.36),
           bevel=0.012, material=coat_light, body=frame)
    v4.box(f"safety_stop_arm_{side}", (0.20, 0.40, 0.045), (arm_x, -0.70, 0.38),
           bevel=0.012, material=dark_steel, body=frame)
    v4.box(f"safety_arm_end_cap_{side}", (0.205, 0.055, 0.050), (arm_x, -0.885, 0.38),
           bevel=0.012, material=rubber, body=frame)

# Twin guide rods sit just inside the front uprights, with substantial end mounts.
rail_xs = (-0.46, 0.46)
rail_y = -0.415
rail_lo, rail_hi = 0.20, 2.08
for i, x in enumerate(rail_xs):
    v4.cylinder(f"guide_rod_{i}", 0.023, rail_hi-rail_lo, (x, rail_y, (rail_hi+rail_lo)/2),
                segments=48, bevel=0.001, material=chrome, body=frame)
    for z in (0.18, 2.10):
        v4.cylinder(f"guide_rod_mount_{i}_{z}", 0.034, 0.045, (x, rail_y, z),
                    segments=32, material=dark_steel, body=frame)
        v4.box(f"guide_rod_mount_plate_{i}_{z}", (0.14, 0.024, 0.10),
               (x, rail_y-0.028, z), bevel=0.006, material=coat_light, body=frame)
        for dx in (-0.050, 0.050):
            for dz in (-0.030, 0.030):
                v4.cylinder(f"guide_mount_socket_{i}_{z}_{dx}_{dz}", 0.008, 0.014,
                            (x+dx, rail_y-0.044, z+dz), rot=(math.pi/2, 0, 0),
                            segments=16, bevel=0.001, material=chrome, body=frame)

    # Elastomer travel stops and chrome retaining rings at both rod ends.
    for stop_z, label in ((0.235, "lower"), (2.045, "upper")):
        stop = v4.cylinder(f"guide_stop_bumper_{i}_{label}", 0.039, 0.032,
                           (x, rail_y, stop_z), segments=40, bevel=0.003,
                           material=rubber, body=frame)
        bore = v4.cylinder(f"guide_stop_bumper_bore_{i}_{label}", 0.0225, 0.040,
                           (x, rail_y, stop_z), segments=32, material=None)
        v4.boolean(stop, bore)
        v4.torus(f"guide_stop_trim_{i}_{label}", 0.031, 0.0025,
                 (x, rail_y, stop_z+(-0.017 if label == "lower" else 0.017)),
                 rot=(0, 0, 0), segments=32, ring_segments=8,
                 material=steel, body=frame)

# Cross ties physically anchor the guide rod end mounts to the front uprights.
for z, name in ((0.18, "lower"), (2.10, "upper")):
    v4.box(f"guide_rod_{name}_cross_tie", (1.42, 0.08, 0.055), (0, rail_y, z),
           bevel=0.008, material=coat_light, body=frame)

# Inboard catch ladders beside the guide rods. Each station is an upward-open seat
# in the XZ plane; the hook sweeps through it as the bar rolls about X.
catch_y = -0.657
# Upward-open slots repeat every 80 mm. The lower seat surface aligns just below
# the hook bend at the +34 degree locking rotation.
catch_zs = [0.531 + 0.08*j for j in range(17)]
for side, post in ((-1, post_x[0]), (1, post_x[1])):
    cx = side * 0.42
    spine_x = side * 0.465
    # Build the catch comb from distinct convex pieces: a backing spine, an
    # upward-facing seat shelf, and a short retaining lip at each 80 mm station.
    # The 90 mm throat is centered on the hook line (X=±0.42 m).
    x_outer, x_inner = side*0.48, side*0.45
    x_lip_center = side*0.35
    v4.box(f"notched_catch_strip_{side}", (0.03, 0.018, 1.92),
           (side*0.465, catch_y, 1.09), bevel=0.001,
           material=dark_steel, body=frame)
    for index, z in enumerate(catch_zs):
        # Split one shelf around the hook lane to provide at least 7 mm of
        # lateral clearance through the parked hook's full -34 degree release.
        if index == 6:
            relief_inner = None
            for part_index, (center_x, width) in enumerate(((0.445, 0.010), (0.378, 0.044))):
                seat_piece = v4.box(f"catch_seat_{side}_{index}_{part_index}", (width, 0.018, 0.018),
                                    (side*center_x, catch_y, z+0.009), bevel=0.001,
                                    material=dark_steel, body=frame)
                if part_index == 1:
                    relief_inner = seat_piece
        else:
            v4.box(f"catch_seat_{side}_{index}", (0.09, 0.018, 0.010),
                   (side*0.405, catch_y, z+0.005), bevel=0.001,
                   material=dark_steel, body=frame)
        catch_lip = v4.box(f"catch_lip_{side}_{index}", (0.020, 0.018, 0.035),
                           (x_lip_center, catch_y, z+0.0275), bevel=0.001,
                           material=dark_steel, body=frame)
        if index == 6:
            v4.boolean(relief_inner, catch_lip, op="UNION")
            # A raised bridge reconnects the split shelf around the hook's swept
            # opening while staying above its full rotational envelope.
            v4.box(f"catch_relief_inner_post_{side}", (0.020, 0.018, 0.180),
                   (x_lip_center, catch_y, z+0.130), bevel=0.001,
                   material=dark_steel, body=frame)
            v4.box(f"catch_relief_bridge_{side}", (0.130, 0.018, 0.012),
                   (side*0.405, catch_y, z+0.220), bevel=0.001,
                   material=dark_steel, body=frame)
    # Box-section clamps bolt the ladder directly to the upright. A broad foot
    # carries its lower end down onto the front base runner.
    v4.box(f"catch_ladder_base_foot_{side}", (0.13, 0.22, 0.09),
           (spine_x, -0.59, 0.165), bevel=0.012, material=coat_light, body=frame)
    # Intermediate box clamps and socket heads make the entire ladder's load
    # path visibly land on the upright, not just at its endpoints.
    for n, z in enumerate((0.23, 0.66, 1.42, 2.00)):
        bracket = v4.box(f"catch_box_bracket_{side}_{n}", (0.18, 0.15, 0.09),
                         (side*0.545, -0.59, z), bevel=0.012,
                         material=coat_light, body=frame)
        # Four large exposed socket heads on each bracket face.
        for dx in (-0.052, 0.052):
            for dz in (-0.024, 0.024):
                v4.cylinder(f"catch_bracket_bolt_{side}_{n}_{dx}_{dz}", 0.010, 0.014,
                            (side*0.545+dx, -0.669, z+dz), rot=(math.pi/2, 0, 0),
                            segments=20, bevel=0.001, material=dark_steel, body=frame)

# Rear storage horns: two low profile holders and three cast plates per side.
for side, x in ((-1, post_x[0]), (1, post_x[1])):
    for level, z in enumerate((0.47, 0.80)):
        start = x + side*0.038
        end = x + side*0.27
        v4.rod(f"plate_horn_{side}_{level}", (start, rear_y, z), (end, rear_y, z), 0.018,
               material=chrome, body=frame)
        v4.cylinder(f"horn_end_stop_{side}_{level}", 0.025, 0.018,
                    (end, rear_y, z), rot=(0, math.pi/2, 0), material=steel, body=frame)
        plate_specs = ((0.126, 0.028), (0.105, 0.034), (0.084, 0.040))
        plate_offsets = (0.100, 0.131, 0.168)
        for j, (radius, thickness) in enumerate(plate_specs):
            px = x + side*plate_offsets[j]
            v4.cylinder(f"stored_plate_{side}_{level}_{j}", radius, thickness,
                        (px, rear_y, z), rot=(0, math.pi/2, 0), segments=48,
                        bevel=0.006, material=plate_mat, body=frame)
            hub_radius = (0.040, 0.034, 0.029)[j]
            v4.cylinder(f"plate_hub_{side}_{level}_{j}", hub_radius, thickness+0.006,
                        (px, rear_y, z), rot=(0, math.pi/2, 0), segments=32,
                        bevel=0.003, material=coat_light, body=frame)

# Linked carriage: one bridge keeps both polymer lined guide blocks level.
v4.box("carriage_crossbridge", (0.99, 0.045, 0.035), (0, -0.3475, 1.10),
       bevel=0.008, material=coat_light, body=carriage)
for i, x in enumerate(rail_xs):
    # Bearing shell surrounds the rod with a 2 mm polymer liner.
    housing = v4.cylinder(f"bearing_housing_{i}", 0.055, 0.17, (x, rail_y, 1.10),
                          segments=48, bevel=0.006, material=coat, body=carriage)
    bore = v4.cylinder(f"bearing_housing_bore_{i}", 0.0255, 0.19, (x, rail_y, 1.10),
                       segments=48, bevel=0, material=None)
    v4.boolean(housing, bore)
    liner_shell = v4.cylinder(f"bearing_liner_{i}", 0.027, 0.174, (x, rail_y, 1.10),
                              segments=48, bevel=0, material=liner, body=carriage)
    liner_bore = v4.cylinder(f"bearing_liner_bore_{i}", 0.0237, 0.19, (x, rail_y, 1.10),
                             segments=48, bevel=0, material=None)
    v4.boolean(liner_shell, liner_bore)
    for z in (1.035, 1.165):
        rim = v4.cylinder(f"bearing_rim_{i}_{z}", 0.058, 0.018, (x, rail_y, z),
                          segments=48, bevel=0.003, material=dark_steel, body=carriage)
        rim_bore = v4.cylinder(f"bearing_rim_bore_{i}_{z}", 0.0255, 0.03,
                               (x, rail_y, z), segments=40, bevel=0, material=None)
        v4.boolean(rim, rim_bore)
    # Four flush socket heads secure each bearing shell to its sliding block.
    for dx in (-0.030, 0.030):
        for dz in (-0.042, 0.042):
            v4.cylinder(f"bearing_socket_{i}_{dx}_{dz}", 0.0065, 0.010,
                        (x+dx, rail_y-0.050, 1.10+dz), rot=(math.pi/2, 0, 0),
                        segments=16, bevel=0.001, material=steel, body=carriage)
    # Arms travel from the guide blocks to the bar axle, with welded gussets.
    sx = -1 if x < 0 else 1
    v4.rod(f"carriage_arm_{i}", (x, -0.468, 1.10), (sx*0.57, -0.56, 1.10), 0.028,
           material=coat_light, body=carriage, square=True)
    # A substantial yoke bridges the forward bearing block to the bar axle while
    # leaving a small running gap around the rotating shaft.
    v4.box(f"carriage_axle_yoke_{i}", (0.12, 0.14, 0.10),
           (sx*0.55, -0.52, 1.10), bevel=0.014, material=coat_light, body=carriage)
    for bx in (-0.032, 0.032):
        v4.cylinder(f"carriage_yoke_bolt_{i}_{bx}", 0.008, 0.012,
                    (sx*0.55+bx, -0.52, 1.158), segments=16,
                    bevel=0.001, material=dark_steel, body=carriage)
    boss = v4.cylinder(f"axle_boss_{i}", 0.063, 0.12, (sx*0.57, -0.62, 1.10),
                       rot=(0, math.pi/2, 0), segments=40, bevel=0.006, material=coat, body=carriage)
    boss_bore = v4.cylinder(f"axle_boss_bore_{i}", 0.030, 0.15, (sx*0.57, -0.62, 1.10),
                            rot=(0, math.pi/2, 0), segments=40, bevel=0, material=None)
    v4.boolean(boss, boss_bore)
    # Fixed inner and outer axle washers belong to carriage, so the bar spins between them.
    for nm, xx in (("inner", sx*0.505), ("outer", sx*0.635)):
        washer = v4.cylinder(f"axle_washer_{nm}_{i}", 0.043, 0.012, (xx, -0.62, 1.10),
                             rot=(0, math.pi/2, 0), segments=32, material=steel, body=carriage)
        washer_bore = v4.cylinder(f"axle_washer_bore_{nm}_{i}", 0.030, 0.02, (xx, -0.62, 1.10),
                                  rot=(0, math.pi/2, 0), segments=32, bevel=0, material=None)
        v4.boolean(washer, washer_bore)

# Captive bar, pivoting around its own long axis. The 50 mm sleeves extend about
# 350 mm beyond the carriage blocks and clear the outer frame uprights.
bar_y, bar_z = -0.62, 1.10
v4.cylinder("bar_shaft", 0.027, 1.29, (0, bar_y, bar_z), rot=(0, math.pi/2, 0),
            segments=64, bevel=0.002, material=chrome, body=barbell)
for side in (-1, 1):
    sleeve_center = side * (0.645 + 0.275/2)
    v4.cylinder(f"loadable_sleeve_{side}", 0.025, 0.275, (sleeve_center, bar_y, bar_z),
                rot=(0, math.pi/2, 0), segments=64, bevel=0.0015, material=chrome, body=barbell)
    v4.cylinder(f"bar_end_collar_{side}", 0.046, 0.035, (side*0.66, bar_y, bar_z),
                rot=(0, math.pi/2, 0), segments=48, bevel=0.004, material=steel, body=barbell)
    # Collared grip sleeves, knurled with fine raised circumferential bands.
    gx = side*0.17
    v4.cylinder(f"knurled_grip_{side}", 0.0295, 0.30, (gx, bar_y, bar_z),
                rot=(0, math.pi/2, 0), segments=48, bevel=0.001, material=dark_steel, body=barbell)
    for k in range(17):
        xx = gx - side*0.14 + side*k*0.0175
        v4.torus(f"grip_ring_{side}_{k}", 0.0295, 0.0007, (xx, bar_y, bar_z),
                 rot=(0, math.pi/2, 0), segments=24, ring_segments=6, material=steel, body=barbell)
    # Fine crossed helical ridges give the grip a real diamond-knurl catch.
    for direction in (-1, 1):
        for phase in range(10):
            points = []
            for sample in range(145):
                t = sample / 144.0
                angle = 2*math.pi*phase/10 + direction*2*math.pi*24*t
                xx = gx - side*0.145 + side*t*0.29
                points.append((xx, bar_y+0.0302*math.cos(angle),
                               bar_z+0.0302*math.sin(angle)))
            v4.tube(f"grip_diamond_knurl_{side}_{direction}_{phase}", points, 0.00045,
                    material=steel, body=barbell, resolution=1)

    # Two iron plates and a lock collar load onto each chrome sleeve. Their bores
    # overlap the sleeve slightly so each added part is physically mounted.
    for plate_index, xoff in enumerate((0.72, 0.775)):
        plate = v4.cylinder(f"bar_plate_{side}_{plate_index}", 0.125, 0.030,
                            (side*xoff, bar_y, bar_z), rot=(0, math.pi/2, 0),
                            segments=64, bevel=0.004, material=plate_mat, body=barbell)
        plate_bore = v4.cylinder(f"bar_plate_bore_{side}_{plate_index}", 0.0245, 0.040,
                                 (side*xoff, bar_y, bar_z), rot=(0, math.pi/2, 0),
                                 segments=48, material=None)
        v4.boolean(plate, plate_bore)
        # Cast center boss and raised ring detail on the plate's outward face.
        face_x = side*(xoff+0.015)
        hub = v4.cylinder(f"bar_plate_hub_{side}_{plate_index}", 0.038, 0.010,
                          (face_x, bar_y, bar_z), rot=(0, math.pi/2, 0),
                          segments=40, bevel=0.002, material=coat_light, body=barbell)
        hub_bore = v4.cylinder(f"bar_plate_hub_bore_{side}_{plate_index}", 0.0245, 0.020,
                               (face_x, bar_y, bar_z), rot=(0, math.pi/2, 0),
                               segments=32, material=None)
        v4.boolean(hub, hub_bore)
    lock = v4.cylinder(f"sleeve_lock_collar_{side}", 0.043, 0.022,
                       (side*0.800, bar_y, bar_z), rot=(0, math.pi/2, 0),
                       segments=48, bevel=0.002, material=steel, body=barbell)
    lock_bore = v4.cylinder(f"sleeve_lock_bore_{side}", 0.0245, 0.032,
                            (side*0.800, bar_y, bar_z), rot=(0, math.pi/2, 0),
                            segments=32, material=None)
    v4.boolean(lock, lock_bore)
    v4.cylinder(f"sleeve_end_cap_{side}", 0.042, 0.024,
                (side*0.902, bar_y, bar_z), rot=(0, math.pi/2, 0),
                segments=48, bevel=0.003, material=dark_steel, body=barbell)
    # Thick welded J hooks sit just inboard of the carriages. The forward return
    # clears the catch strip at rest; rolling the bar +34° swings its lower bend
    # back into an open notch, while -34° moves it farther clear.
    hx = side*0.42
    v4.tube(f"welded_J_hook_{side}",
            [(hx, -0.62, 1.10), (hx, -0.62, 1.075), (hx, -0.63, 1.025),
             (hx, -0.65, 0.995), (hx, -0.73, 1.03), (hx, -0.73, 1.12)],
            0.0140, material=red, body=barbell, resolution=16)
    # Short axial grip levers are welded to each hook tip for rolling the bar
    # into and out of the ladder seats.
    v4.rod(f"hook_rotation_lever_{side}", (side*0.42, -0.73, 1.12),
           (side*0.435, -0.73, 1.12), 0.009, material=steel, body=barbell)
    v4.cylinder(f"hook_lever_grip_{side}", 0.012, 0.062,
                (side*0.466, -0.73, 1.12), rot=(0, math.pi/2, 0),
                segments=24, bevel=0.002, material=rubber, body=barbell)

# Small brand plate and abstract engraved stripes on the front header. (Avoid
# disconnected font glyphs: the icon treatment also reads clearly at distance.)
v4.box("maker_badge", (0.30, 0.012, 0.052), (0, front_y-0.071, 2.17),
       bevel=0.007, material=dark_steel, body=frame)
for i, (w, z) in enumerate(((0.12, 2.17), (0.21, 2.15), (0.16, 2.19))):
    v4.box(f"maker_badge_groove_{i}", (w, 0.004, 0.003), (0, front_y-0.079, z),
           bevel=0.001, material=white, body=frame)

# Small service / safety decals on the inner faces of both front uprights.
for side, x in ((-1, post_x[0]), (1, post_x[1])):
    decal_y = front_y-0.043
    v4.box(f"upright_id_plate_{side}", (0.050, 0.012, 0.145),
           (x, decal_y, 1.87), bevel=0.006, material=dark_steel, body=frame)
    v4.box(f"upright_id_red_rule_{side}", (0.035, 0.004, 0.012),
           (x, decal_y-0.008, 1.915), bevel=0.002, material=red, body=frame)
    for n, (width, z) in enumerate(((0.036, 1.887), (0.028, 1.868), (0.032, 1.849))):
        v4.box(f"upright_id_line_{side}_{n}", (width, 0.004, 0.003),
               (x, decal_y-0.008, z), bevel=0.001, material=white, body=frame)

# Mechanism joints. Slider travel stays inside the rail end mounts. Bar axle passes
# through the two carriage bosses and carries both welded catches as one rigid body.
# Set the bar 25 mm below the initial layout so the welded hook clears the
# tooth above its intended open notch instead of intersecting the seat.
REST_RAISE = -0.025
for obj in bpy.data.objects:
    if obj.parent in (carriage, barbell) and obj.type in {"MESH", "CURVE", "FONT"}:
        world = obj.matrix_world.copy()
        world.translation.z += REST_RAISE
        obj.matrix_world = world

v4.joint("vertical_travel", "prismatic", frame, carriage,
         origin=(0, rail_y, 1.10 + REST_RAISE), axis=(0, 0, 1), limits=(-0.60, 0.80))
v4.joint("bar_rotation", "revolute", carriage, barbell,
         origin=(0, bar_y, bar_z + REST_RAISE), axis=(1, 0, 0), limits=(-0.60, 0.60))

# Merge the contacting fixed frame assemblies into continuous meshes. This keeps
# the rail collars, screw heads, storage horns and plates mechanically continuous
# in the exported rigid-body geometry rather than merely overlapping primitives.
for i in range(2):
    rail = bpy.data.objects[f"guide_rod_{i}"]
    for z in (0.18, 2.10):
        v4.boolean(rail, bpy.data.objects[f"guide_rod_mount_{i}_{z}"], op="UNION")
for side in (-1, 1):
    for level in range(2):
        # Start with the cast plate material so the merged assembly keeps an iron finish.
        assembly = bpy.data.objects[f"stored_plate_{side}_{level}_0"]
        v4.boolean(assembly, bpy.data.objects[f"plate_horn_{side}_{level}"], op="UNION")
        v4.boolean(assembly, bpy.data.objects[f"horn_end_stop_{side}_{level}"], op="UNION")
        for j in (1, 2):
            v4.boolean(assembly, bpy.data.objects[f"stored_plate_{side}_{level}_{j}"], op="UNION")
        for j in range(3):
            v4.boolean(assembly, bpy.data.objects[f"plate_hub_{side}_{level}_{j}"], op="UNION")

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