"""Weight check for a walking mech (BYOK Games, MIT license).

Measures, on every frame of the walk, how the hull and the cab move after each
footfall: how far they drop, when they bottom out, how far they rebound past
their settled level (overshoot), how long they take to settle, and how much the
stance leg shortens (hull point to planted foot). It then asks whether that
motion is big enough to read on a phone.

Run:
  blender -b walk.blend -P weight_check.py -- out.json [options]

Options (each is optional; names are guessed when left out):
  --hull NAME        object that carries the hull (default: B_hull, or a name with "hull")
  --cab NAME         object that carries the cab (default: B_cab, or a name with "cab"); "none" to skip
  --feet A,B         foot objects (default: every object named like B_foot_*)
  --height M         machine height in metres (default: measured from the meshes at frame 0)
  --camera NAME      also measure in that camera's view, and time its shake against footfalls
  --width PX         phone width in pixels (default 390)
  --fill F           share of a 16:9 frame's height the machine fills in the reference framing (default 0.7)

How the numbers are defined:
  * A footfall is the frame a foot's lowest point comes within 1 cm of the
    lowest it ever gets, after having risen at least 5 cm.
  * Each footfall's window runs to the next footfall of any foot.
  * The tracked point on a body is the centre of its meshes' bounding boxes,
    fixed to the body at frame 0, so it moves exactly as the body does.
  * hull and cab: world height of that point. cab_on_hull: the cab point's
    height in the hull's own frame, which is the settle on the mounts, the
    secondary motion that makes a heavy machine read as heavy.
  * drop: height at the footfall minus the lowest height in the window.
  * bottom_frames: frames from the footfall to that lowest point.
  * settled level: median height over the last third of the window.
  * overshoot: highest point after the bottom, above the settled level, as a
    percent of (settled level minus the bottom).
  * recovery: time from the footfall until the body stays within 25% of the
    drop of its settled level for the rest of the window.
  * leg compression: distance from the hull point to the planted foot at the
    footfall, minus its smallest value in the window.
  * side sway: peak to peak of the hull point across the direction of travel.
  * foot lift: how high the lowest point of a foot rises, as a percent of height.
    These two are reported but not gated: reviewers said a big roll over the
    planted leg and a low foot lift sell weight more than the vertical drop,
    and we do not have enough evidence yet to set a number.
  * phone pixels: drop / height x fill x (width x 9/16). With the defaults a
    5.3 m machine is 153 px tall on a 390 px wide phone, and 1 px is 3.5 cm.

Readability gates (the minimum we hold ourselves to; change them if you
disagree): the hull drops at least 1.5 px and bottoms out within 6 frames
(a hit, not a float); the cab settles on its mounts by at least 1.5 px,
overshoots its settled level by 10% to 60%, and settles within 0.6 s and
before the next footfall. A 3 cm cab settle on a 5.3 m machine is 0.9 px and
fails.
"""
import bpy, json, sys, statistics
from mathutils import Vector
from bpy_extras.object_utils import world_to_camera_view

A = sys.argv[sys.argv.index('--') + 1:]
OUT = A[0]
opt = {}
i = 1
while i < len(A):
    if A[i].startswith('--'):
        opt[A[i][2:]] = A[i + 1]
        i += 2
    else:
        i += 1

SC = bpy.context.scene
F0, F1 = SC.frame_start, SC.frame_end
FR = list(range(F0, F1 + 1))
NF = len(FR)
FPS = SC.render.fps / SC.render.fps_base
WIDTH = float(opt.get('width', 390))
FILL = float(opt.get('fill', 0.7))
GATE = {'hull_drop_px': 1.5, 'hull_bottom_frames': 6, 'cab_settle_px': 1.5, 'overshoot_pct': (10.0, 60.0), 'recovery_s': 0.6}


def find(name, key):
    if name and name.lower() == 'none':
        return None
    if name:
        return bpy.data.objects[name]
    if 'B_' + key in bpy.data.objects:
        return bpy.data.objects['B_' + key]
    c = [o for o in bpy.data.objects if key in o.name.lower() and o.parent is None]
    return c[0] if c else None


HULL = find(opt.get('hull'), 'hull')
CAB = find(opt.get('cab'), 'cab')
if 'feet' in opt:
    FEET = [bpy.data.objects[n] for n in opt['feet'].split(',')]
else:
    FEET = sorted([o for o in bpy.data.objects if o.name.startswith('B_foot_')], key=lambda o: o.name)
if HULL is None or not FEET:
    raise SystemExit('weight_check: name the hull and feet with --hull and --feet')
CAM = bpy.data.objects[opt['camera']] if 'camera' in opt else None


def meshes_under(ob):
    out = [ob] if ob.type in ('MESH', 'CURVE') else []
    for c in ob.children_recursive:
        if c.type in ('MESH', 'CURVE'):
            out.append(c)
    return out


SC.frame_set(F0)


def local_corners(ob):
    inv = ob.matrix_world.inverted()
    pts = []
    for m in meshes_under(ob):
        for c in m.bound_box:
            pts.append(inv @ (m.matrix_world @ Vector(c)))
    if not pts:
        pts = [Vector((0, 0, 0))]
    return pts


def centre(pts):
    lo = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts)))
    hi = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))
    return (lo + hi) / 2


HULL_C = centre(local_corners(HULL))
CAB_C = centre(local_corners(CAB)) if CAB else None
FOOT_PTS = {f.name: local_corners(f) for f in FEET}

if 'height' in opt:
    HEIGHT = float(opt['height'])
else:
    zs_lo, zs_hi = [], []
    seen = set()
    roots = [HULL] + FEET + ([CAB] if CAB else [])
    # the machine: meshes under the named roots and under every rigid body empty (B_*)
    for o in bpy.data.objects:
        if o.type not in ('MESH', 'CURVE'):
            continue
        r = o
        while r.parent is not None:
            r = r.parent
        if not (r in roots or r.name.startswith('B_')):
            continue
        for c in o.bound_box:
            w = o.matrix_world @ Vector(c)
            zs_lo.append(w.z)
            zs_hi.append(w.z)
    HEIGHT = max(zs_hi) - min(min(zs_lo), 0.0)

REF_PX_H = WIDTH * 9 / 16 * FILL      # machine height on screen, reference framing
PX_PER_M = REF_PX_H / HEIGHT

# ---------------------------------------------------------------- sample every frame
hz, cz, cabrel, foot_low, foot_pos, hull_w, cam_px, cam_rot = [], [], [], {}, {}, [], [], []
for f in FEET:
    foot_low[f.name] = []
    foot_pos[f.name] = []
for fr in FR:
    SC.frame_set(fr)
    hp = HULL.matrix_world @ HULL_C
    hz.append(hp.z)
    hull_w.append(hp.copy())
    if CAB:
        cp = CAB.matrix_world @ CAB_C
        cz.append(cp.z)
        cabrel.append((HULL.matrix_world.inverted() @ cp).z)
    for f in FEET:
        pts = [f.matrix_world @ p for p in FOOT_PTS[f.name]]
        foot_low[f.name].append(min(p.z for p in pts))
        foot_pos[f.name].append(f.matrix_world.translation.copy())
    if CAM:
        rx = SC.render.resolution_x
        ry = SC.render.resolution_y
        sc = WIDTH / rx
        row = []
        for p in ([hp] + ([CAB.matrix_world @ CAB_C] if CAB else [])):
            v = world_to_camera_view(SC, CAM, p)
            row.append((v.x * rx * sc, (1 - v.y) * ry * sc))
        cam_px.append(row)
        cam_rot.append(CAM.matrix_world.to_quaternion())

# ---------------------------------------------------------------- footfalls
strikes = []
for f in FEET:
    lo = foot_low[f.name]
    floor_ = min(lo)
    # hysteresis: a foot lands at 1 cm above its lowest, and must rise past 5 cm to land again
    state = None
    for k in range(-NF, NF):
        z = lo[k % NF]
        if z <= floor_ + 0.01:
            if state == 'up' and k >= 0:
                strikes.append((k, f.name))
            state = 'down'
        elif z >= floor_ + 0.05:
            state = 'up'
strikes.sort()

def window(k):
    nxt = [s for s, _ in strikes if s > k]
    return (nxt[0] if nxt else strikes[0][0] + NF) - k


def settle(series, k, n):
    w = [series[(k + j) % NF] for j in range(n)]
    z0 = w[0]
    jb = min(range(n), key=lambda j: w[j])
    zb = w[jb]
    tail = w[n - max(2, n // 3):]
    rest = statistics.median(tail)
    drop = z0 - zb
    sink = rest - zb
    peak = max(w[jb:]) if jb < n else zb
    over = (peak - rest) / sink * 100 if sink > 1e-5 else 0.0
    band = 0.25 * max(drop, 1e-4)
    jr = n - 1
    for j in range(n - 1, -1, -1):
        if abs(w[j] - rest) > band:
            jr = j + 1
            break
    else:
        jr = 0
    return {'drop_cm': round(drop * 100, 2), 'bottom_frames': jb, 'settled_sink_cm': round(sink * 100, 2),
            'overshoot_pct': round(over, 1), 'recovery_s': round(jr / FPS, 3), 'settles_before_next': jr < n,
            'window_frames': n}


rows = []
for k, fname in strikes:
    n = window(k)
    r = {'frame': FR[k], 'foot': fname, 'hull': settle(hz, k, n)}
    if CAB:
        r['cab'] = settle(cz, k, n)
        r['cab_on_hull'] = settle(cabrel, k, n)
    d = [(hull_w[(k + j) % NF] - foot_pos[fname][(k + j) % NF]).length for j in range(n)]
    r['leg_compression_cm'] = round((d[0] - min(d)) * 100, 2)
    if CAM and k + n <= NF:
        for idx, key in ((0, 'hull'), (1, 'cab')):
            if idx < len(cam_px[k]):
                ys = [cam_px[k + j][idx][1] for j in range(n)]
                r[key + '_screen_drop_px'] = round(max(ys) - ys[0], 2)
    rows.append(r)


def agg(key, sub, fn=statistics.mean):
    v = [r[key][sub] for r in rows if key in r]
    return round(fn(v), 3) if v else None


summary = {'height_m': round(HEIGHT, 3), 'footfalls': len(rows),  'fps': FPS, 'frames': NF,
           'phone_width_px': WIDTH, 'reference_machine_px': round(REF_PX_H, 1), 'cm_per_px': round(100 / PX_PER_M, 2)}
for key in ('hull', 'cab', 'cab_on_hull'):
    if rows and key in rows[0]:
        dmin = agg(key, 'drop_cm', min)
        summary[key] = {
            'drop_cm_mean': agg(key, 'drop_cm'), 'drop_cm_min': dmin,
            'drop_pct_height_min': round(dmin / 100 / HEIGHT * 100, 2),
            'drop_px_min': round(dmin / 100 * PX_PER_M, 2),
            'bottom_frames_mean': agg(key, 'bottom_frames'),
            'overshoot_pct_mean': agg(key, 'overshoot_pct'),
            'recovery_s_max': agg(key, 'recovery_s', max),
            'all_settle_before_next': all(r[key]['settles_before_next'] for r in rows),
        }
# whole-body gait numbers (reported, not gated yet): side sway of the hull point and how
# high the feet lift, because reviewers said these sell weight more than the vertical drop
ys = []
for fr in range(NF):
    hp = hull_w[fr]
    ys.append(hp.y)
# remove the walking direction's drift: sway is measured across the direction of travel
dx = hull_w[-1] - hull_w[0]
fwd = Vector((dx.x, dx.y, 0)).normalized() if dx.length > 1e-6 else Vector((1, 0, 0))
side = Vector((-fwd.y, fwd.x, 0))
lat = [hull_w[k].dot(side) for k in range(NF)]
summary['hull_side_sway_cm'] = round((max(lat) - min(lat)) * 100, 1)
summary['hull_side_sway_px'] = round((max(lat) - min(lat)) * PX_PER_M, 2)
lifts = [max(foot_low[f.name]) - min(foot_low[f.name]) for f in FEET]
summary['foot_lift_cm'] = round(max(lifts) * 100, 1)
summary['foot_lift_pct_height'] = round(max(lifts) / HEIGHT * 100, 2)
lc = [r['leg_compression_cm'] for r in rows]
summary['leg_compression_cm_mean'] = round(statistics.mean(lc), 2) if lc else None
if CAM:
    for key in ('hull', 'cab'):
        v = [r[key + '_screen_drop_px'] for r in rows if key + '_screen_drop_px' in r]
        if v:
            summary[key + '_screen_drop_px_min_in_camera'] = min(v)
    # camera shake timing: angular speed peaks against footfalls
    sp = [0.0] + [cam_rot[j].rotation_difference(cam_rot[j - 1]).angle * FPS for j in range(1, NF)]
    base = statistics.median(sp)
    lags = []
    for k, _ in strikes:
        seg = [(sp[(k + j) % NF], j) for j in range(-2, 7)]
        pk, j = max(seg)
        if pk > base * 2 + 1e-4:
            lags.append(j)
    summary['camera_shake'] = {'footfalls_with_a_shake_peak': len(lags), 'peak_lag_frames': lags}

g = {}
h = summary['hull']
g['hull_drop_px'] = h['drop_px_min'] >= GATE['hull_drop_px']
g['hull_hits_fast'] = h['bottom_frames_mean'] <= GATE['hull_bottom_frames']
if 'cab_on_hull' in summary:
    c = summary['cab_on_hull']
    g['cab_settle_px'] = c['drop_px_min'] >= GATE['cab_settle_px']
    g['cab_overshoot'] = GATE['overshoot_pct'][0] <= c['overshoot_pct_mean'] <= GATE['overshoot_pct'][1]
    g['cab_recovery'] = c['recovery_s_max'] <= GATE['recovery_s'] and c['all_settle_before_next']
summary['gates'] = g
summary['reads_at_phone_size'] = all(g.values())

json.dump({'summary': summary, 'gate_values': GATE, 'footfalls': rows}, open(OUT, 'w'), indent=1)
print('WEIGHT', json.dumps(summary))
