Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
* Fixed :class:`~isaaclab_ov.renderers.ovrtx_lidar_sensor.OVRTXLidar` overwriting the returns of
every environment when only some were due. A capture still traces all tiles, but with
``update_period > 0`` it writes only the due environments, so each environment keeps its own
sampling period after partial resets.
40 changes: 31 additions & 9 deletions source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ def _channel(mapped, name: str, *, clone: bool = True) -> torch.Tensor | None:
return _as_torch(mapped[name], clone=clone)


def copy_tiled_point_cloud(mapped, points: torch.Tensor, intensity: torch.Tensor, valid: torch.Tensor) -> None:
def copy_tiled_point_cloud(
mapped, points: torch.Tensor, intensity: torch.Tensor, valid: torch.Tensor, *, env_mask: wp.array

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Compatibility — Preserve mask-free point-cloud copies

Existing four-argument copy_tiled_point_cloud calls now raise TypeError. Keep omission copying every tile; requiring a mask later needs a warned, documented, tested deprecation transition.

) -> None:
"""Copy one mapped point cloud into per-environment buffers.

``points`` has shape ``(num_envs, num_rays, 3)``. Tile ``i`` is environment ``i``, which is the
Expand All @@ -81,6 +83,7 @@ def copy_tiled_point_cloud(mapped, points: torch.Tensor, intensity: torch.Tensor
points: Destination positions.
intensity: Destination intensity, shape ``(num_envs, num_rays)``.
valid: Destination hit mask, shape ``(num_envs, num_rays)``.
env_mask: Environments to write, shape ``(num_envs,)``. Other environments keep their returns.

Raises:
RuntimeError: If the tile count, layout, or ray count does not match the destination.
Expand Down Expand Up @@ -153,7 +156,9 @@ def copy_tiled_point_cloud(mapped, points: torch.Tensor, intensity: torch.Tensor
raise RuntimeError(f"Unsupported OvRTX lidar coordsType: {coords_type!r}.")
spherical = coords_type == _SPHERICAL
if on_device:
_copy_dense_on_device(coordinates, signal, flags, points, intensity, valid, tile_count, stride, spherical)
_copy_dense_on_device(
coordinates, signal, flags, points, intensity, valid, tile_count, stride, spherical, env_mask=env_mask
)
else:
coordinates = coordinates.to(device=device, dtype=points.dtype)
if spherical:
Expand All @@ -166,23 +171,38 @@ def copy_tiled_point_cloud(mapped, points: torch.Tensor, intensity: torch.Tensor
signal = signal.to(device=device, dtype=intensity.dtype)
hit_source = (flags.to(device=device, dtype=torch.int64) & _VALID_FLAG) != 0

_copy_dense(coordinates, signal, hit_source, points, intensity, valid, tile_count, stride)
_copy_dense(
coordinates, signal, hit_source, points, intensity, valid, tile_count, stride, env_mask=env_mask
)


def _copy_dense(coordinates, signal, hits, points, intensity, valid, tile_count: int, stride: int) -> None:
"""Copy a dense ``(tile, ray)`` cloud. ``hits`` selects the finite returns."""
def _copy_dense(
coordinates, signal, hits, points, intensity, valid, tile_count: int, stride: int, *, env_mask: wp.array
) -> None:
"""Copy a dense ``(tile, ray)`` cloud. ``hits`` selects the finite returns, ``env_mask`` the written tiles."""
coordinates = coordinates.reshape(tile_count, stride, 3)
signal = signal.reshape(tile_count, stride)
hits = hits.reshape(tile_count, stride)
filled = torch.where(hits.unsqueeze(-1), coordinates, torch.full_like(coordinates, float("inf")))
signal = torch.where(hits, signal, torch.zeros_like(signal))
points.copy_(filled)
intensity.copy_(signal)
valid.copy_(hits)
due = wp.to_torch(env_mask).unsqueeze(-1)
points.copy_(torch.where(due.unsqueeze(-1), filled, points))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Implementation — Avoid fallback selection temporaries

Each CPU-map capture allocates three full-sized torch.where outputs and copies them into existing buffers. Write each selection directly to its destination with out=.

intensity.copy_(torch.where(due, signal, intensity))
valid.copy_(torch.where(due, hits, valid))
Comment on lines +188 to +191

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Due scans can be skipped

If Torch and Warp use different CUDA streams, the CPU-map fallback can read env_mask after SensorBase clears it. The three torch.where calls queue reads on Torch's current stream, but the caller immediately queues the clear on Warp's stream without waiting for those reads.

A due environment can keep old returns or get mismatched points, intensity, and validity, while its sampling clock is marked updated. Run the fallback copies on Warp's consuming stream too, so they read the mask before it is cleared.



def _copy_dense_on_device(
coordinates, signal, flags, points, intensity, valid, tile_count: int, stride: int, spherical: bool
coordinates,
signal,
flags,
points,
intensity,
valid,
tile_count: int,
stride: int,
spherical: bool,
*,
env_mask: wp.array,
) -> None:
"""Copy a dense CUDA ``(tile, ray)`` cloud into the destination buffers.

Expand All @@ -207,6 +227,8 @@ def _copy_dense_on_device(
wp.from_torch(intensity.reshape(count), dtype=wp.float32),
wp.from_torch(valid.reshape(count), dtype=wp.bool),
spherical,
env_mask,
stride,
],
device=launch_device,
)
15 changes: 9 additions & 6 deletions source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,18 +287,21 @@ def _invalidate_initialize_callback(self, event):
self._parent_view = None

def _update_buffers_impl(self, env_mask: wp.array):
"""Capture every tile when any environment is due. A tiled product cannot render one tile.
"""Capture every tile when any environment is due, and write only the due environments.

A forced capture still renders 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.
A tiled product cannot render one tile. A forced capture still renders when the sampling
period has not expired. ``update`` marks the buffers dirty without filling ``_is_outdated``,
so a forced capture, like ``update_period == 0``, writes every environment.
"""
if self.cfg.update_period > 0.0 and not self._force_capture and not bool(env_mask.numpy().any()):
due_envs_only = self.cfg.update_period > 0.0 and not self._force_capture
if due_envs_only 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)
self._renderer.render_lidar(
self._render_data, self._data, env_mask=env_mask if due_envs_only else self._ALL_ENV_MASK
)

def _push_renderer_pose(self) -> None:
"""Write the current world pose of every tile. Safe to call more than once per step."""
Expand Down
29 changes: 21 additions & 8 deletions source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -1035,13 +1035,13 @@ def _map_lidar_point_cloud(self, point_cloud, device: Device) -> Iterator[Any]:
finally:
mapping.unmap(stream=stream)

def render_lidar(self, render_data: OVRTXLidarRenderData, lidar_data: LidarData) -> None:
def render_lidar(self, render_data: OVRTXLidarRenderData, lidar_data: LidarData, *, env_mask: wp.array) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Compatibility — Preserve mask-free lidar captures

Existing two-argument render_lidar calls now raise TypeError. Make omission retain all-environment publication; requiring the mask later needs a warned, documented, tested deprecation transition.

"""Capture one tiled lidar product and publish its point cloud.

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.
submission waits. The product traces every tile; only the tiles in ``env_mask`` are written.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Style Consistency — Specify the required mask

The public method now requires env_mask, but its docstring gives no dtype, shape, or device requirement. Document the boolean (num_envs,) mask on the lidar data device.

"""
if not self._initialized_scene:
raise RuntimeError("Scene not initialized. Call initialize() first.")
Expand Down Expand Up @@ -1085,10 +1085,15 @@ def render_lidar(self, render_data: OVRTXLidarRenderData, lidar_data: LidarData)
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)
self._publish_lidar_output(render_data, result, lidar_data, env_mask=env_mask)

def _publish_lidar_output(
self, render_data: OVRTXLidarRenderData, products: RenderProductSetOutputs, lidar_data: LidarData
self,
render_data: OVRTXLidarRenderData,
products: RenderProductSetOutputs,
lidar_data: LidarData,
*,
env_mask: wp.array,
) -> None:
"""Split one lidar product's point cloud into ``lidar_data``.

Expand All @@ -1108,16 +1113,18 @@ def _publish_lidar_output(
)

try:
self._copy_mapped_lidar_point_cloud(point_cloud, lidar_data, Device.CUDA)
self._copy_mapped_lidar_point_cloud(point_cloud, lidar_data, Device.CUDA, env_mask=env_mask)
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

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)
self._copy_mapped_lidar_point_cloud(point_cloud, lidar_data, Device.CPU, env_mask=env_mask)

def _copy_mapped_lidar_point_cloud(self, point_cloud, lidar_data: LidarData, device: Device) -> None:
def _copy_mapped_lidar_point_cloud(
self, point_cloud, lidar_data: LidarData, device: Device, *, env_mask: wp.array
) -> 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.
Expand All @@ -1143,7 +1150,13 @@ def mapped_point_count(mapped) -> int:
if device is Device.CUDA and mapped_point_count(mapped) == 0:
raise RuntimeError("OVRTX lidar CUDA point cloud was empty")

copy_tiled_point_cloud(mapped, lidar_data.points.torch, lidar_data.intensity.torch, lidar_data.valid.torch)
copy_tiled_point_cloud(
mapped,
lidar_data.points.torch,
lidar_data.intensity.torch,
lidar_data.valid.torch,
env_mask=env_mask,
)

def update_lidar(
self,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,16 @@ def copy_dense_lidar_points_kernel(
intensity_out: wp.array(dtype=wp.float32),
valid: wp.array(dtype=wp.bool),
spherical: bool,
env_mask: wp.array(dtype=wp.bool),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Compatibility — Preserve the existing kernel launch

Existing seven-input launches no longer match this public kernel. Keep that launch functional and add a masked variant; retire the original only through a documented, warned, tested transition.

stride: int,
):
"""Copy one dense lidar cloud. Bit 6 of ``flags`` marks a hit; misses become non-finite."""
"""Copy one dense lidar cloud into the environments selected by ``env_mask``.

Bit 6 of ``flags`` marks a hit; misses become non-finite. ``stride`` is the slot count of one tile.
"""
i = wp.tid()
if not env_mask[i // stride]:
return
hit = (flags[i] & wp.int32(0x40)) != wp.int32(0)
if hit:
point = wp.vec3f(coordinates[i, 0], coordinates[i, 1], coordinates[i, 2])
Expand Down
36 changes: 28 additions & 8 deletions source/isaaclab_ov/test/test_ovrtx_lidar.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ def test_lidar_world_pose_composes_a_rotated_parent():


def test_cpu_mapped_spherical_cloud_preserves_returns():
"""Decode a CPU fallback map containing an oblique hit and a missed slot."""
"""Decode a CPU fallback map with an oblique hit and a missed slot. A tile that is not due keeps its returns."""
from isaaclab_ov.renderers.ovrtx_lidar import copy_tiled_point_cloud

from isaaclab.sensors import LidarData
Expand All @@ -143,16 +143,20 @@ class MappedCloud(dict):
params = {"coordsType": np.array([1]), "tileStridePoints": np.array([2])}

cloud = MappedCloud(
Coordinates=np.array([[90.0, -30.0, 2.0], [10.0, 20.0, 3.0]], dtype=np.float32),
Flags=np.array([0x40, 0], dtype=np.int32),
Intensity=np.array([0.75, 1.0], dtype=np.float32),
Coordinates=np.array(
[[90.0, -30.0, 2.0], [10.0, 20.0, 3.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]], dtype=np.float32
),
Flags=np.array([0x40, 0, 0x40, 0x40], dtype=np.int32),
Intensity=np.array([0.75, 1.0, 1.0, 1.0], dtype=np.float32),
)
data = LidarData(1, 2, "cpu")
copy_tiled_point_cloud(cloud, data.points.torch, data.intensity.torch, data.valid.torch)
data = LidarData(2, 2, "cpu")
env_mask = wp.array([True, False], dtype=wp.bool, device="cpu")
copy_tiled_point_cloud(cloud, data.points.torch, data.intensity.torch, data.valid.torch, env_mask=env_mask)
torch.testing.assert_close(data.points.torch[0, 0], torch.tensor([0.0, math.sqrt(3.0), -1.0]))
assert torch.isinf(data.points.torch[0, 1]).all()
torch.testing.assert_close(data.valid.torch, torch.tensor([[True, False]]))
torch.testing.assert_close(data.intensity.torch, torch.tensor([[0.75, 0.0]]))
assert torch.isinf(data.points.torch[1]).all()
torch.testing.assert_close(data.valid.torch, torch.tensor([[True, False], [False, False]]))
torch.testing.assert_close(data.intensity.torch, torch.tensor([[0.75, 0.0], [0.0, 0.0]]))


@pytest.mark.integration
Expand Down Expand Up @@ -192,6 +196,7 @@ class SceneCfg(InteractiveSceneCfg):
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")
periodic = replace(lidar, prim_path="{ENV_REGEX_NS}/Periodic", update_period=10.0)

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))
Expand Down Expand Up @@ -220,6 +225,21 @@ class SceneCfg(InteractiveSceneCfg):
assert lidar.data.valid.torch[1].all()
torch.testing.assert_close(lidar.data.points.torch[1], kept)

# After a reset of environment 0, the periodic lidar captures again but writes only that
# environment. Environment 1 is not due and keeps its scan although its target moved.
periodic = scene["periodic"]
periodic_kept = periodic.data.points.torch[1].clone()
periodic.reset(env_ids=[0])
target = scene["target"]
pose = target.data.root_link_pose_w.torch.clone()
pose[1, :3] += pose.new_tensor([0.3, 0.3, -0.3])
target.write_root_pose_to_sim_index(root_pose=pose)
sim.step()
scene.update(sim.get_physics_dt())
assert not torch.allclose(lidar.data.points.torch[1], kept, atol=1e-3)
assert periodic.data.valid.torch[0].all()
torch.testing.assert_close(periodic.data.points.torch[1], periodic_kept)


@pytest.mark.integration
@pytest.mark.rendering
Expand Down
15 changes: 10 additions & 5 deletions source/isaaclab_ov/test/test_ovrtx_renderer_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,9 +453,10 @@ def test_lidar_and_camera_captures_use_separate_steps(monkeypatch):
assert native.step.call_args.kwargs["render_products"] == set(camera.render_product_paths)

data = LidarData(1, 1, "cpu")
renderer.render_lidar(lidar, data)
env_mask = wp.ones(1, dtype=wp.bool, device="cpu")
renderer.render_lidar(lidar, data, env_mask=env_mask)
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)
publish.assert_called_once_with(lidar, native.step.return_value, data, env_mask=env_mask)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Test Quality — Drop private mask forwarding assertion

The new exact mask assertion checks a mocked private handoff, while integration checks its observable effect. Retain the separate-step assertion and check only that publication occurred.



def test_lidar_readback_propagates_cpu_map_failure(monkeypatch):
Expand All @@ -473,7 +474,9 @@ def test_lidar_readback_propagates_cpu_map_failure(monkeypatch):
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"))
renderer._publish_lidar_output(
lidar, products, LidarData(1, 1, "cpu"), env_mask=wp.ones(1, dtype=wp.bool, device="cpu")
)


@pytest.mark.parametrize("missing", ["product", "renderer", "backend"])
Expand All @@ -495,7 +498,7 @@ def test_lidar_capture_fails_when_unavailable(monkeypatch, missing):
renderer.backend = None

with pytest.raises(RuntimeError, match=lidar.render_product_path):
renderer.render_lidar(lidar, LidarData(1, 1, "cpu"))
renderer.render_lidar(lidar, LidarData(1, 1, "cpu"), env_mask=wp.ones(1, dtype=wp.bool, device="cpu"))


def test_ovrtx_render_batch_empty_sequence_does_not_require_initialized_backend():
Expand Down Expand Up @@ -2847,7 +2850,9 @@ def consume(*_args, **_kwargs):
valid=types.SimpleNamespace(torch=object()),
)
with pytest.raises(ValueError, match="consumer failed") if consumer_fails else contextlib.nullcontext():
renderer._copy_mapped_lidar_point_cloud(point_cloud, lidar_data, ovrtx_renderer_module.Device.CUDA)
renderer._copy_mapped_lidar_point_cloud(
point_cloud, lidar_data, ovrtx_renderer_module.Device.CUDA, env_mask=object()
)

assert point_cloud.map.call_args.kwargs["sync_stream"] == (expected_stream if gpu_side else 0)
assert events == ([] if gpu_side else ["wait"]) + ["consume", ("release", expected_stream)]
39 changes: 27 additions & 12 deletions source/isaaclab_ov/test/test_ovrtx_renderer_kernels.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,29 +258,33 @@ def test_matches_host_reference(self):

@pytest.mark.skipif(not wp.is_cuda_available(), reason="CUDA not available")
def test_copy_dense_lidar_points_kernel_keeps_hits_and_clears_misses():
"""A dense cloud writes hit positions and replaces misses with non-finite points."""
"""A dense cloud writes hits and non-finite misses into due tiles. A tile that is not due keeps its returns."""
coordinates = wp.array(
np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=np.float32), dtype=wp.float32, device=DEVICE
np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [1.0, 1.0, 1.0]], dtype=np.float32),
dtype=wp.float32,
device=DEVICE,
)
intensity = wp.array(np.array([0.5, 0.25], dtype=np.float32), dtype=wp.float32, device=DEVICE)
flags = wp.array(np.array([0x40, 0], dtype=np.int32), dtype=wp.int32, device=DEVICE)
points = wp.zeros(2, dtype=wp.vec3f, device=DEVICE)
out_intensity = wp.full(2, 7.0, dtype=wp.float32, device=DEVICE)
valid = wp.zeros(2, dtype=wp.bool, device=DEVICE)
intensity = wp.array(np.array([0.5, 0.25, 1.0, 1.0], dtype=np.float32), dtype=wp.float32, device=DEVICE)
flags = wp.array(np.array([0x40, 0, 0x40, 0x40], dtype=np.int32), dtype=wp.int32, device=DEVICE)
points = wp.zeros(4, dtype=wp.vec3f, device=DEVICE)
out_intensity = wp.full(4, 7.0, dtype=wp.float32, device=DEVICE)
valid = wp.zeros(4, dtype=wp.bool, device=DEVICE)
env_mask = wp.array([True, False], dtype=wp.bool, device=DEVICE)

wp.launch(
copy_dense_lidar_points_kernel,
dim=2,
inputs=[coordinates, intensity, flags, points, out_intensity, valid, False],
dim=4,
inputs=[coordinates, intensity, flags, points, out_intensity, valid, False, env_mask, 2],
device=DEVICE,
)
wp.synchronize()

points_np = points.numpy()
np.testing.assert_allclose(points_np[0], [1.0, 2.0, 3.0])
assert not np.isfinite(points_np[1]).any()
np.testing.assert_allclose(out_intensity.numpy(), [0.5, 0.0])
np.testing.assert_array_equal(valid.numpy(), [True, False])
np.testing.assert_allclose(points_np[2:], 0.0)
np.testing.assert_allclose(out_intensity.numpy(), [0.5, 0.0, 7.0, 7.0])
np.testing.assert_array_equal(valid.numpy(), [True, False, False, False])


@pytest.mark.skipif(not wp.is_cuda_available(), reason="CUDA not available")
Expand All @@ -297,7 +301,18 @@ def test_copy_dense_on_device_returns_without_waiting_for_the_device(monkeypatch
intensity = torch.zeros((1, 2), device=DEVICE)
valid = torch.zeros((1, 2), dtype=torch.bool, device=DEVICE)

_copy_dense_on_device(coordinates, signal, flags, points, intensity, valid, 1, 2, spherical=True)
_copy_dense_on_device(
coordinates,
signal,
flags,
points,
intensity,
valid,
1,
2,
spherical=True,
env_mask=wp.ones(1, dtype=wp.bool, device=DEVICE),
)
wp.synchronize()

np.testing.assert_allclose(points[0, 0].cpu().numpy(), [0.0, np.sqrt(3.0), -1.0], atol=1e-6)
Expand Down
Loading