"""Mossback BK-07 (v6, the weight pass of 2026-11-21): a scripted walking mech for Blender 5.2 (BYOK Studio).

Run:  blender -b --factory-startup -P mech.py -- <out_dir>

Method (adopted from the public Higgsfield thread, then extended):
  * build around a scale pilot: the cab fits a seated adult, the hull follows
    the cab, the legs follow the hull;
  * every part is its own named object on one rigid body (an empty);
  * joints are real: hip ball joints with 4% clearance, pinned hinges with
    4% bore clearance and axial gaps, a cardan (universal) ankle, piston
    eyes on pins or spherical rod ends;
  * pistons are sized from the walk itself, so rods always stay inside
    their sleeves and never bottom out;
  * a numbered .blend is saved after each stage.
"""
import bpy, bmesh, math, json, os, sys
from mathutils import Vector, Matrix, Quaternion
from math import sin, cos, pi, radians, sqrt, acos, exp, floor

ARGS = sys.argv[sys.argv.index('--') + 1:] if '--' in sys.argv else []
OUT = ARGS[0] if ARGS else './blend'
os.makedirs(OUT, exist_ok=True)

# ---------------------------------------------------------------- walk params
FPS = 24
TC = 2.5            # one full gait cycle (two steps), seconds
NCYC = 4
NF = int(round(TC * NCYC * FPS))   # 240 frames = 10 s, seamless loop
STEP = 1.35         # step length, m
V = 2 * STEP / TC   # forward speed, m/s
LOOP_DIST = V * TC * NCYC
DUTY = 0.62         # stance fraction of the cycle
HIP_Y = 0.85
FOOT_Y = 0.90
L1 = 1.20           # thigh: hip centre to knee pin
L2 = 1.20           # shin: knee pin to ankle pitch pin
ROLL_H = 0.30       # ankle roll axis above the sole
SDROP = 0.19        # pitch pin above the roll pin (cardan spider)
HIP_Z0 = 2.56
LIFT = 0.17          # v5: was 0.30; a high springy knee lift read as a light toy
TOE_OUT = radians(4)
CLR = 1.04          # 4% bore / socket clearance

# ---------------------------------------------------------------- scene reset
bpy.ops.wm.read_factory_settings(use_empty=True)
SC = bpy.context.scene
SC.render.fps = FPS
SC.frame_start = 0
SC.frame_end = NF - 1
MECH = bpy.data.collections.new('mech')
SC.collection.children.link(MECH)

BODIES = {}
PARTS = []      # dicts: name, body, kind
MATS = {}


def mat(name):
    if name not in MATS:
        m = bpy.data.materials.new(name)
        MATS[name] = m
    return MATS[name]


def body(name):
    e = bpy.data.objects.new('B_' + name, None)
    e.empty_display_size = 0.15
    e.rotation_mode = 'QUATERNION'
    MECH.objects.link(e)
    BODIES[name] = e
    return e


# ---------------------------------------------------------------- mesh helpers
def bm_new():
    return bmesh.new()


def add_mesh(bm, verts, faces):
    base = len(bm.verts)
    vs = [bm.verts.new(v) for v in verts]
    bm.verts.ensure_lookup_table()
    for f in faces:
        ids = []
        for i in f:
            if not ids or ids[-1] != i:
                ids.append(i)
        if len(ids) > 1 and ids[0] == ids[-1]:
            ids.pop()
        if len(set(ids)) < 3:
            continue
        try:
            bm.faces.new([vs[i] for i in ids])
        except ValueError:
            pass
    return bm


def lathe(profile, segs=32, M=None, bm=None):
    """Closed (r, z) profile revolved about local Z."""
    bm = bm or bm_new()
    verts, idx = [], []
    for (r, z) in profile:
        if r < 1e-7:
            verts.append((0, 0, z))
            idx.append([len(verts) - 1] * segs)
        else:
            row = []
            for i in range(segs):
                a = 2 * pi * i / segs
                verts.append((r * cos(a), r * sin(a), z))
                row.append(len(verts) - 1)
            idx.append(row)
    faces = []
    n = len(profile)
    for j in range(n):
        j2 = (j + 1) % n
        for i in range(segs):
            i2 = (i + 1) % segs
            faces.append([idx[j][i], idx[j][i2], idx[j2][i2], idx[j2][i]])
    tmp = bm_new()
    add_mesh(tmp, verts, faces)
    bmesh.ops.recalc_face_normals(tmp, faces=tmp.faces)
    if M is not None:
        bmesh.ops.transform(tmp, matrix=M, verts=tmp.verts)
    return merge(bm, tmp)


def merge(bm, other):
    me = bpy.data.meshes.new('_tmp')
    other.to_mesh(me)
    other.free()
    bm.from_mesh(me)
    bpy.data.meshes.remove(me)
    return bm


def prism(poly, a0, a1, plane='XZ', M=None, bm=None):
    """Extrude a 2D polygon. plane XZ: poly in (x, z), extruded along y from a0 to a1."""
    bm = bm or bm_new()
    n = len(poly)

    def P(u, v, w):
        if plane == 'XZ':
            return (u, w, v)
        if plane == 'XY':
            return (u, v, w)
        if plane == 'YZ':
            return (w, u, v)
    verts = [P(u, v, a0) for (u, v) in poly] + [P(u, v, a1) for (u, v) in poly]
    faces = [list(range(n)), list(range(2 * n - 1, n - 1, -1))]
    for i in range(n):
        i2 = (i + 1) % n
        faces.append([i, i2, n + i2, n + i])
    tmp = bm_new()
    add_mesh(tmp, verts, faces)
    bmesh.ops.recalc_face_normals(tmp, faces=tmp.faces)
    if M is not None:
        bmesh.ops.transform(tmp, matrix=M, verts=tmp.verts)
    return merge(bm, tmp)


def box(c, s, M=None, bm=None):
    x, y, z = c
    sx, sy, sz = s[0] / 2, s[1] / 2, s[2] / 2
    poly = [(x - sx, z - sz), (x + sx, z - sz), (x + sx, z + sz), (x - sx, z + sz)]
    return prism(poly, y - sy, y + sy, 'XZ', M, bm)


def boxr(x0, x1, y0, y1, z0, z1, M=None, bm=None):
    return box(((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2),
               (abs(x1 - x0), abs(y1 - y0), abs(z1 - z0)), M, bm)


def sphere(c, r, M=None, bm=None, u=32, v=16):
    tmp = bm_new()
    bmesh.ops.create_uvsphere(tmp, u_segments=u, v_segments=v, radius=r)
    bmesh.ops.translate(tmp, vec=Vector(c), verts=tmp.verts)
    if M is not None:
        bmesh.ops.transform(tmp, matrix=M, verts=tmp.verts)
    return merge(bm or bm_new(), tmp)


def axis_M(axis, c=(0, 0, 0)):
    """Matrix taking local Z to the given axis, translated to c."""
    if isinstance(axis, str):
        axis = {'X': Vector((1, 0, 0)), 'Y': Vector((0, 1, 0)), 'Z': Vector((0, 0, 1)),
                '-X': Vector((-1, 0, 0)), '-Y': Vector((0, -1, 0)), '-Z': Vector((0, 0, -1))}[axis]
    axis = Vector(axis).normalized()
    q = Vector((0, 0, 1)).rotation_difference(axis)
    return Matrix.Translation(Vector(c)) @ q.to_matrix().to_4x4()


def cyl(c, r, h, axis='Z', segs=32, bm=None):
    return lathe([(0, -h / 2), (r, -h / 2), (r, h / 2), (0, h / 2)], segs, axis_M(axis, c), bm)


def tube(c, ri, ro, h, axis='Z', segs=32, bm=None):
    return lathe([(ri, -h / 2), (ro, -h / 2), (ro, h / 2), (ri, h / 2)], segs, axis_M(axis, c), bm)


def seg_cyl(p0, p1, r, segs=20, bm=None):
    p0, p1 = Vector(p0), Vector(p1)
    d = p1 - p0
    return lathe([(0, 0), (r, 0), (r, d.length), (0, d.length)], segs, axis_M(d, p0), bm)


def capsule(p0, p1, r, segs=20, bm=None):
    p0, p1 = Vector(p0), Vector(p1)
    d = p1 - p0
    L = d.length
    prof = []
    n = 6
    for i in range(n + 1):
        a = -pi / 2 + (pi / 2) * i / n
        prof.append((r * cos(a), r * sin(a)))
    for i in range(n + 1):
        a = (pi / 2) * i / n
        prof.append((r * cos(a), L + r * sin(a)))
    prof = [(abs(x) if abs(x) > 1e-6 else 0.0, z) for x, z in prof]
    return lathe(prof, segs, axis_M(d, p0), bm)


def hexbolts(points, normal, r=0.022, h=0.014, bm=None):
    bm = bm or bm_new()
    for p in points:
        lathe([(0, 0), (r, 0), (r, h), (0, h)], 6, axis_M(normal, p), bm)
    return bm


def part(b, name, bm, m, bevel=0.012, segs=2, kind='solid', smooth=True, angle=35):
    full = b + '.' + name
    me = bpy.data.meshes.new(full)
    bm.to_mesh(me)
    bm.free()
    ob = bpy.data.objects.new(full, me)
    MECH.objects.link(ob)
    ob.parent = BODIES[b]
    me.materials.append(mat(m))
    if smooth:
        for p in me.polygons:
            p.use_smooth = True
    if bevel > 0:
        md = ob.modifiers.new('bevel', 'BEVEL')
        md.width = bevel
        md.segments = segs
        md.limit_method = 'ANGLE'
        md.angle_limit = radians(angle)
        md.harden_normals = True
        md.use_clamp_overlap = True
    ob['body'] = b
    ob['kind'] = kind
    PARTS.append({'name': full, 'body': b, 'kind': kind})
    return ob


def decal_text(b, name, text, size, M, m='stencil'):
    cu = bpy.data.curves.new(name, 'FONT')
    cu.body = text
    cu.size = size
    cu.extrude = 0.0012
    cu.align_x = 'CENTER'
    cu.align_y = 'CENTER'
    tmp = bpy.data.objects.new(name + '_tmp', cu)
    MECH.objects.link(tmp)
    dg = bpy.context.evaluated_depsgraph_get()
    me = bpy.data.meshes.new_from_object(tmp.evaluated_get(dg))
    bpy.data.objects.remove(tmp)
    me.transform(M)
    full = b + '.' + name
    me.name = full
    ob = bpy.data.objects.new(full, me)
    MECH.objects.link(ob)
    ob.parent = BODIES[b]
    me.materials.append(mat(m))
    ob['body'] = b
    ob['kind'] = 'decal'
    PARTS.append({'name': full, 'body': b, 'kind': 'decal'})
    return ob


def save(stage):
    p = os.path.join(OUT, stage + '.blend')
    bpy.ops.wm.save_as_mainfile(filepath=p, compress=True)
    print('SAVED', p, 'parts', len([q for q in PARTS if q['kind'] != 'decal']))


SIDES = {'L': 1, 'R': -1}


def side_M(sg):
    # text faces +Y (left side) or -Y (right side) and reads front-to-back correctly
    if sg > 0:
        return Matrix.Rotation(pi, 4, 'Z') @ Matrix.Rotation(pi / 2, 4, 'X')
    return Matrix.Rotation(pi / 2, 4, 'X')

# =========================================================================
# Stage 1: scale pilot and cab (hull body, origin at the hip axis midpoint)
# =========================================================================
body('hull')
body('cab')
H = 'cab'   # stage 1 parts all ride on the cab body
SEAT_HIP = Vector((0.27, 0.0, 1.58))

# pilot, a plain scale figure (1.78 m standing)
pb = bm_new()
capsule((0.25, 0, 1.64), (0.21, 0, 1.98), 0.15, bm=pb)
part(H, 'pilot_torso', pb, 'pilot_suit', bevel=0)
part(H, 'pilot_neck', capsule((0.215, 0, 2.02), (0.22, 0, 2.10), 0.05), 'pilot_suit', bevel=0)
part(H, 'pilot_helmet', sphere((0.225, 0, 2.21), 0.135), 'pilot_helmet', bevel=0)
vb = bm_new()
sphere((0.228, 0, 2.205), 0.138, bm=vb, u=40, v=20)
bmesh.ops.delete(vb, geom=[v for v in vb.verts if v.co.x < 0.31 or v.co.z < 2.13 or v.co.z > 2.28], context='VERTS')
bmesh.ops.solidify(vb, geom=vb.faces[:], thickness=0.006)
part(H, 'pilot_visor', vb, 'visor', bevel=0)
for s, sg in SIDES.items():
    y = 0.105 * sg
    part(H, 'pilot_thigh_' + s, capsule((0.26, y, 1.60), (0.66, y * 1.1, 1.62), 0.075), 'pilot_suit', bevel=0)
    part(H, 'pilot_shin_' + s, capsule((0.66, y * 1.1, 1.62), (0.74, y * 1.15, 1.30), 0.06), 'pilot_suit', bevel=0)
    part(H, 'pilot_boot_' + s, boxr(0.68, 0.92, y * 1.15 - 0.055, y * 1.15 + 0.055, 1.19, 1.27), 'rubber', bevel=0.02)
    part(H, 'pilot_upperarm_' + s, capsule((0.22, 0.20 * sg, 1.94), (0.33, 0.24 * sg, 1.72), 0.05), 'pilot_suit', bevel=0)
    part(H, 'pilot_forearm_' + s, capsule((0.33, 0.24 * sg, 1.72), (0.56, 0.26 * sg, 1.70), 0.042), 'pilot_suit', bevel=0)
    part(H, 'pilot_glove_' + s, sphere((0.60, 0.27 * sg, 1.70), 0.045), 'rubber', bevel=0)
    # control stick on a side console
    part(H, 'console_' + s, boxr(0.42, 0.80, 0.30 * sg, 0.46 * sg, 1.18, 1.52), 'frame', bevel=0.015)
    part(H, 'stick_' + s, capsule((0.62, 0.30 * sg, 1.52), (0.60, 0.28 * sg, 1.66), 0.018), 'steel', bevel=0)

seat = bm_new()
boxr(0.04, 0.50, -0.25, 0.25, 1.38, 1.52, bm=seat)
part(H, 'seat_cushion', seat, 'seat', bevel=0.03, segs=3)
part(H, 'seat_back', prism([(-0.04, 1.50), (0.06, 1.50), (0.10, 2.12), (0.0, 2.14)], -0.24, 0.24), 'seat', bevel=0.03, segs=3)
part(H, 'seat_post', boxr(0.14, 0.36, -0.10, 0.10, 1.18, 1.38), 'frame', bevel=0.01)
part(H, 'harness', prism([(0.07, 1.62), (0.10, 1.62), (0.16, 2.00), (0.13, 2.00)], -0.16, 0.16), 'rubber', bevel=0.005)
dash = prism([(0.86, 1.40), (1.02, 1.40), (1.02, 1.64), (0.92, 1.70)], -0.50, 0.50)
part(H, 'dashboard', dash, 'frame', bevel=0.015)
for i, y in enumerate((-0.24, 0.0, 0.24)):
    scr = prism([(0.914, 1.56), (0.93, 1.56), (0.955, 1.67), (0.939, 1.67)], y - 0.10, y + 0.10)
    part(H, 'screen_%d' % i, scr, 'screen', bevel=0)

# cab shell (hollow so the pilot reads through the glass)
part(H, 'cab_floor', boxr(-0.15, 1.12, -0.62, 0.62, 1.10, 1.18), 'paint', bevel=0.02)
part(H, 'cab_back', boxr(-0.15, -0.05, -0.62, 0.62, 1.18, 2.62), 'paint2', bevel=0.02)
nose = [(0.90, 1.10), (1.12, 1.10), (1.24, 1.22), (1.24, 1.52), (1.12, 1.66), (0.90, 1.66)]
part(H, 'cab_nose', prism(nose, -0.62, 0.62), 'paint2', bevel=0.03, segs=3)
for s, sg in SIDES.items():
    lo = prism([(-0.15, 1.18), (0.90, 1.18), (0.90, 1.62), (-0.15, 1.62)], 0.56 * sg, 0.62 * sg)
    part(H, 'cab_side_' + s, lo, 'paint2', bevel=0.02)
    ap = prism([(1.075, 1.64), (1.135, 1.64), (0.955, 2.62), (0.895, 2.62)], 0.52 * sg, 0.62 * sg)
    part(H, 'a_pillar_' + s, ap, 'paint2', bevel=0.012)
    part(H, 'b_pillar_' + s, boxr(0.30, 0.38, 0.555 * sg, 0.62 * sg, 1.60, 2.62), 'paint2', bevel=0.012)
    part(H, 'c_pillar_' + s, boxr(-0.15, -0.05, 0.52 * sg, 0.62 * sg, 1.60, 2.62), 'paint2', bevel=0.012)
    sw = prism([(-0.05, 1.615), (1.08, 1.615), (0.905, 2.605), (-0.05, 2.605)], 0.583 * sg, 0.593 * sg)
    part(H, 'side_glass_' + s, sw, 'glass', bevel=0)
    # headlamp: housing cup facing +X, glowing lens, chrome bezel
    c = (1.24, 0.40 * sg, 1.40)
    part(H, 'lamp_housing_' + s, lathe([(0, -0.02), (0.10, -0.02), (0.11, 0.07), (0.095, 0.075), (0.085, 0.01), (0, 0.01)], 32, axis_M('X', c)), 'frame', bevel=0.004)
    part(H, 'lamp_lens_' + s, lathe([(0, 0.05), (0.086, 0.05), (0.086, 0.062), (0, 0.068)], 32, axis_M('X', c)), 'lamp', bevel=0)
    part(H, 'lamp_bezel_' + s, tube((c[0] + 0.072, c[1], c[2]), 0.084, 0.106, 0.016, 'X'), 'chrome', bevel=0.003)
    # grab handle beside the door
    hb = bm_new()
    # v4: moved onto the rear pillar (it floated 2.7 cm off the side glass; the gap audit found it)
    seg_cyl((-0.10, 0.64 * sg, 1.75), (-0.10, 0.64 * sg, 2.35), 0.016, bm=hb)
    seg_cyl((-0.10, 0.615 * sg, 1.75), (-0.10, 0.655 * sg, 1.75), 0.016, bm=hb)
    seg_cyl((-0.10, 0.615 * sg, 2.35), (-0.10, 0.655 * sg, 2.35), 0.016, bm=hb)
    part(H, 'grab_handle_' + s, hb, 'hazard_bar', bevel=0)
ws = prism([(1.10, 1.655), (1.12, 1.655), (0.94, 2.605), (0.92, 2.605)], -0.525, 0.525)
part(H, 'windshield', ws, 'glass', bevel=0)
part(H, 'wiper', seg_cyl((1.128, 0.0, 1.70), (1.05, 0.30, 2.05), 0.009), 'frame', bevel=0)
roof = [(-0.18, 2.60), (0.96, 2.60), (1.10, 2.64), (1.06, 2.74), (0.86, 2.79), (-0.18, 2.79)]
part(H, 'roof_brow', prism(roof, -0.66, 0.66), 'paint2', bevel=0.03, segs=3)
part(H, 'roof_rack', boxr(-0.10, 0.70, -0.40, 0.40, 2.79, 2.83), 'frame', bevel=0.01)
# beacon and antenna base
part(H, 'beacon_base', cyl((0.10, 0.42, 2.85), 0.07, 0.06), 'frame', bevel=0.005)
part(H, 'beacon_dome', lathe([(0, 2.88), (0.06, 2.88), (0.06, 2.95), (0.045, 2.99), (0, 3.0)], 32, axis_M('Z', (0.10, 0.42, 0))), 'beacon', bevel=0)   # v4: was built at the cab centre, off its base
part(H, 'antenna_base', tube((0.10, -0.45, 2.88), 0.016, 0.04, 0.10), 'frame', bevel=0.004)
part(H, 'antenna_foot', cyl((0.10, -0.45, 2.815), 0.06, 0.03), 'frame', bevel=0.004)
save('01_pilot_cab')

# =========================================================================
# Stage 2: hull (chest, power pack, hip yoke and sockets, shoulders)
H = 'hull'
# =========================================================================
chest = [(-0.45, 0.55), (0.85, 0.55), (1.08, 0.78), (1.08, 1.02), (-0.45, 1.02)]
# v4: the cab rides in a cradle on soft mounts. The cradle walls stand 3 cm clear of the cab
# all round, so the cab can sink into it and rebound; four rubber bump stops sit on its floor.
for i, (x, y) in enumerate([(0.0, -0.48), (0.0, 0.48), (0.92, -0.48), (0.92, 0.48)]):
    part(H, 'cab_isolator_%d' % i, cyl((x, y, 1.030), 0.07, 0.01), 'rubber', bevel=0.003)
part(H, 'cab_cradle_floor', boxr(-0.21, 1.29, -0.68, 0.68, 1.005, 1.025), 'frame', bevel=0.008)
for s_, sg_ in SIDES.items():
    part(H, 'cab_cradle_side_' + s_, boxr(-0.21, 1.29, 0.65 * sg_, 0.68 * sg_, 1.005, 1.24), 'frame', bevel=0.01)
part(H, 'cab_cradle_back', boxr(-0.21, -0.185, -0.65, 0.65, 1.005, 1.24), 'frame', bevel=0.01)
part(H, 'cab_cradle_front', boxr(1.27, 1.29, -0.65, 0.65, 1.005, 1.20), 'hazard', bevel=0.008)
part(H, 'chest', prism(chest, -0.70, 0.70), 'paint', bevel=0.035, segs=3)
part(H, 'bumper', boxr(1.08, 1.15, -0.58, 0.58, 0.64, 0.92), 'hazard', bevel=0.012)
part(H, 'chest_belly', boxr(-0.35, 0.80, -0.55, 0.55, 0.48, 0.56), 'frame', bevel=0.012)
part(H, 'yoke', boxr(-0.30, 0.30, -0.98, 0.98, 0.25, 0.59), 'frame', bevel=0.025, segs=3)
pack = [(-1.16, 0.62), (-0.45, 0.55), (-0.22, 0.70), (-0.22, 2.32), (-0.34, 2.44), (-1.04, 2.44), (-1.18, 2.28)]
part(H, 'power_pack', prism(pack, -0.68, 0.68), 'paint', bevel=0.035, segs=3)
gr = bm_new()
boxr(-1.215, -1.17, -0.52, 0.52, 0.95, 2.05, bm=gr)
part(H, 'radiator_frame', gr, 'frame', bevel=0.01)
sl = bm_new()
for i in range(12):
    z = 1.0 + i * 0.087
    prism([(-1.25, z), (-1.21, z), (-1.21, z + 0.05), (-1.25, z + 0.032)], -0.48, 0.48, bm=sl)
part(H, 'radiator_louvers', sl, 'frame', bevel=0.004)
for s, sg in SIDES.items():
    y = 0.42 * sg
    part(H, 'exhaust_stack_' + s, tube((-0.78, y, 2.74), 0.052, 0.066, 0.62), 'exhaust', bevel=0.004)
    part(H, 'exhaust_guard_' + s, tube((-0.78, y, 2.64), 0.080, 0.088, 0.30), 'frame', bevel=0.003)
    part(H, 'exhaust_flange_' + s, cyl((-0.78, y, 2.46), 0.10, 0.04), 'frame', bevel=0.005)
    part(H, 'exhaust_cap_' + s, prism([(-0.86, 3.045), (-0.70, 3.045), (-0.70, 3.06), (-0.86, 3.095)], y - 0.075, y + 0.075), 'frame', bevel=0.004)
part(H, 'fuel_tank', lathe([(0, -0.34), (0.12, -0.34), (0.15, -0.30), (0.15, 0.30), (0.12, 0.34), (0, 0.34)], 32, axis_M('X', (-0.70, 0.83, 1.18))), 'paint2', bevel=0)
fb = bm_new()
for x in (-0.95, -0.45):
    tube((x, 0.83, 1.18), 0.151, 0.165, 0.05, 'X', bm=fb)
part(H, 'fuel_tank_straps', fb, 'frame', bevel=0.003)
part(H, 'fuel_cap', cyl((-0.62, 0.83, 1.345), 0.045, 0.04), 'brass', bevel=0.004)
# ladder on the right side of the power pack, up to the cab door
lad = bm_new()
for x in (-0.62, -0.30):
    seg_cyl((x, -0.74, 0.62), (x, -0.74, 2.30), 0.018, bm=lad)
part(H, 'ladder_rails', lad, 'hazard_bar', bevel=0)
rg = bm_new()
for i in range(7):
    z = 0.78 + i * 0.22
    seg_cyl((-0.62, -0.74, z), (-0.30, -0.74, z), 0.014, bm=rg)
    seg_cyl((-0.62, -0.74, z), (-0.62, -0.69, z), 0.012, bm=rg)
    seg_cyl((-0.30, -0.74, z), (-0.30, -0.69, z), 0.012, bm=rg)
part(H, 'ladder_rungs', rg, 'steel', bevel=0)
# hip sockets: spherical shells, 4% clearance on the 0.20 m balls, open below
RB = 0.20
for s, sg in SIDES.items():
    y = HIP_Y * sg
    prof = []
    for i in range(0, 25):
        th = radians(115) * i / 24
        prof.append((0.275 * sin(th), 0.275 * cos(th)))
    prof.append((0.29 * sin(radians(115)), 0.29 * cos(radians(115))))
    for i in range(24, -1, -1):
        th = radians(115) * i / 24
        prof.append((RB * CLR * sin(th), RB * CLR * cos(th)))
    TILT = Matrix.Translation((0, y, 0)) @ Matrix.Rotation(radians(-25), 4, 'Y')
    part(H, 'hip_socket_' + s, lathe(prof, 48, TILT), 'frame', bevel=0.006)
    part(H, 'hip_socket_mount_' + s, boxr(-0.20, 0.20, y - 0.20, y + 0.20, 0.22, 0.30), 'frame', bevel=0.015)
    rb_ = tube((0, 0, 0.10), 0.24, 0.29, 0.05)
    bmesh.ops.transform(rb_, matrix=TILT, verts=rb_.verts)
    part(H, 'hip_socket_ring_' + s, rb_, 'steel', bevel=0.004)
    hb_ = hexbolts([(0.27 * cos(a), 0.27 * sin(a), 0.125) for a in [2 * pi * i / 10 for i in range(10)]], 'Z', 0.018, 0.012)
    bmesh.ops.transform(hb_, matrix=TILT, verts=hb_.verts)
    part(H, 'hip_bolts_' + s, hb_, 'steel', bevel=0)
    # shoulder: block, cantilever axle, retaining cap
    part(H, 'shoulder_block_' + s, boxr(0.28, 0.62, 0.68 * sg, 0.86 * sg, 0.78, 1.12), 'frame', bevel=0.02)
    part(H, 'shoulder_motor_' + s, cyl((0.45, 0.80 * sg, 0.95), 0.17, 0.10, 'Y'), 'steel', bevel=0.008)
    part(H, 'shoulder_axle_' + s, cyl((0.45, 1.03 * sg, 0.95), 0.065, 0.44, 'Y'), 'steel', bevel=0.004)
    part(H, 'shoulder_cap_' + s, cyl((0.45, 1.215 * sg, 0.95), 0.115, 0.05, 'Y'), 'frame', bevel=0.006)
    part(H, 'chest_bolts_' + s, hexbolts([(x, 0.70 * sg, 0.62) for x in (-0.35, -0.1, 0.15, 0.40, 0.65)], 'Y' if sg > 0 else '-Y'), 'steel', bevel=0)
part(H, 'chest_front_bolts', hexbolts([(1.08, y, 0.96) for y in (-0.5, -0.25, 0, 0.25, 0.5)], 'X'), 'steel', bevel=0)
# decals: unit number and name
for s, sg in SIDES.items():
    M = Matrix.Translation((-0.70, 0.684 * sg, 1.90)) @ side_M(sg)
    decal_text(H, 'decal_bk07_' + s, 'BK-07', 0.20, M)
    M2 = Matrix.Translation((0.40, 0.6235 * sg, 1.40)) @ side_M(sg)
    decal_text('cab', 'decal_name_' + s, 'MOSSBACK', 0.085, M2)
save('02_hull')

# =========================================================================
# Stage 3: legs (thigh with ball, shin, cardan spider, foot)
# =========================================================================
for s, sg in SIDES.items():
    T, S, X, F = 'thigh_' + s, 'shin_' + s, 'spider_' + s, 'foot_' + s
    for n in (T, S, X, F):
        body(n)
    # ---- thigh (origin: ball centre; knee pin at (0, 0, -L1))
    part(T, 'ball', sphere((0, 0, 0), RB, u=48, v=24), 'steel', bevel=0)
    part(T, 'neck', cyl((0, 0, -0.22), 0.085, 0.22), 'steel', bevel=0.004)
    tprof = [(-0.20, -0.31), (0.19, -0.31), (0.25, -0.42), (0.235, -0.74), (0.02, -0.99), (-0.17, -0.99), (-0.24, -0.62)]
    part(T, 'thigh_shell', prism(tprof, -0.20, 0.20), 'paint', bevel=0.03, segs=3)
    part(T, 'thigh_collar', cyl((0, 0, -0.32), 0.15, 0.06), 'frame', bevel=0.006)
    side = [(-0.14, -0.40), (0.15, -0.40), (0.16, -0.70), (0.0, -0.90), (-0.14, -0.86)]
    part(T, 'thigh_plate_out', prism(side, 0.20 * sg, 0.225 * sg), 'paint2', bevel=0.008)
    part(T, 'thigh_plate_in', prism(side, -0.20 * sg, -0.22 * sg), 'paint', bevel=0.008)
    part(T, 'thigh_bolts', hexbolts([(x, 0.225 * sg, z) for x, z in ((-0.10, -0.45), (0.10, -0.45), (-0.09, -0.80), (0.09, -0.72))], 'Y' if sg > 0 else '-Y', 0.016, 0.01), 'steel', bevel=0)
    for side_s in (1, -1):
        pl = [(-0.15, -0.93), (0.07, -0.93), (0.15, -1.08)]
        for i in range(13):
            a = radians(-30 - 180 * i / 12)
            pl.append((0.15 * cos(a), -L1 + 0.15 * sin(a)))
        part(T, 'knee_clevis_%s' % ('a' if side_s > 0 else 'b'), prism(pl, 0.155 * side_s, 0.215 * side_s), 'frame', bevel=0.008)
    part(T, 'knee_pin', cyl((0, 0, -L1), 0.07, 0.47, 'Y'), 'steel', bevel=0.004)
    for side_s in (1, -1):
        part(T, 'knee_nut_%s' % ('a' if side_s > 0 else 'b'), cyl((0, 0.228 * side_s, -L1), 0.095, 0.026, 'Y', segs=6), 'steel', bevel=0.004)
    # ---- shin (origin: knee pin; ankle pitch pin at (0, 0, -L2))
    part(S, 'knee_boss', tube((0, 0, 0), 0.07 * CLR, 0.14, 0.28, 'Y'), 'steel', bevel=0.005)
    sprof = [(-0.125, -0.10), (0.11, -0.10), (0.16, -0.30), (0.15, -0.86), (0.08, -1.02), (-0.08, -1.02), (-0.14, -0.70)]
    part(S, 'shin_core', prism(sprof, -0.13, 0.13), 'frame', bevel=0.02)
    armor = [(-0.13, -0.32), (0.21, -0.30), (0.27, -0.40), (0.25, -0.78), (0.15, -0.94), (-0.11, -0.94), (-0.16, -0.62)]
    part(S, 'shin_armor', prism(armor, -0.24, 0.24), 'paint', bevel=0.03, segs=3)
    part(S, 'shin_guard', prism([(0.27, -0.42), (0.30, -0.44), (0.28, -0.74), (0.25, -0.76)], -0.17, 0.17), 'hazard', bevel=0.006)
    for side_s in (1, -1):
        # v6: slimmer at the back, because the deeper knee give brings the outer ankle ram rod
        # forward past the old plate edge
        pl = [(-0.085, -0.88), (0.10, -0.88), (0.13, -1.0)]
        for i in range(13):
            a = radians(-20 - 180 * i / 12)
            r_ = 0.13 if i <= 6 else 0.13 - 0.03 * (i - 6) / 6
            pl.append((r_ * cos(a), -L2 + r_ * sin(a)))
        part(S, 'ankle_clevis_%s' % ('a' if side_s > 0 else 'b'), prism(pl, 0.125 * side_s, 0.185 * side_s), 'frame', bevel=0.008)
    part(S, 'ankle_pin', cyl((0, 0, -L2), 0.06, 0.42, 'Y'), 'steel', bevel=0.004)
    for side_s in (1, -1):
        part(S, 'ankle_nut_%s' % ('a' if side_s > 0 else 'b'), cyl((0, 0.197 * side_s, -L2), 0.08, 0.024, 'Y', segs=6), 'steel', bevel=0.004)
    M = Matrix.Translation((0.05, 0.2435 * sg, -0.60)) @ side_M(sg)
    decal_text(S, 'decal_07', '07', 0.20, M)
    # ---- spider (origin: pitch pin; roll pin SDROP below)
    part(X, 'pitch_boss', tube((0, 0, 0), 0.06 * CLR, 0.105, 0.22, 'Y'), 'steel', bevel=0.004)
    part(X, 'roll_boss', tube((0, 0, -SDROP), 0.05 * CLR, 0.09, 0.20, 'X'), 'steel', bevel=0.004)
    part(X, 'web', boxr(-0.07, 0.07, -0.07, 0.07, -0.13, -0.085), 'frame', bevel=0.006)
    # ---- foot (origin: roll pin centre; sole at z = -ROLL_H)
    sole = -ROLL_H
    part(F, 'sole_plate', boxr(-0.48, 0.56, -0.33, 0.33, sole + 0.03, sole + 0.15), 'frame', bevel=0.02)
    hous = [(-0.36, sole + 0.14), (0.44, sole + 0.14), (0.30, -0.115), (-0.26, -0.115)]
    part(F, 'ankle_housing', prism(hous, -0.27, 0.27), 'paint', bevel=0.02, segs=3)
    for i, y in enumerate((-0.22, 0.0, 0.22)):
        toe = [(0.52, sole + 0.005), (0.80, sole + 0.005), (0.89, sole + 0.06), (0.85, sole + 0.14), (0.52, sole + 0.19)]
        part(F, 'toe_%d' % i, prism(toe, y - 0.095, y + 0.095), 'hazard', bevel=0.02, segs=3)
        part(F, 'toe_pad_%d' % i, boxr(0.55, 0.82, y - 0.08, y + 0.08, sole + 0.0, sole + 0.012), 'rubber', bevel=0.004)
    heel = [(-0.46, sole + 0.005), (-0.62, sole + 0.04), (-0.64, sole + 0.10), (-0.46, sole + 0.16)]
    part(F, 'heel_spur', prism(heel, -0.16, 0.16), 'frame', bevel=0.015)
    for i, (x0, x1) in enumerate(((-0.46, -0.02), (0.02, 0.52))):
        part(F, 'sole_pad_%d' % i, boxr(x0, x1, -0.31, 0.31, sole + 0.0, sole + 0.03), 'rubber', bevel=0.006)
    for side_s in (1, -1):
        lug = [(-0.07, -0.12), (0.07, -0.12), (0.07, 0.0)]
        for i in range(9):
            a = radians(180 * i / 8)
            lug.append((0.075 * cos(a), 0.075 * sin(a)))
        lug.append((-0.07, 0.0))
        part(F, 'roll_lug_%s' % ('a' if side_s > 0 else 'b'),
             prism(lug, 0.115 * side_s, 0.165 * side_s, 'YZ'), 'frame', bevel=0.006)
    part(F, 'roll_pin', cyl((0, 0, 0), 0.05, 0.36, 'X'), 'steel', bevel=0.004)
    part(F, 'foot_bolts', hexbolts([(x, y, sole + 0.15) for x in (-0.42, 0.50) for y in (-0.25, 0.25)], 'Z', 0.018, 0.012), 'steel', bevel=0)
    part(S, 'calf_bracket', boxr(-0.29, -0.12, -0.06, 0.06, -0.43, -0.29), 'frame', bevel=0.01)
    part(T, 'ram_outrigger', boxr(-0.06, 0.10, 0.22 * sg, 0.33 * sg, -0.87, -0.73), 'frame', bevel=0.012)
    part(F, 'heel_bracket', boxr(-0.55, -0.30, -0.075, 0.075, -0.16, 0.0), 'frame', bevel=0.012)
    part(H, 'hip_cyl_bracket_' + s, boxr(0.17, 0.43, 0.90 * sg, 1.17 * sg, 0.40, 0.59), 'frame', bevel=0.012)
save('03_legs')

# =========================================================================
# Stage 4: arms (shoulder hinge, elbow hinge, claw on the right, winch on the left)
# =========================================================================
UA = 0.62   # shoulder pin to elbow pin
for s, sg in SIDES.items():
    U, Fa = 'upperarm_' + s, 'forearm_' + s
    body(U)
    body(Fa)
    part(U, 'shoulder_boss', tube((0, 0, 0), 0.065 * CLR, 0.12, 0.26, 'Y'), 'steel', bevel=0.005)
    part(U, 'arm_beam', boxr(0.10, 0.39, -0.09, 0.09, -0.10, 0.10), 'frame', bevel=0.015)   # v4: reaches the boss
    part(U, 'arm_armor', prism([(0.15, 0.10), (0.42, 0.10), (0.46, 0.04), (0.42, -0.13), (0.15, -0.13)], -0.11, 0.11), 'paint', bevel=0.02, segs=3)
    for side_s in (1, -1):
        pl = [(0.38, -0.07), (0.50, -0.07)]
        for i in range(13):
            a = radians(-90 + 180 * i / 12)
            pl.append((UA + 0.10 * cos(a), 0.10 * sin(a)))
        pl.append((0.50, 0.07))
        pl.append((0.38, 0.07))
        part(U, 'elbow_clevis_%s' % ('a' if side_s > 0 else 'b'), prism(pl, 0.085 * side_s, 0.125 * side_s), 'frame', bevel=0.006)
    part(U, 'elbow_pin', cyl((UA, 0, 0), 0.045, 0.29, 'Y'), 'steel', bevel=0.003)
    # forearm (origin: elbow pin)
    part(Fa, 'elbow_boss', tube((0, 0, 0), 0.045 * CLR, 0.085, 0.14, 'Y'), 'steel', bevel=0.004)
    part(Fa, 'fore_beam', boxr(0.07, 0.70, -0.065, 0.065, -0.08, 0.06), 'frame', bevel=0.012)
    part(Fa, 'fore_armor', prism([(0.12, 0.06), (0.62, 0.06), (0.66, 0.0), (0.62, -0.10), (0.16, -0.10)], -0.075, 0.075), 'paint2', bevel=0.015, segs=3)
    if sg < 0:
        # claw: wrist, palm, three two-piece fingers
        part(Fa, 'wrist', cyl((0.76, 0, 0), 0.10, 0.14, 'X'), 'steel', bevel=0.006)
        part(Fa, 'palm', lathe([(0, 0.83), (0.13, 0.83), (0.14, 0.88), (0.10, 0.93), (0, 0.93)], 6, axis_M('X') @ Matrix.Translation((0, 0, 0)) @ Matrix.Rotation(0, 4, 'Z')), 'frame', bevel=0.008)
        for i in range(3):
            a = 2 * pi * i / 3 + pi / 2
            R = Matrix.Rotation(a, 4, 'X')
            p1 = [(0.90, 0.07), (1.08, 0.10), (1.10, 0.06), (0.92, 0.03)]
            part(Fa, 'finger_%d_base' % i, prism(p1, -0.035, 0.035, 'XZ', R), 'frame', bevel=0.008)
            p2 = [(1.07, 0.10), (1.20, 0.05), (1.22, 0.00), (1.17, 0.01), (1.08, 0.055)]
            part(Fa, 'finger_%d_tip' % i, prism(p2, -0.03, 0.03, 'XZ', R), 'hazard', bevel=0.006)
    else:
        # winch: drum with wound cable, fairlead ring below the tip
        part(Fa, 'winch_drum', cyl((0.80, 0, 0), 0.075, 0.12, 'Y'), 'steel', bevel=0.004)
        part(Fa, 'winch_cable_wrap', cyl((0.80, 0, 0), 0.085, 0.10, 'Y', segs=24), 'cable', bevel=0)
        for side_s in (1, -1):
            part(Fa, 'winch_cheek_%s' % ('a' if side_s > 0 else 'b'), cyl((0.80, 0.07 * side_s, 0), 0.12, 0.02, 'Y'), 'frame', bevel=0.004)
        part(Fa, 'fairlead_arm', boxr(0.70, 0.90, -0.03, 0.03, -0.139, -0.09), 'frame', bevel=0.006)   # v4: now meets the fairlead
        # v4: a flatter, wider bell mouth with its throat above the pivot, because the heavier
        # footfalls swing the hook up to 79 degrees off the forearm
        part(Fa, 'fairlead', lathe([(0.042, 0.016), (0.120, 0.002), (0.132, 0.002), (0.070, 0.034), (0.048, 0.034)], 32, axis_M('Z', (0.885, 0, -0.16))), 'steel', bevel=0.003)
        part(Fa, 'cable_feed', seg_cyl((0.885, 0, -0.004), (0.885, 0, -0.07), 0.011, segs=10), 'cable', bevel=0)
        body('hook')
        part('hook', 'cable', seg_cyl((0, 0, 0.0), (0, 0, -0.32), 0.011, segs=10), 'cable', bevel=0)
        HK = 0.52
        part('hook', 'hook_block', boxr(-0.07, 0.07, -0.05, 0.05, -0.98 + HK, -0.84 + HK), 'hazard', bevel=0.012)
        part('hook', 'hook_sheave', cyl((0, 0, -0.91 + HK), 0.05, 0.11, 'Y'), 'steel', bevel=0.004)
        hk = bm_new()
        tor = []
        for i in range(17):
            a = radians(-40 + 260 * i / 16)
            tor.append((0.08 * cos(a) + 0.0, -1.10 + HK + 0.08 * sin(a)))
        for i in range(len(tor) - 1):
            p0 = Vector((tor[i][0], 0, tor[i][1]))
            p1 = Vector((tor[i + 1][0], 0, tor[i + 1][1]))
            seg_cyl(p0, p1, 0.022, segs=12, bm=hk)
        seg_cyl((0, 0, -0.98 + HK), (0.0, 0, -1.02 + HK), 0.025, segs=12, bm=hk)
        bmesh.ops.remove_doubles(hk, verts=hk.verts, dist=1e-5)
        part('hook', 'hook', hk, 'steel', bevel=0)
save('04_arms')

# =========================================================================
# Kinematics: every body's world matrix as a function of time t (seconds)
# =========================================================================


def frame(X, Y, Z, T):
    M = Matrix.Identity(4)
    for i in range(3):
        M[i][0], M[i][1], M[i][2], M[i][3] = X[i], Y[i], Z[i], T[i]
    return M


def smooth5(s):
    s = min(max(s, 0.0), 1.0)
    return s * s * s * (10 - 15 * s + 6 * s * s)


# v4 weight: between steps the hull rises over the stance leg, then falls the last 12 cm
# onto the next foot at 1.5 m/s; the stance leg catches it like a stiff spring and damper
# (1.5 Hz, damping 0.4), so it sinks hard, bottoms in about 3 frames and rebounds a little.
FALL_V = 1.5
FALL_T = 0.12
CATCH_W = 2 * pi * 1.5
CATCH_Z = 0.40
KNEE_GIVE = 0.18
KNEE_TAU = 0.20
CATCH_WD = CATCH_W * sqrt(1 - CATCH_Z ** 2)
ARCH = FALL_V * FALL_T / 2


def catch(t):
    """Hull sink after each foot strike (one strike every TC/2), metres, negative is down."""
    tt = t % (TC / 2)
    spring = -(FALL_V / CATCH_WD) * exp(-CATCH_Z * CATCH_W * tt) * sin(CATCH_WD * tt)
    # v6: then the knees give: the hull sinks a further KNEE_GIVE into the stance leg over about
    # 5 frames and climbs back out through the rest of the stance (reviewers asked for 25 to 40 cm)
    give = -KNEE_GIVE * (tt / KNEE_TAU) * exp(1 - tt / KNEE_TAU)
    return spring + give


def arch(t):
    tt = t % (TC / 2)
    tm = TC / 2 - FALL_T
    if tt < tm:
        s = tt / tm
        return ARCH * s * s * (3 - 2 * s)
    s = (tt - tm) / FALL_T
    return ARCH * (1 - s * s)     # free fall onto the foot, arriving at FALL_V


def dip(t):
    return -catch(t) / 0.25


def hull_M(t):
    ph = t / TC
    x = V * t - 0.02 * sin(4 * pi * ph)
    y = 0.16 * cos(2 * pi * (ph - 0.31))      # v5/v6: rolls over the planted leg (was 0.11; 0.20 read as a waddle)
    z = HIP_Z0 - 0.03 + arch(t) + catch(t)
    roll = radians(-4.5) * cos(2 * pi * (ph - 0.31))
    yaw = radians(2.2) * sin(2 * pi * (ph - 0.31))
    pitch = radians(3.0) + radians(3.5) * dip(t)   # v5: pitches into each step
    R = Matrix.Rotation(yaw, 4, 'Z') @ Matrix.Rotation(pitch, 4, 'Y') @ Matrix.Rotation(roll, 4, 'X')
    return Matrix.Translation((x, y, z)) @ R


def foot_M(t, s):
    sg = SIDES[s]
    off = 0.0 if s == 'L' else 0.5
    ph = t / TC + off
    k = floor(ph)
    u = ph - k
    a = DUTY * STEP
    tk = (k - off) * TC
    Xk = V * tk + a
    y = FOOT_Y * sg
    yaw = TOE_OUT * sg
    if u < DUTY:
        x, z, pitch, yy = Xk, 0.0, 0.0, 0.0
        stance = True
    else:
        sw = (u - DUTY) / (1 - DUTY)
        x = Xk + 2 * STEP * smooth5(sw)
        # v4: soft lift-off, but the foot comes down at speed and lands flat (a slap, not a touch)
        z = LIFT * sin(pi * (sw ** 0.8)) ** (1.3 - 0.3 * sw)
        pitch = radians(14) * sin(pi * sw) ** 2 * (1 - 2 * sw)
        yy = 0.035 * sin(pi * sw) * sg
        stance = False
    R = Matrix.Rotation(yaw, 4, 'Z') @ Matrix.Rotation(pitch, 4, 'Y')
    sole = Vector((x, y + yy, z))
    M = Matrix.Translation(sole) @ R @ Matrix.Translation((0, 0, ROLL_H))
    return M, stance, (Xk, y, yaw, tk)


def leg_solve(t, s, Mh, Mf):
    sg = SIDES[s]
    Hp = Mh @ Vector((0, HIP_Y * sg, 0))
    Rf = Mf.to_3x3()
    f = Rf.col[0].normalized()
    O = Mf.translation
    k = Rf.col[1].normalized()
    for _ in range(8):
        Zs = f.cross(k).normalized()
        Ap = O + Zs * SDROP
        d = Ap - Hp
        k = f.cross(d).normalized()
    Zs = f.cross(k).normalized()
    Ap = O + Zs * SDROP
    d = Ap - Hp
    D = d.length
    dn = d / D
    ca = (L1 * L1 + D * D - L2 * L2) / (2 * L1 * D)
    ca = max(-1.0, min(1.0, ca))
    al = acos(ca)
    n = dn.cross(k).normalized()
    K = Hp + L1 * (cos(al) * dn + sin(al) * n)
    Zt = (Hp - K).normalized()
    Mt = frame(k.cross(Zt), k, Zt, Hp)
    Zsh = (K - Ap).normalized()
    Ms = frame(k.cross(Zsh), k, Zsh, K)
    Mx = frame(f, k, Zs, Ap)
    return {'thigh_' + s: Mt, 'shin_' + s: Ms, 'spider_' + s: Mx}, D


def arm_solve(t, s, Mh):
    sg = SIDES[s]
    ph = t / TC + (0.0 if s == 'L' else 0.5)
    # arms counter-swing the leg on the same side, lagging a little (inertia)
    sh = radians(40) + radians(20) * sin(2 * pi * (ph - 0.42))
    el = radians(-40) + radians(18) * sin(2 * pi * (ph - 0.55))
    Mu = Mh @ Matrix.Translation((0.45, 1.03 * sg, 0.95)) @ Matrix.Rotation(sh, 4, 'Y')
    Mfa = Mu @ Matrix.Translation((UA, 0, 0)) @ Matrix.Rotation(el, 4, 'Y')
    return {'upperarm_' + s: Mu, 'forearm_' + s: Mfa}


CAB_PIVOT = Vector((0.48, 0.0, 1.10))
CAB_RAISE = 0.04      # v4: the cab sits 4 cm higher, in its cradle, with room to sink


def _cab_sim():
    """The cab is a mass on soft mounts (2.2 Hz, damping 0.35), driven by the hull's own
    vertical acceleration, so it floats a little while the hull falls and sinks hard when the
    leg catches it. Simulated for ten loops; the last half step is the periodic answer."""
    dt = 1.0 / 480
    w = 2 * pi * 2.2
    zt = 0.35
    gain = 0.55
    half = TC / 2

    def hz(t):
        return arch(t) + catch(t)
    c = cv = 0.0
    n = int(round(half / dt))
    out = []
    for i in range(n * 20):
        t = i * dt
        a = (hz(t + dt) - 2 * hz(t) + hz(t - dt)) / (dt * dt)
        cv += (-2 * zt * w * cv - w * w * c - gain * a) * dt
        c += cv * dt
        if i >= n * 19:
            out.append(c)
    return out, dt


CAB_SIM, CAB_DT = _cab_sim()


def cab_dz(t):
    tt = t % (TC / 2)
    i = tt / CAB_DT
    i0 = int(i) % len(CAB_SIM)
    i1 = (i0 + 1) % len(CAB_SIM)
    u = i - int(i)
    return CAB_SIM[i0] * (1 - u) + CAB_SIM[i1] * u


def cab_M(t, Mh=None):
    """The cab rides in its cradle on soft mounts: it floats as the hull falls, sinks and nods
    nose-down when the foot lands, rebounds once and settles, and lags the hull's sway."""
    Mh = Mh if Mh is not None else hull_M(t)
    ph = t / TC
    dz = CAB_RAISE + cab_dz(t)
    nod = -radians(1.2) * cab_dz(t - 0.04) / 0.06
    roll = radians(0.8) * sin(2 * pi * (ph - 0.31) - 0.9)
    return (Mh @ Matrix.Translation(CAB_PIVOT + Vector((0, 0, dz))) @ Matrix.Rotation(nod, 4, 'Y')
            @ Matrix.Rotation(roll, 4, 'X') @ Matrix.Translation(-CAB_PIVOT))


def rigid_pose(t):
    P = {}
    Mh = hull_M(t)
    P['hull'] = Mh
    P['cab'] = cab_M(t, Mh)
    info = {}
    for s in SIDES:
        Mf, stance, plant = foot_M(t, s)
        P['foot_' + s] = Mf
        legs, D = leg_solve(t, s, Mh, Mf)
        P.update(legs)
        P.update(arm_solve(t, s, Mh))
        info[s] = (stance, plant, D)
    return P, info


# =========================================================================
# Secondary motion: hook pendulum, antenna whip (periodic steady state)
# =========================================================================
DT = 1.0 / 480
FAIRLEAD_L = Vector((0.885, 0, -0.16))
HOOK_LEN = 0.40
G = Vector((0, 0, -9.81))


def world_pt(Mfun, p, t):
    return Mfun(t) @ p


def simulate():
    warm = TC * 10
    t = -warm
    # pendulum state: bob position and velocity (world)
    piv = rigid_pose(t)[0]['forearm_L'] @ FAIRLEAD_L
    bob = piv + Vector((0, 0, -HOOK_LEN))
    vel = Vector((0, 0, 0))
    # antenna tip deflection in hull frame (x, y) and velocity
    ant = Vector((0, 0))
    antv = Vector((0, 0))
    w_a = 2 * pi * 1.2
    z_a = 0.10
    ANT_BASE = Vector((0.10, -0.45, 2.88))

    def base_acc(tt):
        h = 1 / 240
        p0 = cab_M(tt - h) @ ANT_BASE
        p1 = cab_M(tt) @ ANT_BASE
        p2 = cab_M(tt + h) @ ANT_BASE
        return (p2 - 2 * p1 + p0) / (h * h)
    rec = {}
    frame_times = {round(f / FPS, 6): f for f in range(-1, NF + 1)}
    steps = int(round((warm + NF / FPS + 2 / FPS) / DT))
    for i in range(steps + 1):
        tt = -warm + i * DT
        key = round(tt, 6)
        Mh = hull_M(tt)
        if key in frame_times:
            rec[frame_times[key]] = (bob.copy(), ant.copy(), Mh.copy())
        # pendulum (position-based, constraint to cable length, light damping)
        piv = arm_solve(tt, 'L', Mh)['forearm_L'] @ FAIRLEAD_L
        vel += G * DT
        vel *= (1 - 4.0 * DT)   # v5: a harder winch brake; the bigger side roll swung the hook into its own arm at 1.6
        nb = bob + vel * DT
        dvec = nb - piv
        nb = piv + dvec.normalized() * HOOK_LEN
        vel = (nb - bob) / DT
        bob = nb
        # antenna: damped oscillator driven by base acceleration (hull frame)
        a = base_acc(tt)
        Rinv = cab_M(tt, Mh).to_3x3().inverted()
        al = Rinv @ a
        acc = Vector((-al.x, -al.y)) * 1.5 - ant * (w_a ** 2) - antv * (2 * z_a * w_a)
        antv += acc * DT
        ant += antv * DT
    return rec


SIM = simulate()


def hook_M(f, Mfa):
    piv = Mfa @ FAIRLEAD_L
    bob = SIM[f][0]
    Z = (piv - bob).normalized()
    Xh = Mfa.to_3x3().col[0]
    Y = Z.cross(Xh).normalized()
    X = Y.cross(Z).normalized()
    return frame(X, Y, Z, piv)


# =========================================================================
# Pistons: anchors, sized from the walk
# =========================================================================
PISTONS = [
    # name, A body, A point, A kind, A axis (local), A base dir, B body, B point, B kind, B axis, B base dir, rod r, barrel r, pin/ball r
]
for s, sg in SIDES.items():
    T, S, F = 'thigh_' + s, 'shin_' + s, 'foot_' + s
    PISTONS.append(dict(name='knee_cyl_' + s, A=T, pA=Vector((0.37, 0, -0.33)), kA='pin', axA=Vector((0, 1, 0)), baseA=Vector((-1, 0, 0.3)), lenA=0.19,
                        B=S, pB=Vector((0.28, 0, 0.20)), kB='pin', axB=Vector((0, 1, 0)), baseB=Vector((-0.81, 0, -0.58)), lenB=0.26,
                        rr=0.038, Rb=0.072, rp=0.03, w=0.045))
    for side_s in (1, -1):
        tag = 'o' if side_s == sg else 'i'
        PISTONS.append(dict(name='ankle_cyl_%s_%s' % (s, tag), A=S, pA=Vector((-0.30, 0.13 * side_s, -0.36)), kA='ball', axA=Vector((0, side_s, 0)), baseA=None, lenA=0,
                            B=F, pB=Vector((-0.50, 0.13 * side_s, -0.04)), kB='ball', axB=Vector((0, side_s, 0)), baseB=None, lenB=0,
                            rr=0.03, Rb=0.058, rp=0.042, w=0.0))
    PISTONS.append(dict(name='hip_cyl_' + s, A='hull', pA=Vector((0.30, 1.26 * sg, 0.50)), kA='ball', axA=Vector((0, sg, 0)), baseA=None, lenA=0,
                        B=T, pB=Vector((0.02, 0.41 * sg, -0.80)), kB='ball', axB=Vector((0, sg, 0)), baseB=None, lenB=0,
                        rr=0.032, Rb=0.062, rp=0.045, w=0.0))
    U, Fa = 'upperarm_' + s, 'forearm_' + s
    PISTONS.append(dict(name='elbow_cyl_' + s, A=U, pA=Vector((-0.10, 0, 0.20)), kA='pin', axA=Vector((0, 1, 0)), baseA=Vector((0.3, 0, -1)), lenA=0.09,
                        B=Fa, pB=Vector((0.073, 0, 0.23)), kB='pin', axB=Vector((0, 1, 0)), baseB=Vector((-0.30, 0, -0.95)), lenB=0.16,
                        rr=0.024, Rb=0.048, rp=0.022, w=0.03))

ALLT = [f / FPS for f in range(-1, NF + 1)]
POSES = {}
INFO = {}
for f in range(-1, NF + 1):
    POSES[f], INFO[f] = rigid_pose(f / FPS)

for p in PISTONS:
    ds = []
    for f in range(-1, NF + 1):
        PA = POSES[f][p['A']] @ p['pA']
        PB = POSES[f][p['B']] @ p['pB']
        ds.append((PA - PB).length)
    p['Dmin'], p['Dmax'] = min(ds), max(ds)


def eye_size(p, k):
    if k == 'pin':
        return p['rp'] * 1.9
    return p['rp'] * 1.55


E_TGT = 0.14
for p in PISTONS:
    eA = eye_size(p, p['kA'])
    eB = eye_size(p, p['kB'])
    p['z0'] = eA + 0.02 + 0.6 * p['Rb']  # barrel cap starts here, clear of the clevis plates
    floor_ = p['z0'] + 0.025             # inner floor of the barrel
    p['Lr'] = p['Dmin'] - floor_ - 0.03  # 3 cm from bottoming at full retraction
    Lb = p['Dmax'] - p['Lr'] + E_TGT
    lim = p['Dmin'] - eB - 0.035
    if Lb > lim:
        Lb = lim
    p['Lb'] = Lb
    p['e_min'] = p['Lr'] + p['Lb'] - p['Dmax']
    p['bottom_min'] = p['Dmin'] - p['Lr'] - floor_
    print('PISTON %-16s D %.3f..%.3f stroke %.3f Lb %.3f Lr %.3f engage_min %.3f bottom_clear %.3f'
          % (p['name'], p['Dmin'], p['Dmax'], p['Dmax'] - p['Dmin'], p['Lb'], p['Lr'], p['e_min'], p['bottom_min']))


def anchor_hw(p, end):
    b = p[end]
    pt = p['p' + end]
    k = p['k' + end]
    ax = p['ax' + end].normalized()
    nm = p['name'] + '_' + end.lower()
    if k == 'pin':
        w = p['w']
        rp = p['rp']
        base = p['base' + end].normalized()
        L = p['len' + end]
        # clevis plates: rounded end around the pin, extending along base
        r_pl = rp * 1.9 + 0.012
        perp = ax.cross(base).normalized()
        for side_s in (1, -1):
            pl = []
            for i in range(13):
                a = pi / 2 + pi * i / 12
                pl.append((r_pl * cos(a), r_pl * sin(a)))
            pl.append((r_pl * cos(1.5 * pi) + L, -r_pl))
            pl.append((L, r_pl))
            # local plate frame: u along -base? build in (u=base, v=perp)
            pl = [(-u if False else u, v) for (u, v) in pl]
            M = Matrix.Identity(4)
            U = -base
            for i in range(3):
                M[i][0], M[i][1], M[i][2] = -U[i], perp[i], ax[i]
                M[i][3] = pt[i]
            a0 = (w + 0.012) * side_s
            a1 = (w + 0.012 + 0.018) * side_s
            pr = [(u, v) for (u, v) in pl]
            part(b, nm + '_clevis_%s' % ('a' if side_s > 0 else 'b'), prism(pr, a0, a1, 'XY', M), 'frame', bevel=0.005)
        part(b, nm + '_pin', cyl(pt, rp, 2 * (w + 0.012 + 0.018) + 0.03, ax), 'steel', bevel=0.003)
    else:
        rb = p['rp']
        # ball stud: lug, post along ax, ball at the anchor point
        half = rb * 0.6
        lug_c = pt - ax * (half + 0.03 + 0.03)
        part(b, nm + '_ball', sphere(pt, rb, u=24, v=12), 'steel', bevel=0)
        part(b, nm + '_post', seg_cyl(pt, pt - ax * (half + 0.035), rb * 0.45, segs=16), 'steel', bevel=0.002)
        lb = lathe([(0, -0.03), (rb * 1.3, -0.03), (rb * 1.3, 0.03), (0, 0.03)], 6, axis_M(ax, lug_c))
        part(b, nm + '_lug', lb, 'frame', bevel=0.004)


for p in PISTONS:
    anchor_hw(p, 'A')
    anchor_hw(p, 'B')
    bn, rn = p['name'] + '_barrel', p['name'] + '_rod'
    body(bn)
    body(rn)
    for nm, end, length in ((bn, 'A', p['Lb']), (rn, 'B', p['Lr'])):
        k = p['k' + end]
        if k == 'pin':
            ri, ro, hw = p['rp'] * CLR, p['rp'] * 1.9, p['w']
        else:
            ri, ro, hw = p['rp'] * CLR, p['rp'] * 1.55, p['rp'] * 0.6
        part(nm, 'eye', tube((0, 0, 0), ri, ro, 2 * hw, 'Y', segs=32), 'steel', bevel=0.003)
        z0 = ro + 0.02 + (0.6 * p['Rb'] if nm == bn else 0.0)
        neck_w = min(hw, ro * 0.8)
        part(nm, 'neck', boxr(-ro * 0.62, ro * 0.62, -neck_w * 0.95, neck_w * 0.95, ri * 1.35, z0 + 0.012), 'steel', bevel=0.004)
        if nm == bn:
            Rb, rr = p['Rb'], p['rr']
            prof = [(0, z0), (Rb, z0), (Rb, length - 0.05), (Rb + 0.008, length - 0.05), (Rb + 0.008, length),
                    (rr * CLR, length), (rr * CLR, length - 0.04), (Rb - 0.012, length - 0.04), (Rb - 0.012, z0 + 0.025), (0, z0 + 0.025)]
            part(nm, 'barrel', lathe(prof, 32), 'barrel', bevel=0.004)
            part(nm, 'port', cyl((0, Rb + 0.012, z0 + 0.06), 0.016, 0.03, 'Y', segs=12), 'brass', bevel=0.002)
            part(nm, 'band', tube((0, 0, z0 + 0.012), Rb - 0.002, Rb + 0.006, 0.02, 'Z'), 'hazard', bevel=0.002)
        else:
            rr = p['rr']
            part(nm, 'rod', lathe([(0, z0 - 0.01), (rr, z0 - 0.01), (rr, length), (0, length)], 24), 'chrome', bevel=0.003)
    p['z0A'] = eye_size(p, p['kA']) + 0.02

save('05_hydraulics')

# =========================================================================
# Hoses (keyed polylines) and antenna whip
# =========================================================================
HOSES = []
for s, sg in SIDES.items():
    HOSES.append(dict(name='knee_hose_' + s, A='thigh_' + s, pA=Vector((-0.12, 0.265 * sg, -0.74)), dA=Vector((-0.2, 0.7 * sg, -0.7)),
                      B='shin_' + s, pB=Vector((-0.10, 0.275 * sg, -0.45)), dB=Vector((-0.1, 0.7 * sg, 0.7)), sag=0.06, out=0.22 * sg))
    HOSES.append(dict(name='ankle_hose_' + s, A='shin_' + s, pA=Vector((0.06, 0.275 * sg, -0.78)), dA=Vector((0, 0.8 * sg, -0.6)),
                      B='foot_' + s, pB=Vector((0.16, 0.29 * sg, -0.118)), dB=Vector((0.1, 0.5 * sg, 0.85)), sag=0.03, out=0.14 * sg))
HR = 0.021
NPTS = 18


def hose_points(h, P):
    MA, MB = P[h['A']], P[h['B']]
    pA = MA @ h['pA']
    dA = (MA.to_3x3() @ h['dA']).normalized()
    pB = MB @ h['pB']
    dB = (MB.to_3x3() @ h['dB']).normalized()
    dist = (pB - pA).length
    T = max(0.25, dist * 0.9)
    outv = (MA.to_3x3() @ Vector((0, 1, 0))).normalized() * h['out']
    pts = [pA - dA * 0.015]
    for i in range(NPTS):
        s = i / (NPTS - 1)
        h00 = 2 * s ** 3 - 3 * s ** 2 + 1
        h10 = s ** 3 - 2 * s ** 2 + s
        h01 = -2 * s ** 3 + 3 * s ** 2
        h11 = s ** 3 - s ** 2
        q = h00 * pA + h10 * T * dA + h01 * pB + h11 * T * (-dB)
        q += Vector((0, 0, -h['sag'])) * sin(pi * s) ** 2 * 0.5 + outv * sin(pi * s) ** 1.5 * 0.5
        pts.append(q)
    pts.append(pB - dB * 0.015)
    return pts


def fitting(h, end):
    b = h[end]
    p = h['p' + end]
    d = h['d' + end].normalized()
    part(b, h['name'] + '_fit_' + end.lower(), lathe([(HR * 1.35, -0.06), (0.034, -0.06), (0.034, -0.02), (0.03, -0.015), (0.03, 0.0), (HR * 1.35, 0.0)], 6 if True else 24, axis_M(d, p)), 'brass', bevel=0.002)


for h in HOSES:
    fitting(h, 'A')
    fitting(h, 'B')
    cu = bpy.data.curves.new(h['name'], 'CURVE')
    cu.dimensions = '3D'
    cu.bevel_depth = HR
    cu.bevel_resolution = 3
    cu.use_fill_caps = True
    sp = cu.splines.new('POLY')
    sp.points.add(NPTS + 2 - 1)
    ob = bpy.data.objects.new('hose.' + h['name'], cu)
    MECH.objects.link(ob)
    cu.materials.append(mat('rubber'))
    ob['body'] = 'hose_' + h['name']
    ob['kind'] = 'hose'
    PARTS.append({'name': ob.name, 'body': 'hose_' + h['name'], 'kind': 'hose'})
    h['ob'] = ob

ANT_N = 12
ANT_L = 1.45
cu = bpy.data.curves.new('antenna_whip', 'CURVE')
cu.dimensions = '3D'
cu.bevel_depth = 0.007
cu.bevel_resolution = 2
cu.use_fill_caps = True
sp = cu.splines.new('POLY')
sp.points.add(ANT_N - 1)
ANT = bpy.data.objects.new('hose.antenna_whip', cu)
MECH.objects.link(ANT)
cu.materials.append(mat('frame'))
ANT['body'] = 'antenna'
ANT['kind'] = 'hose'
PARTS.append({'name': ANT.name, 'body': 'antenna', 'kind': 'hose'})


def antenna_points(f, Mh):
    base = Mh @ Vector((0.10, -0.45, 2.85))
    R = Mh.to_3x3()
    dx, dy = SIM[f][1]
    pts = []
    for i in range(ANT_N):
        s = i / (ANT_N - 1)
        sh = s * s * (3 - s) / 2
        local = Vector((dx * sh, dy * sh, ANT_L * s))
        pts.append(base + R @ local)
    return pts


# =========================================================================
# Stage 6: key the walk
# =========================================================================
bpy.context.preferences.edit.keyframe_new_interpolation_type = 'LINEAR'
prevq = {}
for f in range(-1, NF + 1):
    P = dict(POSES[f])
    P['hook'] = hook_M(f, P['forearm_L'])
    for p in PISTONS:
        PA = P[p['A']] @ p['pA']
        PB = P[p['B']] @ p['pB']
        Z = (PB - PA).normalized()
        for end, org, zz in (('A', PA, Z), ('B', PB, -Z)):
            ax = (P[p[end]].to_3x3() @ p['ax' + end]).normalized()
            Y = (ax - zz * ax.dot(zz)).normalized()
            X = Y.cross(zz)
            P[p['name'] + ('_barrel' if end == 'A' else '_rod')] = frame(X, Y, zz, org)
    for name, e in BODIES.items():
        M = P[name]
        loc, q, _ = M.decompose()
        if name in prevq:
            q.make_compatible(prevq[name])
        prevq[name] = q
        e.location = loc
        e.rotation_quaternion = q
        e.keyframe_insert('location', frame=f)
        e.keyframe_insert('rotation_quaternion', frame=f)
    for h in HOSES:
        pts = hose_points(h, P)
        for i, q in enumerate(pts):
            pt = h['ob'].data.splines[0].points[i]
            pt.co = (q.x, q.y, q.z, 1.0)
            pt.keyframe_insert('co', frame=f)
    for i, q in enumerate(antenna_points(f, P['cab'])):
        pt = ANT.data.splines[0].points[i]
        pt.co = (q.x, q.y, q.z, 1.0)
        pt.keyframe_insert('co', frame=f)

# metadata for the checker and the scene stage
meta = {
    'fps': FPS, 'nf': NF, 'tc': TC, 'v': V, 'loop_dist': LOOP_DIST, 'step': STEP, 'roll_h': ROLL_H,
    'pistons': [{k: (v if isinstance(v, (int, float, str)) else None) for k, v in p.items()} for p in PISTONS],
    'parts': PARTS,
    'plants': {},
    'stance': {},
    'pendulum_seam_mm': (SIM[NF][0] - SIM[0][0] - Vector((LOOP_DIST, 0, 0))).length * 1000,
    'antenna_seam_mm': (SIM[NF][1] - SIM[0][1]).length * 1000,
}
for s in SIDES:
    plants = set()
    st = []
    for f in range(0, NF):
        stance, plant, D = INFO[f][s]
        st.append(bool(stance))
        if stance:
            plants.add(tuple(round(v, 6) for v in plant))
    meta['stance'][s] = st
    meta['plants'][s] = sorted(plants)
    meta['legD_' + s] = [INFO[f][s][2] for f in range(0, NF)]
with open(os.path.join(OUT, 'meta.json'), 'w') as fh:
    json.dump(meta, fh, indent=1)
print('PARTS', len([q for q in PARTS if q['kind'] != 'decal']), 'DECALS', len([q for q in PARTS if q['kind'] == 'decal']),
      'BODIES', len(BODIES), 'seam pendulum mm %.2f antenna mm %.2f' % (meta['pendulum_seam_mm'], meta['antenna_seam_mm']))
save('06_walk')
