#!/usr/bin/env python3 """Replay a duck-state-rec.py jsonl through MuJoCo offscreen: exact sim qpos per frame -> mp4. Uses the body server's own World/Body mapping (joint names -> qpos addresses), so the render is the simulated robot's real state, not a re-simulation. Tracking camera on the trunk. usage (in microduck_rl, MUJOCO_GL=egl): uv run python duck-replay-render.py [--fps 30] [--w 1280] [--h 720] [--dist 0.9] [--elev -15] [--azim 135] [--label TEXT] """ import argparse, json import imageio import mujoco import numpy as np from mjlab_microduck.sim.body_server import DEFAULT_SCENE, World, Body ap = argparse.ArgumentParser() ap.add_argument("inp"); ap.add_argument("out") ap.add_argument("--fps", type=int, default=30) ap.add_argument("--w", type=int, default=1280); ap.add_argument("--h", type=int, default=720) ap.add_argument("--dist", type=float, default=0.9) ap.add_argument("--elev", type=float, default=-15.0) ap.add_argument("--azim", type=float, default=135.0) ap.add_argument("--fixed", type=str, default=None, help="x,y,z fixed lookat (world camera, no tracking)") a = ap.parse_args() rows = [json.loads(l) for l in open(a.inp)] world = World(DEFAULT_SCENE, 1) body = Body(world, 0) m, d = world.model, world.data m.vis.global_.offwidth = max(m.vis.global_.offwidth, a.w) m.vis.global_.offheight = max(m.vis.global_.offheight, a.h) r = mujoco.Renderer(m, height=a.h, width=a.w) cam = mujoco.MjvCamera() cam.type = mujoco.mjtCamera.mjCAMERA_FREE cam.distance, cam.elevation, cam.azimuth = a.dist, a.elev, a.azim # resample the recording onto a fixed frame clock (wall time), nearest earlier sample t = np.array([row["wall"] for row in rows]); t -= t[0] n_frames = int(t[-1] * a.fps) + 1 w = imageio.get_writer(a.out, fps=a.fps, codec="libx264", quality=8, pixelformat="yuv420p", macro_block_size=8) j = 0 look = None for k in range(n_frames): tk = k / a.fps while j + 1 < len(rows) and t[j + 1] <= tk: j += 1 row = rows[j] d.qpos[body.trunk:body.trunk + 3] = row["trunk"] d.qpos[body.trunk + 3:body.trunk + 7] = row["quat"] for slot, wire in enumerate(body.to_wire): d.qpos[body.qpos_adr[slot]] = row["positions"][wire] mujoco.mj_forward(m, d) p = np.array(row["trunk"], dtype=float) # smooth the camera target so walking bob does not shake the frame look = p if look is None else 0.9 * look + 0.1 * p cam.lookat[:] = [float(v) for v in a.fixed.split(",")] if a.fixed else [look[0], look[1], 0.08] r.update_scene(d, camera=cam) w.append_data(r.render()) w.close() print(f"{n_frames} frames, {t[-1]:.1f} s -> {a.out}")