"""Sweep all joints together, report self-collision contacts per pose, render a montage.
Usage: render_sweep.py <urdf> <out.png>
"""
import sys
import xml.etree.ElementTree as ET
import mujoco
import numpy as np
from PIL import Image

urdf, out = sys.argv[1], sys.argv[2]
root = ET.parse(urdf).getroot()
for l in root.findall("link"):
    if l.find("inertial") is None:
        i = ET.SubElement(l, "inertial")
        ET.SubElement(i, "mass", {"value": "0.1"})
        ET.SubElement(i, "inertia", dict(ixx="1e-4", ixy="0", ixz="0", iyy="1e-4", iyz="0", izz="1e-4"))
mj = ET.Element("mujoco")
c = ET.SubElement(mj, "compiler")
c.set("discardvisual", "false")
c.set("meshdir", ".")
root.insert(0, mj)
m = mujoco.MjModel.from_xml_string(ET.tostring(root, encoding="unicode"))
d = mujoco.MjData(m)
ims = []
worst = 0
for q in [-1.2, -0.6, 0.0, 0.6, 1.2]:
    d.qpos[:] = q
    mujoco.mj_forward(m, d)
    worst = max(worst, d.ncon)
    print(f"q={q:+.1f}: contacts={d.ncon}")
    cam = mujoco.MjvCamera()
    cam.lookat[:] = m.stat.center
    cam.distance = m.stat.extent * 1.5
    cam.azimuth = 35
    cam.elevation = -16
    with mujoco.Renderer(m, 460, 460) as r:
        r.update_scene(d, cam)
        ims.append(r.render())
Image.fromarray(np.concatenate(ims, 1)).save(out)
print(f"worst-case contacts over sweep = {worst}  ->", "CLEAN" if worst == 0 else "check")
print("rendered", out)
