"""Detailed articulated 37-note performance keytar. Run with 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()

# Materials: a restrained modern red/charcoal performance-instrument palette.
red = v4.painted("Candy_red_shell", color=(0.55, 0.025, 0.045), roughness=0.27)
red_dark = v4.painted("Deep_red_trim", color=(0.22, 0.012, 0.022), roughness=0.3)
charcoal = v4.plastic("Charcoal_chassis", color=(0.035, 0.043, 0.052), roughness=0.42)
well = v4.rubber("Keywell_rubber", color=(0.018, 0.022, 0.027), roughness=0.72)
ivory = v4.plastic("Ivory_keys", color=(0.91, 0.89, 0.82), roughness=0.28)
black = v4.plastic("Black_keys", color=(0.024, 0.027, 0.032), roughness=0.24)
metal = v4.metal("Satin_aluminum", color=(0.59, 0.64, 0.69), roughness=0.28, brushed=True)
dark_metal = v4.metal("Dark_hardware", color=(0.15, 0.17, 0.19), roughness=0.36, brushed=False)
rubber = v4.rubber("Grip_rubber", color=(0.028, 0.031, 0.034), roughness=0.8)
orange = v4.plastic("Trigger_orange", color=(0.96, 0.12, 0.018), roughness=0.25)
green = v4.emissive("Status_green", color=(0.04, 0.75, 0.22), strength=1.4)
amber = v4.emissive("Status_amber", color=(1.0, 0.36, 0.025), strength=1.1)
print_white = v4.mat("Warm_white_print", color=(0.85, 0.88, 0.88), roughness=0.5)

shell = v4.body("shell")

# Neck components use a local frame running forward from the keybed shoulder.
# The 13-degree rise gives the left hand a slim, lifted control handle.
neck_angle = math.radians(13.0)
neck_origin = (0.405, 0.055, 0.025)
neck_rotation = (0.0, -neck_angle, 0.0)

def neck_point(s, lateral=0.0, height=0.0):
    ca, sa = math.cos(neck_angle), math.sin(neck_angle)
    return (neck_origin[0] + s*ca + height*sa,
            neck_origin[1] + lateral,
            neck_origin[2] + s*sa + height*ca)

def neck_box(name, size, s, lateral, height, **kwargs):
    return v4.box(name, size, neck_point(s, lateral, height),
                  rot=neck_rotation, **kwargs)

# Lower molded chassis and red upper shell. The plan-view perimeter makes a
# recognizable broad key wing and narrows into the projecting performance neck.
outline = [(-0.47, -0.19), (0.36, -0.19), (0.45, -0.15), (0.49, -0.09),
           (0.49, 0.12), (0.41, 0.18), (-0.425, 0.18), (-0.47, 0.11)]
v4.extrude("one_piece_lower_chassis", outline, 0.073, loc=(0, 0, 0.025), bevel=0.010,
           material=charcoal, body=shell)
# A narrow, raised handle grows from the keybed shoulder. Both layers share the
# same local outline, so the underbody stays flush with the red deck.
neck_outline = [(0.0, -0.085), (0.055, -0.065), (0.150, -0.035),
                (0.505, -0.035), (0.56, -0.026), (0.56, 0.026),
                (0.505, 0.035), (0.150, 0.035), (0.055, 0.065), (0.0, 0.085)]
v4.extrude("solid_neck_underbody", neck_outline, 0.073,
           loc=neck_origin, rot=neck_rotation, bevel=0.008,
           material=charcoal, body=shell)
# Main glossy top wing and neck insert; slight height layering creates a molded shell seam.
red_keybed_shroud = v4.extrude("red_keybed_shroud", [(-0.455, -0.175), (0.35, -0.175), (0.435, -0.13),
           (0.445, 0.105), (0.38, 0.16), (-0.425, 0.16), (-0.46, 0.11)],
           0.025, loc=(0, 0, 0.098), bevel=0.008, material=red, body=shell)
red_neck_shroud = v4.extrude("red_neck_shroud", neck_outline, 0.027,
           loc=neck_point(0.0, 0.0, 0.073), rot=neck_rotation,
           bevel=0.008, material=red, body=shell)

# Crosswise hinge barrels sit in shallow, close-fitting clearance notches.
trigger_stations = (0.135, 0.465)
for station in trigger_stations:
    cutter = v4.cylinder("trigger_axle_clearance", 0.010, 0.053,
                         neck_point(station+0.021, 0.0, 0.1075),
                         rot=(math.pi/2, -neck_angle, 0), bevel=0,
                         material=None, body=None)
    v4.boolean(red_neck_shroud, cutter)

# Keybed well and rear rail.
keybed_well = v4.box("keybed_well", (0.805, 0.355, 0.009), (-0.005, -0.006, 0.120),
       bevel=0.004, material=well, body=shell)
v4.box("rear_key_hinge_rail", (0.802, 0.018, 0.038), (-0.005, 0.153, 0.136),
       bevel=0.003, material=dark_metal, body=shell)
v4.box("front_key_lip", (0.82, 0.014, 0.012), (-0.005, -0.182, 0.13),
       bevel=0.003, material=red_dark, body=shell)

# 37 semitones C2 through C5: mirrored so the low-note end meets the neck.
key_span = 0.78
pitch = key_span / 22.0
white_w = pitch - 0.0028
white_y_front, white_y_back = -0.166, 0.143
white_hinge_y = white_y_back
white_hinge_z = 0.155
white_index = 0
black_centers = []
black_after = []
for octave in range(3):
    black_after.extend([octave * 7 + 0, octave * 7 + 1, octave * 7 + 3,
                        octave * 7 + 4, octave * 7 + 5])
# Open a generous keywell under the white-key travel arc. The lower chassis roof
# remains below the 4.5-degree press envelope, while the rear hinge strip stays intact.
slot = v4.box("white_key_sweep_cutter", (0.79, 0.305, 0.08),
              (-0.005, -0.0225, 0.105), bevel=0, material=None, body=None)
v4.boolean(red_keybed_shroud, slot)
slot = v4.box("white_well_sweep_cutter", (0.79, 0.305, 0.08),
              (-0.005, -0.0225, 0.105), bevel=0, material=None, body=None)
v4.boolean(keybed_well, slot)
for wi in range(22):
    cx = -(-key_span / 2 + (wi + 0.5) * pitch)
    kb = v4.body(f"white_key_{wi:02d}")
    # Deep skirt and clean ivory cap are fixed together on the moving key body.
    v4.box(f"white_key_skirt_{wi:02d}", (white_w - 0.001, 0.304, 0.012),
           (cx, (white_y_front + white_y_back) / 2, 0.1365), bevel=0.0025,
           material=ivory, body=kb)
    v4.box(f"white_key_cap_{wi:02d}", (white_w, 0.300, 0.012),
           (cx, (white_y_front + white_y_back) / 2, 0.1485), bevel=0.0032,
           material=ivory, body=kb)
    v4.box(f"white_hinge_foot_{wi:02d}", (white_w-0.003, 0.004, 0.004),
           (cx, 0.142, 0.1285), bevel=0.0008, material=dark_metal, body=kb)
    v4.joint(f"white_key_hinge_{wi:02d}", "revolute", shell, kb,
             origin=(cx, white_hinge_y, white_hinge_z), axis=(1, 0, 0),
             limits=(0, math.radians(4.5)))

# Black keys sit behind the white fronts; their bases are separated vertically from
# the white caps, as on a real keyboard, while leaving the front touch surfaces exposed.
for bi, boundary in enumerate(black_after):
    cx = -(-key_span / 2 + (boundary + 1) * pitch)
    b = v4.body(f"black_key_{bi:02d}")
    width = 0.0205
    back = 0.143
    front = 0.004
    hinge_z = 0.165
    # A shallow front ramp and broad edge round make the accidental read as a
    # molded key rather than a rectangular block.
    black_profile = [(-0.156, back), (-0.172, back), (-0.172, front+0.012),
                     (-0.168, front), (-0.156, front)]
    v4.extrude(f"black_keycap_{bi:02d}", black_profile, width,
               loc=(cx-width/2, 0, 0), rot=(0, math.pi/2, 0),
               bevel=0.0025, material=black, body=b)
    # A short concealed hinge saddle continues from the keybed to the rear end
    # of each accidental. It meets the key at the pivot edge and stays behind it.
    v4.box(f"black_key_saddle_{bi:02d}", (width-0.002, 0.012, 0.029),
           (cx, back+0.006, 0.1405), bevel=0.001, material=dark_metal, body=shell)
    v4.joint(f"black_key_hinge_{bi:02d}", "revolute", shell, b,
             origin=(cx, back, hinge_z), axis=(1, 0, 0), limits=(0, math.radians(4.5)))

# A proper control strip occupies the red shoulder beside the treble keys.
panel_x, panel_z = -0.432, 0.125
v4.box("control_panel_inlay", (0.042, 0.180, 0.004), (panel_x, 0.035, panel_z),
       bevel=0.004, material=red_dark, body=shell)
v4.box("control_panel_inner", (0.035, 0.170, 0.002), (panel_x, 0.035, 0.128),
       bevel=0.003, material=charcoal, body=shell)
v4.box("status_display_frame", (0.031, 0.047, 0.005), (panel_x, 0.072, 0.1315),
       bevel=0.004, material=dark_metal, body=shell)
v4.box("status_display_glass", (0.025, 0.038, 0.002), (panel_x, 0.072, 0.135),
       bevel=0.002, material=well, body=shell)
for i, m in enumerate((green, amber, green)):
    v4.cylinder(f"display_led_{i}", 0.0022, 0.0015,
                (panel_x-0.007+i*0.007, 0.072, 0.1365),
                bevel=0.0002, material=m, body=shell)
for ki, (label, py) in enumerate((("VOL", -0.042), ("OCT", 0.005))):
    v4.cylinder(f"control_knob_base_{ki}", 0.014, 0.006,
                (panel_x, py, 0.132), bevel=0.0015, material=dark_metal, body=shell)
    v4.cylinder(f"control_knob_{ki}", 0.0105, 0.012,
                (panel_x, py, 0.141), bevel=0.002, material=metal, body=shell)
    v4.box(f"knob_index_{ki}", (0.0015, 0.005, 0.001),
           (panel_x, py+0.004, 0.1475), bevel=0.0003, material=print_white, body=shell)
    v4.text(f"control_label_{ki}", label, 0.0055,
            loc=(panel_x+0.014, py, 0.1292), extrude_depth=0.00035,
            material=print_white, body=shell)
for bi, (bx, label) in enumerate(((panel_x-0.009, "-"), (panel_x+0.009, "+"))):
    v4.cylinder(f"program_button_{bi}", 0.0058, 0.005,
                (bx, 0.112, 0.1315), bevel=0.001, material=orange, body=shell)
    v4.text(f"program_label_{bi}", label, 0.006,
            loc=(bx, 0.099, 0.1292), extrude_depth=0.00035,
            material=print_white, body=shell)
v4.text("program_panel_label", "PRG", 0.0055,
        loc=(panel_x+0.014, 0.112, 0.1292), extrude_depth=0.00035,
        material=print_white, body=shell)

# Spring-return trigger caps and the thumb wheel sit directly on the angled neck.
# The trigger pivots run across the handle; negative rotation presses their fronts down.
for ti, station in enumerate(trigger_stations):
    # Four rails leave a real opening under the cap's press arc.
    for edge, lateral in enumerate((-1, 1)):
        neck_box(f"trigger_bezel_side_{ti}_{edge}", (0.078, 0.006, 0.008),
                 station, lateral*0.028, 0.104, bevel=0.002,
                 material=dark_metal, body=shell)
    for edge, along in enumerate((-1, 1)):
        neck_box(f"trigger_bezel_end_{ti}_{edge}", (0.008, 0.050, 0.008),
                 station+along*0.035, 0.0, 0.104, bevel=0.002,
                 material=dark_metal, body=shell)
    b = v4.body(f"trigger_{ti}")
    neck_box(f"trigger_cap_{ti}", (0.052, 0.043, 0.015), station, 0.0, 0.117,
             bevel=0.007, material=orange, body=b)
    neck_box(f"trigger_cap_mark_{ti}", (0.023, 0.003, 0.0015), station-0.004, 0.0, 0.125,
             bevel=0.0008, material=print_white, body=b)
    # A coaxial hinge barrel reaches the deck and remains stationary as the cap pivots.
    v4.cylinder(f"trigger_axle_{ti}", 0.0075, 0.048,
                neck_point(station+0.021, 0.0, 0.1075),
                rot=(math.pi/2, -neck_angle, 0), bevel=0.001,
                material=dark_metal, body=b)
    v4.joint(f"trigger_hinge_{ti}", "revolute", shell, b,
             origin=neck_point(station+0.021, 0.0, 0.1075), axis=(0, 1, 0),
             limits=(-0.12, 0))

# Modulation wheel is a grippy crosswise roller in a shallow, clearance-fit pocket.
wheel_station = 0.300
wheel_pivot = neck_point(wheel_station, 0.0, 0.130)
neck_box("mod_wheel_well", (0.083, 0.064, 0.003), wheel_station, 0.0, 0.1025,
         bevel=0.010, material=black, body=shell)
wheel = v4.body("mod_wheel")
v4.cylinder("mod_wheel_rubber", 0.022, 0.055, wheel_pivot,
            rot=(math.pi/2, 0, 0), segments=48, bevel=0.003, material=rubber, body=wheel)
for rib in range(9):
    lateral = -0.024 + rib*0.006
    v4.cylinder(f"mod_wheel_tread_{rib}", 0.023, 0.0014,
                neck_point(wheel_station, lateral, 0.130),
                rot=(math.pi/2, 0, 0), segments=40, bevel=0.0005,
                material=dark_metal, body=wheel)
for sx in (-1, 1):
    v4.cylinder(f"mod_axle_cap_{sx}", 0.006, 0.002,
                neck_point(wheel_station, sx*0.029, 0.130),
                rot=(math.pi/2, 0, 0), segments=24, bevel=0.0005,
                material=metal, body=wheel)
v4.joint("mod_wheel_hinge", "revolute", shell, wheel,
         origin=wheel_pivot, axis=(0, 1, 0), limits=(-0.30, 0.30))
# Raised slot shoulders keep the roller visually nested while leaving its swing arc clear.
for side in (-1, 1):
    neck_box(f"mod_wheel_slot_rail_{side}", (0.010, 0.062, 0.018),
             wheel_station+side*0.036, 0.0, 0.111,
             bevel=0.004, material=charcoal, body=shell)

# Shoulder strap lugs: one at the body end and one at the raised neck tip.
for side, (lx, ly) in enumerate(((-0.435, -0.045),)):
    v4.box(f"strap_lug_pad_{side}", (0.052, 0.032, 0.008), (lx, ly, 0.107),
           bevel=0.006, material=red_dark, body=shell)
    v4.torus(f"strap_lug_loop_{side}", 0.016, 0.0035, (lx, ly, 0.119),
             rot=(math.pi/2, 0, 0), material=metal, body=shell)
    v4.cylinder(f"strap_lug_pin_{side}", 0.004, 0.032, (lx, ly, 0.119),
                rot=(math.pi/2, 0, 0), bevel=0.0005, material=dark_metal, body=shell)
    for sx in (-1, 1):
        v4.cylinder(f"lug_screw_{side}_{sx}", 0.003, 0.002,
                    (lx + sx*0.016, ly, 0.113), rot=(0, 0, 0),
                    segments=16, bevel=0.0004, material=metal, body=shell)

neck_lug_s, neck_lug_h = 0.535, 0.105
neck_box("strap_lug_pad_1", (0.046, 0.030, 0.008), neck_lug_s, 0.0, neck_lug_h,
         bevel=0.005, material=red_dark, body=shell)
v4.torus("strap_lug_loop_1", 0.015, 0.0032, neck_point(neck_lug_s, 0.0, 0.123),
         rot=(math.pi/2, 0, 0), material=metal, body=shell)
for sx in (-1, 1):
    neck_box(f"lug_screw_1_{sx}", (0.003, 0.002, 0.002), neck_lug_s+sx*0.014, 0.0, 0.111,
             bevel=0.0003, material=metal, body=shell)

# Separate body-end strap button with a narrow stem and retaining mushroom head.
button_x, button_y = -0.435, -0.145
v4.cylinder("body_strap_button_base", 0.011, 0.006,
            (button_x, button_y, 0.126), bevel=0.0015, material=dark_metal, body=shell)
v4.cylinder("body_strap_button_stem", 0.0045, 0.013,
            (button_x, button_y, 0.1355), bevel=0.001, material=metal, body=shell)
v4.cylinder("body_strap_button_head", 0.009, 0.004,
            (button_x, button_y, 0.144), bevel=0.0015, material=metal, body=shell)

# Three recessed 1/4-inch/MIDI-style output sockets on the back edge.
for ji, jx in enumerate((-0.29, -0.21, -0.13)):
    v4.cylinder(f"output_jack_shell_{ji}", 0.010, 0.012, (jx, 0.179, 0.073),
                rot=(math.pi/2, 0, 0), bevel=0.001, material=dark_metal, body=shell)
    v4.torus(f"output_jack_rim_{ji}", 0.009, 0.0018, (jx, 0.184, 0.073),
             rot=(math.pi/2, 0, 0), material=metal, body=shell)
    v4.cylinder(f"output_jack_socket_{ji}", 0.0045, 0.002,
                (jx, 0.186, 0.073), rot=(math.pi/2, 0, 0),
                bevel=0.0005, material=black, body=shell)
    jack_label = ("OUT", "USB", "MIDI")[ji]
    v4.text(f"output_jack_label_{ji}", jack_label, 0.0048,
            loc=(jx, 0.151, 0.124), extrude_depth=0.00035,
            material=print_white, body=shell)

# Side speaker perforations and decorative heat vents on the lower wing.
for row in range(3):
    for col in range(9):
        x = -0.325 + col*0.027
        y = -0.094 + row*0.012
        v4.box(f"speaker_slot_{row}_{col}", (0.015, 0.002, 0.003),
               (x, -0.189, 0.058 + row*0.010),
               bevel=0.0007, material=black, body=shell)
for i in range(4):
    neck_box(f"neck_grip_rib_{i}", (0.008, 0.052, 0.002), 0.035+i*0.018, 0.0, 0.101,
             bevel=0.002, material=rubber, body=shell)
# Soft, rounded palm pad on the underside, with fine transverse anti-slip ribs.
neck_box("neck_underside_grip", (0.315, 0.052, 0.006), 0.295, 0.0, -0.002,
         bevel=0.0028, material=rubber, body=shell)
for i in range(8):
    neck_box(f"underside_grip_rib_{i}", (0.003, 0.044, 0.001),
             0.16+i*0.038, 0.0, -0.0055, bevel=0.0004,
             material=well, body=shell)
for side in (-1, 1):
    neck_box(f"neck_side_grip_{side}", (0.235, 0.004, 0.032), 0.315, side*0.034, 0.038,
             bevel=0.003, material=rubber, body=shell)
    for i in range(7):
        neck_box(f"neck_side_grip_rib_{side}_{i}", (0.0025, 0.003, 0.024),
                 0.215+i*0.033, side*0.037, 0.038, bevel=0.001,
                 material=well, body=shell)

# Perimeter fasteners and tiny connector details.
for si, (sx, sy) in enumerate(((-0.405, -0.155), (0.395, -0.155),
                               (-0.405, 0.135), (0.405, 0.135))):
    v4.cylinder(f"shell_screw_{si}", 0.0032, 0.0015, (sx, sy, 0.125),
                bevel=0.0004, material=metal, body=shell)
for si, station in enumerate((0.505,)):
    for side in (-1, 1):
        neck_box(f"neck_screw_{si}_{side}", (0.003, 0.002, 0.002), station, side*0.024, 0.101,
                 bevel=0.0003, material=metal, body=shell)

# Front edge maker plaque and small printed model mark.
v4.box("brand_badge", (0.160, 0.003, 0.024), (0.0, -0.1905, 0.067),
       rot=(math.pi/2, 0, 0), bevel=0.003, material=red_dark, body=shell)
v4.text("brand_mark", "ARIA  |  STAGE 37", 0.011,
        loc=(0.0, -0.1921, 0.067), rot=(math.pi/2, 0, 0),
        extrude_depth=0.0004, material=print_white, body=shell)

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