#!/usr/bin/env python3 """ Render CLAW trajectory CSV files to MP4 videos with MuJoCo EGL rendering. """ import os import subprocess from pathlib import Path # Set EGL as the rendering backend BEFORE importing mujoco os.environ.setdefault('MUJOCO_GL', 'egl') REPO_ROOT = Path(__file__).resolve().parents[1] DEFAULT_MODEL_PATH = REPO_ROOT / 'g1_xml' / 'g1_29dof_rev_1_0.xml' import numpy as np import pandas as pd import mujoco import cv2 def csv_to_mp4(csv_path, output_path, max_frames=None, fps=50, resolution=(640, 480), model_path=None, track_body=None, track_distance=3.0, track_azimuth=90.0, track_elevation=-15.0, dynamic_root_camera=False, static_fit_camera=False, fit_distance_scale=1.8, fit_margin=1.2, fit_lookat_z_offset=0.45, white_scene=False, white_grid_scene=False, crf=28, preset='ultrafast'): """ Convert CSV motion data to MP4 video using EGL headless rendering Args: csv_path: Path to input CSV file output_path: Path to output MP4 file max_frames: Maximum frames to process (None for all) fps: Frames per second resolution: (width, height) tuple model_path: Path to robot model XML file track_body: Body name to track with camera (e.g. "pelvis"). If None, uses the named camera "follow" defined in the XML. track_distance: Camera distance from tracked body (metres) track_azimuth: Camera azimuth angle in degrees (world frame) track_elevation: Camera elevation angle in degrees (negative = above) """ try: # Read data data = pd.read_csv(csv_path, header=None).values print(f" Data shape: {data.shape}") # Adjust Z-axis offset for AMASS data if data[0, 2] < 0.1: data[:, 2] += 0.793 print(" Applied AMASS Z-axis offset") # Limit frames if specified if max_frames: data = data[:max_frames] print(f" Limited to first {max_frames} frames") # Load robot model if model_path is None: model_path = str(DEFAULT_MODEL_PATH) if not os.path.exists(model_path): raise FileNotFoundError(f"MuJoCo model XML not found: {model_path}") m = mujoco.MjModel.from_xml_path(model_path) d = mujoco.MjData(m) # Set parameters m.opt.timestep = 1.0 / fps # Default: no shadows, no ground reflection if m.nlight: m.light_castshadow[:] = 0 if m.nmat: m.mat_reflectance[:] = 0.0 if white_scene: if m.tex_data.size: m.tex_data[:] = 255 if m.nmat: m.mat_rgba[:, :] = np.array([1.0, 1.0, 1.0, 1.0]) floor_id = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_GEOM, 'floor') if floor_id >= 0: m.geom_rgba[floor_id] = np.array([1.0, 1.0, 1.0, 1.0]) m.vis.rgba.haze[:] = np.array([1.0, 1.0, 1.0, 1.0]) try: m.vis.rgba.fog[:] = np.array([1.0, 1.0, 1.0, 1.0]) except AttributeError: pass print(" Applied white scene (skybox, ground, haze)") if white_grid_scene: # White sky + white ground with gray grid lines. sky_id = -1 ground_id = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_TEXTURE, 'groundplane') for t in range(m.ntex): if m.tex_type[t] == mujoco.mjtTexture.mjTEXTURE_SKYBOX: sky_id = t # Whiten skybox texture only if sky_id >= 0: adr = m.tex_adr[sky_id] size = m.tex_height[sky_id] * m.tex_width[sky_id] * m.tex_nchannel[sky_id] m.tex_data[adr:adr + size] = 255 # Paint ground texture: white background, gray grid if ground_id >= 0: w = m.tex_width[ground_id] h = m.tex_height[ground_id] nc = m.tex_nchannel[ground_id] adr = m.tex_adr[ground_id] tile = np.full((h, w, nc), 255, dtype=np.uint8) grid_color = 150 # gray grid lines line_w = max(1, w // 150) tile[:line_w, :, :] = grid_color tile[-line_w:, :, :] = grid_color tile[:, :line_w, :] = grid_color tile[:, -line_w:, :] = grid_color m.tex_data[adr:adr + h * w * nc] = tile.reshape(-1) if m.nmat: m.mat_rgba[:, :] = np.array([1.0, 1.0, 1.0, 1.0]) m.vis.rgba.haze[:] = np.array([1.0, 1.0, 1.0, 1.0]) try: m.vis.rgba.fog[:] = np.array([1.0, 1.0, 1.0, 1.0]) except AttributeError: pass print(" Applied white-grid scene (white skybox, white ground w/ gray grid)") # Set up camera dynamic_camera = None if static_fit_camera: center = 0.5 * (data[:, :3].min(axis=0) + data[:, :3].max(axis=0)) span = data[:, :3].max(axis=0) - data[:, :3].min(axis=0) horizontal_radius = 0.5 * np.linalg.norm(span[:2]) + fit_margin distance = max(track_distance, fit_distance_scale * horizontal_radius + 0.5) static_camera = mujoco.MjvCamera() static_camera.type = mujoco.mjtCamera.mjCAMERA_FREE static_camera.lookat[:] = np.array([center[0], center[1], max(center[2] + fit_lookat_z_offset, 0.65)]) static_camera.distance = distance static_camera.azimuth = track_azimuth static_camera.elevation = track_elevation camera_arg = static_camera print(f" Static fit camera, lookat={static_camera.lookat.round(3)}, " f"dist={distance:.2f}, az={track_azimuth}, el={track_elevation}") elif dynamic_root_camera: dynamic_camera = mujoco.MjvCamera() dynamic_camera.type = mujoco.mjtCamera.mjCAMERA_FREE dynamic_camera.distance = track_distance dynamic_camera.azimuth = track_azimuth dynamic_camera.elevation = track_elevation camera_arg = dynamic_camera print(f" Dynamic root camera, dist={track_distance}, " f"az={track_azimuth}, el={track_elevation}") elif track_body is not None: body_id = mujoco.mj_name2id(m, mujoco.mjtObj.mjOBJ_BODY, track_body) if body_id < 0: raise ValueError(f"Body '{track_body}' not found in model") cam = mujoco.MjvCamera() cam.type = mujoco.mjtCamera.mjCAMERA_TRACKING cam.trackbodyid = body_id cam.distance = track_distance cam.azimuth = track_azimuth cam.elevation = track_elevation camera_arg = cam print(f" Tracking body '{track_body}' (id={body_id}), " f"dist={track_distance}, az={track_azimuth}, el={track_elevation}") else: camera_arg = "follow" # Create renderer with EGL backend (automatically used when MUJOCO_GL=egl) width, height = resolution m.vis.global_.offwidth = max(m.vis.global_.offwidth, width) m.vis.global_.offheight = max(m.vis.global_.offheight, height) renderer = mujoco.Renderer(m, height=height, width=width) # Create temporary video file temp_path = output_path.replace('.mp4', '_temp.mp4') fourcc = cv2.VideoWriter_fourcc(*'mp4v') writer = cv2.VideoWriter(temp_path, fourcc, fps, (width, height)) if not writer.isOpened(): raise RuntimeError(f"Failed to open video writer for {temp_path}") print(f" Processing {len(data)} frames at {fps} FPS, {width}x{height}...") # Process frames for i, frame in enumerate(data): # Set robot state d.qpos[:36] = frame # Quaternion conversion: xyzw -> wxyz d.qpos[3] = frame[6] # w d.qpos[4:7] = frame[3:6] # xyz # Forward dynamics and render mujoco.mj_forward(m, d) if dynamic_camera is not None: dynamic_camera.lookat[:] = d.qpos[:3] dynamic_camera.lookat[2] += 0.8 renderer.update_scene(d, camera=camera_arg) img = renderer.render() # Write to video img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) writer.write(img_bgr) if (i + 1) % 50 == 0: print(f" Progress: {i+1}/{len(data)} ({100*(i+1)/len(data):.1f}%)") writer.release() renderer.close() # Convert to H264 format with compression print(f" Converting to H.264 format...") try: result = subprocess.run([ 'ffmpeg', '-i', temp_path, '-vcodec', 'libx264', '-crf', str(crf), '-preset', preset, '-pix_fmt', 'yuv420p', '-y', output_path ], check=True, capture_output=True, text=True) # Delete temporary file if os.path.exists(temp_path): os.remove(temp_path) file_size_mb = os.path.getsize(output_path) / (1024 * 1024) print(f" ✓ Video saved: {output_path} ({file_size_mb:.2f} MB)") return True except FileNotFoundError: print(f" Warning: ffmpeg not found, saving without H.264 compression") if os.path.exists(temp_path): os.rename(temp_path, output_path) print(f" ✓ Video saved: {output_path}") return True except subprocess.CalledProcessError as e: print(f" Warning: FFmpeg failed: {e.stderr}") if os.path.exists(temp_path): os.rename(temp_path, output_path) print(f" ✓ Video saved: {output_path} (uncompressed)") return True except Exception as e: print(f" ✗ Error processing {csv_path}: {e}") return False if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Render a CLAW CSV trajectory to MP4 video (MuJoCo EGL headless)') parser.add_argument('--csv', type=str, required=True, help='Input CSV file path') parser.add_argument('--output', type=str, required=True, help='Output MP4 file path') parser.add_argument('--max-frames', type=int, default=None, help='Maximum frames to process') parser.add_argument('--fps', type=int, default=50, help='Frames per second (default: 50)') parser.add_argument('--width', type=int, default=640, help='Video width (default: 640, smaller = faster)') parser.add_argument('--height', type=int, default=480, help='Video height (default: 480, smaller = faster)') parser.add_argument('--model', type=str, default=str(DEFAULT_MODEL_PATH), help='Path to robot model XML file ' f'(default: {DEFAULT_MODEL_PATH})') parser.add_argument('--track-body', type=str, default=None, help='Body name to follow with camera (e.g. "pelvis"). ' 'Overrides the XML "follow" camera.') parser.add_argument('--track-distance', type=float, default=3.0, help='Camera distance from tracked body in metres (default: 3.0)') parser.add_argument('--track-azimuth', type=float, default=90.0, help='Camera azimuth angle in degrees, world frame (default: 90)') parser.add_argument('--track-elevation', type=float, default=-15.0, help='Camera elevation angle in degrees, negative = above (default: -15)') parser.add_argument('--dynamic-root-camera', action='store_true', help='Move a free camera with the root position instead of using a fixed XML camera') parser.add_argument('--static-fit-camera', action='store_true', help='Use one fixed camera per clip, centered on the full root trajectory') parser.add_argument('--fit-distance-scale', type=float, default=1.8, help='Distance multiplier for --static-fit-camera (smaller = larger robot)') parser.add_argument('--fit-margin', type=float, default=1.2, help='Extra trajectory margin in metres for --static-fit-camera') parser.add_argument('--fit-lookat-z-offset', type=float, default=0.45, help='Vertical lookat offset for --static-fit-camera') parser.add_argument('--white-scene', action='store_true', help='Render with white skybox, white ground, and white haze') parser.add_argument('--white-grid-scene', action='store_true', help='Render with white skybox and white ground with gray grid lines') parser.add_argument('--crf', type=int, default=28, help='H.264 CRF quality (lower is higher quality; default: 28)') parser.add_argument('--preset', type=str, default='ultrafast', help='H.264 encoder preset (default: ultrafast)') args = parser.parse_args() # Create output directory os.makedirs(os.path.dirname(args.output) or '.', exist_ok=True) # Convert csv_to_mp4( csv_path=args.csv, output_path=args.output, max_frames=args.max_frames, fps=args.fps, resolution=(args.width, args.height), model_path=args.model, track_body=args.track_body, track_distance=args.track_distance, track_azimuth=args.track_azimuth, track_elevation=args.track_elevation, dynamic_root_camera=args.dynamic_root_camera, static_fit_camera=args.static_fit_camera, fit_distance_scale=args.fit_distance_scale, fit_margin=args.fit_margin, fit_lookat_z_offset=args.fit_lookat_z_offset, white_scene=args.white_scene, white_grid_scene=args.white_grid_scene, crf=args.crf, preset=args.preset, )