Source code for joltsim.camera

from __future__ import annotations

from typing import Any, Optional, Tuple

import numpy as np


[docs] def has_wgpu() -> bool: try: import wgpu # noqa: F401 return True except ImportError: return False
def _quat_to_mat(q: np.ndarray) -> np.ndarray: """Convert xyzw quaternion(s) (..., 4) to 3x3 rotation matrix (..., 3, 3).""" q = np.asarray(q, dtype=np.float32) x, y, z, w = q[..., 0], q[..., 1], q[..., 2], q[..., 3] norm = np.sqrt(x * x + y * y + z * z + w * w) norm = np.maximum(norm, 1e-8) x, y, z, w = x / norm, y / norm, z / norm, w / norm xx, yy, zz = x * x, y * y, z * z xy, xz, yz = x * y, x * z, y * z wx, wy, wz = w * x, w * y, w * z r = np.empty(q.shape[:-1] + (3, 3), dtype=np.float32) r[..., 0, 0] = 1.0 - 2.0 * (yy + zz) r[..., 0, 1] = 2.0 * (xy - wz) r[..., 0, 2] = 2.0 * (xz + wy) r[..., 1, 0] = 2.0 * (xy + wz) r[..., 1, 1] = 1.0 - 2.0 * (xx + zz) r[..., 1, 2] = 2.0 * (yz - wx) r[..., 2, 0] = 2.0 * (xz - wy) r[..., 2, 1] = 2.0 * (yz + wx) r[..., 2, 2] = 1.0 - 2.0 * (xx + yy) return r def _quat_mul(q1: np.ndarray, q2: np.ndarray) -> np.ndarray: """Multiply xyzw quaternions (..., 4) * (..., 4).""" x1, y1, z1, w1 = q1[..., 0], q1[..., 1], q1[..., 2], q1[..., 3] x2, y2, z2, w2 = q2[..., 0], q2[..., 1], q2[..., 2], q2[..., 3] return np.stack( [ w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2, w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, ], axis=-1, ).astype(np.float32)
[docs] def compute_view_matrix( eye: Tuple[float, float, float], target: Tuple[float, float, float], up: Tuple[float, float, float] = (0.0, 0.0, 1.0), ) -> np.ndarray: """Compute a 4x4 column-major look-at view matrix (float32).""" e = np.asarray(eye, dtype=np.float32) t = np.asarray(target, dtype=np.float32) u = np.asarray(up, dtype=np.float32) f = t - e f = f / max(1e-8, float(np.linalg.norm(f))) s = np.cross(f, u) s = s / max(1e-8, float(np.linalg.norm(s))) u_ortho = np.cross(s, f) m = np.eye(4, dtype=np.float32) m[0, :3] = s m[1, :3] = u_ortho m[2, :3] = -f m[0, 3] = -np.dot(s, e) m[1, 3] = -np.dot(u_ortho, e) m[2, 3] = np.dot(f, e) return m
[docs] def compute_projection_matrix( fov_deg: float, aspect: float, near: float = 0.05, far: float = 50.0, ) -> np.ndarray: """Compute a 4x4 perspective projection matrix (float32).""" f = 1.0 / np.tan(np.deg2rad(fov_deg) * 0.5) m = np.zeros((4, 4), dtype=np.float32) m[0, 0] = f / max(1e-6, aspect) m[1, 1] = f m[2, 2] = (far + near) / (near - far) m[2, 3] = (2.0 * far * near) / (near - far) m[3, 2] = -1.0 return m
def _shade_hits( body_idx: np.ndarray, frac: np.ndarray, normals: np.ndarray, cos_angle: np.ndarray, far: float, ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: # Convert Euclidean ray distance (frac * far) to planar Z-depth along camera forward axis depth = (frac * float(far) * cos_angle).astype(np.float32) seg = body_idx.astype(np.int32) light_dir = np.array([0.4, -0.4, 0.8], dtype=np.float32) light_dir /= np.linalg.norm(light_dir) ndotl = np.clip(np.sum(normals * light_dir[None, :], axis=-1), 0.15, 1.0) rgb = np.empty(body_idx.shape + (3,), dtype=np.uint8) rgb[..., 0] = 24 rgb[..., 1] = 26 rgb[..., 2] = 32 hit_mask = seg >= 0 if np.any(hit_mask): ids = seg[hit_mask] base_r = ((ids * 67 + 90) % 180 + 60).astype(np.float32) base_g = ((ids * 131 + 110) % 180 + 60).astype(np.float32) base_b = ((ids * 197 + 140) % 180 + 60).astype(np.float32) shade = ndotl[hit_mask] rgb[hit_mask, 0] = np.clip(base_r * shade, 0, 255).astype(np.uint8) rgb[hit_mask, 1] = np.clip(base_g * shade, 0, 255).astype(np.uint8) rgb[hit_mask, 2] = np.clip(base_b * shade, 0, 255).astype(np.uint8) return rgb, depth, seg def _resolve_camera_frame( world: Any, is_vec: bool, view_matrix: Optional[np.ndarray], body_idx: Optional[int], site_idx: Optional[int], local_pos: Tuple[float, float, float], local_quat: Tuple[float, float, float, float], ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """Return (eye, right, up, forward, cam_linvel, cam_angvel). For World: each array has shape (3,). For VecWorld: each array has shape (N, 3) when mounted or (3,) when fixed view_matrix. """ if view_matrix is not None: view = np.asarray(view_matrix, dtype=np.float32) inv_view = np.linalg.inv(view) eye = inv_view[:3, 3] right = inv_view[:3, 0] up = inv_view[:3, 1] forward = -inv_view[:3, 2] zeros = np.zeros(3, dtype=np.float32) return eye, right, up, forward, zeros, zeros if body_idx is None and site_idx is None: raise ValueError("Must provide either view_matrix, body_idx, or site_idx") l_pos = np.asarray(local_pos, dtype=np.float32) l_quat = np.asarray(local_quat, dtype=np.float32) if is_vec: n_envs = int(world.num_envs) if site_idx is not None: pos_list = [] quat_list = [] for e in range(n_envs): p, q = world.get_site_pose(e, int(site_idx)) pos_list.append(p) quat_list.append(q) base_pos = np.asarray(pos_list, dtype=np.float32) base_quat = np.asarray(quat_list, dtype=np.float32) else: base_pos = np.asarray(world.body_pos[:, int(body_idx)], dtype=np.float32) base_quat = np.asarray(world.body_quat[:, int(body_idx)], dtype=np.float32) r_base = _quat_to_mat(base_quat) eye = base_pos + np.einsum("nij,j->ni", r_base, l_pos) cam_quat = _quat_mul(base_quat, np.broadcast_to(l_quat, (n_envs, 4))) r_cam = _quat_to_mat(cam_quat) right = r_cam[:, :, 0] up = r_cam[:, :, 1] forward = -r_cam[:, :, 2] if body_idx is not None: b_lin = np.asarray(world.body_linvel[:, int(body_idx)], dtype=np.float32) b_ang = np.asarray(world.body_angvel[:, int(body_idx)], dtype=np.float32) b_pos = np.asarray(world.body_pos[:, int(body_idx)], dtype=np.float32) cam_linvel = b_lin + np.cross(b_ang, eye - b_pos) cam_angvel = b_ang else: cam_linvel = np.zeros((n_envs, 3), dtype=np.float32) cam_angvel = np.zeros((n_envs, 3), dtype=np.float32) return eye, right, up, forward, cam_linvel, cam_angvel # Single World if site_idx is not None: base_pos, base_quat = world.get_site_pose(int(site_idx)) base_pos = np.asarray(base_pos, dtype=np.float32) base_quat = np.asarray(base_quat, dtype=np.float32) else: base_pos = np.asarray(world.body_pos[int(body_idx)], dtype=np.float32) base_quat = np.asarray(world.body_quat[int(body_idx)], dtype=np.float32) r_base = _quat_to_mat(base_quat) eye = base_pos + r_base @ l_pos cam_quat = _quat_mul(base_quat, l_quat) r_cam = _quat_to_mat(cam_quat) right = r_cam[:, 0] up = r_cam[:, 1] forward = -r_cam[:, 2] if body_idx is not None: b_lin = np.asarray(world.body_linvel[int(body_idx)], dtype=np.float32) b_ang = np.asarray(world.body_angvel[int(body_idx)], dtype=np.float32) b_pos = np.asarray(world.body_pos[int(body_idx)], dtype=np.float32) cam_linvel = b_lin + np.cross(b_ang, eye - b_pos) cam_angvel = b_ang else: cam_linvel = np.zeros(3, dtype=np.float32) cam_angvel = np.zeros(3, dtype=np.float32) return eye, right, up, forward, cam_linvel, cam_angvel def _compute_optical_flow( world: Any, is_vec: bool, hit_body_idx: np.ndarray, hit_pos: np.ndarray, eye: np.ndarray, right: np.ndarray, up: np.ndarray, forward: np.ndarray, cam_linvel: np.ndarray, cam_angvel: np.ndarray, width: int, height: int, fov_tan_x: float, fov_tan_y: float, ) -> np.ndarray: """Compute 2D pixel velocity (du/dt, dv/dt) in pixels/sec from rigid-body motion.""" flow = np.zeros(hit_body_idx.shape + (2,), dtype=np.float32) hit_mask = hit_body_idx >= 0 if not np.any(hit_mask): return flow b_pos_all = np.asarray(world.body_pos, dtype=np.float32) b_lin_all = np.asarray(world.body_linvel, dtype=np.float32) b_ang_all = np.asarray(world.body_angvel, dtype=np.float32) if is_vec: n_envs = int(world.num_envs) env_ids = np.arange(n_envs, dtype=np.int32)[:, None, None] env_ids = np.broadcast_to(env_ids, hit_body_idx.shape) e_idx = env_ids[hit_mask] b_idx = hit_body_idx[hit_mask] p_hit = hit_pos[hit_mask] b_pos = b_pos_all[e_idx, b_idx] b_lin = b_lin_all[e_idx, b_idx] b_ang = b_ang_all[e_idx, b_idx] v_hit = b_lin + np.cross(b_ang, p_hit - b_pos) if eye.ndim == 2: c_eye = eye[e_idx] c_right = right[e_idx] c_up = up[e_idx] c_fwd = forward[e_idx] c_lin = cam_linvel[e_idx] c_ang = cam_angvel[e_idx] else: c_eye = eye[None, :] c_right = right[None, :] c_up = up[None, :] c_fwd = forward[None, :] c_lin = cam_linvel[None, :] c_ang = cam_angvel[None, :] else: b_idx = hit_body_idx[hit_mask] p_hit = hit_pos[hit_mask] b_pos = b_pos_all[b_idx] b_lin = b_lin_all[b_idx] b_ang = b_ang_all[b_idx] v_hit = b_lin + np.cross(b_ang, p_hit - b_pos) c_eye = eye[None, :] c_right = right[None, :] c_up = up[None, :] c_fwd = forward[None, :] c_lin = cam_linvel[None, :] c_ang = cam_angvel[None, :] rel_p = p_hit - c_eye v_cam_pt = c_lin + np.cross(c_ang, rel_p) v_rel = v_hit - v_cam_pt x_c = np.sum(rel_p * c_right, axis=-1) y_c = np.sum(rel_p * c_up, axis=-1) z_c = np.maximum(np.sum(rel_p * c_fwd, axis=-1), 1e-6) vx_c = np.sum(v_rel * c_right, axis=-1) vy_c = np.sum(v_rel * c_up, axis=-1) vz_c = np.sum(v_rel * c_fwd, axis=-1) inv_z2 = 1.0 / (z_c * z_c) du_dt = (width / (2.0 * fov_tan_x)) * (vx_c * z_c - x_c * vz_c) * inv_z2 dv_dt = -(height / (2.0 * fov_tan_y)) * (vy_c * z_c - y_c * vz_c) * inv_z2 flow[hit_mask, 0] = du_dt.astype(np.float32) flow[hit_mask, 1] = dv_dt.astype(np.float32) return flow
[docs] def get_camera_image( world: Any, width: int, height: int, view_matrix: Optional[np.ndarray] = None, projection_matrix: Optional[np.ndarray] = None, far: float = 50.0, as_torch: bool = False, device: str = "cpu", body_idx: Optional[int] = None, site_idx: Optional[int] = None, local_pos: Tuple[float, float, float] = (0.0, 0.0, 0.0), local_quat: Tuple[float, float, float, float] = (0.0, 0.0, 0.0, 1.0), return_flow: bool = False, ) -> Tuple[Any, ...]: """Render offscreen (rgb uint8, depth float32, seg int32[, flow float32]) for World or VecWorld. Supports either an explicit ``view_matrix`` or mounting to a ``body_idx`` / ``site_idx`` with optional ``local_pos`` and ``local_quat`` (xyzw). When ``return_flow=True``, also returns instantaneous 2D optical flow ``(du/dt, dv/dt)`` in pixels/second of shape ``(H, W, 2)`` or ``(N, H, W, 2)``. When ``as_torch=True``, converts outputs via ``joltsim.to_torch(..., device=device)``. """ if projection_matrix is None: projection_matrix = compute_projection_matrix(60.0, float(width) / max(1.0, float(height)), 0.05, float(far)) is_vec = hasattr(world, "num_envs") eye, right, up, forward, cam_linvel, cam_angvel = _resolve_camera_frame( world, is_vec, view_matrix, body_idx, site_idx, local_pos, local_quat ) fov_tan_y = 1.0 / max(1e-6, float(projection_matrix[1, 1])) fov_tan_x = 1.0 / max(1e-6, float(projection_matrix[0, 0])) xs = (2.0 * (np.arange(width, dtype=np.float32) + 0.5) / width - 1.0) * fov_tan_x ys = (1.0 - 2.0 * (np.arange(height, dtype=np.float32) + 0.5) / height) * fov_tan_y gx, gy = np.meshgrid(xs, ys) if is_vec and eye.ndim == 2: n_envs = int(world.num_envs) dirs = ( gx[None, :, :, None] * right[:, None, None, :] + gy[None, :, :, None] * up[:, None, None, :] + forward[:, None, None, :] ) norms = np.linalg.norm(dirs, axis=-1, keepdims=True) dirs = (dirs / np.maximum(norms, 1e-8)).reshape(n_envs, width * height, 3).astype(np.float32) starts = np.broadcast_to(eye[:, None, :], (n_envs, width * height, 3)).copy().astype(np.float32) cos_angle = np.sum(dirs * forward[:, None, :], axis=-1).reshape(n_envs, height, width) else: dirs = ( gx[..., None] * right[None, None, :] + gy[..., None] * up[None, None, :] + forward[None, None, :] ) norms = np.linalg.norm(dirs, axis=-1, keepdims=True) dirs = (dirs / np.maximum(norms, 1e-8)).reshape(-1, 3).astype(np.float32) starts = np.broadcast_to(eye[None, :], (width * height, 3)).copy().astype(np.float32) cos_hw = np.sum(dirs * forward[None, :], axis=-1).reshape(height, width) if is_vec: n_envs = int(world.num_envs) cos_angle = np.broadcast_to(cos_hw[None, :, :], (n_envs, height, width)) else: cos_angle = cos_hw hits = world.raycast_batch(starts, dirs, float(far)) if is_vec: n_envs = int(world.num_envs) body_idx_arr = hits["body_idx"].reshape(n_envs, height, width) frac = hits["fraction"].reshape(n_envs, height, width) normals = np.stack([hits["nx"], hits["ny"], hits["nz"]], axis=-1).reshape(n_envs, height, width, 3) hit_pos = np.stack([hits["px"], hits["py"], hits["pz"]], axis=-1).reshape(n_envs, height, width, 3) else: body_idx_arr = hits["body_idx"].reshape(height, width) frac = hits["fraction"].reshape(height, width) normals = np.stack([hits["nx"], hits["ny"], hits["nz"]], axis=-1).reshape(height, width, 3) hit_pos = np.stack([hits["px"], hits["py"], hits["pz"]], axis=-1).reshape(height, width, 3) rgb, depth, seg = _shade_hits(body_idx_arr, frac, normals, cos_angle, far) outputs: Tuple[Any, ...] if return_flow: flow = _compute_optical_flow( world, is_vec, body_idx_arr, hit_pos, eye, right, up, forward, cam_linvel, cam_angvel, width, height, fov_tan_x, fov_tan_y, ) outputs = (rgb, depth, seg, flow) else: outputs = (rgb, depth, seg) if as_torch: from joltsim.torch_bridge import to_torch nb = device != "cpu" return tuple(to_torch(arr, device=device, non_blocking=nb) for arr in outputs) return outputs