"""HFC online qualifier: T800 starter script.

See the EngineAI T800 in the MuJoCo simulator, and play a boxing move on it.

  1. Install Python 3.10 or newer (python.org), then:   pip install mujoco numpy
  2. Unzip the T800 model next to this file, so you have a folder called  t800
  3. See the robot:         python t800_starter.py
     Play a move on it:     python t800_starter.py left_hook.npy

A move file (.npy) holds one row per frame at 30 frames a second, 32 numbers a row:
base position (3), base rotation as a quaternion w x y z (4), then the 25 joint angles (25).
That is exactly the robot's pose in MuJoCo (its qpos), so playing a move just poses the robot frame by frame.
Your job in the qualifier is to make the robot perform these moves under real physics, with a policy you train.

Keys in the viewer: drag to turn, scroll to zoom, double-click a part to select it. Close the window to stop.
"""
import os
import sys
import time

try:
    import mujoco
    import mujoco.viewer
    import numpy as np
except ImportError:
    sys.exit("Missing software. Run:  pip install mujoco numpy")

HERE = os.path.dirname(os.path.abspath(__file__))
MODEL = os.path.join(HERE, "t800", "xml", "serial_t800.xml")
FPS = 30


def main():
    if not os.path.exists(MODEL):
        sys.exit("Can't find " + MODEL + "\nUnzip the T800 model next to this script, so there is a folder called t800.")
    model = mujoco.MjModel.from_xml_path(MODEL)
    data = mujoco.MjData(model)
    print("T800 loaded: %d moving joints, pose size %d" % (model.njnt - 1, model.nq))
    for j in range(1, model.njnt):
        lo, hi = model.jnt_range[j]
        print("  %-24s %6.0f to %4.0f degrees" % (mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_JOINT, j), np.degrees(lo), np.degrees(hi)))

    frames = None
    if len(sys.argv) > 1:
        frames = np.load(sys.argv[1])
        frames = frames.reshape(len(frames), -1)
        if frames.shape[1] != model.nq:
            sys.exit("This move has %d numbers a frame; the T800 needs %d." % (frames.shape[1], model.nq))
        print("Playing %s: %d frames, %.1f seconds, on a loop" % (sys.argv[1], len(frames), len(frames) / FPS))
    else:
        data.qpos[2] = 1.03  # stand the robot at its normal height

    with mujoco.viewer.launch_passive(model, data) as viewer:
        i = 0
        while viewer.is_running():
            start = time.time()
            if frames is not None:
                data.qpos[:] = frames[i % len(frames)]
                i += 1
            mujoco.mj_forward(model, data)  # pose only, no physics: the robot shows the move exactly
            viewer.sync()
            time.sleep(max(0.0, 1.0 / FPS - (time.time() - start)))


if __name__ == "__main__":
    main()
