diff --git a/source/isaaclab/changelog.d/pr-9215-lidar-test-viewers.skip b/source/isaaclab/changelog.d/pr-9215-lidar-test-viewers.skip new file mode 100644 index 00000000000..e69de29bb2d diff --git a/source/isaaclab/test/markers/test_visualization_markers.py b/source/isaaclab/test/markers/test_visualization_markers.py index 577f34a0dba..af3eb5bd0f8 100644 --- a/source/isaaclab/test/markers/test_visualization_markers.py +++ b/source/isaaclab/test/markers/test_visualization_markers.py @@ -408,6 +408,7 @@ def test_visualizer_step_renders_markers_and_closes_frame(monkeypatch, caplog, m class Viewer: show_contacts = False + show_lidar_hits = False _server = SimpleNamespace(get_clients=lambda: {0: object()}) def is_paused(self): diff --git a/source/isaaclab_visualizers/changelog.d/OMPE-118533-lidar-visualization-toggle.changed.rst b/source/isaaclab_visualizers/changelog.d/OMPE-118533-lidar-visualization-toggle.changed.rst new file mode 100644 index 00000000000..818043abfa5 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/OMPE-118533-lidar-visualization-toggle.changed.rst @@ -0,0 +1,3 @@ +* Replaced the every-tenth-step lidar hit upload with an opt-in overlay. Newton GL and Viser expose a + checkbox. ``NewtonGLBackendCfg.show_lidar_hits`` and ``ViserBackendCfg.show_lidar_hits`` enable it + at launch. diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/kit/kit_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/kit/kit_visualizer.py index 654c2c99169..3232b2302c5 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/kit/kit_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/kit/kit_visualizer.py @@ -79,7 +79,6 @@ def __init__(self, cfg: VisualizerCfg): self._simulation_app = None self._viewport_window = None self._viewport_api = None - self._step_counter = 0 self._hidden_env_visibilities: dict[str, str] = {} # PointInstancer prim path -> (had authored invisibleIds, previous value) for partial viz restore. self._point_instancer_invisible_ids_backup: dict[str, tuple[bool, object]] = {} @@ -199,7 +198,7 @@ def step(self, dt: float) -> None: return self._app_pumped_this_step = False self._sim_time += dt - self._step_counter += 1 + # Headless mode: skip the app update and camera panel refresh; rendering is # triggered on demand by render_rgb_array() / render_tiled_rgb_array(). if self._runtime_headless: @@ -233,7 +232,7 @@ def _draw_lidar_points(self) -> None: Debug draw is a viewport overlay, so the lidar product does not scan the points. A missing debug-draw interface is reported once and the step continues. """ - hits = collect_lidar_hits(self._sim, self._env_ids, self._step_counter) + hits = collect_lidar_hits(self._sim, self._env_ids) if hits is None: return draw = self._lidar_debug_draw() diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/lidar_points.py b/source/isaaclab_visualizers/isaaclab_visualizers/lidar_points.py index 1c39345ff79..fa9ebb8f46f 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/lidar_points.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/lidar_points.py @@ -8,7 +8,7 @@ from __future__ import annotations import math -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any import numpy as np import torch @@ -23,9 +23,6 @@ from isaaclab.visualizers.base_visualizer import BaseVisualizer -LIDAR_LOG_INTERVAL = 10 -"""Visualizer steps between host copies of one environment's lidar hits.""" - LIDAR_POINT_RADIUS = 0.02 """Sphere radius, in meters, used by viewers that log a point batch.""" @@ -207,10 +204,33 @@ def frame_visualizer_closeup(visualizer: BaseVisualizer, cameras) -> None: camera.lookat = lookat -def collect_lidar_hits( - sim: SimulationContext, env_ids: list[int] | None, step_counter: int -) -> list[tuple[str, np.ndarray]] | None: - """Return every visualized environment's lidar hits on every tenth visualizer step. +def _ovrtx_lidar_cls() -> type | None: + """Return :class:`~isaaclab_ov.renderers.ovrtx_lidar_sensor.OVRTXLidar`, or None if it is unavailable.""" + try: + from isaaclab_ov.renderers.ovrtx_lidar_sensor import OVRTXLidar + except ImportError: + return None + return OVRTXLidar + + +def scene_has_lidar(sim: SimulationContext) -> bool: + """Return whether the interactive scene owns an OvRTX lidar. + + Args: + sim: Simulation whose interactive scene is searched. + + Returns: + True when at least one sensor is an OvRTX lidar. + """ + scene = sim.get_scene_data_provider().get_interactive_scene() + lidar_cls = _ovrtx_lidar_cls() + if scene is None or lidar_cls is None: + return False + return any(isinstance(sensor, lidar_cls) for sensor in scene.sensors.values()) + + +def collect_lidar_hits(sim: SimulationContext, env_ids: list[int] | None) -> list[tuple[str, np.ndarray]]: + """Return every visualized environment's lidar hits. ``env_ids`` None includes every environment. Each lidar is included even when its cloud is empty, so a viewer can hide the previous batch. Other sensors are ignored. @@ -218,31 +238,54 @@ def collect_lidar_hits( Args: sim: Simulation whose interactive scene owns the lidars. env_ids: Visualized environments. None includes every environment. - step_counter: Visualizer step. Hits are collected when this is a multiple of - :data:`LIDAR_LOG_INTERVAL`. Returns: - ``(sensor_name, points)`` pairs, or None when this step is not logged. + ``(sensor_name, points)`` pairs. """ - if step_counter % LIDAR_LOG_INTERVAL != 0: - return None scene = sim.get_scene_data_provider().get_interactive_scene() - if scene is None: - return [] - - try: - from isaaclab_ov.renderers.ovrtx_lidar_sensor import OVRTXLidar - except ImportError: + lidar_cls = _ovrtx_lidar_cls() + if scene is None or lidar_cls is None: return [] selected = None if env_ids is None else list(env_ids) hits = [] for name, sensor in scene.sensors.items(): - if isinstance(sensor, OVRTXLidar): + if isinstance(sensor, lidar_cls): hits.append((name, lidar_world_points(sensor, selected))) return hits +def sync_lidar_hits( + sim: SimulationContext, + env_ids: list[int] | None, + viewer: Any, + enabled: bool, + previous_names: list[str], +) -> list[str]: + """Upload lidar hits when enabled, or hide the previous batch when disabled. + + A disabled step with no previous names does not read the scene. A disabled step with previous + names logs empty clouds so the last batch disappears. + + Args: + sim: Simulation whose interactive scene owns the lidars. + env_ids: Visualized environments. None includes every environment. + viewer: Newton or Viser viewer. + enabled: Whether lidar hits are copied and uploaded this step. + previous_names: Sensor names logged on a previous enabled step. + + Returns: + Sensor names logged this step, or an empty list when the cloud is hidden. + """ + if not enabled: + if previous_names: + log_lidar_hits(viewer, [(name, np.empty((0, 3), dtype=np.float32)) for name in previous_names]) + return [] + hits = collect_lidar_hits(sim, env_ids) + log_lidar_hits(viewer, hits) + return [name for name, _ in hits] + + def log_lidar_hits(viewer, hits: list[tuple[str, np.ndarray]], radius: float = LIDAR_POINT_RADIUS) -> None: """Log collected hits through a viewer ``log_points`` method. diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py index 52b1e2b68e8..cb81c5dbd7b 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py @@ -54,7 +54,7 @@ from isaaclab.visualizers.visualizer_cfg import PerspectiveCameraCfg, WindowCfg from isaaclab_visualizers.desktop_entry import write_desktop_entry -from isaaclab_visualizers.lidar_points import collect_lidar_hits, frame_visualizer_closeup, log_lidar_hits +from isaaclab_visualizers.lidar_points import frame_visualizer_closeup, scene_has_lidar, sync_lidar_hits from isaaclab_visualizers.newton.newton_overlay_meshes import OverlayMeshPublisher from isaaclab_visualizers.newton.newton_visualization_markers import render_newton_visualization_markers @@ -176,6 +176,9 @@ class NewtonViewerGL(ViewerGL): """Newton GL window with Isaac Lab controls and device-image presentation.""" _contacts_available = True + _lidar_available = False + show_lidar_hits = False + """Whether lidar hits are copied onto the host and drawn in the OpenGL view.""" CAMERA_SPEED_BOOST_MULTIPLIER = 2.0 camera_keys_suspended = False """Set while keyboard camera movement is disabled (see :meth:`NewtonVisualizerBase.set_camera_keys_enabled`).""" @@ -535,6 +538,15 @@ def tip(text: str) -> None: tip("Length of the contact arrows") _, renderer.arrow_scale = imgui.slider_float("Contact Width", renderer.arrow_scale, 0.25, 5.0) tip("Width of the contact arrows") + _lidar_available = (not rtx) and self._lidar_available + self.show_lidar_hits = _imgui_optional_checkbox( + imgui, + "Show Lidar Hits", + self.show_lidar_hits, + _lidar_available, + "OpenGL only" if rtx else "No lidar sensors in this environment", + "Copy and draw lidar hits", + ) _model = self.model _has_particles = _model.particle_count > 0 _has_springs = _model.spring_count > 0 @@ -1667,7 +1679,7 @@ def __init__(self, cfg: VisualizerCfg): self._cfg_visible_env_ids: list[int] | None = None self._visible_env_count: int | None = None self._num_envs = 0 - self._lidar_step_counter = 0 + self._logged_lidar_names: list[str] = [] # ------------------------------------------------------------------ # GL lifecycle @@ -1776,13 +1788,13 @@ def initialize(self, sim: SimulationContext, *, cameras: list[PerspectiveCameraC # out "Show Contacts" when neither native Newton contacts nor a ContactSensor # exists in the scene. self._viewer._contacts_available = newton_backend_active or bool(scene_data_provider.get_contact_sensors()) + self._viewer._lidar_available = scene_has_lidar(sim) - def _log_lidar_points(self, viewer: Any) -> None: + def _log_lidar_hits(self, viewer: Any) -> None: """Log every visualized environment's lidar hits into the Newton GL scene.""" - self._lidar_step_counter += 1 - hits = collect_lidar_hits(self._sim, self._env_ids, self._lidar_step_counter) - if hits is not None: - log_lidar_hits(viewer, hits) + self._logged_lidar_names = sync_lidar_hits( + self._sim, self._env_ids, viewer, viewer.show_lidar_hits, self._logged_lidar_names + ) def _render_frame(self) -> None: """Render one GL frame for the window or an on-demand capture.""" @@ -1824,7 +1836,7 @@ def _render_frame(self) -> None: self._log_scene_contact_sensor_arrows() if self.cfg.enable_markers: render_newton_visualization_markers(viewer, self._env_ids, num_envs=self.backend.model.num_envs) - self._log_lidar_points(viewer) + self._log_lidar_hits(viewer) for name, arguments in self._pending_mesh_submissions.items(): viewer.log_mesh(name, **arguments) self._pending_mesh_submissions.clear() @@ -2300,6 +2312,7 @@ def _configure_viewer(self) -> None: self._viewer.show_inertia_boxes = self.cfg.backend.show_inertia_boxes self._viewer.show_com = self.cfg.backend.show_com self._viewer.show_particles = self.cfg.backend.show_particles + self._viewer.show_lidar_hits = self.cfg.backend.show_lidar_hits self._viewer.up_axis = 2 # Z-up self._viewer.scaling = 1.0 self._viewer.particle_color = self.cfg.backend.particle_color diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer_cfg.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer_cfg.py index 21f8bf30156..30d53929240 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer_cfg.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer_cfg.py @@ -53,6 +53,9 @@ class NewtonGLBackendCfg(VisualizerBackendCfg): show_particles: bool = True """Show simulation particles. Set to False to hide them, for example in a surface-only view.""" + show_lidar_hits: bool = False + """Show lidar hit visualization. Set to True to copy and draw hits; a dense scan is expensive to upload.""" + particle_color: tuple[float, float, float] | None = None """Optional particle color RGB [0, 1]. Uses Newton viewer defaults when ``None``.""" diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer.py index 5944d325a8c..25512a4e774 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer.py @@ -27,7 +27,7 @@ from isaaclab.visualizers.base_visualizer import BaseVisualizer from isaaclab.visualizers.visualizer_cfg import PerspectiveCameraCfg -from isaaclab_visualizers.lidar_points import collect_lidar_hits, frame_visualizer_closeup, log_lidar_hits +from isaaclab_visualizers.lidar_points import frame_visualizer_closeup, sync_lidar_hits from isaaclab_visualizers.newton.newton_visualization_markers import render_newton_visualization_markers from isaaclab_visualizers.newton_adapter import log_geo_with_expanded_plane_scale @@ -289,7 +289,7 @@ def __init__(self, cfg: VisualizerCfg): self.backend = None self._pending_camera_pose: tuple[tuple[float, float, float], tuple[float, float, float]] | None = None self._warned_marker_render_failure = False - self._lidar_step_counter = 0 + self._logged_lidar_names: list[str] = [] self._paused_rendering = False self._paused_simulation = False @@ -327,6 +327,7 @@ def initialize(self, sim: SimulationContext, *, cameras: list[PerspectiveCameraC self._viewer.set_model(self.backend.model) self._geometry_change_version = self.backend.geometry_change_version self._viewer.show_particles = self.cfg.backend.show_particles + self._viewer.show_lidar_hits = self.cfg.backend.show_lidar_hits # set_model() clears model-dependent GUI elements; build the sidebar afterwards. self._setup_isaaclab_sidebar(self._viewer._server) self._viewer.set_visible_worlds(self._env_ids) @@ -398,7 +399,7 @@ def step(self, dt: float) -> None: self._viewer.log_state(self.backend.state_0) if self.cfg.enable_markers: self._render_markers(self.backend.model.num_envs) - self._log_lidar_points() + self._log_lidar_hits() self._render_live_plots() self._push_streaming_frame() finally: @@ -417,14 +418,13 @@ def _push_streaming_frame(self) -> None: # the browser canvas. Black bars are added on whichever axis needs it. self._viewer._server.scene.set_background_image(_letterbox_16_9(composite), format="jpeg") - def _log_lidar_points(self) -> None: - """Log one lidar environment's hits into the Viser scene.""" + def _log_lidar_hits(self) -> None: + """Log lidar hits into the Viser scene when the overlay is enabled.""" if self._viewer is None: return - self._lidar_step_counter += 1 - hits = collect_lidar_hits(self._sim, self._env_ids, self._lidar_step_counter) - if hits is not None: - log_lidar_hits(self._viewer, hits) + self._logged_lidar_names = sync_lidar_hits( + self._sim, self._env_ids, self._viewer, self._viewer.show_lidar_hits, self._logged_lidar_names + ) def _render_markers(self, num_envs: int) -> None: """Render marker overlays without letting them interrupt Viser body updates.""" @@ -566,6 +566,7 @@ def _(_): ("Springs", "show_springs"), ("Cloth", "show_triangles"), ("Inertia Boxes", "show_inertia_boxes"), + ("Lidar Hits", "show_lidar_hits"), ] with vis_folder: for label, attr in _VIZ_FLAGS: diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer_cfg.py b/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer_cfg.py index 67336960a72..8eaf611a94f 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer_cfg.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/viser/viser_visualizer_cfg.py @@ -67,6 +67,13 @@ class ViserBackendCfg(VisualizerBackendCfg): panel in the Viser sidebar. """ + show_lidar_hits: bool = False + """Copy lidar hits to the viewer and draw them. + + Off by default. A dense scan is expensive to move to the host and upload every visualizer step. + Viser exposes a runtime checkbox. + """ + @configclass class ViserVisualizerCfg(ViserBackendCfg, VisualizerCfg): diff --git a/source/isaaclab_visualizers/test/test_lidar_points.py b/source/isaaclab_visualizers/test/test_lidar_points.py index eb9d27bc2ab..0a7b9d1ee61 100644 --- a/source/isaaclab_visualizers/test/test_lidar_points.py +++ b/source/isaaclab_visualizers/test/test_lidar_points.py @@ -20,6 +20,7 @@ frame_visualizer_closeup, lidar_world_points, log_lidar_hits, + sync_lidar_hits, ) from isaaclab.test.utils import DeviceScope, test_devices @@ -86,8 +87,8 @@ def __del__(self): return _Lidar() -def test_collect_lidar_hits_returns_lidar_clouds_on_the_interval(): - """Only lidar sensors are returned, and only on every tenth step.""" +def _lidar_sim(): + """Simulation stand-in with one hit lidar, one empty lidar, and a non-lidar sensor.""" scene = SimpleNamespace( sensors={ "range": _world_lidar(torch.tensor([[[1.0, 2.0, 3.0]]]), torch.tensor([[True]])), @@ -97,10 +98,12 @@ def test_collect_lidar_hits_returns_lidar_clouds_on_the_interval(): "camera": object(), } ) - sim = SimpleNamespace(get_scene_data_provider=lambda: SimpleNamespace(get_interactive_scene=lambda: scene)) + return SimpleNamespace(get_scene_data_provider=lambda: SimpleNamespace(get_interactive_scene=lambda: scene)) + - assert collect_lidar_hits(sim, [0], 9) is None - hits = collect_lidar_hits(sim, [0], 10) +def test_collect_lidar_hits_returns_lidar_clouds(): + """Only lidar sensors are returned, including an empty cloud so a viewer can hide the last batch.""" + hits = collect_lidar_hits(_lidar_sim(), [0]) assert [name for name, _ in hits] == ["range", "empty"] np.testing.assert_allclose(hits[0][1], [[1.0, 2.0, 3.0]]) assert hits[1][1].shape == (0, 3) @@ -114,7 +117,7 @@ def test_collect_lidar_hits_draws_every_environment_without_a_subset(): ) scene = SimpleNamespace(sensors={"lidar": sensor}) sim = SimpleNamespace(get_scene_data_provider=lambda: SimpleNamespace(get_interactive_scene=lambda: scene)) - hits = collect_lidar_hits(sim, None, 10) + hits = collect_lidar_hits(sim, None) np.testing.assert_allclose(hits[0][1], [[70.0, -70.0, 1.0], [10.0, -10.0, 2.0]]) @@ -171,6 +174,25 @@ class _ViewerViser(_RecordingViewer): """Name matches the Viser viewer, which copies the batch on the CPU.""" +def test_sync_lidar_hits_hides_previous_clouds_until_enabled(): + """A disabled overlay hides the last batch without reading the scene. Enabling uploads lidar hits.""" + viewer = _ViewerViser("cpu") + assert sync_lidar_hits(None, [0], viewer, False, []) == [] + assert viewer.batches == [] + + assert sync_lidar_hits(None, [0], viewer, False, ["range"]) == [] + name, cloud, _, _ = viewer.batches[0] + assert name == "lidar/range" + assert cloud is None + + names = sync_lidar_hits(_lidar_sim(), [0], viewer, True, []) + assert names == ["range", "empty"] + uploaded = [batch[0] for batch in viewer.batches[1:]] + assert uploaded == ["lidar/range", "lidar/empty"] + np.testing.assert_allclose(viewer.batches[1][1].numpy(), [[1.0, 2.0, 3.0]]) + assert viewer.batches[2][1] is None + + @pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA)) def test_log_lidar_hits_allocates_gl_points_on_the_viewer_device(device: str) -> None: """A GL viewer must receive positions and colors on its own device.""" diff --git a/source/isaaclab_visualizers/test/test_newton_adapter.py b/source/isaaclab_visualizers/test/test_newton_adapter.py index 39d2ec0b27d..c7dc28cf1e8 100644 --- a/source/isaaclab_visualizers/test/test_newton_adapter.py +++ b/source/isaaclab_visualizers/test/test_newton_adapter.py @@ -566,6 +566,7 @@ class _Viewer: def __init__(self): self.device = "cpu" self.show_contacts = False + self.show_lidar_hits = False self.paused = False self.logged_state = None self.logged_contacts = None