Skip to content
Draft
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 @@
* 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.
Empty file.
8 changes: 8 additions & 0 deletions source/isaaclab/isaaclab/renderers/base_renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,14 @@ def update_geometries(self) -> None:
"""
pass

def update_time(self, time: float) -> None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Why not:

def render(self, render_data: Any, dt: 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,
Expand Down
17 changes: 13 additions & 4 deletions source/isaaclab/isaaclab/renderers/render_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -66,6 +66,8 @@ class RenderContext:

__slots__ = (
"clone_contexts",
"time",
"_physics_dt",
"_backend_registry",
"_physics_initialized",
"_prepared_renderer_ids",
Expand All @@ -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()
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion source/isaaclab/isaaclab/sim/simulation_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
14 changes: 14 additions & 0 deletions source/isaaclab/test/renderers/test_simulation_render_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand All @@ -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),
]
Expand Down
2 changes: 2 additions & 0 deletions source/isaaclab_ov/changelog.d/huidongc-lidar-scan.added.rst
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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.
Empty file.
Original file line number Diff line number Diff line change
@@ -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.
28 changes: 25 additions & 3 deletions source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_cfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``.
Expand Down Expand Up @@ -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``."""
Expand All @@ -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.
Expand Down Expand Up @@ -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.")

Expand Down
30 changes: 17 additions & 13 deletions source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_lidar_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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:
Expand All @@ -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."""
Expand All @@ -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):
Expand All @@ -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)

Expand Down
Loading
Loading