From 8f7567e7637a859f7ed8b01086e6cbcb80e9b60a Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Tue, 6 Oct 2026 16:23:42 -0700 Subject: [PATCH 01/16] bump: mujoco version --- docker/Dockerfile | 2 +- pyproject.toml | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index d40dace23..db9d23c03 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -48,7 +48,7 @@ RUN chmod +x /usr/local/bin/link-editable-source \ pybind11 \ cmake \ ninja \ - "mujoco==3.2.6" \ + "mujoco==3.15.0" \ "pin==3.7.0" \ && uv pip install /opt/rcs-src \ && uv pip install --no-build-isolation /opt/rcs-src/extensions/rcs_fr3 \ diff --git a/pyproject.toml b/pyproject.toml index 2079ea41c..0f0ba562d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,7 +7,7 @@ requires = [ "pybind11", "cmake", "ninja", - "mujoco==3.10.0", + "mujoco==3.15.0", "pin==3.7.0", ] build-backend = "scikit_build_core.build" @@ -36,7 +36,7 @@ dependencies = [ "rpyc~=6.0.2", "pyarrow", "simplejpeg", - "mujoco==3.10.0", + "mujoco==3.15.0", "pin==3.7.0", # pin 3.7.0 currently resolves against older urdfdom/tinyxml SONAMEs at runtime "cmeel-urdfdom<5", @@ -76,7 +76,7 @@ dev = [ "twine~=6.0", ] build_deps = [ - "mujoco==3.10.0", + "mujoco==3.15.0", "pin==3.7.0", "cmeel-urdfdom<5", "cmeel-tinyxml2<11", @@ -93,7 +93,7 @@ environment = { SKBUILD_BUILD_DIR = "/tmp/rcs-build/{wheel_tag}" } archs = ["x86_64"] manylinux-x86_64-image = "manylinux_2_28" before-all = "yum install -y epel-release && yum install -y libXi-devel libXcursor-devel libXinerama-devel libXrandr-devel glfw-devel" -repair-wheel-command = "auditwheel repair -w {dest_dir} {wheel} --exclude libmujoco.so.3.10.0 --exclude libpinocchio_default.so.3.7.0 --exclude libpinocchio_parsers.so.3.7.0" +repair-wheel-command = "auditwheel repair -w {dest_dir} {wheel} --exclude libmujoco.so.3.15.0 --exclude libpinocchio_default.so.3.7.0 --exclude libpinocchio_parsers.so.3.7.0" [tool.cibuildwheel.macos] archs = ["arm64"] From 2330a28f9feb6a755fbf1230aaf0ff7cb1018f81 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Tue, 6 Oct 2026 17:30:16 -0700 Subject: [PATCH 02/16] feat(sim): add support for filament renderer - sim config flag that switches between renderers - pystudio viewer when filament renderer is active - fr3 cart example uses filament renderer --- docs/user_guide/scene_configuration.md | 28 +++ examples/fr3/fr3_env_cartesian_control.py | 3 +- python/rcs/_core/sim.pyi | 36 ++++ python/rcs/camera/sim.py | 234 ++++++++++++++++++-- python/rcs/sim/__init__.py | 2 + python/rcs/sim/filament.py | 235 +++++++++++++++++++++ python/rcs/sim/render_context_bootstrap.py | 7 + python/rcs/sim/sim.py | 28 ++- python/tests/test_filament.py | 60 ++++++ src/pybind/rcs.cpp | 13 +- src/sim/sim.h | 4 + 11 files changed, 620 insertions(+), 30 deletions(-) create mode 100644 python/rcs/sim/filament.py create mode 100644 python/tests/test_filament.py diff --git a/docs/user_guide/scene_configuration.md b/docs/user_guide/scene_configuration.md index aeddac885..889c3eba0 100644 --- a/docs/user_guide/scene_configuration.md +++ b/docs/user_guide/scene_configuration.md @@ -299,6 +299,34 @@ Example: - `depth[y, x] == 1500` means the point is about **1.5 m** away from the camera +## Rendering backend (Filament) + +By default, simulation cameras and the GUI use MuJoCo's classic OpenGL renderer. MuJoCo >= 3.15 also +ships the physically based [Filament](https://github.com/google/filament) renderer and the new +MuJoCo Studio viewer. Switch to them with the `renderer` flag of `SimConfig`: + +```python +from rcs.sim import RendererBackend, SimConfig + +sim_cfg = SimConfig(async_control=False, realtime=False, renderer=RendererBackend.FILAMENT) +``` + +With this flag + +- `SimCameraSet(...)` returns a `FilamentSimCameraSet`: color images are rendered with Filament in + Python (frames are rendered when requested, a fixed camera frame rate is not supported). Filament does + not expose a metric depth buffer through MuJoCo's Python API, so depth images are still rendered with + the classic renderer and always use the metric units described above. +- `open_gui()` launches MuJoCo Studio instead of the passive `mujoco.viewer`. Studio runs in the GUI + subprocess under a regular `python` interpreter (not `mjpython`, also on macOS). + +Environment variables for fine tuning: + +- `RCS_FILAMENT_GRAPHICS_API=opengl|vulkan` graphics API of the camera renderer (default `opengl`) +- `RCS_FILAMENT_SOFTWARE_RENDERING=1` force software rendering for the cameras +- `RCS_FILAMENT_GFX=opengl|vulkan|web|...` Studio graphics mode; `web` serves the viewer over http instead + of opening a window + ### Camera placement #### Fixed scene camera diff --git a/examples/fr3/fr3_env_cartesian_control.py b/examples/fr3/fr3_env_cartesian_control.py index ab0b5fea2..1cc7fd2b1 100644 --- a/examples/fr3/fr3_env_cartesian_control.py +++ b/examples/fr3/fr3_env_cartesian_control.py @@ -2,7 +2,7 @@ import gymnasium as gym from rcs._core.common import RobotPlatform -from rcs._core.sim import SimConfig +from rcs._core.sim import RendererBackend, SimConfig from rcs.camera.sim import SimCameraSet from rcs.envs.base import ( CameraSetWrapper, @@ -50,6 +50,7 @@ def main(): sim_cfg = SimConfig( realtime=False, async_control=False, + renderer=RendererBackend.FILAMENT, ) mjmodel = scene.create_model(cfg) diff --git a/python/rcs/_core/sim.pyi b/python/rcs/_core/sim.pyi index 042e2608e..2d67fc7df 100644 --- a/python/rcs/_core/sim.pyi +++ b/python/rcs/_core/sim.pyi @@ -15,6 +15,7 @@ __all__: list[str] = [ "DynamicJointState", "FrameSet", "GuiClient", + "RendererBackend", "Sim", "SimCameraConfig", "SimCameraSet", @@ -28,6 +29,8 @@ __all__: list[str] = [ "SimTilburgHand", "SimTilburgHandConfig", "SimTilburgHandState", + "CLASSIC", + "FILAMENT", "default_free", "fixed", "free", @@ -102,6 +105,35 @@ class GuiClient: def set_model_and_data(self, arg0: int, arg1: int) -> None: ... def sync(self) -> None: ... +class RendererBackend: + """ + Members: + + CLASSIC + + FILAMENT + """ + + CLASSIC: typing.ClassVar[RendererBackend] # value = + FILAMENT: typing.ClassVar[RendererBackend] # value = + __members__: typing.ClassVar[ + dict[str, RendererBackend] + ] # value = {'CLASSIC': , 'FILAMENT': } + def __eq__(self, other: typing.Any) -> bool: ... + def __getstate__(self) -> int: ... + def __hash__(self) -> int: ... + def __index__(self) -> int: ... + def __init__(self, value: int) -> None: ... + def __int__(self) -> int: ... + def __ne__(self, other: typing.Any) -> bool: ... + def __repr__(self) -> str: ... + def __setstate__(self, state: int) -> None: ... + def __str__(self) -> str: ... + @property + def name(self) -> str: ... + @property + def value(self) -> int: ... + class Sim: def __init__(self, mjmdl: int, mjdata: int) -> None: ... def _start_gui_server(self, id: str) -> None: ... @@ -141,6 +173,7 @@ class SimConfig: frequency: float max_convergence_steps: int realtime: bool + renderer: RendererBackend def __copy__(self) -> SimConfig: ... def __deepcopy__(self, arg0: dict) -> SimConfig: ... def __init__( @@ -149,6 +182,7 @@ class SimConfig: realtime: bool = False, frequency: float = 30.0, max_convergence_steps: int = 500, + renderer: RendererBackend = ..., ) -> None: ... class SimGripper(rcs._core.common.Gripper): @@ -385,3 +419,5 @@ default_free: CameraType # value = fixed: CameraType # value = free: CameraType # value = tracking: CameraType # value = +CLASSIC: RendererBackend # value = +FILAMENT: RendererBackend # value = diff --git a/python/rcs/camera/sim.py b/python/rcs/camera/sim.py index 12af75b47..815fbac88 100644 --- a/python/rcs/camera/sim.py +++ b/python/rcs/camera/sim.py @@ -7,20 +7,71 @@ # from rcs._core.common import BaseCameraConfig from rcs._core import common +from rcs._core.sim import CameraType from rcs._core.sim import FrameSet as _FrameSet -from rcs._core.sim import SimCameraConfig +from rcs._core.sim import RendererBackend, SimCameraConfig from rcs._core.sim import SimCameraSet as _SimCameraSet from rcs.camera.interface import BaseCameraSet, CameraFrame, DataFrame, Frame, FrameSet -from rcs.sim import render_context_bootstrap +from rcs.sim import filament, render_context_bootstrap from rcs import sim +logger = logging.getLogger(__name__) + + +def _camera_id(model: mujoco.MjModel, cfg: SimCameraConfig) -> int: + return mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_CAMERA, cfg.identifier) + + +def _intrinsics( + model: mujoco.MjModel, cfg: SimCameraConfig +) -> np.ndarray[tuple[Literal[3], Literal[4]], np.dtype[np.float64]]: + fovy = model.cam_fovy[_camera_id(model, cfg)] + fx = fy = 0.5 * cfg.resolution_height / np.tan(fovy * np.pi / 360) + return np.array( + [ + [fx, 0, (cfg.resolution_width - 1) / 2, 0], + [0, fy, (cfg.resolution_height - 1) / 2, 0], + [0, 0, 1, 0], + ] + ) + + +def _extrinsics( + model: mujoco.MjModel, data: mujoco.MjData, cfg: SimCameraConfig +) -> np.ndarray[tuple[Literal[4], Literal[4]], np.dtype[np.float64]]: + cam_id = _camera_id(model, cfg) + xpos = data.cam_xpos[cam_id] + xmat = data.cam_xmat[cam_id].reshape(3, 3) + + cam = common.Pose(rotation=xmat, translation=xpos) + # put z axis infront + rotation_p = common.Pose(rpy_vector=np.array([np.pi, 0, 0]), translation=np.array([0, 0, 0])) # type: ignore + cam = cam * rotation_p + + return cam.inverse().pose_matrix() + class SimCameraSet(_SimCameraSet): """Represents a set of cameras in a mujoco simulation. Implements BaseCameraSet + + Rendering happens in C++ with MuJoCo's classic OpenGL renderer. If the simulation was configured with + ``SimConfig(renderer=RendererBackend.FILAMENT)``, constructing this class returns a + :class:`FilamentSimCameraSet` instead. """ + def __new__( + cls, + simulation: sim.Sim, + cameras: dict[str, SimCameraConfig], + physical_units: bool = False, + render_on_demand: bool = True, + ): + if simulation.get_config().renderer == RendererBackend.FILAMENT: + return FilamentSimCameraSet(simulation, cameras, physical_units, render_on_demand) + return super().__new__(cls) + def __init__( self, simulation: sim.Sim, @@ -93,28 +144,10 @@ def _cpp_to_python_frames(self, cpp_frameset: _FrameSet | None) -> FrameSet | No return FrameSet(frames=frames, avg_timestamp=cpp_frameset.timestamp) def _intrinsics(self, camera_name) -> np.ndarray[tuple[Literal[3], Literal[4]], np.dtype[np.float64]]: - cam_id = mujoco.mj_name2id(self._sim.model, mujoco.mjtObj.mjOBJ_CAMERA, self.cameras[camera_name].identifier) - fovy = self._sim.model.cam_fovy[cam_id] - fx = fy = 0.5 * self.cameras[camera_name].resolution_height / np.tan(fovy * np.pi / 360) - return np.array( - [ - [fx, 0, (self.cameras[camera_name].resolution_width - 1) / 2, 0], - [0, fy, (self.cameras[camera_name].resolution_height - 1) / 2, 0], - [0, 0, 1, 0], - ] - ) + return _intrinsics(self._sim.model, self.cameras[camera_name]) def _extrinsics(self, camera_name) -> np.ndarray[tuple[Literal[4], Literal[4]], np.dtype[np.float64]]: - cam_id = mujoco.mj_name2id(self._sim.model, mujoco.mjtObj.mjOBJ_CAMERA, self.cameras[camera_name].identifier) - xpos = self._sim.data.cam_xpos[cam_id] - xmat = self._sim.data.cam_xmat[cam_id].reshape(3, 3) - - cam = common.Pose(rotation=xmat, translation=xpos) - # put z axis infront - rotation_p = common.Pose(rpy_vector=np.array([np.pi, 0, 0]), translation=np.array([0, 0, 0])) # type: ignore - cam = cam * rotation_p - - return cam.inverse().pose_matrix() + return _extrinsics(self._sim.model, self._sim.data, self.cameras[camera_name]) def calibrate(self) -> bool: return True @@ -135,3 +168,160 @@ def camera_names(self) -> list[str]: @property def name_to_identifier(self) -> dict[str, str]: return {name: cfg.identifier for name, cfg in self.cameras.items()} + + +class _ClassicDepthRenderer: + """Renders metric depth with MuJoCo's classic renderer from Python. + + Unlike ``mujoco.Renderer`` this is not limited by the model's ``offwidth``/``offheight``. + """ + + def __init__(self, model: mujoco.MjModel, width: int, height: int): + render_context_bootstrap.require("simulation depth rendering") + render_context_bootstrap.make_current() + self._model = model + self._scene = mujoco.MjvScene(model, maxgeom=2000) + self._opt = mujoco.MjvOption() + self._ctx = mujoco.MjrContext(model, mujoco.mjtFontScale.mjFONTSCALE_150) + mujoco.mjr_setBuffer(mujoco.mjtFramebuffer.mjFB_OFFSCREEN, self._ctx) + mujoco.mjr_resizeOffscreen(width, height, self._ctx) + self._viewport = mujoco.MjrRect(0, 0, width, height) + self._depth = np.empty((height, width), dtype=np.float32) + extent = model.stat.extent + self._near = model.vis.map.znear * extent + self._far = model.vis.map.zfar * extent + + def render(self, data: mujoco.MjData, camera: mujoco.MjvCamera) -> np.ndarray: + """Returns metric depth in meters as (H, W) float32, top row first.""" + render_context_bootstrap.make_current() + mujoco.mjv_updateScene(self._model, data, self._opt, None, camera, mujoco.mjtCatBit.mjCAT_ALL, self._scene) + mujoco.mjr_setBuffer(mujoco.mjtFramebuffer.mjFB_OFFSCREEN, self._ctx) + mujoco.mjr_render(self._viewport, self._scene, self._ctx) + mujoco.mjr_readPixels(None, self._depth, self._viewport, self._ctx) + # OpenGL reads bottom-up; convert the [0, 1] depth buffer to meters (see SimCameraSet) + depth = self._depth[::-1] + return self._near / (1 - depth * (1 - self._near / self._far)) + + def close(self): + self._ctx.free() + + +class FilamentSimCameraSet: + """Set of simulation cameras rendered with MuJoCo's Filament renderer (MuJoCo >= 3.15). + Implements BaseCameraSet + + Color images come from Filament. Filament does not expose a metric depth buffer through + MuJoCo's Python API, so depth images are rendered with the classic renderer; they are always + metric (scaled by ``BaseCameraSet.DEPTH_SCALE``), regardless of ``physical_units``. + + Rendering happens in Python when frames are requested, i.e. always "on demand"; rendering at a + fixed camera frame rate while the simulation steps is not supported with this backend. + """ + + def __init__( + self, + simulation: sim.Sim, + cameras: dict[str, SimCameraConfig], + physical_units: bool = True, + render_on_demand: bool = True, + max_buffer_frames: int = 100, + ): + filament.require("FilamentSimCameraSet") + if not physical_units: + logger.warning("FilamentSimCameraSet always returns metric depth; physical_units=False is ignored.") + if not render_on_demand: + logger.warning("FilamentSimCameraSet always renders on demand; render_on_demand=False is ignored.") + if max_buffer_frames <= 0: + msg = "max_buffer_frames must be positive" + raise ValueError(msg) + self._sim = simulation + self.cameras = cameras + self.physical_units = physical_units + self.render_on_demand = True + self._buffer: list[FrameSet] = [] + self._max_buffer_frames = max_buffer_frames + + self._renderer = filament.FilamentRenderer(self._sim.model) + self._mj_cameras: dict[str, mujoco.MjvCamera] = {} + for name, cfg in cameras.items(): + cam = mujoco.MjvCamera() + if cfg.type == CameraType.default_free: + mujoco.mjv_defaultFreeCamera(self._sim.model, cam) + else: + cam.type = int(cfg.type) + cam.fixedcamid = _camera_id(self._sim.model, cfg) + self._mj_cameras[name] = cam + # classic renderers for metric depth, one per resolution + self._depth_renderers: dict[tuple[int, int], _ClassicDepthRenderer] = {} + + def _depth_renderer(self, cfg: SimCameraConfig) -> _ClassicDepthRenderer: + key = (cfg.resolution_width, cfg.resolution_height) + if key not in self._depth_renderers: + self._depth_renderers[key] = _ClassicDepthRenderer(self._sim.model, *key) + return self._depth_renderers[key] + + def _render(self) -> FrameSet: + model, data = self._sim.model, self._sim.data + timestamp = data.time + self._renderer.update(data) + frames: dict[str, Frame] = {} + for name, cfg in self.cameras.items(): + color = self._renderer.render(data, self._mj_cameras[name], cfg.resolution_width, cfg.resolution_height) + depth = self._depth_renderer(cfg).render(data, self._mj_cameras[name])[..., np.newaxis] + intrinsics = _intrinsics(model, cfg) + extrinsics = _extrinsics(model, data, cfg) + frames[name] = Frame( + camera=CameraFrame( + color=DataFrame(data=color, timestamp=timestamp, intrinsics=intrinsics, extrinsics=extrinsics), + depth=DataFrame( + data=(depth * BaseCameraSet.DEPTH_SCALE).astype(np.uint16), + timestamp=timestamp, + intrinsics=intrinsics, + extrinsics=extrinsics, + ), + ), + avg_timestamp=timestamp, + ) + return FrameSet(frames=frames, avg_timestamp=timestamp) + + def buffer_size(self) -> int: + return len(self._buffer) + + def clear_buffer(self): + self._buffer.clear() + + def get_latest_frames(self) -> FrameSet | None: + """Renders all cameras for the current simulation state and returns the frames.""" + if self._buffer and self._buffer[-1].avg_timestamp == self._sim.data.time: + return self._buffer[-1] + frameset = self._render() + self._buffer.append(frameset) + del self._buffer[: -self._max_buffer_frames] + return frameset + + def get_timestamp_frames(self, ts: datetime) -> FrameSet | None: + """Returns the most recent buffered frames with a simulation time <= ts.""" + for frameset in reversed(self._buffer): + if frameset.avg_timestamp is not None and frameset.avg_timestamp <= ts.timestamp(): + return frameset + return None + + def calibrate(self) -> bool: + return True + + def config(self, camera_name: str) -> SimCameraConfig: + return self.cameras[camera_name] + + def close(self): + for renderer in self._depth_renderers.values(): + renderer.close() + self._depth_renderers.clear() + self._renderer.close() + + @property + def camera_names(self) -> list[str]: + return list(self.cameras.keys()) + + @property + def name_to_identifier(self) -> dict[str, str]: + return {name: cfg.identifier for name, cfg in self.cameras.items()} diff --git a/python/rcs/sim/__init__.py b/python/rcs/sim/__init__.py index dab8c835d..58a7b550a 100644 --- a/python/rcs/sim/__init__.py +++ b/python/rcs/sim/__init__.py @@ -1,4 +1,5 @@ from rcs._core.sim import ( + RendererBackend, SimCameraConfig, SimConfig, SimGripper, @@ -27,4 +28,5 @@ "gui_loop", "SimCameraConfig", "SimConfig", + "RendererBackend", ] diff --git a/python/rcs/sim/filament.py b/python/rcs/sim/filament.py new file mode 100644 index 000000000..cbdd1c320 --- /dev/null +++ b/python/rcs/sim/filament.py @@ -0,0 +1,235 @@ +""" +Filament rendering backend (MuJoCo >= 3.15). + +MuJoCo ships its Filament-based renderer only inside the Python extension modules +(``mujoco._render_filament`` and ``mujoco.experimental.studio``); ``libmujoco`` does not +export the ``mjrf_*`` C API. Everything Filament related therefore lives on the Python +side of RCS: + +- :class:`FilamentRenderer` renders RGB images of fixed/free MuJoCo cameras offscreen. + Filament does not expose a metric depth buffer through the Python API (its depth draw + mode is an 8-bit visualization), so depth is still produced by the classic renderer. +- :func:`gui_loop` runs MuJoCo Studio (the Filament viewer) in the RCS GUI subprocess. + Studio must own the main thread of its process and, unlike ``mujoco.viewer``, must *not* + run under ``mjpython`` on macOS. + +Enable it via ``SimConfig(renderer=RendererBackend.FILAMENT)``. + +Environment variables: + +- ``RCS_FILAMENT_GRAPHICS_API``: ``opengl`` or ``vulkan`` (default: opengl) +- ``RCS_FILAMENT_SOFTWARE_RENDERING=1``: force software rendering for offscreen cameras +- ``RCS_FILAMENT_GFX``: Studio graphics mode for the GUI, e.g. ``opengl``, ``vulkan``, ``web`` + (``web`` serves the viewer over http instead of opening a native window) +""" + +import os +import sys +import threading +from logging import getLogger +from tempfile import NamedTemporaryFile + +import mujoco +import numpy as np +from rcs._core.sim import GuiClient as _GuiClient +from rcs.utils import SimpleFrameRate + +logger = getLogger(__name__) + +# Target frames per second of the GUI loop +FPS = 60 + + +def _import_error() -> str | None: + # NOTE: do not import mujoco.experimental.studio.window here: it registers Filament resource + # providers that MuJoCo Studio registers again, which crashes the GUI process (see gui_loop) + try: + import mujoco._render_filament + import mujoco.experimental.studio # noqa: F401 + except ImportError as exc: + return repr(exc) + return None + + +def is_available() -> bool: + return _import_error() is None + + +def require(feature: str = "Filament rendering"): + error = _import_error() + if error is None: + return + msg = ( + f"{feature} requires the Filament renderer, which is shipped with the MuJoCo Python package " + f"since version 3.15 (installed: {mujoco.__version__}). Import failed with: {error}" + ) + raise RuntimeError(msg) + + +class FilamentRenderer: + """Offscreen RGB renderer for a MuJoCo model based on Filament. + + All methods must be called from the thread that created the renderer: Filament asserts + thread affinity when its engine is destroyed. + """ + + def __init__(self, model: mujoco.MjModel): + require("FilamentRenderer") + import mujoco._render_filament as mjrf # type: ignore[import-not-found] + + # importing the studio window module registers Filament's built-in assets + # (materials such as pbr.filamat); without it context creation fails. It must not be + # imported in a process that runs MuJoCo Studio (see _import_error) + import mujoco.experimental.studio.window # noqa: F401 + + self._mjrf = mjrf + self.model = model + self._ctx = mjrf.Context(self._context_config()) + self._ctx.set_clear_color(np.zeros(3, dtype=np.float32)) + self._objects = mjrf.ModelObjects(self._ctx, model) + self._scene = self._ctx.create_scene(mjrf.SceneParams()) + self._scene.configure_from_model(model) + self._lights = mjrf.ModelLights(self._scene, self._objects) + self._renderables = mjrf.ModelRenderables(self._scene, self._objects) + # one render target per resolution, created lazily + self._targets: dict[tuple[int, int], tuple[object, object, np.ndarray]] = {} + self._closed = False + + def _context_config(self): + mjrf = self._mjrf + cfg = mjrf.ContextConfig() + # OpenGL like MuJoCo's own samples; the platform default resolves to Vulkan on some systems + # (e.g. macOS) where it is not usable + cfg.graphics_api = mjrf.GraphicsApi.GRAPHICS_API_OPENGL + api = os.environ.get("RCS_FILAMENT_GRAPHICS_API", "").lower() + if api == "vulkan": + cfg.graphics_api = mjrf.GraphicsApi.GRAPHICS_API_VULKAN + elif api not in ("", "opengl"): + logger.warning("Unknown RCS_FILAMENT_GRAPHICS_API=%r, using OpenGL", api) + cfg.force_software_rendering = os.environ.get("RCS_FILAMENT_SOFTWARE_RENDERING", "") == "1" + return cfg + + def set_options(self, opt: mujoco.MjvOption): + self._renderables.set_options(opt) + + def update(self, data: mujoco.MjData): + """Syncs lights and renderables with the current simulation state.""" + self._lights.update(data) + self._renderables.update(data) + + def _target(self, width: int, height: int): + key = (width, height) + if key not in self._targets: + mjrf = self._mjrf + target = self._ctx.create_render_target( + mjrf.RenderTargetConfig(color_format=mjrf.PixelFormat.PIXEL_FORMAT_RGB8) + ) + target.resize(width, height) + buffer = np.empty((height, width, 3), dtype=np.uint8) + read = mjrf.ReadPixelsRequest() + read.target = target + read.set_buffer(buffer) + self._targets[key] = (target, read, buffer) + return self._targets[key] + + def render(self, data: mujoco.MjData, camera: mujoco.MjvCamera, width: int, height: int) -> np.ndarray: + """Renders the given camera and returns an (H, W, 3) uint8 RGB image (top row first). + + Call :meth:`update` first whenever ``data`` changed. + """ + mjrf = self._mjrf + target, read, buffer = self._target(width, height) + glcam = mujoco.mjv_camera2GLCamera(self.model, data, camera) + request = mjrf.RenderRequest( + camera=mjrf.Camera( + pos=glcam.pos, + forward=glcam.forward, + up=glcam.up, + frustum_bottom=glcam.frustum_bottom, + frustum_top=glcam.frustum_top, + frustum_near=glcam.frustum_near, + frustum_far=glcam.frustum_far, + ), + draw_mode=mjrf.DrawMode.DRAW_MODE_DEFAULT, + ) + request.scene = self._scene + request.target = target + request.viewport.left = 0 + request.viewport.bottom = 0 + request.viewport.width = width + request.viewport.height = height + # the bindings currently support only a single read request per render call + frame = self._ctx.render([request], [read]) + self._ctx.wait_for_frame(frame) + return buffer.copy() + + def close(self): + if self._closed: + return + self._closed = True + # destroy in reverse creation order; the context must outlive everything it created + self._targets.clear() + del self._renderables, self._lights, self._scene, self._objects + del self._ctx + + +def gui_executable() -> str: + """Python executable for the Filament GUI subprocess (never mjpython, see module docstring).""" + return sys.executable + + +def gui_loop(gui_uuid: str, close_event): + """Runs MuJoCo Studio for the simulation identified by ``gui_uuid``. + + Mirrors :func:`rcs.sim.sim.gui_loop`: the GUI process holds its own copy of the model and data + and synchronizes the state through the GuiClient. The viewer runs on the main thread of this + process, stepping/syncing happens on a background thread. + """ + require("The Filament GUI") + from mujoco.experimental.studio import ( + launch_native, + launch_thread, + viewer_app, + viewer_handle, + viewer_protocol, + ) + + gui_client = _GuiClient(gui_uuid) + model_bytes = gui_client.get_model_bytes() + with NamedTemporaryFile(mode="wb") as f: + f.write(model_bytes) + f.flush() + model = mujoco.MjModel.from_binary_path(f.name) + data = mujoco.MjData(model) + gui_client.set_model_and_data(model._address, data._address) + mujoco.mj_step(model, data) + + viewer_endpoint, sim_endpoint = launch_thread.make_thread_endpoints() + handle = viewer_handle.ViewerHandle(sim_endpoint) + viewer_closed = threading.Event() + + def sim_loop(): + frame_rate = SimpleFrameRate(FPS, "gui_loop") + try: + while not close_event.is_set() and not viewer_closed.is_set() and handle.is_running(): + mujoco.mj_step(model, data) + # the viewer may hand back a new model (e.g. drag and drop); we keep ours as the + # GuiClient owns the pointers to model and data + handle.sync(model, data) + gui_client.sync() + frame_rate() + finally: + handle.close() + + sim_thread = threading.Thread(target=sim_loop, daemon=True) + sim_thread.start() + try: + config = viewer_protocol.ViewerConfig(title="RCS", gfx=os.environ.get("RCS_FILAMENT_GFX", "")) + # ViewerApp provides the interactive Studio GUI (camera selection, visualization options, + # dragging bodies, ...); without it only the bare scene is rendered. The camera selection + # lives in the toolbar, which Studio hides by default ([ and ] cycle cameras regardless). + app = viewer_app.ViewerApp(viewer_app.ViewerAppConfig(show_toolbar=True)) + launch_native.run_native_viewer(config, viewer_endpoint, plugins=[app]) + finally: + viewer_closed.set() + sim_thread.join(timeout=5) diff --git a/python/rcs/sim/render_context_bootstrap.py b/python/rcs/sim/render_context_bootstrap.py index e27f2411b..ff1bb065e 100644 --- a/python/rcs/sim/render_context_bootstrap.py +++ b/python/rcs/sim/render_context_bootstrap.py @@ -95,6 +95,13 @@ def require(feature: str = "offscreen rendering"): raise RuntimeError(message) +def make_current(): + """Makes the bootstrapped GL context current on the calling thread (for rendering from Python).""" + require() + assert _state.gl_context is not None + _state.gl_context.make_current() + + def bootstrap(): if not _state.available: return diff --git a/python/rcs/sim/sim.py b/python/rcs/sim/sim.py index 4ee8b02bc..9bccf712b 100644 --- a/python/rcs/sim/sim.py +++ b/python/rcs/sim/sim.py @@ -19,7 +19,7 @@ from rcs._core.sim import DynamicJointSchema, DynamicJointState from rcs._core.sim import GuiClient as _GuiClient from rcs._core.sim import Sim as _Sim -from rcs.sim import SimConfig, render_context_bootstrap +from rcs.sim import RendererBackend, SimConfig, filament, render_context_bootstrap from rcs.sim.composer import ModelComposer from rcs.utils import SimpleFrameRate @@ -33,9 +33,19 @@ ROOT_RELATIVE_FREE_STATE_ENCODING = "root_relative_free" -def configure_viewer_mp_context(ctx: "mp.context.SpawnContext") -> None: - """On macOS the passive MuJoCo viewer must run under ``mjpython``.""" +def configure_viewer_mp_context( + ctx: "mp.context.SpawnContext", renderer: RendererBackend = RendererBackend.CLASSIC +) -> None: + """Selects the interpreter of the GUI subprocess. + + On macOS the passive MuJoCo viewer must run under ``mjpython``, whereas MuJoCo Studio (Filament) must + run under a regular ``python`` as it owns the main thread itself. + """ + if renderer == RendererBackend.FILAMENT: + ctx.set_executable(filament.gui_executable()) + return if sys.platform != "darwin": + ctx.set_executable(sys.executable) return mjpython = shutil.which("mjpython") if mjpython is None: @@ -79,7 +89,6 @@ def __init__(self, mjmdl: str | PathLike | ModelComposer, cfg: SimConfig | None self.data = mj.MjData(self.model) super().__init__(self.model._address, self.data._address) self._mp_context = mp.get_context("spawn") - configure_viewer_mp_context(self._mp_context) self._gui_uuid: Optional[str] = None self._gui_client: Optional[_GuiClient] = None self._gui_process: Optional[mp.context.SpawnProcess] = None @@ -250,13 +259,22 @@ def close_gui(self): self._gui_atexit_registered = False def open_gui(self): + """Opens the viewer in a subprocess. + + Uses the passive ``mujoco.viewer`` or, with ``SimConfig(renderer=RendererBackend.FILAMENT)``, + MuJoCo Studio (Filament). + """ + renderer = self.get_config().renderer + if renderer == RendererBackend.FILAMENT: + filament.require("The Filament GUI") if self._gui_uuid is None: self._gui_uuid = "rcs_" + str(uuid.uuid4()) self._start_gui_server(self._gui_uuid) if self._gui_process is None or not self._gui_process.is_alive(): + configure_viewer_mp_context(self._mp_context, renderer) self._stop_event = self._mp_context.Event() self._gui_process = self._mp_context.Process( - target=gui_loop, + target=filament.gui_loop if renderer == RendererBackend.FILAMENT else gui_loop, args=(self._gui_uuid, self._stop_event), daemon=True, ) diff --git a/python/tests/test_filament.py b/python/tests/test_filament.py new file mode 100644 index 000000000..7ce69f1f7 --- /dev/null +++ b/python/tests/test_filament.py @@ -0,0 +1,60 @@ +import numpy as np +import pytest +from rcs.camera.sim import FilamentSimCameraSet, SimCameraSet +from rcs.envs.configs import EmptyWorldFR3 +from rcs.sim import RendererBackend, SimConfig, filament + +from rcs import sim + +pytestmark = pytest.mark.skipif(not filament.is_available(), reason="Filament renderer requires mujoco >= 3.15") + + +@pytest.fixture() +def fr3_sim(): + scene = EmptyWorldFR3() + cfg = scene.prefixed_cfg(scene.config()) + simulation = sim.Sim(scene.create_model(cfg), SimConfig(renderer=RendererBackend.FILAMENT)) + return simulation, cfg + + +def test_sim_camera_set_dispatches_to_filament(fr3_sim): + simulation, cfg = fr3_sim + camera_set = SimCameraSet(simulation, cfg.camera_cfgs, physical_units=True) + assert isinstance(camera_set, FilamentSimCameraSet) + assert camera_set.camera_names == list(cfg.camera_cfgs.keys()) + camera_set.close() + + +def test_filament_camera_set_renders_rgb_and_metric_depth(fr3_sim): + simulation, cfg = fr3_sim + camera_set = FilamentSimCameraSet(simulation, cfg.camera_cfgs) + try: + simulation.step(1) + frameset = camera_set.get_latest_frames() + assert frameset is not None + assert frameset.frames.keys() == cfg.camera_cfgs.keys() + for name, frame in frameset.frames.items(): + cam_cfg = cfg.camera_cfgs[name] + assert frame.camera.depth is not None + color = frame.camera.color.data + depth = frame.camera.depth.data + assert color.shape == (cam_cfg.resolution_height, cam_cfg.resolution_width, 3) + assert color.dtype == np.uint8 + # the scene is lit and textured, so the image must not be uniform + assert color.std() > 1 + assert depth.shape == (cam_cfg.resolution_height, cam_cfg.resolution_width, 1) + assert depth.dtype == np.uint16 + # metric depth in millimeters: the cameras look at the robot/floor within a few meters + assert 10 < np.median(depth) < 10_000 + assert frame.camera.color.intrinsics is not None + assert frame.camera.color.extrinsics is not None + assert frame.camera.color.intrinsics.shape == (3, 4) + assert frame.camera.color.extrinsics.shape == (4, 4) + + # the same simulation time returns the buffered frames, a new step renders again + assert camera_set.get_latest_frames() is frameset + simulation.step(1) + assert camera_set.get_latest_frames() is not frameset + assert camera_set.buffer_size() == 2 + finally: + camera_set.close() diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 307137ff5..ee731bfe4 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -720,27 +720,36 @@ PYBIND11_MODULE(_core, m) { .def_readonly("last_width", &rcs::sim::SimGripperState::last_width) .def_readonly("collision", &rcs::sim::SimGripperState::collision); + py::enum_(sim, "RendererBackend") + .value("CLASSIC", rcs::sim::RendererBackend::CLASSIC) + .value("FILAMENT", rcs::sim::RendererBackend::FILAMENT) + .export_values(); + rcs::sim::SimConfig default_sim_cfg = rcs::sim::SimConfig(); py::class_(sim, "SimConfig") .def(py::init([](bool async_control, bool realtime, double frequency, - int max_convergence_steps) { + int max_convergence_steps, + rcs::sim::RendererBackend renderer) { rcs::sim::SimConfig config; config.async_control = async_control; config.realtime = realtime; config.frequency = frequency; config.max_convergence_steps = max_convergence_steps; + config.renderer = renderer; return config; }), py::arg("async_control") = default_sim_cfg.async_control, py::arg("realtime") = default_sim_cfg.realtime, py::arg("frequency") = default_sim_cfg.frequency, py::arg("max_convergence_steps") = - default_sim_cfg.max_convergence_steps) + default_sim_cfg.max_convergence_steps, + py::arg("renderer") = default_sim_cfg.renderer) .def_readwrite("async_control", &rcs::sim::SimConfig::async_control) .def_readwrite("realtime", &rcs::sim::SimConfig::realtime) .def_readwrite("frequency", &rcs::sim::SimConfig::frequency) .def_readwrite("max_convergence_steps", &rcs::sim::SimConfig::max_convergence_steps) + .def_readwrite("renderer", &rcs::sim::SimConfig::renderer) .def("__copy__", [](const rcs::sim::SimConfig& self) { return rcs::sim::SimConfig(self); diff --git a/src/sim/sim.h b/src/sim/sim.h index 6cae264c0..fa8d8a87c 100644 --- a/src/sim/sim.h +++ b/src/sim/sim.h @@ -29,11 +29,15 @@ class Renderer { std::unordered_map ctxs; }; +// Filament renderer is implemented in python +enum class RendererBackend { CLASSIC, FILAMENT }; + struct SimConfig { bool async_control = false; bool realtime = false; double frequency = 30; // in Hz int max_convergence_steps = 500; + RendererBackend renderer = RendererBackend::CLASSIC; }; struct Callback { From 1b61622740dc221f78394cb3845da17b874a915c Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Tue, 6 Oct 2026 17:40:26 -0700 Subject: [PATCH 03/16] perf(sim): filament render does not render depth if not requested to be faster --- docs/user_guide/scene_configuration.md | 4 +++- python/rcs/camera/sim.py | 25 +++++++++++++------- python/rcs/envs/base.py | 3 +++ python/tests/test_filament.py | 32 ++++++++++++++++++++++++++ 4 files changed, 55 insertions(+), 9 deletions(-) diff --git a/docs/user_guide/scene_configuration.md b/docs/user_guide/scene_configuration.md index 889c3eba0..19b8ffc3d 100644 --- a/docs/user_guide/scene_configuration.md +++ b/docs/user_guide/scene_configuration.md @@ -316,7 +316,9 @@ With this flag - `SimCameraSet(...)` returns a `FilamentSimCameraSet`: color images are rendered with Filament in Python (frames are rendered when requested, a fixed camera frame rate is not supported). Filament does not expose a metric depth buffer through MuJoCo's Python API, so depth images are still rendered with - the classic renderer and always use the metric units described above. + the classic renderer and always use the metric units described above. The depth pass costs about as + much as the whole classic renderer, so it is skipped when `CameraSetWrapper(include_depth=False)` + (or `FilamentSimCameraSet(render_depth=False)`) is used. - `open_gui()` launches MuJoCo Studio instead of the passive `mujoco.viewer`. Studio runs in the GUI subprocess under a regular `python` interpreter (not `mjpython`, also on macOS). diff --git a/python/rcs/camera/sim.py b/python/rcs/camera/sim.py index 815fbac88..518b4f991 100644 --- a/python/rcs/camera/sim.py +++ b/python/rcs/camera/sim.py @@ -212,12 +212,16 @@ class FilamentSimCameraSet: Color images come from Filament. Filament does not expose a metric depth buffer through MuJoCo's Python API, so depth images are rendered with the classic renderer; they are always - metric (scaled by ``BaseCameraSet.DEPTH_SCALE``), regardless of ``physical_units``. + metric (scaled by ``BaseCameraSet.DEPTH_SCALE``), regardless of ``physical_units``. The depth + pass costs about as much as the classic renderer, set ``render_depth=False`` (done automatically + by ``CameraSetWrapper(include_depth=False)``) to skip it; frames then have ``depth=None``. Rendering happens in Python when frames are requested, i.e. always "on demand"; rendering at a fixed camera frame rate while the simulation steps is not supported with this backend. """ + DEPTH_SCALE: int = BaseCameraSet.DEPTH_SCALE + def __init__( self, simulation: sim.Sim, @@ -225,6 +229,7 @@ def __init__( physical_units: bool = True, render_on_demand: bool = True, max_buffer_frames: int = 100, + render_depth: bool = True, ): filament.require("FilamentSimCameraSet") if not physical_units: @@ -238,6 +243,7 @@ def __init__( self.cameras = cameras self.physical_units = physical_units self.render_on_demand = True + self.render_depth = render_depth self._buffer: list[FrameSet] = [] self._max_buffer_frames = max_buffer_frames @@ -267,18 +273,21 @@ def _render(self) -> FrameSet: frames: dict[str, Frame] = {} for name, cfg in self.cameras.items(): color = self._renderer.render(data, self._mj_cameras[name], cfg.resolution_width, cfg.resolution_height) - depth = self._depth_renderer(cfg).render(data, self._mj_cameras[name])[..., np.newaxis] intrinsics = _intrinsics(model, cfg) extrinsics = _extrinsics(model, data, cfg) + depth_frame = None + if self.render_depth: + depth = self._depth_renderer(cfg).render(data, self._mj_cameras[name])[..., np.newaxis] + depth_frame = DataFrame( + data=(depth * BaseCameraSet.DEPTH_SCALE).astype(np.uint16), + timestamp=timestamp, + intrinsics=intrinsics, + extrinsics=extrinsics, + ) frames[name] = Frame( camera=CameraFrame( color=DataFrame(data=color, timestamp=timestamp, intrinsics=intrinsics, extrinsics=extrinsics), - depth=DataFrame( - data=(depth * BaseCameraSet.DEPTH_SCALE).astype(np.uint16), - timestamp=timestamp, - intrinsics=intrinsics, - extrinsics=extrinsics, - ), + depth=depth_frame, ), avg_timestamp=timestamp, ) diff --git a/python/rcs/envs/base.py b/python/rcs/envs/base.py index 0d1b62615..f82a812b7 100644 --- a/python/rcs/envs/base.py +++ b/python/rcs/envs/base.py @@ -961,6 +961,9 @@ def __init__(self, env, camera_set: BaseCameraSet, include_depth: bool = False): super().__init__(env) self.camera_set = camera_set self.include_depth = include_depth + # camera sets that render depth separately (e.g. FilamentSimCameraSet) can skip it if not requested + if hasattr(camera_set, "render_depth"): + camera_set.render_depth = include_depth self.observation_space: gym.spaces.Dict # rgb is always included diff --git a/python/tests/test_filament.py b/python/tests/test_filament.py index 7ce69f1f7..369646ae7 100644 --- a/python/tests/test_filament.py +++ b/python/tests/test_filament.py @@ -1,6 +1,8 @@ +import gymnasium as gym import numpy as np import pytest from rcs.camera.sim import FilamentSimCameraSet, SimCameraSet +from rcs.envs.base import CameraSetWrapper from rcs.envs.configs import EmptyWorldFR3 from rcs.sim import RendererBackend, SimConfig, filament @@ -58,3 +60,33 @@ def test_filament_camera_set_renders_rgb_and_metric_depth(fr3_sim): assert camera_set.buffer_size() == 2 finally: camera_set.close() + + +def test_filament_camera_set_skips_depth_when_not_requested(fr3_sim): + simulation, cfg = fr3_sim + camera_set = FilamentSimCameraSet(simulation, cfg.camera_cfgs, render_depth=False) + try: + simulation.step(1) + frameset = camera_set.get_latest_frames() + assert frameset is not None + assert all(frame.camera.depth is None for frame in frameset.frames.values()) + assert all(frame.camera.color.data.dtype == np.uint8 for frame in frameset.frames.values()) + finally: + camera_set.close() + + +class _EmptyObsEnv(gym.Env): + observation_space = gym.spaces.Dict({}) + action_space = gym.spaces.Dict({}) + + +def test_camera_set_wrapper_configures_depth_rendering(fr3_sim): + simulation, cfg = fr3_sim + camera_set = FilamentSimCameraSet(simulation, cfg.camera_cfgs) + try: + CameraSetWrapper(_EmptyObsEnv(), camera_set, include_depth=False) + assert camera_set.render_depth is False + CameraSetWrapper(_EmptyObsEnv(), camera_set, include_depth=True) + assert camera_set.render_depth is True + finally: + camera_set.close() From 5f0820fee956352daf848da09eeca7aecb89c137 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 13 Nov 2026 10:28:38 -0800 Subject: [PATCH 04/16] fix(stubs): regenerate sim stubs to match stubgen ordering --- python/rcs/_core/sim.pyi | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/python/rcs/_core/sim.pyi b/python/rcs/_core/sim.pyi index 8aaf44304..02623105b 100644 --- a/python/rcs/_core/sim.pyi +++ b/python/rcs/_core/sim.pyi @@ -10,9 +10,11 @@ import numpy import rcs._core.common __all__: list[str] = [ + "CLASSIC", "CameraType", "DynamicJointSchema", "DynamicJointState", + "FILAMENT", "FrameSet", "GuiClient", "RendererBackend", @@ -29,8 +31,6 @@ __all__: list[str] = [ "SimTilburgHand", "SimTilburgHandConfig", "SimTilburgHandState", - "CLASSIC", - "FILAMENT", "default_free", "fixed", "free", @@ -417,9 +417,9 @@ class SimTilburgHandState(rcs._core.common.HandState): @property def last_qpos(self) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]: ... +CLASSIC: RendererBackend # value = +FILAMENT: RendererBackend # value = default_free: CameraType # value = fixed: CameraType # value = free: CameraType # value = tracking: CameraType # value = -CLASSIC: RendererBackend # value = -FILAMENT: RendererBackend # value = From c6811559188e5d789dfcf861f4ccec8564cf1995 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 13 Nov 2026 11:14:09 -0800 Subject: [PATCH 05/16] build(deps): bump mujoco to 4.0.1 Filament moved out of mujoco.experimental in 4.0 and some mjrf bindings were renamed (ModelObjects -> ModelResources, ReadPixelsRequest -> ReadRequest, force_software_rendering -> software_rendering). Studio's ViewerApp became mujoco.studio.app.App. Importing studio.window to register Filament assets is no longer needed. The Filament tests now only skip on mujoco < 4 and fail if the import breaks, so a moved module can no longer silently skip them. --- docker/Dockerfile | 2 +- docs/user_guide/scene_configuration.md | 2 +- pyproject.toml | 8 ++--- python/rcs/camera/sim.py | 2 +- python/rcs/sim/filament.py | 42 +++++++++++--------------- python/tests/test_filament.py | 11 ++++++- 6 files changed, 34 insertions(+), 33 deletions(-) diff --git a/docker/Dockerfile b/docker/Dockerfile index db9d23c03..161e0cc8f 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -48,7 +48,7 @@ RUN chmod +x /usr/local/bin/link-editable-source \ pybind11 \ cmake \ ninja \ - "mujoco==3.15.0" \ + "mujoco==4.0.1" \ "pin==3.7.0" \ && uv pip install /opt/rcs-src \ && uv pip install --no-build-isolation /opt/rcs-src/extensions/rcs_fr3 \ diff --git a/docs/user_guide/scene_configuration.md b/docs/user_guide/scene_configuration.md index 19b8ffc3d..1d5fdcc4f 100644 --- a/docs/user_guide/scene_configuration.md +++ b/docs/user_guide/scene_configuration.md @@ -301,7 +301,7 @@ Example: ## Rendering backend (Filament) -By default, simulation cameras and the GUI use MuJoCo's classic OpenGL renderer. MuJoCo >= 3.15 also +By default, simulation cameras and the GUI use MuJoCo's classic OpenGL renderer. MuJoCo >= 4.0 also ships the physically based [Filament](https://github.com/google/filament) renderer and the new MuJoCo Studio viewer. Switch to them with the `renderer` flag of `SimConfig`: diff --git a/pyproject.toml b/pyproject.toml index 7b601821c..9af1e7f8b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,7 +7,7 @@ requires = [ "pybind11", "cmake", "ninja", - "mujoco==3.15.0", + "mujoco==4.0.1", "pin==3.7.0", ] build-backend = "scikit_build_core.build" @@ -36,7 +36,7 @@ dependencies = [ "rpyc~=6.0.2", "pyarrow", "simplejpeg", - "mujoco==3.15.0", + "mujoco==4.0.1", "pin==3.7.0", # pin 3.7.0 currently resolves against older urdfdom/tinyxml SONAMEs at runtime "cmeel-urdfdom<5", @@ -76,7 +76,7 @@ dev = [ "twine~=6.0", ] build_deps = [ - "mujoco==3.15.0", + "mujoco==4.0.1", "pin==3.7.0", "cmeel-urdfdom<5", "cmeel-tinyxml2<11", @@ -93,7 +93,7 @@ environment = { SKBUILD_BUILD_DIR = "/tmp/rcs-build/{wheel_tag}" } archs = ["x86_64"] manylinux-x86_64-image = "manylinux_2_28" before-all = "yum install -y epel-release && yum install -y libXi-devel libXcursor-devel libXinerama-devel libXrandr-devel glfw-devel" -repair-wheel-command = "auditwheel repair -w {dest_dir} {wheel} --exclude libmujoco.so.3.15.0 --exclude libpinocchio_default.so.3.7.0 --exclude libpinocchio_parsers.so.3.7.0" +repair-wheel-command = "auditwheel repair -w {dest_dir} {wheel} --exclude libmujoco.so.4.0.1 --exclude libpinocchio_default.so.3.7.0 --exclude libpinocchio_parsers.so.3.7.0" [tool.cibuildwheel.macos] archs = ["arm64"] diff --git a/python/rcs/camera/sim.py b/python/rcs/camera/sim.py index 518b4f991..910838f3b 100644 --- a/python/rcs/camera/sim.py +++ b/python/rcs/camera/sim.py @@ -207,7 +207,7 @@ def close(self): class FilamentSimCameraSet: - """Set of simulation cameras rendered with MuJoCo's Filament renderer (MuJoCo >= 3.15). + """Set of simulation cameras rendered with MuJoCo's Filament renderer (MuJoCo >= 4.0). Implements BaseCameraSet Color images come from Filament. Filament does not expose a metric depth buffer through diff --git a/python/rcs/sim/filament.py b/python/rcs/sim/filament.py index cbdd1c320..442bbcdf6 100644 --- a/python/rcs/sim/filament.py +++ b/python/rcs/sim/filament.py @@ -1,10 +1,9 @@ """ -Filament rendering backend (MuJoCo >= 3.15). +Filament rendering backend (MuJoCo >= 4.0). -MuJoCo ships its Filament-based renderer only inside the Python extension modules -(``mujoco._render_filament`` and ``mujoco.experimental.studio``); ``libmujoco`` does not -export the ``mjrf_*`` C API. Everything Filament related therefore lives on the Python -side of RCS: +MuJoCo ships its Filament-based renderer only inside the ``mujoco-studio`` Python package +(``mujoco.mjrf`` and ``mujoco.studio``); ``libmujoco`` does not export the ``mjrf_*`` C API. +Everything Filament related therefore lives on the Python side of RCS: - :class:`FilamentRenderer` renders RGB images of fixed/free MuJoCo cameras offscreen. Filament does not expose a metric depth buffer through the Python API (its depth draw @@ -41,11 +40,9 @@ def _import_error() -> str | None: - # NOTE: do not import mujoco.experimental.studio.window here: it registers Filament resource - # providers that MuJoCo Studio registers again, which crashes the GUI process (see gui_loop) try: - import mujoco._render_filament - import mujoco.experimental.studio # noqa: F401 + import mujoco.studio # noqa: F401 + from mujoco import mjrf # noqa: F401 except ImportError as exc: return repr(exc) return None @@ -61,7 +58,7 @@ def require(feature: str = "Filament rendering"): return msg = ( f"{feature} requires the Filament renderer, which is shipped with the MuJoCo Python package " - f"since version 3.15 (installed: {mujoco.__version__}). Import failed with: {error}" + f"(mujoco-studio) since version 4.0 (installed: {mujoco.__version__}). Import failed with: {error}" ) raise RuntimeError(msg) @@ -75,18 +72,13 @@ class FilamentRenderer: def __init__(self, model: mujoco.MjModel): require("FilamentRenderer") - import mujoco._render_filament as mjrf # type: ignore[import-not-found] - - # importing the studio window module registers Filament's built-in assets - # (materials such as pbr.filamat); without it context creation fails. It must not be - # imported in a process that runs MuJoCo Studio (see _import_error) - import mujoco.experimental.studio.window # noqa: F401 + from mujoco import mjrf self._mjrf = mjrf self.model = model self._ctx = mjrf.Context(self._context_config()) self._ctx.set_clear_color(np.zeros(3, dtype=np.float32)) - self._objects = mjrf.ModelObjects(self._ctx, model) + self._objects = mjrf.ModelResources(self._ctx, model) self._scene = self._ctx.create_scene(mjrf.SceneParams()) self._scene.configure_from_model(model) self._lights = mjrf.ModelLights(self._scene, self._objects) @@ -106,7 +98,7 @@ def _context_config(self): cfg.graphics_api = mjrf.GraphicsApi.GRAPHICS_API_VULKAN elif api not in ("", "opengl"): logger.warning("Unknown RCS_FILAMENT_GRAPHICS_API=%r, using OpenGL", api) - cfg.force_software_rendering = os.environ.get("RCS_FILAMENT_SOFTWARE_RENDERING", "") == "1" + cfg.software_rendering = os.environ.get("RCS_FILAMENT_SOFTWARE_RENDERING", "") == "1" return cfg def set_options(self, opt: mujoco.MjvOption): @@ -126,8 +118,7 @@ def _target(self, width: int, height: int): ) target.resize(width, height) buffer = np.empty((height, width, 3), dtype=np.uint8) - read = mjrf.ReadPixelsRequest() - read.target = target + read = mjrf.ReadRequest(target=target) read.set_buffer(buffer) self._targets[key] = (target, read, buffer) return self._targets[key] @@ -158,7 +149,7 @@ def render(self, data: mujoco.MjData, camera: mujoco.MjvCamera, width: int, heig request.viewport.bottom = 0 request.viewport.width = width request.viewport.height = height - # the bindings currently support only a single read request per render call + # the bindings still support only a single read request per render call (MuJoCo 4.0.1) frame = self._ctx.render([request], [read]) self._ctx.wait_for_frame(frame) return buffer.copy() @@ -186,10 +177,10 @@ def gui_loop(gui_uuid: str, close_event): process, stepping/syncing happens on a background thread. """ require("The Filament GUI") - from mujoco.experimental.studio import ( + from mujoco.studio import app as studio_app + from mujoco.studio import ( launch_native, launch_thread, - viewer_app, viewer_handle, viewer_protocol, ) @@ -225,10 +216,11 @@ def sim_loop(): sim_thread.start() try: config = viewer_protocol.ViewerConfig(title="RCS", gfx=os.environ.get("RCS_FILAMENT_GFX", "")) - # ViewerApp provides the interactive Studio GUI (camera selection, visualization options, + # App provides the interactive Studio GUI (camera selection, visualization options, # dragging bodies, ...); without it only the bare scene is rendered. The camera selection # lives in the toolbar, which Studio hides by default ([ and ] cycle cameras regardless). - app = viewer_app.ViewerApp(viewer_app.ViewerAppConfig(show_toolbar=True)) + # Studio's SIM_PLUGINS (step control, history) are not used: sim_loop steps and paces itself. + app = studio_app.App(studio_app.Config(show_toolbar=True)) launch_native.run_native_viewer(config, viewer_endpoint, plugins=[app]) finally: viewer_closed.set() diff --git a/python/tests/test_filament.py b/python/tests/test_filament.py index 369646ae7..a014b5ce7 100644 --- a/python/tests/test_filament.py +++ b/python/tests/test_filament.py @@ -1,4 +1,5 @@ import gymnasium as gym +import mujoco import numpy as np import pytest from rcs.camera.sim import FilamentSimCameraSet, SimCameraSet @@ -8,7 +9,15 @@ from rcs import sim -pytestmark = pytest.mark.skipif(not filament.is_available(), reason="Filament renderer requires mujoco >= 3.15") +# Filament ships with mujoco >= 4.0 (mujoco-studio). Only skip on older versions: if the import breaks on +# a supported version (e.g. a moved module), the tests must fail instead of being skipped silently. +pytestmark = pytest.mark.skipif( + int(mujoco.__version__.split(".")[0]) < 4, reason="Filament renderer requires mujoco >= 4.0" +) + + +def test_filament_is_available(): + assert filament.is_available(), filament._import_error() @pytest.fixture() From 7ab522d376e7afb69193434388619873949bfe04 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 13 Nov 2026 11:14:37 -0800 Subject: [PATCH 06/16] feat(sim): render metric depth with filament MuJoCo 4.0 renders Filament's depth draw mode without post processing, so reading it into an R32F target gives reversed-z values that convert to metric depth like the classic depth buffer. This replaces the extra classic OpenGL depth pass of FilamentSimCameraSet and removes the now unused _ClassicDepthRenderer. --- docs/user_guide/scene_configuration.md | 11 +++-- python/rcs/camera/sim.py | 60 +++----------------------- python/rcs/sim/filament.py | 44 +++++++++++++------ 3 files changed, 42 insertions(+), 73 deletions(-) diff --git a/docs/user_guide/scene_configuration.md b/docs/user_guide/scene_configuration.md index 1d5fdcc4f..cd207bf1d 100644 --- a/docs/user_guide/scene_configuration.md +++ b/docs/user_guide/scene_configuration.md @@ -313,12 +313,11 @@ sim_cfg = SimConfig(async_control=False, realtime=False, renderer=RendererBacken With this flag -- `SimCameraSet(...)` returns a `FilamentSimCameraSet`: color images are rendered with Filament in - Python (frames are rendered when requested, a fixed camera frame rate is not supported). Filament does - not expose a metric depth buffer through MuJoCo's Python API, so depth images are still rendered with - the classic renderer and always use the metric units described above. The depth pass costs about as - much as the whole classic renderer, so it is skipped when `CameraSetWrapper(include_depth=False)` - (or `FilamentSimCameraSet(render_depth=False)`) is used. +- `SimCameraSet(...)` returns a `FilamentSimCameraSet`: color and depth images are rendered with Filament + in Python (frames are rendered when requested, a fixed camera frame rate is not supported). Depth images + always use the metric units described above. The depth pass is a second Filament render per camera, so + it is skipped when `CameraSetWrapper(include_depth=False)` (or `FilamentSimCameraSet(render_depth=False)`) + is used. - `open_gui()` launches MuJoCo Studio instead of the passive `mujoco.viewer`. Studio runs in the GUI subprocess under a regular `python` interpreter (not `mjpython`, also on macOS). diff --git a/python/rcs/camera/sim.py b/python/rcs/camera/sim.py index 910838f3b..a9a784261 100644 --- a/python/rcs/camera/sim.py +++ b/python/rcs/camera/sim.py @@ -170,51 +170,14 @@ def name_to_identifier(self) -> dict[str, str]: return {name: cfg.identifier for name, cfg in self.cameras.items()} -class _ClassicDepthRenderer: - """Renders metric depth with MuJoCo's classic renderer from Python. - - Unlike ``mujoco.Renderer`` this is not limited by the model's ``offwidth``/``offheight``. - """ - - def __init__(self, model: mujoco.MjModel, width: int, height: int): - render_context_bootstrap.require("simulation depth rendering") - render_context_bootstrap.make_current() - self._model = model - self._scene = mujoco.MjvScene(model, maxgeom=2000) - self._opt = mujoco.MjvOption() - self._ctx = mujoco.MjrContext(model, mujoco.mjtFontScale.mjFONTSCALE_150) - mujoco.mjr_setBuffer(mujoco.mjtFramebuffer.mjFB_OFFSCREEN, self._ctx) - mujoco.mjr_resizeOffscreen(width, height, self._ctx) - self._viewport = mujoco.MjrRect(0, 0, width, height) - self._depth = np.empty((height, width), dtype=np.float32) - extent = model.stat.extent - self._near = model.vis.map.znear * extent - self._far = model.vis.map.zfar * extent - - def render(self, data: mujoco.MjData, camera: mujoco.MjvCamera) -> np.ndarray: - """Returns metric depth in meters as (H, W) float32, top row first.""" - render_context_bootstrap.make_current() - mujoco.mjv_updateScene(self._model, data, self._opt, None, camera, mujoco.mjtCatBit.mjCAT_ALL, self._scene) - mujoco.mjr_setBuffer(mujoco.mjtFramebuffer.mjFB_OFFSCREEN, self._ctx) - mujoco.mjr_render(self._viewport, self._scene, self._ctx) - mujoco.mjr_readPixels(None, self._depth, self._viewport, self._ctx) - # OpenGL reads bottom-up; convert the [0, 1] depth buffer to meters (see SimCameraSet) - depth = self._depth[::-1] - return self._near / (1 - depth * (1 - self._near / self._far)) - - def close(self): - self._ctx.free() - - class FilamentSimCameraSet: """Set of simulation cameras rendered with MuJoCo's Filament renderer (MuJoCo >= 4.0). Implements BaseCameraSet - Color images come from Filament. Filament does not expose a metric depth buffer through - MuJoCo's Python API, so depth images are rendered with the classic renderer; they are always - metric (scaled by ``BaseCameraSet.DEPTH_SCALE``), regardless of ``physical_units``. The depth - pass costs about as much as the classic renderer, set ``render_depth=False`` (done automatically - by ``CameraSetWrapper(include_depth=False)``) to skip it; frames then have ``depth=None``. + Color and depth images come from Filament. Depth images are always metric (scaled by + ``BaseCameraSet.DEPTH_SCALE``), regardless of ``physical_units``. The depth pass is a second + Filament render per camera, set ``render_depth=False`` (done automatically by + ``CameraSetWrapper(include_depth=False)``) to skip it; frames then have ``depth=None``. Rendering happens in Python when frames are requested, i.e. always "on demand"; rendering at a fixed camera frame rate while the simulation steps is not supported with this backend. @@ -257,14 +220,6 @@ def __init__( cam.type = int(cfg.type) cam.fixedcamid = _camera_id(self._sim.model, cfg) self._mj_cameras[name] = cam - # classic renderers for metric depth, one per resolution - self._depth_renderers: dict[tuple[int, int], _ClassicDepthRenderer] = {} - - def _depth_renderer(self, cfg: SimCameraConfig) -> _ClassicDepthRenderer: - key = (cfg.resolution_width, cfg.resolution_height) - if key not in self._depth_renderers: - self._depth_renderers[key] = _ClassicDepthRenderer(self._sim.model, *key) - return self._depth_renderers[key] def _render(self) -> FrameSet: model, data = self._sim.model, self._sim.data @@ -277,7 +232,9 @@ def _render(self) -> FrameSet: extrinsics = _extrinsics(model, data, cfg) depth_frame = None if self.render_depth: - depth = self._depth_renderer(cfg).render(data, self._mj_cameras[name])[..., np.newaxis] + depth = self._renderer.render_depth( + data, self._mj_cameras[name], cfg.resolution_width, cfg.resolution_height + )[..., np.newaxis] depth_frame = DataFrame( data=(depth * BaseCameraSet.DEPTH_SCALE).astype(np.uint16), timestamp=timestamp, @@ -322,9 +279,6 @@ def config(self, camera_name: str) -> SimCameraConfig: return self.cameras[camera_name] def close(self): - for renderer in self._depth_renderers.values(): - renderer.close() - self._depth_renderers.clear() self._renderer.close() @property diff --git a/python/rcs/sim/filament.py b/python/rcs/sim/filament.py index 442bbcdf6..86ee5aeb1 100644 --- a/python/rcs/sim/filament.py +++ b/python/rcs/sim/filament.py @@ -5,9 +5,8 @@ (``mujoco.mjrf`` and ``mujoco.studio``); ``libmujoco`` does not export the ``mjrf_*`` C API. Everything Filament related therefore lives on the Python side of RCS: -- :class:`FilamentRenderer` renders RGB images of fixed/free MuJoCo cameras offscreen. - Filament does not expose a metric depth buffer through the Python API (its depth draw - mode is an 8-bit visualization), so depth is still produced by the classic renderer. +- :class:`FilamentRenderer` renders RGB images and metric depth of fixed/free MuJoCo cameras + offscreen. Depth comes from Filament's depth draw mode read back into a float target. - :func:`gui_loop` runs MuJoCo Studio (the Filament viewer) in the RCS GUI subprocess. Studio must own the main thread of its process and, unlike ``mujoco.viewer``, must *not* run under ``mjpython`` on macOS. @@ -83,8 +82,11 @@ def __init__(self, model: mujoco.MjModel): self._scene.configure_from_model(model) self._lights = mjrf.ModelLights(self._scene, self._objects) self._renderables = mjrf.ModelRenderables(self._scene, self._objects) - # one render target per resolution, created lazily - self._targets: dict[tuple[int, int], tuple[object, object, np.ndarray]] = {} + # one render target per (resolution, kind), created lazily + self._targets: dict[tuple[int, int, str], tuple[object, object, np.ndarray]] = {} + extent = model.stat.extent + self._near = model.vis.map.znear * extent + self._far = model.vis.map.zfar * extent self._closed = False def _context_config(self): @@ -109,15 +111,16 @@ def update(self, data: mujoco.MjData): self._lights.update(data) self._renderables.update(data) - def _target(self, width: int, height: int): - key = (width, height) + def _target(self, width: int, height: int, kind: str = "rgb"): + key = (width, height, kind) if key not in self._targets: mjrf = self._mjrf - target = self._ctx.create_render_target( - mjrf.RenderTargetConfig(color_format=mjrf.PixelFormat.PIXEL_FORMAT_RGB8) - ) + if kind == "rgb": + fmt, buffer = mjrf.PixelFormat.PIXEL_FORMAT_RGB8, np.empty((height, width, 3), dtype=np.uint8) + else: + fmt, buffer = mjrf.PixelFormat.PIXEL_FORMAT_R32F, np.empty((height, width), dtype=np.float32) + target = self._ctx.create_render_target(mjrf.RenderTargetConfig(color_format=fmt)) target.resize(width, height) - buffer = np.empty((height, width, 3), dtype=np.uint8) read = mjrf.ReadRequest(target=target) read.set_buffer(buffer) self._targets[key] = (target, read, buffer) @@ -128,8 +131,21 @@ def render(self, data: mujoco.MjData, camera: mujoco.MjvCamera, width: int, heig Call :meth:`update` first whenever ``data`` changed. """ + return self._render(data, camera, width, height, "rgb").copy() + + def render_depth(self, data: mujoco.MjData, camera: mujoco.MjvCamera, width: int, height: int) -> np.ndarray: + """Renders the given camera and returns metric depth in meters as (H, W) float32 (top row first). + + Call :meth:`update` first whenever ``data`` changed. + """ + depth = self._render(data, camera, width, height, "depth") + # Filament's depth draw mode writes reversed-z (1 at znear, 0 at zfar) without post processing + # (MuJoCo >= 4.0); convert like the classic renderer's [0, 1] depth buffer + return self._near / (1 - (1 - depth) * (1 - self._near / self._far)) + + def _render(self, data: mujoco.MjData, camera: mujoco.MjvCamera, width: int, height: int, kind: str): mjrf = self._mjrf - target, read, buffer = self._target(width, height) + target, read, buffer = self._target(width, height, kind) glcam = mujoco.mjv_camera2GLCamera(self.model, data, camera) request = mjrf.RenderRequest( camera=mjrf.Camera( @@ -141,7 +157,7 @@ def render(self, data: mujoco.MjData, camera: mujoco.MjvCamera, width: int, heig frustum_near=glcam.frustum_near, frustum_far=glcam.frustum_far, ), - draw_mode=mjrf.DrawMode.DRAW_MODE_DEFAULT, + draw_mode=mjrf.DrawMode.DRAW_MODE_DEFAULT if kind == "rgb" else mjrf.DrawMode.DRAW_MODE_DEPTH, ) request.scene = self._scene request.target = target @@ -152,7 +168,7 @@ def render(self, data: mujoco.MjData, camera: mujoco.MjvCamera, width: int, heig # the bindings still support only a single read request per render call (MuJoCo 4.0.1) frame = self._ctx.render([request], [read]) self._ctx.wait_for_frame(frame) - return buffer.copy() + return buffer def close(self): if self._closed: From 6a05c82d29be8ca320d7a1870aa48b2e8e6e954b Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 13 Nov 2026 11:16:30 -0800 Subject: [PATCH 07/16] fix(sim): filament hangs without x display and breaks classic egl Filament's OpenGL backend uses GLX on Linux: without an X display it prints "Failed to open X display. (exiting)" and then hangs. Default to Vulkan on Linux without DISPLAY and raise instead of hanging when OpenGL is requested explicitly there. Destroying a Filament Vulkan context on NVIDIA drivers calls eglTerminate() on the default EGL display, which invalidates the classic renderer's EGL context (eglMakeCurrent fails with EGL_NOT_INITIALIZED). Filament contexts are therefore pooled per thread and reused instead of destroyed. Pooled contexts are kept alive at exit, as destroying them on the main thread aborts for contexts created by other threads. --- docs/user_guide/scene_configuration.md | 3 +- python/rcs/sim/filament.py | 90 ++++++++++++++++++++------ python/tests/test_filament.py | 40 ++++++++++++ 3 files changed, 114 insertions(+), 19 deletions(-) diff --git a/docs/user_guide/scene_configuration.md b/docs/user_guide/scene_configuration.md index cd207bf1d..a2c98c1c9 100644 --- a/docs/user_guide/scene_configuration.md +++ b/docs/user_guide/scene_configuration.md @@ -323,7 +323,8 @@ With this flag Environment variables for fine tuning: -- `RCS_FILAMENT_GRAPHICS_API=opengl|vulkan` graphics API of the camera renderer (default `opengl`) +- `RCS_FILAMENT_GRAPHICS_API=opengl|vulkan` graphics API of the camera renderer (default `opengl`, or `vulkan` + on Linux without an X display, where Filament's OpenGL backend does not work) - `RCS_FILAMENT_SOFTWARE_RENDERING=1` force software rendering for the cameras - `RCS_FILAMENT_GFX=opengl|vulkan|web|...` Studio graphics mode; `web` serves the viewer over http instead of opening a window diff --git a/python/rcs/sim/filament.py b/python/rcs/sim/filament.py index 86ee5aeb1..f4236eb5b 100644 --- a/python/rcs/sim/filament.py +++ b/python/rcs/sim/filament.py @@ -15,12 +15,15 @@ Environment variables: -- ``RCS_FILAMENT_GRAPHICS_API``: ``opengl`` or ``vulkan`` (default: opengl) +- ``RCS_FILAMENT_GRAPHICS_API``: ``opengl`` or ``vulkan`` (default: opengl, vulkan on Linux without an + X display: Filament's OpenGL backend needs X and hangs without it) - ``RCS_FILAMENT_SOFTWARE_RENDERING=1``: force software rendering for offscreen cameras - ``RCS_FILAMENT_GFX``: Studio graphics mode for the GUI, e.g. ``opengl``, ``vulkan``, ``web`` (``web`` serves the viewer over http instead of opening a native window) """ +import atexit +import ctypes import os import sys import threading @@ -62,11 +65,75 @@ def require(feature: str = "Filament rendering"): raise RuntimeError(msg) +def _graphics_api(mjrf): + """Graphics API for offscreen Filament contexts, see ``RCS_FILAMENT_GRAPHICS_API``.""" + api = os.environ.get("RCS_FILAMENT_GRAPHICS_API", "").lower() + if api not in ("", "opengl", "vulkan"): + logger.warning("Unknown RCS_FILAMENT_GRAPHICS_API=%r, using the default", api) + api = "" + # Filament's OpenGL backend on Linux uses GLX: without an X display it prints "Failed to open X + # display. (exiting)" and then hangs instead of exiting, so headless Linux has to use Vulkan + headless_linux = sys.platform.startswith("linux") and not os.environ.get("DISPLAY") + if api == "opengl" and headless_linux: + msg = ( + "RCS_FILAMENT_GRAPHICS_API=opengl requires an X display on Linux, but DISPLAY is not set. " + "Use RCS_FILAMENT_GRAPHICS_API=vulkan (the default without a display) or run under an X server." + ) + raise RuntimeError(msg) + if api == "vulkan" or (api == "" and headless_linux): + return mjrf.GraphicsApi.GRAPHICS_API_VULKAN + # OpenGL like MuJoCo's own samples; the platform default resolves to Vulkan on some systems + # (e.g. macOS) where it is not usable + return mjrf.GraphicsApi.GRAPHICS_API_OPENGL + + +# Filament contexts that are not in use, per (thread, graphics API, software rendering). +# Contexts are reused instead of destroyed: destroying a Vulkan context on NVIDIA drivers calls +# eglTerminate() on the process' default EGL display (from libGLX_nvidia on Filament's engine thread), +# which kills the EGL context of the classic renderer (eglMakeCurrent then fails with +# EGL_NOT_INITIALIZED). They are keyed by thread as Filament requires all calls of a context to come +# from the thread that created it. +_free_contexts: dict[tuple[int, object, bool], list] = {} +_free_contexts_lock = threading.Lock() + + +def _acquire_context(mjrf): + software = os.environ.get("RCS_FILAMENT_SOFTWARE_RENDERING", "") == "1" + key = (threading.get_ident(), _graphics_api(mjrf), software) + with _free_contexts_lock: + free = _free_contexts.setdefault(key, []) + ctx = free.pop() if free else None + if ctx is None: + cfg = mjrf.ContextConfig() + cfg.graphics_api = key[1] + cfg.software_rendering = software + ctx = mjrf.Context(cfg) + ctx.set_clear_color(np.zeros(3, dtype=np.float32)) + return key, ctx + + +def _release_context(key, ctx): + with _free_contexts_lock: + _free_contexts.setdefault(key, []).append(ctx) + + +@atexit.register +def _leak_free_contexts(): + # Pooled contexts would otherwise be destroyed during interpreter shutdown on the main thread, + # which aborts the process for contexts created by other threads ("Engine::shutdown() called from + # the wrong thread!"). Keep them alive instead; the OS frees them when the process exits. + with _free_contexts_lock: + for contexts in _free_contexts.values(): + for ctx in contexts: + ctypes.pythonapi.Py_IncRef(ctypes.py_object(ctx)) + + class FilamentRenderer: """Offscreen RGB renderer for a MuJoCo model based on Filament. All methods must be called from the thread that created the renderer: Filament asserts - thread affinity when its engine is destroyed. + thread affinity when its engine is destroyed. The Filament context is borrowed from a per-thread + pool and returned on :meth:`close` (a context can only serve one model at a time). """ def __init__(self, model: mujoco.MjModel): @@ -75,8 +142,7 @@ def __init__(self, model: mujoco.MjModel): self._mjrf = mjrf self.model = model - self._ctx = mjrf.Context(self._context_config()) - self._ctx.set_clear_color(np.zeros(3, dtype=np.float32)) + self._ctx_key, self._ctx = _acquire_context(mjrf) self._objects = mjrf.ModelResources(self._ctx, model) self._scene = self._ctx.create_scene(mjrf.SceneParams()) self._scene.configure_from_model(model) @@ -89,20 +155,6 @@ def __init__(self, model: mujoco.MjModel): self._far = model.vis.map.zfar * extent self._closed = False - def _context_config(self): - mjrf = self._mjrf - cfg = mjrf.ContextConfig() - # OpenGL like MuJoCo's own samples; the platform default resolves to Vulkan on some systems - # (e.g. macOS) where it is not usable - cfg.graphics_api = mjrf.GraphicsApi.GRAPHICS_API_OPENGL - api = os.environ.get("RCS_FILAMENT_GRAPHICS_API", "").lower() - if api == "vulkan": - cfg.graphics_api = mjrf.GraphicsApi.GRAPHICS_API_VULKAN - elif api not in ("", "opengl"): - logger.warning("Unknown RCS_FILAMENT_GRAPHICS_API=%r, using OpenGL", api) - cfg.software_rendering = os.environ.get("RCS_FILAMENT_SOFTWARE_RENDERING", "") == "1" - return cfg - def set_options(self, opt: mujoco.MjvOption): self._renderables.set_options(opt) @@ -177,6 +229,8 @@ def close(self): # destroy in reverse creation order; the context must outlive everything it created self._targets.clear() del self._renderables, self._lights, self._scene, self._objects + # the context is not destroyed but reused, see _free_contexts + _release_context(self._ctx_key, self._ctx) del self._ctx diff --git a/python/tests/test_filament.py b/python/tests/test_filament.py index a014b5ce7..52a028195 100644 --- a/python/tests/test_filament.py +++ b/python/tests/test_filament.py @@ -1,3 +1,5 @@ +import sys + import gymnasium as gym import mujoco import numpy as np @@ -99,3 +101,41 @@ def test_camera_set_wrapper_configures_depth_rendering(fr3_sim): assert camera_set.render_depth is True finally: camera_set.close() + + +@pytest.mark.skipif(not sys.platform.startswith("linux"), reason="X display detection is Linux specific") +def test_graphics_api_without_x_display(monkeypatch): + from mujoco import mjrf + + monkeypatch.delenv("DISPLAY", raising=False) + monkeypatch.delenv("RCS_FILAMENT_GRAPHICS_API", raising=False) + # Filament's OpenGL backend hangs without X, so headless Linux defaults to Vulkan ... + assert filament._graphics_api(mjrf) == mjrf.GraphicsApi.GRAPHICS_API_VULKAN + # ... and an explicit OpenGL request fails instead of hanging + monkeypatch.setenv("RCS_FILAMENT_GRAPHICS_API", "opengl") + with pytest.raises(RuntimeError, match="X display"): + filament._graphics_api(mjrf) + + +def test_filament_contexts_are_reused(fr3_sim): + simulation, _ = fr3_sim + first = filament.FilamentRenderer(simulation.model) + ctx = first._ctx + first.close() + second = filament.FilamentRenderer(simulation.model) + try: + assert second._ctx is ctx + finally: + second.close() + + +def test_classic_rendering_after_filament_close(fr3_sim): + # destroying a Filament (Vulkan) context used to terminate the EGL display of the classic renderer + simulation, cfg = fr3_sim + FilamentSimCameraSet(simulation, cfg.camera_cfgs).close() + classic = sim.Sim(EmptyWorldFR3().create_model(cfg), SimConfig()) + camera_set = SimCameraSet(classic, cfg.camera_cfgs, physical_units=True) + classic.step(1) + frameset = camera_set.get_latest_frames() + assert frameset is not None + assert all(frame.camera.color.data.std() > 1 for frame in frameset.frames.values()) From 490888f55de5f1d9d17df8d1fe26874ca7183dfc Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 13 Nov 2026 11:18:02 -0800 Subject: [PATCH 08/16] fix(sim): classic camera images depend on render order All cameras share one mjvScene, and mjv_updateScene positions infinite planes such as the floor relative to scene.camera before it updates the camera, i.e. relative to the previously rendered camera. This shifted the floor (and its shadows) by grid cells depending on which camera was rendered before, so images differed between calls on the same state and between single- and multi-camera setups. Update the camera before the scene. --- python/tests/test_sim_camera.py | 35 +++++++++++++++++++++++++++++++++ src/sim/camera.cpp | 8 +++++--- 2 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 python/tests/test_sim_camera.py diff --git a/python/tests/test_sim_camera.py b/python/tests/test_sim_camera.py new file mode 100644 index 000000000..7dcf2f86c --- /dev/null +++ b/python/tests/test_sim_camera.py @@ -0,0 +1,35 @@ +import numpy as np +from rcs.camera.sim import SimCameraSet +from rcs.envs.configs import EmptyWorldDroid +from rcs.sim import SimConfig + +from rcs import sim + + +def _render(camera_cfgs) -> dict[str, np.ndarray]: + scene = EmptyWorldDroid() + cfg = scene.prefixed_cfg(scene.config()) + simulation = sim.Sim(scene.create_model(cfg), SimConfig()) + simulation.step(10) + camera_set = SimCameraSet(simulation, {name: cfg.camera_cfgs[name] for name in camera_cfgs}, physical_units=True) + frames = [] + for _ in range(2): + frameset = camera_set.get_latest_frames() + assert frameset is not None + frames.append({name: frame.camera.color.data.astype(int) for name, frame in frameset.frames.items()}) + # rendering the same state twice gives the same images + for name in frames[0]: + assert np.abs(frames[0][name] - frames[1][name]).max() <= 1, name + return frames[1] + + +def test_camera_images_do_not_depend_on_other_cameras(): + # The cameras share one mjvScene and mjv_updateScene places infinite planes (the floor) relative to + # the scene's previous camera, which made images depend on which camera was rendered before. + scene = EmptyWorldDroid() + names = list(scene.prefixed_cfg(scene.config()).camera_cfgs) + assert len(names) > 1 + together = _render(names) + for name in names: + alone = _render([name])[name] + assert np.abs(together[name] - alone).max() <= 1, name diff --git a/src/sim/camera.cpp b/src/sim/camera.cpp index eadbae5b3..0d9410eff 100644 --- a/src/sim/camera.cpp +++ b/src/sim/camera.cpp @@ -117,11 +117,13 @@ void SimCameraSet::render_single(const std::string& id, mjrContext& ctx, ColorFrame frame = ColorFrame::Zero(3 * W * H); DepthFrame depth = DepthFrame::Zero(1 * W * H); // update abstract scene - // TODO: we might be able to call this once for all cameras - // there is also a mjv_updateCamera function + // The scene is shared by all cameras and mjv_updateScene positions infinite + // planes (e.g. the floor) from scene.camera *before* it updates the camera, + // i.e. from the previously rendered camera. Update the camera first so that + // images do not depend on the render order of the cameras. + mjv_updateCamera(this->sim->m, this->sim->d, &this->cameras[id], &scene); mjv_updateScene(this->sim->m, this->sim->d, &opt, NULL, &this->cameras[id], mjCAT_ALL, &scene); - // mjv_updateCamera(this->sim->m, this->sim->d, &this->cameras[id], &scene); // render scene in offscreen buffer mjr_render(viewport, &scene, &ctx); From 608f83117ad99f17bfb84b9fedac1563ae3c9133 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 13 Nov 2026 11:34:22 -0800 Subject: [PATCH 09/16] perf(sim): render filament color into rgba8 target GPUs generally do not support 3 channel 8 bit render targets (Vulkan's R8G8B8_UNORM has no image features on NVIDIA), so Filament emulates RGB8 with a slow readback. Render into RGBA8 and drop alpha with cv2.cvtColor, which is ~100x faster than a numpy slice copy. Images are identical, 3 cameras at 1280x720 go from ~8.5 to ~5.3 ms on Vulkan. --- python/rcs/sim/filament.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/python/rcs/sim/filament.py b/python/rcs/sim/filament.py index f4236eb5b..3346d811c 100644 --- a/python/rcs/sim/filament.py +++ b/python/rcs/sim/filament.py @@ -30,6 +30,7 @@ from logging import getLogger from tempfile import NamedTemporaryFile +import cv2 import mujoco import numpy as np from rcs._core.sim import GuiClient as _GuiClient @@ -168,7 +169,10 @@ def _target(self, width: int, height: int, kind: str = "rgb"): if key not in self._targets: mjrf = self._mjrf if kind == "rgb": - fmt, buffer = mjrf.PixelFormat.PIXEL_FORMAT_RGB8, np.empty((height, width, 3), dtype=np.uint8) + # RGBA8 instead of RGB8: GPUs generally do not support 3 channel 8 bit render targets + # (e.g. Vulkan's R8G8B8_UNORM has no image features on NVIDIA), so Filament emulates + # RGB8 with a slow readback path (about 2x slower on Vulkan); alpha is dropped in render() + fmt, buffer = mjrf.PixelFormat.PIXEL_FORMAT_RGBA8, np.empty((height, width, 4), dtype=np.uint8) else: fmt, buffer = mjrf.PixelFormat.PIXEL_FORMAT_R32F, np.empty((height, width), dtype=np.float32) target = self._ctx.create_render_target(mjrf.RenderTargetConfig(color_format=fmt)) @@ -183,7 +187,8 @@ def render(self, data: mujoco.MjData, camera: mujoco.MjvCamera, width: int, heig Call :meth:`update` first whenever ``data`` changed. """ - return self._render(data, camera, width, height, "rgb").copy() + # cv2 drops the alpha channel ~100x faster than a numpy slice copy + return cv2.cvtColor(self._render(data, camera, width, height, "rgb"), cv2.COLOR_RGBA2RGB) def render_depth(self, data: mujoco.MjData, camera: mujoco.MjvCamera, width: int, height: int) -> np.ndarray: """Renders the given camera and returns metric depth in meters as (H, W) float32 (top row first). From b7b511a806e415b70b4abc76eb4addf83897996c Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 13 Nov 2026 11:37:33 -0800 Subject: [PATCH 10/16] test(sim): narrow optional camera configs for mypy --- python/tests/test_sim_camera.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/python/tests/test_sim_camera.py b/python/tests/test_sim_camera.py index 7dcf2f86c..156c04975 100644 --- a/python/tests/test_sim_camera.py +++ b/python/tests/test_sim_camera.py @@ -9,6 +9,7 @@ def _render(camera_cfgs) -> dict[str, np.ndarray]: scene = EmptyWorldDroid() cfg = scene.prefixed_cfg(scene.config()) + assert cfg.camera_cfgs is not None simulation = sim.Sim(scene.create_model(cfg), SimConfig()) simulation.step(10) camera_set = SimCameraSet(simulation, {name: cfg.camera_cfgs[name] for name in camera_cfgs}, physical_units=True) @@ -27,7 +28,9 @@ def test_camera_images_do_not_depend_on_other_cameras(): # The cameras share one mjvScene and mjv_updateScene places infinite planes (the floor) relative to # the scene's previous camera, which made images depend on which camera was rendered before. scene = EmptyWorldDroid() - names = list(scene.prefixed_cfg(scene.config()).camera_cfgs) + camera_cfgs = scene.prefixed_cfg(scene.config()).camera_cfgs + assert camera_cfgs is not None + names = list(camera_cfgs) assert len(names) > 1 together = _render(names) for name in names: From 253fbd376e956e894949b7478d0f6c65855591e5 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 13 Nov 2026 11:43:55 -0800 Subject: [PATCH 11/16] feat(sim): capture simulation states at fixed rates Sim.register_state_capture records the simulation state (mj_getState) at a fixed rate of simulation time into a ring buffer, e.g. at the exposure times of a camera, so that frames can later be rendered from the state a real camera would have recorded. Captures follow a fixed schedule (no drift), happen at the physics step closest to each capture time after integration, and restart on reset or when time goes back. --- python/rcs/_core/sim.pyi | 11 +++++ python/tests/test_sim_camera.py | 49 ++++++++++++++++++ src/pybind/rcs.cpp | 13 +++++ src/sim/sim.cpp | 88 +++++++++++++++++++++++++++++++++ src/sim/sim.h | 38 ++++++++++++++ 5 files changed, 199 insertions(+) diff --git a/python/rcs/_core/sim.pyi b/python/rcs/_core/sim.pyi index 02623105b..182e4d3f6 100644 --- a/python/rcs/_core/sim.pyi +++ b/python/rcs/_core/sim.pyi @@ -12,6 +12,7 @@ import rcs._core.common __all__: list[str] = [ "CLASSIC", "CameraType", + "CapturedState", "DynamicJointSchema", "DynamicJointState", "FILAMENT", @@ -73,6 +74,12 @@ class CameraType: @property def value(self) -> int: ... +class CapturedState: + @property + def state(self) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]: ... + @property + def timestamp(self) -> float: ... + class DynamicJointSchema: joint_names: list[str] joint_types: list[int] @@ -138,10 +145,14 @@ class Sim: def __init__(self, mjmdl: int, mjdata: int) -> None: ... def _start_gui_server(self, id: str) -> None: ... def _stop_gui_server(self) -> None: ... + def captured_state_count(self, id: int) -> int: ... + def clear_captured_states(self, id: int) -> None: ... + def get_captured_state(self, id: int, max_timestamp: float = ...) -> CapturedState | None: ... def get_config(self) -> SimConfig: ... def get_dynamic_joint_schema(self) -> DynamicJointSchema: ... def get_dynamic_joint_state(self) -> DynamicJointState: ... def is_converged(self) -> bool: ... + def register_state_capture(self, frame_rate: float, buffer_size: int, state_spec: int) -> int: ... def reset(self) -> None: ... def set_config(self, cfg: SimConfig) -> bool: ... def set_dynamic_joint_state(self, schema: DynamicJointSchema, state: DynamicJointState) -> None: ... diff --git a/python/tests/test_sim_camera.py b/python/tests/test_sim_camera.py index 156c04975..59aa7817f 100644 --- a/python/tests/test_sim_camera.py +++ b/python/tests/test_sim_camera.py @@ -1,3 +1,6 @@ +import math + +import mujoco import numpy as np from rcs.camera.sim import SimCameraSet from rcs.envs.configs import EmptyWorldDroid @@ -5,6 +8,8 @@ from rcs import sim +STATE_SPEC = mujoco.mjtState.mjSTATE_INTEGRATION + def _render(camera_cfgs) -> dict[str, np.ndarray]: scene = EmptyWorldDroid() @@ -36,3 +41,47 @@ def test_camera_images_do_not_depend_on_other_cameras(): for name in names: alone = _render([name])[name] assert np.abs(together[name] - alone).max() <= 1, name + + +def _droid_sim(): + scene = EmptyWorldDroid() + cfg = scene.prefixed_cfg(scene.config()) + assert cfg.camera_cfgs is not None + return sim.Sim(scene.create_model(cfg), SimConfig()), cfg.camera_cfgs + + +def test_state_capture_follows_fixed_schedule(): + simulation, _ = _droid_sim() + dt = simulation.model.opt.timestep + frame_rate = 30 + capture = simulation.register_state_capture(frame_rate, 1000, int(STATE_SPEC)) + # the current state is captured right away + assert simulation.captured_state_count(capture) == 1 + first = simulation.get_captured_state(capture) + assert first is not None + assert first.timestamp == 0 + assert len(first.state) == mujoco.mj_stateSize(simulation.model, STATE_SPEC) + + simulation.step(round(2.0 / dt)) + timestamps: list[float] = [] + for _ in range(simulation.captured_state_count(capture)): + captured = simulation.get_captured_state(capture, timestamps[-1] - dt / 2 if timestamps else math.inf) + assert captured is not None + timestamps.append(captured.timestamp) + timestamps.reverse() + # one capture per frame at the physics step closest to k / frame_rate, i.e. no drift over time + assert len(timestamps) == 2 * frame_rate + 1 + expected = np.arange(len(timestamps)) / frame_rate + assert np.abs(np.array(timestamps) - expected).max() <= dt / 2 + 1e-9 + + +def test_state_capture_restarts_on_reset(): + simulation, _ = _droid_sim() + capture = simulation.register_state_capture(30, 100, int(STATE_SPEC)) + simulation.step(100) + assert simulation.captured_state_count(capture) > 1 + simulation.reset() + assert simulation.captured_state_count(capture) == 1 + captured = simulation.get_captured_state(capture) + assert captured is not None + assert captured.timestamp == 0 diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 0d2d01bff..60879f6ad 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include "rcs/Kinematics.h" @@ -801,6 +802,9 @@ PYBIND11_MODULE(_core, m) { .def_readwrite("qpos", &rcs::sim::DynamicJointState::qpos) .def_readwrite("qvel", &rcs::sim::DynamicJointState::qvel); + py::class_(sim, "CapturedState") + .def_readonly("timestamp", &rcs::sim::CapturedState::timestamp) + .def_readonly("state", &rcs::sim::CapturedState::state); py::class_>(sim, "Sim") .def(py::init([](long m, long d) { return std::make_shared((mjModel*)m, (mjData*)d); @@ -818,6 +822,15 @@ PYBIND11_MODULE(_core, m) { .def("get_dynamic_joint_state", &rcs::sim::Sim::get_dynamic_joint_state) .def("set_dynamic_joint_state", &rcs::sim::Sim::set_dynamic_joint_state, py::arg("schema"), py::arg("state")) + .def("register_state_capture", &rcs::sim::Sim::register_state_capture, + py::arg("frame_rate"), py::arg("buffer_size"), py::arg("state_spec")) + .def("get_captured_state", &rcs::sim::Sim::get_captured_state, + py::arg("id"), + py::arg("max_timestamp") = std::numeric_limits::infinity()) + .def("captured_state_count", &rcs::sim::Sim::captured_state_count, + py::arg("id")) + .def("clear_captured_states", &rcs::sim::Sim::clear_captured_states, + py::arg("id")) .def("_start_gui_server", &rcs::sim::Sim::start_gui_server, py::arg("id")) .def("_stop_gui_server", &rcs::sim::Sim::stop_gui_server); diff --git a/src/sim/sim.cpp b/src/sim/sim.cpp index 2cbafbb36..f55e49f63 100644 --- a/src/sim/sim.cpp +++ b/src/sim/sim.cpp @@ -2,6 +2,7 @@ #include +#include #include #include #include @@ -140,6 +141,45 @@ void Sim::invoke_rendering_callbacks() { } } +void Sim::capture_state(StateCapture& capture) { + mj_getState(this->m, this->d, + capture.states.data() + capture.next_index * capture.state_size, + capture.state_spec); + capture.timestamps[capture.next_index] = this->d->time; + capture.next_index = (capture.next_index + 1) % capture.capacity; + capture.size = std::min(capture.size + 1, capture.capacity); +} + +void Sim::restart_state_capture(StateCapture& capture) { + capture.next_index = 0; + capture.size = 0; + this->capture_state(capture); + capture.next_capture_time = this->d->time + capture.period; +} + +void Sim::invoke_state_captures() { + // capture at the physics step closest to the scheduled capture time + mjtNum half_step = 0.5 * this->m->opt.timestep; + for (StateCapture& capture : this->state_captures) { + size_t latest = + (capture.next_index + capture.capacity - 1) % capture.capacity; + if (capture.size > 0 && this->d->time < capture.timestamps[latest]) { + // simulation time went backwards (e.g. the state was reset externally) + this->restart_state_capture(capture); + continue; + } + if (this->d->time + half_step < capture.next_capture_time) { + continue; + } + this->capture_state(capture); + // advance on the fixed schedule, skipping capture times that fell into + // this step (frame rates above the physics rate) + while (capture.next_capture_time <= this->d->time + half_step) { + capture.next_capture_time += capture.period; + } + } +} + bool Sim::is_converged() { return this->converged; } void Sim::step_until_convergence() { this->convergence_steps = 0; @@ -170,6 +210,7 @@ void Sim::step(size_t k) { mj_step1(this->m, this->d); this->invoke_callbacks(); mj_step2(this->m, this->d); + this->invoke_state_captures(); this->invoke_rendering_callbacks(); } } @@ -323,6 +364,9 @@ void Sim::reset_callbacks() { this->rendering_callbacks[i].last_call_timestamp = -this->rendering_callbacks[i].seconds_between_calls; } + for (StateCapture& capture : this->state_captures) { + this->restart_state_capture(capture); + } } void Sim::register_cb(std::function cb, @@ -360,6 +404,50 @@ void Sim::register_rendering_callback( } } +size_t Sim::register_state_capture(double frame_rate, size_t buffer_size, + int state_spec) { + if (frame_rate <= 0) { + throw std::invalid_argument("frame_rate must be positive"); + } + if (buffer_size == 0) { + throw std::invalid_argument("buffer_size must be positive"); + } + StateCapture capture; + capture.period = 1.0 / frame_rate; + capture.state_spec = state_spec; + capture.state_size = mj_stateSize(this->m, state_spec); + capture.capacity = buffer_size; + capture.states.resize(buffer_size * capture.state_size); + capture.timestamps.resize(buffer_size); + this->restart_state_capture(capture); + this->state_captures.push_back(std::move(capture)); + return this->state_captures.size() - 1; +} + +std::optional Sim::get_captured_state( + size_t id, mjtNum max_timestamp) const { + const StateCapture& capture = this->state_captures.at(id); + for (size_t i = 0; i < capture.size; ++i) { + size_t idx = + (capture.next_index + capture.capacity - 1 - i) % capture.capacity; + if (capture.timestamps[idx] <= max_timestamp) { + return CapturedState{capture.timestamps[idx], + Eigen::Map( + capture.states.data() + idx * capture.state_size, + capture.state_size)}; + } + } + return std::nullopt; +} + +size_t Sim::captured_state_count(size_t id) const { + return this->state_captures.at(id).size; +} + +void Sim::clear_captured_states(size_t id) { + this->restart_state_capture(this->state_captures.at(id)); +} + void Sim::start_gui_server(const std::string& id) { if (this->gui.has_value()) { throw std::runtime_error("Start gui server should be called only once."); diff --git a/src/sim/sim.h b/src/sim/sim.h index c35835f61..59849dd8c 100644 --- a/src/sim/sim.h +++ b/src/sim/sim.h @@ -67,6 +67,26 @@ struct RenderingCallback { mjtNum last_call_timestamp; // in seconds }; +/* Simulation states captured at a fixed rate of simulation time, e.g. at the + * exposure times of a camera, so that they can be rendered later. Kept in a + * ring buffer of the most recent states. */ +struct StateCapture { + mjtNum period; // in seconds + mjtNum next_capture_time; // in seconds of simulation time + int state_spec; // mjtState bit mask passed to mj_getState + int state_size; + size_t capacity; + std::vector states; // capacity x state_size, row major + std::vector timestamps; // capacity + size_t next_index = 0; + size_t size = 0; +}; + +struct CapturedState { + mjtNum timestamp; + rcs::common::VectorXd state; +}; + struct DynamicJointSchema { std::vector joint_names; std::vector joint_types; @@ -95,11 +115,15 @@ class Sim { std::vector any_callbacks; std::vector all_callbacks; std::vector rendering_callbacks; + std::vector state_captures; std::vector dynamic_joint_specs; std::unordered_map dynamic_joint_name_to_index; void invoke_callbacks(); bool invoke_condition_callbacks(); void invoke_rendering_callbacks(); + void invoke_state_captures(); + void capture_state(StateCapture& capture); + void restart_state_capture(StateCapture& capture); void init_dynamic_joint_specs(); static int get_joint_qpos_size(int joint_type); static int get_joint_qvel_size(int joint_type); @@ -142,6 +166,20 @@ class Sim { mjvOption&)> cb, const std::string& id, int frame_rate, size_t width, size_t height); + /* Captures the simulation state (mj_getState with state_spec) frame_rate + * times per second of simulation time and keeps the latest buffer_size + * states. The current state is captured right away. Captures follow a fixed + * schedule (no drift) and happen at the physics step closest to each capture + * time, after integration so that the state is consistent with its time + * stamp. Returns the id of the capture. */ + size_t register_state_capture(double frame_rate, size_t buffer_size, + int state_spec); + /* Latest captured state with a time stamp <= max_timestamp */ + std::optional get_captured_state(size_t id, + mjtNum max_timestamp) const; + size_t captured_state_count(size_t id) const; + /* Clears the buffer and restarts the capture schedule at the current state */ + void clear_captured_states(size_t id); void start_gui_server(const std::string& id); void stop_gui_server(); void sync_gui(); From 0090b5a0ece8f2809895818328087a5d2d973135 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 13 Nov 2026 11:44:10 -0800 Subject: [PATCH 12/16] refactor(sim): render simulation cameras in python SimCameraSet now renders in Python with either MuJoCo's classic OpenGL renderer or Filament, from a separate render-only MjData whose kinematics are recomputed from the state, so images, time stamps and extrinsics always belong together. With render_on_demand=True frames show the state at request time; with render_on_demand=False they show the state captured at each camera's frame rate (the last exposure of a real camera) and are rendered from it on request. This removes the C++ camera implementation (SimCameraSet, FrameSet, Renderer and the rendering callbacks that ran in every physics step), the C++ EGL context handoff and the EGL headers dependency. Rendering from Python is faster: frames are read into numpy arrays directly instead of being copied through Eigen and pybind11. --- CMakeLists.txt | 11 +- docs/user_guide/scene_configuration.md | 26 +- include/rcs/utils.h | 4 - python/rcs/_core/common.pyi | 2 - python/rcs/_core/sim.pyi | 27 -- python/rcs/camera/sim.py | 392 +++++++++++++-------- python/rcs/sim/render_context_bootstrap.py | 57 +-- python/rcs/sim/sim.py | 3 +- python/tests/test_sim_camera.py | 52 ++- src/pybind/rcs.cpp | 34 -- src/rcs/CMakeLists.txt | 2 +- src/rcs/utils.cpp | 45 --- src/sim/CMakeLists.txt | 2 +- src/sim/camera.cpp | 159 --------- src/sim/camera.h | 53 --- src/sim/renderer.cpp | 49 --- src/sim/sim.cpp | 47 +-- src/sim/sim.h | 33 +- 18 files changed, 328 insertions(+), 670 deletions(-) delete mode 100644 src/rcs/utils.cpp delete mode 100644 src/sim/camera.cpp delete mode 100644 src/sim/renderer.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index fe288a399..335f0fa27 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -49,15 +49,6 @@ FetchContent_Declare(Eigen3 URL https://gitlab.com/libeigen/eigen/-/archive/3.4.1/eigen-3.4.1.tar.gz EXCLUDE_FROM_ALL ) -FetchContent_Declare( - egl_headers - GIT_REPOSITORY https://github.com/KhronosGroup/EGL-Registry.git - GIT_TAG main - GIT_SHALLOW TRUE -) - -FetchContent_MakeAvailable(pybind11 Eigen3 egl_headers) -# egl headers -include_directories(${egl_headers_SOURCE_DIR}/api) +FetchContent_MakeAvailable(pybind11 Eigen3) add_subdirectory(src) diff --git a/docs/user_guide/scene_configuration.md b/docs/user_guide/scene_configuration.md index a2c98c1c9..9ed007477 100644 --- a/docs/user_guide/scene_configuration.md +++ b/docs/user_guide/scene_configuration.md @@ -299,6 +299,28 @@ Example: - `depth[y, x] == 1500` means the point is about **1.5 m** away from the camera +## Camera timing + +Simulation cameras render in Python (`rcs.camera.sim.SimCameraSet`) and show one of two simulation states: + +- `render_on_demand=True` (default): the state at the moment the frames are requested, e.g. after the + last env step. +- `render_on_demand=False`: the state at the last *exposure* of each camera, like a real camera that + records at its `frame_rate`. While the simulation steps, it captures its state at each camera frame + rate (the state only, no rendering, about a microsecond per capture); frames are rendered from the + latest captured state when they are requested. With a 30 Hz camera and a 10 Hz env, an observation + therefore shows the scene up to 33 ms before the end of the env step, as a real camera would. + +```python +camera_set = SimCameraSet(simulation, camera_cfgs, physical_units=True, render_on_demand=False) +``` + +Captures follow a fixed schedule of simulation time (`k / frame_rate`, no drift) and happen at the +physics step closest to each capture time. Frame time stamps are the simulation time of the rendered +state, and `get_timestamp_frames(ts)` renders the latest exposure at or before `ts` (the last +`max_buffer_frames` captured states are kept). Cameras with different frame rates are captured +independently. + ## Rendering backend (Filament) By default, simulation cameras and the GUI use MuJoCo's classic OpenGL renderer. MuJoCo >= 4.0 also @@ -314,8 +336,8 @@ sim_cfg = SimConfig(async_control=False, realtime=False, renderer=RendererBacken With this flag - `SimCameraSet(...)` returns a `FilamentSimCameraSet`: color and depth images are rendered with Filament - in Python (frames are rendered when requested, a fixed camera frame rate is not supported). Depth images - always use the metric units described above. The depth pass is a second Filament render per camera, so + instead of the classic renderer (both timing modes below are supported). Depth images always use the + metric units described above. The depth pass is a second Filament render per camera, so it is skipped when `CameraSetWrapper(include_depth=False)` (or `FilamentSimCameraSet(render_depth=False)`) is used. - `open_gui()` launches MuJoCo Studio instead of the passive `mujoco.viewer`. Studio runs in the GUI diff --git a/include/rcs/utils.h b/include/rcs/utils.h index f12cb85a1..75ecf41f9 100644 --- a/include/rcs/utils.h +++ b/include/rcs/utils.h @@ -40,10 +40,6 @@ Eigen::Matrix array2eigen( Eigen::Matrix matrix(array.data()); return matrix; } -void bootstrap_egl_context(std::uintptr_t fn_addr, std::uintptr_t display, - std::uintptr_t context); -void bootstrap_gl_context(); -void ensure_current(); /*** * @brief thread safe holder for a single value, e.g. to hand data from a diff --git a/python/rcs/_core/common.pyi b/python/rcs/_core/common.pyi index a9c2380ef..b9d0385cf 100644 --- a/python/rcs/_core/common.pyi +++ b/python/rcs/_core/common.pyi @@ -351,8 +351,6 @@ def FrankaHandTCPOffset() -> numpy.ndarray[tuple[typing.Literal[4], typing.Liter def IdentityRotMatrix() -> numpy.ndarray[tuple[typing.Literal[3], typing.Literal[3]], numpy.dtype[numpy.float64]]: ... def IdentityRotQuatVec() -> numpy.ndarray[tuple[typing.Literal[4]], numpy.dtype[numpy.float64]]: ... def IdentityTranslation() -> numpy.ndarray[tuple[typing.Literal[3]], numpy.dtype[numpy.float64]]: ... -def _bootstrap_egl_context(fn_addr: int, display: int, context: int) -> None: ... -def _bootstrap_gl_context() -> None: ... HARDWARE: RobotPlatform # value = LATERAL_GRASP: GraspType # value = diff --git a/python/rcs/_core/sim.pyi b/python/rcs/_core/sim.pyi index 182e4d3f6..bafff1fa3 100644 --- a/python/rcs/_core/sim.pyi +++ b/python/rcs/_core/sim.pyi @@ -16,12 +16,10 @@ __all__: list[str] = [ "DynamicJointSchema", "DynamicJointState", "FILAMENT", - "FrameSet", "GuiClient", "RendererBackend", "Sim", "SimCameraConfig", - "SimCameraSet", "SimConfig", "SimGripper", "SimGripperConfig", @@ -92,20 +90,6 @@ class DynamicJointState(typing.Generic[M]): qvel: numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]] def __init__(self) -> None: ... -class FrameSet: - def __init__( - self, - color_frames: dict[str, numpy.ndarray[tuple[M], numpy.dtype[numpy.uint8]]], - depth_frames: dict[str, numpy.ndarray[tuple[M], numpy.dtype[numpy.float32]]], - timestamp: float, - ) -> None: ... - @property - def color_frames(self) -> dict[str, numpy.ndarray[tuple[M], numpy.dtype[numpy.uint8]]]: ... - @property - def depth_frames(self) -> dict[str, numpy.ndarray[tuple[M], numpy.dtype[numpy.float32]]]: ... - @property - def timestamp(self) -> float: ... - class GuiClient: def __init__(self, id: str) -> None: ... def get_model_bytes(self) -> bytes: ... @@ -168,17 +152,6 @@ class SimCameraConfig(rcs._core.common.BaseCameraConfig): self, identifier: str, frame_rate: int, resolution_width: int, resolution_height: int, type: CameraType = ... ) -> None: ... -class SimCameraSet: - def __init__( - self, sim: Sim, cameras: dict[str, SimCameraConfig], render_on_demand: bool = True, max_buffer_frames: int = 100 - ) -> None: ... - def buffer_size(self) -> int: ... - def clear_buffer(self) -> None: ... - def get_latest_frameset(self) -> FrameSet | None: ... - def get_timestamp_frameset(self, ts: float) -> FrameSet | None: ... - @property - def _sim(self) -> Sim: ... - class SimConfig: async_control: bool frequency: float diff --git a/python/rcs/camera/sim.py b/python/rcs/camera/sim.py index a9a784261..4ebdd71d6 100644 --- a/python/rcs/camera/sim.py +++ b/python/rcs/camera/sim.py @@ -1,16 +1,30 @@ +""" +Simulation cameras. + +Images are rendered in Python, either with MuJoCo's classic OpenGL renderer or with Filament +(``SimConfig(renderer=RendererBackend.FILAMENT)``). They show one of two simulation states: + +- ``render_on_demand=True`` (default): the state at the time the frames are requested. +- ``render_on_demand=False``: the state at the last exposure of each camera, like a real camera that + records at its ``frame_rate``. The simulation captures its state at each camera's frame rate while + it steps (``Sim.register_state_capture``, cheap: no rendering), and frames are rendered from the + captured states when they are requested. + +In both cases the state is loaded into a separate render-only ``MjData`` and its kinematics are +recomputed, so the image, its time stamp and the camera extrinsics always belong together. +""" + import logging +import math +from collections import deque from datetime import datetime from typing import Literal +import cv2 import mujoco import numpy as np - -# from rcs._core.common import BaseCameraConfig from rcs._core import common -from rcs._core.sim import CameraType -from rcs._core.sim import FrameSet as _FrameSet -from rcs._core.sim import RendererBackend, SimCameraConfig -from rcs._core.sim import SimCameraSet as _SimCameraSet +from rcs._core.sim import CameraType, RendererBackend, SimCameraConfig from rcs.camera.interface import BaseCameraSet, CameraFrame, DataFrame, Frame, FrameSet from rcs.sim import filament, render_context_bootstrap @@ -18,6 +32,9 @@ logger = logging.getLogger(__name__) +# state that is captured and restored for rendering +STATE_SPEC = mujoco.mjtState.mjSTATE_INTEGRATION + def _camera_id(model: mujoco.MjModel, cfg: SimCameraConfig) -> int: return mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_CAMERA, cfg.identifier) @@ -52,191 +69,202 @@ def _extrinsics( return cam.inverse().pose_matrix() -class SimCameraSet(_SimCameraSet): - """Represents a set of cameras in a mujoco simulation. - Implements BaseCameraSet +class _ClassicRenderer: + """MuJoCo's classic OpenGL renderer, offscreen, one context per resolution. - Rendering happens in C++ with MuJoCo's classic OpenGL renderer. If the simulation was configured with - ``SimConfig(renderer=RendererBackend.FILAMENT)``, constructing this class returns a - :class:`FilamentSimCameraSet` instead. + Unlike ``mujoco.Renderer`` this is not limited by the model's ``offwidth``/``offheight``. """ - def __new__( - cls, - simulation: sim.Sim, - cameras: dict[str, SimCameraConfig], - physical_units: bool = False, - render_on_demand: bool = True, - ): - if simulation.get_config().renderer == RendererBackend.FILAMENT: - return FilamentSimCameraSet(simulation, cameras, physical_units, render_on_demand) - return super().__new__(cls) - - def __init__( - self, - simulation: sim.Sim, - cameras: dict[str, SimCameraConfig], - physical_units: bool = False, - render_on_demand: bool = True, - ): - self._logger = logging.getLogger(__name__) - self.cameras = cameras - self.physical_units = physical_units - + def __init__(self, model: mujoco.MjModel, physical_units: bool): render_context_bootstrap.require("simulation camera rendering") - super().__init__(simulation, cameras, render_on_demand=render_on_demand) - self._sim: sim.Sim + render_context_bootstrap.make_current() + self._model = model + self._physical_units = physical_units + self._scene = mujoco.MjvScene(model, maxgeom=2000) + self._opt = mujoco.MjvOption() + self._contexts: dict[tuple[int, int], tuple[mujoco.MjrContext, mujoco.MjrRect, np.ndarray, np.ndarray]] = {} + extent = model.stat.extent + self._near = model.vis.map.znear * extent + self._far = model.vis.map.zfar * extent + + def _context(self, width: int, height: int): + key = (width, height) + if key not in self._contexts: + ctx = mujoco.MjrContext(self._model, mujoco.mjtFontScale.mjFONTSCALE_150) + mujoco.mjr_setBuffer(mujoco.mjtFramebuffer.mjFB_OFFSCREEN, ctx) + mujoco.mjr_resizeOffscreen(width, height, ctx) + rgb = np.empty((height, width, 3), dtype=np.uint8) + depth = np.empty((height, width), dtype=np.float32) + self._contexts[key] = (ctx, mujoco.MjrRect(0, 0, width, height), rgb, depth) + return self._contexts[key] + + def update(self, data: mujoco.MjData): + pass - def get_latest_frames(self) -> FrameSet | None: - """Should return the latest frame from the camera with the given name.""" - return self._cpp_to_python_frames(super().get_latest_frameset()) + def render( + self, data: mujoco.MjData, camera: mujoco.MjvCamera, width: int, height: int, depth: bool + ) -> tuple[np.ndarray, np.ndarray | None]: + """Returns (H, W, 3) uint8 RGB and, if requested, (H, W) float32 depth, both top row first. + + Depth is in meters with ``physical_units``, otherwise the raw [0, 1] OpenGL depth buffer. + """ + render_context_bootstrap.make_current() + ctx, viewport, rgb_buffer, depth_buffer = self._context(width, height) + mujoco.mjr_setBuffer(mujoco.mjtFramebuffer.mjFB_OFFSCREEN, ctx) + # The scene is shared by all cameras and mjv_updateScene positions infinite planes (e.g. the + # floor) from scene.camera *before* it updates the camera, i.e. from the previously rendered + # camera. Update the camera first so that images do not depend on the render order. + mujoco.mjv_updateCamera(self._model, data, camera, self._scene) + mujoco.mjv_updateScene(self._model, data, self._opt, None, camera, mujoco.mjtCatBit.mjCAT_ALL, self._scene) + mujoco.mjr_render(viewport, self._scene, ctx) + mujoco.mjr_readPixels(rgb_buffer, depth_buffer if depth else None, viewport, ctx) + # OpenGL reads bottom-up + rgb = cv2.flip(rgb_buffer, 0) + if not depth: + return rgb, None + depth_image = cv2.flip(depth_buffer, 0) + if self._physical_units: + # Convert from [0 1] to depth in meters, see links below: + # http://stackoverflow.com/a/6657284/1461210 + # https://www.khronos.org/opengl/wiki/Depth_Buffer_Precision + depth_image = self._near / (1 - depth_image * (1 - self._near / self._far)) + return rgb, depth_image - def get_timestamp_frames(self, ts: datetime) -> FrameSet | None: - """Should return the frame from the camera with the given name and closest to the given timestamp.""" - return self._cpp_to_python_frames(super().get_timestamp_frameset(ts.timestamp())) + def close(self): + if not self._contexts: + return + render_context_bootstrap.make_current() + for ctx, *_ in self._contexts.values(): + ctx.free() + self._contexts.clear() - def _cpp_to_python_frames(self, cpp_frameset: _FrameSet | None) -> FrameSet | None: - if cpp_frameset is None: - return None - frames: dict[str, Frame] = {} - c_frames_iter = cpp_frameset.color_frames.items() - d_frames_iter = cpp_frameset.depth_frames.items() - for (color_name, color_frame), (depth_name, depth_frame) in zip(c_frames_iter, d_frames_iter, strict=True): - assert color_name == depth_name - color_np_frame = np.copy(color_frame).reshape( - self.cameras[color_name].resolution_height, self.cameras[color_name].resolution_width, 3 - )[ - # convert from column-major (c++ eigen) to row-major (python numpy) - ::-1 - ] - depth_np_frame = np.copy(depth_frame).reshape( - self.cameras[depth_name].resolution_height, self.cameras[depth_name].resolution_width, 1 - )[ - # convert from column-major (c++ eigen) to row-major (python numpy) - ::-1 - ] - if self.physical_units: - # Convert from [0 1] to depth in meters, see links below: - # http://stackoverflow.com/a/6657284/1461210 - # https://www.khronos.org/opengl/wiki/Depth_Buffer_Precision - # https://github.com/htung0101/table_dome/blob/master/table_dome_calib/utils.py#L160 - extent = self._sim.model.stat.extent - near = self._sim.model.vis.map.znear * extent - far = self._sim.model.vis.map.zfar * extent - depth_np_frame = near / (1 - depth_np_frame * (1 - near / far)) - - cameraframe = CameraFrame( - color=DataFrame( - data=color_np_frame, - timestamp=cpp_frameset.timestamp, - intrinsics=self._intrinsics(color_name), - extrinsics=self._extrinsics(color_name), - ), - depth=DataFrame( - data=(depth_np_frame * BaseCameraSet.DEPTH_SCALE).astype(np.uint16), - timestamp=cpp_frameset.timestamp, - intrinsics=self._intrinsics(depth_name), - extrinsics=self._extrinsics(depth_name), - ), - ) - frame = Frame(camera=cameraframe, avg_timestamp=cpp_frameset.timestamp) - frames[color_name] = frame - return FrameSet(frames=frames, avg_timestamp=cpp_frameset.timestamp) - def _intrinsics(self, camera_name) -> np.ndarray[tuple[Literal[3], Literal[4]], np.dtype[np.float64]]: - return _intrinsics(self._sim.model, self.cameras[camera_name]) +class _FilamentRenderer: + """Adapter of :class:`rcs.sim.filament.FilamentRenderer` (depth is always metric).""" - def _extrinsics(self, camera_name) -> np.ndarray[tuple[Literal[4], Literal[4]], np.dtype[np.float64]]: - return _extrinsics(self._sim.model, self._sim.data, self.cameras[camera_name]) + def __init__(self, model: mujoco.MjModel): + self._renderer = filament.FilamentRenderer(model) - def calibrate(self) -> bool: - return True + def update(self, data: mujoco.MjData): + self._renderer.update(data) - def config(self, camera_name: str) -> SimCameraConfig: - """Should return the configuration of the camera with the given name.""" - return self.cameras[camera_name] + def render( + self, data: mujoco.MjData, camera: mujoco.MjvCamera, width: int, height: int, depth: bool + ) -> tuple[np.ndarray, np.ndarray | None]: + rgb = self._renderer.render(data, camera, width, height) + return rgb, self._renderer.render_depth(data, camera, width, height) if depth else None def close(self): - # TODO: this could deregister camera callbacks in simulation - pass - - @property - def camera_names(self) -> list[str]: - """Should return a list of the activated human readable names of the cameras.""" - return list(self.cameras.keys()) - - @property - def name_to_identifier(self) -> dict[str, str]: - return {name: cfg.identifier for name, cfg in self.cameras.items()} - + self._renderer.close() -class FilamentSimCameraSet: - """Set of simulation cameras rendered with MuJoCo's Filament renderer (MuJoCo >= 4.0). - Implements BaseCameraSet - Color and depth images come from Filament. Depth images are always metric (scaled by - ``BaseCameraSet.DEPTH_SCALE``), regardless of ``physical_units``. The depth pass is a second - Filament render per camera, set ``render_depth=False`` (done automatically by - ``CameraSetWrapper(include_depth=False)``) to skip it; frames then have ``depth=None``. - - Rendering happens in Python when frames are requested, i.e. always "on demand"; rendering at a - fixed camera frame rate while the simulation steps is not supported with this backend. +class SimCameraSet: + """Set of cameras in a MuJoCo simulation, implements BaseCameraSet. + + Rendering uses MuJoCo's classic OpenGL renderer, or Filament if the simulation was configured with + ``SimConfig(renderer=RendererBackend.FILAMENT)`` (constructing this class then returns a + :class:`FilamentSimCameraSet`). + + Args: + simulation: the simulation to render. + cameras: camera configurations by name. + physical_units: depth in meters (scaled by ``BaseCameraSet.DEPTH_SCALE``); otherwise the raw + [0, 1] depth buffer of the classic renderer is scaled. + render_on_demand: if True, frames show the simulation state at the time they are requested. + If False, they show the state at the last exposure of each camera according to its + ``frame_rate``, which the simulation captures while it steps, see module docstring. + max_buffer_frames: number of rendered framesets (``render_on_demand=True``) or captured states + per frame rate (``render_on_demand=False``) that are kept for ``get_timestamp_frames``. + render_depth: render depth images; frames have ``depth=None`` otherwise. Set automatically by + ``CameraSetWrapper(include_depth=...)``. """ DEPTH_SCALE: int = BaseCameraSet.DEPTH_SCALE + def __new__(cls, simulation: sim.Sim, *_args, **_kwargs): + if cls is SimCameraSet and simulation.get_config().renderer == RendererBackend.FILAMENT: + return super().__new__(FilamentSimCameraSet) + return super().__new__(cls) + def __init__( self, simulation: sim.Sim, cameras: dict[str, SimCameraConfig], - physical_units: bool = True, + physical_units: bool = False, render_on_demand: bool = True, max_buffer_frames: int = 100, render_depth: bool = True, ): - filament.require("FilamentSimCameraSet") - if not physical_units: - logger.warning("FilamentSimCameraSet always returns metric depth; physical_units=False is ignored.") - if not render_on_demand: - logger.warning("FilamentSimCameraSet always renders on demand; render_on_demand=False is ignored.") if max_buffer_frames <= 0: msg = "max_buffer_frames must be positive" raise ValueError(msg) self._sim = simulation self.cameras = cameras self.physical_units = physical_units - self.render_on_demand = True + self.render_on_demand = render_on_demand self.render_depth = render_depth - self._buffer: list[FrameSet] = [] self._max_buffer_frames = max_buffer_frames + self._renderer = self._create_renderer() - self._renderer = filament.FilamentRenderer(self._sim.model) + model = self._sim.model + self._render_data = mujoco.MjData(model) + self._state = np.empty(mujoco.mj_stateSize(model, STATE_SPEC)) self._mj_cameras: dict[str, mujoco.MjvCamera] = {} for name, cfg in cameras.items(): cam = mujoco.MjvCamera() if cfg.type == CameraType.default_free: - mujoco.mjv_defaultFreeCamera(self._sim.model, cam) + mujoco.mjv_defaultFreeCamera(model, cam) else: cam.type = int(cfg.type) - cam.fixedcamid = _camera_id(self._sim.model, cfg) + cam.fixedcamid = _camera_id(model, cfg) self._mj_cameras[name] = cam - def _render(self) -> FrameSet: - model, data = self._sim.model, self._sim.data - timestamp = data.time + # render_on_demand=True: rendered framesets, newest last + self._buffer: deque[FrameSet] = deque(maxlen=max_buffer_frames) + self._buffer_states: deque[np.ndarray] = deque(maxlen=max_buffer_frames) + # render_on_demand=False: one state capture per frame rate and the cameras using it + self._captures: dict[int, list[str]] = {} + # rendered frames of captured states by (capture id, time stamp) + self._capture_frames: dict[tuple[int, float], dict[str, Frame]] = {} + if not render_on_demand: + by_rate: dict[int, list[str]] = {} + for name, cfg in cameras.items(): + by_rate.setdefault(cfg.frame_rate, []).append(name) + for frame_rate, names in by_rate.items(): + capture_id = self._sim.register_state_capture(frame_rate, max_buffer_frames, int(STATE_SPEC)) + self._captures[capture_id] = names + + def _create_renderer(self) -> _ClassicRenderer | _FilamentRenderer: + return _ClassicRenderer(self._sim.model, self.physical_units) + + def _load_state(self, state: np.ndarray): + """Loads a state into the render data and computes what rendering needs from it.""" + model, data = self._sim.model, self._render_data + mujoco.mj_setState(model, data, state, STATE_SPEC) + mujoco.mj_kinematics(model, data) + mujoco.mj_camlight(model, data) + if model.ntendon: + mujoco.mj_tendon(model, data) + if model.nflex: + mujoco.mj_flex(model, data) self._renderer.update(data) + + def _render(self, names: list[str]) -> dict[str, Frame]: + """Renders the given cameras from the render data.""" + model, data = self._sim.model, self._render_data + timestamp = data.time frames: dict[str, Frame] = {} - for name, cfg in self.cameras.items(): - color = self._renderer.render(data, self._mj_cameras[name], cfg.resolution_width, cfg.resolution_height) + for name in names: + cfg = self.cameras[name] + color, depth = self._renderer.render( + data, self._mj_cameras[name], cfg.resolution_width, cfg.resolution_height, self.render_depth + ) intrinsics = _intrinsics(model, cfg) extrinsics = _extrinsics(model, data, cfg) depth_frame = None - if self.render_depth: - depth = self._renderer.render_depth( - data, self._mj_cameras[name], cfg.resolution_width, cfg.resolution_height - )[..., np.newaxis] + if depth is not None: depth_frame = DataFrame( - data=(depth * BaseCameraSet.DEPTH_SCALE).astype(np.uint16), + data=(depth[..., np.newaxis] * BaseCameraSet.DEPTH_SCALE).astype(np.uint16), timestamp=timestamp, intrinsics=intrinsics, extrinsics=extrinsics, @@ -248,43 +276,103 @@ def _render(self) -> FrameSet: ), avg_timestamp=timestamp, ) - return FrameSet(frames=frames, avg_timestamp=timestamp) - - def buffer_size(self) -> int: - return len(self._buffer) + return frames - def clear_buffer(self): - self._buffer.clear() + def _captured_frames(self, max_timestamp: float) -> FrameSet | None: + frames: dict[str, Frame] = {} + for capture_id, names in self._captures.items(): + captured = self._sim.get_captured_state(capture_id, max_timestamp) + if captured is None: + return None + key = (capture_id, captured.timestamp) + if key not in self._capture_frames: + self._load_state(captured.state) + self._capture_frames[key] = self._render(names) + # keep as many rendered frames as captured states + while len(self._capture_frames) > self._max_buffer_frames * len(self._captures): + del self._capture_frames[next(iter(self._capture_frames))] + frames.update(self._capture_frames[key]) + timestamps = [frame.avg_timestamp for frame in frames.values() if frame.avg_timestamp is not None] + return FrameSet(frames=frames, avg_timestamp=float(np.mean(timestamps)) if timestamps else None) def get_latest_frames(self) -> FrameSet | None: - """Renders all cameras for the current simulation state and returns the frames.""" - if self._buffer and self._buffer[-1].avg_timestamp == self._sim.data.time: + """Frames of the current simulation state, or of the last exposures (``render_on_demand=False``).""" + if not self.render_on_demand: + return self._captured_frames(math.inf) + mujoco.mj_getState(self._sim.model, self._sim.data, self._state, STATE_SPEC) + if self._buffer_states and np.array_equal(self._buffer_states[-1], self._state): return self._buffer[-1] - frameset = self._render() + self._load_state(self._state) + frames = self._render(list(self.cameras)) + frameset = FrameSet(frames=frames, avg_timestamp=self._render_data.time) self._buffer.append(frameset) - del self._buffer[: -self._max_buffer_frames] + self._buffer_states.append(self._state.copy()) return frameset def get_timestamp_frames(self, ts: datetime) -> FrameSet | None: - """Returns the most recent buffered frames with a simulation time <= ts.""" + """Most recent frames with a simulation time <= ts.""" + if not self.render_on_demand: + return self._captured_frames(ts.timestamp()) for frameset in reversed(self._buffer): if frameset.avg_timestamp is not None and frameset.avg_timestamp <= ts.timestamp(): return frameset return None + def buffer_size(self) -> int: + if not self.render_on_demand: + return min(self._sim.captured_state_count(capture_id) for capture_id in self._captures) + return len(self._buffer) + + def clear_buffer(self): + self._buffer.clear() + self._buffer_states.clear() + self._capture_frames.clear() + for capture_id in self._captures: + self._sim.clear_captured_states(capture_id) + def calibrate(self) -> bool: return True def config(self, camera_name: str) -> SimCameraConfig: + """Should return the configuration of the camera with the given name.""" return self.cameras[camera_name] def close(self): + # the state captures keep running in the simulation, they are cheap (no rendering) self._renderer.close() @property def camera_names(self) -> list[str]: + """Should return a list of the activated human readable names of the cameras.""" return list(self.cameras.keys()) @property def name_to_identifier(self) -> dict[str, str]: return {name: cfg.identifier for name, cfg in self.cameras.items()} + + +class FilamentSimCameraSet(SimCameraSet): + """Set of simulation cameras rendered with MuJoCo's Filament renderer (MuJoCo >= 4.0). + + Same as :class:`SimCameraSet`, except that depth images are always metric (scaled by + ``BaseCameraSet.DEPTH_SCALE``), regardless of ``physical_units``. The depth pass is a second + Filament render per camera, set ``render_depth=False`` (done automatically by + ``CameraSetWrapper(include_depth=False)``) to skip it. + """ + + def __init__( + self, + simulation: sim.Sim, + cameras: dict[str, SimCameraConfig], + physical_units: bool = True, + render_on_demand: bool = True, + max_buffer_frames: int = 100, + render_depth: bool = True, + ): + filament.require("FilamentSimCameraSet") + if not physical_units: + logger.warning("FilamentSimCameraSet always returns metric depth; physical_units=False is ignored.") + super().__init__(simulation, cameras, True, render_on_demand, max_buffer_frames, render_depth) + + def _create_renderer(self) -> _ClassicRenderer | _FilamentRenderer: + return _FilamentRenderer(self._sim.model) diff --git a/python/rcs/sim/render_context_bootstrap.py b/python/rcs/sim/render_context_bootstrap.py index ff1bb065e..b706b40e1 100644 --- a/python/rcs/sim/render_context_bootstrap.py +++ b/python/rcs/sim/render_context_bootstrap.py @@ -1,23 +1,16 @@ """ -Bootstrap an offscreen GL render context and register it with the C++ backend. +Bootstrap the offscreen GL render context used by the classic renderer (python/rcs/camera/sim.py). Two backends are supported, selected by platform: -- Linux: load libEGL via ctypes, create a persistent MuJoCo EGL ``GLContext``, - and hand its ``eglMakeCurrent`` / display / context to C++ (the ``egl`` - backend). -- macOS: there is no libEGL. Create a persistent MuJoCo ``GLContext`` and make - it current on this thread; C++ then treats ``ensure_current()`` as a no-op - (the ``current_context`` backend). +- Linux: create a persistent MuJoCo EGL ``GLContext`` (headless). +- macOS: there is no libEGL. Create a persistent MuJoCo ``GLContext``. -The initialized state is held in a module-level ``_state`` (references keep the -library and context from being garbage-collected). Call ``bootstrap()`` to -complete initialization. +Rendering code calls ``make_current()`` before using the context. The initialized state is held in a +module-level ``_state`` (references keep the context from being garbage-collected). """ -import ctypes import ctypes.util -import os import sys from dataclasses import dataclass from typing import Any @@ -28,12 +21,8 @@ class _RenderBackend: backend: str = "none" # "none" | "egl" | "current_context" available: bool = False error: str | None = None - # references kept so the GL context / EGL library are not garbage-collected + # reference kept so the GL context is not garbage-collected gl_context: Any = None - egl_lib: Any = None - addr_make_current: int | None = None - egl_display: int | None = None - egl_context: int | None = None def _init_current_context() -> _RenderBackend: @@ -48,26 +37,14 @@ def _init_current_context() -> _RenderBackend: def _init_egl() -> _RenderBackend: - """Linux/other: load libEGL and create a persistent MuJoCo EGL GLContext.""" - name = ctypes.util.find_library("EGL") - if name is None: + """Linux/other: create a persistent MuJoCo EGL GLContext.""" + if ctypes.util.find_library("EGL") is None: return _RenderBackend(error="Could not find libEGL via ctypes.util.find_library('EGL').") try: - import mujoco.egl from mujoco.egl import GLContext - egl_lib = ctypes.CDLL(name, mode=os.RTLD_LOCAL | os.RTLD_NOW) - addr_make_current = ctypes.cast(egl_lib.eglMakeCurrent, ctypes.c_void_p).value ctx = GLContext(max_width=3840, max_height=2160) - return _RenderBackend( - backend="egl", - available=True, - gl_context=ctx, - egl_lib=egl_lib, - addr_make_current=addr_make_current, - egl_display=int(mujoco.egl.EGL_DISPLAY.address), - egl_context=int(ctx._context.address), - ) + return _RenderBackend(backend="egl", available=True, gl_context=ctx) except Exception as exc: return _RenderBackend(error=f"Failed to initialize MuJoCo EGL context: {exc!r}") @@ -100,19 +77,3 @@ def make_current(): require() assert _state.gl_context is not None _state.gl_context.make_current() - - -def bootstrap(): - if not _state.available: - return - import rcs._core as _cxx - - if _state.backend == "current_context": - assert _state.gl_context is not None - _state.gl_context.make_current() - _cxx.common._bootstrap_gl_context() - elif _state.backend == "egl": - assert _state.addr_make_current is not None - assert _state.egl_display is not None - assert _state.egl_context is not None - _cxx.common._bootstrap_egl_context(_state.addr_make_current, _state.egl_display, _state.egl_context) diff --git a/python/rcs/sim/sim.py b/python/rcs/sim/sim.py index 891e0f142..4612b5b34 100644 --- a/python/rcs/sim/sim.py +++ b/python/rcs/sim/sim.py @@ -19,11 +19,10 @@ from rcs._core.sim import DynamicJointSchema, DynamicJointState from rcs._core.sim import GuiClient as _GuiClient from rcs._core.sim import Sim as _Sim -from rcs.sim import RendererBackend, SimConfig, filament, render_context_bootstrap +from rcs.sim import RendererBackend, SimConfig, filament from rcs.sim.composer import ModelComposer from rcs.utils import SimpleFrameRate -render_context_bootstrap.bootstrap() logger = getLogger(__name__) diff --git a/python/tests/test_sim_camera.py b/python/tests/test_sim_camera.py index 59aa7817f..99dde804b 100644 --- a/python/tests/test_sim_camera.py +++ b/python/tests/test_sim_camera.py @@ -2,14 +2,13 @@ import mujoco import numpy as np -from rcs.camera.sim import SimCameraSet +import pytest +from rcs.camera.sim import STATE_SPEC, SimCameraSet from rcs.envs.configs import EmptyWorldDroid from rcs.sim import SimConfig from rcs import sim -STATE_SPEC = mujoco.mjtState.mjSTATE_INTEGRATION - def _render(camera_cfgs) -> dict[str, np.ndarray]: scene = EmptyWorldDroid() @@ -85,3 +84,50 @@ def test_state_capture_restarts_on_reset(): captured = simulation.get_captured_state(capture) assert captured is not None assert captured.timestamp == 0 + + +def test_frames_show_last_exposure(): + simulation, camera_cfgs = _droid_sim() + dt = simulation.model.opt.timestep + name = next(iter(camera_cfgs)) + cfg = camera_cfgs[name] + period = 1 / cfg.frame_rate + exposed = SimCameraSet(simulation, {name: cfg}, physical_units=True, render_on_demand=False) + live = SimCameraSet(simulation, {name: cfg}, physical_units=True) + simulation.data.ctrl[:] = 0.5 + + # step to just after an exposure: the exposure is the live state at that time + simulation.step(round(3 * period / dt)) + live_at_exposure = live.get_latest_frames() + exposed_frames = exposed.get_latest_frames() + assert live_at_exposure is not None + assert exposed_frames is not None + assert exposed_frames.avg_timestamp == pytest.approx(live_at_exposure.avg_timestamp) + exposure = exposed_frames.frames[name].camera + live_frame = live_at_exposure.frames[name].camera + assert np.abs(exposure.color.data.astype(int) - live_frame.color.data.astype(int)).max() <= 1 + assert exposure.depth is not None + assert live_frame.depth is not None + assert np.array_equal(exposure.depth.data, live_frame.depth.data) + assert exposure.color.extrinsics is not None + assert np.allclose(exposure.color.extrinsics, live_frame.color.extrinsics) # type: ignore[arg-type] + + # until the next exposure, the frames do not change while the live state does + simulation.step(round(0.5 * period / dt)) + later = exposed.get_latest_frames() + assert later is not None + assert later.avg_timestamp == exposed_frames.avg_timestamp + assert later.frames[name] is exposed_frames.frames[name] + later_live = live.get_latest_frames() + assert later_live is not None + assert later_live.avg_timestamp is not None + assert later.avg_timestamp is not None + assert later_live.avg_timestamp > later.avg_timestamp + + # after the next exposure, new frames are rendered + simulation.step(round(0.6 * period / dt)) + newer = exposed.get_latest_frames() + assert newer is not None + assert newer.avg_timestamp == pytest.approx(4 * period, abs=dt) + exposed.close() + live.close() diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 60879f6ad..6b6428a02 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -257,9 +257,6 @@ PYBIND11_MODULE(_core, m) { // COMMON MODULE auto common = m.def_submodule("common", "common module"); - common.def("_bootstrap_egl_context", &rcs::common::bootstrap_egl_context, - py::arg("fn_addr"), py::arg("display"), py::arg("context")); - common.def("_bootstrap_gl_context", &rcs::common::bootstrap_gl_context); common.def("IdentityTranslation", &rcs::common::IdentityTranslation); common.def("IdentityRotMatrix", &rcs::common::IdentityRotMatrix); common.def("IdentityRotQuatVec", &rcs::common::IdentityRotQuatVec); @@ -972,37 +969,6 @@ PYBIND11_MODULE(_core, m) { .def("__deepcopy__", [](const rcs::sim::SimCameraConfig& self, py::dict) { return rcs::sim::SimCameraConfig(self); }); - py::class_(sim, "FrameSet") - .def(py::init( - [](const std::unordered_map& - color_frames, - const std::unordered_map& - depth_frames, - double timestamp) { - rcs::sim::FrameSet fs; - fs.color_frames = color_frames; - fs.depth_frames = depth_frames; - fs.timestamp = timestamp; - return fs; - }), - py::arg("color_frames"), py::arg("depth_frames"), - py::arg("timestamp")) - .def_readonly("color_frames", &rcs::sim::FrameSet::color_frames) - .def_readonly("depth_frames", &rcs::sim::FrameSet::depth_frames) - .def_readonly("timestamp", &rcs::sim::FrameSet::timestamp); - py::class_(sim, "SimCameraSet") - .def(py::init, - std::unordered_map, - bool, int>(), - py::arg("sim"), py::arg("cameras"), - py::arg("render_on_demand") = true, - py::arg("max_buffer_frames") = 100) - .def("buffer_size", &rcs::sim::SimCameraSet::buffer_size) - .def("clear_buffer", &rcs::sim::SimCameraSet::clear_buffer) - .def("get_latest_frameset", &rcs::sim::SimCameraSet::get_latest_frameset) - .def_property_readonly("_sim", &rcs::sim::SimCameraSet::get_sim) - .def("get_timestamp_frameset", - &rcs::sim::SimCameraSet::get_timestamp_frameset, py::arg("ts")); py::class_(sim, "GuiClient") .def(py::init(), py::arg("id")) .def("get_model_bytes", diff --git a/src/rcs/CMakeLists.txt b/src/rcs/CMakeLists.txt index 56391f749..bd1eb07b1 100644 --- a/src/rcs/CMakeLists.txt +++ b/src/rcs/CMakeLists.txt @@ -6,7 +6,7 @@ endif() add_library(rcs SHARED) target_include_directories(rcs PUBLIC ${CMAKE_SOURCE_DIR}/include) -target_sources(rcs PRIVATE Pose.cpp Robot.cpp Kinematics.cpp utils.cpp) +target_sources(rcs PRIVATE Pose.cpp Robot.cpp Kinematics.cpp) target_link_libraries(rcs PUBLIC Eigen3::Eigen pinocchio::all) set_target_properties(rcs PROPERTIES INSTALL_RPATH "${_rpath_origin};${_rpath_origin}/../cmeel.prefix/lib" diff --git a/src/rcs/utils.cpp b/src/rcs/utils.cpp deleted file mode 100644 index 630d850fa..000000000 --- a/src/rcs/utils.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include "rcs/utils.h" - -#include - -#include - -namespace rcs { -namespace common { -enum class RenderBackend { none, egl, current_context }; - -static RenderBackend g_backend = RenderBackend::none; -static PFNEGLMAKECURRENTPROC g_makeCurrent = nullptr; -static EGLDisplay g_display = EGL_NO_DISPLAY; -static EGLSurface g_surface = EGL_NO_SURFACE; -static EGLContext g_context = EGL_NO_CONTEXT; - -void bootstrap_egl_context(uintptr_t fn_addr, uintptr_t dpy, uintptr_t ctx) { - g_makeCurrent = reinterpret_cast(fn_addr); - g_display = reinterpret_cast(dpy); - g_context = reinterpret_cast(ctx); - g_backend = RenderBackend::egl; -} - -void bootstrap_gl_context() { g_backend = RenderBackend::current_context; } - -void ensure_current() { - switch (g_backend) { - case RenderBackend::current_context: - return; - case RenderBackend::egl: - if (!g_makeCurrent(g_display, g_surface, g_surface, g_context)) - throw std::runtime_error("eglMakeCurrent failed"); - return; - case RenderBackend::none: - default: - throw std::runtime_error( - "Rendering was requested, but no render backend was bootstrapped. " - "This usually means libEGL or the MuJoCo GL context is unavailable. " - "Run without cameras/viewers if you do not need rendering, or " - "install " - "the required system EGL/OpenGL runtime libraries."); - } -} -} // namespace common -} // namespace rcs diff --git a/src/sim/CMakeLists.txt b/src/sim/CMakeLists.txt index 5c57a61c9..48ac27199 100644 --- a/src/sim/CMakeLists.txt +++ b/src/sim/CMakeLists.txt @@ -1,6 +1,6 @@ add_library(sim) target_sources(sim - PRIVATE sim.cpp SimRobot.cpp renderer.cpp camera.cpp SimGripper.cpp SimTilburgHand.cpp gui_server.cpp gui_client.cpp + PRIVATE sim.cpp SimRobot.cpp SimGripper.cpp SimTilburgHand.cpp gui_server.cpp gui_client.cpp ) target_link_libraries(sim PUBLIC rcs MuJoCo::MuJoCo) diff --git a/src/sim/camera.cpp b/src/sim/camera.cpp deleted file mode 100644 index 0d9410eff..000000000 --- a/src/sim/camera.cpp +++ /dev/null @@ -1,159 +0,0 @@ - -#include "sim/camera.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "mujoco/mjdata.h" -#include "mujoco/mjmodel.h" -#include "mujoco/mujoco.h" -#include "rcs/Robot.h" - -namespace rcs { -namespace sim { - -SimCameraSet::SimCameraSet( - std::shared_ptr sim, - std::unordered_map cameras_cfg, - bool render_on_demand, int max_buffer_frames) - : sim{sim}, - cameras_cfg{cameras_cfg}, - buffer{}, - buffer_lock{}, - cameras{}, - render_on_demand{render_on_demand}, - max_buffer_frames{max_buffer_frames} { - if (this->max_buffer_frames <= 0) { - throw std::invalid_argument("max_buffer_frames must be positive"); - } - buffer.resize(this->max_buffer_frames); - for (auto const& [id, cam] : cameras_cfg) { - this->sim->register_rendering_callback( - [this](const std::string& id, mjrContext& ctx, mjvScene& scene, - mjvOption& opt) { this->frame_callback(id, ctx, scene, opt); }, - id, cam.frame_rate, cam.resolution_width, cam.resolution_height); - - mjvCamera mjcam; - mjv_defaultCamera(&mjcam); - - if (cam.type == CameraType::default_free) { - mjv_defaultFreeCamera(this->sim->m, &mjcam); - } else { - mjcam.type = cam.type; - mjcam.fixedcamid = - mj_name2id(this->sim->m, mjOBJ_CAMERA, cam.identifier.c_str()); - } - cameras[id] = mjcam; - } -} - -SimCameraSet::~SimCameraSet() {} -int SimCameraSet::buffer_size() { - std::lock_guard lock(buffer_lock); - return buffer_len; -} -void SimCameraSet::clear_buffer() { - std::lock_guard lock(buffer_lock); - // when we clear the buffer, there is no last image timestep - this->last_ts = 0; - this->next_ring_index = 0; - this->buffer_len = 0; - std::fill(buffer.begin(), buffer.end(), std::nullopt); -} - -std::optional SimCameraSet::get_latest_frameset() { - if (this->render_on_demand) { - this->render_all(); - } - std::lock_guard lock(buffer_lock); - if (buffer_len == 0) { - return std::nullopt; - } - int idx = (next_ring_index - 1 + max_buffer_frames) % max_buffer_frames; - return buffer[idx]; -} -std::optional SimCameraSet::get_timestamp_frameset(float ts) { - std::lock_guard lock(buffer_lock); - for (int i = 0; i < buffer_len; ++i) { - int idx = (next_ring_index - i - 1 + max_buffer_frames) % max_buffer_frames; - if (buffer[idx].has_value() && buffer[idx]->timestamp <= ts) { - return buffer[idx]; - } - } - return std::nullopt; -} - -void SimCameraSet::render_all() { - for (auto const& [id, cam] : this->cameras_cfg) { - mjrContext* ctx = this->sim->renderer.get_context(id); - this->render_single(id, *ctx, this->sim->renderer.scene, - this->sim->renderer.opt); - } -} - -void SimCameraSet::frame_callback(const std::string& id, mjrContext& ctx, - mjvScene& scene, mjvOption& opt) { - if (!this->render_on_demand) { - this->render_single(id, ctx, scene, opt); - } -} - -void SimCameraSet::render_single(const std::string& id, mjrContext& ctx, - mjvScene& scene, mjvOption& opt) { - mjrRect viewport = mjr_maxViewport(&ctx); - int W = viewport.width; - int H = viewport.height; - - // allocate rgb and depth buffers - ColorFrame frame = ColorFrame::Zero(3 * W * H); - DepthFrame depth = DepthFrame::Zero(1 * W * H); - // update abstract scene - // The scene is shared by all cameras and mjv_updateScene positions infinite - // planes (e.g. the floor) from scene.camera *before* it updates the camera, - // i.e. from the previously rendered camera. Update the camera first so that - // images do not depend on the render order of the cameras. - mjv_updateCamera(this->sim->m, this->sim->d, &this->cameras[id], &scene); - mjv_updateScene(this->sim->m, this->sim->d, &opt, NULL, &this->cameras[id], - mjCAT_ALL, &scene); - - // render scene in offscreen buffer - mjr_render(viewport, &scene, &ctx); - - // read rgb and depth buffers - // depth documentation can be found here: - // https://registry.khronos.org/OpenGL-Refpages/gl4/html/glReadPixels.xhtml - mjr_readPixels(frame.data(), depth.data(), viewport, &ctx); - - auto ts = this->sim->d->time; - std::lock_guard lock(buffer_lock); - // The following code assumes that all render callbacks for a timestep - // happen directly after each other - if (this->last_ts == ts && this->buffer_len > 0) { - int latest_idx = (this->next_ring_index - 1 + this->max_buffer_frames) % - this->max_buffer_frames; - buffer[latest_idx]->color_frames[id] = frame; - buffer[latest_idx]->depth_frames[id] = depth; - } else { - FrameSet fs; - fs.timestamp = ts; - fs.color_frames[id] = frame; - fs.depth_frames[id] = depth; - buffer[this->next_ring_index] = std::move(fs); - this->next_ring_index = - (this->next_ring_index + 1) % this->max_buffer_frames; - this->buffer_len = std::min(this->buffer_len + 1, this->max_buffer_frames); - this->last_ts = ts; - } -} - -} // namespace sim -} // namespace rcs diff --git a/src/sim/camera.h b/src/sim/camera.h index 3750c86da..875bf76a9 100644 --- a/src/sim/camera.h +++ b/src/sim/camera.h @@ -1,18 +1,8 @@ #ifndef RCS_CAMSIM_H #define RCS_CAMSIM_H #include -#include -#include - -#include -#include -#include -#include -#include -#include #include "rcs/Camera.h" -#include "sim/sim.h" namespace rcs { namespace sim { @@ -28,49 +18,6 @@ struct SimCameraConfig : common::BaseCameraConfig { CameraType type; }; -// (H,W,3) -typedef Eigen::Matrix ColorFrame; -typedef Eigen::Matrix DepthFrame; - -struct FrameSet { - std::unordered_map color_frames; - std::unordered_map depth_frames; - mjtNum timestamp; -}; - -class SimCameraSet { - public: - SimCameraSet(std::shared_ptr sim, - std::unordered_map cameras, - bool render_on_demand = true, int max_buffer_frames = 100); - ~SimCameraSet(); - - int buffer_size(); - void clear_buffer(); - - std::optional get_latest_frameset(); - std::optional get_timestamp_frameset(float ts); - - void frame_callback(const std::string& id, mjrContext& ctx, mjvScene& scene, - mjvOption& opt); - - std::shared_ptr get_sim() { return sim; } - bool render_on_demand; - - private: - std::shared_ptr sim; - std::unordered_map cameras_cfg; - std::vector> buffer; - std::unordered_map cameras; - std::mutex buffer_lock; - int max_buffer_frames; - int next_ring_index = 0; - int buffer_len = 0; - mjtNum last_ts = 0; - void render_all(); - void render_single(const std::string& id, mjrContext& ctx, mjvScene& scene, - mjvOption& opt); -}; } // namespace sim } // namespace rcs #endif // RCS_CAMSIM_H diff --git a/src/sim/renderer.cpp b/src/sim/renderer.cpp deleted file mode 100644 index 9e5e87a43..000000000 --- a/src/sim/renderer.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include -#include - -#include -#include - -#include "rcs/utils.h" -#include "sim/sim.h" -namespace rcs { -namespace sim { - -Renderer::Renderer(mjModel* m) : m{m} { - mjv_defaultOption(&this->opt); - mjv_defaultScene(&this->scene); - size_t max_geoms = 2000; - mjv_makeScene(this->m, &this->scene, max_geoms); - this->ctxs = std::unordered_map(); -} - -Renderer::~Renderer() { - for (auto const& [id, ctx] : this->ctxs) { - mjr_freeContext(ctx); - } - mjv_freeScene(&this->scene); -} - -void Renderer::register_context(const std::string& id, size_t width, - size_t height) { - common::ensure_current(); - mjrContext* ctx = new mjrContext(); - mjr_defaultContext(ctx); - mjr_makeContext(this->m, ctx, 200); - mjr_setBuffer(mjFB_OFFSCREEN, ctx); - mjr_resizeOffscreen(width, height, ctx); - if (ctx->currentBuffer != mjFB_OFFSCREEN) { - std::cout << "Warning: offscreen rendering not supported, using " - "default/window framebuffer" - << std::endl; - } - this->ctxs[id] = ctx; -} - -mjrContext* Renderer::get_context(const std::string& id) { - common::ensure_current(); - mjr_setBuffer(mjFB_OFFSCREEN, this->ctxs[id]); - return this->ctxs[id]; -} -} // namespace sim -} // namespace rcs diff --git a/src/sim/sim.cpp b/src/sim/sim.cpp index f55e49f63..775912a5f 100644 --- a/src/sim/sim.cpp +++ b/src/sim/sim.cpp @@ -85,7 +85,7 @@ void Sim::init_dynamic_joint_specs() { } } -Sim::Sim(mjModel* m, mjData* d) : m(m), d(d), renderer(m) { +Sim::Sim(mjModel* m, mjData* d) : m(m), d(d) { this->init_dynamic_joint_specs(); }; @@ -121,26 +121,6 @@ bool Sim::invoke_condition_callbacks() { return false; } -void Sim::invoke_rendering_callbacks() { - // bool scene_updated = false; - for (size_t i = 0; i < std::size(this->rendering_callbacks); ++i) { - RenderingCallback& cb = this->rendering_callbacks[i]; - mjtNum dt = this->d->time - cb.last_call_timestamp; - if (dt > cb.seconds_between_calls) { - // if (!scene_updated) { - // // update scene once for all cameras - // mjv_updateScene(this->m, this->d, &this->renderer.opt, NULL, NULL, - // mjCAT_ALL, - // &this->renderer.scene); - // scene_updated = true; - // } - mjrContext* ctx = this->renderer.get_context(cb.id); - cb.cb(cb.id, *ctx, this->renderer.scene, this->renderer.opt); - cb.last_call_timestamp = this->d->time; - } - } -} - void Sim::capture_state(StateCapture& capture) { mj_getState(this->m, this->d, capture.states.data() + capture.next_index * capture.state_size, @@ -211,7 +191,6 @@ void Sim::step(size_t k) { this->invoke_callbacks(); mj_step2(this->m, this->d); this->invoke_state_captures(); - this->invoke_rendering_callbacks(); } } @@ -358,12 +337,6 @@ void Sim::reset_callbacks() { for (size_t i = 0; i < std::size(this->all_callbacks); ++i) { this->all_callbacks[i].last_call_timestamp = 0; } - for (size_t i = 0; i < std::size(this->rendering_callbacks); ++i) { - // this is negative so that we will directly render the cameras - // in the first step - this->rendering_callbacks[i].last_call_timestamp = - -this->rendering_callbacks[i].seconds_between_calls; - } for (StateCapture& capture : this->state_captures) { this->restart_state_capture(capture); } @@ -386,24 +359,6 @@ void Sim::register_all_cb(std::function cb, ConditionCallback{cb, seconds_between_calls, 0.0, false}); } -void Sim::register_rendering_callback( - std::function - cb, - const std::string& id, int frame_rate, size_t width, size_t height) { - this->renderer.register_context(id, width, height); - // in case frame_rate is zero, rendering needs to be triggered - // manually - if (frame_rate != 0) { - this->rendering_callbacks.push_back( - RenderingCallback{.cb = cb, - .id = id, - .seconds_between_calls = 1.0 / frame_rate, - // this is negative so that we will directly render - // the cameras in the first step - .last_call_timestamp = -1.0 / frame_rate}); - } -} - size_t Sim::register_state_capture(double frame_rate, size_t buffer_size, int state_spec) { if (frame_rate <= 0) { diff --git a/src/sim/sim.h b/src/sim/sim.h index 59849dd8c..cbc2b0255 100644 --- a/src/sim/sim.h +++ b/src/sim/sim.h @@ -15,21 +15,7 @@ namespace rcs { namespace sim { -class Renderer { - public: - Renderer(mjModel* m); - ~Renderer(); - void register_context(const std::string& id, size_t width, size_t height); - mjrContext* get_context(const std::string& id); - mjvScene scene; - mjvOption opt; - - private: - mjModel* m; - std::unordered_map ctxs; -}; - -// Filament renderer is implemented in python +// Both renderers are implemented in python, see python/rcs/camera/sim.py enum class RendererBackend { CLASSIC, FILAMENT }; struct SimConfig { @@ -58,15 +44,6 @@ struct ConditionCallback { bool last_return_value; }; -struct RenderingCallback { - const std::function - cb; - const std::string id; // rendering context id in renderer class - mjtNum seconds_between_calls; // in seconds - mjtNum last_call_timestamp; // in seconds -}; - /* Simulation states captured at a fixed rate of simulation time, e.g. at the * exposure times of a camera, so that they can be rendered later. Kept in a * ring buffer of the most recent states. */ @@ -114,13 +91,11 @@ class Sim { std::vector callbacks; std::vector any_callbacks; std::vector all_callbacks; - std::vector rendering_callbacks; std::vector state_captures; std::vector dynamic_joint_specs; std::unordered_map dynamic_joint_name_to_index; void invoke_callbacks(); bool invoke_condition_callbacks(); - void invoke_rendering_callbacks(); void invoke_state_captures(); void capture_state(StateCapture& capture); void restart_state_capture(StateCapture& capture); @@ -134,7 +109,6 @@ class Sim { public: // TODO: hide m & d, pass as parameter to callback (easier refactoring) - rcs::sim::Renderer renderer; mjModel* m; mjData* d; Sim(mjModel* m, mjData* d); @@ -161,11 +135,6 @@ class Sim { mjtNum seconds_between_calls); void register_all_cb(std::function cb, mjtNum seconds_between_calls); - void register_rendering_callback( - std::function - cb, - const std::string& id, int frame_rate, size_t width, size_t height); /* Captures the simulation state (mj_getState with state_spec) frame_rate * times per second of simulation time and keeps the latest buffer_size * states. The current state is captured right away. Captures follow a fixed From 44a8d56e7d13097dd235e4924ebe94056eda45eb Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 13 Nov 2026 13:03:33 -0800 Subject: [PATCH 13/16] ci: move macos jobs to macos-15 runners --- .github/workflows/build_wheels.yaml | 2 +- .github/workflows/ci.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build_wheels.yaml b/.github/workflows/build_wheels.yaml index 4099ed200..327e7165c 100644 --- a/.github/workflows/build_wheels.yaml +++ b/.github/workflows/build_wheels.yaml @@ -14,7 +14,7 @@ jobs: matrix: os: - ubuntu-latest - - macos-14 + - macos-15 steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index eb6bea24c..5ecb53f85 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -43,7 +43,7 @@ jobs: run: xvfb-run make pytest pythonpackage-macos: - runs-on: macos-14 + runs-on: macos-15 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} steps: From 60aeabfcc3abd89e180d452d904e4353ebbfbf60 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 12:00:12 -0800 Subject: [PATCH 14/16] fix(sim): call callbacks on a fixed schedule after integration Callbacks were called when more than seconds_between_calls had passed since their last call, so each period was rounded up to the next physics step and the calls drifted (e.g. 98 instead of 100 calls in 10 s at a 0.1 s interval and a 2 ms timestep). They also ran between mj_step1 and mj_step2, i.e. on a state that was not yet integrated. All callbacks now share the scheduling of the state captures: the k-th call is due at start + k * period and happens at the closest physics step, after integration. The schedule restarts on reset and whenever the simulation time goes backwards, which previously stopped callbacks until the time caught up again. The state capture is now a regular callback with a restart hook instead of a separate mechanism, and since nothing runs between the two step halves anymore, step uses mj_step. --- python/tests/test_sim_camera.py | 18 ++++ src/sim/sim.cpp | 174 +++++++++++++++++++------------- src/sim/sim.h | 66 +++++++----- 3 files changed, 160 insertions(+), 98 deletions(-) diff --git a/python/tests/test_sim_camera.py b/python/tests/test_sim_camera.py index 99dde804b..b69c205a6 100644 --- a/python/tests/test_sim_camera.py +++ b/python/tests/test_sim_camera.py @@ -86,6 +86,24 @@ def test_state_capture_restarts_on_reset(): assert captured.timestamp == 0 +def test_state_capture_restarts_when_time_goes_backwards(): + simulation, _ = _droid_sim() + dt = simulation.model.opt.timestep + capture = simulation.register_state_capture(30, 100, int(STATE_SPEC)) + simulation.step(100) + assert simulation.captured_state_count(capture) > 1 + # set the time back without reset, e.g. when a recorded state is restored + simulation.data.time = 0 + simulation.step(1) + assert simulation.captured_state_count(capture) == 1 + captured = simulation.get_captured_state(capture) + assert captured is not None + assert captured.timestamp == pytest.approx(dt) + # and the fixed schedule continues from there + simulation.step(round(1 / 30 / dt)) + assert simulation.captured_state_count(capture) == 2 + + def test_frames_show_last_exposure(): simulation, camera_cfgs = _droid_sim() dt = simulation.model.opt.timestep diff --git a/src/sim/sim.cpp b/src/sim/sim.cpp index 775912a5f..a55221fd9 100644 --- a/src/sim/sim.cpp +++ b/src/sim/sim.cpp @@ -14,17 +14,6 @@ namespace rcs { namespace sim { -void process_condition_callbacks(std::vector& cbs, - mjtNum time) { - for (int i = 0; i < std::size(cbs); ++i) { - mjtNum dt = time - cbs[i].last_call_timestamp; - if (dt > cbs[i].seconds_between_calls) { - cbs[i].last_return_value = cbs[i].cb(); - cbs[i].last_call_timestamp = time; - } - } -} - bool get_last_return_value(ConditionCallback cb) { return cb.last_return_value; } @@ -96,20 +85,72 @@ bool Sim::set_config(const SimConfig& cfg) { SimConfig Sim::get_config() { return this->cfg; } +Sim::Due Sim::poll(CallbackSchedule& schedule) { + mjtNum time = this->d->time; + if (time < schedule.last_check_time) { + // simulation time went backwards (e.g. the state was set externally) + return Due::restarted; + } + schedule.last_check_time = time; + // call at the physics step closest to the scheduled time + mjtNum half_step = 0.5 * this->m->opt.timestep; + if (time + half_step < schedule.next_call_time) { + return Due::no; + } + if (schedule.period <= 0) { + schedule.next_call_time = time; + } else { + // advance on the fixed schedule, skipping call times that fell into this + // step (rates above the physics rate) + while (schedule.next_call_time <= time + half_step) { + schedule.next_call_time += schedule.period; + } + } + return Due::yes; +} + +void Sim::restart(CallbackSchedule& schedule) { + schedule.next_call_time = this->d->time + schedule.period; + schedule.last_check_time = this->d->time; +} + +void Sim::restart(Callback& callback) { + this->restart(callback.schedule); + if (callback.on_restart) { + callback.on_restart(); + } +} + void Sim::invoke_callbacks() { - for (int i = 0; i < std::size(this->callbacks); ++i) { - Callback& cb = this->callbacks[i]; - mjtNum dt = this->d->time - cb.last_call_timestamp; - if (dt > cb.seconds_between_calls) { - cb.cb(); - cb.last_call_timestamp = this->d->time; + for (size_t i = 0; i < std::size(this->callbacks); ++i) { + switch (this->poll(this->callbacks[i].schedule)) { + case Due::yes: + this->callbacks[i].cb(); + break; + case Due::restarted: + this->restart(this->callbacks[i]); + break; + case Due::no: + break; } } } bool Sim::invoke_condition_callbacks() { - process_condition_callbacks(this->any_callbacks, this->d->time); - process_condition_callbacks(this->all_callbacks, this->d->time); + for (auto* cbs : {&this->any_callbacks, &this->all_callbacks}) { + for (ConditionCallback& cb : *cbs) { + switch (this->poll(cb.schedule)) { + case Due::yes: + cb.last_return_value = cb.cb(); + break; + case Due::restarted: + this->restart(cb.schedule); + break; + case Due::no: + break; + } + } + } if (std::any_of(this->any_callbacks.begin(), this->any_callbacks.end(), get_last_return_value)) { return true; @@ -121,7 +162,8 @@ bool Sim::invoke_condition_callbacks() { return false; } -void Sim::capture_state(StateCapture& capture) { +void Sim::capture_state(size_t id) { + StateCapture& capture = this->state_captures[id]; mj_getState(this->m, this->d, capture.states.data() + capture.next_index * capture.state_size, capture.state_spec); @@ -130,36 +172,6 @@ void Sim::capture_state(StateCapture& capture) { capture.size = std::min(capture.size + 1, capture.capacity); } -void Sim::restart_state_capture(StateCapture& capture) { - capture.next_index = 0; - capture.size = 0; - this->capture_state(capture); - capture.next_capture_time = this->d->time + capture.period; -} - -void Sim::invoke_state_captures() { - // capture at the physics step closest to the scheduled capture time - mjtNum half_step = 0.5 * this->m->opt.timestep; - for (StateCapture& capture : this->state_captures) { - size_t latest = - (capture.next_index + capture.capacity - 1) % capture.capacity; - if (capture.size > 0 && this->d->time < capture.timestamps[latest]) { - // simulation time went backwards (e.g. the state was reset externally) - this->restart_state_capture(capture); - continue; - } - if (this->d->time + half_step < capture.next_capture_time) { - continue; - } - this->capture_state(capture); - // advance on the fixed schedule, skipping capture times that fell into - // this step (frame rates above the physics rate) - while (capture.next_capture_time <= this->d->time + half_step) { - capture.next_capture_time += capture.period; - } - } -} - bool Sim::is_converged() { return this->converged; } void Sim::step_until_convergence() { this->convergence_steps = 0; @@ -187,10 +199,10 @@ void Sim::step_until_convergence() { void Sim::step(size_t k) { for (size_t i = 0; i < k; ++i) { - mj_step1(this->m, this->d); + mj_step(this->m, this->d); + // after integration, so that callbacks see a state consistent with its + // time stamp this->invoke_callbacks(); - mj_step2(this->m, this->d); - this->invoke_state_captures(); } } @@ -329,34 +341,45 @@ void Sim::set_dynamic_joint_state(const DynamicJointSchema& schema, void Sim::reset_callbacks() { for (size_t i = 0; i < std::size(this->callbacks); ++i) { - this->callbacks[i].last_call_timestamp = 0; - } - for (size_t i = 0; i < std::size(this->any_callbacks); ++i) { - this->any_callbacks[i].last_call_timestamp = 0; + this->restart(this->callbacks[i]); } - for (size_t i = 0; i < std::size(this->all_callbacks); ++i) { - this->all_callbacks[i].last_call_timestamp = 0; + for (auto* cbs : {&this->any_callbacks, &this->all_callbacks}) { + for (ConditionCallback& cb : *cbs) { + this->restart(cb.schedule); + } } - for (StateCapture& capture : this->state_captures) { - this->restart_state_capture(capture); +} + +static CallbackSchedule make_schedule(mjtNum seconds_between_calls) { + if (seconds_between_calls < 0) { + throw std::invalid_argument("seconds_between_calls must not be negative"); } + return CallbackSchedule{.period = seconds_between_calls}; } -void Sim::register_cb(std::function cb, - mjtNum seconds_between_calls) { - this->callbacks.push_back(Callback{cb, seconds_between_calls, 0.0}); +size_t Sim::register_cb(std::function cb, + mjtNum seconds_between_calls, + std::function on_restart) { + this->callbacks.push_back( + Callback{.cb = std::move(cb), + .on_restart = std::move(on_restart), + .schedule = make_schedule(seconds_between_calls)}); + this->restart(this->callbacks.back()); + return this->callbacks.size() - 1; } void Sim::register_any_cb(std::function cb, mjtNum seconds_between_calls) { - this->any_callbacks.push_back( - ConditionCallback{cb, seconds_between_calls, 0.0, false}); + this->any_callbacks.push_back(ConditionCallback{ + .cb = std::move(cb), .schedule = make_schedule(seconds_between_calls)}); + this->restart(this->any_callbacks.back().schedule); } void Sim::register_all_cb(std::function cb, mjtNum seconds_between_calls) { - this->all_callbacks.push_back( - ConditionCallback{cb, seconds_between_calls, 0.0, false}); + this->all_callbacks.push_back(ConditionCallback{ + .cb = std::move(cb), .schedule = make_schedule(seconds_between_calls)}); + this->restart(this->all_callbacks.back().schedule); } size_t Sim::register_state_capture(double frame_rate, size_t buffer_size, @@ -368,15 +391,22 @@ size_t Sim::register_state_capture(double frame_rate, size_t buffer_size, throw std::invalid_argument("buffer_size must be positive"); } StateCapture capture; - capture.period = 1.0 / frame_rate; capture.state_spec = state_spec; capture.state_size = mj_stateSize(this->m, state_spec); capture.capacity = buffer_size; capture.states.resize(buffer_size * capture.state_size); capture.timestamps.resize(buffer_size); - this->restart_state_capture(capture); this->state_captures.push_back(std::move(capture)); - return this->state_captures.size() - 1; + size_t id = this->state_captures.size() - 1; + // on (re)start: clear the buffer and capture the current state right away + this->state_captures[id].callback_id = this->register_cb( + [this, id]() { this->capture_state(id); }, 1.0 / frame_rate, + [this, id]() { + this->state_captures[id].next_index = 0; + this->state_captures[id].size = 0; + this->capture_state(id); + }); + return id; } std::optional Sim::get_captured_state( @@ -400,7 +430,7 @@ size_t Sim::captured_state_count(size_t id) const { } void Sim::clear_captured_states(size_t id) { - this->restart_state_capture(this->state_captures.at(id)); + this->restart(this->callbacks.at(this->state_captures.at(id).callback_id)); } void Sim::start_gui_server(const std::string& id) { diff --git a/src/sim/sim.h b/src/sim/sim.h index cbc2b0255..60c503226 100644 --- a/src/sim/sim.h +++ b/src/sim/sim.h @@ -31,26 +31,37 @@ struct SimConfig { RendererBackend renderer = RendererBackend::CLASSIC; }; +/* Fixed schedule of a callback in simulation time: the k-th call is due at + * start + k * period and happens at the physics step closest to that time, so + * that the calls do not drift. The schedule restarts on reset and whenever + * the simulation time goes backwards. */ +struct CallbackSchedule { + mjtNum period; // in seconds, 0 calls the callback every step + mjtNum next_call_time = 0; // in seconds of simulation time + mjtNum last_check_time = 0; // to detect the simulation time going backwards +}; + struct Callback { - const std::function cb; - mjtNum seconds_between_calls; // in seconds - mjtNum last_call_timestamp; + std::function cb; + // called when the schedule (re)starts: at registration, on reset and when + // the simulation time goes backwards, may be empty + std::function on_restart; + CallbackSchedule schedule; }; struct ConditionCallback { - const std::function cb; - mjtNum seconds_between_calls; // in seconds - mjtNum last_call_timestamp; // in seconds - bool last_return_value; + std::function cb; + CallbackSchedule schedule; + bool last_return_value = false; }; /* Simulation states captured at a fixed rate of simulation time, e.g. at the * exposure times of a camera, so that they can be rendered later. Kept in a - * ring buffer of the most recent states. */ + * ring buffer of the most recent states. The captures are taken by a + * callback. */ struct StateCapture { - mjtNum period; // in seconds - mjtNum next_capture_time; // in seconds of simulation time - int state_spec; // mjtState bit mask passed to mj_getState + size_t callback_id; + int state_spec; // mjtState bit mask passed to mj_getState int state_size; size_t capacity; std::vector states; // capacity x state_size, row major @@ -94,11 +105,13 @@ class Sim { std::vector state_captures; std::vector dynamic_joint_specs; std::unordered_map dynamic_joint_name_to_index; + enum class Due { no, yes, restarted }; + Due poll(CallbackSchedule& schedule); + void restart(CallbackSchedule& schedule); + void restart(Callback& callback); void invoke_callbacks(); bool invoke_condition_callbacks(); - void invoke_state_captures(); - void capture_state(StateCapture& capture); - void restart_state_capture(StateCapture& capture); + void capture_state(size_t id); void init_dynamic_joint_specs(); static int get_joint_qpos_size(int joint_type); static int get_joint_qvel_size(int joint_type); @@ -123,24 +136,25 @@ class Sim { DynamicJointState get_dynamic_joint_state() const; void set_dynamic_joint_state(const DynamicJointSchema& schema, const DynamicJointState& state); - /* NOTE: IMPORTANT, the callback is not necessarily called at exactly the - * the requested interval. We invoke a callback if the elapsed simulation time - * since the last call of the callback is greater than the requested time. - * The exact interval at which they are called depends on the models timestep - * option (cf. - * https://mujoco.readthedocs.io/en/stable/programming/simulation.html#simulation-loop - */ - void register_cb(std::function cb, mjtNum seconds_between_calls); + /* Callbacks are called after each physics step that is closest to their + * fixed schedule of start + k * seconds_between_calls in simulation time, + * i.e. the actual calls jitter by up to half a timestep but do not drift. + * The schedule starts at registration and restarts on reset and whenever + * the simulation time goes backwards. seconds_between_calls = 0 calls the + * callback after every step. Condition callbacks are only evaluated in + * step_until_convergence. */ + size_t register_cb(std::function cb, mjtNum seconds_between_calls, + std::function on_restart = nullptr); void register_any_cb(std::function cb, mjtNum seconds_between_calls); void register_all_cb(std::function cb, mjtNum seconds_between_calls); /* Captures the simulation state (mj_getState with state_spec) frame_rate * times per second of simulation time and keeps the latest buffer_size - * states. The current state is captured right away. Captures follow a fixed - * schedule (no drift) and happen at the physics step closest to each capture - * time, after integration so that the state is consistent with its time - * stamp. Returns the id of the capture. */ + * states. The current state is captured right away. The captures are taken + * by a callback, i.e. they follow its fixed schedule and happen after + * integration so that the state is consistent with its time stamp. Returns + * the id of the capture. */ size_t register_state_capture(double frame_rate, size_t buffer_size, int state_spec); /* Latest captured state with a time stamp <= max_timestamp */ From fbde12e10df7f88d661bee3e453f0e9358ce025d Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 13:57:51 -0800 Subject: [PATCH 15/16] fix(camera): count only filled slots of the hardware camera buffer The number of buffered framesets was max(len + 1, max_buffer_frames) instead of min(...), so it was at least the buffer size after the first frameset. Until the buffer was full once, get_timestamp_frames then searched empty slots and failed an assertion. --- python/rcs/camera/hw.py | 2 +- python/tests/test_hw_camera.py | 43 ++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 python/tests/test_hw_camera.py diff --git a/python/rcs/camera/hw.py b/python/rcs/camera/hw.py index da8dc8d93..799e5dacd 100644 --- a/python/rcs/camera/hw.py +++ b/python/rcs/camera/hw.py @@ -250,7 +250,7 @@ def polling_thread(self, warm_up: bool = True): with self._buffer_lock: self._buffer[self._next_ring_index] = frame_set self._next_ring_index = (self._next_ring_index + 1) % self.max_buffer_frames - self._buffer_len = max(self._buffer_len + 1, self.max_buffer_frames) + self._buffer_len = min(self._buffer_len + 1, self.max_buffer_frames) # video recording for camera_key, writer in self.writer.items(): if frame_set is not None: diff --git a/python/tests/test_hw_camera.py b/python/tests/test_hw_camera.py new file mode 100644 index 000000000..31c5a2914 --- /dev/null +++ b/python/tests/test_hw_camera.py @@ -0,0 +1,43 @@ +import time +from datetime import datetime + +import numpy as np +from rcs._core.common import BaseCameraConfig +from rcs.camera.hw import HardwareCameraSet +from rcs.camera.interface import CameraFrame, DataFrame, Frame + + +class _FakeCamera: + @property + def camera_names(self) -> list[str]: + return ["cam"] + + def open(self): + pass + + def close(self): + pass + + def config(self, camera_name: str) -> BaseCameraConfig: + return BaseCameraConfig(identifier=camera_name, frame_rate=100, resolution_width=4, resolution_height=3) + + def poll_frame(self, camera_name: str) -> Frame: + ts = time.time() + color = DataFrame(data=np.zeros((3, 4, 3), dtype=np.uint8), timestamp=ts) + return Frame(camera=CameraFrame(color=color), avg_timestamp=ts) + + def calibrate(self) -> bool: + return True + + +def test_timestamp_lookup_before_the_buffer_is_full(): + cameras = HardwareCameraSet([_FakeCamera()], warm_up_disposal_frames=0, max_buffer_frames=1000) + cameras.start(warm_up=False) + try: + cameras.wait_for_frames() + finally: + cameras.stop() + assert 0 < cameras.buffer_size() < cameras.max_buffer_frames + # only the filled slots are searched + assert cameras.get_timestamp_frames(datetime.fromtimestamp(0)) is None + assert cameras.get_timestamp_frames(datetime.now()) is cameras.get_latest_frames() From c001937ff1a51b08400138fc3b464f903e6019f8 Mon Sep 17 00:00:00 2001 From: Tobias Juelg Date: Fri, 20 Nov 2026 12:10:39 -0800 Subject: [PATCH 16/16] refactor(sim)!: drop camera types, render the cameras of the model Sim cameras could be free, tracking, fixed or default_free cameras, but only fixed cameras were usable: SimCameraConfig had no parameters for the pose of free or the target of tracking cameras, and the intrinsics and extrinsics of default_free cameras silently came from the last camera of the model. All env configs use fixed cameras, and moving cameras, e.g. for videos, are cameras attached to a body or with a tracking mode in MJCF. SimCameraSet now always renders the camera of the model named by the identifier and raises if it does not exist. CameraType, the type field and src/sim/camera.h are removed, SimCameraConfig is kept as an alias of BaseCameraConfig. BREAKING CHANGE: rcs._core.sim.CameraType and the type argument and field of SimCameraConfig are removed. --- docs/getting_started/index.md | 1 - docs/user_guide/scene_configuration.md | 6 +-- examples/fr3/fr3_direct_control.py | 12 +----- python/rcs/_core/sim.pyi | 53 +------------------------- python/rcs/camera/sim.py | 19 +++++---- python/rcs/envs/configs.py | 20 +--------- python/rcs/envs/utils.py | 9 ----- python/tests/test_sim_camera.py | 7 ++++ src/pybind/rcs.cpp | 34 ++--------------- src/sim/camera.h | 23 ----------- 10 files changed, 28 insertions(+), 156 deletions(-) delete mode 100644 src/sim/camera.h diff --git a/docs/getting_started/index.md b/docs/getting_started/index.md index 16ac8644b..575d5418b 100644 --- a/docs/getting_started/index.md +++ b/docs/getting_started/index.md @@ -63,7 +63,6 @@ Here is a simple example of direct robot control using the low-level API: ```python import rcs from rcs import sim -from rcs._core.sim import CameraType from rcs.camera.sim import SimCameraConfig, SimCameraSet from time import sleep import numpy as np diff --git a/docs/user_guide/scene_configuration.md b/docs/user_guide/scene_configuration.md index 9ed007477..5c7d443f5 100644 --- a/docs/user_guide/scene_configuration.md +++ b/docs/user_guide/scene_configuration.md @@ -100,7 +100,7 @@ This is the main top-level config for the scene API. | `task_cfg` | Optional task-specific config | Add pick/place or other task logic | | `scene` | Base scene XML path or scene key | Usually from `SCENE_PATHS[...]` | | `gripper_cfgs` | Optional gripper config per robot | Add one gripper per robot | -| `camera_cfgs` | Optional camera config dictionary | Define resolution, type, and frame rate for named cameras | +| `camera_cfgs` | Optional camera config dictionary | Define the model camera, resolution and frame rate for named cameras | | `max_relative_movement` | Relative action limit | Limit per-step Cartesian delta | | `relative_to` | Relative action reference | Usually `RelativeTo.LAST_STEP` or `RelativeTo.NONE` | | `robot_to_shared_base_frame` | Per-robot offset relative to the shared base frame | Multi-robot layouts | @@ -149,8 +149,8 @@ Each gripper entry usually defines: Each camera entry usually defines: -- camera identifier -- camera type +- camera identifier, the name of the camera in the MuJoCo model. Cameras attached to a body or with a + tracking `mode` in MJCF move with the simulation, e.g. for videos. - resolution - frame rate diff --git a/examples/fr3/fr3_direct_control.py b/examples/fr3/fr3_direct_control.py index 342f1dec9..e16a33c74 100644 --- a/examples/fr3/fr3_direct_control.py +++ b/examples/fr3/fr3_direct_control.py @@ -2,7 +2,7 @@ import numpy as np from rcs._core.common import RobotPlatform -from rcs._core.sim import CameraType, SimConfig +from rcs._core.sim import SimConfig from rcs.camera.sim import SimCameraConfig, SimCameraSet from rcs.envs.configs import EmptyWorldFR3 from rcs_fr3._core import hw @@ -86,18 +86,10 @@ def main(): gripper_cfg = cfg.gripper_cfgs[fr3] # type: ignore gripper = sim.SimGripper(simulation, gripper_cfg) - # add camera to have a rendering gui + # render the wrist camera of the model cameras = { - "default_free": sim.SimCameraConfig( - identifier="", - type=CameraType.default_free, - resolution_width=1280, - resolution_height=720, - frame_rate=20, - ), "wrist": SimCameraConfig( identifier="wrist_0", - type=CameraType.fixed, resolution_width=640, resolution_height=480, frame_rate=30, diff --git a/python/rcs/_core/sim.pyi b/python/rcs/_core/sim.pyi index bafff1fa3..ca800634e 100644 --- a/python/rcs/_core/sim.pyi +++ b/python/rcs/_core/sim.pyi @@ -8,10 +8,10 @@ import typing import numpy import rcs._core.common +from rcs._core.common import BaseCameraConfig as SimCameraConfig __all__: list[str] = [ "CLASSIC", - "CameraType", "CapturedState", "DynamicJointSchema", "DynamicJointState", @@ -30,48 +30,9 @@ __all__: list[str] = [ "SimTilburgHand", "SimTilburgHandConfig", "SimTilburgHandState", - "default_free", - "fixed", - "free", - "tracking", ] M = typing.TypeVar("M", bound=int) -class CameraType: - """ - Members: - - free - - tracking - - fixed - - default_free - """ - - __members__: typing.ClassVar[ - dict[str, CameraType] - ] # value = {'free': , 'tracking': , 'fixed': , 'default_free': } - default_free: typing.ClassVar[CameraType] # value = - fixed: typing.ClassVar[CameraType] # value = - free: typing.ClassVar[CameraType] # value = - tracking: typing.ClassVar[CameraType] # value = - def __eq__(self, other: typing.Any) -> bool: ... - def __getstate__(self) -> int: ... - def __hash__(self) -> int: ... - def __index__(self) -> int: ... - def __init__(self, value: int) -> None: ... - def __int__(self) -> int: ... - def __ne__(self, other: typing.Any) -> bool: ... - def __repr__(self) -> str: ... - def __setstate__(self, state: int) -> None: ... - def __str__(self) -> str: ... - @property - def name(self) -> str: ... - @property - def value(self) -> int: ... - class CapturedState: @property def state(self) -> numpy.ndarray[tuple[M], numpy.dtype[numpy.float64]]: ... @@ -144,14 +105,6 @@ class Sim: def step_until_convergence(self) -> None: ... def sync_gui(self) -> None: ... -class SimCameraConfig(rcs._core.common.BaseCameraConfig): - type: CameraType - def __copy__(self) -> SimCameraConfig: ... - def __deepcopy__(self, arg0: dict) -> SimCameraConfig: ... - def __init__( - self, identifier: str, frame_rate: int, resolution_width: int, resolution_height: int, type: CameraType = ... - ) -> None: ... - class SimConfig: async_control: bool frequency: float @@ -403,7 +356,3 @@ class SimTilburgHandState(rcs._core.common.HandState): CLASSIC: RendererBackend # value = FILAMENT: RendererBackend # value = -default_free: CameraType # value = -fixed: CameraType # value = -free: CameraType # value = -tracking: CameraType # value = diff --git a/python/rcs/camera/sim.py b/python/rcs/camera/sim.py index 4ebdd71d6..39a2e2065 100644 --- a/python/rcs/camera/sim.py +++ b/python/rcs/camera/sim.py @@ -24,7 +24,7 @@ import mujoco import numpy as np from rcs._core import common -from rcs._core.sim import CameraType, RendererBackend, SimCameraConfig +from rcs._core.sim import RendererBackend, SimCameraConfig from rcs.camera.interface import BaseCameraSet, CameraFrame, DataFrame, Frame, FrameSet from rcs.sim import filament, render_context_bootstrap @@ -37,7 +37,11 @@ def _camera_id(model: mujoco.MjModel, cfg: SimCameraConfig) -> int: - return mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_CAMERA, cfg.identifier) + cam_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_CAMERA, cfg.identifier) + if cam_id < 0: + msg = f"camera {cfg.identifier!r} does not exist in the model" + raise ValueError(msg) + return cam_id def _intrinsics( @@ -167,7 +171,9 @@ class SimCameraSet: Args: simulation: the simulation to render. - cameras: camera configurations by name. + cameras: camera configurations by name. Each renders the camera of the model named by its + ``identifier``; cameras attached to bodies or with a tracking ``mode`` in MJCF move with the + simulation. physical_units: depth in meters (scaled by ``BaseCameraSet.DEPTH_SCALE``); otherwise the raw [0, 1] depth buffer of the classic renderer is scaled. render_on_demand: if True, frames show the simulation state at the time they are requested. @@ -212,11 +218,8 @@ def __init__( self._mj_cameras: dict[str, mujoco.MjvCamera] = {} for name, cfg in cameras.items(): cam = mujoco.MjvCamera() - if cfg.type == CameraType.default_free: - mujoco.mjv_defaultFreeCamera(model, cam) - else: - cam.type = int(cfg.type) - cam.fixedcamid = _camera_id(model, cfg) + cam.type = mujoco.mjtCamera.mjCAMERA_FIXED + cam.fixedcamid = _camera_id(model, cfg) self._mj_cameras[name] = cam # render_on_demand=True: rendered framesets, newest last diff --git a/python/rcs/envs/configs.py b/python/rcs/envs/configs.py index d9e79f752..7a49b78ea 100644 --- a/python/rcs/envs/configs.py +++ b/python/rcs/envs/configs.py @@ -5,13 +5,7 @@ import gymnasium as gym import numpy as np from rcs._core.common import GripperType, RobotType -from rcs._core.sim import ( - CameraType, - SimCameraConfig, - SimConfig, - SimGripperConfig, - SimRobotConfig, -) +from rcs._core.sim import SimCameraConfig, SimConfig, SimGripperConfig, SimRobotConfig from rcs.envs.base import ControlMode, RelativeTo from rcs.envs.scenes import ( CameraAdderConfig, @@ -105,14 +99,12 @@ def config(self) -> SimEnvCreatorConfig: camera_cfgs: dict[str, SimCameraConfig] | None = { "bird_eye": SimCameraConfig( identifier="bird_eye", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, ), "wrist": SimCameraConfig( identifier="wrist", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, @@ -251,28 +243,24 @@ def config(self) -> SimEnvCreatorConfig: cfg.camera_cfgs = { "over_shoulder_left": SimCameraConfig( identifier="over_shoulder_left", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, ), "over_shoulder_right": SimCameraConfig( identifier="over_shoulder_right", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, ), "front": SimCameraConfig( identifier="front", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, ), "wrist": SimCameraConfig( identifier="wrist", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, @@ -357,21 +345,18 @@ def config(self) -> SimEnvCreatorConfig: camera_cfgs: dict[str, SimCameraConfig] | None = { "head": SimCameraConfig( identifier="head", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, ), "left_wrist": SimCameraConfig( identifier="left_wrist", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, ), "right_wrist": SimCameraConfig( identifier="right_wrist", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, @@ -673,7 +658,6 @@ def config(self) -> SimEnvCreatorConfig: cfg.camera_cfgs = { "wrist": SimCameraConfig( identifier="wrist", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, @@ -712,7 +696,6 @@ def config(self) -> SimEnvCreatorConfig: camera_cfgs: dict[str, SimCameraConfig] | None = { name: SimCameraConfig( identifier=name, - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, @@ -809,7 +792,6 @@ def config(self) -> SimEnvCreatorConfig: camera_cfgs = { f"{name}_wrist": SimCameraConfig( identifier=f"{name}_wrist", - type=CameraType.fixed, resolution_width=1280, resolution_height=720, frame_rate=30, diff --git a/python/rcs/envs/utils.py b/python/rcs/envs/utils.py index 7a33c0492..4319b059c 100644 --- a/python/rcs/envs/utils.py +++ b/python/rcs/envs/utils.py @@ -5,7 +5,6 @@ from rcs._core.sim import SimCameraConfig from rcs.camera.digit_cam import DigitCam -import rcs from rcs import sim logger = logging.getLogger(__name__) @@ -37,14 +36,6 @@ def default_mujoco_cameraset_cfg() -> dict[str, SimCameraConfig]: return { "wrist": SimCameraConfig( identifier="wrist_0", - type=rcs._core.sim.CameraType.fixed, - frame_rate=10, - resolution_width=256, - resolution_height=256, - ), - "default_free": SimCameraConfig( - identifier="", - type=rcs._core.sim.CameraType.default_free, frame_rate=10, resolution_width=256, resolution_height=256, diff --git a/python/tests/test_sim_camera.py b/python/tests/test_sim_camera.py index b69c205a6..eb72d22dc 100644 --- a/python/tests/test_sim_camera.py +++ b/python/tests/test_sim_camera.py @@ -149,3 +149,10 @@ def test_frames_show_last_exposure(): assert newer.avg_timestamp == pytest.approx(4 * period, abs=dt) exposed.close() live.close() + + +def test_unknown_camera_raises(): + simulation, _ = _droid_sim() + cfg = sim.SimCameraConfig(identifier="missing", frame_rate=30, resolution_width=64, resolution_height=48) + with pytest.raises(ValueError, match="missing"): + SimCameraSet(simulation, {"missing": cfg}) diff --git a/src/pybind/rcs.cpp b/src/pybind/rcs.cpp index 6b6428a02..0ebd39b9c 100644 --- a/src/pybind/rcs.cpp +++ b/src/pybind/rcs.cpp @@ -6,13 +6,13 @@ #include #include #include -#include #include #include #include #include +#include "rcs/Camera.h" #include "rcs/Kinematics.h" #include "rcs/Pose.h" #include "rcs/Robot.h" @@ -939,36 +939,8 @@ PYBIND11_MODULE(_core, m) { .def("get_state", &rcs::sim::SimTilburgHand::get_state) .def("set_config", &rcs::sim::SimTilburgHand::set_config, py::arg("cfg")); - py::enum_(sim, "CameraType") - .value("free", rcs::sim::CameraType::free) - .value("tracking", rcs::sim::CameraType::tracking) - .value("fixed", rcs::sim::CameraType::fixed) - .value("default_free", rcs::sim::CameraType::default_free) - .export_values(); - py::class_( - sim, "SimCameraConfig") - .def(py::init([](const std::string& identifier, int frame_rate, - int resolution_width, int resolution_height, - rcs::sim::CameraType type) { - rcs::sim::SimCameraConfig config; - config.identifier = identifier; - config.frame_rate = frame_rate; - config.resolution_width = resolution_width; - config.resolution_height = resolution_height; - config.type = type; - return config; - }), - py::arg("identifier"), py::arg("frame_rate"), - py::arg("resolution_width"), py::arg("resolution_height"), - py::arg("type") = rcs::sim::CameraType::fixed) - .def_readwrite("type", &rcs::sim::SimCameraConfig::type) - .def("__copy__", - [](const rcs::sim::SimCameraConfig& self) { - return rcs::sim::SimCameraConfig(self); - }) - .def("__deepcopy__", [](const rcs::sim::SimCameraConfig& self, py::dict) { - return rcs::sim::SimCameraConfig(self); - }); + // simulated cameras render the camera of the model named by identifier + sim.attr("SimCameraConfig") = common.attr("BaseCameraConfig"); py::class_(sim, "GuiClient") .def(py::init(), py::arg("id")) .def("get_model_bytes", diff --git a/src/sim/camera.h b/src/sim/camera.h deleted file mode 100644 index 875bf76a9..000000000 --- a/src/sim/camera.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef RCS_CAMSIM_H -#define RCS_CAMSIM_H -#include - -#include "rcs/Camera.h" - -namespace rcs { -namespace sim { - -enum CameraType { - free = mjCAMERA_FREE, - tracking = mjCAMERA_TRACKING, - fixed = mjCAMERA_FIXED, - default_free -}; - -struct SimCameraConfig : common::BaseCameraConfig { - CameraType type; -}; - -} // namespace sim -} // namespace rcs -#endif // RCS_CAMSIM_H