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..dd315da89810 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.""" @@ -210,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/changelog.d/huidongc-lidar-scan.added.rst b/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.added.rst new file mode 100644 index 000000000000..a50262b6ebd9 --- /dev/null +++ b/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.added.rst @@ -0,0 +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 new file mode 100644 index 000000000000..ff74f3e21dca --- /dev/null +++ b/source/isaaclab_ov/changelog.d/huidongc-lidar-scan.changed.rst @@ -0,0 +1,7 @@ +* **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. +* 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. 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/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..6b2cebb6d65c --- /dev/null +++ b/source/isaaclab_ov/changelog.d/ovrtx-shared-engine-step.fixed.rst @@ -0,0 +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 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_lidar_cfg.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py index 6c8ea581be99..75fcc253ae55 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,18 @@ 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)``, 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. 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" """USD ``scanType`` token. Defaults to ``rotary``. @@ -75,7 +87,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 +98,11 @@ 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 + """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. @@ -131,6 +146,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..152d325a303b 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) @@ -210,13 +209,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: @@ -238,12 +237,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.""" @@ -270,6 +273,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 = self._push_renderer_pose self._push_renderer_pose() def _invalidate_initialize_callback(self, event): @@ -289,14 +294,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 03801a364723..c9828476397e 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 @@ -75,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 @@ -119,13 +123,19 @@ 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 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." @@ -320,6 +330,12 @@ def __init__(self, cfg: OVRTXBackendCfg): self.cfg = cfg self.attached = False self.render_products: set[str] = set() + # 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. self.unrendered: dict[OVRTXCameraRenderData, OVRTXRenderer] = {} # Resolve the wheel's native dependency here, including callers without a viewer. @@ -537,19 +553,23 @@ 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: 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 @@ -852,8 +872,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( @@ -945,10 +964,12 @@ 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 - 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 @@ -977,12 +998,10 @@ def _map_lidar_point_cloud(self, point_cloud, device: Device) -> Iterator[Any]: 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 simulated time advanced since its 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.") @@ -993,70 +1012,64 @@ 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.") - 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.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) + wp.copy(lidar_data.valid.warp, render_data.scan.valid.warp) 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. - """ - 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}.") + 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. + 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 - 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)}." - ) - 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 + # 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 + ) + + return + + # 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 - 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) + 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, 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. @@ -1915,6 +1928,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(): @@ -2049,11 +2069,19 @@ 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 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() - # 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.backend.time != self.backend.step_time: + lidars = tuple(self.backend.lidars.items()) + for data, _ in lidars: + 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: @@ -2068,11 +2096,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._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. 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) @@ -2081,7 +2112,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._submit_step(products).wait().fetch() + self._keep_lidar_scans(result, lidars) self._process_render_products(render_data, result) finally: if material_writer is not None: @@ -2098,9 +2130,38 @@ 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._submit_step(products, ordinal=ordinal).wait().fetch() + self._keep_lidar_scans(result, lidars) 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 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 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. + """ + time = self.backend.time + kwargs = {} if ordinal is None else {"ordinal": ordinal} + delta_time = time - self.backend.step_time + operation = self.backend.renderer.step_async(render_products=products, delta_time=delta_time, **kwargs) + 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]] + ) -> 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 ef44125c28ac..1664f8c6c221 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() @@ -221,6 +232,89 @@ 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_async = ovrtx.Renderer.step_async + + # 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_async", 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], + # 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") + # 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 @@ -237,12 +331,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 +353,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 +367,118 @@ 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 + 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() + 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 + # 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 + ) + + 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" diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py b/source/isaaclab_ov/test/test_ovrtx_renderer_contract.py index 3821b2b9bc77..3253b126a4a1 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 +"""Simulated time of one physics step in these tests [s].""" def _make_camera_cfg(data_types: list[str]) -> CameraCfg: @@ -106,6 +106,20 @@ 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 _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}" @@ -126,6 +140,8 @@ def _make_ovrtx_renderer_without_backend() -> OVRTXRenderer: renderer.backend.attached = False renderer.backend.render_products = set() renderer.backend.unrendered = {} + 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 renderer.backend.cfg = cfg @@ -186,7 +202,6 @@ def _simulation_registry(monkeypatch): plan=None, ) sim.render_context = sim._render_context - sim.get_rendering_dt = lambda: _RENDERING_DT sim.get_clone_plan = lambda: sim.plan sim.get_scene_data_provider = lambda: types.SimpleNamespace( backend=types.SimpleNamespace(transform_paths=[]), get_geometry_points=lambda: {} @@ -403,12 +418,13 @@ 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)) render = renderer.render_batch if batch else renderer.render request = cameras if batch else cameras[0] + renderer.update_time(_PHYSICS_DT) if missing_output is None: render(request) assert processed == [ @@ -421,8 +437,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,8 +453,8 @@ 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 @@ -448,43 +464,143 @@ def test_lidar_and_camera_captures_use_separate_steps(monkeypatch): 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: 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()) - publish = MagicMock() - monkeypatch.setattr(renderer, "_publish_lidar_output", publish) + # Each kept scan records the physics step that produced it. + def keep(data, products, scan): + 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. + renderer.update_time(2 * _PHYSICS_DT) + renderer.render(camera) + _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) + assert (output.intensity.torch == 2).all() + 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. + renderer.update_time(3 * _PHYSICS_DT) + renderer.render_lidar(lidars[1], outputs[1]) + _assert_stepped(native, products, _PHYSICS_DT) + assert (outputs[1].intensity.torch == 3).all() renderer.render(camera) - assert native.step.call_args.kwargs["render_products"] == set(camera.render_product_paths) + _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 + 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.""" + 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] + + renderer.update_time(3 * _PHYSICS_DT) + with pytest.raises(RuntimeError, match="rejected"): + renderer._render_batch_once([camera]) + renderer._render_batch_once([camera]) + renderer.update_time(4 * _PHYSICS_DT) + with pytest.raises(RuntimeError, match="failed while rendering"): + renderer._render_batch_once([camera]) + renderer._render_batch_once([camera]) - 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) + deltas = [call.kwargs["delta_time"] for call in native.step_async.call_args_list] + assert deltas == pytest.approx([3 * _PHYSICS_DT, 3 * _PHYSICS_DT, _PHYSICS_DT, 0.0]) -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("Failed to map output") + 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)) - 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"), + monkeypatch.setattr(renderer, "_copy_mapped_lidar_point_cloud", copy) + + lidar = ovrtx_renderer_module.OVRTXLidarRenderData("Lidar", ["/Lidar"], LidarData(1, 1, "cpu")) + 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"] + + # 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() + frames[1].render_vars = {lidar.point_cloud_path: "incomplete"} + lidar_data = new_lidar_data() + with pytest.raises(RuntimeError, match="Failed to map output"): + renderer._publish_lidar_output(lidar, products, lidar_data) + assert copied == [] + 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 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 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 = { + 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"]) @@ -1768,8 +1884,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. @@ -1939,16 +2055,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"]) @@ -1996,8 +2113,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 == 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)] if batch: # SDK capture times identify the real image independently of the returned list order. @@ -2019,6 +2138,7 @@ def consume(camera, frame, buffers): def capture(value, indices): nonlocal ordinal ordinal = value + 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_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 a33837f3a4ca..d56b4f63666b 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): @@ -122,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={}) + 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 @@ -130,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_rendering_dt=lambda: 1.0 / 60.0) + renderer._sim = SimpleNamespace() renderer._camera_render_data = [] if use_ovstage: from isaaclab_ov.stage import OvstageBackend