"""HdRenderer: pybullet (DIRECT, ER_TINY_RENDERER) model of one HRDexDB robot embodiment (xArm6 + hand) that renders pixel-aligned RGB / mask / camera-space-normal images for a given OpenCV camera (K, cam_from_world). Modelled on robot_tools/trex/scripts/trex_robot.py::TrexRenderer / droid render_episode.py::RobotRenderer (read-only reuse of droid dutils.py for the GL matrices: TinyRenderer rasterizes one row too high -> projection uses cy+1). Geometry -------- * URDF = dataset assets/robots/<...>.urdf (hd_data.URDF); the URDF root link `world` is the robot frame of C2R (official viewer: robot at identity, cameras at inv(ext @ C2R)). We place the root at T_world_robot = C2R and render in the dataset world frame, so the camera view matrix is simply cam_from_world (static extrinsics.json or per-frame ego_calib.json). * qpos (6 arm + hand dof) is applied to the URDF's non-fixed non-mimic joints in file order (hd_data.urdf_joint_spec, same order the official yourdfpy/viser viewer uses); mimic joints are set to multiplier * parent + offset (pybullet ignores ). * every link is recoloured uniform light grey (render video); masks/normals do not depend on colour. render(T_cam_from_world, K, wh) -> rgb (H,W,3) uint8, mask (H,W) bool, normal (H,W,3) uint8 (OpenGL camera convention, (n+1)/2, background 0; computed inside the mask bounding box only). """ import sys from pathlib import Path import cv2 import imageio.v2 as imageio import numpy as np import pybullet as p from scipy.spatial.transform import Rotation as R ROOT = Path(__file__).resolve().parent.parent DROID_SCRIPTS = Path("/home/wujiayir/robot_tools/droid/scripts") for _p in (str(DROID_SCRIPTS), str(ROOT / "scripts")): if _p not in sys.path: sys.path.insert(0, _p) from dutils import gl_projection_matrix, gl_view_matrix # noqa: E402 (read-only reuse) from hd_data import URDF, urdf_joint_spec # noqa: E402 NEAR, FAR = 0.05, 6.0 ROBOT_RGBA = (0.78, 0.78, 0.80, 1.0) def mat_to_pq(T): return T[:3, 3].tolist(), R.from_matrix(T[:3, :3]).as_quat().tolist() class HdRenderer: def __init__(self, emb, tiny_renderer=True, rgba=ROBOT_RGBA): self.emb = emb self.urdf = Path(URDF[emb]) self.tiny_renderer = bool(tiny_renderer) self.cid = p.connect(p.DIRECT) self.robot = p.loadURDF(str(self.urdf), useFixedBase=True, physicsClientId=self.cid) self.joint_idx, self.link_idx = {}, {"__base__": -1} for j in range(p.getNumJoints(self.robot, physicsClientId=self.cid)): info = p.getJointInfo(self.robot, j, physicsClientId=self.cid) self.joint_idx[info[1].decode()] = j self.link_idx[info[12].decode()] = j self.actuated, self.mimic = urdf_joint_spec(self.urdf) missing = [n for n in list(self.actuated) + list(self.mimic) if n not in self.joint_idx] if missing: raise KeyError(f"{self.urdf}: joints not in pybullet model: {missing}") if rgba is not None: for j in range(-1, p.getNumJoints(self.robot, physicsClientId=self.cid)): p.changeVisualShape(self.robot, j, rgbaColor=list(rgba), physicsClientId=self.cid) self.T_world_robot = np.eye(4) self.q = np.zeros(len(self.actuated)) self.set_qpos(self.q) @property def ndof(self): return len(self.actuated) # -- state ------------------------------------------------------------------------------ def set_base(self, T_world_robot): self.T_world_robot = np.asarray(T_world_robot, dtype=float) pos, quat = mat_to_pq(self.T_world_robot) p.resetBasePositionAndOrientation(self.robot, pos, quat, physicsClientId=self.cid) def set_qpos(self, q): q = np.asarray(q, dtype=float).ravel() assert len(q) == self.ndof, (len(q), self.ndof) qd = dict(zip(self.actuated, q)) for n, v in qd.items(): p.resetJointState(self.robot, self.joint_idx[n], float(v), physicsClientId=self.cid) for n, (parent, mult, off) in self.mimic.items(): p.resetJointState(self.robot, self.joint_idx[n], mult * float(qd[parent]) + off, physicsClientId=self.cid) self.q = q def link_pose(self, name): """4x4 world pose of a URDF link frame.""" j = self.link_idx[name] if j == -1: pos, quat = p.getBasePositionAndOrientation(self.robot, physicsClientId=self.cid) else: st = p.getLinkState(self.robot, j, computeForwardKinematics=True, physicsClientId=self.cid) pos, quat = st[4], st[5] T = np.eye(4) T[:3, :3] = R.from_quat(quat).as_matrix() T[:3, 3] = pos return T # -- rendering ---------------------------------------------------------------------------- def render_raw(self, T_cam_from_world, K, wh): w, h = int(wh[0]), int(wh[1]) V = gl_view_matrix(np.asarray(T_cam_from_world, dtype=float)) P = gl_projection_matrix(np.asarray(K, dtype=float), w, h, NEAR, FAR, tiny_renderer=self.tiny_renderer) _, _, rgb, depth, seg = p.getCameraImage(w, h, viewMatrix=V, projectionMatrix=P, renderer=p.ER_TINY_RENDERER, flags=p.ER_NO_SEGMENTATION_MASK if False else p.ER_SEGMENTATION_MASK_OBJECT_AND_LINKINDEX, physicsClientId=self.cid) rgb = np.asarray(rgb, dtype=np.uint8).reshape(h, w, 4)[:, :, :3] depth = np.asarray(depth, dtype=np.float64).reshape(h, w) seg = np.asarray(seg).reshape(h, w) return rgb, depth, seg def render(self, T_cam_from_world, K, wh, with_normals=True): rgb, depth, seg = self.render_raw(T_cam_from_world, K, wh) mask = seg >= 0 if not with_normals: return rgb, mask, None normal = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.uint8) if mask.any(): ys, xs = np.nonzero(mask) y0, y1 = max(int(ys.min()) - 2, 0), min(int(ys.max()) + 3, mask.shape[0]) x0, x1 = max(int(xs.min()) - 2, 0), min(int(xs.max()) + 3, mask.shape[1]) z = FAR * NEAR / (FAR - (FAR - NEAR) * depth[y0:y1, x0:x1]) Kc = np.asarray(K, dtype=float).copy() Kc[0, 2] -= x0 Kc[1, 2] -= y0 normal[y0:y1, x0:x1] = camera_space_normals(z, Kc, mask[y0:y1, x0:x1]) return rgb, mask, normal def close(self): cid = getattr(self, "cid", None) if cid is None: return self.cid = None try: if p.isConnected(cid): p.disconnect(physicsClientId=cid) except Exception: pass def __del__(self): try: self.close() except Exception: pass # ---------------------------------------------------------------------------- image helpers (copied from droid render_episode.py) def camera_space_normals(z_eye, K, mask): """Per-pixel camera-space normals from a clean synthetic depth map -> HxWx3 uint8, OpenGL camera convention (x right, y up, z toward viewer), encoded n*0.5+0.5; background 0.""" h, w = z_eye.shape fx, fy = K[0, 0], K[1, 1] cx, cy = K[0, 2], K[1, 2] us, vs = np.meshgrid(np.arange(w), np.arange(h)) X = (us - cx) / fx * z_eye Y = (vs - cy) / fy * z_eye P3 = np.stack([X, Y, z_eye], axis=-1) def one_sided(axis): sl_f = [slice(None)] * 3 sl_b = [slice(None)] * 3 sl_f[axis] = slice(0, -1) sl_b[axis] = slice(1, None) diff = P3[tuple(sl_b)] - P3[tuple(sl_f)] fwd = np.zeros_like(P3) bwd = np.zeros_like(P3) fwd[tuple(sl_f)] = diff bwd[tuple(sl_b)] = diff first = [slice(None)] * 3 last = [slice(None)] * 3 first[axis] = slice(0, 1) last[axis] = slice(-1, None) fwd[tuple(last)] = bwd[tuple(last)] bwd[tuple(first)] = fwd[tuple(first)] pick_bwd = np.abs(bwd[..., 2]) < np.abs(fwd[..., 2]) out = fwd.copy() out[pick_bwd] = bwd[pick_bwd] return out dx = one_sided(1) dy = one_sided(0) n = np.cross(dy, dx) n /= np.linalg.norm(n, axis=-1, keepdims=True) + 1e-9 n[..., 1] *= -1.0 n[..., 2] *= -1.0 out = np.zeros((h, w, 3), dtype=np.uint8) out[mask] = ((n[mask] * 0.5 + 0.5) * 255).astype(np.uint8) return out class VideoWriter: """H.264 writer (BGR input), macro_block_size=1, same settings as the DROID / T-Rex outputs (+ x264 preset knob).""" def __init__(self, path, fps=30, macro_block_size=1, quality=7, preset="veryfast", threads=2): self.path = Path(path) self.n = 0 self.w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=quality, pixelformat="yuv420p", macro_block_size=macro_block_size, ffmpeg_params=["-movflags", "+faststart", "-preset", preset, "-threads", str(threads)]) def write(self, bgr): self.w.append_data(np.ascontiguousarray(bgr[:, :, ::-1])) self.n += 1 def release(self): self.w.close() def overlay_frame(real_bgr, render_rgb, mask, alpha=0.6): out = real_bgr.copy() render_bgr = render_rgb[:, :, ::-1] out[mask] = (alpha * render_bgr[mask] + (1 - alpha) * real_bgr[mask]).astype(np.uint8) return out def draw_contours(img_bgr, mask, color=(0, 255, 255), thickness=2): cs, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) cv2.drawContours(img_bgr, cs, -1, color, thickness) return img_bgr def selftest(): """Load every robot URDF, check joint resolution, and render one frame from a synthetic camera.""" import time for emb in URDF: t0 = time.time() r = HdRenderer(emb) T = np.eye(4) T[:3, 3] = [0.0, 0.0, 1.5] T[:3, :3] = R.from_euler("x", 180, degrees=True).as_matrix() # looking down -z of world from +1.5 m K = np.array([[1700.0, 0, 1024.0], [0, 1700.0, 768.0], [0, 0, 1]]) r.set_qpos(np.zeros(r.ndof)) rgb, mask, nrm = r.render(T, K, (2048, 1536)) t1 = time.time() rgb, mask, nrm = r.render(T, K, (2048, 1536)) print(f"{emb}: {r.ndof} dof {len(r.mimic)} mimic, links {len(r.link_idx)}, mask px {int(mask.sum())}, " f"load+first {t1 - t0:.1f}s, render {time.time() - t1:.2f}s") r.close() if __name__ == "__main__": selftest()