"""Detailed articulated service biped. Run with Blender: blender -b --python build.py."""
import math
import os
import sys

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

v4.reset()

# -- finishes ---------------------------------------------------------------------
ivory = v4.painted("warm_technical_ceramic", (0.82, 0.85, 0.86), roughness=0.27, coat=0.48)
ivory_shadow = v4.painted("cool_ceramic", (0.57, 0.63, 0.66), roughness=0.31, coat=0.36)
graphite = v4.painted("graphite_composite", (0.075, 0.095, 0.115), roughness=0.38, coat=0.22)
black = v4.rubber("joint_boot_rubber", (0.025, 0.032, 0.04), roughness=0.74)
sole_rubber = v4.rubber("sole_rubber", (0.045, 0.052, 0.06), roughness=0.82)
titanium = v4.metal("satin_titanium", (0.66, 0.71, 0.73), roughness=0.28, brushed=True)
steel_dark = v4.metal("dark_steel", (0.24, 0.29, 0.32), roughness=0.34, brushed=False)
orange = v4.painted("safety_orange", (0.98, 0.27, 0.045), roughness=0.26, coat=0.55)
glass_dark = v4.glass("smoked_optics", (0.045, 0.11, 0.16), roughness=0.06)
cyan = v4.emissive("cyan_status", (0.08, 0.78, 1.0), strength=2.2)
white_emit = v4.emissive("white_sensor_emit", (0.72, 0.91, 1.0), strength=1.5)

# -- dimensions, metres -------------------------------------------------------------
HIP_Z = 0.98
KNEE_Z = 0.57
ANKLE_Z = 0.132
LEG_X = 0.16
RING_X = 0.24
ANKLE_RING_X = 0.27
RING_INNER = 0.039
RING_OUTER = 0.064
RING_DEPTH = 0.040
SHAFT_RADIUS = 0.037


def x_cylinder(name, radius, depth, loc, material, body, bevel=0.0008, segments=40):
    return v4.cylinder(name, radius, depth, loc, rot=(0, math.pi / 2, 0), segments=segments,
                       bevel=bevel, material=material, body=body)


def y_cylinder(name, radius, depth, loc, material, body, bevel=0.0008, segments=40):
    return v4.cylinder(name, radius, depth, loc, rot=(math.pi / 2, 0, 0), segments=segments,
                       bevel=bevel, material=material, body=body)


def bearing_ring(name, body, side, x_center, z_center):
    # A hollow turned housing; the rotor shaft runs through the 39 mm bore.
    half = RING_DEPTH / 2
    profile = [(RING_INNER, -half), (RING_OUTER, -half),
               (RING_OUTER, half), (RING_INNER, half), (RING_INNER, -half)]
    ring = v4.lathe(name, profile, loc=(side * x_center, 0, z_center),
                    rot=(0, math.pi / 2, 0), material=steel_dark, body=body)
    # Fine turned race on the exposed face of the stator ring.
    face_x = side * (x_center + half + 0.001)
    v4.torus(name + "_race", 0.044, 0.0018,
             loc=(face_x, 0, z_center), rot=(0, math.pi / 2, 0),
             material=titanium, body=body)
    for i, angle in enumerate((45, 135, 225, 315)):
        a = math.radians(angle)
        yy = 0.052 * math.cos(a)
        zz = z_center + 0.052 * math.sin(a)
        x_cylinder(f"{name}_bolt_{i}", 0.0042, 0.005,
                   (side * (x_center + half + 0.0025), yy, zz), titanium, body,
                   bevel=0.0004, segments=20)
    # One orange index tick ties the actuator finish together without hiding its race.
    v4.box(name + "_index", (0.004, 0.009, 0.014),
           (side * (x_center + half + 0.0015), 0, z_center + 0.053),
           bevel=0.001, material=orange, body=body)
    return ring


def rotor_shaft(name, body, side, x_center, z_center, depth=0.12):
    x_cylinder(name + "_shaft", SHAFT_RADIUS, depth,
               (side * x_center, 0, z_center), titanium, body, bevel=0.0007)
    end_x = side * (x_center + depth / 2 + 0.004)
    x_cylinder(name + "_retainer", 0.032, 0.010,
               (end_x, 0, z_center), orange, body, bevel=0.001)
    x_cylinder(name + "_center_cap", 0.014, 0.004,
               (side * (x_center + depth / 2 + 0.011), 0, z_center), steel_dark, body,
               bevel=0.0005, segments=32)


def hinge_yoke(name, body, side, pivot_z, shell_edge_x, ring_x, top=True):
    """Twin cheek webs linking a leg shell to its annular stator, clear of the rotor."""
    sign = 1 if ring_x > shell_edge_x else -1
    cx = (shell_edge_x + ring_x) / 2
    span = abs(ring_x - shell_edge_x) + 0.016
    # Webs sit fore and aft of the shaft. Their ends overlap the parent shell and ring rim.
    if top:
        zc = pivot_z + 0.061
    else:
        zc = pivot_z + 0.061
    for yi, sy in enumerate((-1, 1)):
        v4.box(f"{name}_yoke_{yi}", (span, 0.020, 0.046),
               (side * cx, sy * 0.042, zc), bevel=0.004,
               material=graphite, body=body)


# -- chassis: the single root body, torso, pelvis and fixed sensor head ----------------
chassis = v4.body("chassis")

# Two rounded shells meet at the waist and form one rigid torso/pelvis assembly.
v4.box("pelvis_shell", (0.36, 0.25, 0.16), (0, 0, 1.105), bevel=0.035,
       material=graphite, body=chassis)
v4.box("thorax_shell", (0.42, 0.28, 0.39), (0, 0, 1.365), bevel=0.052,
       material=ivory, body=chassis)
v4.box("pelvis_front_armor", (0.285, 0.014, 0.085), (0, -0.132, 1.105),
       bevel=0.018, material=ivory_shadow, body=chassis)
v4.box("waist_service_band", (0.30, 0.012, 0.025), (0, -0.141, 1.105),
       bevel=0.006, material=orange, body=chassis)

# Central chest panel, recessed display and small status lamps.
chest_panel = v4.box("chest_display_bezel", (0.238, 0.015, 0.118), (0, -0.147, 1.397),
                     bevel=0.022, material=ivory_shadow, body=chassis)
screen = v4.box("chest_screen", (0.196, 0.009, 0.076), (0, -0.159, 1.399),
                bevel=0.012, material=graphite, body=chassis)
v4.text("chest_brand", "AURORA  /  SVC-02", 0.018,
        loc=(0, -0.164, 1.399), rot=(math.pi / 2, 0, 0), material=cyan,
        body=chassis, on=screen, height=0.0008)
for sx in (-1, 1):
    for z in (1.355, 1.441):
        y_cylinder(f"chest_fastener_{sx}_{z:.3f}", 0.0045, 0.0035,
                   (sx * 0.104, -0.158, z), titanium, chassis, bevel=0.0004, segments=20)
for i, sx in enumerate((-1, 1)):
    y_cylinder(f"chest_status_{i}", 0.006, 0.004,
               (sx * 0.106, -0.158, 1.395), cyan if i == 0 else white_emit,
               chassis, bevel=0.0005, segments=24)

# Recessed lower sternum grille, vertical ribs sit directly on the ceramic front.
v4.box("sternum_grille_frame", (0.11, 0.010, 0.078), (0, -0.144, 1.273),
       bevel=0.012, material=graphite, body=chassis)
for i in range(5):
    x = (i - 2) * 0.018
    v4.box(f"sternum_grille_vane_{i}", (0.006, 0.004, 0.056), (x, -0.152, 1.273),
           bevel=0.002, material=titanium, body=chassis)

# Rear battery/service hatch and heat exchanger give the broad back shell real hardware.
rear_hatch = v4.box("rear_battery_bezel", (0.27, 0.012, 0.27), (0, 0.146, 1.370),
                    bevel=0.024, material=ivory_shadow, body=chassis)
battery_panel = v4.box("rear_battery_panel", (0.218, 0.008, 0.206), (0, 0.156, 1.370),
                       bevel=0.016, material=graphite, body=chassis)
v4.text("rear_battery_label", "POWER CORE  /  48V", 0.015,
        loc=(0, 0.160, 1.404), rot=(-math.pi / 2, 0, 0), material=cyan,
        body=chassis, on=battery_panel, height=0.0007)
for i in range(5):
    v4.box(f"rear_heat_exchanger_fin_{i}", (0.128, 0.004, 0.004),
           (0, 0.161, 1.307 + i * 0.010), bevel=0.0015,
           material=titanium, body=chassis)
for sx in (-1, 1):
    for z in (1.290, 1.450):
        y_cylinder(f"rear_hatch_fastener_{sx}_{z:.3f}", 0.0045, 0.004,
                   (sx * 0.092, 0.161, z), titanium, chassis,
                   bevel=0.0004, segments=20)
    y_cylinder(f"rear_power_indicator_{sx}", 0.0055, 0.004,
               (sx * 0.061, 0.161, 1.421), cyan if sx > 0 else orange,
               chassis, bevel=0.0004, segments=24)

# Shoulder-side armor and compact ventilation slots.
for side, tag in ((-1, "L"), (1, "R")):
    v4.box(f"shoulder_side_plate_{tag}", (0.016, 0.155, 0.235),
           (side * 0.211, 0.002, 1.385), bevel=0.018, material=ivory_shadow, body=chassis)
    for i in range(4):
        v4.box(f"shoulder_vent_{tag}_{i}", (0.004, 0.075, 0.006),
               (side * 0.221, 0.008, 1.335 + i * 0.018), bevel=0.002,
               material=graphite, body=chassis)
    # Upper hip stator and a bridge from the pelvis side wall to its top rim.
    bearing_ring(f"{tag.lower()}_hip_stator", chassis, side, RING_X, HIP_Z)
    v4.box(f"{tag.lower()}_hip_mount", (0.060, 0.032, 0.030),
           (side * 0.200, 0, 1.040), bevel=0.007, material=graphite, body=chassis)
    v4.box(f"{tag.lower()}_hip_cover", (0.014, 0.022, 0.090),
           (side * 0.229, -0.052, 0.981), bevel=0.008,
           material=ivory_shadow, body=chassis)

# Neck collar and a compact fixed stereo/LiDAR sensor head.
v4.cylinder("neck_pedestal", 0.071, 0.046, (0, 0, 1.555), bevel=0.005,
            material=steel_dark, body=chassis)
v4.cylinder("neck_collar", 0.082, 0.014, (0, 0, 1.575), bevel=0.003,
            material=titanium, body=chassis)
v4.box("sensor_head_shell", (0.25, 0.20, 0.11), (0, 0.012, 1.595),
       bevel=0.035, material=ivory, body=chassis)
visor = v4.box("sensor_visor", (0.205, 0.012, 0.052), (0, -0.092, 1.598),
               bevel=0.016, material=graphite, body=chassis)
for i, sx in enumerate((-1, 1)):
    y_cylinder(f"camera_bezel_{i}", 0.026, 0.010,
               (sx * 0.060, -0.104, 1.600), titanium, chassis, bevel=0.001, segments=40)
    y_cylinder(f"camera_optic_{i}", 0.017, 0.006,
               (sx * 0.060, -0.112, 1.600), glass_dark, chassis, bevel=0.0005, segments=40)
    y_cylinder(f"camera_core_{i}", 0.006, 0.002,
               (sx * 0.060, -0.116, 1.600), cyan if i == 0 else white_emit,
               chassis, bevel=0.0003, segments=24)
# Tiny forward depth sensor between the stereo optics.
y_cylinder("depth_sensor", 0.007, 0.008, (0, -0.102, 1.579), orange,
           chassis, bevel=0.0005, segments=24)

# Roof-mounted 360 degree lidar, with stepped optic rings and a safety index.
v4.cylinder("lidar_base", 0.061, 0.015, (0, 0.012, 1.656), bevel=0.003,
            material=graphite, body=chassis)
v4.cylinder("lidar_band", 0.052, 0.008, (0, 0.012, 1.668), bevel=0.002,
            material=orange, body=chassis)
v4.cylinder("lidar_glass", 0.044, 0.008, (0, 0.012, 1.676), bevel=0.002,
            material=glass_dark, body=chassis)
v4.torus("lidar_luminous_ring", 0.037, 0.0018, loc=(0, 0.012, 1.681),
         material=cyan, body=chassis)

# Small raised model mark on the lower front shell.
v4.text("pelvis_model_mark", "BIPED 01", 0.018,
        loc=(0, -0.144, 1.072), rot=(math.pi / 2, 0, 0),
        material=graphite, body=chassis, on="auto", height=0.0007)


# -- two independent articulated legs ------------------------------------------------
for side, tag in ((-1, "left"), (1, "right")):
    cx = side * LEG_X
    thigh = v4.body(tag + "_thigh")
    shin = v4.body(tag + "_shin")
    foot = v4.body(tag + "_foot")

    # Upper link shell and its front service panel.
    v4.box(f"{tag}_thigh_shell", (0.12, 0.12, 0.27), (cx, 0.045, 0.785),
           bevel=0.034, material=ivory, body=thigh)
    v4.box(f"{tag}_thigh_front_guard", (0.078, 0.010, 0.17), (cx, -0.020, 0.786),
           bevel=0.015, material=ivory_shadow, body=thigh)
    v4.box(f"{tag}_thigh_safety_stripe", (0.070, 0.005, 0.010), (cx, -0.0275, 0.846),
           bevel=0.002, material=orange, body=thigh)
    v4.box(f"{tag}_thigh_dorsal_panel", (0.072, 0.008, 0.17), (cx, 0.109, 0.785),
           bevel=0.012, material=graphite, body=thigh)
    for i in range(5):
        v4.box(f"{tag}_thigh_dorsal_rib_{i}", (0.046, 0.004, 0.004),
               (cx, 0.115, 0.744 + i * 0.014), bevel=0.0012,
               material=titanium, body=thigh)
    for i in range(4):
        v4.box(f"{tag}_thigh_vent_{i}", (0.043, 0.004, 0.004),
               (cx, -0.027, 0.748 + i * 0.012), bevel=0.0015,
               material=graphite, body=thigh)
    for z in (0.715, 0.855):
        x_cylinder(f"{tag}_thigh_side_bolt_{z:.3f}", 0.0045, 0.004,
                   (side * 0.222, 0.055, z), titanium, thigh, bevel=0.0004, segments=20)

    # Hip rotor belongs to the thigh; it passes through the pelvis mounted stator.
    rotor_shaft(f"{tag}_hip_rotor", thigh, side, RING_X, HIP_Z, depth=0.12)
    v4.rod(f"{tag}_hip_neck", (cx, 0, 0.918), (cx, 0, 0.946), 0.034,
           material=steel_dark, body=thigh, bevel=0.0005)

    # Knee stator on the upper link, with two cheek plates into the femur shell.
    bearing_ring(f"{tag}_knee_stator", thigh, side, RING_X, KNEE_Z)
    for i, yy in enumerate((-0.005, 0.050)):
        v4.box(f"{tag}_knee_yoke_{i}", (0.092, 0.022, 0.046),
               (side * 0.224, yy, 0.632), bevel=0.006,
               material=graphite, body=thigh)

    # Lower link with a tapered graphite shin guard, cooling slots and hardware.
    v4.box(f"{tag}_shin_shell", (0.12, 0.145, 0.30), (cx, 0.004, 0.350),
           bevel=0.029, material=ivory, body=shin)
    v4.box(f"{tag}_shin_front_guard", (0.080, 0.010, 0.235), (cx, -0.073, 0.352),
           bevel=0.016, material=graphite, body=shin)
    v4.box(f"{tag}_shin_dorsal_panel", (0.070, 0.008, 0.20), (cx, 0.0805, 0.350),
           bevel=0.012, material=ivory_shadow, body=shin)
    v4.box(f"{tag}_shin_dorsal_recess", (0.050, 0.004, 0.128), (cx, 0.0865, 0.350),
           bevel=0.008, material=graphite, body=shin)
    for i in range(5):
        v4.box(f"{tag}_shin_dorsal_fin_{i}", (0.036, 0.004, 0.004),
               (cx, 0.0905, 0.312 + i * 0.018), bevel=0.0012,
               material=titanium, body=shin)
    v4.box(f"{tag}_shin_badge", (0.066, 0.008, 0.034), (cx, -0.082, 0.426),
           bevel=0.008, material=orange, body=shin)
    for i in range(5):
        v4.box(f"{tag}_shin_louver_{i}", (0.050, 0.004, 0.004),
               (cx, -0.079, 0.319 + i * 0.012), bevel=0.0015,
               material=titanium, body=shin)
    for z in (0.26, 0.44):
        x_cylinder(f"{tag}_shin_side_fastener_{z:.2f}", 0.0045, 0.004,
                   (side * 0.222, 0.049, z), titanium, shin, bevel=0.0004, segments=20)

    # Knee rotor belongs to the shin and runs through the thigh's hollow bearing.
    rotor_shaft(f"{tag}_knee_rotor", shin, side, RING_X, KNEE_Z, depth=0.12)
    v4.rod(f"{tag}_knee_neck", (cx, 0, 0.499), (cx, 0, 0.535), 0.034,
           material=steel_dark, body=shin, bevel=0.0005)

    # Ankle stator on the lower link. It sits outside the foot's wider shell.
    bearing_ring(f"{tag}_ankle_stator", shin, side, ANKLE_RING_X, ANKLE_Z)
    for i, sy in enumerate((-1, 1)):
        v4.box(f"{tag}_ankle_yoke_{i}", (0.078, 0.022, 0.046),
               (side * 0.235, sy * 0.040, 0.194), bevel=0.006,
               material=graphite, body=shin)

    # Foot sole and upper shell; toe points forward along -Y.
    v4.box(f"{tag}_foot_outsole", (0.184, 0.315, 0.020), (cx, -0.043, 0.020),
           bevel=0.007, material=sole_rubber, body=foot)
    v4.box(f"{tag}_foot_shell", (0.18, 0.300, 0.070), (cx, -0.043, 0.064),
           bevel=0.021, material=ivory_shadow, body=foot)
    v4.box(f"{tag}_toe_guard", (0.165, 0.020, 0.033), (cx, -0.188, 0.064),
           bevel=0.009, material=ivory, body=foot)
    v4.box(f"{tag}_toe_safety_mark", (0.105, 0.006, 0.009), (cx, -0.200, 0.064),
           bevel=0.002, material=orange, body=foot)
    # Segmented traction bars touch the outsole underside and remain visible in low views.
    for i, y in enumerate((-0.158, -0.103, -0.048, 0.007, 0.062)):
        v4.box(f"{tag}_tread_{i}", (0.154, 0.026, 0.008), (cx, y, 0.006),
               bevel=0.003, material=black, body=foot)
    # Outer sidewall wear strip and a small forward proximity sensor.
    v4.box(f"{tag}_foot_side_rail", (0.008, 0.21, 0.026),
           (side * 0.252, -0.043, 0.054), bevel=0.006, material=graphite, body=foot)
    x_cylinder(f"{tag}_toe_sensor", 0.008, 0.005,
               (side * 0.251, -0.168, 0.067), cyan, foot, bevel=0.0005, segments=24)

    # Ankle rotor shaft is retained in the foot and passes through the shin stator.
    rotor_shaft(f"{tag}_ankle_rotor", foot, side, ANKLE_RING_X, ANKLE_Z, depth=0.13)

    # Real limited hinges: flexion axis is transverse to the sagittal leg plane.
    v4.joint(f"{tag}_hip", "revolute", chassis, thigh,
             origin=(cx, 0, HIP_Z), axis=(1, 0, 0),
             limits=(-math.radians(35), math.radians(35)))
    v4.joint(f"{tag}_knee", "revolute", thigh, shin,
             origin=(cx, 0, KNEE_Z), axis=(1, 0, 0),
             limits=(-math.radians(112), math.radians(8)))
    v4.joint(f"{tag}_ankle", "revolute", shin, foot,
             origin=(cx, 0, ANKLE_Z), axis=(1, 0, 0),
             limits=(-math.radians(25), math.radians(25)))

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