From a28f501cc6ae914bfcad61f45d09f46ac56a144a Mon Sep 17 00:00:00 2001 From: HuiDong Chen Date: Mon, 30 Nov 2026 21:24:17 +0800 Subject: [PATCH 01/16] Publish only a complete OVRTX lidar scan - Copy the newest complete PointCloud frame and clear returns when none maps. - Make frame_rate configurable and default instant_lidar to False. - Drop the cameraSensorType attribute from spawned lidar prims. - Cover scan timing, frame ordering, and the existing tiled and mount checks. --- .../huidongc-lidar-clear.added.rst | 1 + .../changelog.d/huidongc-lidar-clear.minor | 0 .../isaaclab/sensors/lidar/lidar_data.py | 9 ++ .../changelog.d/huidongc-lidar-scan.added.rst | 1 + .../huidongc-lidar-scan.changed.rst | 4 + .../changelog.d/huidongc-lidar-scan.minor | 0 .../isaaclab_ov/renderers/ovrtx_lidar_cfg.py | 16 ++- .../renderers/ovrtx_lidar_sensor.py | 3 +- .../isaaclab_ov/renderers/ovrtx_renderer.py | 50 ++++---- source/isaaclab_ov/test/test_ovrtx_lidar.py | 108 +++++++++++++++++- .../test/test_ovrtx_renderer_contract.py | 69 +++++++++-- 11 files changed, 221 insertions(+), 40 deletions(-) create mode 100644 source/isaaclab/changelog.d/huidongc-lidar-clear.added.rst create mode 100644 source/isaaclab/changelog.d/huidongc-lidar-clear.minor create mode 100644 source/isaaclab_ov/changelog.d/huidongc-lidar-scan.added.rst create mode 100644 source/isaaclab_ov/changelog.d/huidongc-lidar-scan.changed.rst create mode 100644 source/isaaclab_ov/changelog.d/huidongc-lidar-scan.minor diff --git a/source/isaaclab/changelog.d/huidongc-lidar-clear.added.rst b/source/isaaclab/changelog.d/huidongc-lidar-clear.added.rst new file mode 100644 index 000000000000..284f59152ae3 --- /dev/null +++ b/source/isaaclab/changelog.d/huidongc-lidar-clear.added.rst @@ -0,0 +1 @@ +* Added :meth:`~isaaclab.sensors.lidar.lidar_data.LidarData.clear` to reset every lidar return to a miss. diff --git a/source/isaaclab/changelog.d/huidongc-lidar-clear.minor b/source/isaaclab/changelog.d/huidongc-lidar-clear.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/sensors/lidar/lidar_data.py b/source/isaaclab/isaaclab/sensors/lidar/lidar_data.py index 2f1c45b17653..e8755e77c710 100644 --- a/source/isaaclab/isaaclab/sensors/lidar/lidar_data.py +++ b/source/isaaclab/isaaclab/sensors/lidar/lidar_data.py @@ -29,6 +29,15 @@ def __init__(self, num_envs: int, num_rays: int, device: str): self._intensity = ProxyArray(wp.zeros((num_envs, num_rays), dtype=wp.float32, device=device)) self._valid = ProxyArray(wp.zeros((num_envs, num_rays), dtype=wp.bool, device=device)) + def clear(self) -> None: + """Reset every return to a miss. + + Points become non-finite. Intensity and validity become zero. + """ + self._points.warp.fill_(wp.vec3f(wp.inf)) + self._intensity.warp.fill_(0.0) + self._valid.warp.fill_(False) + @property def points(self) -> ProxyArray: """Cartesian XYZ positions in meters in the configured output frame. diff --git a/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.added.rst b/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.added.rst new file mode 100644 index 000000000000..a87de0457446 --- /dev/null +++ b/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.added.rst @@ -0,0 +1 @@ +* Added ``frame_rate`` to :class:`~isaaclab_ov.renderers.ovrtx_lidar_cfg.OVRTXLidarCfg` and authored it as ``omni:sensor:frameRate``. diff --git a/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.changed.rst b/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.changed.rst new file mode 100644 index 000000000000..ae18430f1f89 --- /dev/null +++ b/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.changed.rst @@ -0,0 +1,4 @@ +* Changed ``instant_lidar`` to default to ``False``, so rays are spread across the lidar frame instead of emitted in one render step. + Set ``instant_lidar=True`` on the config passed to ``spawn_lidar`` to restore a complete scan per capture. +* Published the newest complete lidar scan and cleared every return when a step has no complete scan. + A partial or unmapped point cloud is no longer copied from a CPU fallback. diff --git a/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.minor b/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py index 6c8ea581be99..f7be76a4e66e 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py @@ -35,6 +35,9 @@ class OVRTXLidarCfg(LidarCfg): spawn: OVRTXLidarSpawnerCfg | None = OVRTXLidarSpawnerCfg() renderer_cfg: OVRTXRendererCfg = OVRTXRendererCfg(motion_bvh="auto") + frame_rate: tuple[float, float] = (10.0, 1.0) + """USD ``omni:sensor:frameRate`` rational ``(numerator, denominator)``. Defaults to ``(10.0, 1.0)``.""" + scan_type: Literal["rotary", "solidState"] = "rotary" """USD ``scanType`` token. Defaults to ``rotary``. @@ -75,7 +78,7 @@ class OVRTXLidarCfg(LidarCfg): """ max_returns: int = 2 - """Maximum returns stored for each ray. Defaults to 2, matching ``maxReturns``.""" + """Maximum returns stored for each ray. Defaults to 2.""" output_frame_of_reference: Literal["SENSOR", "WORLD"] = "SENSOR" """Coordinate frame of the returned points. Defaults to ``SENSOR``.""" @@ -86,8 +89,8 @@ class OVRTXLidarCfg(LidarCfg): elements_coords_type: Literal["CARTESIAN", "SPHERICAL"] = "CARTESIAN" """Native coordinate encoding. Both modes publish Cartesian XYZ positions in meters. Defaults to ``CARTESIAN``.""" - instant_lidar: bool = True - """Whether one render step publishes a complete scan. Defaults to True.""" + instant_lidar: bool = False + """If true, all rays are emitted at the frame timestamp. Defaults to False.""" include_invalid_points: bool = True """Keep missed rays in their original slots. Tiled OvRTX lidar requires True. @@ -131,6 +134,13 @@ def __post_init__(self): if self.far_range_m <= 0.0: raise ValueError(f"Lidar far_range_m must be positive, got {self.far_range_m}.") + if len(self.frame_rate) != 2 or not ( + 0.0 < self.frame_rate[0] < math.inf and 0.0 < self.frame_rate[1] < math.inf + ): + raise ValueError( + f"Lidar frame_rate must be a finite, positive (numerator, denominator) pair, got {self.frame_rate}." + ) + if any(time < 0 for time in self.fire_time_ns): raise ValueError("Lidar fire_time_ns values cannot be negative.") diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_sensor.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_sensor.py index a70c3308ed83..0f1e9adfaa15 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_sensor.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_sensor.py @@ -108,9 +108,8 @@ def spawn_lidar(prim_path: str, cfg: OVRTXLidarCfg) -> Usd.Prim: xform.AddScaleOp(UsdGeom.XformOp.PrecisionDouble).Set(Gf.Vec3d(1.0, 1.0, 1.0)) prim.CreateAttribute("omni:sensor:modelName", Sdf.ValueTypeNames.String).Set("LidarWpm") - prim.CreateAttribute("cameraSensorType", Sdf.ValueTypeNames.Token).Set("lidar") prim.CreateAttribute("visibility", Sdf.ValueTypeNames.Token).Set("invisible") - prim.CreateAttribute("omni:sensor:frameRate", Sdf.ValueTypeNames.Double2).Set(Gf.Vec2d(10.0, 1.0)) + prim.CreateAttribute("omni:sensor:frameRate", Sdf.ValueTypeNames.Double2).Set(Gf.Vec2d(*cfg.frame_rate)) _author_wpm(prim, cfg) diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index 03801a364723..1df6eafe9839 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -948,7 +948,7 @@ def create_lidar_render_data( return render_data @contextlib.contextmanager - def _map_lidar_point_cloud(self, point_cloud, device: Device) -> Iterator[Any]: + def _map_lidar_point_cloud(self, point_cloud: RenderVarOutput, device: Device) -> Iterator[Any]: """Map a lidar point cloud for reads and release it after the consumer returns. CUDA maps wait for rendering on the consuming Warp stream, or on the host on Linux unless @@ -1029,34 +1029,40 @@ def render_lidar(self, render_data: OVRTXLidarRenderData, lidar_data: LidarData) def _publish_lidar_output( self, render_data: OVRTXLidarRenderData, products: RenderProductSetOutputs, lidar_data: LidarData ) -> None: - """Split one lidar product's point cloud into ``lidar_data``. + """Copy the newest complete lidar scan into ``lidar_data``. - A missing frame or point-cloud variable raises. If the CUDA map is unavailable, - retry on the CPU and propagate any fallback readback error. + A step can return several frames when the render steps across multiple lidar frame boundaries. The newest + frame that contains complete lidar scan is published. When no frame contains a complete lidar scan, every + return is cleared to a miss. """ - if render_data.render_product_path not in products or not products[render_data.render_product_path].frames: - raise RuntimeError(f"OVRTX returned no frame for lidar product {render_data.render_product_path!r}.") + markers = ["failed to map", "unpublish", "point cloud was empty", "raw resource"] + # The frame array does not promise an order, so sort by end_time and prioritize newer frames over older ones. frames = products[render_data.render_product_path].frames - frame = frames[-1] - point_cloud = frame.render_vars.get(render_data.point_cloud_path) - if point_cloud is None: - raise RuntimeError( - f"OVRTX lidar frame has no point cloud at {render_data.point_cloud_path!r}. " - f"Available render vars: {list(frame.render_vars)}." - ) + frames.sort(key=lambda frame: frame.end_time, reverse=True) - try: - self._copy_mapped_lidar_point_cloud(point_cloud, lidar_data, Device.CUDA) - except Exception as exc: - message = str(exc).lower() - if not ("failed to map" in message or "unpublish" in message or "point cloud was empty" in message): - raise + for frame in frames: + # TODO: rework the exception handling on OVRTX 1.0 which won't return incomplete lidar scans. + try: + self._copy_mapped_lidar_point_cloud( + frame.render_vars[render_data.point_cloud_path], lidar_data, Device.CUDA + ) + except Exception as exc: + message = str(exc).lower() + if all(marker not in message for marker in markers): + raise + + continue - logger.info("Retrying OvRTX lidar point-cloud readback on the CPU: %s", exc) - self._copy_mapped_lidar_point_cloud(point_cloud, lidar_data, Device.CPU) + # A complete lidar scan was produced in this step. Return to break the loop. + return + + # No complete lidar scan was produced in this step. Drop the previous data so it is not read as the new one. + lidar_data.clear() - def _copy_mapped_lidar_point_cloud(self, point_cloud, lidar_data: LidarData, device: Device) -> None: + def _copy_mapped_lidar_point_cloud( + self, point_cloud: RenderVarOutput, lidar_data: LidarData, device: Device + ) -> None: """Map one point cloud and copy it into the lidar buffers. A CUDA map that produces no coordinates raises so the caller can fall back to the CPU map. diff --git a/source/isaaclab_ov/test/test_ovrtx_lidar.py b/source/isaaclab_ov/test/test_ovrtx_lidar.py index ef44125c28ac..1c26306280b6 100644 --- a/source/isaaclab_ov/test/test_ovrtx_lidar.py +++ b/source/isaaclab_ov/test/test_ovrtx_lidar.py @@ -8,6 +8,7 @@ from __future__ import annotations import math +from importlib.metadata import version as package_version from types import SimpleNamespace import numpy as np @@ -16,6 +17,7 @@ import warp as wp from isaaclab_ov.renderers import OVRTXLidarCfg from isaaclab_ov.renderers.ovrtx_lidar_sensor import OVRTXLidar +from packaging.version import Version from isaaclab.utils import validate from isaaclab.utils.warp import ProxyArray @@ -179,6 +181,7 @@ class SceneCfg(InteractiveSceneCfg): mass_props=sim_utils.MassCfg(mass=1.0), ), ) + # Two rays, fired together. instant_lidar publishes the whole scan in one render step. lidar = _lidar_cfg( prim_path="{ENV_REGEX_NS}/Lidar", scan_type="solidState", @@ -186,9 +189,11 @@ class SceneCfg(InteractiveSceneCfg): elevation_deg=[-5.0, 10.0], fire_time_ns=[0, 0], channel_id=[0, 1], + instant_lidar=True, offset=OVRTXLidarCfg.OffsetCfg(pos=(0.2, 0.1, 3.0), rot=(0.0, 0.0, 0.5, math.sqrt(0.75))), ) + # Same pattern in spherical coordinates and in the world frame. replace() keeps instant_lidar. spherical = replace(lidar, prim_path="{ENV_REGEX_NS}/Spherical", elements_coords_type="SPHERICAL") world = replace(lidar, prim_path="{ENV_REGEX_NS}/WorldLidar", output_frame_of_reference="WORLD") world_spherical = replace(world, prim_path="{ENV_REGEX_NS}/WorldSpherical", elements_coords_type="SPHERICAL") @@ -202,17 +207,23 @@ class SceneCfg(InteractiveSceneCfg): lidar = scene["lidar"] data = lidar.data points, valid = data.points.torch, data.valid.torch + + # Both tiles hit. Each environment has two rays, and every return is valid and finite. assert points.shape == (2, 2, 3) assert valid.all() assert torch.isfinite(points).all() + + # Hits are sensor-local. The tiles are 8 m apart, so a world-frame leak would separate the rows. torch.testing.assert_close(points[0], points[1], atol=1e-3, rtol=0.0) + # Spherical samples convert to the same Cartesian points. This does not compare sensor and world frames. for native, converted in ((lidar, scene["spherical"]), (scene["world"], scene["world_spherical"])): expected, actual = native.data, converted.data assert expected.valid.torch.all() torch.testing.assert_close(actual.valid.torch, expected.valid.torch) torch.testing.assert_close(actual.points.torch, expected.points.torch, atol=1e-4, rtol=1e-5) + # Reset is per environment. Clearing tile 0 leaves the captured returns of tile 1 in place. kept = points[1].clone() lidar.reset(env_ids=[0]) assert not lidar.data.valid.torch[0].any() @@ -237,12 +248,13 @@ def test_referenced_lidar_follows_authored_mount(): def spawn_platform(path, cfg, **kwargs): platform = sim_utils.spawn_cuboid(path, cfg, **kwargs) + # 30° about Y pitches the forward ray off vertical. The mount is 3 m above the platform origin. mount = OVRTXLidarCfg.OffsetCfg( pos=(0.3, 0.0, 3.0), rot=(0.0, math.sin(math.pi / 12), 0.0, math.cos(math.pi / 12)) ) spawn_lidar( str(platform.GetPath()) + "/Lidar", - _lidar_cfg(scan_type="solidState", offset=mount, output_frame_of_reference="WORLD"), + _lidar_cfg(scan_type="solidState", offset=mount, output_frame_of_reference="WORLD", instant_lidar=True), ) return platform @@ -258,6 +270,7 @@ class SceneCfg(InteractiveSceneCfg): mass_props=sim_utils.MassCfg(mass=1.0), ), ) + # spawn=None binds the prim authored on the platform instead of creating another lidar. lidar = _lidar_cfg( prim_path="{ENV_REGEX_NS}/Platform/Lidar", spawn=None, @@ -271,13 +284,104 @@ class SceneCfg(InteractiveSceneCfg): sim.reset() platform = scene["platform"] pose = platform.data.root_link_pose_w.torch.clone() - # A beam tilted 30 degrees from vertical intersects the top face 2.5 m below its mount. + + # The top face is at z = 0.5. A 30° tilt over the remaining 2.5 m shifts the hit toward -X. local_hit = pose.new_tensor([0.3 - 2.5 * math.tan(math.pi / 6), 0.0, 0.5]) + + # The first pass leaves both platforms still. The second moves environment 1 by 0.4 m. for displacement in (0.0, 0.4): pose[1, 0] += displacement platform.write_root_pose_to_sim_index(root_pose=pose) sim.step() scene.update(sim.get_physics_dt()) data = scene["lidar"].data + + # Both tiles hit. World points follow the platform: pose plus the platform-frame hit. assert data.valid.torch.all() torch.testing.assert_close(data.points.torch[:, 0], pose[:, :3] + local_hit, atol=1e-3, rtol=0.0) + + +@pytest.mark.integration +@pytest.mark.rendering +@pytest.mark.ov +@pytest.mark.skipif(not wp.is_cuda_available(), reason="Tiled lidar capture requires CUDA.") +@pytest.mark.parametrize("update_period", [0.0, 0.05, 0.1, 0.2, 0.25]) +@pytest.mark.parametrize("instant_lidar", [False, True]) +@pytest.mark.parametrize( + "frame_rate", + [ + (10.0, 1.0), + pytest.param( + (60.0, 1.0), + marks=pytest.mark.skipif( + Version(package_version("ovrtx")).major < 1, + reason="A 60 Hz lidar scan ends 1 ns early and is not published.", + ), + ), + ], +) +def test_lidar_capture(update_period, instant_lidar, frame_rate): + from isaaclab_ov.physics import OvPhysxCfg + + import isaaclab.sim as sim_utils + from isaaclab.assets import RigidObjectCfg + from isaaclab.scene import InteractiveSceneCfg + from isaaclab.utils import configclass, instantiate + + @configclass + class SceneCfg(InteractiveSceneCfg): + target = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Target", + spawn=sim_utils.CuboidCfg( + size=(4.0, 4.0, 1.0), + rigid_props=sim_utils.UsdPhysicsRigidBodyCfg(kinematic_enabled=True), + collision_props=sim_utils.UsdPhysicsCollisionCfg(), + mass_props=sim_utils.MassCfg(mass=1.0), + ), + ) + lidar = OVRTXLidarCfg( + prim_path="{ENV_REGEX_NS}/Lidar", + frame_rate=frame_rate, + scan_type="solidState", + azimuth_deg=[-8.0, 12.0], + elevation_deg=[-5.0, 10.0], + fire_time_ns=[0, 0], + channel_id=[0, 1], + max_returns=1, + instant_lidar=instant_lidar, + update_period=update_period, + offset=OVRTXLidarCfg.OffsetCfg(pos=(0.2, 0.1, 3.0), rot=(0.0, 0.0, 0.5, math.sqrt(0.75))), + ) + + with sim_utils.build_simulation_context(sim_cfg=sim_utils.SimulationCfg(physics=OvPhysxCfg())) as sim: + scene = instantiate(SceneCfg(num_envs=2, env_spacing=8.0)) + sim.register_interactive_scene(scene) + sim.reset() + dt = sim.get_physics_dt() + lidar = scene["lidar"] + numerator, denominator = frame_rate + scan_period = denominator / numerator + sample_dt = update_period if update_period > 0.0 else dt + lidar_time = 0.0 + since_capture = 0.0 + closed_scan = False + # Half a second of sim time, reading the lidar every step like an observation term. + for step in range(math.ceil(0.5 / dt)): + sim.step() + scene.update(dt) + since_capture += dt + # Reset leaves the sensor unsampled, so the first positive step always captures. + if lidar_time == 0.0 or since_capture >= update_period - 1e-6: + previous = lidar_time + lidar_time += sample_dt + since_capture = 0.0 + closed_scan = instant_lidar or math.floor((lidar_time + 1e-9) / scan_period) > math.floor( + (previous + 1e-9) / scan_period + ) + data = lidar.data + detail = f"instant={instant_lidar} update_period={update_period} step={step} lidar_time={lidar_time}" + if closed_scan: + assert data.valid.torch.all(), f"{detail} returned an incomplete scan" + assert torch.isfinite(data.points.torch).all(), f"{detail} returned a non-finite hit" + else: + assert not data.valid.torch.all(), f"{detail} published a finished scan early" diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py index 3821b2b9bc77..42ffba2f8234 100644 --- a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py @@ -469,22 +469,69 @@ def test_lidar_and_camera_captures_use_separate_steps(monkeypatch): publish.assert_called_once_with(lidar, native.step.return_value, data) -def test_lidar_readback_propagates_cpu_map_failure(monkeypatch): - """A failed fallback map must reach the caller rather than publish an all-miss scan.""" +def test_lidar_output_readback(monkeypatch): + """Test the lidar output readback - OVRTXRenderer._publish_lidar_output.""" from isaaclab.sensors import LidarData + def new_lidar_data(): + lidar_data = LidarData(1, 1, "cpu") + lidar_data.points.torch.fill_(1.0) + lidar_data.intensity.torch.fill_(1.0) + lidar_data.valid.torch.fill_(True) + return lidar_data + + def copy(point_cloud, _lidar_data, _device): + if point_cloud == "incomplete": + raise RuntimeError("buffer must be a raw resource") + copied.append(point_cloud) + renderer = _make_mocked_scene_renderer(monkeypatch, use_ovstage=False, clone_env_paths=[]) - renderer._warp_device = types.SimpleNamespace(stream=types.SimpleNamespace(cuda_stream=1)) + monkeypatch.setattr(renderer, "_copy_mapped_lidar_point_cloud", copy) + lidar = ovrtx_renderer_module.OVRTXLidarRenderData("Lidar", 0.1, ["/Lidar"]) - cloud = MagicMock() - cloud.map.side_effect = [ - RuntimeError("Failed to map CUDA point cloud"), - RuntimeError("Failed to map CPU point cloud"), + copied = [] + + # The newest complete lidar scan is returned. + frames = [ + types.SimpleNamespace(end_time=0.3, render_vars={lidar.point_cloud_path: "newest"}), + types.SimpleNamespace(end_time=0.2, render_vars={lidar.point_cloud_path: "middle"}), + types.SimpleNamespace(end_time=0.1, render_vars={lidar.point_cloud_path: "oldest"}), ] - frame = types.SimpleNamespace(render_vars={lidar.point_cloud_path: cloud}) - products = {lidar.render_product_path: types.SimpleNamespace(frames=[frame])} - with pytest.raises(RuntimeError, match="Failed to map CPU point cloud"): - renderer._publish_lidar_output(lidar, products, LidarData(1, 1, "cpu")) + products = {lidar.render_product_path: types.SimpleNamespace(frames=frames)} + renderer._publish_lidar_output(lidar, products, new_lidar_data()) + assert copied == ["newest"] + + # If the newest frame is incomplete, the middle frame is returned. + copied.clear() + frames[0].render_vars = {lidar.point_cloud_path: "incomplete"} + renderer._publish_lidar_output(lidar, products, new_lidar_data()) + assert copied == ["middle"] + + # If all frames are incomplete, the lidar data is cleared. + copied.clear() + for frame in frames[1:]: + frame.render_vars = {lidar.point_cloud_path: "incomplete"} + lidar_data = new_lidar_data() + renderer._publish_lidar_output(lidar, products, lidar_data) + assert copied == [] + assert not torch.isfinite(lidar_data.points.torch).any() + assert lidar_data.intensity.torch.eq(0).all() + assert not lidar_data.valid.torch.any() + + # If the lidar product is empty, the lidar data is cleared. + lidar_data = new_lidar_data() + renderer._publish_lidar_output(lidar, {lidar.render_product_path: types.SimpleNamespace(frames=[])}, lidar_data) + assert copied == [] + assert not torch.isfinite(lidar_data.points.torch).any() + assert lidar_data.intensity.torch.eq(0).all() + assert not lidar_data.valid.torch.any() + + # If the point cloud is missing in the lidar frames , an error is raised. + missing = { + lidar.render_product_path: types.SimpleNamespace(frames=[types.SimpleNamespace(end_time=0.1, render_vars={})]) + } + with pytest.raises(KeyError): + renderer._publish_lidar_output(lidar, missing, new_lidar_data()) @pytest.mark.parametrize("missing", ["product", "renderer", "backend"]) From 68d64129fb47e862018e776f789f705d23f004af Mon Sep 17 00:00:00 2001 From: HuiDong Chen Date: Mon, 30 Nov 2026 21:41:37 +0800 Subject: [PATCH 02/16] frame rate docstring improvement --- source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py index f7be76a4e66e..c8248d9e29d2 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py @@ -36,7 +36,10 @@ class OVRTXLidarCfg(LidarCfg): renderer_cfg: OVRTXRendererCfg = OVRTXRendererCfg(motion_bvh="auto") frame_rate: tuple[float, float] = (10.0, 1.0) - """USD ``omni:sensor:frameRate`` rational ``(numerator, denominator)``. Defaults to ``(10.0, 1.0)``.""" + """USD ``omni:sensor:frameRate`` rational ``(numerator, denominator)``, in hertz. Defaults to ``(10.0, 1.0)``. + + ``numerator / denominator`` is the number of scans per second. ``(10.0, 1.0)`` is 10 Hz, so one scan lasts 0.1 s. + """ scan_type: Literal["rotary", "solidState"] = "rotary" """USD ``scanType`` token. Defaults to ``rotary``. From d8a7e7281ffe2d15cd42c0bde3ce2d35a826ce8a Mon Sep 17 00:00:00 2001 From: HuiDong Chen Date: Tue, 1 Dec 2026 13:37:48 +0800 Subject: [PATCH 03/16] Keep the previous lidar scan when OVRTX publishes no complete frame - Copy the newest frame directly on OVRTX 1.0. - On pre-1.0, skip one "Failed to map output" and raise on a second. - Leave the previous lidar data in place instead of clearing it. --- .../isaaclab_ov/renderers/ovrtx_renderer.py | 63 +++++++++++++------ .../test/test_ovrtx_renderer_contract.py | 25 ++++---- 2 files changed, 57 insertions(+), 31 deletions(-) diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index 1df6eafe9839..3a9f808f627e 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -34,9 +34,12 @@ from builtins import ExceptionGroup from collections import deque from collections.abc import Callable, Iterable, Iterator, Sequence +from importlib.metadata import PackageNotFoundError, version from pathlib import Path from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar +from packaging.version import Version + logger = logging.getLogger(__name__) import numpy as np @@ -126,6 +129,13 @@ from isaaclab.renderers.camera_render_spec import CameraRenderSpec +try: + OVRTX_VERSION = Version(version("ovrtx")) +except PackageNotFoundError: + # Documentation mocks the native runtime without installing its distribution. + OVRTX_VERSION = None + +_RENDER_DELTA_TIME = 1.0 / 60.0 _FAILED_FRAME_TEXT = "failed to produce a frame" _FAILED_FRAME_NOTE = ( "One cause of a failed frame is a camera sensor with too many environments." @@ -1031,34 +1041,49 @@ def _publish_lidar_output( ) -> None: """Copy the newest complete lidar scan into ``lidar_data``. - A step can return several frames when the render steps across multiple lidar frame boundaries. The newest - frame that contains complete lidar scan is published. When no frame contains a complete lidar scan, every - return is cleared to a miss. - """ - markers = ["failed to map", "unpublish", "point cloud was empty", "raw resource"] + A step can return several frames when the render steps across multiple lidar frame boundaries. + When the product has no frames, the previous returns in ``lidar_data`` stay in place. - # The frame array does not promise an order, so sort by end_time and prioritize newer frames over older ones. + OVRTX 1.0 and newer do not return incomplete lidar scans, so the newest frame is copied directly and a + map failure propagates. Pre-1.0 ovrtx can return one incomplete scan, so the first ``Failed to map + output`` among the two newest frames is skipped and the older frame is tried. A second failure is raised: + the older frame is the one expected to be complete, and swallowing it would hide a real publish error. + When the only candidate frame is incomplete, the previous returns in ``lidar_data`` stay in place. + """ + # The frame array does not promise an order. frames = products[render_data.render_product_path].frames - frames.sort(key=lambda frame: frame.end_time, reverse=True) - for frame in frames: - # TODO: rework the exception handling on OVRTX 1.0 which won't return incomplete lidar scans. - try: + # ovrtx 1.0 and above will not return incomplete lidar scans. + if OVRTX_VERSION and OVRTX_VERSION.major >= 1: + if frames: + frame = max(frames, key=lambda frame: frame.end_time) self._copy_mapped_lidar_point_cloud( frame.render_vars[render_data.point_cloud_path], lidar_data, Device.CUDA ) - except Exception as exc: - message = str(exc).lower() - if all(marker not in message for marker in markers): - raise - continue - - # A complete lidar scan was produced in this step. Return to break the loop. return - # No complete lidar scan was produced in this step. Drop the previous data so it is not read as the new one. - lidar_data.clear() + # Pre-1.0 needs the two newest frames to allow one incomplete scan, so sort once. Pre-1.0 ovrtx can pair + # the in-progress frame with the previous complete frame, so the first "Failed to map output" skips to + # the older frame. A second one is a failure of the frame that should have been complete, and must + # propagate. + frames = sorted(frames, key=lambda frame: frame.end_time, reverse=True) + found_unpublished_output = False + + for frame in frames[:2]: + try: + self._copy_mapped_lidar_point_cloud( + frame.render_vars[render_data.point_cloud_path], lidar_data, Device.CUDA + ) + + # A complete lidar scan was produced in this step. Break the loop. + break + except Exception as exc: + if not found_unpublished_output and "Failed to map output" in str(exc): + found_unpublished_output = True + continue + + raise def _copy_mapped_lidar_point_cloud( self, point_cloud: RenderVarOutput, lidar_data: LidarData, device: Device diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py index 42ffba2f8234..33619719740b 100644 --- a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py @@ -482,7 +482,7 @@ def new_lidar_data(): def copy(point_cloud, _lidar_data, _device): if point_cloud == "incomplete": - raise RuntimeError("buffer must be a raw resource") + raise RuntimeError("Failed to map output") copied.append(point_cloud) renderer = _make_mocked_scene_renderer(monkeypatch, use_ovstage=False, clone_env_paths=[]) @@ -507,24 +507,25 @@ def copy(point_cloud, _lidar_data, _device): renderer._publish_lidar_output(lidar, products, new_lidar_data()) assert copied == ["middle"] - # If all frames are incomplete, the lidar data is cleared. + # A second incomplete frame is a real publish failure. The first is skipped, so nothing is copied + # and the previous returns stay in place. copied.clear() - for frame in frames[1:]: - frame.render_vars = {lidar.point_cloud_path: "incomplete"} + frames[1].render_vars = {lidar.point_cloud_path: "incomplete"} lidar_data = new_lidar_data() - renderer._publish_lidar_output(lidar, products, lidar_data) + with pytest.raises(RuntimeError, match="Failed to map output"): + renderer._publish_lidar_output(lidar, products, lidar_data) assert copied == [] - assert not torch.isfinite(lidar_data.points.torch).any() - assert lidar_data.intensity.torch.eq(0).all() - assert not lidar_data.valid.torch.any() + assert lidar_data.points.torch.eq(1).all() + assert lidar_data.intensity.torch.eq(1).all() + assert lidar_data.valid.torch.all() - # If the lidar product is empty, the lidar data is cleared. + # If the lidar product is empty, the previous returns stay in place. lidar_data = new_lidar_data() renderer._publish_lidar_output(lidar, {lidar.render_product_path: types.SimpleNamespace(frames=[])}, lidar_data) assert copied == [] - assert not torch.isfinite(lidar_data.points.torch).any() - assert lidar_data.intensity.torch.eq(0).all() - assert not lidar_data.valid.torch.any() + assert lidar_data.points.torch.eq(1).all() + assert lidar_data.intensity.torch.eq(1).all() + assert lidar_data.valid.torch.all() # If the point cloud is missing in the lidar frames , an error is raised. missing = { From cdfeec32f2cc133b320e995530f1bf9ca5e4b928 Mon Sep 17 00:00:00 2001 From: HuiDong Chen Date: Tue, 1 Dec 2026 13:58:36 +0800 Subject: [PATCH 04/16] Expect the previous lidar scan to stay between completed scans test_lidar_capture required every return to be invalid on a step that did not close a scan. After a completed scan, those returns stay in place until the next complete frame, so the test now checks that the held scan is unchanged. --- source/isaaclab_ov/test/test_ovrtx_lidar.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/source/isaaclab_ov/test/test_ovrtx_lidar.py b/source/isaaclab_ov/test/test_ovrtx_lidar.py index 1c26306280b6..d82c86dc6fbc 100644 --- a/source/isaaclab_ov/test/test_ovrtx_lidar.py +++ b/source/isaaclab_ov/test/test_ovrtx_lidar.py @@ -365,6 +365,8 @@ class SceneCfg(InteractiveSceneCfg): lidar_time = 0.0 since_capture = 0.0 closed_scan = False + # A step that does not close a scan leaves the last complete scan in place. + held_scan = None # Half a second of sim time, reading the lidar every step like an observation term. for step in range(math.ceil(0.5 / dt)): sim.step() @@ -378,10 +380,22 @@ class SceneCfg(InteractiveSceneCfg): closed_scan = instant_lidar or math.floor((lidar_time + 1e-9) / scan_period) > math.floor( (previous + 1e-9) / scan_period ) + data = lidar.data detail = f"instant={instant_lidar} update_period={update_period} step={step} lidar_time={lidar_time}" + if closed_scan: assert data.valid.torch.all(), f"{detail} returned an incomplete scan" assert torch.isfinite(data.points.torch).all(), f"{detail} returned a non-finite hit" + held_scan = ( + data.points.torch.clone(), + data.intensity.torch.clone(), + data.valid.torch.clone(), + ) + elif held_scan is not None: + points, intensity, valid = held_scan + torch.testing.assert_close(data.points.torch, points, msg=f"{detail} changed a held scan") + torch.testing.assert_close(data.intensity.torch, intensity, msg=f"{detail} changed a held scan") + torch.testing.assert_close(data.valid.torch, valid, msg=f"{detail} changed a held scan") else: assert not data.valid.torch.all(), f"{detail} published a finished scan early" From 7e51ca0bee8f138170f7518fbbb10e43a92472cf Mon Sep 17 00:00:00 2001 From: HuiDong Chen Date: Tue, 1 Dec 2026 14:06:50 +0800 Subject: [PATCH 05/16] Reverted unnecessary changes --- .../isaaclab/changelog.d/huidongc-lidar-clear.added.rst | 1 - source/isaaclab/changelog.d/huidongc-lidar-clear.minor | 0 source/isaaclab/isaaclab/sensors/lidar/lidar_data.py | 9 --------- 3 files changed, 10 deletions(-) delete mode 100644 source/isaaclab/changelog.d/huidongc-lidar-clear.added.rst delete mode 100644 source/isaaclab/changelog.d/huidongc-lidar-clear.minor diff --git a/source/isaaclab/changelog.d/huidongc-lidar-clear.added.rst b/source/isaaclab/changelog.d/huidongc-lidar-clear.added.rst deleted file mode 100644 index 284f59152ae3..000000000000 --- a/source/isaaclab/changelog.d/huidongc-lidar-clear.added.rst +++ /dev/null @@ -1 +0,0 @@ -* Added :meth:`~isaaclab.sensors.lidar.lidar_data.LidarData.clear` to reset every lidar return to a miss. diff --git a/source/isaaclab/changelog.d/huidongc-lidar-clear.minor b/source/isaaclab/changelog.d/huidongc-lidar-clear.minor deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/source/isaaclab/isaaclab/sensors/lidar/lidar_data.py b/source/isaaclab/isaaclab/sensors/lidar/lidar_data.py index e8755e77c710..2f1c45b17653 100644 --- a/source/isaaclab/isaaclab/sensors/lidar/lidar_data.py +++ b/source/isaaclab/isaaclab/sensors/lidar/lidar_data.py @@ -29,15 +29,6 @@ def __init__(self, num_envs: int, num_rays: int, device: str): self._intensity = ProxyArray(wp.zeros((num_envs, num_rays), dtype=wp.float32, device=device)) self._valid = ProxyArray(wp.zeros((num_envs, num_rays), dtype=wp.bool, device=device)) - def clear(self) -> None: - """Reset every return to a miss. - - Points become non-finite. Intensity and validity become zero. - """ - self._points.warp.fill_(wp.vec3f(wp.inf)) - self._intensity.warp.fill_(0.0) - self._valid.warp.fill_(False) - @property def points(self) -> ProxyArray: """Cartesian XYZ positions in meters in the configured output frame. From f33d46c69b5f7d92e7fbd41ec02d3fe219aa0566 Mon Sep 17 00:00:00 2001 From: HuiDong Chen Date: Tue, 1 Dec 2026 14:07:09 +0800 Subject: [PATCH 06/16] Updated the changelog fragments --- .../isaaclab_ov/changelog.d/huidongc-lidar-scan.added.rst | 1 + .../changelog.d/huidongc-lidar-scan.changed.rst | 7 +++++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.added.rst b/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.added.rst index a87de0457446..a50262b6ebd9 100644 --- a/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.added.rst +++ b/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.added.rst @@ -1 +1,2 @@ * Added ``frame_rate`` to :class:`~isaaclab_ov.renderers.ovrtx_lidar_cfg.OVRTXLidarCfg` and authored it as ``omni:sensor:frameRate``. + The default is ``(10.0, 1.0)`` (10 Hz). The numerator and denominator must be finite and positive. diff --git a/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.changed.rst b/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.changed.rst index ae18430f1f89..ff74f3e21dca 100644 --- a/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.changed.rst +++ b/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.changed.rst @@ -1,4 +1,7 @@ -* Changed ``instant_lidar`` to default to ``False``, so rays are spread across the lidar frame instead of emitted in one render step. +* **Breaking:** Changed ``instant_lidar`` to default to ``False``, so rays are spread across the lidar frame instead of emitted in one render step. Set ``instant_lidar=True`` on the config passed to ``spawn_lidar`` to restore a complete scan per capture. -* Published the newest complete lidar scan and cleared every return when a step has no complete scan. +* Changed lidar capture to copy the newest complete scan. OVRTX 1.0 and newer copy that frame directly. + Older OVRTX skips one unmapped in-progress frame and copies the previous complete frame. + A second map failure is raised. When a step has no frames, or the only candidate frame is incomplete, the previous returns stay in place. A partial or unmapped point cloud is no longer copied from a CPU fallback. +* Removed the authored ``cameraSensorType`` attribute from spawned OmniLidar prims. From 73972c5e084f813294d66e64a23eb3fa248c046f Mon Sep 17 00:00:00 2001 From: HuiDong Chen Date: Tue, 1 Dec 2026 19:52:30 +0800 Subject: [PATCH 07/16] Add more docstring for frame_rate config --- source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py index c8248d9e29d2..b2551d2ca107 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py @@ -39,6 +39,12 @@ class OVRTXLidarCfg(LidarCfg): """USD ``omni:sensor:frameRate`` rational ``(numerator, denominator)``, in hertz. Defaults to ``(10.0, 1.0)``. ``numerator / denominator`` is the number of scans per second. ``(10.0, 1.0)`` is 10 Hz, so one scan lasts 0.1 s. + + With ``instant_lidar`` left false, rays are spread across that scan duration. A complete cloud is published only + when the scan closes. When the scan lasts longer than ``update_period``, the scan rate limits how often a new + complete cloud appears. A shorter update period simulates the sensor at a finer time resolution, but it does not + publish new complete scans any faster. When ``update_period`` is longer than one scan, clouds are published only + at that slower rate. One update can span more than one scan, and the newest complete scan is the one published. """ scan_type: Literal["rotary", "solidState"] = "rotary" From 59ffbad33da36612305a83826c1ca213233474fc Mon Sep 17 00:00:00 2001 From: HuiDong Chen Date: Tue, 1 Dec 2026 21:07:42 +0800 Subject: [PATCH 08/16] Improve docstring --- .../isaaclab_ov/renderers/ovrtx_lidar_cfg.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py index b2551d2ca107..75fcc253ae55 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py @@ -40,11 +40,11 @@ class OVRTXLidarCfg(LidarCfg): ``numerator / denominator`` is the number of scans per second. ``(10.0, 1.0)`` is 10 Hz, so one scan lasts 0.1 s. - With ``instant_lidar`` left false, rays are spread across that scan duration. A complete cloud is published only - when the scan closes. When the scan lasts longer than ``update_period``, the scan rate limits how often a new - complete cloud appears. A shorter update period simulates the sensor at a finer time resolution, but it does not - publish new complete scans any faster. When ``update_period`` is longer than one scan, clouds are published only - at that slower rate. One update can span more than one scan, and the newest complete scan is the one published. + With ``instant_lidar`` left false, rays are spread across that scan duration. The sensor simulation step that + closes the scan publishes that complete cloud. A step that closes no scan leaves the previous cloud in place. + A shorter simulation step simulates the lidar scan at a finer time resolution, while a new complete scan is still + published only as often as ``frame_rate``. A longer simulation step may span more than one scan, and the newest + complete scan is the one published. """ scan_type: Literal["rotary", "solidState"] = "rotary" @@ -99,7 +99,10 @@ class OVRTXLidarCfg(LidarCfg): """Native coordinate encoding. Both modes publish Cartesian XYZ positions in meters. Defaults to ``CARTESIAN``.""" instant_lidar: bool = False - """If true, all rays are emitted at the frame timestamp. Defaults to False.""" + """Whether one render step publishes a complete scan. Defaults to False. + + If true, all rays are emitted at the frame timestamp. + """ include_invalid_points: bool = True """Keep missed rays in their original slots. Tiled OvRTX lidar requires True. From 3c5a8025ac4826de18238a169c5863ee7ac53ea4 Mon Sep 17 00:00:00 2001 From: Alexander Temirov Date: Tue, 1 Dec 2026 16:42:21 -0800 Subject: [PATCH 09/16] Step each OVRTX engine once per physics step for all its sensors --- .../ovrtx-shared-engine-step.fixed.rst | 4 + .../renderers/ovrtx_lidar_sensor.py | 28 ++-- .../isaaclab_ov/renderers/ovrtx_renderer.py | 125 ++++++++++-------- source/isaaclab_ov/test/test_ovrtx_lidar.py | 84 +++++++++++- .../test/test_ovrtx_renderer_contract.py | 74 +++++++---- .../test/test_ovrtx_visual_material_sync.py | 4 +- 6 files changed, 228 insertions(+), 91 deletions(-) create mode 100644 source/isaaclab_ov/changelog.d/ovrtx-shared-engine-step.fixed.rst diff --git a/source/isaaclab_ov/changelog.d/ovrtx-shared-engine-step.fixed.rst b/source/isaaclab_ov/changelog.d/ovrtx-shared-engine-step.fixed.rst new file mode 100644 index 000000000000..bfe8b36c6cd6 --- /dev/null +++ b/source/isaaclab_ov/changelog.d/ovrtx-shared-engine-step.fixed.rst @@ -0,0 +1,4 @@ +* Fixed OVRTX cameras and lidars on one engine each stepping its clock on their own reads, which counted the same + physics time more than once and left lidars out of each other's steps. A read now steps the engine only when + physics advanced since its last step, by that simulated time instead of the rendering time step, with every + camera and lidar product. Each lidar keeps its scan from that step until its sensor reads it. diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_sensor.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_sensor.py index 0f1e9adfaa15..bf1d3771d44e 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_sensor.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_sensor.py @@ -15,6 +15,7 @@ from __future__ import annotations import sys +import weakref from typing import TYPE_CHECKING import torch @@ -209,13 +210,13 @@ def update(self, dt: float, force_recompute: bool = False): Args: dt: Time elapsed since the previous sensor update, in seconds. - force_recompute: When True, capture again even if the sampling period has not expired. + force_recompute: When True, publish the latest scan even if the sampling period has not expired. """ self._force_capture = force_recompute try: if force_recompute and self._is_initialized: - # A repeated read in this physics step must render again. The base update only - # captures when the buffers are dirty. + # Another sensor may have stepped the engine and kept a newer scan. The base update only + # refreshes when the buffers are dirty. self._data_dirty = True super().update(dt, force_recompute=force_recompute) finally: @@ -237,12 +238,16 @@ def reset(self, env_ids=None, env_mask=None) -> None: if self._data is None: return - wp.launch( - _clear_lidar_returns_kernel, - dim=(self._num_envs, self._data.points.warp.shape[1]), - inputs=[reset_mask, self._data.points.warp, self._data.intensity.warp, self._data.valid.warp], - device=self._device, - ) + # Clear the kept scan too, so a read before the next timed step cannot restore the old returns. + for data in (self._data, self._render_data.scan if self._render_data is not None else None): + if data is None: + continue + wp.launch( + _clear_lidar_returns_kernel, + dim=(self._num_envs, data.points.warp.shape[1]), + inputs=[reset_mask, data.points.warp, data.intensity.warp, data.valid.warp], + device=self._device, + ) def _initialize_impl(self): """Allocate the return buffers and register the tiled lidar product.""" @@ -269,6 +274,8 @@ def _initialize_impl(self): positions, rotations = self.cfg.offset.pos, self.cfg.offset.rot self._local_pos = torch.tensor(positions, dtype=torch.float32, device=self._device) self._local_quat = torch.tensor(rotations, dtype=torch.float32, device=self._device) + # Any sensor on the engine can step it, so the engine writes this pose before every timed step. + self._render_data.prepare = weakref.WeakMethod(self._push_renderer_pose) self._push_renderer_pose() def _invalidate_initialize_callback(self, event): @@ -288,14 +295,13 @@ def _invalidate_initialize_callback(self, event): def _update_buffers_impl(self, env_mask: wp.array): """Capture every tile when any environment is due. A tiled product cannot render one tile. - A forced capture still renders when the sampling period has not expired. ``update`` marks + A forced capture still publishes when the sampling period has not expired. ``update`` marks the buffers dirty without filling ``_is_outdated``, so the empty mask is not a reason to keep the previous scan. """ if self.cfg.update_period > 0.0 and not self._force_capture and not bool(env_mask.numpy().any()): return - self._push_renderer_pose() self._sim.render_context.update_scene_state(self._sim.get_physics_step_count()) self._renderer.render_lidar(self._render_data, self._data) diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index 3a9f808f627e..699d199e81b4 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -78,6 +78,7 @@ from isaaclab.renderers._rtx_renderer_cfg import _SIMPLE_SHADING_MODES from isaaclab.scene_data import SceneDataFormat from isaaclab.sensors.camera.camera_data import CameraData +from isaaclab.sensors.lidar.lidar_data import LidarData from isaaclab.sim import PreviewSurfaceCfg, SimulationContext, use_stage from isaaclab.utils.warp import ProxyArray @@ -122,7 +123,6 @@ from ovrtx import AttributeBinding, FrameOutput, Operation, PendingFetch, RenderVarOutput from isaaclab.renderers.base_renderer import VisualMaterialBatch - from isaaclab.sensors import LidarData from isaaclab_ov.renderers.ovrtx_lidar_cfg import OVRTXLidarCfg from isaaclab_ov.stage import OvstageBackend @@ -330,6 +330,11 @@ def __init__(self, cfg: OVRTXBackendCfg): self.cfg = cfg self.attached = False self.render_products: set[str] = set() + # Physics step count at this engine's previous timed step. The engine has one clock, so every renderer on it + # shares the count. It starts here, so the clock stays at the simulated time since the engine was created. + self.step_count = SimulationContext.instance().get_physics_step_count() + # Lidars of every renderer on this engine, and their renderers. Every timed step scans all of them. + self.lidars: dict[OVRTXLidarRenderData, OVRTXRenderer] = {} # Camera sensors of every renderer on this engine without a rendered frame, and their renderers. self.unrendered: dict[OVRTXCameraRenderData, OVRTXRenderer] = {} # Resolve the wheel's native dependency here, including callers without a viewer. @@ -547,16 +552,19 @@ def _set_layout(self, render_scope_name: str, max_envs: int) -> None: class OVRTXLidarRenderData: - """Native resources and capture interval for one tiled lidar.""" + """Native resources and latest scan of one tiled lidar.""" - def __init__(self, scope: str, sample_dt: float, lidar_paths: list[str]): + def __init__(self, scope: str, lidar_paths: list[str], scan: LidarData): self.lidar_paths = lidar_paths self.render_product_path = f"/{scope}/RenderProduct" self.point_cloud_path = f"/{scope}/Vars/PointCloud" self.xform_binding: AttributeBinding[wp.array] | ovstage.Query | None = None self.resources = contextlib.ExitStack() self.pose_writes = _AsyncWriteBuffers[wp.array]() - self.sample_dt = sample_dt + self.scan = scan + """Latest scan. Any sensor's read can step the engine, so the scan waits here until this lidar is read.""" + self.prepare: weakref.WeakMethod | None = None + """Writes the lidar's current pose before a timed step. Weak, so the engine does not keep the sensor alive.""" def cleanup(self) -> None: """Release the pose writes before releasing the binding.""" @@ -862,8 +870,7 @@ def create_lidar_render_data( ) scope = f"RenderLidar_{self.scene.next_camera_id}" - update_period = float(cfg.update_period) - render_data = OVRTXLidarRenderData(scope, update_period or self._sim.get_physics_dt(), lidar_paths) + render_data = OVRTXLidarRenderData(scope, lidar_paths, LidarData(num_envs, cfg.num_rays(), self._device)) product_path = render_data.render_product_path usd = build_lidar_render_product_as_string( @@ -955,6 +962,8 @@ def create_lidar_render_data( self.scene.next_camera_id += 1 self._lidars.append(render_data) + self.backend.lidars[render_data] = self + render_data.resources.callback(self.backend.lidars.pop, render_data, None) return render_data @contextlib.contextmanager @@ -987,54 +996,23 @@ def _map_lidar_point_cloud(self, point_cloud: RenderVarOutput, device: Device) - mapping.unmap(stream=stream) def render_lidar(self, render_data: OVRTXLidarRenderData, lidar_data: LidarData) -> None: - """Capture one tiled lidar product and publish its point cloud. + """Publish the latest scan of one lidar, after stepping the engine if physics advanced since its last step. - The capture submits only this lidar. Another lidar's pose is written when that lidar - captures, so including it here would replace its buffers with a scan from a stale pose. - Camera products stay on the camera step. A lidar needs the point cloud immediately, so this - submission waits. + The engine has one clock, so each timed step scans every lidar on it and renders every camera product. A + camera or another lidar may have stepped the engine first; this lidar's scan then waits in its render data. """ if not self._initialized_scene: raise RuntimeError("Scene not initialized. Call initialize() first.") - - lidars = self._lidars if self.backend is None or self.backend.renderer is None: raise RuntimeError(f"Cannot capture {render_data.render_product_path!r}: OvRTX renderer is unavailable.") - if render_data not in lidars: + if render_data not in self._lidars: raise RuntimeError(f"OvRTX lidar product {render_data.render_product_path!r} is not registered.") - delta_time = render_data.sample_dt - - # The first step initializes GPU transforms from authored poses and must not advance any - # lidar clock. The capture itself includes only the lidar whose pose was just written. - products = {data.render_product_path for data in lidars} - requested = {render_data.render_product_path} - - material_writer = self._visual_material_writer_ref() if self._visual_material_writer_ref is not None else None - try: - if material_writer is not None: - material_writer.publish() - if self._needs_transform_initialization: - self.backend.renderer.step(render_products=products, delta_time=0.0) - self._needs_transform_initialization = False - if self._use_ovstage: - ordinal = self.scene.commit() - else: - result = self.backend.renderer.step(render_products=requested, delta_time=delta_time) - finally: - if material_writer is not None: - primary_active = sys.exc_info()[0] is not None - try: - material_writer.drain() - except Exception as exc: - if not primary_active: - raise - logger.warning("Error draining material writes after a failed render: %s", exc, exc_info=True) - - if self._use_ovstage: - result = self.backend.renderer.step(render_products=requested, delta_time=delta_time, ordinal=ordinal) - - self._publish_lidar_output(render_data, result, lidar_data) + if self._sim.get_physics_step_count() != self.backend.step_count: + self._render_with_retry(()) + wp.copy(lidar_data.points.warp, render_data.scan.points.warp) + wp.copy(lidar_data.intensity.warp, render_data.scan.intensity.warp) + wp.copy(lidar_data.valid.warp, render_data.scan.valid.warp) def _publish_lidar_output( self, render_data: OVRTXLidarRenderData, products: RenderProductSetOutputs, lidar_data: LidarData @@ -1946,6 +1924,13 @@ def render_batch(self, render_data: Sequence[OVRTXCameraRenderData]) -> None: ) from failed.first_frame_error if self.backend.renderer is None or not self._camera_render_data: return + self._render_with_retry(render_data) + + def _render_with_retry(self, render_data: Sequence[OVRTXCameraRenderData]) -> None: + """Step the engine and read back ``render_data``, moving cameras whose first frame fails to smaller layouts. + + A lidar read steps with no cameras requested, but the step still renders every camera product on the engine. + """ # TODO: Remove the split search once OVRTX renders a tiled image of any size. # After _MAX_SMALLER_LAYOUTS smaller layouts, the plan halves no sensor, so the loop ends. for num_smaller_layouts in itertools.count(): @@ -2080,11 +2065,20 @@ def _copy_render_product_attributes(self, source: str, targets: Sequence[str]) - ) def _render_batch_once(self, render_data: Sequence[OVRTXCameraRenderData]) -> None: - """Render one step with every registered render product, and read back the images of ``render_data``.""" + """Render one step with every registered render product, and read back the images of ``render_data``. + + A step after physics advanced is timed: it scans every lidar on the engine and keeps each scan for its sensor. + Every lidar product is submitted on every step, because a product left out of a timed step loses that time. + """ products = self.backend.render_products.copy() - # OVRTX uses the step delta only for temporal effects such as motion blur and motion - # vectors, so it must match the simulated time between rendered frames. - delta_time = self._sim.get_rendering_dt() + products.update(data.render_product_path for data in self.backend.lidars) + lidars = () + if self._sim.get_physics_step_count() != self.backend.step_count: + lidars = tuple(self.backend.lidars.items()) + for data, _ in lidars: + prepare = data.prepare() if data.prepare is not None else None + if prepare is not None: + prepare() material_writer = self._visual_material_writer_ref() if self._visual_material_writer_ref is not None else None try: if material_writer is not None: @@ -2099,11 +2093,14 @@ def _render_batch_once(self, render_data: Sequence[OVRTXCameraRenderData]) -> No ordinal = self.scene.commit() elif self.cfg.async_rendering: unread = {data.ready[0] for data in render_data if data.ready is not None} - operation = self.backend.renderer.step_async(render_products=products, delta_time=delta_time) + operation = self.backend.renderer.step_async(render_products=products, delta_time=self._step_dt()) if self.backend.unrendered: # While a sensor has no rendered frame, the step waits for its frame, so a failed frame raises # where the search can act. operation.wait() + if lidars: + # The next step replaces the lidar outputs, so keep the scans now. Fetching twice is allowed. + self._keep_lidar_scans(operation.wait().fetch(), lidars) for data in render_data: previous = data.pending data.pending = (operation, data.capture) @@ -2112,7 +2109,8 @@ def _render_batch_once(self, render_data: Sequence[OVRTXCameraRenderData]) -> No for previous in unread: previous.wait().fetch() else: - result = self.backend.renderer.step(render_products=products, delta_time=delta_time) + result = self.backend.renderer.step(render_products=products, delta_time=self._step_dt()) + self._keep_lidar_scans(result, lidars) self._process_render_products(render_data, result) finally: if material_writer is not None: @@ -2129,9 +2127,30 @@ def _render_batch_once(self, render_data: Sequence[OVRTXCameraRenderData]) -> No if self._use_ovstage: # Stage writes and material reads finish before rendering. Consume only after advancing # the ordinal so a failed readback cannot leave later writes at the sealed floor. - result = self.backend.renderer.step(render_products=products, delta_time=delta_time, ordinal=ordinal) + result = self.backend.renderer.step(render_products=products, delta_time=self._step_dt(), ordinal=ordinal) + self._keep_lidar_scans(result, lidars) self._process_render_products(render_data, result) + def _step_dt(self) -> float: + """Claim the simulated time since this engine's previous timed step [s]. + + OVRTX uses the step delta for temporal effects such as motion blur and motion vectors and for lidar scans, so + it must match the simulated time. The count belongs to the engine, so a second step in the same physics step, + for example for another camera, steps by zero. Call when submitting the step: a failed preparation leaves the + time for the retry. + """ + count = self._sim.get_physics_step_count() + previous, self.backend.step_count = self.backend.step_count, count + return (count - previous) * self._sim.get_physics_dt() + + @staticmethod + def _keep_lidar_scans( + products: RenderProductSetOutputs, lidars: Sequence[tuple[OVRTXLidarRenderData, OVRTXRenderer]] + ) -> None: + """Copy each lidar's scan into its render data before the next step replaces the native output.""" + for data, renderer in lidars: + renderer._publish_lidar_output(data, products, data.scan) + def cleanup(self, render_data: OVRTXCameraRenderData | None) -> None: """Release the render data's buffers. See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.cleanup`. diff --git a/source/isaaclab_ov/test/test_ovrtx_lidar.py b/source/isaaclab_ov/test/test_ovrtx_lidar.py index d82c86dc6fbc..9fbfc0551604 100644 --- a/source/isaaclab_ov/test/test_ovrtx_lidar.py +++ b/source/isaaclab_ov/test/test_ovrtx_lidar.py @@ -232,6 +232,86 @@ class SceneCfg(InteractiveSceneCfg): torch.testing.assert_close(lidar.data.points.torch[1], kept) +@pytest.mark.integration +@pytest.mark.rendering +@pytest.mark.ov +@pytest.mark.skipif(not wp.is_cuda_available(), reason="Tiled lidar capture requires CUDA.") +def test_camera_and_lidars_on_one_engine_advance_its_clock_by_physics_time(monkeypatch): + """Reads of a camera and two lidars on one engine, in any order, step its clock once per physics step.""" + import ovrtx + from isaaclab_ov.physics import OvPhysxCfg + + import isaaclab.sim as sim_utils + from isaaclab.assets import RigidObjectCfg + from isaaclab.scene import InteractiveSceneCfg + from isaaclab.sensors import CameraCfg + from isaaclab.utils import configclass, instantiate, replace + + steps = [] + native_step = ovrtx.Renderer.step + + def record(self, **kwargs): + steps.append((kwargs["delta_time"], frozenset(kwargs["render_products"]))) + return native_step(self, **kwargs) + + monkeypatch.setattr(ovrtx.Renderer, "step", record) + + @configclass + class SceneCfg(InteractiveSceneCfg): + target = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Target", + spawn=sim_utils.CuboidCfg( + size=(4.0, 4.0, 1.0), + rigid_props=sim_utils.UsdPhysicsRigidBodyCfg(kinematic_enabled=True), + collision_props=sim_utils.UsdPhysicsCollisionCfg(), + mass_props=sim_utils.MassCfg(mass=1.0), + ), + ) + lidar = _lidar_cfg( + prim_path="{ENV_REGEX_NS}/Lidar", + scan_type="solidState", + azimuth_deg=[-8.0, 12.0], + elevation_deg=[-5.0, 10.0], + fire_time_ns=[0, 0], + channel_id=[0, 1], + offset=OVRTXLidarCfg.OffsetCfg(pos=(0.2, 0.1, 3.0), rot=(0.0, 0.0, 0.5, math.sqrt(0.75))), + ) + other_lidar = replace(lidar, prim_path="{ENV_REGEX_NS}/OtherLidar") + # The lidars' renderer settings, so the camera renders on their engine. + camera = CameraCfg( + prim_path="{ENV_REGEX_NS}/Camera", + height=16, + width=16, + data_types=["rgb"], + spawn=sim_utils.PinholeCameraCfg(clipping_range=(0.1, 20.0)), + offset=CameraCfg.OffsetCfg(pos=(0.0, 0.0, 6.0), rot=(0.0, 0.0, 0.0, 1.0), convention="opengl"), + renderer_cfg=lidar.renderer_cfg, + ) + + with sim_utils.build_simulation_context(sim_cfg=sim_utils.SimulationCfg(physics=OvPhysxCfg())) as sim: + scene = instantiate(SceneCfg(num_envs=2, env_spacing=8.0)) + sim.register_interactive_scene(scene) + sim.reset() + camera, lidars = scene["camera"], (scene["lidar"], scene["other_lidar"]) + assert camera._renderer.backend is lidars[0]._renderer.backend is lidars[1]._renderer.backend + dt = sim.get_physics_dt() + orders = [(camera, *lidars), (lidars[1], camera, lidars[0]), (*lidars, camera)] + for order in orders: + sim.step() + scene.update(dt) + for sensor in order: + sensor.data + for lidar in lidars: + assert lidar.data.valid.torch.all() + + timed = [(delta, products) for delta, products in steps if delta > 0.0] + assert [delta for delta, _ in timed] == pytest.approx([dt] * len(orders)) + assert sum(delta for delta, _ in steps) == pytest.approx(len(orders) * dt) + expected = {lidar._render_data.render_product_path for lidar in lidars} + expected.update(camera._render_data.render_product_paths) + assert all(products == expected for _, products in steps) + + @pytest.mark.integration @pytest.mark.rendering @pytest.mark.ov @@ -361,7 +441,6 @@ class SceneCfg(InteractiveSceneCfg): lidar = scene["lidar"] numerator, denominator = frame_rate scan_period = denominator / numerator - sample_dt = update_period if update_period > 0.0 else dt lidar_time = 0.0 since_capture = 0.0 closed_scan = False @@ -375,7 +454,8 @@ class SceneCfg(InteractiveSceneCfg): # Reset leaves the sensor unsampled, so the first positive step always captures. if lidar_time == 0.0 or since_capture >= update_period - 1e-6: previous = lidar_time - lidar_time += sample_dt + # The engine clock follows physics, so a capture scans up to the current physics time. + lidar_time = (step + 1) * dt since_capture = 0.0 closed_scan = instant_lidar or math.floor((lidar_time + 1e-9) / scan_period) > math.floor( (previous + 1e-9) / scan_period diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py index 33619719740b..2cac02a013fc 100644 --- a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py @@ -87,8 +87,8 @@ # Tolerances (atol, rtol) of the color means. HDR color scales with the camera exposure, so its tolerance is relative. _SPLIT_COLOR_MEAN_TOLERANCES = {"rgb": (8.0, 0.0), "rgba": (8.0, 0.0), "rgb_hdr": (0.0, 0.05)} -_RENDERING_DT = 0.025 -"""Simulated time between rendered frames reported by the fake simulation context [s].""" +_PHYSICS_DT = 0.025 +"""Physics time step reported by the fake simulation context [s].""" def _make_camera_cfg(data_types: list[str]) -> CameraCfg: @@ -126,6 +126,8 @@ def _make_ovrtx_renderer_without_backend() -> OVRTXRenderer: renderer.backend.attached = False renderer.backend.render_products = set() renderer.backend.unrendered = {} + renderer.backend.step_count = 0 + renderer.backend.lidars = {} cfg = OVRTXBackendCfg(scene_key=renderer.cfg, use_ovstage=False, read_gpu_transforms=True, device="cpu") renderer.scene.stage = renderer.scene.paths = None renderer.backend.cfg = cfg @@ -186,7 +188,9 @@ def _simulation_registry(monkeypatch): plan=None, ) sim.render_context = sim._render_context - sim.get_rendering_dt = lambda: _RENDERING_DT + sim.physics_step_count = 0 + sim.get_physics_dt = lambda: _PHYSICS_DT + sim.get_physics_step_count = lambda: sim.physics_step_count sim.get_clone_plan = lambda: sim.plan sim.get_scene_data_provider = lambda: types.SimpleNamespace( backend=types.SimpleNamespace(transform_paths=[]), get_geometry_points=lambda: {} @@ -409,6 +413,7 @@ def advance_write_floor(*, ordinal): render = renderer.render_batch if batch else renderer.render request = cameras if batch else cameras[0] + SimulationContext.instance().physics_step_count = 1 if missing_output is None: render(request) assert processed == [ @@ -421,8 +426,8 @@ def advance_write_floor(*, ordinal): assert not processed assert len(submissions) == 1 - # Temporal effects advance by the simulated rendering interval, not a fixed frame rate. - assert submissions[0]["delta_time"] == _RENDERING_DT + # Temporal effects advance by the simulated time since the engine's previous step. + assert submissions[0]["delta_time"] == _PHYSICS_DT # Unrequested products are submitted too, and only the requested cameras are read back. assert submissions[0]["render_products"] == { *[path for camera in cameras for path in camera.render_product_paths], @@ -437,36 +442,56 @@ def advance_write_floor(*, ordinal): assert not published_ordinals -def test_lidar_and_camera_captures_use_separate_steps(monkeypatch): - """A lidar capture submits only the requested product at its own sampling interval.""" +def test_cameras_and_lidars_share_one_timed_step(monkeypatch): + """Each physics step gets one timed step with every product; the other reads in that step reuse its scans.""" from isaaclab_ov.renderers import OVRTXLidarCfg from isaaclab.sensors import LidarData + sim = SimulationContext.instance() renderer = _make_mocked_scene_renderer(monkeypatch, use_ovstage=False, clone_env_paths=[]) renderer._needs_transform_initialization = False camera = _make_ovrtx_camera_render_data() renderer._camera_render_data.append(camera) renderer.backend.render_products.update(camera.render_product_paths) - cfg = OVRTXLidarCfg( - prim_path="/Lidar", update_period=0.1, azimuth_deg=[0.0], elevation_deg=[0.0], fire_time_ns=[0], channel_id=[0] - ) - lidar = renderer.create_lidar_render_data(cfg, [cfg.prim_path], 1) - other = replace(cfg, prim_path="/OtherLidar", update_period=0.2) - renderer.create_lidar_render_data(other, [other.prim_path], 1) + cfg = OVRTXLidarCfg(prim_path="/Lidar", azimuth_deg=[0.0], elevation_deg=[0.0], fire_time_ns=[0], channel_id=[0]) + lidars = [renderer.create_lidar_render_data(replace(cfg, prim_path=p), [p], 1) for p in ("/Lidar", "/OtherLidar")] + prepared = [] + for lidar in lidars: + lidar.prepare = lambda lidar=lidar: lambda: prepared.append(lidar) native = renderer.backend.renderer native.step.return_value = {_single_render_product(camera).path: types.SimpleNamespace(frames=[object()])} monkeypatch.setattr(renderer, "_process_render_frames", MagicMock()) - publish = MagicMock() - monkeypatch.setattr(renderer, "_publish_lidar_output", publish) - renderer.render(camera) - assert native.step.call_args.kwargs["render_products"] == set(camera.render_product_paths) + # Each kept scan records the physics step that produced it. + def keep(data, products, scan): + scan.intensity.torch.fill_(sim.physics_step_count) + + monkeypatch.setattr(renderer, "_publish_lidar_output", keep) + products = {*camera.render_product_paths, *(lidar.render_product_path for lidar in lidars)} + outputs = [LidarData(1, 1, "cpu") for _ in lidars] - data = LidarData(1, 1, "cpu") - renderer.render_lidar(lidar, data) - native.step.assert_called_with(render_products={lidar.render_product_path}, delta_time=0.1) - publish.assert_called_once_with(lidar, native.step.return_value, data) + # A camera read takes the timed step for every product, after writing every lidar pose. + sim.physics_step_count = 2 + renderer.render(camera) + native.step.assert_called_once_with(render_products=products, delta_time=2 * _PHYSICS_DT) + assert prepared == lidars + for lidar, output in zip(lidars, outputs): + renderer.render_lidar(lidar, output) + assert output.intensity.torch.item() == 2 + assert native.step.call_count == 1 + + # A lidar read takes the next timed step; the camera read after it in the same physics step steps by zero. + sim.physics_step_count = 3 + renderer.render_lidar(lidars[1], outputs[1]) + native.step.assert_called_with(render_products=products, delta_time=_PHYSICS_DT) + assert outputs[1].intensity.torch.item() == 3 + renderer.render(camera) + native.step.assert_called_with(render_products=products, delta_time=0.0) + renderer.render_lidar(lidars[0], outputs[0]) + assert outputs[0].intensity.torch.item() == 3 + assert native.step.call_count == 3 + assert prepared == lidars * 2 def test_lidar_output_readback(monkeypatch): @@ -488,7 +513,7 @@ def copy(point_cloud, _lidar_data, _device): renderer = _make_mocked_scene_renderer(monkeypatch, use_ovstage=False, clone_env_paths=[]) monkeypatch.setattr(renderer, "_copy_mapped_lidar_point_cloud", copy) - lidar = ovrtx_renderer_module.OVRTXLidarRenderData("Lidar", 0.1, ["/Lidar"]) + lidar = ovrtx_renderer_module.OVRTXLidarRenderData("Lidar", ["/Lidar"], LidarData(1, 1, "cpu")) copied = [] # The newest complete lidar scan is returned. @@ -2044,8 +2069,10 @@ def test_async_cameras_publish_independently_with_capture_metadata_and_reset(mon ordinal = 0 def submit(render_products, delta_time): - assert delta_time == _RENDERING_DT + # The first step of a capture advances by one physics step; the other cameras of the capture step by zero. + assert delta_time == (_PHYSICS_DT if not operations or operations[-1].ordinal != ordinal else 0.0) operation = MagicMock() + operation.ordinal = ordinal frames = [types.SimpleNamespace(end_time=float(ordinal), value=ordinal)] if batch: # SDK capture times identify the real image independently of the returned list order. @@ -2067,6 +2094,7 @@ def consume(camera, frame, buffers): def capture(value, indices): nonlocal ordinal ordinal = value + SimulationContext.instance().physics_step_count += 1 frame.warp.fill_(value) for index in indices: data = camera_data[index] diff --git a/source/isaaclab_ov/test/test_ovrtx_visual_material_sync.py b/source/isaaclab_ov/test/test_ovrtx_visual_material_sync.py index a33837f3a4ca..8496e8bf1a0d 100644 --- a/source/isaaclab_ov/test/test_ovrtx_visual_material_sync.py +++ b/source/isaaclab_ov/test/test_ovrtx_visual_material_sync.py @@ -122,7 +122,7 @@ def destroy_path_list(self, path_list): def _renderer(*, use_ovstage: bool = False): events: list[str] = [] renderer = OVRTXRenderer.__new__(OVRTXRenderer) - renderer.backend = SimpleNamespace(render_products=set(), unrendered={}) + renderer.backend = SimpleNamespace(render_products=set(), unrendered={}, step_count=0, lidars={}) renderer.scene = renderer.backend renderer._initialized_scene = True renderer._needs_transform_initialization = False @@ -130,7 +130,7 @@ def _renderer(*, use_ovstage: bool = False): renderer.backend.renderer = _NativeRecorder(events) renderer._visual_material_writer_ref = None renderer.cfg = OVRTXRendererCfg() - renderer._sim = SimpleNamespace(get_rendering_dt=lambda: 1.0 / 60.0) + renderer._sim = SimpleNamespace(get_physics_dt=lambda: 1.0 / 60.0, get_physics_step_count=lambda: 1) renderer._camera_render_data = [] if use_ovstage: from isaaclab_ov.stage import OvstageBackend From ad38653dfad9131ad040c473426e46986d5ab4d5 Mon Sep 17 00:00:00 2001 From: Alexander Temirov Date: Tue, 1 Dec 2026 17:01:02 -0800 Subject: [PATCH 10/16] Size the shared-step test's lidar outputs to the scan --- source/isaaclab_ov/test/test_ovrtx_renderer_contract.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py index 2cac02a013fc..10af40dceb26 100644 --- a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py @@ -469,7 +469,7 @@ def keep(data, products, scan): monkeypatch.setattr(renderer, "_publish_lidar_output", keep) products = {*camera.render_product_paths, *(lidar.render_product_path for lidar in lidars)} - outputs = [LidarData(1, 1, "cpu") for _ in lidars] + outputs = [LidarData(1, cfg.num_rays(), "cpu") for _ in lidars] # A camera read takes the timed step for every product, after writing every lidar pose. sim.physics_step_count = 2 @@ -478,18 +478,18 @@ def keep(data, products, scan): assert prepared == lidars for lidar, output in zip(lidars, outputs): renderer.render_lidar(lidar, output) - assert output.intensity.torch.item() == 2 + assert (output.intensity.torch == 2).all() assert native.step.call_count == 1 # A lidar read takes the next timed step; the camera read after it in the same physics step steps by zero. sim.physics_step_count = 3 renderer.render_lidar(lidars[1], outputs[1]) native.step.assert_called_with(render_products=products, delta_time=_PHYSICS_DT) - assert outputs[1].intensity.torch.item() == 3 + assert (outputs[1].intensity.torch == 3).all() renderer.render(camera) native.step.assert_called_with(render_products=products, delta_time=0.0) renderer.render_lidar(lidars[0], outputs[0]) - assert outputs[0].intensity.torch.item() == 3 + assert (outputs[0].intensity.torch == 3).all() assert native.step.call_count == 3 assert prepared == lidars * 2 From 9bb40a385cf3d76940655c9392a8959197aaa958 Mon Sep 17 00:00:00 2001 From: Alexander Temirov Date: Tue, 1 Dec 2026 17:40:22 -0800 Subject: [PATCH 11/16] Hold the lidar pose callback without a weak reference --- .../isaaclab_ov/renderers/ovrtx_lidar_sensor.py | 3 +-- .../isaaclab_ov/renderers/ovrtx_renderer.py | 10 +++++----- .../isaaclab_ov/test/test_ovrtx_renderer_contract.py | 5 ++++- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_sensor.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_sensor.py index bf1d3771d44e..152d325a303b 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_sensor.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_sensor.py @@ -15,7 +15,6 @@ from __future__ import annotations import sys -import weakref from typing import TYPE_CHECKING import torch @@ -275,7 +274,7 @@ def _initialize_impl(self): self._local_pos = torch.tensor(positions, dtype=torch.float32, device=self._device) self._local_quat = torch.tensor(rotations, dtype=torch.float32, device=self._device) # Any sensor on the engine can step it, so the engine writes this pose before every timed step. - self._render_data.prepare = weakref.WeakMethod(self._push_renderer_pose) + self._render_data.prepare = self._push_renderer_pose self._push_renderer_pose() def _invalidate_initialize_callback(self, event): diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index 699d199e81b4..406f20ef631d 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -563,11 +563,12 @@ def __init__(self, scope: str, lidar_paths: list[str], scan: LidarData): self.pose_writes = _AsyncWriteBuffers[wp.array]() self.scan = scan """Latest scan. Any sensor's read can step the engine, so the scan waits here until this lidar is read.""" - self.prepare: weakref.WeakMethod | None = None - """Writes the lidar's current pose before a timed step. Weak, so the engine does not keep the sensor alive.""" + self.prepare: Callable[[], None] | None = None + """Writes the lidar's current pose before a timed step. Cleared on cleanup, which releases the sensor.""" def cleanup(self) -> None: """Release the pose writes before releasing the binding.""" + self.prepare = None with self.resources: self.pose_writes.close() self.xform_binding = None @@ -2076,9 +2077,8 @@ def _render_batch_once(self, render_data: Sequence[OVRTXCameraRenderData]) -> No if self._sim.get_physics_step_count() != self.backend.step_count: lidars = tuple(self.backend.lidars.items()) for data, _ in lidars: - prepare = data.prepare() if data.prepare is not None else None - if prepare is not None: - prepare() + if data.prepare is not None: + data.prepare() material_writer = self._visual_material_writer_ref() if self._visual_material_writer_ref is not None else None try: if material_writer is not None: diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py index 10af40dceb26..0d3cac938ee9 100644 --- a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py @@ -458,7 +458,7 @@ def test_cameras_and_lidars_share_one_timed_step(monkeypatch): lidars = [renderer.create_lidar_render_data(replace(cfg, prim_path=p), [p], 1) for p in ("/Lidar", "/OtherLidar")] prepared = [] for lidar in lidars: - lidar.prepare = lambda lidar=lidar: lambda: prepared.append(lidar) + lidar.prepare = lambda lidar=lidar: prepared.append(lidar) native = renderer.backend.renderer native.step.return_value = {_single_render_product(camera).path: types.SimpleNamespace(frames=[object()])} monkeypatch.setattr(renderer, "_process_render_frames", MagicMock()) @@ -492,6 +492,9 @@ def keep(data, products, scan): assert (outputs[0].intensity.torch == 3).all() assert native.step.call_count == 3 assert prepared == lidars * 2 + # Cleanup drops the pose callback, so the engine no longer keeps the sensor alive. + renderer.cleanup_lidar(lidars[0]) + assert lidars[0].prepare is None and lidars[0] not in renderer.backend.lidars def test_lidar_output_readback(monkeypatch): From 67e319ce1914b60679d06f6de047cbd2ebfbb728 Mon Sep 17 00:00:00 2001 From: Alexander Temirov Date: Tue, 1 Dec 2026 17:44:10 -0800 Subject: [PATCH 12/16] Keep the local lidar list in render_lidar --- source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index 406f20ef631d..559f2a24ea23 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -1004,9 +1004,11 @@ def render_lidar(self, render_data: OVRTXLidarRenderData, lidar_data: LidarData) """ if not self._initialized_scene: raise RuntimeError("Scene not initialized. Call initialize() first.") + + lidars = self._lidars if self.backend is None or self.backend.renderer is None: raise RuntimeError(f"Cannot capture {render_data.render_product_path!r}: OvRTX renderer is unavailable.") - if render_data not in self._lidars: + if render_data not in lidars: raise RuntimeError(f"OvRTX lidar product {render_data.render_product_path!r} is not registered.") if self._sim.get_physics_step_count() != self.backend.step_count: From af39cc7d951afb135d437d636ce42854d5c128ec Mon Sep 17 00:00:00 2001 From: Alexander Temirov Date: Wed, 2 Dec 2026 13:49:06 -0800 Subject: [PATCH 13/16] Use instant lidars in the shared-step clock test --- source/isaaclab_ov/test/test_ovrtx_lidar.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source/isaaclab_ov/test/test_ovrtx_lidar.py b/source/isaaclab_ov/test/test_ovrtx_lidar.py index 9fbfc0551604..3d2a17607713 100644 --- a/source/isaaclab_ov/test/test_ovrtx_lidar.py +++ b/source/isaaclab_ov/test/test_ovrtx_lidar.py @@ -274,6 +274,8 @@ class SceneCfg(InteractiveSceneCfg): elevation_deg=[-5.0, 10.0], fire_time_ns=[0, 0], channel_id=[0, 1], + # Each timed step returns a complete scan, so every physics step can check the returns. + instant_lidar=True, offset=OVRTXLidarCfg.OffsetCfg(pos=(0.2, 0.1, 3.0), rot=(0.0, 0.0, 0.5, math.sqrt(0.75))), ) other_lidar = replace(lidar, prim_path="{ENV_REGEX_NS}/OtherLidar") From d8faf0adfa2cb63ed30a8e3b2dc1e0202f81320f Mon Sep 17 00:00:00 2001 From: Alexander Temirov Date: Wed, 2 Dec 2026 14:05:38 -0800 Subject: [PATCH 14/16] Claim the OVRTX step time once the step is submitted --- .../isaaclab_ov/renderers/ovrtx_renderer.py | 21 +++--- source/isaaclab_ov/test/test_ovrtx_lidar.py | 11 ++-- .../test/test_ovrtx_renderer_contract.py | 64 +++++++++++++++---- ...t_ovrtx_renderer_rigid_object_rendering.py | 11 ++-- .../test/test_ovrtx_visual_material_sync.py | 4 ++ 5 files changed, 79 insertions(+), 32 deletions(-) diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index 559f2a24ea23..4f4356a7d6d1 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -2095,7 +2095,7 @@ def _render_batch_once(self, render_data: Sequence[OVRTXCameraRenderData]) -> No ordinal = self.scene.commit() elif self.cfg.async_rendering: unread = {data.ready[0] for data in render_data if data.ready is not None} - operation = self.backend.renderer.step_async(render_products=products, delta_time=self._step_dt()) + operation = self._submit_step(products) if self.backend.unrendered: # While a sensor has no rendered frame, the step waits for its frame, so a failed frame raises # where the search can act. @@ -2111,7 +2111,7 @@ def _render_batch_once(self, render_data: Sequence[OVRTXCameraRenderData]) -> No for previous in unread: previous.wait().fetch() else: - result = self.backend.renderer.step(render_products=products, delta_time=self._step_dt()) + result = self._submit_step(products).wait().fetch() self._keep_lidar_scans(result, lidars) self._process_render_products(render_data, result) finally: @@ -2129,21 +2129,24 @@ def _render_batch_once(self, render_data: Sequence[OVRTXCameraRenderData]) -> No if self._use_ovstage: # Stage writes and material reads finish before rendering. Consume only after advancing # the ordinal so a failed readback cannot leave later writes at the sealed floor. - result = self.backend.renderer.step(render_products=products, delta_time=self._step_dt(), ordinal=ordinal) + result = self._submit_step(products, ordinal=ordinal).wait().fetch() self._keep_lidar_scans(result, lidars) self._process_render_products(render_data, result) - def _step_dt(self) -> float: - """Claim the simulated time since this engine's previous timed step [s]. + def _submit_step(self, products: set[str], *, ordinal: int | None = None) -> Operation: + """Submit one step by the simulated time since this engine's previous timed step. OVRTX uses the step delta for temporal effects such as motion blur and motion vectors and for lidar scans, so it must match the simulated time. The count belongs to the engine, so a second step in the same physics step, - for example for another camera, steps by zero. Call when submitting the step: a failed preparation leaves the - time for the retry. + for example for another camera, steps by zero. The time is claimed once OVRTX accepts the step: a rejected + submission leaves it for the retry, and a step that fails while rendering has already advanced the clock. """ count = self._sim.get_physics_step_count() - previous, self.backend.step_count = self.backend.step_count, count - return (count - previous) * self._sim.get_physics_dt() + kwargs = {} if ordinal is None else {"ordinal": ordinal} + delta_time = (count - self.backend.step_count) * self._sim.get_physics_dt() + operation = self.backend.renderer.step_async(render_products=products, delta_time=delta_time, **kwargs) + self.backend.step_count = count + return operation @staticmethod def _keep_lidar_scans( diff --git a/source/isaaclab_ov/test/test_ovrtx_lidar.py b/source/isaaclab_ov/test/test_ovrtx_lidar.py index 3d2a17607713..1664f8c6c221 100644 --- a/source/isaaclab_ov/test/test_ovrtx_lidar.py +++ b/source/isaaclab_ov/test/test_ovrtx_lidar.py @@ -248,13 +248,14 @@ def test_camera_and_lidars_on_one_engine_advance_its_clock_by_physics_time(monke from isaaclab.utils import configclass, instantiate, replace steps = [] - native_step = ovrtx.Renderer.step + native_step_async = ovrtx.Renderer.step_async - def record(self, **kwargs): - steps.append((kwargs["delta_time"], frozenset(kwargs["render_products"]))) - return native_step(self, **kwargs) + # Every path submits through step_async; step submits through it too. + def record(self, render_products, delta_time, **kwargs): + steps.append((delta_time, frozenset(render_products))) + return native_step_async(self, render_products, delta_time, **kwargs) - monkeypatch.setattr(ovrtx.Renderer, "step", record) + monkeypatch.setattr(ovrtx.Renderer, "step_async", record) @configclass class SceneCfg(InteractiveSceneCfg): diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py index 0d3cac938ee9..c984614a12a7 100644 --- a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py @@ -106,6 +106,13 @@ def _make_ovrtx_camera_render_data(render_scope_name: str = "RenderCamera_0") -> return OVRTXCameraRenderData(spec, render_scope_name, [f"/World/envs/env_{i}/Camera" for i in range(2)], "auto") +def _finished(result): + """Return a fake native step operation that completed with ``result``.""" + operation = MagicMock() + operation.wait.return_value.fetch.return_value = result + return operation + + def _single_render_product(render_data: OVRTXCameraRenderData): """Return the render product of a sensor that must have exactly one.""" assert len(render_data.products) == 1, f"Expected one render product, got {render_data.render_product_paths}" @@ -407,7 +414,7 @@ def advance_write_floor(*, ordinal): published_ordinals.append(ordinal) return types.SimpleNamespace(wait=lambda: None) - renderer.backend.renderer = types.SimpleNamespace(step=step) + renderer.backend.renderer = types.SimpleNamespace(step_async=lambda **kwargs: _finished(step(**kwargs))) renderer.scene.stage = types.SimpleNamespace(advance_write_floor=advance_write_floor) monkeypatch.setattr(renderer, "_process_render_frames", lambda *args: processed.append(args)) @@ -460,7 +467,9 @@ def test_cameras_and_lidars_share_one_timed_step(monkeypatch): for lidar in lidars: lidar.prepare = lambda lidar=lidar: prepared.append(lidar) native = renderer.backend.renderer - native.step.return_value = {_single_render_product(camera).path: types.SimpleNamespace(frames=[object()])} + native.step_async.return_value = _finished( + {_single_render_product(camera).path: types.SimpleNamespace(frames=[object()])} + ) monkeypatch.setattr(renderer, "_process_render_frames", MagicMock()) # Each kept scan records the physics step that produced it. @@ -474,29 +483,57 @@ def keep(data, products, scan): # A camera read takes the timed step for every product, after writing every lidar pose. sim.physics_step_count = 2 renderer.render(camera) - native.step.assert_called_once_with(render_products=products, delta_time=2 * _PHYSICS_DT) + native.step_async.assert_called_once_with(render_products=products, delta_time=2 * _PHYSICS_DT) assert prepared == lidars for lidar, output in zip(lidars, outputs): renderer.render_lidar(lidar, output) assert (output.intensity.torch == 2).all() - assert native.step.call_count == 1 + assert native.step_async.call_count == 1 # A lidar read takes the next timed step; the camera read after it in the same physics step steps by zero. sim.physics_step_count = 3 renderer.render_lidar(lidars[1], outputs[1]) - native.step.assert_called_with(render_products=products, delta_time=_PHYSICS_DT) + native.step_async.assert_called_with(render_products=products, delta_time=_PHYSICS_DT) assert (outputs[1].intensity.torch == 3).all() renderer.render(camera) - native.step.assert_called_with(render_products=products, delta_time=0.0) + native.step_async.assert_called_with(render_products=products, delta_time=0.0) renderer.render_lidar(lidars[0], outputs[0]) assert (outputs[0].intensity.torch == 3).all() - assert native.step.call_count == 3 + assert native.step_async.call_count == 3 assert prepared == lidars * 2 # Cleanup drops the pose callback, so the engine no longer keeps the sensor alive. renderer.cleanup_lidar(lidars[0]) assert lidars[0].prepare is None and lidars[0] not in renderer.backend.lidars +def test_step_claims_elapsed_time_once_submitted(monkeypatch): + """A rejected submission leaves the elapsed time for the retry; a step that fails after submission spends it.""" + sim = SimulationContext.instance() + renderer = _make_mocked_scene_renderer(monkeypatch, use_ovstage=False, clone_env_paths=[]) + renderer._needs_transform_initialization = False + camera = _make_ovrtx_camera_render_data() + renderer._camera_render_data.append(camera) + renderer.backend.render_products.update(camera.render_product_paths) + monkeypatch.setattr(renderer, "_process_render_frames", MagicMock()) + rendered = _finished({_single_render_product(camera).path: types.SimpleNamespace(frames=[object()])}) + failed = MagicMock() + failed.wait.side_effect = RuntimeError("failed while rendering") + native = renderer.backend.renderer + native.step_async.side_effect = [RuntimeError("rejected"), rendered, failed, rendered] + + sim.physics_step_count = 3 + with pytest.raises(RuntimeError, match="rejected"): + renderer._render_batch_once([camera]) + renderer._render_batch_once([camera]) + sim.physics_step_count = 4 + with pytest.raises(RuntimeError, match="failed while rendering"): + renderer._render_batch_once([camera]) + renderer._render_batch_once([camera]) + + deltas = [call.kwargs["delta_time"] for call in native.step_async.call_args_list] + assert deltas == [3 * _PHYSICS_DT, 3 * _PHYSICS_DT, _PHYSICS_DT, 0.0] + + def test_lidar_output_readback(monkeypatch): """Test the lidar output readback - OVRTXRenderer._publish_lidar_output.""" from isaaclab.sensors import LidarData @@ -1844,8 +1881,8 @@ def step(renderer, render_products, *args, **kwargs): return step - # Both the legacy and the ovstage path render each frame with step. - monkeypatch.setattr(ovrtx.Renderer, "step", record_products(ovrtx.Renderer.step)) + # Every path submits each frame with step_async; step submits through it too. + monkeypatch.setattr(ovrtx.Renderer, "step_async", record_products(ovrtx.Renderer.step_async)) positions = torch.tensor(_SPLIT_CAMERA_POSITIONS, device="cuda:0") # The center pixel of each camera sees the top of a cube on the ground. @@ -2015,16 +2052,17 @@ def test_ovrtx_split_search_recovers_from_a_real_failed_frame(monkeypatch, caplo UsdGeom.Cube.Define(stage, env_template.format(0) + "/cube").CreateSizeAttr(_SPLIT_CUBE_SIZE) errors = [] - native_step = ovrtx.Renderer.step + native_wait = ovrtx.Operation.wait - def recording_step(renderer, render_products, *args, **kwargs): + # A failed frame surfaces when its step operation is waited on. + def recording_wait(operation, *args, **kwargs): try: - return native_step(renderer, render_products, *args, **kwargs) + return native_wait(operation, *args, **kwargs) except RuntimeError as error: errors.append(str(error)) raise - monkeypatch.setattr(ovrtx.Renderer, "step", recording_step) + monkeypatch.setattr(ovrtx.Operation, "wait", recording_wait) try: renderer.prepare_stage(stage, num_envs) camera_cfg = _make_camera_cfg(["rgb"]) diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_rigid_object_rendering.py b/source/isaaclab_ov/test/test_ovrtx_renderer_rigid_object_rendering.py index a1afb5a53d51..13a64e852d8f 100644 --- a/source/isaaclab_ov/test/test_ovrtx_renderer_rigid_object_rendering.py +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_rigid_object_rendering.py @@ -169,13 +169,14 @@ class SceneCfg(InteractiveSceneCfg): ) submissions = [] - native_step = ovrtx.Renderer.step + native_step_async = ovrtx.Renderer.step_async - def record_products(renderer, **kwargs): - submissions.append(set(kwargs["render_products"])) - return native_step(renderer, **kwargs) + # Every path submits through step_async; step submits through it too. + def record_products(renderer, render_products, *args, **kwargs): + submissions.append(set(render_products)) + return native_step_async(renderer, render_products, *args, **kwargs) - monkeypatch.setattr(ovrtx.Renderer, "step", record_products) + monkeypatch.setattr(ovrtx.Renderer, "step_async", record_products) cfg = SimulationCfg(device="cuda:0", dt=1 / 60, gravity=(0.0, 0.0, 0.0), physics=OvPhysxCfg()) with build_simulation_context(sim_cfg=cfg) as sim: sim._app_control_on_stop_handle = None diff --git a/source/isaaclab_ov/test/test_ovrtx_visual_material_sync.py b/source/isaaclab_ov/test/test_ovrtx_visual_material_sync.py index 8496e8bf1a0d..ac5e198584a8 100644 --- a/source/isaaclab_ov/test/test_ovrtx_visual_material_sync.py +++ b/source/isaaclab_ov/test/test_ovrtx_visual_material_sync.py @@ -55,6 +55,10 @@ def step(self, **kwargs): self.events.append("step") return {path: SimpleNamespace(frames=[object()]) for path in kwargs["render_products"]} + def step_async(self, **kwargs): + result = self.step(**kwargs) + return SimpleNamespace(wait=lambda: SimpleNamespace(fetch=lambda: result)) + class _NativeBinding: def __init__(self, recorder, prim_paths, attribute_name, kwargs): From b480b25cf3f7f4f585e2858352eec0555b392ade Mon Sep 17 00:00:00 2001 From: Alexander Temirov Date: Wed, 2 Dec 2026 14:17:52 -0800 Subject: [PATCH 15/16] Publish the simulated time from the render context to renderers --- .../render-context-simulated-time.added.rst | 4 +++ .../render-context-simulated-time.minor | 0 .../isaaclab/renderers/base_renderer.py | 8 +++++ .../isaaclab/renderers/render_context.py | 17 +++++++--- .../isaaclab/sim/simulation_context.py | 2 +- .../test_simulation_render_context.py | 12 +++++++ .../ovrtx-shared-engine-step.fixed.rst | 7 ++-- .../isaaclab_ov/renderers/ovrtx_renderer.py | 32 +++++++++++-------- .../test/test_ovrtx_renderer_contract.py | 23 ++++++------- .../test/test_ovrtx_visual_material_sync.py | 4 +-- 10 files changed, 72 insertions(+), 37 deletions(-) create mode 100644 source/isaaclab/changelog.d/render-context-simulated-time.added.rst create mode 100644 source/isaaclab/changelog.d/render-context-simulated-time.minor diff --git a/source/isaaclab/changelog.d/render-context-simulated-time.added.rst b/source/isaaclab/changelog.d/render-context-simulated-time.added.rst new file mode 100644 index 000000000000..4b93c813abe5 --- /dev/null +++ b/source/isaaclab/changelog.d/render-context-simulated-time.added.rst @@ -0,0 +1,4 @@ +* Added :attr:`~isaaclab.renderers.RenderContext.time` and :meth:`~isaaclab.renderers.BaseRenderer.update_time`. + :meth:`~isaaclab.renderers.RenderContext.update_scene_state` publishes the simulated time of the physics step to + every renderer, so renderers with temporal effects step their scene clocks without querying physics. Renderers + without a scene clock ignore it. diff --git a/source/isaaclab/changelog.d/render-context-simulated-time.minor b/source/isaaclab/changelog.d/render-context-simulated-time.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/renderers/base_renderer.py b/source/isaaclab/isaaclab/renderers/base_renderer.py index a9d2891cf184..5c0ea25ed2ed 100644 --- a/source/isaaclab/isaaclab/renderers/base_renderer.py +++ b/source/isaaclab/isaaclab/renderers/base_renderer.py @@ -143,6 +143,14 @@ def update_geometries(self) -> None: """ pass + def update_time(self, time: float) -> None: + """Set the simulated time [s] that the renderer's scene clock advances to on its next render. + + Called by :class:`~isaaclab.renderers.RenderContext` with the scene state. A renderer with temporal + effects, such as motion blur or scanned lidars, steps its clock by the time since its previous step. + Renderers without a scene clock ignore it. + """ + @abstractmethod def update_camera( self, diff --git a/source/isaaclab/isaaclab/renderers/render_context.py b/source/isaaclab/isaaclab/renderers/render_context.py index a3ff217a9edc..9d954c55418e 100644 --- a/source/isaaclab/isaaclab/renderers/render_context.py +++ b/source/isaaclab/isaaclab/renderers/render_context.py @@ -9,7 +9,7 @@ import logging import warnings -from collections.abc import Sequence +from collections.abc import Callable, Sequence from typing import Any import torch @@ -66,6 +66,8 @@ class RenderContext: __slots__ = ( "clone_contexts", + "time", + "_physics_dt", "_backend_registry", "_physics_initialized", "_prepared_renderer_ids", @@ -80,9 +82,12 @@ class RenderContext: "_consumers_finalized", ) - def __init__(self, backend_registry: list[tuple[Any, Any]]) -> None: + def __init__(self, backend_registry: list[tuple[Any, Any]], physics_dt: Callable[[], float] | None = None) -> None: self.clone_contexts: set[type[cloner.ReplicateContext] | str] = set() """Scene representations declared by camera renderers and visualizers before cloning.""" + self.time = 0.0 + """Simulated time [s] of the latest published scene state, which renderers advance their clocks to.""" + self._physics_dt = physics_dt self._backend_registry = backend_registry self._physics_initialized: bool = False # Set to True after the first PHYSICS_READY callback fires. self._prepared_renderer_ids: set[int] = set() @@ -324,13 +329,17 @@ def ensure_prepare_stage(self, stage: Any, num_envs: int) -> None: self._prepared_num_envs = num_envs def update_scene_state(self, physics_step_count: int) -> None: - """Publish physics state and refresh renderers through SDP's producer versions. + """Publish physics state and simulated time, and refresh renderers through SDP's producer versions. - Producer versions also cover geometry writes between physics steps. + Producer versions also cover geometry writes between physics steps. The simulated time is the physics + steps times the physics time step; renderers step their scene clocks to it, so they never query physics. """ + if self._physics_dt is not None: + self.time = physics_step_count * self._physics_dt() for _cfg, renderer in self._renderer_entries: renderer.update_transforms() renderer.update_geometries() + renderer.update_time(self.time) def render_into_camera( self, diff --git a/source/isaaclab/isaaclab/sim/simulation_context.py b/source/isaaclab/isaaclab/sim/simulation_context.py index a23aafb42fd7..d444b25d1517 100644 --- a/source/isaaclab/isaaclab/sim/simulation_context.py +++ b/source/isaaclab/isaaclab/sim/simulation_context.py @@ -239,7 +239,7 @@ def __init__(self, cfg: SimulationCfg | None = None): self._render_generation: int = 0 # Shared renderers for all Camera sensors (compatible renderer_cfg only). - self._render_context = RenderContext(self._backend_registry) + self._render_context = RenderContext(self._backend_registry, self.get_physics_dt) # Run renderer post-physics setup. self.backend_manager.register_callback( diff --git a/source/isaaclab/test/renderers/test_simulation_render_context.py b/source/isaaclab/test/renderers/test_simulation_render_context.py index ab10e322acdc..4a111f999e81 100644 --- a/source/isaaclab/test/renderers/test_simulation_render_context.py +++ b/source/isaaclab/test/renderers/test_simulation_render_context.py @@ -197,6 +197,18 @@ def test_scene_state_does_not_skip_writes_within_a_physics_step(sim): assert renderer.update_geometries.call_count == 4 +def test_scene_state_publishes_simulated_time_to_renderers(): + """Renderers receive the physics steps as simulated time, so they never query physics themselves.""" + registry = [] + context = RenderContext(registry, lambda: 0.025) + renderer = Mock(spec=BaseRenderer) + registry.append((RendererCfg(class_type=_renderer), renderer)) + for step in (4, 4, 6): + context.update_scene_state(step) + assert context.time == pytest.approx(0.15) + assert [args[0] for args, _ in renderer.update_time.call_args_list] == pytest.approx([0.1, 0.1, 0.15]) + + @pytest.mark.parametrize("profile", [False, True]) def test_render_into_camera_call_order_and_profile_output(sim, capsys, profile): """Profiling preserves call order and collects timings without printing.""" diff --git a/source/isaaclab_ov/changelog.d/ovrtx-shared-engine-step.fixed.rst b/source/isaaclab_ov/changelog.d/ovrtx-shared-engine-step.fixed.rst index bfe8b36c6cd6..6b2cebb6d65c 100644 --- a/source/isaaclab_ov/changelog.d/ovrtx-shared-engine-step.fixed.rst +++ b/source/isaaclab_ov/changelog.d/ovrtx-shared-engine-step.fixed.rst @@ -1,4 +1,5 @@ * Fixed OVRTX cameras and lidars on one engine each stepping its clock on their own reads, which counted the same - physics time more than once and left lidars out of each other's steps. A read now steps the engine only when - physics advanced since its last step, by that simulated time instead of the rendering time step, with every - camera and lidar product. Each lidar keeps its scan from that step until its sensor reads it. + physics time more than once and left lidars out of each other's steps. A read now steps the engine only when the + render context published a later simulated time than its last step, by that time instead of the rendering time + step, with every camera and lidar product. The renderer no longer queries physics. Each lidar keeps its scan from + that step until its sensor reads it. diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index 4f4356a7d6d1..c9828476397e 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -330,9 +330,10 @@ def __init__(self, cfg: OVRTXBackendCfg): self.cfg = cfg self.attached = False self.render_products: set[str] = set() - # Physics step count at this engine's previous timed step. The engine has one clock, so every renderer on it - # shares the count. It starts here, so the clock stays at the simulated time since the engine was created. - self.step_count = SimulationContext.instance().get_physics_step_count() + # The engine has one clock, shared by every renderer on it. ``time`` is the simulated time [s] the render + # context last published, and ``step_time`` the time its submitted steps reached. Both start at the context's + # time, so the clock stays at the simulated time since the engine was created. + self.time = self.step_time = SimulationContext.instance().render_context.time # Lidars of every renderer on this engine, and their renderers. Every timed step scans all of them. self.lidars: dict[OVRTXLidarRenderData, OVRTXRenderer] = {} # Camera sensors of every renderer on this engine without a rendered frame, and their renderers. @@ -997,7 +998,7 @@ def _map_lidar_point_cloud(self, point_cloud: RenderVarOutput, device: Device) - mapping.unmap(stream=stream) def render_lidar(self, render_data: OVRTXLidarRenderData, lidar_data: LidarData) -> None: - """Publish the latest scan of one lidar, after stepping the engine if physics advanced since its last step. + """Publish the latest scan of one lidar, after stepping the engine if simulated time advanced since its step. The engine has one clock, so each timed step scans every lidar on it and renders every camera product. A camera or another lidar may have stepped the engine first; this lidar's scan then waits in its render data. @@ -1011,7 +1012,7 @@ def render_lidar(self, render_data: OVRTXLidarRenderData, lidar_data: LidarData) if render_data not in lidars: raise RuntimeError(f"OvRTX lidar product {render_data.render_product_path!r} is not registered.") - if self._sim.get_physics_step_count() != self.backend.step_count: + if self.backend.time != self.backend.step_time: self._render_with_retry(()) wp.copy(lidar_data.points.warp, render_data.scan.points.warp) wp.copy(lidar_data.intensity.warp, render_data.scan.intensity.warp) @@ -2070,13 +2071,13 @@ def _copy_render_product_attributes(self, source: str, targets: Sequence[str]) - def _render_batch_once(self, render_data: Sequence[OVRTXCameraRenderData]) -> None: """Render one step with every registered render product, and read back the images of ``render_data``. - A step after physics advanced is timed: it scans every lidar on the engine and keeps each scan for its sensor. + A step after simulated time advanced is timed: it scans every lidar on the engine and keeps each scan for it. Every lidar product is submitted on every step, because a product left out of a timed step loses that time. """ products = self.backend.render_products.copy() products.update(data.render_product_path for data in self.backend.lidars) lidars = () - if self._sim.get_physics_step_count() != self.backend.step_count: + if self.backend.time != self.backend.step_time: lidars = tuple(self.backend.lidars.items()) for data, _ in lidars: if data.prepare is not None: @@ -2134,20 +2135,25 @@ def _render_batch_once(self, render_data: Sequence[OVRTXCameraRenderData]) -> No self._process_render_products(render_data, result) def _submit_step(self, products: set[str], *, ordinal: int | None = None) -> Operation: - """Submit one step by the simulated time since this engine's previous timed step. + """Submit one step by the simulated time the render context published since this engine's previous step. OVRTX uses the step delta for temporal effects such as motion blur and motion vectors and for lidar scans, so - it must match the simulated time. The count belongs to the engine, so a second step in the same physics step, - for example for another camera, steps by zero. The time is claimed once OVRTX accepts the step: a rejected + it must match the simulated time. The time belongs to the engine, so a second step at the same time, for + example for another camera, steps by zero. The time is claimed once OVRTX accepts the step: a rejected submission leaves it for the retry, and a step that fails while rendering has already advanced the clock. """ - count = self._sim.get_physics_step_count() + time = self.backend.time kwargs = {} if ordinal is None else {"ordinal": ordinal} - delta_time = (count - self.backend.step_count) * self._sim.get_physics_dt() + delta_time = time - self.backend.step_time operation = self.backend.renderer.step_async(render_products=products, delta_time=delta_time, **kwargs) - self.backend.step_count = count + self.backend.step_time = time return operation + def update_time(self, time: float) -> None: + """Set the simulated time [s] the engine's next step advances to. Renderers on one engine share it.""" + if self.backend is not None: + self.backend.time = time + @staticmethod def _keep_lidar_scans( products: RenderProductSetOutputs, lidars: Sequence[tuple[OVRTXLidarRenderData, OVRTXRenderer]] diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py index c984614a12a7..350afc427653 100644 --- a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py @@ -88,7 +88,7 @@ _SPLIT_COLOR_MEAN_TOLERANCES = {"rgb": (8.0, 0.0), "rgba": (8.0, 0.0), "rgb_hdr": (0.0, 0.05)} _PHYSICS_DT = 0.025 -"""Physics time step reported by the fake simulation context [s].""" +"""Simulated time of one physics step in these tests [s].""" def _make_camera_cfg(data_types: list[str]) -> CameraCfg: @@ -133,7 +133,7 @@ def _make_ovrtx_renderer_without_backend() -> OVRTXRenderer: renderer.backend.attached = False renderer.backend.render_products = set() renderer.backend.unrendered = {} - renderer.backend.step_count = 0 + renderer.backend.time = renderer.backend.step_time = 0.0 renderer.backend.lidars = {} cfg = OVRTXBackendCfg(scene_key=renderer.cfg, use_ovstage=False, read_gpu_transforms=True, device="cpu") renderer.scene.stage = renderer.scene.paths = None @@ -195,9 +195,6 @@ def _simulation_registry(monkeypatch): plan=None, ) sim.render_context = sim._render_context - sim.physics_step_count = 0 - sim.get_physics_dt = lambda: _PHYSICS_DT - sim.get_physics_step_count = lambda: sim.physics_step_count sim.get_clone_plan = lambda: sim.plan sim.get_scene_data_provider = lambda: types.SimpleNamespace( backend=types.SimpleNamespace(transform_paths=[]), get_geometry_points=lambda: {} @@ -420,7 +417,7 @@ def advance_write_floor(*, ordinal): render = renderer.render_batch if batch else renderer.render request = cameras if batch else cameras[0] - SimulationContext.instance().physics_step_count = 1 + renderer.update_time(_PHYSICS_DT) if missing_output is None: render(request) assert processed == [ @@ -455,7 +452,6 @@ def test_cameras_and_lidars_share_one_timed_step(monkeypatch): from isaaclab.sensors import LidarData - sim = SimulationContext.instance() renderer = _make_mocked_scene_renderer(monkeypatch, use_ovstage=False, clone_env_paths=[]) renderer._needs_transform_initialization = False camera = _make_ovrtx_camera_render_data() @@ -474,14 +470,14 @@ def test_cameras_and_lidars_share_one_timed_step(monkeypatch): # Each kept scan records the physics step that produced it. def keep(data, products, scan): - scan.intensity.torch.fill_(sim.physics_step_count) + scan.intensity.torch.fill_(round(renderer.backend.time / _PHYSICS_DT)) monkeypatch.setattr(renderer, "_publish_lidar_output", keep) products = {*camera.render_product_paths, *(lidar.render_product_path for lidar in lidars)} outputs = [LidarData(1, cfg.num_rays(), "cpu") for _ in lidars] # A camera read takes the timed step for every product, after writing every lidar pose. - sim.physics_step_count = 2 + renderer.update_time(2 * _PHYSICS_DT) renderer.render(camera) native.step_async.assert_called_once_with(render_products=products, delta_time=2 * _PHYSICS_DT) assert prepared == lidars @@ -491,7 +487,7 @@ def keep(data, products, scan): assert native.step_async.call_count == 1 # A lidar read takes the next timed step; the camera read after it in the same physics step steps by zero. - sim.physics_step_count = 3 + renderer.update_time(3 * _PHYSICS_DT) renderer.render_lidar(lidars[1], outputs[1]) native.step_async.assert_called_with(render_products=products, delta_time=_PHYSICS_DT) assert (outputs[1].intensity.torch == 3).all() @@ -508,7 +504,6 @@ def keep(data, products, scan): def test_step_claims_elapsed_time_once_submitted(monkeypatch): """A rejected submission leaves the elapsed time for the retry; a step that fails after submission spends it.""" - sim = SimulationContext.instance() renderer = _make_mocked_scene_renderer(monkeypatch, use_ovstage=False, clone_env_paths=[]) renderer._needs_transform_initialization = False camera = _make_ovrtx_camera_render_data() @@ -521,11 +516,11 @@ def test_step_claims_elapsed_time_once_submitted(monkeypatch): native = renderer.backend.renderer native.step_async.side_effect = [RuntimeError("rejected"), rendered, failed, rendered] - sim.physics_step_count = 3 + renderer.update_time(3 * _PHYSICS_DT) with pytest.raises(RuntimeError, match="rejected"): renderer._render_batch_once([camera]) renderer._render_batch_once([camera]) - sim.physics_step_count = 4 + renderer.update_time(4 * _PHYSICS_DT) with pytest.raises(RuntimeError, match="failed while rendering"): renderer._render_batch_once([camera]) renderer._render_batch_once([camera]) @@ -2135,7 +2130,7 @@ def consume(camera, frame, buffers): def capture(value, indices): nonlocal ordinal ordinal = value - SimulationContext.instance().physics_step_count += 1 + renderer.update_time(value * _PHYSICS_DT) frame.warp.fill_(value) for index in indices: data = camera_data[index] diff --git a/source/isaaclab_ov/test/test_ovrtx_visual_material_sync.py b/source/isaaclab_ov/test/test_ovrtx_visual_material_sync.py index ac5e198584a8..d56b4f63666b 100644 --- a/source/isaaclab_ov/test/test_ovrtx_visual_material_sync.py +++ b/source/isaaclab_ov/test/test_ovrtx_visual_material_sync.py @@ -126,7 +126,7 @@ def destroy_path_list(self, path_list): def _renderer(*, use_ovstage: bool = False): events: list[str] = [] renderer = OVRTXRenderer.__new__(OVRTXRenderer) - renderer.backend = SimpleNamespace(render_products=set(), unrendered={}, step_count=0, lidars={}) + renderer.backend = SimpleNamespace(render_products=set(), unrendered={}, time=0.0, step_time=0.0, lidars={}) renderer.scene = renderer.backend renderer._initialized_scene = True renderer._needs_transform_initialization = False @@ -134,7 +134,7 @@ def _renderer(*, use_ovstage: bool = False): renderer.backend.renderer = _NativeRecorder(events) renderer._visual_material_writer_ref = None renderer.cfg = OVRTXRendererCfg() - renderer._sim = SimpleNamespace(get_physics_dt=lambda: 1.0 / 60.0, get_physics_step_count=lambda: 1) + renderer._sim = SimpleNamespace() renderer._camera_render_data = [] if use_ovstage: from isaaclab_ov.stage import OvstageBackend From 1ce9de44506be785e788194a6ca0f2875140f2ef Mon Sep 17 00:00:00 2001 From: Alexander Temirov Date: Wed, 2 Dec 2026 14:23:51 -0800 Subject: [PATCH 16/16] Compare stepped simulated time with a tolerance in renderer tests --- .../test_simulation_render_context.py | 2 ++ .../test/test_ovrtx_renderer_contract.py | 18 +++++++++++++----- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/source/isaaclab/test/renderers/test_simulation_render_context.py b/source/isaaclab/test/renderers/test_simulation_render_context.py index 4a111f999e81..dd315da89810 100644 --- a/source/isaaclab/test/renderers/test_simulation_render_context.py +++ b/source/isaaclab/test/renderers/test_simulation_render_context.py @@ -222,10 +222,12 @@ def test_render_into_camera_call_order_and_profile_output(sim, capsys, profile): assert renderer.mock_calls == [ call.update_transforms(), call.update_geometries(), + call.update_time(0.0), call.render_batch([data]), call.read_output(data, camera), call.update_transforms(), call.update_geometries(), + call.update_time(0.0), call.render_batch([data]), call.read_output(data, camera), ] diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py index 350afc427653..3253b126a4a1 100644 --- a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py @@ -113,6 +113,13 @@ def _finished(result): return operation +def _assert_stepped(native, products: set[str], delta_time: float) -> None: + """Check the latest native step. Its delta is a difference of simulated times, so compare it with a tolerance.""" + kwargs = native.step_async.call_args.kwargs + assert kwargs["render_products"] == products + assert kwargs["delta_time"] == pytest.approx(delta_time) + + def _single_render_product(render_data: OVRTXCameraRenderData): """Return the render product of a sensor that must have exactly one.""" assert len(render_data.products) == 1, f"Expected one render product, got {render_data.render_product_paths}" @@ -479,7 +486,8 @@ def keep(data, products, scan): # A camera read takes the timed step for every product, after writing every lidar pose. renderer.update_time(2 * _PHYSICS_DT) renderer.render(camera) - native.step_async.assert_called_once_with(render_products=products, delta_time=2 * _PHYSICS_DT) + _assert_stepped(native, products, 2 * _PHYSICS_DT) + assert native.step_async.call_count == 1 assert prepared == lidars for lidar, output in zip(lidars, outputs): renderer.render_lidar(lidar, output) @@ -489,10 +497,10 @@ def keep(data, products, scan): # A lidar read takes the next timed step; the camera read after it in the same physics step steps by zero. renderer.update_time(3 * _PHYSICS_DT) renderer.render_lidar(lidars[1], outputs[1]) - native.step_async.assert_called_with(render_products=products, delta_time=_PHYSICS_DT) + _assert_stepped(native, products, _PHYSICS_DT) assert (outputs[1].intensity.torch == 3).all() renderer.render(camera) - native.step_async.assert_called_with(render_products=products, delta_time=0.0) + _assert_stepped(native, products, 0.0) renderer.render_lidar(lidars[0], outputs[0]) assert (outputs[0].intensity.torch == 3).all() assert native.step_async.call_count == 3 @@ -526,7 +534,7 @@ def test_step_claims_elapsed_time_once_submitted(monkeypatch): renderer._render_batch_once([camera]) deltas = [call.kwargs["delta_time"] for call in native.step_async.call_args_list] - assert deltas == [3 * _PHYSICS_DT, 3 * _PHYSICS_DT, _PHYSICS_DT, 0.0] + assert deltas == pytest.approx([3 * _PHYSICS_DT, 3 * _PHYSICS_DT, _PHYSICS_DT, 0.0]) def test_lidar_output_readback(monkeypatch): @@ -2106,7 +2114,7 @@ def test_async_cameras_publish_independently_with_capture_metadata_and_reset(mon def submit(render_products, delta_time): # The first step of a capture advances by one physics step; the other cameras of the capture step by zero. - assert delta_time == (_PHYSICS_DT if not operations or operations[-1].ordinal != ordinal else 0.0) + assert delta_time == pytest.approx(_PHYSICS_DT if not operations or operations[-1].ordinal != ordinal else 0.0) operation = MagicMock() operation.ordinal = ordinal frames = [types.SimpleNamespace(end_time=float(ordinal), value=ordinal)]