From 94d2ab07f787e5448d371c8e81dcecd476bef7e1 Mon Sep 17 00:00:00 2001 From: mtrepte Date: Thu, 5 Nov 2026 22:58:29 +0000 Subject: [PATCH 1/9] Select prims by clicking in the Isaac Sim viewer's viewport Answer the host's viewport picks with Isaac Lab's OVRTX renderer and outline the host's selection, so clicking a prim selects it in the viewport, stage tree and property pane. --- .../isaac_sim/isaac_sim_host_adapter.py | 57 +++++++++++++ .../isaac_sim/isaac_sim_shared_stage.py | 85 ++++++++++++++++++- .../isaac_sim/isaac_sim_shared_world.py | 4 + 3 files changed, 143 insertions(+), 3 deletions(-) diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_adapter.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_adapter.py index cf5d4b28c0b9..7d51ce41f361 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_adapter.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_adapter.py @@ -256,6 +256,63 @@ def _capture_selection(self, view: Any, demand: Any) -> dict[str, Any]: return LiveInspection +class ViewportPicker: + """Answers the host's viewport picks with Isaac Lab's OVRTX renderer. + + The host's own picker sends requests through Isaac Sim's scheduled renderer; here the next render Isaac Lab starts + answers them. + + Args: + renderer: Isaac Lab's viewer renderer (``ViewerRenderer``). + data: The world's data handle, for the answering simulation time. + """ + + capabilities = { + "point": True, + "region": True, + "multiple_hits": True, + "exact_capture": False, + "native_events": False, + } + + def __init__(self, renderer: Any, data: HostData): + import itertools + + self._renderer = renderer + self._data = data + self._ids = itertools.count(1) + + def pick(self, host: Any, product: str, body: dict[str, Any]) -> dict[str, Any]: + """Return the prims under a normalized rectangle of ``product``'s next frame.""" + from isaacsim.application.host.impl import picking + from isaacsim.application.host.impl.renderer_picking import maximum_hits, validate_generation + + if body.get("capture") is not None: + raise NotImplementedError("Picks answer the next frame; earlier frames are not retained") + validate_generation(host, body) + rect = picking.normalized_rect(body) + maximum = maximum_hits(body) + request_id = next(self._ids) + paths = self._renderer.request_pick(product, rect).result(timeout=5.0) + return picking.pick_payload(request_id, paths, maximum_hits=maximum, sim_time_ns=self._data.time_ns) + + +class SelectionOutline: + """Outlines the host's selection in Isaac Lab's OVRTX renderer. + + Args: + renderer: Isaac Lab's viewer renderer (``ViewerRenderer``). + """ + + supports_selection_outline = True + + def __init__(self, renderer: Any): + self._renderer = renderer + + def set_selection_outline(self, paths: list[str]) -> None: + self._renderer.set_selection_outline(paths) + + class BorrowedContext: """Stage context whose stage outlives the host's world: ``close()`` leaves it open. diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_stage.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_stage.py index 2ca533c67f21..1101125cf06e 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_stage.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_stage.py @@ -18,6 +18,7 @@ import threading import time from collections.abc import Sequence +from concurrent.futures import Future from pathlib import Path from types import SimpleNamespace from typing import Any, NamedTuple @@ -38,6 +39,9 @@ class Replication(NamedTuple): """Environment origins [m] with shape ``[len(env_paths), 3]``, or ``None`` to keep authored placement.""" +_PICK_HIT = "pick_hit" +"""Substring of OVRTX's pick-hit render variable name (``ovrtx_pick_hit``).""" + _MATRIX_ATTRIBUTES = frozenset({"omni:xform", "omni:fabric:worldMatrix", "omni:fabric:localMatrix", "worldMatrix"}) @@ -218,6 +222,12 @@ def __init__(self, stage: SharedStage, device: int = 0): self._lock = threading.Lock() self._products: dict[str, bool] = {} self._pending: tuple | None = None + self._picks: dict[str, tuple[tuple[float, float, float, float], Future]] = {} + """Pick rectangles requested by the host, answered by the next render of their product.""" + self._selection: list[str] | None = None + """Selection outline to apply before the next render, or ``None`` if unchanged.""" + self._outlined: list[str] = [] + self._styled = False self.timings = {"step": 0.0, "readback": 0.0, "renders": 0} """Accumulated wall time [s] of OVRTX submission and pixel readback on Isaac Lab's thread, for benchmarking.""" @@ -234,6 +244,46 @@ def set_product_enabled(self, product: str, enabled: bool) -> None: if product in self._products: self._products[product] = enabled + def request_pick(self, product: str, rect: tuple[float, float, float, float]) -> Future: + """Ask the next render of ``product`` which prims cover a rectangle; thread-safe. + + Args: + product: Render product the rectangle is in. + rect: ``(left, top, right, bottom)`` in ``[0, 1]`` with a top-left origin. + + Returns: + A future of the hit prim paths, nearest first. A newer request for the product supersedes it. + """ + future: Future = Future() + with self._lock: + previous = self._picks.get(product) + self._picks[product] = (rect, future) + if previous is not None: + previous[1].cancel() + return future + + def set_selection_outline(self, paths: Sequence[str]) -> None: + """Outline ``paths`` from the next render on; an empty selection clears the outline. Thread-safe.""" + with self._lock: + self._selection = list(paths) + + def _apply_selection(self) -> None: + with self._lock: + selection, self._selection = self._selection, None + if selection is None: + return + renderer = self._renderer + if not self._styled: + # Kit's selection colour: an orange outline and no fill. + style = self._ovrtx.SelectionGroupStyle(outline_color=(1.0, 0.6, 0.0, 1.0), fill_color=(0.0, 0.0, 0.0, 0.0)) + renderer.set_selection_group_styles({1: style}) + self._styled = True + if self._outlined: + renderer.set_selection_outline_group_strings(self._outlined, 0) + if selection: + renderer.set_selection_outline_group_strings(selection, 1) + self._outlined = selection + def poll(self, frames: FrameStore) -> tuple[int, bool]: """Publish the in-flight render if it finished, without waiting. @@ -252,10 +302,14 @@ def render(self, ordinal: int, time_ns: int) -> None: raise RuntimeError("a render is already in flight") with self._lock: products = {product for product, enabled in self._products.items() if enabled} + picks = {product: self._picks.pop(product) for product in list(self._picks) if product in products} if products: start = time.perf_counter() + self._apply_selection() + for product, (rect, _) in picks.items(): + self._renderer.enqueue_pick_query(product, *rect) operation = self._renderer.step_async(render_products=products, delta_time=1.0 / 60.0, ordinal=ordinal) - self._pending = (operation, products, time_ns, ordinal) + self._pending = (operation, products, time_ns, ordinal, picks) self.timings["step"] += time.perf_counter() - start def _collect(self, frames: FrameStore, *, block: bool) -> int: @@ -264,7 +318,7 @@ def _collect(self, frames: FrameStore, *, block: bool) -> int: if self._pending is None: return 0 - operation, products, time_ns, ordinal = self._pending + operation, products, time_ns, ordinal, picks = self._pending pending = operation.wait(timeout_ns=None if block else 0) if pending is None: return 0 @@ -276,7 +330,10 @@ def _collect(self, frames: FrameStore, *, block: bool) -> int: output = result[product] if not output.frames: continue - var = next(iter(output.frames[0].render_vars.values())) + render_vars = output.frames[0].render_vars + if product in picks: + self._answer_pick(render_vars, picks[product][1]) + var = next(value for name, value in render_vars.items() if _PICK_HIT not in name) mapping = var.map(device=self._ovrtx.Device.CUDA, sync_stream=0) try: mapping.wait() @@ -289,6 +346,28 @@ def _collect(self, frames: FrameStore, *, block: bool) -> int: self.timings["renders"] += 1 return published + def _answer_pick(self, render_vars: Any, future: Future) -> None: + """Resolve a pick from the render's pick-hit output: prim paths, nearest first, without repeats.""" + if future.done(): + return + try: + hits = next((value for name, value in render_vars.items() if _PICK_HIT in name), None) + paths: list[str] = [] + if hits is not None: + mapping = hits.map(device=self._ovrtx.Device.CPU) + try: + ids = np.from_dlpack(mapping["primPath"]).reshape(-1).tolist() + finally: + mapping.unmap() + for path_id in ids: + if path_id: + path = self._renderer.resolve_prim_path_id(path_id) + if path not in paths: + paths.append(path) + future.set_result(paths) + except Exception as error: # noqa: BLE001 - a failed pick is reported to its caller, not to rendering + future.set_exception(error) + def close(self) -> None: """Finish the in-flight render, then detach from the stage.""" try: diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_world.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_world.py index 300395d4abcf..68324dd1bd9d 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_world.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_world.py @@ -29,7 +29,9 @@ CloneAuthoring, HostClock, HostData, + SelectionOutline, StageView, + ViewportPicker, live_inspection_type, ) from .isaac_sim_shared_stage import FrameStore, Replication, SharedStage, ViewerRenderer @@ -193,6 +195,8 @@ def __call__(self, scene: str, wake: Callable[[], None]) -> World: ) world.on_simulation_step = self._grant_step world.renderer_name = "ovrtx" + world.picker = ViewportPicker(self.renderer, data) + world.renderer_selection = SelectionOutline(self.renderer) world.authoring = CloneAuthoring(self.authoring, self._copies) world.authoring_revision = self.authoring.revision world.authoring_sync = AuthoringSync(self.authoring.stage) From 2519faf605c31b7396d1c982f3d5bda1152522e0 Mon Sep 17 00:00:00 2001 From: mtrepte Date: Thu, 5 Nov 2026 23:42:14 +0000 Subject: [PATCH 2/9] Render the Isaac Sim viewer with Isaac Lab's OVRTX scene cameras Declare the viewer's perspective cameras as scene cameras on a shared OVRTX renderer, as for newton_rtx, and let that renderer's scene stage come from the Isaac Sim host's stage context through a new OVRTXRendererCfg.stage_provider. The host's panes then read the stage Isaac Lab renders. Remove the viewer's separate stage, renderer, markers and scene export. --- .../isaac-sim-viewer-prototype.added.rst | 1 + source/isaaclab/isaaclab/app/sim_launcher.py | 2 +- .../ovstage-stage-provider.added.rst | 4 + .../isaaclab_ov/cloner/replicate.py | 9 +- .../renderers/ovrtx_renderer_cfg.py | 8 + source/isaaclab_ov/isaaclab_ov/stage.py | 43 +- .../isaac-sim-viewer-prototype.added.rst | 8 +- .../isaac_sim/isaac_sim_host_stage.py | 174 ++++++++ .../isaac_sim/isaac_sim_host_world.py | 237 +++++++++++ .../isaac_sim/isaac_sim_shared_markers.py | 143 ------- .../isaac_sim/isaac_sim_shared_stage.py | 378 ------------------ .../isaac_sim/isaac_sim_shared_world.py | 293 -------------- .../isaac_sim/isaac_sim_stage.py | 40 -- .../isaac_sim/isaac_sim_visualizer.py | 283 +++++++------ .../isaac_sim/isaac_sim_visualizer_cfg.py | 26 +- .../test/test_isaac_sim_visualizer.py | 106 ++--- 16 files changed, 684 insertions(+), 1071 deletions(-) create mode 100644 source/isaaclab_ov/changelog.d/ovstage-stage-provider.added.rst create mode 100644 source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_stage.py create mode 100644 source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py delete mode 100644 source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_markers.py delete mode 100644 source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_stage.py delete mode 100644 source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_world.py delete mode 100644 source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_stage.py diff --git a/source/isaaclab/changelog.d/isaac-sim-viewer-prototype.added.rst b/source/isaaclab/changelog.d/isaac-sim-viewer-prototype.added.rst index 44c5df114887..c4d05fbca46f 100644 --- a/source/isaaclab/changelog.d/isaac-sim-viewer-prototype.added.rst +++ b/source/isaaclab/changelog.d/isaac-sim-viewer-prototype.added.rst @@ -1 +1,2 @@ * Added the ``isaac_sim`` (``--viz isaac-sim``) visualizer type to the visualizer registry and ``--viz`` selection. + Launch preparation declares its perspective cameras as scene cameras, as for ``newton_rtx``. diff --git a/source/isaaclab/isaaclab/app/sim_launcher.py b/source/isaaclab/isaaclab/app/sim_launcher.py index bcba04a98340..2c7e7699d1e3 100644 --- a/source/isaaclab/isaaclab/app/sim_launcher.py +++ b/source/isaaclab/isaaclab/app/sim_launcher.py @@ -315,7 +315,7 @@ def validate_launch( # noqa: C901 # Declare RTX perspective cameras before scene construction; runtime viewers only borrow their output. scene_cfg = next((node for node in configs if isinstance(node, InteractiveSceneCfg)), None) for viewer_index, visualizer in enumerate(viewers): - if not isinstance(visualizer.backend, NewtonRTXBackendCfg) or scene_cfg is None: + if not isinstance(visualizer.backend, (NewtonRTXBackendCfg, IsaacSimBackendCfg)) or scene_cfg is None: continue sources = ( [visualizer.view.source] if visualizer.view is not None else list(visualizer.cameras or [ diff --git a/source/isaaclab_ov/changelog.d/ovstage-stage-provider.added.rst b/source/isaaclab_ov/changelog.d/ovstage-stage-provider.added.rst new file mode 100644 index 000000000000..cf7a3be1708e --- /dev/null +++ b/source/isaaclab_ov/changelog.d/ovstage-stage-provider.added.rst @@ -0,0 +1,4 @@ +* Added :attr:`~isaaclab_ov.renderers.OVRTXRendererCfg.stage_provider` and + :attr:`~isaaclab_ov.stage.OvstageBackendCfg.stage_provider`, which let an application create the OVStage that an + OVRTX renderer's scene is populated into, for example a viewer that also reads the stage through its own stage + context. Population starts after any ordinals the provided stage already holds. diff --git a/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py b/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py index f350bd6b2626..1517eb7a8e6f 100644 --- a/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py +++ b/source/isaaclab_ov/isaaclab_ov/cloner/replicate.py @@ -189,7 +189,8 @@ def prepare(sim: SimulationContext, routing: dict[type[cloner.ReplicateContext], if value not in {"0", "1"}: raise ValueError(f"Invalid ISAAC_LAB_OVRTX_USE_OVSTAGE: {value!r}. Expected 0 or 1.") share_ovstage = os.environ.get("ISAAC_LAB_SHARE_OVSTAGE") == "1" - use_ovstage = share_ovstage or value == "1" + provided = any(renderer.cfg.stage_provider is not None for renderer in renderers) + use_ovstage = share_ovstage or value == "1" or provided if share_ovstage and not with_ovphysx: raise ValueError("Shared OVStage cloning requires OVPhysX.") if share_ovstage and sim.backend_manager.backend is not None and sim.backend_manager.backend.owns_scene: @@ -225,7 +226,11 @@ def prepare(sim: SimulationContext, routing: dict[type[cloner.ReplicateContext], if use_ovstage: domains = ovstage.PopulationDomain.ALL if share_ovstage else ovstage.PopulationDomain.RENDERING scene = sim.get_or_create_backend( - OvstageBackendCfg(scene_key=None if share_ovstage else backend_cfg, population_domains=domains) + OvstageBackendCfg( + scene_key=None if share_ovstage else backend_cfg, + population_domains=domains, + stage_provider=renderer.cfg.stage_provider, + ) ) renderer.backend = sim.get_or_create_backend(backend_cfg) renderer.scene = scene if use_ovstage else renderer.backend diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py index a08c341a0178..c13aab8bc7d9 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_cfg.py @@ -65,6 +65,14 @@ class OVRTXRendererCfg(RendererCfg): cloning_contexts: tuple[type | str, ...] = ("isaaclab_ov.cloner:OvrtxReplicateContext",) """Request native OVRTX copies; clone preparation may select a shared OVStage instead.""" + stage_provider: str | None = None + """``module:callable`` that creates this renderer's OVStage scene; see + :attr:`~isaaclab_ov.stage.OvstageBackendCfg.stage_provider`. + + Setting it selects an OVStage scene for this renderer, so an application can supply a stage it also reads, such as + a viewer whose panes read the stage through their own stage context. ``None`` keeps the default scene selection. + """ + async_rendering: bool = False """Trade one capture of camera latency for pipelined rendering. Defaults to False (synchronous). diff --git a/source/isaaclab_ov/isaaclab_ov/stage.py b/source/isaaclab_ov/isaaclab_ov/stage.py index e9f9f67a0d57..65f74543393d 100644 --- a/source/isaaclab_ov/isaaclab_ov/stage.py +++ b/source/isaaclab_ov/isaaclab_ov/stage.py @@ -159,6 +159,15 @@ class OvstageBackendCfg(BackendCfg): """None selects the simulation scene; isolated consumers use their configuration or instance identity.""" population_domains: ovstage.PopulationDomain = ovstage.PopulationDomain.RENDERING """USD domains to populate. Physics consumers require PHYSICS or ALL.""" + stage_provider: str | None = None + """``module:callable`` that creates the stage instead of :func:`create_ovstage`, or ``None``. + + The callable takes the stage name and returns a context manager whose value has a ``stage`` attribute: the + :class:`ovstage.Stage` to populate. The value stays available as :attr:`OvstageBackend.stage_owner` until the + backend closes, so an application that created the stage (for example a viewer that registers it with its own + stage context) can find it. The stage may already hold sealed ordinals; population starts after them. If the value + has a ``prepare_population(usda) -> usda`` method, population uses the USD it returns. + """ class OvstageBackend: @@ -177,13 +186,16 @@ def __init__(self, cfg: OvstageBackendCfg): self.clone_positions: np.ndarray | None = None self.resources = contextlib.ExitStack() """Release borrowers before paths and stage, in reverse registration order.""" + self.stage_owner = None + """The value the configured :attr:`OvstageBackendCfg.stage_provider` created, or ``None``.""" self.reset() def populate(self, usda: str) -> None: """Import the exported prototypes and apply the clone context's prepared operations. - Population commits ordinal 1. Consumers may then author render products and poses - starting at ordinal 2, after every cloned camera path exists. + Population commits the first ordinal after those the stage was created with (ordinal 1 for a stage from + :func:`create_ovstage`). Consumers then author render products and poses at later ordinals, after every + cloned camera path exists. Args: usda: USD scene containing the routed prototypes and their materials. @@ -191,12 +203,16 @@ def populate(self, usda: str) -> None: if self.ordinal: return - # Ordinal 0 is the empty state; population and cloning form the first committed write. - ovstage.population.open_usd_from_string(self.stage, usda, ordinal=1, domains=self.cfg.population_domains) + prepare = getattr(self.stage_owner, "prepare_population", None) + if prepare is not None: + usda = prepare(usda) + # Population and cloning form the first committed write after the stage's initial state. + ordinal = self._initial_floor + 1 + ovstage.population.open_usd_from_string(self.stage, usda, ordinal=ordinal, domains=self.cfg.population_domains) ovstage_replicate( - self.stage, self.paths, self.clone_copies, self.clone_env_paths, self.clone_positions, ordinal=1 + self.stage, self.paths, self.clone_copies, self.clone_env_paths, self.clone_positions, ordinal=ordinal ) - self.ordinal = 1 + self.ordinal = ordinal self.commit() @contextlib.contextmanager @@ -226,14 +242,25 @@ def commit(self) -> int: def close(self) -> None: """Release borrowers, then the path dictionary and stage.""" self.resources.close() - self.stage = self.paths = None + self.stage = self.paths = self.stage_owner = None def reset(self) -> None: """Recreate the native stage after all consumers detach, retaining the prepared clone operations.""" self.close() self.ordinal = self.next_camera_id = 0 with contextlib.ExitStack() as resources: - self.stage = resources.enter_context(create_ovstage("isaaclab.scene")) + # A stage Isaac Lab creates starts empty; a provided one may already hold sealed ordinals. + self._initial_floor = 0 + if self.cfg.stage_provider is None: + self.stage = resources.enter_context(create_ovstage("isaaclab.scene")) + else: + from isaaclab.utils.string import string_to_callable + + self.stage_owner = resources.enter_context( + string_to_callable(self.cfg.stage_provider)("isaaclab.scene") + ) + self.stage = self.stage_owner.stage + self._initial_floor = self.stage.fetch_ordinal(self.stage.get_attribute_write_floor()) self.paths = resources.enter_context(ovstage.PathDictionary(self.stage)) self.resources = resources.pop_all() diff --git a/source/isaaclab_visualizers/changelog.d/isaac-sim-viewer-prototype.added.rst b/source/isaaclab_visualizers/changelog.d/isaac-sim-viewer-prototype.added.rst index a44cc131d547..695cc8d23e9e 100644 --- a/source/isaaclab_visualizers/changelog.d/isaac-sim-viewer-prototype.added.rst +++ b/source/isaaclab_visualizers/changelog.d/isaac-sim-viewer-prototype.added.rst @@ -1,6 +1,6 @@ * Added a prototype ``isaac_sim`` visualizer backend (``--viz isaac-sim``, :class:`~isaaclab_visualizers.isaac_sim.IsaacSimBackendCfg`) that shows an Isaac Lab simulation in the Isaac Sim 7 - viewer application, with its stage tree, property and content panes and transport controls. One OVStage is the data - layer for Isaac Lab and the viewer: Isaac Lab populates it through its clone plan, writes body poses and - visualization markers at ordinals it owns, and renders the viewer with OVRTX. The application host runs no - scheduler; Isaac Lab drives every update. + viewer application, with its stage tree, property and content panes and transport controls. The viewer shows Isaac + Lab's own OVRTX scene: its cameras are scene cameras on a shared OVRTX renderer whose scene stage the application + host creates, so the host's panes read the stage Isaac Lab renders. The host runs no scheduler; Isaac Lab drives + every update. diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_stage.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_stage.py new file mode 100644 index 000000000000..227ca25dfbad --- /dev/null +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_stage.py @@ -0,0 +1,174 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Isaac Lab's scene stage, created through the Isaac Sim 7 host's stage context. + +The host's stage tree and property panes read a stage through an ``isaacsim.context.usd.UsdContext``, which can only +read a stage it created itself. :func:`host_stage` is the :attr:`~isaaclab_ov.renderers.OVRTXRendererCfg.stage_provider` +the viewer selects: the context creates an empty OVStage, and Isaac Lab borrows it, populates it and owns its ordinals +as it does any scene stage. +""" + +from __future__ import annotations + +import contextlib +import itertools +import logging +import threading +from collections.abc import Callable, Iterator, Sequence +from types import SimpleNamespace +from typing import Any, NamedTuple + +import numpy as np + +logger = logging.getLogger(__name__) + +_MATRIX_ATTRIBUTES = frozenset({"omni:xform", "omni:fabric:worldMatrix", "omni:fabric:localMatrix", "worldMatrix"}) + + +class HostStage(NamedTuple): + """A stage the host's context created and Isaac Lab borrows.""" + + stage: Any + """Isaac Lab's borrowed view of the native stage (an ``ovstage.Stage``).""" + + context: Any + """The host's stage context that created it (an ``isaacsim.context.usd.UsdContext``).""" + + @staticmethod + def prepare_population(usda: str) -> str: + """Give typeless prims the ``Xform`` type before Isaac Lab populates the stage. + + Isaac Lab's spawners leave containers such as ``/World`` and ``/World/envs`` typeless, and the host's stage + context lists only typed prims as children, so its stage tree would not show them. + """ + from pxr import Sdf + + layer = Sdf.Layer.CreateAnonymous(".usda") + layer.ImportFromString(usda) + typeless = [] + + def visit(path: Sdf.Path) -> None: + spec = layer.GetPrimAtPath(path) + if spec is not None and spec.specifier == Sdf.SpecifierDef and not spec.typeName: + typeless.append(spec) + + layer.Traverse(Sdf.Path.absoluteRootPath, visit) + if not typeless: + return usda + for spec in typeless: + spec.typeName = "Xform" + return layer.ExportToString() + + +@contextlib.contextmanager +def host_stage(name: str) -> Iterator[HostStage]: + """Create an empty stage through the host's stage context for Isaac Lab to populate. + + Args: + name: Isaac Lab's name for the stage, for diagnostics. + + Yields: + The borrowed stage and its context, valid until the context manager exits. + """ + from isaaclab_ov.stage import create_ovstage + + from isaacsim.context.usd import Backend, make_usd_context + from isaacsim.usd.ovstage import borrow_stage + + # ovstage fixes its hierarchy model per process at the first stage; claim Isaac Lab's GPU-incremental model before + # the host's context creates its stage, so OVRTX reads world transforms on the device. + with create_ovstage(f"{name}.anchor"): + context = make_usd_context(Backend.OVSTAGE) + context.create_from_string('#usda 1.0\n(\n upAxis = "Z"\n metersPerUnit = 1\n)\n') + stage = borrow_stage(context.stage_pointer) + try: + yield HostStage(stage, context) + finally: + stage.destroy() + + +class SceneWriter: + """Writes the host's edits into Isaac Lab's scene stage at the ordinal Isaac Lab has open. + + Isaac Lab's renderer seals that ordinal when it next renders, so the edits become visible with Isaac Lab's own + writes. Writes of a viewer camera's local transform go to the camera sensor instead: Isaac Lab's renderer writes + its cameras' poses from their sensors, so the sensor is where the viewer's navigation has to land. + + Args: + scene: Isaac Lab's scene stage (an ``isaaclab_ov.stage.OvstageBackend``). + cameras: Viewer camera prim paths, each with a function that moves its sensor to a local transform. + """ + + def __init__(self, scene: Any, cameras: dict[str, Callable[[np.ndarray], None]]): + self._scene = scene + self._cameras = cameras + + def write(self, paths: Sequence[str], attribute: str, values: Any) -> None: + """Write one value per path at the open ordinal.""" + import ovstage + + paths = list(paths) + array = np.asarray(values) + if attribute == "omni:xform" and paths and all(path in self._cameras for path in paths): + for path, matrix in zip(paths, np.asarray(array, dtype=np.float64).reshape(len(paths), 4, 4)): + self._cameras[path](matrix) + return + kwargs = {} + if array.dtype.kind in "USO": + # Text values, such as ``visibility``, are stored as interned tokens. + array = np.asarray([self._scene.paths.intern_token(str(value)) for value in array.reshape(-1)], np.uint64) + kwargs["semantic"] = ovstage.AttributeSemantic.TOKEN_ID + elif attribute in _MATRIX_ATTRIBUTES: + array = np.ascontiguousarray(array, dtype=np.float64).reshape(len(paths), 16) + kwargs["semantic"] = ovstage.AttributeSemantic.MATRIX + elif array.ndim: + array = np.ascontiguousarray(array).reshape(len(paths), *array.shape[1:]) + with self._scene.query(paths) as query: + self._scene.stage.write_attribute( + query, attribute, ordinal=self._scene.ordinal, tensors=array, is_array=False, **kwargs + ).wait() + + def clone(self, source: str, targets: Sequence[str]) -> None: + """Clone a subtree at the open ordinal.""" + self._scene.stage.clone(source, list(targets), ordinal=self._scene.ordinal) + + def remove(self, paths: Sequence[str]) -> None: + """Delete prim subtrees at the open ordinal.""" + with self._scene.query(list(paths)) as query: + self._scene.stage.delete_attributes(query, [], ordinal=self._scene.ordinal).wait() + + +class FrameStore: + """Latest viewer frame per render product, in the shape the host's renderer outputs read.""" + + def __init__(self): + self._lock = threading.Lock() + self._frames: dict[str, Any] = {} + self._ids = itertools.count(1) + + def publish(self, product: str, pixels: np.ndarray, time_ns: int) -> None: + """Make an RGBA ``[H, W, 4]`` uint8 image the latest frame of ``product``.""" + frame = SimpleNamespace( + pixels=pixels, + memory="cpu", + frame_id=next(self._ids), + time_ns=time_ns, + source="isaaclab-ovrtx", + generation=0, + input_ordinal=0, + output_ordinal=0, + capture_id=None, + timeline="participant", + transforms=[], + camera=None, + depth=None, + ) + with self._lock: + self._frames[product] = frame + + def latest(self, product: str) -> Any: + with self._lock: + return self._frames.get(product) diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py new file mode 100644 index 000000000000..8e247ee78857 --- /dev/null +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py @@ -0,0 +1,237 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Isaac Sim 7 host worlds on Isaac Lab's scene stage. + +:class:`HostWorldOpener` is the ``open_world`` callable of the host. Every world it opens, including after the user +stops the scene, reads Isaac Lab's scene stage through the host's stage context and runs no scheduler. Isaac Lab drains +the host's queued commands (camera moves, edits, property inspection) into the stage at its open ordinal, and its +renderer seals them with its next render. The host's transport controls are recorded for Isaac Lab: Pause and Step +gate its loop, and Stop requests an environment reset. +""" + +from __future__ import annotations + +import logging +import threading +from collections.abc import Callable, Sequence +from concurrent.futures import Future +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from .isaac_sim_host_adapter import ( + BorrowedContext, + CloneAuthoring, + HostClock, + HostData, + StageView, + live_inspection_type, +) +from .isaac_sim_host_stage import FrameStore, SceneWriter + +if TYPE_CHECKING: + from isaacsim.application.host import ViewportSpec, World + from isaacsim.foundation.orchestration import RationalRate + +logger = logging.getLogger(__name__) + + +def _host_world_type() -> type: + from isaacsim.application.host import World + + class HostWorld(World): + """Host world whose queued work Isaac Lab drains on its own steps. + + The host loop steps a stopped world while it has pending work. Here only Isaac Lab drains it, so the loop must + not spin on it; it steps when Isaac Lab requests a redraw after rendering. A simulation step while paused (Step) + is recorded as a grant for Isaac Lab's loop instead of advancing a clock. + """ + + on_simulation_step: Callable[[], None] | None = None + + def has_pending(self) -> bool: + return False + + def set_running(self, running: bool) -> None: + self.running = running + + def step_simulation_frame(self) -> int: + # While playing, the host steps at its own rate; Isaac Lab runs freely then, so only a Step while paused + # is a grant. + if not self.running and self.on_simulation_step is not None: + self.on_simulation_step() + self.frames_stepped += 1 + return self.sim_time_ns + + return HostWorld + + +class HostWorldOpener: + """Open host worlds on Isaac Lab's scene stage. + + Args: + scene_file: Isaac Lab's authored scene, exported for the host's authoring session (attribute types and edits). + context: The host's stage context over Isaac Lab's scene stage (an ``isaacsim.context.usd.UsdContext``). + writer: Writes the host's edits at Isaac Lab's open ordinal. + specs: The viewer's viewports, one per Isaac Lab viewer camera. + frames: Latest frame of each viewport. + rate: Host frame rate. + up: Stage up axis as a vector. + meters_per_unit: Stage units [m]. + copies: Isaac Lab's environment clones as ``(source, targets)``, so the property pane describes clones. + """ + + def __init__( + self, + scene_file: Path, + context: Any, + writer: SceneWriter, + specs: Sequence[ViewportSpec], + frames: FrameStore, + rate: RationalRate, + up: tuple[float, float, float], + meters_per_unit: float, + copies: Sequence[tuple[str, Sequence[str]]], + ): + from isaacsim.viewports.authoring import AuthoringSession + + self.authoring = AuthoringSession(str(scene_file.resolve())) + self._context = context + self._writer = writer + self._specs = tuple(specs) + self.frames = frames + self._rate = rate + self._up = up + self._meters_per_unit = meters_per_unit + self._copies = copies + self._lock = threading.Lock() + self._world: World | None = None + self._data: HostData | None = None + self._activation = 0 + self._opened = 0 + self._step_grants = 0 + self._reset_requested = False + self._revision: int | None = None + self.enabled: set[str] = set() + """Products of the viewports a client currently shows.""" + + def drain(self, time_ns: int) -> bool: + """Apply the host's queued commands at Isaac Lab's open ordinal. + + Args: + time_ns: Isaac Lab's simulation time [ns]. + + Returns: + Whether a command changed the stage, so the viewports need a new frame. + """ + with self._lock: + world, data = self._world, self._data + if world is None or data is None: + return False + data.time_ns = time_ns + self._activation += 1 + view = StageView(data) + changed = False + for source in (world.commands, *world.command_sources): + try: + source._capture_activation(view, self._activation) + changed |= source.snapshot.applied > 0 + except Exception: # noqa: BLE001 - a viewer command must not stop Isaac Lab's simulation + logger.exception("An Isaac Sim viewer command failed; continuing.") + return changed + + def published(self) -> None: + """Resolve the drained commands' futures once Isaac Lab's renderer has sealed their writes.""" + with self._lock: + world = self._world + if world is not None: + for source in (world.commands, *world.command_sources): + source._published() + + def __call__(self, scene: str, wake: Callable[[], None]) -> World: + """Open a host world on Isaac Lab's scene stage.""" + from isaacsim.application.host import AuthoringSync, SceneCommands + from isaacsim.foundation.orchestration import RationalRate + from isaacsim.viewports.adapters import RendererOutput + + context = BorrowedContext(self._context) + data = HostData(context, self._writer) + commands = SceneCommands(rate=self._rate, on_submit=wake) + world = _host_world_type()( + context, + data, + commands, + self._rate, + scene, + clock=HostClock(data), + simulation_participants=[], + up=self._up, + meters_per_unit=self._meters_per_unit, + on_external_submit=wake, + ) + world.on_simulation_step = self._grant_step + world.renderer_name = "ovrtx" + world.authoring = CloneAuthoring(self.authoring, self._copies) + world.authoring_revision = self.authoring.revision + world.authoring_sync = AuthoringSync(self.authoring.stage) + # Property inspection supplies the selected prims' live world poses; Isaac Lab drains it with the commands. + inspection = SceneCommands(rate=RationalRate(10), on_submit=wake) + world.inspection = live_inspection_type()(inspection, set(), context) + world.command_sources.append(inspection) + frames = self.frames + world.renderer_output_factory = lambda path, product: RendererOutput(read=lambda: frames.latest(product)) + self._attach_viewports(world) + with self._lock: + self._world, self._data = world, data + self._opened += 1 + # The host reopens its world when the user stops the scene, and also to apply authored edits while playing. + # Only Stop resets Isaac Lab's environments; an edit changes the authoring revision. + revision = self.authoring.revision + self._reset_requested = self._opened > 1 and revision == self._revision + self._revision = revision + return world + + def _attach_viewports(self, world: World) -> None: + """Offer Isaac Lab's viewer cameras as the host's viewports; they are declared at launch, not created here.""" + products = {spec.product for spec in self._specs} + + def create_viewport(spec: ViewportSpec) -> Future: + done: Future = Future() + if spec.product in products: + done.set_result(None) + else: + done.set_exception(ValueError(f"Isaac Lab declares {len(products)} viewer camera(s) at launch")) + return done + + def set_enabled(product: str, enabled: bool) -> None: + (self.enabled.add if enabled else self.enabled.discard)(product) + + world.viewport_specs = self._specs + world.create_viewport = create_viewport + world.remove_viewport = lambda spec: set_enabled(spec.product, False) + world.set_render_product_enabled = set_enabled + + def _grant_step(self) -> None: + with self._lock: + self._step_grants += 1 + + def take_step(self) -> bool: + """Consume one step the user requested while paused; return whether one was pending.""" + with self._lock: + if self._step_grants: + self._step_grants -= 1 + return True + return False + + def clear_steps(self) -> None: + """Drop steps granted while the host was playing; they only matter while it is paused.""" + with self._lock: + self._step_grants = 0 + + def take_reset(self) -> bool: + """Consume a reset that the host's Stop requested; return whether one was pending.""" + with self._lock: + requested, self._reset_requested = self._reset_requested, False + return requested diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_markers.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_markers.py deleted file mode 100644 index f37a8bb032da..000000000000 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_markers.py +++ /dev/null @@ -1,143 +0,0 @@ -# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). -# All rights reserved. -# -# SPDX-License-Identifier: BSD-3-Clause - -"""Isaac Lab visualization markers as point instancers in the shared stage. - -Isaac Lab hands each marker group's state (translations, orientations, scales and prototype indices) to a -Newton-family marker backend, because the Isaac Sim 7 viewer does not pump Kit. Each group becomes a -``UsdGeom.PointInstancer`` that is added to the shared stage when the group first appears, with the group's own -spawner configurations as prototypes, as Isaac Lab's Kit marker backend builds them. Every frame then writes the -instancer's arrays at Isaac Lab's open ordinal. -""" - -from __future__ import annotations - -import itertools -from typing import TYPE_CHECKING, Any - -import numpy as np - -if TYPE_CHECKING: - from .isaac_sim_shared_stage import SharedStage - - -def _instancer_usd(markers_cfg: dict[str, Any], root: str) -> str: - """Author a point instancer whose prototypes are the marker spawners, and return it as USD text.""" - from pxr import Gf, Usd, UsdGeom, UsdPhysics, Vt - - import isaaclab.sim as sim_utils - - stage = Usd.Stage.CreateInMemory() - with sim_utils.use_stage(stage): - instancer = UsdGeom.PointInstancer.Define(stage, root) - stage.SetDefaultPrim(instancer.GetPrim()) - # OVRTX also draws a prototype where it is authored. Its parent's visibility does not reach the instances, - # so an invisible parent hides only that copy. - UsdGeom.Scope.Define(stage, f"{root}/Prototypes").MakeInvisible() - for name, cfg in markers_cfg.items(): - prim = cfg.func(prim_path=f"{root}/Prototypes/{name}", cfg=cfg) - material = getattr(cfg, "visual_material", None) - material_path = getattr(cfg, "visual_material_path", None) - if material is not None and material_path is not None: - # File spawners apply a separate material only with Kit; the material itself is plain UsdShade. - if not material_path.startswith("/"): - material_path = f"{prim.GetPath()}/{material_path}" - material.func(material_path, material) - sim_utils.bind_visual_material(str(prim.GetPath()), material_path, stage=stage) - # Prototypes are display-only: no physics, and no nested instancing under the point instancer. - for child in Usd.PrimRange(prim): - child.SetInstanceable(False) - for api in (UsdPhysics.ArticulationRootAPI, UsdPhysics.RigidBodyAPI, UsdPhysics.CollisionAPI): - if child.HasAPI(api): - child.RemoveAPI(api) - instancer.GetPrototypesRel().AddTarget(prim.GetPath()) - count = len(markers_cfg) - # Author every array so the stage knows their types before the first runtime write. - instancer.GetProtoIndicesAttr().Set(list(range(count))) - instancer.GetPositionsAttr().Set([Gf.Vec3f(0.0, 0.0, -1.0e6)] * count) - instancer.GetOrientationsAttr().Set(Vt.QuathArray([Gf.Quath(1.0, 0.0, 0.0, 0.0)] * count)) - instancer.GetScalesAttr().Set([Gf.Vec3f(1.0)] * count) - return stage.GetRootLayer().ExportToString() - - -class SharedMarkers: - """Point instancers in the shared stage that mirror Isaac Lab's visualization marker groups.""" - - def __init__(self): - self._roots: dict[str, str] = {} - self._pending: set[str] = set() - self._names = (f"/IsaacLabMarkers_{index}" for index in itertools.count()) - - def sync(self, stage: SharedStage, registry: Any) -> None: - """Add new marker groups and write every group's latest state at the stage's open ordinal. - - A group added at this ordinal receives its state from the next one, once its instancer is populated. - - Args: - stage: The shared stage. - registry: The simulation's visualization marker registry. - """ - import ovstage - - from isaaclab_visualizers.newton.newton_visualization_markers import NewtonVisualizationMarkers - - groups = { - group_id: group - for group_id, group in registry.get_groups().items() - if isinstance(group, NewtonVisualizationMarkers) - } - added = False - for group_id, group in groups.items(): - root = self._roots.get(group_id) - if root is None: - root = self._roots[group_id] = next(self._names) - ovstage.population.add_usd_reference_from_string( - stage.stage, _instancer_usd(group.cfg.markers, root), root - ) - self._pending.add(group_id) - added = True - elif group_id in self._pending: - self._pending.discard(group_id) - else: - self._write(stage, root, group) - if added: - ovstage.population.apply_usd_changes(stage.stage, ordinal=stage.open) - for group_id in set(self._roots) - set(groups): - # A removed group keeps its prims; an empty instancer draws nothing. - self._write(stage, self._roots.pop(group_id), None) - - def _write(self, stage: SharedStage, root: str, group: Any) -> None: - """Write one group's instancer arrays, or empty arrays when it is hidden or removed.""" - import ovstage - from isaaclab_ov.stage import OVSTAGE_POINT_DTYPE - - count = 0 if group is None or not group.is_visible() else int(group.count) - - def column(value: Any, width: int, fill: np.ndarray, dtype: type) -> np.ndarray: - if value is None or count == 0: - return np.broadcast_to(fill, (count, width) if width > 1 else (count,)).astype(dtype) - array = value.detach().cpu().numpy() if hasattr(value, "detach") else np.asarray(value) - return np.ascontiguousarray(array[:count], dtype=dtype) - - positions = column(group.translations if count else None, 3, np.zeros(3), np.float32) - orientations = column(group.orientations if count else None, 4, np.array([0.0, 0.0, 0.0, 1.0]), np.float16) - scales = column(group.scales if count else None, 3, np.ones(3), np.float32) - indices = column(group.marker_indices if count else None, 1, np.zeros(1), np.int32) - half4 = ovstage.DLDataType(code=ovstage.DLDataTypeCode.kDLFloat, bits=16, lanes=4) - float3 = OVSTAGE_POINT_DTYPE - import warp as wp - - for attribute, values, vector, dtype in ( - ("positions", positions, wp.vec3f, float3), - # USD point instancers store orientations as (x, y, z, w) half quaternions, as Isaac Lab passes them. - ("orientations", orientations, wp.vec4h, half4), - ("scales", scales, wp.vec3f, float3), - ("protoIndices", indices, None, None), - ): - tensor = values - if vector is not None: - # ovstage folds the vector components into the column's lanes, as for Isaac Lab's ``points`` writes. - tensor = ovstage.make_dltensor(wp.array(values, dtype=vector, device="cpu"), dtype=dtype) - stage.stage.write_attribute(stage._query([root]), attribute, stage.open, [tensor], is_array=True).wait() diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_stage.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_stage.py deleted file mode 100644 index 1101125cf06e..000000000000 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_stage.py +++ /dev/null @@ -1,378 +0,0 @@ -# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). -# All rights reserved. -# -# SPDX-License-Identifier: BSD-3-Clause - -"""One OVStage shared by Isaac Lab and the Isaac Sim 7 viewer, with Isaac Lab owning its ordinals. - -The Isaac Sim 7 host creates and registers the stage, so its stage tree and property panes read it through the -host's own stage context. Isaac Lab borrows the same native stage: it writes simulation state and the host's edits at -the ordinal it has open, seals that ordinal, renders the viewer's render products with OVRTX at it, and hands the -frames to the host. -""" - -from __future__ import annotations - -import ctypes -import itertools -import threading -import time -from collections.abc import Sequence -from concurrent.futures import Future -from pathlib import Path -from types import SimpleNamespace -from typing import Any, NamedTuple - -import numpy as np - - -class Replication(NamedTuple): - """Environment copies and placement that complete an exported scene in the stage.""" - - copies: Sequence[tuple[str, Sequence[str]]] - """Source subtrees and their destinations, parents before children.""" - - env_paths: Sequence[str] - """Environment roots, in placement order.""" - - positions: np.ndarray | None - """Environment origins [m] with shape ``[len(env_paths), 3]``, or ``None`` to keep authored placement.""" - - -_PICK_HIT = "pick_hit" -"""Substring of OVRTX's pick-hit render variable name (``ovrtx_pick_hit``).""" - -_MATRIX_ATTRIBUTES = frozenset({"omni:xform", "omni:fabric:worldMatrix", "omni:fabric:localMatrix", "worldMatrix"}) - - -class SharedStage: - """Isaac Lab's side of the shared stage: queries, writes at the open ordinal, and sealing. - - Args: - usd: USD text that the Isaac Sim 7 stage context populates the stage from. - replication: Environment copies and placement applied once populated. - """ - - def __init__(self, usd: str, replication: Replication | None = None): - import ovstage - from isaaclab_ov.stage import create_ovstage - - from isaacsim.context.usd import Backend, make_usd_context - from isaacsim.usd.ovstage import borrow_stage - - # ovstage fixes its hierarchy model per process at the first stage; claim Isaac Lab's GPU-incremental model - # before the host creates the shared stage, so OVRTX can read world transforms on the device. - self._anchor = create_ovstage("isaaclab.isaac_sim.anchor") - self.context = make_usd_context(Backend.OVSTAGE) - started = time.perf_counter() - self.context.create_from_string(usd) - self.startup = {"populate": time.perf_counter() - started} - """Wall time [s] of population and cloning, for benchmarking.""" - self.stage = borrow_stage(self.context.stage_pointer) - self._dictionary = ovstage.PathDictionary(self.stage) - self._queries: dict[tuple[str, ...], tuple[Any, Any]] = {} - self.sealed = self.stage.fetch_ordinal(self.stage.get_attribute_write_floor()) - """Latest sealed ordinal; population sealed the first.""" - self.open = self.sealed + 1 - """Ordinal that writes go to until :meth:`seal`.""" - if replication is not None: - from isaaclab_ov.stage import ovstage_replicate - - started = time.perf_counter() - ovstage_replicate( - self.stage, - self._dictionary, - replication.copies, - replication.env_paths, - replication.positions, - ordinal=self.open, - ) - self.seal() - self.startup["clone"] = time.perf_counter() - started - - def _query(self, paths: Sequence[str]) -> Any: - key = tuple(paths) - entry = self._queries.get(key) - if entry is None: - path_list = self._dictionary.create_path_list_from_strings(list(key)) - entry = self._queries[key] = (path_list, self.stage.query_from_path_list(path_list)) - return entry[1] - - def write(self, paths: Sequence[str], attribute: str, values: Any) -> None: - """Write one value per path at the open ordinal.""" - import ovstage - - array = np.asarray(values) - if array.dtype.kind in "USO": - # Text values, such as ``visibility``, are stored as interned tokens. - tokens = [self._dictionary.intern_token(str(value)) for value in array.reshape(-1)] - array = np.asarray(tokens, dtype=np.uint64) - kwargs = {"semantic": ovstage.AttributeSemantic.TOKEN_ID} - self.stage.write_attribute(self._query(paths), attribute, self.open, array, is_array=False, **kwargs).wait() - return - if attribute in _MATRIX_ATTRIBUTES: - array = np.ascontiguousarray(array, dtype=np.float64).reshape(len(paths), 16) - semantic = ovstage.AttributeSemantic.MATRIX - else: - array = np.ascontiguousarray(array).reshape(len(paths), *array.shape[1:]) if array.ndim else array - semantic = None - kwargs = {} if semantic is None else {"semantic": semantic} - self.stage.write_attribute(self._query(paths), attribute, self.open, array, is_array=False, **kwargs).wait() - - def write_device(self, paths: Sequence[str], attribute: str, tensor: Any, cuda_stream: int) -> None: - """Write a device-resident matrix tensor with one ``[16]`` row per path at the open ordinal.""" - import ovstage - - self.stage.write_attribute( - self._query(paths), - attribute, - self.open, - tensor, - is_array=False, - semantic=ovstage.AttributeSemantic.MATRIX, - cuda_stream=cuda_stream, - ).wait() - - def clone(self, source: str, targets: Sequence[str]) -> None: - """Clone a subtree at the open ordinal.""" - self.stage.clone(source, list(targets), self.open) - - def remove(self, paths: Sequence[str]) -> None: - """Delete prim subtrees at the open ordinal.""" - self.stage.delete_attributes(self._query(paths), [], self.open).wait() - - def seal(self) -> int: - """Seal the open ordinal so readers and renderers see it; return it.""" - self.stage.advance_write_floor(self.open).wait() - self.sealed = self.open - self.open += 1 - return self.sealed - - def close(self) -> None: - """Release the queries and the borrowed view, then the host's stage context.""" - try: - for path_list, query in self._queries.values(): - self.stage.release_query(query).wait() - self._dictionary.destroy_path_list(path_list) - self._queries.clear() - self.stage.destroy() - finally: - self.context = None - - -class FrameStore: - """Latest rendered frame per render product, in the shape the host's renderer outputs read.""" - - def __init__(self): - self._lock = threading.Lock() - self._frames: dict[str, Any] = {} - self._ids = itertools.count(1) - - def publish(self, product: str, pixels: np.ndarray, time_ns: int, ordinal: int) -> None: - frame = SimpleNamespace( - pixels=pixels, - memory="cpu", - frame_id=next(self._ids), - time_ns=time_ns, - source="isaaclab-ovrtx", - generation=0, - input_ordinal=ordinal, - output_ordinal=ordinal, - capture_id=None, - timeline="participant", - transforms=[], - camera=None, - depth=None, - ) - with self._lock: - self._frames[product] = frame - - def latest(self, product: str) -> Any: - with self._lock: - return self._frames.get(product) - - -class ViewerRenderer: - """OVRTX renderer for the viewer's render products, reading the shared stage at Isaac Lab's sealed ordinals. - - Args: - stage: The shared stage. - device: CUDA device ordinal to render on. - """ - - def __init__(self, stage: SharedStage, device: int = 0): - import ovrtx - import ovstage - - # OVRTX resolves this native dependency of ovstage through the process, as Isaac Lab's renderer does. - dependency = Path(ovstage.__file__).parent / "bin/plugins/libosdCPU.so.3.6.0" - if dependency.exists(): - ctypes.CDLL(str(dependency)) - self._ovrtx = ovrtx - self._renderer = ovrtx.Renderer( - ovrtx.RendererConfig( - active_cuda_gpus=str(device), - keep_system_alive=True, - read_gpu_transforms=True, - suppress_deprecation_warnings=True, - texture_streaming_mode=ovrtx.TextureStreamingMode.SYNCHRONOUS, - ) - ) - self._renderer.attach_ovstage(stage.stage) - self._lock = threading.Lock() - self._products: dict[str, bool] = {} - self._pending: tuple | None = None - self._picks: dict[str, tuple[tuple[float, float, float, float], Future]] = {} - """Pick rectangles requested by the host, answered by the next render of their product.""" - self._selection: list[str] | None = None - """Selection outline to apply before the next render, or ``None`` if unchanged.""" - self._outlined: list[str] = [] - self._styled = False - self.timings = {"step": 0.0, "readback": 0.0, "renders": 0} - """Accumulated wall time [s] of OVRTX submission and pixel readback on Isaac Lab's thread, for benchmarking.""" - - def add_product(self, product: str) -> None: - with self._lock: - self._products.setdefault(product, True) - - def remove_product(self, product: str) -> None: - with self._lock: - self._products.pop(product, None) - - def set_product_enabled(self, product: str, enabled: bool) -> None: - with self._lock: - if product in self._products: - self._products[product] = enabled - - def request_pick(self, product: str, rect: tuple[float, float, float, float]) -> Future: - """Ask the next render of ``product`` which prims cover a rectangle; thread-safe. - - Args: - product: Render product the rectangle is in. - rect: ``(left, top, right, bottom)`` in ``[0, 1]`` with a top-left origin. - - Returns: - A future of the hit prim paths, nearest first. A newer request for the product supersedes it. - """ - future: Future = Future() - with self._lock: - previous = self._picks.get(product) - self._picks[product] = (rect, future) - if previous is not None: - previous[1].cancel() - return future - - def set_selection_outline(self, paths: Sequence[str]) -> None: - """Outline ``paths`` from the next render on; an empty selection clears the outline. Thread-safe.""" - with self._lock: - self._selection = list(paths) - - def _apply_selection(self) -> None: - with self._lock: - selection, self._selection = self._selection, None - if selection is None: - return - renderer = self._renderer - if not self._styled: - # Kit's selection colour: an orange outline and no fill. - style = self._ovrtx.SelectionGroupStyle(outline_color=(1.0, 0.6, 0.0, 1.0), fill_color=(0.0, 0.0, 0.0, 0.0)) - renderer.set_selection_group_styles({1: style}) - self._styled = True - if self._outlined: - renderer.set_selection_outline_group_strings(self._outlined, 0) - if selection: - renderer.set_selection_outline_group_strings(selection, 1) - self._outlined = selection - - def poll(self, frames: FrameStore) -> tuple[int, bool]: - """Publish the in-flight render if it finished, without waiting. - - OVRTX synchronizes with the stage when a queued render starts and refuses unsealed changes then, so nothing - may be written to the stage while a render is in flight. - - Returns: - How many products were published, and whether a render is still in flight. - """ - published = self._collect(frames, block=False) - return published, self._pending is not None - - def render(self, ordinal: int, time_ns: int) -> None: - """Start rendering the enabled products at a sealed ordinal; :meth:`poll` publishes the frames.""" - if self._pending is not None: - raise RuntimeError("a render is already in flight") - with self._lock: - products = {product for product, enabled in self._products.items() if enabled} - picks = {product: self._picks.pop(product) for product in list(self._picks) if product in products} - if products: - start = time.perf_counter() - self._apply_selection() - for product, (rect, _) in picks.items(): - self._renderer.enqueue_pick_query(product, *rect) - operation = self._renderer.step_async(render_products=products, delta_time=1.0 / 60.0, ordinal=ordinal) - self._pending = (operation, products, time_ns, ordinal, picks) - self.timings["step"] += time.perf_counter() - start - - def _collect(self, frames: FrameStore, *, block: bool) -> int: - """Publish the in-flight render if it finished (or wait for it with ``block``); return products published.""" - import warp as wp - - if self._pending is None: - return 0 - operation, products, time_ns, ordinal, picks = self._pending - pending = operation.wait(timeout_ns=None if block else 0) - if pending is None: - return 0 - self._pending = None - start = time.perf_counter() - result = pending.fetch() - published = 0 - for product in products: - output = result[product] - if not output.frames: - continue - render_vars = output.frames[0].render_vars - if product in picks: - self._answer_pick(render_vars, picks[product][1]) - var = next(value for name, value in render_vars.items() if _PICK_HIT not in name) - mapping = var.map(device=self._ovrtx.Device.CUDA, sync_stream=0) - try: - mapping.wait() - pixels = wp.from_dlpack(mapping).numpy() - finally: - mapping.unmap(stream=1) - frames.publish(product, pixels, time_ns, ordinal) - published += 1 - self.timings["readback"] += time.perf_counter() - start - self.timings["renders"] += 1 - return published - - def _answer_pick(self, render_vars: Any, future: Future) -> None: - """Resolve a pick from the render's pick-hit output: prim paths, nearest first, without repeats.""" - if future.done(): - return - try: - hits = next((value for name, value in render_vars.items() if _PICK_HIT in name), None) - paths: list[str] = [] - if hits is not None: - mapping = hits.map(device=self._ovrtx.Device.CPU) - try: - ids = np.from_dlpack(mapping["primPath"]).reshape(-1).tolist() - finally: - mapping.unmap() - for path_id in ids: - if path_id: - path = self._renderer.resolve_prim_path_id(path_id) - if path not in paths: - paths.append(path) - future.set_result(paths) - except Exception as error: # noqa: BLE001 - a failed pick is reported to its caller, not to rendering - future.set_exception(error) - - def close(self) -> None: - """Finish the in-flight render, then detach from the stage.""" - try: - if self._pending is not None: - self._pending[0].wait() - self._pending = None - finally: - self._renderer.detach_ovstage() diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_world.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_world.py deleted file mode 100644 index 68324dd1bd9d..000000000000 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_shared_world.py +++ /dev/null @@ -1,293 +0,0 @@ -# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). -# All rights reserved. -# -# SPDX-License-Identifier: BSD-3-Clause - -"""Isaac Sim 7 host worlds on a stage that Isaac Lab owns. - -:class:`SharedWorldOpener` is the ``open_world`` callable of the host. Every world it opens, including after the user -stops the scene, uses the same shared stage and runs no scheduler. Isaac Lab calls :meth:`step` once per frame: it -writes simulation state, applies the host's queued commands (camera moves, viewport changes, property reads), seals the -ordinal and renders the viewer's products at it with OVRTX. The host's transport controls are recorded for Isaac Lab: -Pause and Step gate its loop, and Stop requests an environment reset. -""" - -from __future__ import annotations - -import logging -import threading -import time -from collections.abc import Callable, Sequence -from concurrent.futures import Future -from pathlib import Path -from typing import TYPE_CHECKING, Any - -import numpy as np - -from .isaac_sim_host_adapter import ( - BorrowedContext, - CloneAuthoring, - HostClock, - HostData, - SelectionOutline, - StageView, - ViewportPicker, - live_inspection_type, -) -from .isaac_sim_shared_stage import FrameStore, Replication, SharedStage, ViewerRenderer - -if TYPE_CHECKING: - from isaacsim.application.host import ViewportSpec, World - from isaacsim.foundation.orchestration import RationalRate - -logger = logging.getLogger(__name__) - - -def _shared_world_type() -> type: - from isaacsim.application.host import World - - class SharedWorld(World): - """Host world whose queued work Isaac Lab drains on its own steps. - - The host loop steps a stopped world while it has pending work. Here only Isaac Lab drains it, so the loop must - not spin on it; it steps when Isaac Lab requests a redraw after rendering. A simulation step (Play or Step) is - recorded as a grant for Isaac Lab's loop instead of advancing a clock. - """ - - on_simulation_step: Callable[[], None] | None = None - - def has_pending(self) -> bool: - return False - - def set_running(self, running: bool) -> None: - self.running = running - - def step_simulation_frame(self) -> int: - # While playing, the host steps at its own rate; Isaac Lab runs freely then, so only a Step while paused - # is a grant. - if not self.running and self.on_simulation_step is not None: - self.on_simulation_step() - self.frames_stepped += 1 - return self.sim_time_ns - - return SharedWorld - - -class SharedWorldOpener: - """Create the shared stage and open host worlds on it. - - Args: - scene: Exported scene file the stage is populated from; the host's authoring session edits it. - specs: Viewport slots, shared with the host. - rate: Host frame rate. - device: CUDA device ordinal for rendering. - replication: Environment copies and placement applied once the stage is populated. - """ - - def __init__( - self, - scene: Path, - specs: Sequence[ViewportSpec], - rate: RationalRate, - device: int = 0, - replication: Replication | None = None, - ): - from sim_viewer.scene import read_scene_metadata, root_layer - - from isaacsim.viewports.authoring import AuthoringSession - - self._specs = specs - self._rate = rate - self._copies = replication.copies if replication is not None else () - self.metadata = read_scene_metadata(scene) - started = time.perf_counter() - self.authoring = AuthoringSession(str(scene.resolve())) - self.startup = {"authoring": time.perf_counter() - started} - """Wall time [s] of each startup phase, for benchmarking.""" - layer = root_layer(scene, list(specs), self.metadata) - self.stage = SharedStage(self.authoring.compose(layer), replication) - self.startup.update(self.stage.startup) - started = time.perf_counter() - self.renderer = ViewerRenderer(self.stage, device) - self.startup["renderer"] = time.perf_counter() - started - self.frames = FrameStore() - self._lock = threading.Lock() - self._world: World | None = None - self._data: HostData | None = None - self._activation = 0 - self._opened = 0 - self._step_grants = 0 - self._reset_requested = False - self._revision: int | None = None - self.renders = 0 - self.timings = {"write": 0.0, "host": 0.0, "seal": 0.0, "render": 0.0, "steps": 0} - """Accumulated wall time [s] per phase of :meth:`step`, for benchmarking.""" - self.on_frame: Callable[[], None] | None = None - """Tells the host a new frame exists; its publishers only read frames after a host step.""" - - def step(self, time_ns: int, elapsed_ns: int, write_state: Callable[[SharedStage], None]) -> int | None: - """Publish a finished frame, then, if the renderer is idle, advance the stage by one sealed ordinal and render. - - Args: - time_ns: Isaac Lab's simulation time [ns]. - elapsed_ns: Time since the previous step [ns]. - write_state: Writes Isaac Lab's state at the open ordinal. - - Returns: - The sealed ordinal, or ``None`` while a render is in flight and nothing was written. - """ - clock = time.perf_counter - published, busy = self.renderer.poll(self.frames) - self.renders += published - if published and self.on_frame is not None: - self.on_frame() - if busy: - return None - with self._lock: - world, data = self._world, self._data - t0 = clock() - write_state(self.stage) - t1 = clock() - sources = [world.commands, *world.command_sources] if world is not None else [] - if data is not None: - data.time_ns = time_ns - self._activation += 1 - view = StageView(data) - for source in sources: - try: - source._capture_activation(view, self._activation) - except Exception: # noqa: BLE001 - a viewer command must not stop Isaac Lab's simulation - logger.exception("An Isaac Sim viewer command failed; continuing.") - t2 = clock() - ordinal = self.stage.seal() - t3 = clock() - for source in sources: - # Resolves the commands' futures now that their writes are sealed. - source._published() - self.renderer.render(ordinal, time_ns) - t4 = clock() - for key, value in (("write", t1 - t0), ("host", t2 - t1), ("seal", t3 - t2), ("render", t4 - t3)): - self.timings[key] += value - self.timings["steps"] += 1 - return ordinal - - def __call__(self, scene: str, wake: Callable[[], None]) -> World: - """Open a host world on the shared stage.""" - from isaacsim.application.host import AuthoringSync, SceneCommands - from isaacsim.foundation.orchestration import RationalRate - from isaacsim.viewports.adapters import RendererOutput - - world_type = _shared_world_type() - context = BorrowedContext(self.stage.context) - data = HostData(context, self.stage) - commands = SceneCommands(rate=self._rate, on_submit=wake) - world = world_type( - context, - data, - commands, - self._rate, - scene, - clock=HostClock(data), - simulation_participants=[], - up=self.metadata.up_vector, - meters_per_unit=self.metadata.meters_per_unit, - on_external_submit=wake, - ) - world.on_simulation_step = self._grant_step - world.renderer_name = "ovrtx" - world.picker = ViewportPicker(self.renderer, data) - world.renderer_selection = SelectionOutline(self.renderer) - world.authoring = CloneAuthoring(self.authoring, self._copies) - world.authoring_revision = self.authoring.revision - world.authoring_sync = AuthoringSync(self.authoring.stage) - # Property inspection supplies the selected prims' live world poses; Isaac Lab drains it with the commands. - inspection = SceneCommands(rate=RationalRate(10), on_submit=wake) - world.inspection = live_inspection_type()(inspection, set(), context) - world.command_sources.append(inspection) - frames = self.frames - world.renderer_output_factory = lambda path, product: RendererOutput(read=lambda: frames.latest(product)) - self._attach_viewports(world) - with self._lock: - self._world, self._data = world, data - self._opened += 1 - # The host reopens its world when the user stops the scene, and also to apply authored edits while playing. - # Only Stop resets Isaac Lab's environments; an edit changes the authoring revision. - revision = self.authoring.revision - self._reset_requested = self._opened > 1 and revision == self._revision - self._revision = revision - return world - - def _grant_step(self) -> None: - with self._lock: - self._step_grants += 1 - - def take_step(self) -> bool: - """Consume one step the user requested while paused; return whether one was pending.""" - with self._lock: - if self._step_grants: - self._step_grants -= 1 - return True - return False - - def clear_steps(self) -> None: - """Drop steps granted while the host was playing; they only matter while it is paused.""" - with self._lock: - self._step_grants = 0 - - def take_reset(self) -> bool: - """Consume a reset that the host's Stop requested; return whether one was pending.""" - with self._lock: - requested, self._reset_requested = self._reset_requested, False - return requested - - def _attach_viewports(self, world: World) -> None: - """Create client viewports by cloning the template subtree at Isaac Lab's open ordinal.""" - from sim_viewer.scene import CAMERA_SCOPE - - renderer = self.renderer - lock = threading.RLock() - ready: set[str] = set() - for spec in self._specs: - renderer.add_product(spec.product) - ready.add(spec.product) - - def create_viewport(spec: ViewportSpec) -> Future: - root = spec.camera.rsplit("/", 1)[0] - with lock: - if spec.product in ready: - done: Future = Future() - done.set_result(None) - return done - world.close_renderer_outputs(spec.product) - cloned = world.commands.submit( - root, "viewport_topology", lambda view: view.clone_prim(f"{CAMERA_SCOPE}/Template", [root]) - ) - - def register(view: Any) -> None: - cloned.result() - view.write([spec.product], "resolution", np.asarray([spec.resolution], dtype=np.int32)) - with lock: - renderer.add_product(spec.product) - ready.add(spec.product) - - return world.commands.submit(root + "/ready", "viewport_topology", register) - - def remove_viewport(spec: ViewportSpec) -> None: - root = spec.camera.rsplit("/", 1)[0] - with lock: - ready.discard(spec.product) - renderer.remove_product(spec.product) - world.commands.submit(root, "viewport_topology", lambda view: view.remove_prim(root)) - world.close_renderer_outputs(spec.product) - - world.viewport_specs = tuple(self._specs) - world.create_viewport = create_viewport - world.remove_viewport = remove_viewport - world.set_render_product_enabled = renderer.set_product_enabled - - def close(self) -> None: - """Release the renderer, then the stage.""" - try: - self.renderer.close() - finally: - self.stage.close() diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_stage.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_stage.py deleted file mode 100644 index 7bbffa546730..000000000000 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_stage.py +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). -# All rights reserved. -# -# SPDX-License-Identifier: BSD-3-Clause - -"""Helpers that relate Isaac Lab's simulated bodies to the prims shown by the Isaac Sim 7 viewer.""" - -from __future__ import annotations - -import math - -import warp as wp - -from pxr import Gf, Usd, UsdGeom - - -def authored_scales(stage: Usd.Stage, paths: list[str]) -> wp.array | None: - """Return per-body authored scales, or ``None`` when every body is unit scale. - - Simulation poses omit scale, and the viewer renders each body with an ``omni:resetXformStack`` local matrix, - so the authored scale has to be folded back into the published pose. - - Args: - stage: Authored Isaac Lab stage. - paths: Body prim paths, in publication order. - - Returns: - Scales [-] with shape ``[len(paths)]`` of ``vec3f``, or ``None`` for unit scale. - """ - cache = UsdGeom.XformCache() - scales = [] - for path in paths: - prim = stage.GetPrimAtPath(path) - if prim and prim.IsA(UsdGeom.Xformable): - scales.append(tuple(map(float, Gf.Transform(cache.GetLocalToWorldTransform(prim)).GetScale()))) - else: - scales.append((1.0, 1.0, 1.0)) - if all(math.isclose(axis, 1.0, rel_tol=1e-6, abs_tol=1e-6) for scale in scales for axis in scale): - return None - return wp.array(scales, dtype=wp.vec3f) diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py index a2c2457a3f23..c4c428d12cb7 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py @@ -13,39 +13,38 @@ import tempfile import time from pathlib import Path -from types import SimpleNamespace from typing import TYPE_CHECKING import numpy as np -import warp as wp +import torch -from pxr import Sdf, Usd +from pxr import UsdGeom -from isaaclab.scene_data import SceneDataFormat from isaaclab.sim import SimulationContext +from isaaclab.utils.math import quat_from_matrix from isaaclab.visualizers.base_visualizer import BaseVisualizer from isaaclab.visualizers.visualizer_cfg import PerspectiveCameraCfg, VisualizerCfg -from .isaac_sim_shared_stage import Replication -from .isaac_sim_stage import authored_scales from .isaac_sim_visualizer_cfg import IsaacSimBackendCfg if TYPE_CHECKING: from isaaclab.sensors.camera import Camera + from isaaclab.visualizers.image_view import ImageView logger = logging.getLogger(__name__) -_ENVS_ROOT = "/World/envs" -"""Parent of Isaac Lab's cloned environments.""" +_VIEWER_CAMERA_PREFIX = "/World/viewer_camera_" +"""Prim path prefix of the perspective cameras launch preparation declares for viewers.""" class IsaacSimVisualizer(BaseVisualizer): - """Isaac Sim 7 viewer application on an OVStage shared with Isaac Lab. + """Isaac Sim 7 viewer application on Isaac Lab's own OVRTX scene. - The host's stage context creates and registers one OVStage; Isaac Lab borrows it and owns its ordinals. Each - rendered frame, Isaac Lab writes body poses and visualization markers, applies the host's commands, seals the - ordinal and renders the viewer's products with OVRTX. The host reads the same stage for its stage tree and property - panes and streams the frames to its client. Isaac Lab keeps its own loop and physics. + Launch preparation declares the viewer's perspective cameras as ordinary scene cameras on + :attr:`IsaacSimBackendCfg.renderer_cfg`. That renderer's scene stage is created by the host's stage context, so the + host's stage tree and property panes read the stage Isaac Lab renders. Each frame, Isaac Lab applies the host's + queued commands at its open ordinal, renders the viewer cameras, and hands their images to the host, which streams + them to its client. Isaac Lab keeps its own loop and physics; the host runs no scheduler. """ def __init__(self, cfg: VisualizerCfg): @@ -61,15 +60,15 @@ def __init__(self, cfg: VisualizerCfg): self._resources = contextlib.ExitStack() self._host = None self._desktop = None - self._provider = None - self._shared = None - self._markers = None - self._paths: list[str] = [] - self._scales = None - self._pose_output = SceneDataFormat.TransposedMatrix44d() - self._armed = False + self._opener = None + self._viewports: dict[str, ImageView] = {} + """Viewer camera image view per host render product.""" + self._shown: set[str] = set() + """Products whose current frame the host has; a viewport that becomes visible gets one first.""" + self._marker_revision = -1 self._next_render = 0.0 self._running = False + self.renders = 0 self.timings = {"publish": 0.0, "steps": 0} """Accumulated wall time [s] of the viewer's work in :meth:`step`, for benchmarking.""" @@ -79,7 +78,7 @@ def client_url(self) -> str: return f"{self._host.url}/index.html?entry=index.js&token={self._host.token}" def initialize(self, sim: SimulationContext, *, cameras: list[PerspectiveCameraCfg | Camera]) -> None: - """Populate the shared stage, start the Isaac Sim 7 host and open its client. + """Start the Isaac Sim 7 host on Isaac Lab's scene stage and open its client. Args: sim: Simulation owner that provides the authored stage and scene data. @@ -94,70 +93,104 @@ def initialize(self, sim: SimulationContext, *, cameras: list[PerspectiveCameraC " ui='desktop'." ) super().initialize(sim, cameras=cameras) - - from .isaac_sim_shared_markers import SharedMarkers - - self._provider = sim.get_scene_data_provider() - self._paths = list(self._provider.backend.transform_paths) - self._scales = authored_scales(sim.stage, self._paths) - started = time.perf_counter() - scene, replication = self._export_prototypes(sim) - self.timings["export"] = time.perf_counter() - started - self._markers = SharedMarkers() - device = str(sim.device) - device_index = int(device.split(":")[1]) if ":" in device else 0 - self._start_host(scene, replication, device_index) + views = [ + view + for view in self._image_views + if view.camera is not None and view.camera.cfg.prim_path.startswith(_VIEWER_CAMERA_PREFIX) + ] + if not views: + raise ValueError( + "The Isaac Sim viewer shows the perspective cameras that launch preparation declares; pass the" + " environment config to launch_simulation so they are declared before scene construction." + ) + self._viewports = {f"/IsaacLabViewer/Viewport_{index}": view for index, view in enumerate(views)} + renderer = sim.get_or_create_backend(self.backend_cfg.renderer_cfg) + if self.cfg.enable_markers: + renderer.marker_groups = sim.vis_marker_registry.get_groups().values() + self._start_host(sim, renderer) self._log_initialization_table( logger=logger, title="IsaacSimVisualizer Configuration", rows=[ ("ui", "headless" if self.cfg.headless else self.backend_cfg.ui), - ("bodies", len(self._paths)), + ("viewports", len(self._viewports)), ("fps", self.cfg.window.fps), ], ) self._running = True self._is_initialized = True - def _start_host(self, scene: Path, replication: Replication | None, device: int) -> None: - """Run the Isaac Sim 7 application host, with its panes and transport controls, on the shared stage.""" + def _start_host(self, sim: SimulationContext, renderer) -> None: + """Run the Isaac Sim 7 application host, with its panes and transport controls, on Isaac Lab's scene stage.""" from sim_viewer.cli import client_roots_for_backend - from sim_viewer.scene import CAMERA_SCOPE, RENDER_SCOPE, dynamic_viewport_spec, read_scene_metadata - from isaacsim.application.host import AppHost + from isaacsim.application.host import AppHost, ViewportSpec from isaacsim.foundation.orchestration import RationalRate from isaacsim.viewports.presentation import FrameEncoder - from .isaac_sim_shared_world import SharedWorldOpener + from .isaac_sim_host_stage import FrameStore, HostStage, SceneWriter + from .isaac_sim_host_world import HostWorldOpener - started = time.perf_counter() - metadata = read_scene_metadata(scene) - specs: list = [] - rate = RationalRate(int(self.cfg.window.fps)) - self._shared = SharedWorldOpener(scene, specs, rate, device=device, replication=replication) - self._resources.callback(self._shared.close) - self.timings["shared_stage"] = time.perf_counter() - started + scene = renderer.scene + if not isinstance(getattr(scene, "stage_owner", None), HostStage): + raise RuntimeError("The viewer's renderer has no scene stage from the host; check its stage_provider.") + directory = Path(self._resources.enter_context(tempfile.TemporaryDirectory(prefix="isaaclab_isaac_sim_"))) + scene_file = directory / "scene.usda" + # The host's authoring session reads attribute types and authors edits from Isaac Lab's authored layer. + sim.stage.GetRootLayer().Export(str(scene_file)) + up = (0.0, 1.0, 0.0) if UsdGeom.GetStageUpAxis(sim.stage) == UsdGeom.Tokens.y else (0.0, 0.0, 1.0) + width, height = self.cfg.window.size + specs = [ + ViewportSpec(index=index, product=product, camera=view.camera.cfg.prim_path, resolution=(width, height)) + for index, (product, view) in enumerate(self._viewports.items()) + ] + cameras = { + view.camera.cfg.prim_path: (lambda matrix, view=view: self._move_camera(view, matrix)) + for view in self._viewports.values() + } + self._opener = HostWorldOpener( + scene_file, + scene.stage_owner.context, + SceneWriter(scene, cameras), + specs, + FrameStore(), + RationalRate(int(self.cfg.window.fps)), + up, + UsdGeom.GetStageMetersPerUnit(sim.stage), + scene.clone_copies, + ) client_roots = client_roots_for_backend("web") if self.backend_cfg.app_client_root is not None: client_roots = [("/app/", Path(self.backend_cfg.app_client_root) / "renderer"), *client_roots[1:]] if self.backend_cfg.camera_controls == "newton": from .isaac_sim_camera_controls import newton_controls_client - directory = Path(self._resources.enter_context(tempfile.TemporaryDirectory(prefix="isaaclab_client_"))) + client = Path(self._resources.enter_context(tempfile.TemporaryDirectory(prefix="isaaclab_client_"))) client_roots = [ - (prefix, newton_controls_client(root, directory) or root) if prefix == "/" else (prefix, root) + (prefix, newton_controls_client(root, client) or root) if prefix == "/" else (prefix, root) for prefix, root in client_roots ] + + def viewport(index: int) -> ViewportSpec: + if index >= len(specs): + raise ValueError(f"Isaac Lab declares {len(specs)} viewer camera(s) at launch") + return specs[index] + + from isaacsim.common.interfaces import Query + + # Hide the stage's bookkeeping and the renderer's products from the stage tree; the scene is under /World. + roots = scene.stage_owner.context.read(Query("/"), "usd-children")[0] + hidden = tuple(root for root in roots if root not in ("/World", "/physicsScene")) self._host = AppHost( - open_world=self._shared, - scene=str(scene), - viewports=specs, - viewport_factory=lambda index: dynamic_viewport_spec(index, tuple(self.cfg.window.size)), + open_world=self._opener, + hidden_roots=hidden, + scene=str(scene_file), + viewports=[], + viewport_factory=viewport, encoder=FrameEncoder.create("auto"), presentation=self.backend_cfg.presentation, renderer_name="ovrtx", - hidden_roots=(CAMERA_SCOPE, RENDER_SCOPE), - world_up=metadata.up_vector, + world_up=up, host="127.0.0.1", port=self.backend_cfg.port, client_roots=client_roots, @@ -165,8 +198,6 @@ def _start_host(self, scene: Path, replication: Replication | None, device: int) stage_writes=True, ) self._resources.callback(self._host.stop) - # The host steps, and so publishes frames, only on request; each rendered frame requests one. - self._shared.on_frame = self._host.simulation.request_redraw self._host.start() # Isaac Lab is already running, so the viewer's transport controls start in Playing. self._play() @@ -185,93 +216,52 @@ def _open_desktop(self) -> None: ) self._resources.callback(self._desktop.close) - def _export_prototypes(self, sim: SimulationContext) -> tuple[Path, Replication | None]: - """Export each asset once; the environments are cloned and placed in the stage. + def _move_camera(self, view: ImageView, local: np.ndarray) -> None: + """Move a viewer camera sensor to the local transform the host's navigation wrote. - This is Isaac Lab's OVStage population path. With a clone plan, the copies follow it, so environments may hold - different assets. Without one, every environment receives a copy of the first environment's children, and a - scene without cloned environments is exported whole. - - Returns: - The exported scene and the replication that completes it, or ``None`` when the scene is exported whole. - """ - from isaaclab_ov.stage import export_stage_to_string - - stage = sim.stage - plan = sim.get_clone_plan() - if plan is not None and len(plan.topology.world_prototype_layout) > 1: - from isaaclab_ov.cloner.replicate import _prepare_scene_copies - - prepared = SimpleNamespace() - _prepare_scene_copies(plan, tuple(range(plan.topology.num_asset_prototypes)), [prepared]) - replication = Replication(prepared.clone_copies, prepared.clone_env_paths, prepared.clone_positions) - usd = export_stage_to_string( - stage, - prepared.clone_env_paths, - source_paths=tuple(source for source, _ in prepared.clone_copies), - keep_env_roots=False, - env_paths=prepared.population_env_paths, - preserve_references=True, - ) - else: - envs = stage.GetPrimAtPath(_ENVS_ROOT) - env_paths = [child.GetPath().pathString for child in envs.GetChildren()] if envs else [] - if len(env_paths) > 1: - source = env_paths[0] - children = [child.GetName() for child in stage.GetPrimAtPath(source).GetChildren()] - copies = [(f"{source}/{name}", [f"{env}/{name}" for env in env_paths[1:]]) for name in children] - # Environment roots keep their authored transforms, so the copies land in place. - replication = Replication(copies, env_paths, None) - sources = tuple(source for source, _ in copies) - else: - replication, sources = None, () - usd = export_stage_to_string(stage, env_paths, sources, keep_env_roots=True, preserve_references=True) - layer = Sdf.Layer.CreateAnonymous(".usda") - layer.ImportFromString(usd) - exported = Usd.Stage.Open(layer) - for prim in exported.Traverse(): - # The viewer's stage tree omits typeless containers, which Isaac Lab authors. - if not prim.GetTypeName(): - prim.SetTypeName("Xform") - directory = Path(self._resources.enter_context(tempfile.TemporaryDirectory(prefix="isaaclab_isaac_sim_"))) - scene = directory / "scene.usdc" - exported.Export(str(scene)) - return scene, replication - - def _render_frame(self, dt: float) -> None: - """Write the latest poses into the shared stage, seal it and render, at most ``window.fps`` times a second. - - Poses only matter when a frame renders, so steps between frames write nothing. + Args: + view: The camera's image view. + local: Row-major camera transform relative to the camera's parent, which is the identity-posed ``/World``. """ + camera = view.camera + position = torch.as_tensor(local[3, :3], dtype=torch.float32, device=camera.device).unsqueeze(0) + # USD matrices multiply row vectors, so the rotation's columns are the rows of the upper 3x3 block. + rotation = torch.as_tensor(local[:3, :3].T, dtype=torch.float32, device=camera.device) + camera.set_world_poses(position, quat_from_matrix(rotation).unsqueeze(0), convention="opengl") + view.invalidate() + + def _render_frame(self) -> None: + """Apply the host's commands and render the shown viewports, at most ``window.fps`` times a second.""" now = time.monotonic() if now < self._next_render: return self._next_render = now + 1.0 / self.cfg.window.fps - if not self._provider.get_transforms(self._pose_output, allow_passthrough=True, scales=self._scales): - return - from isaaclab_ov.stage import xform_tensor_from_warp - - matrices = self._pose_output.matrices - stream = wp.get_device(matrices.device).stream.cuda_stream or 1 - paths = self._paths - first = not self._armed - markers = self._markers if self.supports_markers() else None - registry = self._sim.vis_marker_registry if markers is not None else None - - def write_state(stage): - if markers is not None: - markers.sync(stage, registry) - if first: - # Bodies carry world matrices: their local transform is their world transform. - stage.write(paths, "omni:resetXformStack", np.ones(len(paths), dtype=np.bool_)) - # Armed only once written: the step skips writing while a render is in flight. - self._armed = True - # The stage's hierarchy derives world matrices from ``omni:xform`` when it seals, so poses go there. The - # matrices stay on the device; ovstage copies them in on the producing stream. - stage.write_device(paths, "omni:xform", xform_tensor_from_warp(matrices), stream) - - self._shared.step(int(self._sim_time * 1e9), int(dt * 1e9), write_state) - self.timings["renders"] = self._shared.renders + time_ns = int(self._sim_time * 1e9) + if self._opener.drain(time_ns): + for view in self._viewports.values(): + view.invalidate() + if self.cfg.enable_markers and self._marker_revision != self._sim.vis_marker_registry.revision: + self._marker_revision = self._sim.vis_marker_registry.revision + for view in self._viewports.values(): + view.invalidate() + frame_id = self._sim.get_physics_step_count() + published = False + self._shown &= self._opener.enabled + for product, view in self._viewports.items(): + if product not in self._opener.enabled: + continue + fresh = view.frame.timestamp != frame_id or product not in self._shown + image = view.read(frame_id) + if image is None or not fresh: + continue + self._shown.add(product) + self._opener.frames.publish(product, np.ascontiguousarray(image.numpy()), time_ns) + published = True + # A render seals the commands' writes; without one they stay at the open ordinal until the next. + if published: + self.renders += 1 + self._opener.published() + self._host.simulation.request_redraw() def _play(self) -> None: """Put the viewer's transport controls in Playing.""" @@ -281,19 +271,19 @@ def _play(self) -> None: def is_training_paused(self) -> bool: """Return whether the viewer's Pause holds Isaac Lab's loop; each Step lets one simulation step through.""" - if self._host is None or self._shared is None: + if self._host is None or self._opener is None: return False if self._host.simulation.run_state.value != "paused": - self._shared.clear_steps() + self._opener.clear_steps() return False - return not self._shared.take_step() + return not self._opener.take_step() def supports_markers(self) -> bool: """Return whether visualization markers are drawn.""" return self.cfg.enable_markers def step(self, dt: float) -> None: - """Update the shared stage and the viewer's frame. + """Apply the viewer's commands and stream its viewports. Args: dt: Simulation time-step in seconds. @@ -302,11 +292,11 @@ def step(self, dt: float) -> None: return self._sim_time += dt start = time.perf_counter() - if self._shared is not None and self._shared.take_reset(): + if self._opener.take_reset(): # The viewer's Stop resets the environments, which then keep running. self._reset_requested = True self._play() - self._render_frame(dt) + self._render_frame() if dt == 0.0: # Isaac Lab calls this in a loop while the viewer is paused; keep serving the viewer without spinning. time.sleep(0.002) @@ -320,12 +310,13 @@ def is_running(self) -> bool: return self._running def close(self) -> None: - """Stop the host, release the shared stage and remove the exported scene.""" + """Stop the host and remove the exported scene; the scene cameras keep their renderer.""" if self._is_closed: return try: self._resources.close() finally: self._running = False - self._host = self._desktop = self._provider = self._shared = None + self._host = self._desktop = self._opener = None + self._viewports.clear() super().close() diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer_cfg.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer_cfg.py index 7835866a98f7..89721e6c89d7 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer_cfg.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer_cfg.py @@ -7,7 +7,9 @@ from __future__ import annotations -from typing import TYPE_CHECKING, ClassVar, Literal +from typing import TYPE_CHECKING, Any, ClassVar, Literal + +from isaaclab_ov.renderers import OVRTXRendererCfg from isaaclab.utils import configclass from isaaclab.visualizers.visualizer_cfg import VisualizerBackendCfg @@ -20,9 +22,10 @@ class IsaacSimBackendCfg(VisualizerBackendCfg): """Configuration for the Isaac Sim 7 viewer attached to an Isaac Lab simulation. - Isaac Lab keeps its own physics. One OVStage, created by the viewer host's stage context and borrowed by Isaac Lab, - is the data layer for both: Isaac Lab owns its ordinals, writes poses, markers and the host's edits, seals, and - renders the viewer's products with OVRTX at most ``window.fps`` times a second. The shared + Isaac Lab keeps its own physics and loop. The viewer shows Isaac Lab's own OVRTX scene: launch preparation declares + the viewer's perspective cameras as ordinary scene cameras on :attr:`renderer_cfg`, whose scene stage the Isaac Sim + 7 host creates (:func:`~.isaac_sim_host_stage.host_stage`) so its stage tree and property panes read it. Isaac Lab + populates that stage and owns its ordinals; the host runs no scheduler. The shared :class:`~isaaclab.visualizers.visualizer_cfg.VisualizerCfg` supplies the viewport size (``window.size``), the frame rate (``window.fps``) and ``headless``, which serves the viewer without a client. """ @@ -33,8 +36,19 @@ class IsaacSimBackendCfg(VisualizerBackendCfg): visualizer_type: str = "isaac_sim" """Type identifier for the Isaac Sim 7 viewer.""" - cloning_contexts: ClassVar[tuple[type | str, ...]] = ("isaaclab.cloner:UsdReplicateContext",) - """The shared stage is populated from the authored USD stage, so every environment is authored there.""" + launcher_type: ClassVar[str] = "isaaclab_ov.app:OvrtxLauncher" + """Registers the OVRTX runtime before the stage is created.""" + + renderer_cfg: OVRTXRendererCfg = OVRTXRendererCfg( + stage_provider="isaaclab_visualizers.isaac_sim.isaac_sim_host_stage:host_stage" + ) + """Renderer of the viewer's cameras. Its stage provider lets the host's panes read Isaac Lab's scene stage. + + Scene cameras with the same configuration share the instance and its stage. + """ + + render_settings: dict[str, Any] = dict() + """RTX attributes to author on the viewer cameras' render products, as ``{name: (usd_type_name, value)}``.""" camera_controls: Literal["newton", "isaac_sim"] = "newton" """Viewport camera bindings. diff --git a/source/isaaclab_visualizers/test/test_isaac_sim_visualizer.py b/source/isaaclab_visualizers/test/test_isaac_sim_visualizer.py index 4d46d2119fcc..c6138090fe34 100644 --- a/source/isaaclab_visualizers/test/test_isaac_sim_visualizer.py +++ b/source/isaaclab_visualizers/test/test_isaac_sim_visualizer.py @@ -3,19 +3,19 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Tests for the Isaac Sim 7 viewer visualizer registration and scene export.""" +"""Tests for the Isaac Sim 7 viewer visualizer: registration, its scene stage and the host's writes.""" from __future__ import annotations -from types import SimpleNamespace - +import numpy as np +import pytest from isaaclab_visualizers.isaac_sim import IsaacSimBackendCfg -from isaaclab_visualizers.isaac_sim.isaac_sim_visualizer import IsaacSimVisualizer +from isaaclab_visualizers.isaac_sim.isaac_sim_host_stage import HostStage, SceneWriter -from pxr import Usd +from pxr import Sdf from isaaclab.scene_data.scene_data_provider import REQUIRES_STAGE_AND_MODEL -from isaaclab.visualizers.visualizer_cfg import VISUALIZER_TYPES, VisualizerCfg +from isaaclab.visualizers.visualizer_cfg import VISUALIZER_TYPES _SCENE = """#usda 1.0 def "World" @@ -24,62 +24,68 @@ def "envs" { def Xform "env_0" { - def Xform "Robot" - { - def Mesh "mesh" - { - point3f[] points = [(0, 0, 0), (1, 0, 0), (0, 1, 0)] - } - } - } - def Xform "env_1" - { - double3 xformOp:translate = (2, 0, 0) - uniform token[] xformOpOrder = ["xformOp:translate"] - def Xform "Robot" + def Cube "box" { - def Mesh "mesh" - { - point3f[] points = [(0, 0, 0), (1, 0, 0), (0, 1, 0)] - } } } } + over "ground" + { + } } """ -def _export(scene: str): - """Export a scene the way the visualizer populates the shared stage, without a clone plan.""" - stage = Usd.Stage.CreateInMemory() - stage.GetRootLayer().ImportFromString(scene) - visualizer = IsaacSimVisualizer(VisualizerCfg(backend=IsaacSimBackendCfg())) - try: - path, replication = visualizer._export_prototypes(SimpleNamespace(stage=stage, get_clone_plan=lambda: None)) - return Usd.Stage.Open(str(path)), replication - finally: - visualizer._resources.close() - - def test_isaac_sim_is_registered(): assert "isaac_sim" in VISUALIZER_TYPES assert REQUIRES_STAGE_AND_MODEL["isaac_sim"] == (True, False) - assert IsaacSimBackendCfg().visualizer_type == "isaac_sim" + cfg = IsaacSimBackendCfg() + assert cfg.visualizer_type == "isaac_sim" + # The viewer's cameras render on a scene stage the host creates, so its panes read what Isaac Lab renders. + assert cfg.renderer_cfg.stage_provider == "isaaclab_visualizers.isaac_sim.isaac_sim_host_stage:host_stage" + + +def test_population_types_typeless_containers(): + layer = Sdf.Layer.CreateAnonymous(".usda") + layer.ImportFromString(HostStage.prepare_population(_SCENE)) + assert layer.GetPrimAtPath("/World").typeName == "Xform" + assert layer.GetPrimAtPath("/World/envs").typeName == "Xform" + assert layer.GetPrimAtPath("/World/envs/env_0/box").typeName == "Cube" + # An over authors no prim of its own, so it keeps no type. + assert not layer.GetPrimAtPath("/World/ground").typeName + + +def test_population_of_typed_scene_is_unchanged(): + scene = '#usda 1.0\ndef Xform "World"\n{\n}\n' + assert HostStage.prepare_population(scene) == scene -def test_export_keeps_one_copy_and_clones_the_other_environments(): - exported, replication = _export(_SCENE) - assert replication.copies == [("/World/envs/env_0/Robot", ["/World/envs/env_1/Robot"])] - assert exported.GetPrimAtPath("/World/envs/env_0/Robot/mesh") - # The other environment keeps its root and placement; its contents come from the clone. - assert exported.GetPrimAtPath("/World/envs/env_1") - copy = exported.GetPrimAtPath("/World/envs/env_1/Robot") - assert not copy or not copy.IsActive() - # The viewer's stage tree omits typeless containers, so they are exported as transforms. - assert exported.GetPrimAtPath("/World").GetTypeName() == "Xform" +def test_viewer_camera_moves_go_to_the_sensor(): + moved = [] + writer = SceneWriter(scene=None, cameras={"/World/viewer_camera_0_0": moved.append}) + pose = np.eye(4) + pose[3, :3] = (1.0, 2.0, 3.0) + writer.write(["/World/viewer_camera_0_0"], "omni:xform", pose.reshape(1, 16)) + assert len(moved) == 1 + np.testing.assert_allclose(moved[0], pose) -def test_export_without_environments_is_whole(): - exported, replication = _export('#usda 1.0\ndef "World"\n{\n def Cube "box"\n {\n }\n}\n') - assert replication is None - assert exported.GetPrimAtPath("/World/box") +def test_host_stage_holds_isaac_lab_population(): + pytest.importorskip("isaacsim.context.usd") + from isaaclab_ov.stage import OvstageBackend, OvstageBackendCfg + + from isaacsim.common.interfaces import Query + + provider = "isaaclab_visualizers.isaac_sim.isaac_sim_host_stage:host_stage" + backend = OvstageBackend(OvstageBackendCfg(stage_provider=provider)) + try: + assert isinstance(backend.stage_owner, HostStage) + backend.populate(_SCENE) + context = backend.stage_owner.context + # Population follows the host context's own first ordinal, and the host reads Isaac Lab's prims. + assert backend.ordinal > 2 + assert "/World" in context.read(Query("/"), "usd-children")[0] + assert context.read(Query("/World/envs"), "usd-prim-type")[0] == "Xform" + assert context.read(Query("/World/envs"), "usd-children")[0] == ["/World/envs/env_0"] + finally: + backend.close() From 2b37011339dc213ffa3195a972df7e91e3459c2e Mon Sep 17 00:00:00 2001 From: mtrepte Date: Thu, 5 Nov 2026 23:44:17 +0000 Subject: [PATCH 3/9] Pick and outline in Isaac Lab's OVRTX renderer Add OVRTXRenderer.request_pick and set_selection_outline, and use them for the Isaac Sim viewer's viewport selection, so any camera on the renderer can be picked and outlined. --- .../ovstage-stage-provider.added.rst | 3 + .../isaaclab_ov/renderers/ovrtx_renderer.py | 96 +++++++++++++++++++ .../isaac_sim/isaac_sim_host_adapter.py | 25 +++-- .../isaac_sim/isaac_sim_host_world.py | 13 +++ .../isaac_sim/isaac_sim_visualizer.py | 8 +- 5 files changed, 137 insertions(+), 8 deletions(-) diff --git a/source/isaaclab_ov/changelog.d/ovstage-stage-provider.added.rst b/source/isaaclab_ov/changelog.d/ovstage-stage-provider.added.rst index cf7a3be1708e..ce1cba0b4e0e 100644 --- a/source/isaaclab_ov/changelog.d/ovstage-stage-provider.added.rst +++ b/source/isaaclab_ov/changelog.d/ovstage-stage-provider.added.rst @@ -2,3 +2,6 @@ :attr:`~isaaclab_ov.stage.OvstageBackendCfg.stage_provider`, which let an application create the OVStage that an OVRTX renderer's scene is populated into, for example a viewer that also reads the stage through its own stage context. Population starts after any ordinals the provided stage already holds. +* Added :meth:`~isaaclab_ov.renderers.OVRTXRenderer.request_pick` and + :meth:`~isaaclab_ov.renderers.OVRTXRenderer.set_selection_outline`: viewport picking of a camera's next render and a + selection outline in every render product. diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index d9c1bb83d659..19cafac92acd 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -28,10 +28,12 @@ import os import sys import tempfile +import threading import weakref from builtins import ExceptionGroup from collections import deque from collections.abc import Callable, Iterable, Iterator, Sequence +from concurrent.futures import Future from pathlib import Path from typing import TYPE_CHECKING, Any, Generic, TypeVar @@ -59,6 +61,7 @@ Renderer, RendererConfig, RenderProductSetOutputs, + SelectionGroupStyle, Semantic, TextureStreamingMode, ) @@ -320,6 +323,13 @@ def __init__(self, cfg: OVRTXRendererCfg, *, sim: SimulationContext): self.markers: dict[Any, OVRTXMarkers] = {} self.marker_groups: Iterable = () self.geometry_callbacks: dict[Any, Callable[[OVRTXRenderer], None]] = {} + self._selection_lock = threading.Lock() + self._picks: dict[str, tuple[tuple[float, float, float, float], Future]] = {} + """Pick rectangles per render product, answered by the product's next synchronous render.""" + self._selection: list[str] | None = None + """Selection outline to apply before the next render, or ``None`` if unchanged.""" + self._outlined: list[str] = [] + self._selection_styled = False self.geometry_resources = contextlib.ExitStack() self._sdp = self._sim.get_scene_data_provider() self._transforms_timestamp = -1 @@ -939,6 +949,89 @@ def _process_render_products( data.warp_buffers[str(RenderBufferKind.RGBA)], ) + def request_pick(self, camera_path: str, rect: tuple[float, float, float, float]) -> Future: + """Ask which prims a camera's next render shows in a rectangle of its image; thread-safe. + + Args: + camera_path: Prim path of a camera this renderer renders. + rect: ``(left, top, right, bottom)`` in ``[0, 1]`` with a top-left origin. + + Returns: + A future of the hit prim paths in hit order, without repeats. A newer request for the same camera + cancels it. Synchronous renders answer picks; asynchronous rendering leaves them pending. + + Raises: + KeyError: This renderer renders no camera at ``camera_path``. + """ + product = next( + (data.render_product_path for data in self._camera_render_data if camera_path in data.camera_paths), None + ) + if product is None: + raise KeyError(f"No OVRTX camera at {camera_path!r}") + future: Future = Future() + with self._selection_lock: + previous = self._picks.get(product) + self._picks[product] = (rect, future) + if previous is not None: + previous[1].cancel() + return future + + @property + def has_pending_picks(self) -> bool: + """Whether a pick waits for a render.""" + with self._selection_lock: + return bool(self._picks) + + def set_selection_outline(self, paths: Sequence[str]) -> None: + """Outline ``paths`` in every product from the next render on; an empty selection clears it. Thread-safe.""" + with self._selection_lock: + self._selection = list(paths) + + def _prepare_selection(self, products: set[str]) -> dict[str, tuple[tuple[float, float, float, float], Future]]: + """Apply a changed selection outline and enqueue the picks the next render answers.""" + with self._selection_lock: + selection, self._selection = self._selection, None + picks = {product: self._picks.pop(product) for product in list(self._picks) if product in products} + renderer = self.backend.renderer + if selection is not None: + if not self._selection_styled: + # Kit's selection colour: an orange outline and no fill. + style = SelectionGroupStyle(outline_color=(1.0, 0.6, 0.0, 1.0), fill_color=(0.0, 0.0, 0.0, 0.0)) + renderer.set_selection_group_styles({1: style}) + self._selection_styled = True + if self._outlined: + renderer.set_selection_outline_group_strings(self._outlined, 0) + if selection: + renderer.set_selection_outline_group_strings(selection, 1) + self._outlined = selection + for product, (rect, _) in picks.items(): + renderer.enqueue_pick_query(product, *rect) + return picks + + def _answer_picks(self, picks: dict[str, tuple[Any, Future]], products: RenderProductSetOutputs) -> None: + """Resolve picks from their products' pick-hit output.""" + for product, (_, future) in picks.items(): + if future.done(): + continue + try: + paths: list[str] = [] + frames = products[product].frames if product in products.keys() else () + render_vars = frames[0].render_vars if frames else {} + hits = next((var for name, var in render_vars.items() if "pick_hit" in name), None) + if hits is not None: + mapping = hits.map(device=Device.CPU) + try: + ids = np.from_dlpack(mapping["primPath"]).reshape(-1).tolist() + finally: + mapping.unmap() + for path_id in ids: + path = self.backend.renderer.resolve_prim_path_id(path_id) if path_id else None + if path and path not in paths: + paths.append(path) + future.set_result(paths) + except Exception as error: # noqa: BLE001 - a failed pick goes to its caller, not to rendering + future.set_exception(error) + def update_transforms(self) -> None: """Write changed SDP transforms to OVRTX.""" binding = self._object_xform_binding @@ -1110,6 +1203,7 @@ def render_batch(self, render_data: Sequence[OVRTXCameraRenderData]) -> None: if self.backend.renderer is None or not self._camera_render_data: return products = self.backend.render_products.copy() + picks = self._prepare_selection(products) if not self.cfg.async_rendering or self._use_ovstage else {} 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: @@ -1134,6 +1228,7 @@ def render_batch(self, render_data: Sequence[OVRTXCameraRenderData]) -> None: previous.wait().fetch() else: result = self.backend.renderer.step(render_products=products, delta_time=_RENDER_DELTA_TIME) + self._answer_picks(picks, result) self._process_render_products(render_data, result) finally: if material_writer is not None: @@ -1153,6 +1248,7 @@ def render_batch(self, render_data: Sequence[OVRTXCameraRenderData]) -> None: result = self.backend.renderer.step( render_products=products, delta_time=_RENDER_DELTA_TIME, ordinal=ordinal ) + self._answer_picks(picks, result) self._process_render_products(render_data, result) def cleanup(self, render_data: OVRTXCameraRenderData | None) -> None: diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_adapter.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_adapter.py index 7d51ce41f361..a854d1b28fc2 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_adapter.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_adapter.py @@ -259,12 +259,14 @@ def _capture_selection(self, view: Any, demand: Any) -> dict[str, Any]: class ViewportPicker: """Answers the host's viewport picks with Isaac Lab's OVRTX renderer. - The host's own picker sends requests through Isaac Sim's scheduled renderer; here the next render Isaac Lab starts - answers them. + The host's own picker sends requests through Isaac Sim's scheduled renderer; here the viewport's camera answers + them with its next render. Args: - renderer: Isaac Lab's viewer renderer (``ViewerRenderer``). + renderer: Isaac Lab's OVRTX renderer of the viewer cameras (``isaaclab_ov.renderers.OVRTXRenderer``). + cameras: Camera prim path of each viewport's render product. data: The world's data handle, for the answering simulation time. + on_request: Called after a pick is queued, so the caller renders soon even if nothing else changed. """ capabilities = { @@ -275,11 +277,13 @@ class ViewportPicker: "native_events": False, } - def __init__(self, renderer: Any, data: HostData): + def __init__(self, renderer: Any, cameras: dict[str, str], data: HostData, on_request: Any = None): import itertools self._renderer = renderer + self._cameras = cameras self._data = data + self._on_request = on_request self._ids = itertools.count(1) def pick(self, host: Any, product: str, body: dict[str, Any]) -> dict[str, Any]: @@ -293,7 +297,10 @@ def pick(self, host: Any, product: str, body: dict[str, Any]) -> dict[str, Any]: rect = picking.normalized_rect(body) maximum = maximum_hits(body) request_id = next(self._ids) - paths = self._renderer.request_pick(product, rect).result(timeout=5.0) + future = self._renderer.request_pick(self._cameras[product], rect) + if self._on_request is not None: + self._on_request() + paths = future.result(timeout=5.0) return picking.pick_payload(request_id, paths, maximum_hits=maximum, sim_time_ns=self._data.time_ns) @@ -301,16 +308,20 @@ class SelectionOutline: """Outlines the host's selection in Isaac Lab's OVRTX renderer. Args: - renderer: Isaac Lab's viewer renderer (``ViewerRenderer``). + renderer: Isaac Lab's OVRTX renderer of the viewer cameras (``isaaclab_ov.renderers.OVRTXRenderer``). + on_change: Called after the selection changes, so the caller renders the outline soon. """ supports_selection_outline = True - def __init__(self, renderer: Any): + def __init__(self, renderer: Any, on_change: Any = None): self._renderer = renderer + self._on_change = on_change def set_selection_outline(self, paths: list[str]) -> None: self._renderer.set_selection_outline(paths) + if self._on_change is not None: + self._on_change() class BorrowedContext: diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py index 8e247ee78857..7fb01f46662e 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py @@ -26,7 +26,9 @@ CloneAuthoring, HostClock, HostData, + SelectionOutline, StageView, + ViewportPicker, live_inspection_type, ) from .isaac_sim_host_stage import FrameStore, SceneWriter @@ -81,6 +83,7 @@ class HostWorldOpener: up: Stage up axis as a vector. meters_per_unit: Stage units [m]. copies: Isaac Lab's environment clones as ``(source, targets)``, so the property pane describes clones. + renderer: Isaac Lab's OVRTX renderer of the viewer cameras, which answers picks and outlines the selection. """ def __init__( @@ -94,6 +97,7 @@ def __init__( up: tuple[float, float, float], meters_per_unit: float, copies: Sequence[tuple[str, Sequence[str]]], + renderer: Any, ): from isaacsim.viewports.authoring import AuthoringSession @@ -106,6 +110,9 @@ def __init__( self._up = up self._meters_per_unit = meters_per_unit self._copies = copies + self._renderer = renderer + self.redraw = False + """Set when a pick or a selection change needs a new frame although the scene did not change.""" self._lock = threading.Lock() self._world: World | None = None self._data: HostData | None = None @@ -173,6 +180,9 @@ def __call__(self, scene: str, wake: Callable[[], None]) -> World: ) world.on_simulation_step = self._grant_step world.renderer_name = "ovrtx" + cameras = {spec.product: spec.camera for spec in self._specs} + world.picker = ViewportPicker(self._renderer, cameras, data, on_request=self._request_redraw) + world.renderer_selection = SelectionOutline(self._renderer, on_change=self._request_redraw) world.authoring = CloneAuthoring(self.authoring, self._copies) world.authoring_revision = self.authoring.revision world.authoring_sync = AuthoringSync(self.authoring.stage) @@ -213,6 +223,9 @@ def set_enabled(product: str, enabled: bool) -> None: world.remove_viewport = lambda spec: set_enabled(spec.product, False) world.set_render_product_enabled = set_enabled + def _request_redraw(self) -> None: + self.redraw = True + def _grant_step(self) -> None: with self._lock: self._step_grants += 1 diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py index c4c428d12cb7..370700f9ae17 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py @@ -158,6 +158,7 @@ def _start_host(self, sim: SimulationContext, renderer) -> None: up, UsdGeom.GetStageMetersPerUnit(sim.stage), scene.clone_copies, + renderer, ) client_roots = client_roots_for_backend("web") if self.backend_cfg.app_client_root is not None: @@ -237,7 +238,12 @@ def _render_frame(self) -> None: return self._next_render = now + 1.0 / self.cfg.window.fps time_ns = int(self._sim_time * 1e9) - if self._opener.drain(time_ns): + changed = self._opener.drain(time_ns) + if self._opener.redraw: + # A pick or a new selection outline needs a render even when the scene is unchanged. + self._opener.redraw = False + changed = True + if changed: for view in self._viewports.values(): view.invalidate() if self.cfg.enable_markers and self._marker_revision != self._sim.vis_marker_registry.revision: From 742197bf05672041eb759e9b52a1452c236c724e Mon Sep 17 00:00:00 2001 From: mtrepte Date: Thu, 5 Nov 2026 23:48:41 +0000 Subject: [PATCH 4/9] Describe the Isaac Sim viewer on Isaac Lab's renderer in its docs Markers come from Isaac Lab's OVRTX renderer and the host's commands are written at the scene's open ordinal; update the package and adapter docs to match. --- .../isaaclab_visualizers/isaac_sim/__init__.py | 9 +++++---- .../isaac_sim/isaac_sim_host_adapter.py | 10 +++++----- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/__init__.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/__init__.py index 69737e1c658b..2d35ce8bfe63 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/__init__.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/__init__.py @@ -5,10 +5,11 @@ """Isaac Sim 7 viewer visualizer backend (prototype), selected with ``--viz isaac-sim``. -One OVStage is the data layer for Isaac Lab and the Isaac Sim 7 viewer application. Isaac Lab owns its ordinals: it -writes body poses and visualization markers, applies the application host's commands, seals, and renders the viewer's -render products with OVRTX. The host supplies its stage tree, property and content panes, transport controls and frame -streaming; it runs no scheduler, and Isaac Lab drives every update. +The viewer shows Isaac Lab's own OVRTX scene. Its cameras are scene cameras on a shared OVRTX renderer whose scene stage +the Isaac Sim 7 application host creates, so the host's stage tree and property panes read the stage Isaac Lab renders. +Isaac Lab populates that stage, owns its ordinals, and draws body poses and visualization markers through its renderer. +The host supplies its panes, transport controls and frame streaming; it runs no scheduler, and Isaac Lab drives every +update. Prototype requirements, not yet captured by the package dependencies: diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_adapter.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_adapter.py index a854d1b28fc2..28b5a2537c58 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_adapter.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_adapter.py @@ -6,8 +6,8 @@ """Minimal pieces the Isaac Sim 7 viewer host needs from a world that Isaac Lab drives. The host's panes read and write the world through a simulation handle and show time from a clock. Here neither runs a -scheduler: :class:`HostData` reads the shared stage and writes at Isaac Lab's open ordinal, :class:`HostClock` reports -Isaac Lab's simulation time, and Isaac Lab drains the host's command queues itself once per frame through a +scheduler: :class:`HostData` reads Isaac Lab's scene stage and writes at Isaac Lab's open ordinal, :class:`HostClock` +reports Isaac Lab's simulation time, and Isaac Lab drains the host's command queues itself once per frame through a :class:`StageView`. """ @@ -43,7 +43,7 @@ def _as_list(paths: Any) -> list[str]: class HostData: - """The simulation handle the host's services use: reads of the shared stage, writes at the owner's ordinal. + """The simulation handle the host's services use: reads of the scene stage, writes at the owner's ordinal. Args: context: The host's stage context, used for sealed reads (an ``isaacsim.context.usd.UsdContext``). @@ -172,7 +172,7 @@ def __getattr__(self, name: str) -> Any: class CloneAuthoring: """Authoring session that describes cloned prims by their source prim. - Isaac Lab clones environments in the shared stage only, so the host's authored stage holds just the source of each + Isaac Lab clones environments in its scene stage only, so the host's authored stage holds just the source of each clone. Without this, a cloned prim's property fields have no declared types. Clones are described read-only: an authored edit would land on the source prim. @@ -213,7 +213,7 @@ def __getattr__(self, name: str) -> Any: def live_inspection_type() -> type: - """Return a property inspection that reads live world poses from the shared stage. + """Return a property inspection that reads live world poses from the scene stage. Isaac Sim's inspection composes poses with native helpers that need a native simulation view, and reads velocities through Isaac Sim physics views. Neither exists when Isaac Lab drives the world, so this one reads the stage's world From a082c9ef59ba7e4a401db13d496047bbdf8fb356 Mon Sep 17 00:00:00 2001 From: mtrepte Date: Thu, 5 Nov 2026 23:56:43 +0000 Subject: [PATCH 5/9] Author preview-surface visual materials on kitless USD file spawns Preview surfaces are plain UsdShade, so author and bind them without Kit too; only MDL materials still need Kit. Kitless visualization markers keep their configured colors. --- .../changelog.d/kitless-preview-surface-materials.fixed.rst | 3 +++ .../isaaclab/isaaclab/sim/spawners/from_files/from_files.py | 5 +++-- 2 files changed, 6 insertions(+), 2 deletions(-) create mode 100644 source/isaaclab/changelog.d/kitless-preview-surface-materials.fixed.rst diff --git a/source/isaaclab/changelog.d/kitless-preview-surface-materials.fixed.rst b/source/isaaclab/changelog.d/kitless-preview-surface-materials.fixed.rst new file mode 100644 index 000000000000..48d3ea5d6d50 --- /dev/null +++ b/source/isaaclab/changelog.d/kitless-preview-surface-materials.fixed.rst @@ -0,0 +1,3 @@ +* Fixed kitless USD file spawns, such as visualization markers, dropping their + :class:`~isaaclab.sim.spawners.materials.PreviewSurfaceCfg` visual material. Preview surfaces are plain ``UsdShade`` + and are now authored and bound without Kit; only MDL materials are still skipped. diff --git a/source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py b/source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py index 1a982fddcc09..2afebfebe13a 100644 --- a/source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py +++ b/source/isaaclab/isaaclab/sim/spawners/from_files/from_files.py @@ -756,7 +756,8 @@ def spawn_from_usd_file( shader, _, _ = UsdShade.Material(prim).ComputeSurfaceSource(context) if shader: _author_material_inputs(shader.GetPrim(), cfg.visual_material) - elif has_kit(): + elif has_kit() or isinstance(cfg.visual_material, PreviewSurfaceCfg): + # Preview surfaces are plain UsdShade, so they are authored without Kit too; MDL materials need Kit. material_path = ( cfg.visual_material_path if cfg.visual_material_path.startswith("/") @@ -765,7 +766,7 @@ def spawn_from_usd_file( cfg.visual_material.func(material_path, cfg.visual_material) bind_visual_material(prim_path, material_path, stage=stage) else: - logger.warning("Skipping visual material application for '%s' in kitless mode.", prim_path) + logger.warning("Skipping MDL visual material application for '%s' in kitless mode.", prim_path) for part_path, material_path in cfg.visual_material_bindings.items(): from pxr import UsdShade # noqa: PLC0415 From b18bd61d1ffbaccf14ab8738f98f3cc234b9e95c Mon Sep 17 00:00:00 2001 From: mtrepte Date: Thu, 5 Nov 2026 23:56:44 +0000 Subject: [PATCH 6/9] Start the Isaac Sim viewer's desktop window with its camera controls Electron loads the renderer from the client it starts, not from the host, so the Newton-style camera bindings only reached browsers. Build a patched copy of the whole client and start the desktop window from it. --- .../isaac_sim/isaac_sim_camera_controls.py | 22 ++++++------ .../isaac_sim/isaac_sim_visualizer.py | 34 +++++++++++++------ 2 files changed, 36 insertions(+), 20 deletions(-) diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_camera_controls.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_camera_controls.py index 94cb4cadb233..6a2d6f8bce6f 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_camera_controls.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_camera_controls.py @@ -7,8 +7,10 @@ The Isaac Sim client binds its camera as Kit does: Alt+left-drag orbits, middle-drag pans and right-drag looks, while a plain left-drag selects. Isaac Lab's Newton viewer looks with the left button and orbits with the middle one. The -client has no setting for its bindings, so this serves a copy of its shared renderer with the bindings in -``panes/viewport-camera.js`` changed: +client has no setting for its bindings, so this builds a copy of the installed client (its Electron shell and shared +renderer) with the bindings in ``panes/viewport-camera.js`` changed. The host serves the copy's renderer to browsers, +and the desktop window starts from the copy, because Electron loads the renderer from its own files rather than from +the host: * Left-drag looks; a left click without dragging still selects, and Shift, Ctrl or Cmd with the left button still select by region. Alt+left-drag still orbits. @@ -78,17 +80,17 @@ ) -def newton_controls_client(shared_renderer: Path, directory: Path) -> Path | None: - """Copy the client's shared renderer into ``directory`` with Newton-viewer camera bindings. +def newton_controls_client(client: Path, directory: Path) -> Path | None: + """Copy the installed client into ``directory`` with Newton-viewer camera bindings. Args: - shared_renderer: The installed client's shared renderer directory. + client: The installed client directory, holding ``electron/`` and ``renderer/``. directory: Empty directory to write the copy into. Returns: - The patched renderer directory, or ``None`` if this client version does not match the expected bindings. + The patched client directory, or ``None`` if this client version does not match the expected bindings. """ - module = shared_renderer / _CAMERA_MODULE + module = client / "renderer" / _CAMERA_MODULE patched = module.read_text() if module.is_file() else "" for old, new in _PATCHES: if patched.count(old) != 1: @@ -98,7 +100,7 @@ def newton_controls_client(shared_renderer: Path, directory: Path) -> Path | Non ) return None patched = patched.replace(old, new) - target = directory / "renderer" - shutil.copytree(shared_renderer, target) - (target / _CAMERA_MODULE).write_text(patched) + target = directory / "client" + shutil.copytree(client, target) + (target / "renderer" / _CAMERA_MODULE).write_text(patched) return target diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py index 370700f9ae17..b924527cb4dc 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py @@ -12,6 +12,7 @@ import os import tempfile import time +from contextlib import nullcontext from pathlib import Path from typing import TYPE_CHECKING @@ -61,6 +62,8 @@ def __init__(self, cfg: VisualizerCfg): self._host = None self._desktop = None self._opener = None + self._client: Path | None = None + """Patched copy of the Isaac Sim client the viewer starts, or ``None`` for the installed one.""" self._viewports: dict[str, ImageView] = {} """Viewer camera image view per host render product.""" self._shown: set[str] = set() @@ -164,13 +167,17 @@ def _start_host(self, sim: SimulationContext, renderer) -> None: if self.backend_cfg.app_client_root is not None: client_roots = [("/app/", Path(self.backend_cfg.app_client_root) / "renderer"), *client_roots[1:]] if self.backend_cfg.camera_controls == "newton": + from isaacsim.application.client.impl.launch import client_directory + from .isaac_sim_camera_controls import newton_controls_client - client = Path(self._resources.enter_context(tempfile.TemporaryDirectory(prefix="isaaclab_client_"))) - client_roots = [ - (prefix, newton_controls_client(root, client) or root) if prefix == "/" else (prefix, root) - for prefix, root in client_roots - ] + copy = Path(self._resources.enter_context(tempfile.TemporaryDirectory(prefix="isaaclab_client_"))) + self._client = newton_controls_client(client_directory(), copy) + if self._client is not None: + client_roots = [ + (prefix, self._client / "renderer") if prefix == "/" else (prefix, root) + for prefix, root in client_roots + ] def viewport(index: int) -> ViewportSpec: if index >= len(specs): @@ -209,12 +216,19 @@ def viewport(index: int) -> ViewportSpec: def _open_desktop(self) -> None: """Open the Electron window attached to the host that this process runs.""" - from isaacsim.application.client import start_desktop + from unittest import mock - self._desktop = start_desktop( - Path(self.backend_cfg.app_client_root) / "main.cjs", - environment={"SIM_VIEWER_ATTACH_URL": self._host.url, "SIM_VIEWER_ATTACH_TOKEN": self._host.token}, - ) + from isaacsim.application.client import start_desktop + from isaacsim.application.client.impl import launch + + # Electron loads the renderer from the client it starts from, not from the host, so a patched client (camera + # controls) has to be the one it starts. The launcher always starts the installed client otherwise. + client = self._client + with mock.patch.object(launch, "client_directory", lambda: client) if client is not None else nullcontext(): + self._desktop = start_desktop( + Path(self.backend_cfg.app_client_root) / "main.cjs", + environment={"SIM_VIEWER_ATTACH_URL": self._host.url, "SIM_VIEWER_ATTACH_TOKEN": self._host.token}, + ) self._resources.callback(self._desktop.close) def _move_camera(self, view: ImageView, local: np.ndarray) -> None: From c4b808e3a85185996b29c9bdaac95446899de5f7 Mon Sep 17 00:00:00 2001 From: mtrepte Date: Fri, 6 Nov 2026 00:44:42 +0000 Subject: [PATCH 7/9] Move and rotate Isaac Lab assets with the Isaac Sim viewer's gizmo Give the host a live manipulation that resolves any selected prim to the articulation or rigid object instance owning it, and moves that instance rigidly with the gizmo by writing its root link pose at rest. Frame such selections from the live stage, and capture a fresh image after scene edits and camera moves while paused. --- .../isaac-sim-viewer-prototype.added.rst | 2 + .../isaac_sim/isaac_sim_host_adapter.py | 51 ++++- .../isaac_sim/isaac_sim_host_world.py | 14 +- .../isaac_sim/isaac_sim_manipulation.py | 211 ++++++++++++++++++ .../isaac_sim/isaac_sim_visualizer.py | 14 +- .../test/test_isaac_sim_visualizer.py | 106 +++++++++ 6 files changed, 394 insertions(+), 4 deletions(-) create mode 100644 source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_manipulation.py diff --git a/source/isaaclab_visualizers/changelog.d/isaac-sim-viewer-prototype.added.rst b/source/isaaclab_visualizers/changelog.d/isaac-sim-viewer-prototype.added.rst index 695cc8d23e9e..a1e570eda6d3 100644 --- a/source/isaaclab_visualizers/changelog.d/isaac-sim-viewer-prototype.added.rst +++ b/source/isaaclab_visualizers/changelog.d/isaac-sim-viewer-prototype.added.rst @@ -4,3 +4,5 @@ Lab's own OVRTX scene: its cameras are scene cameras on a shared OVRTX renderer whose scene stage the application host creates, so the host's panes read the stage Isaac Lab renders. The host runs no scheduler; Isaac Lab drives every update. + Clicking a prim selects and outlines it; the transform gizmo moves and rotates the Isaac Lab asset that owns it + (an articulation or rigid object, per environment), also while paused. diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_adapter.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_adapter.py index 28b5a2537c58..fa2c002be952 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_adapter.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_adapter.py @@ -179,11 +179,13 @@ class CloneAuthoring: Args: session: The host's ``isaacsim.viewports.authoring.AuthoringSession``. copies: Source subtrees and their clone destinations. + owners: Resolves a prim to the Isaac Lab asset instance that owns it (with a ``root`` path), or ``None``. """ - def __init__(self, session: Any, copies: Sequence[tuple[str, Sequence[str]]]): + def __init__(self, session: Any, copies: Sequence[tuple[str, Sequence[str]]], owners: Any = None): self._session = session self._sources = {target: source for source, targets in copies for target in targets} + self._owners = owners def source_of(self, path: str) -> str | None: """Return the authored prim a cloned path was copied from, or ``None`` if it is not a clone.""" @@ -208,6 +210,53 @@ def attributes(self, path: str) -> dict[str, dict[str, Any]]: for name, row in self._session.attributes(source).items() } + def selection_frame(self, paths: list[str], matrices: dict[str, Any] | None = None) -> dict[str, Any]: + """Describe a selection's pivot and roots, looking cloned prims up by their source prim. + + Args: + paths: Selected prim paths, the active prim last. + matrices: Optional live world matrices keyed by selected path; they place a clone's pivot where it is. + + Returns: + The authoring session's frame, with paths and roots naming the selected prims. + """ + instances = [self._owners(path) for path in paths] if self._owners is not None else [] + if instances and all(instance is not None for instance in instances): + return self._asset_frame(paths, [instance.root for instance in instances], matrices) + sources = [self.source_of(path) or path for path in paths] + if len(set(sources)) != len(sources): + raise ValueError("Select copies of different prims, not the same prim in several environments") + selected = dict(zip(sources, paths)) + mapped = None if matrices is None else {source: matrices[path] for source, path in selected.items()} + frame = dict(self._session.selection_frame(sources, mapped)) + frame["paths"] = [selected.get(path, path) for path in frame["paths"]] + frame["roots"] = [selected.get(path, path) for path in frame["roots"]] + return frame + + @staticmethod + def _asset_frame(paths: list[str], roots: list[str], matrices: dict[str, Any] | None) -> dict[str, Any]: + """Frame a selection of Isaac Lab assets: they move as whole instances, pivoting at the active prim. + + The authored scene cannot describe these selections: an asset's visual meshes are often inside instances, and + Isaac Lab poses the asset by its root rather than by the selected prim. + """ + import numpy as np + + roots = list(dict.fromkeys(roots)) + pivot = np.eye(4) + if matrices is not None: + active = np.asarray(matrices[paths[-1]], dtype=float).reshape(4, 4) + # Keep the rotation and position of the active prim; drop its scale. + u, _, vt = np.linalg.svd(active[:3, :3]) + pivot[:3, :3] = u @ vt + pivot[3, :3] = active[3, :3] + return { + "paths": list(paths), + "roots": roots, + "pivot_key": "|".join(roots), + "matrix": pivot.reshape(-1).tolist(), + } + def __getattr__(self, name: str) -> Any: return getattr(self._session, name) diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py index 7fb01f46662e..e07eab63ee63 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py @@ -84,6 +84,8 @@ class HostWorldOpener: meters_per_unit: Stage units [m]. copies: Isaac Lab's environment clones as ``(source, targets)``, so the property pane describes clones. renderer: Isaac Lab's OVRTX renderer of the viewer cameras, which answers picks and outlines the selection. + manipulation: Creates the live manipulation of Isaac Lab's assets from the world's authoring session. + owners: Resolves a prim to the Isaac Lab asset instance that owns it, or ``None``. """ def __init__( @@ -98,6 +100,8 @@ def __init__( meters_per_unit: float, copies: Sequence[tuple[str, Sequence[str]]], renderer: Any, + manipulation: Callable[[Any], Any], + owners: Callable[[str], Any], ): from isaacsim.viewports.authoring import AuthoringSession @@ -111,6 +115,8 @@ def __init__( self._meters_per_unit = meters_per_unit self._copies = copies self._renderer = renderer + self._manipulation = manipulation + self._owners = owners self.redraw = False """Set when a pick or a selection change needs a new frame although the scene did not change.""" self._lock = threading.Lock() @@ -183,9 +189,15 @@ def __call__(self, scene: str, wake: Callable[[], None]) -> World: cameras = {spec.product: spec.camera for spec in self._specs} world.picker = ViewportPicker(self._renderer, cameras, data, on_request=self._request_redraw) world.renderer_selection = SelectionOutline(self._renderer, on_change=self._request_redraw) - world.authoring = CloneAuthoring(self.authoring, self._copies) + world.authoring = CloneAuthoring(self.authoring, self._copies, self._owners) world.authoring_revision = self.authoring.revision world.authoring_sync = AuthoringSync(self.authoring.stage) + # The transform gizmo moves Isaac Lab's assets; Isaac Lab drains the gestures with the other commands. + world.manipulation = self._manipulation(world.authoring) + manipulation = SceneCommands(rate=self._rate, on_submit=wake) + manipulation.add_reader("holds", world.manipulation.tick) + world.manipulation_worker = manipulation + world.command_sources.append(manipulation) # Property inspection supplies the selected prims' live world poses; Isaac Lab drains it with the commands. inspection = SceneCommands(rate=RationalRate(10), on_submit=wake) world.inspection = live_inspection_type()(inspection, set(), context) diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_manipulation.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_manipulation.py new file mode 100644 index 000000000000..31b0f04433df --- /dev/null +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_manipulation.py @@ -0,0 +1,211 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Move and rotate Isaac Lab assets with the Isaac Sim 7 viewer's transform gizmo. + +The host's own live manipulation moves free rigid bodies through Isaac Sim physics. Isaac Lab owns the physics here, +so this controller applies the gizmo's poses to Isaac Lab's assets instead: selecting any prim of an articulation or a +rigid object moves that asset in its environment, by writing its root link pose (and zero velocity) and updating the +kinematics so the change shows while the simulation is paused. Prims that no Isaac Lab asset owns (terrain, lights, +sensors) are not movable, and scaling is not supported, as in the host's live manipulation. +""" + +from __future__ import annotations + +import re +from collections.abc import Callable +from typing import Any, NamedTuple + +import numpy as np +import torch + + +class Owner(NamedTuple): + """The Isaac Lab asset instance a prim belongs to.""" + + asset: Any + """The articulation or rigid object.""" + + env_id: int + """Environment index of the instance.""" + + root: str + """Prim path of the instance's root.""" + + +class AssetOwners: + """Resolves prims to the Isaac Lab asset instances that own them. + + Args: + scene: Isaac Lab's interactive scene. + """ + + def __init__(self, scene: Any): + self._patterns = [] + for asset in (*scene.articulations.values(), *scene.rigid_objects.values()): + pattern = asset.cfg.prim_path.replace("{ENV_REGEX_NS}", "/World/envs/env_.*") + self._patterns.append((re.compile(f"({pattern})(/.*)?$"), asset)) + self._cache: dict[str, Owner | None] = {} + + def __call__(self, path: str) -> Owner | None: + """Return the asset instance owning ``path``, or ``None`` if no Isaac Lab asset does.""" + if path not in self._cache: + owner = None + for pattern, asset in self._patterns: + match = pattern.match(path) + env = re.search(r"/env_(\d+)(/|$)", path) if match else None + if match: + owner = Owner(asset, int(env.group(1)) if env else 0, match.group(1)) + break + self._cache[path] = owner + return self._cache[path] + + +class MovablePaths: + """The host's set of live-movable paths: every prim of an Isaac Lab asset.""" + + def __init__(self, owners: AssetOwners): + self._owners = owners + + def __contains__(self, path: object) -> bool: + return isinstance(path, str) and self._owners(path) is not None + + +def _rotation(orientation: Any) -> np.ndarray: + """Return the row-vector rotation matrix of an xyzw quaternion.""" + from pxr import Gf + + x, y, z, w = map(float, orientation) + return np.asarray(Gf.Matrix3d(Gf.Quatd(w, Gf.Vec3d(x, y, z)))) + + +def _orientation(rotation: np.ndarray) -> list[float]: + """Return the xyzw quaternion of a row-vector rotation matrix.""" + from pxr import Gf + + quat = Gf.Matrix3d(*rotation.reshape(-1).tolist()).ExtractRotation().GetQuat() + return [*quat.GetImaginary(), quat.GetReal()] + + +class AssetManipulation: + """The host's live manipulation, applied to Isaac Lab's assets. + + Implements what the host's editing routes use: ``supports_groups``, ``backend.paths``, :meth:`apply` and + :meth:`tick`. Commands run on Isaac Lab's thread when it drains the host's queues, so the writes are ordinary + Isaac Lab state writes between simulation steps. + + Args: + owners: Resolves prims to Isaac Lab asset instances. + authoring: The host's authoring session (clone aware), for the selection's pivot. + forward: Updates kinematics after pose writes without stepping physics. + """ + + supports_groups = True + + def __init__(self, owners: AssetOwners, authoring: Any, forward: Callable[[], None]): + self._owners = owners + self._authoring = authoring + self._forward = forward + self.backend = type("Backend", (), {"paths": MovablePaths(owners)})() + self._groups: dict[tuple[str, str], dict[str, Any]] = {} + + def tick(self, view: Any) -> dict: + """Report the paths held by an unfinished gesture.""" + return {"held": sorted(root for group in self._groups.values() for root in group["roots"])} + + def apply(self, owner: str, body: dict, view: Any) -> dict: + """Apply one ordered gesture command (begin, update, heartbeat, end or cancel) to the selection. + + Args: + owner: Client identity. + body: Gesture with ``paths``, ``action``, ``sequence`` and, for updates, the pivot's new world pose. + view: The view the command runs against, for the selection's live world matrices. + + Returns: + The selection pivot's world position and xyzw orientation. + + Raises: + ValueError: The selection holds a prim no Isaac Lab asset owns, the gesture expired or scales. + """ + if "scale" in body: + raise ValueError("Scaling Isaac Lab assets is unsupported") + paths = body.get("paths") or [body["path"]] + key = (owner, body["gesture"]) + action, sequence = body["action"], body["sequence"] + if action == "begin": + return self._begin(key, paths, sequence, view) + group = self._groups.get(key) + if group is None or group["paths"] != paths: + raise ValueError("The gesture expired or belongs to another client") + if sequence <= group["sequence"]: + raise ValueError("Manipulation sequence must increase") + group["sequence"] = sequence + if action == "update": + self._move(group, np.asarray(body["position"], dtype=float), body["orientation"]) + elif action == "cancel": + for instance, (position, orientation) in zip(group["owners"], group["initial"]): + self._write(instance, position, orientation) + self._forward() + if action in ("cancel", "end"): + del self._groups[key] + return {"position": group["position"], "orientation": group["orientation"]} + + def _begin(self, key: tuple[str, str], paths: list[str], sequence: int, view: Any) -> dict: + if key in self._groups: + raise ValueError("This gesture already began; use a new gesture identifier") + matrices = {} + for path in paths: + with_matrix = view.read([path], "omni:fabric:worldMatrix") + matrices[path] = np.asarray(with_matrix, dtype=float).reshape(4, 4) + frame = self._authoring.selection_frame(paths, matrices) + instances: list[Owner] = [] + for root in frame["roots"]: + instance = self._owners(root) + if instance is None: + raise ValueError(f"Only Isaac Lab assets (articulations, rigid objects) can be moved; not {root}") + if all(instance.asset is not other.asset or instance.env_id != other.env_id for other in instances): + instances.append(instance) + held = {root for group in self._groups.values() for root in group["roots"]} + if held.intersection(instance.root for instance in instances): + raise ValueError("A selected asset is already being moved") + pivot = np.asarray(frame["matrix"], dtype=float).reshape(4, 4) + initial = [] + for instance in instances: + pose = instance.asset.data.root_link_pose_w.torch[instance.env_id].detach().cpu().numpy().astype(float) + initial.append((pose[:3], pose[3:7])) + self._groups[key] = { + "paths": paths, + "roots": [instance.root for instance in instances], + "owners": instances, + "initial": initial, + "pivot": pivot, + "sequence": sequence, + "position": pivot[3, :3].tolist(), + "orientation": _orientation(pivot[:3, :3]), + } + return {"position": self._groups[key]["position"], "orientation": self._groups[key]["orientation"]} + + def _move(self, group: dict[str, Any], position: np.ndarray, orientation: Any) -> None: + """Move every asset in the group rigidly with the pivot's new pose.""" + pivot = group["pivot"] + # Row-vector rotations: the change from the pivot's start to its new orientation. + delta = pivot[:3, :3].T @ _rotation(orientation) + for instance, (start, start_orientation) in zip(group["owners"], group["initial"]): + moved = (start - pivot[3, :3]) @ delta + position + self._write(instance, moved, _orientation(_rotation(start_orientation) @ delta)) + self._forward() + group["position"], group["orientation"] = position.tolist(), list(map(float, orientation)) + + @staticmethod + def _write(instance: Owner, position: Any, orientation: Any) -> None: + """Place an asset instance's root link, at rest.""" + asset = instance.asset + device = asset.data.root_link_pose_w.torch.device + pose = torch.tensor([[*map(float, position), *map(float, orientation)]], dtype=torch.float32, device=device) + env_ids = torch.tensor([instance.env_id], dtype=torch.int32, device=device) + asset.write_root_link_pose_to_sim_index(root_pose=pose, env_ids=env_ids) + asset.write_root_link_velocity_to_sim_index( + root_velocity=torch.zeros((1, 6), dtype=torch.float32, device=device), env_ids=env_ids + ) diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py index b924527cb4dc..9450e54dcb95 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py @@ -133,6 +133,7 @@ def _start_host(self, sim: SimulationContext, renderer) -> None: from .isaac_sim_host_stage import FrameStore, HostStage, SceneWriter from .isaac_sim_host_world import HostWorldOpener + from .isaac_sim_manipulation import AssetManipulation, AssetOwners scene = renderer.scene if not isinstance(getattr(scene, "stage_owner", None), HostStage): @@ -151,6 +152,7 @@ def _start_host(self, sim: SimulationContext, renderer) -> None: view.camera.cfg.prim_path: (lambda matrix, view=view: self._move_camera(view, matrix)) for view in self._viewports.values() } + owners = AssetOwners(sim.get_scene_data_provider().get_interactive_scene()) self._opener = HostWorldOpener( scene_file, scene.stage_owner.context, @@ -162,6 +164,8 @@ def _start_host(self, sim: SimulationContext, renderer) -> None: UsdGeom.GetStageMetersPerUnit(sim.stage), scene.clone_copies, renderer, + lambda authoring: AssetManipulation(owners, authoring, sim.forward), + owners, ) client_roots = client_roots_for_backend("web") if self.backend_cfg.app_client_root is not None: @@ -243,6 +247,12 @@ def _move_camera(self, view: ImageView, local: np.ndarray) -> None: # USD matrices multiply row vectors, so the rotation's columns are the rows of the upper 3x3 block. rotation = torch.as_tensor(local[:3, :3].T, dtype=torch.float32, device=camera.device) camera.set_world_poses(position, quat_from_matrix(rotation).unsqueeze(0), convention="opengl") + self._redraw(view) + + @staticmethod + def _redraw(view: ImageView) -> None: + """Make the next read capture a new image, also when no simulation step has outdated the camera (paused).""" + view.camera._invalidate_buffers() view.invalidate() def _render_frame(self) -> None: @@ -259,11 +269,11 @@ def _render_frame(self) -> None: changed = True if changed: for view in self._viewports.values(): - view.invalidate() + self._redraw(view) if self.cfg.enable_markers and self._marker_revision != self._sim.vis_marker_registry.revision: self._marker_revision = self._sim.vis_marker_registry.revision for view in self._viewports.values(): - view.invalidate() + self._redraw(view) frame_id = self._sim.get_physics_step_count() published = False self._shown &= self._opener.enabled diff --git a/source/isaaclab_visualizers/test/test_isaac_sim_visualizer.py b/source/isaaclab_visualizers/test/test_isaac_sim_visualizer.py index c6138090fe34..1b1f324d47ff 100644 --- a/source/isaaclab_visualizers/test/test_isaac_sim_visualizer.py +++ b/source/isaaclab_visualizers/test/test_isaac_sim_visualizer.py @@ -89,3 +89,109 @@ def test_host_stage_holds_isaac_lab_population(): assert context.read(Query("/World/envs"), "usd-children")[0] == ["/World/envs/env_0"] finally: backend.close() + + +class _FakeAsset: + """Root poses per environment and the writes the viewer's gizmo makes, in Isaac Lab's (x, y, z, w) order.""" + + def __init__(self, prim_path: str, poses): + import torch + + self.cfg = type("Cfg", (), {"prim_path": prim_path})() + self._poses = torch.tensor(poses, dtype=torch.float32) + self.data = type("Data", (), {})() + self.data.root_link_pose_w = type("Pose", (), {"torch": self._poses})() + self.velocities = [] + + def write_root_link_pose_to_sim_index(self, *, root_pose, env_ids): + self._poses[env_ids.long()] = root_pose + + def write_root_link_velocity_to_sim_index(self, *, root_velocity, env_ids): + self.velocities.append((env_ids.tolist(), root_velocity.tolist())) + + +def _manipulation(): + from types import SimpleNamespace + + from isaaclab_visualizers.isaac_sim.isaac_sim_host_adapter import CloneAuthoring + from isaaclab_visualizers.isaac_sim.isaac_sim_manipulation import AssetManipulation, AssetOwners + + robot = _FakeAsset("/World/envs/env_.*/Robot", [[0, 0, 0, 0, 0, 0, 1], [5, 0, 0, 0, 0, 0, 1]]) + scene = SimpleNamespace(articulations={"robot": robot}, rigid_objects={}) + owners = AssetOwners(scene) + forwards = [] + authoring = CloneAuthoring(session=None, copies=(), owners=owners) + return robot, owners, AssetManipulation(owners, authoring, lambda: forwards.append(1)), forwards + + +class _PoseView: + """World matrices of selected prims, as the host's view reads them.""" + + def __init__(self, positions: dict[str, tuple[float, float, float]]): + self._positions = positions + + def read(self, paths, attribute): + matrix = np.eye(4) + matrix[3, :3] = self._positions[paths[0]] + return matrix.reshape(1, 16) + + +def test_any_prim_of_an_asset_moves_its_instance(): + _, owners, manipulation, _ = _manipulation() + owner = owners("/World/envs/env_1/Robot/torso_link/visuals/mesh_0") + assert owner.env_id == 1 and owner.root == "/World/envs/env_1/Robot" + assert owners("/World/ground") is None + assert "/World/envs/env_1/Robot/pelvis" in manipulation.backend.paths + assert "/World/ground" not in manipulation.backend.paths + + +def test_gizmo_moves_and_turns_the_owning_instance_at_rest(): + robot, _, manipulation, forwards = _manipulation() + mesh = "/World/envs/env_1/Robot/torso_link/visuals/mesh_0" + view = _PoseView({mesh: (5.0, 0.0, 1.0)}) + gesture = {"paths": [mesh], "gesture": "g"} + begun = manipulation.apply("me", {**gesture, "action": "begin", "sequence": 0}, view) + assert begun["position"] == [5.0, 0.0, 1.0] + assert manipulation.tick(view)["held"] == ["/World/envs/env_1/Robot"] + # Raise the pivot 1 m and turn 90 degrees about z: the root, 1 m below the pivot, follows rigidly. + turn = [0.0, 0.0, float(np.sin(np.pi / 4)), float(np.cos(np.pi / 4))] + manipulation.apply( + "me", {**gesture, "action": "update", "sequence": 1, "position": [5.0, 0.0, 2.0], "orientation": turn}, view + ) + np.testing.assert_allclose(robot._poses[1, :3].numpy(), [5.0, 0.0, 1.0], atol=1e-6) + np.testing.assert_allclose(np.abs(robot._poses[1, 3:].numpy()), np.abs(turn), atol=1e-6) + np.testing.assert_allclose(robot._poses[0].numpy(), [0, 0, 0, 0, 0, 0, 1]) + assert robot.velocities[-1] == ([1], [[0.0] * 6]) and forwards + manipulation.apply("me", {**gesture, "action": "end", "sequence": 2}, view) + assert manipulation.tick(view)["held"] == [] + + +def test_cancel_restores_the_starting_pose(): + robot, _, manipulation, _ = _manipulation() + mesh = "/World/envs/env_1/Robot/pelvis" + view = _PoseView({mesh: (5.0, 0.0, 0.0)}) + gesture = {"paths": [mesh], "gesture": "g"} + manipulation.apply("me", {**gesture, "action": "begin", "sequence": 0}, view) + manipulation.apply( + "me", + {**gesture, "action": "update", "sequence": 1, "position": [9.0, 9.0, 9.0], "orientation": [0, 0, 0, 1]}, + view, + ) + manipulation.apply("me", {**gesture, "action": "cancel", "sequence": 2}, view) + np.testing.assert_allclose(robot._poses[1].numpy(), [5, 0, 0, 0, 0, 0, 1]) + + +def test_scaling_an_asset_is_rejected(): + _, _, manipulation, _ = _manipulation() + with pytest.raises(ValueError, match="Scaling"): + manipulation.apply( + "me", + { + "paths": ["/World/envs/env_0/Robot"], + "gesture": "g", + "action": "update", + "sequence": 1, + "scale": [2, 2, 2], + }, + None, + ) From 8eae1f38df25cdebd685fda50a71602fcd8150b8 Mon Sep 17 00:00:00 2001 From: mtrepte Date: Fri, 6 Nov 2026 01:01:37 +0000 Subject: [PATCH 8/9] Attach gizmo calibration to the Isaac Sim viewer's frames The client draws its transform gizmo only over a frame whose camera and selected transforms it knows. Record each client's selection and attach the viewer camera's calibration, the selected prims' world matrices and the selection pivot to every frame Isaac Lab publishes. --- .../isaac_sim/isaac_sim_host_stage.py | 59 ++++++++++++++++--- .../isaac_sim/isaac_sim_host_world.py | 5 +- .../isaac_sim/isaac_sim_visualizer.py | 59 ++++++++++++++++++- 3 files changed, 113 insertions(+), 10 deletions(-) diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_stage.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_stage.py index 227ca25dfbad..1589405a7351 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_stage.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_stage.py @@ -141,6 +141,31 @@ def remove(self, paths: Sequence[str]) -> None: self._scene.stage.delete_attributes(query, [], ordinal=self._scene.ordinal).wait() +class GizmoSelections: + """Each client's selection, which the host reports for its transform gizmo. + + The host's own gizmo capture also computes the overlay calibration; here Isaac Lab attaches it to each frame it + publishes, so this only records the selections. + """ + + def __init__(self): + self._lock = threading.Lock() + self._selections: dict[str, tuple[str, ...]] = {} + + def select(self, paths: Sequence[str], *, owner: str = "") -> None: + """Record a client's selection; an empty or oversized one has no gizmo.""" + with self._lock: + if 0 < len(paths) <= 128: + self._selections[owner] = tuple(paths) + else: + self._selections.pop(owner, None) + + def selections(self) -> tuple[tuple[str, ...], ...]: + """Return the distinct selections of all clients.""" + with self._lock: + return tuple(dict.fromkeys(self._selections.values())) + + class FrameStore: """Latest viewer frame per render product, in the shape the host's renderer outputs read.""" @@ -149,21 +174,41 @@ def __init__(self): self._frames: dict[str, Any] = {} self._ids = itertools.count(1) - def publish(self, product: str, pixels: np.ndarray, time_ns: int) -> None: - """Make an RGBA ``[H, W, 4]`` uint8 image the latest frame of ``product``.""" + def publish( + self, + product: str, + pixels: np.ndarray, + time_ns: int, + *, + generation: int = 0, + camera: Any = None, + transforms: Sequence[tuple[str, Sequence[float]]] = (), + ) -> None: + """Make an RGBA ``[H, W, 4]`` uint8 image the latest frame of ``product``. + + Args: + product: Render product the image is of. + pixels: The image. + time_ns: Simulation time [ns] of the image. + generation: The host world's generation the image belongs to. + camera: The camera's calibration for the image (an ``isaacsim.viewports.manager.CameraSnapshot``), which + the client needs to draw its transform gizmo over the image. + transforms: World matrices of the selected prims and selection pivots, keyed by path or pivot key. + """ + frame_id = next(self._ids) frame = SimpleNamespace( pixels=pixels, memory="cpu", - frame_id=next(self._ids), + frame_id=frame_id, time_ns=time_ns, source="isaaclab-ovrtx", - generation=0, + generation=generation, input_ordinal=0, output_ordinal=0, - capture_id=None, + capture_id=frame_id, timeline="participant", - transforms=[], - camera=None, + transforms=tuple((key, tuple(map(float, matrix))) for key, matrix in transforms), + camera=camera, depth=None, ) with self._lock: diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py index e07eab63ee63..cb19cbf218b2 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py @@ -31,7 +31,7 @@ ViewportPicker, live_inspection_type, ) -from .isaac_sim_host_stage import FrameStore, SceneWriter +from .isaac_sim_host_stage import FrameStore, GizmoSelections, SceneWriter if TYPE_CHECKING: from isaacsim.application.host import ViewportSpec, World @@ -117,6 +117,8 @@ def __init__( self._renderer = renderer self._manipulation = manipulation self._owners = owners + self.gizmo = GizmoSelections() + """Each client's selection, for the gizmo calibration Isaac Lab attaches to its frames.""" self.redraw = False """Set when a pick or a selection change needs a new frame although the scene did not change.""" self._lock = threading.Lock() @@ -189,6 +191,7 @@ def __call__(self, scene: str, wake: Callable[[], None]) -> World: cameras = {spec.product: spec.camera for spec in self._specs} world.picker = ViewportPicker(self._renderer, cameras, data, on_request=self._request_redraw) world.renderer_selection = SelectionOutline(self._renderer, on_change=self._request_redraw) + world.gizmo_capture = self.gizmo world.authoring = CloneAuthoring(self.authoring, self._copies, self._owners) world.authoring_revision = self.authoring.revision world.authoring_sync = AuthoringSync(self.authoring.stage) diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py index 9450e54dcb95..1689d96c1a20 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py @@ -22,7 +22,7 @@ from pxr import UsdGeom from isaaclab.sim import SimulationContext -from isaaclab.utils.math import quat_from_matrix +from isaaclab.utils.math import matrix_from_quat, quat_from_matrix from isaaclab.visualizers.base_visualizer import BaseVisualizer from isaaclab.visualizers.visualizer_cfg import PerspectiveCameraCfg, VisualizerCfg @@ -285,7 +285,15 @@ def _render_frame(self) -> None: if image is None or not fresh: continue self._shown.add(product) - self._opener.frames.publish(product, np.ascontiguousarray(image.numpy()), time_ns) + camera, transforms = self._calibration(view) + self._opener.frames.publish( + product, + np.ascontiguousarray(image.numpy()), + time_ns, + generation=self._host.simulation.progress.generation, + camera=camera, + transforms=transforms, + ) published = True # A render seals the commands' writes; without one they stay at the open ordinal until the next. if published: @@ -293,6 +301,53 @@ def _render_frame(self) -> None: self._opener.published() self._host.simulation.request_redraw() + def _calibration(self, view: ImageView) -> tuple: + """Describe a just-rendered viewport image for the client's transform gizmo. + + The client draws the gizmo only over an image whose camera and selected transforms it knows. Isaac Lab renders + the image synchronously from the stage it just sealed, so the stage's current matrices match it. + + Returns: + The camera calibration (an ``isaacsim.viewports.manager.CameraSnapshot``, or ``None`` if unavailable) and + the world matrices of the selected prims and selection pivots, keyed by path or pivot key. + """ + from isaacsim.common.interfaces import Query + from isaacsim.viewports.manager import CameraSnapshot + + context, camera = self._opener._context, view.camera + + def world(path: str) -> np.ndarray: + return np.asarray(context.read(Query(path), "omni:fabric:worldMatrix"), dtype=float).reshape(4, 4) + + try: + height, width = camera.image_shape + intrinsics = camera.data.intrinsic_matrices.torch[0].detach().cpu().numpy() + near, far = camera.cfg.spawn.clipping_range + projection = np.zeros((4, 4)) + projection[0, 0] = 2.0 * intrinsics[0, 0] / width + projection[1, 1] = 2.0 * intrinsics[1, 1] / height + projection[2, 2] = -(far + near) / (far - near) + projection[2, 3] = -2.0 * far * near / (far - near) + projection[3, 2] = -1.0 + # The sensor's pose is the one the renderer used; the snapshot takes the world-to-camera matrix, with the + # camera looking along -Z and Y up (the OpenGL convention). + camera_to_world = np.eye(4) + camera_to_world[:3, :3] = matrix_from_quat(camera.data.quat_w_opengl.torch[:1]).cpu().numpy()[0] + camera_to_world[:3, 3] = camera.data.pos_w.torch[0].detach().cpu().numpy() + snapshot = CameraSnapshot(np.linalg.inv(camera_to_world), projection, width, height, 1.0) + except Exception: # noqa: BLE001 - without calibration the image simply shows no gizmo + return None, () + transforms = [] + for paths in self._opener.gizmo.selections(): + try: + matrices = {path: world(path) for path in paths} + transforms.extend((path, matrix.reshape(-1)) for path, matrix in matrices.items()) + frame = self._opener._world.authoring.selection_frame(list(paths), matrices) + transforms.append((frame["pivot_key"], np.asarray(frame["matrix"], dtype=float).reshape(-1))) + except Exception: # noqa: BLE001 - a selection that cannot be framed shows no gizmo + continue + return snapshot, tuple(dict(transforms).items()) + def _play(self) -> None: """Put the viewer's transport controls in Playing.""" from isaacsim.application.host import Command, TimeTarget From 4c0762f13d59b8300e08d239583afdd063b8733b Mon Sep 17 00:00:00 2001 From: mtrepte Date: Fri, 6 Nov 2026 01:17:18 +0000 Subject: [PATCH 9/9] Move Isaac Lab assets through Isaac Sim's own live manipulation Replace the viewer's own gesture controller with Isaac Sim's SelectionManipulation and native LiveManipulation, with Isaac Lab supplying only the pose backend through its assets. Isaac Sim's selection manipulation reads world matrices from the stage through the view Isaac Lab drains with. --- .../isaac_sim/isaac_sim_host_world.py | 6 +- .../isaac_sim/isaac_sim_manipulation.py | 229 +++++++----------- .../isaac_sim/isaac_sim_visualizer.py | 9 +- .../test/test_isaac_sim_visualizer.py | 101 +++----- 4 files changed, 131 insertions(+), 214 deletions(-) diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py index cb19cbf218b2..ff404f8ead0d 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_host_world.py @@ -84,7 +84,7 @@ class HostWorldOpener: meters_per_unit: Stage units [m]. copies: Isaac Lab's environment clones as ``(source, targets)``, so the property pane describes clones. renderer: Isaac Lab's OVRTX renderer of the viewer cameras, which answers picks and outlines the selection. - manipulation: Creates the live manipulation of Isaac Lab's assets from the world's authoring session. + manipulation: Creates the live manipulation of Isaac Lab's assets for a world and its authoring session. owners: Resolves a prim to the Isaac Lab asset instance that owns it, or ``None``. """ @@ -100,7 +100,7 @@ def __init__( meters_per_unit: float, copies: Sequence[tuple[str, Sequence[str]]], renderer: Any, - manipulation: Callable[[Any], Any], + manipulation: Callable[[Any, Any], Any], owners: Callable[[str], Any], ): from isaacsim.viewports.authoring import AuthoringSession @@ -196,7 +196,7 @@ def __call__(self, scene: str, wake: Callable[[], None]) -> World: world.authoring_revision = self.authoring.revision world.authoring_sync = AuthoringSync(self.authoring.stage) # The transform gizmo moves Isaac Lab's assets; Isaac Lab drains the gestures with the other commands. - world.manipulation = self._manipulation(world.authoring) + world.manipulation = self._manipulation(world, world.authoring) manipulation = SceneCommands(rate=self._rate, on_submit=wake) manipulation.add_reader("holds", world.manipulation.tick) world.manipulation_worker = manipulation diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_manipulation.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_manipulation.py index 31b0f04433df..071cbdba290e 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_manipulation.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_manipulation.py @@ -5,17 +5,19 @@ """Move and rotate Isaac Lab assets with the Isaac Sim 7 viewer's transform gizmo. -The host's own live manipulation moves free rigid bodies through Isaac Sim physics. Isaac Lab owns the physics here, -so this controller applies the gizmo's poses to Isaac Lab's assets instead: selecting any prim of an articulation or a -rigid object moves that asset in its environment, by writing its root link pose (and zero velocity) and updating the +The gestures run through Isaac Sim's own live manipulation: its selection manipulation moves a group rigidly around +the selection's pivot, and its native controller leases each moved body, orders the gesture's commands and restores +the starting pose on cancel. Isaac Sim moves free rigid bodies through Isaac Sim physics; here Isaac Lab owns the +physics, so :class:`AssetPoseBackend` supplies the poses through Isaac Lab's assets instead: selecting any prim of an +articulation or a rigid object moves that asset instance, by writing its root link pose at rest and updating the kinematics so the change shows while the simulation is paused. Prims that no Isaac Lab asset owns (terrain, lights, -sensors) are not movable, and scaling is not supported, as in the host's live manipulation. +sensors) are not movable, and scaling is not supported, as in Isaac Sim's live manipulation. """ from __future__ import annotations import re -from collections.abc import Callable +from collections.abc import Callable, Iterable from typing import Any, NamedTuple import numpy as np @@ -55,157 +57,110 @@ def __call__(self, path: str) -> Owner | None: owner = None for pattern, asset in self._patterns: match = pattern.match(path) - env = re.search(r"/env_(\d+)(/|$)", path) if match else None if match: + env = re.search(r"/env_(\d+)(/|$)", path) owner = Owner(asset, int(env.group(1)) if env else 0, match.group(1)) break self._cache[path] = owner return self._cache[path] -class MovablePaths: - """The host's set of live-movable paths: every prim of an Isaac Lab asset.""" - - def __init__(self, owners: AssetOwners): - self._owners = owners - - def __contains__(self, path: object) -> bool: - return isinstance(path, str) and self._owners(path) is not None - - -def _rotation(orientation: Any) -> np.ndarray: - """Return the row-vector rotation matrix of an xyzw quaternion.""" - from pxr import Gf - - x, y, z, w = map(float, orientation) - return np.asarray(Gf.Matrix3d(Gf.Quatd(w, Gf.Vec3d(x, y, z)))) +class AssetPoseBackend: + """Isaac Sim's live-manipulation pose backend, applied to Isaac Lab's asset instances. - -def _orientation(rotation: np.ndarray) -> list[float]: - """Return the xyzw quaternion of a row-vector rotation matrix.""" - from pxr import Gf - - quat = Gf.Matrix3d(*rotation.reshape(-1).tolist()).ExtractRotation().GetQuat() - return [*quat.GetImaginary(), quat.GetReal()] - - -class AssetManipulation: - """The host's live manipulation, applied to Isaac Lab's assets. - - Implements what the host's editing routes use: ``supports_groups``, ``backend.paths``, :meth:`apply` and - :meth:`tick`. Commands run on Isaac Lab's thread when it drains the host's queues, so the writes are ordinary - Isaac Lab state writes between simulation steps. + Implements ``isaacsim.viewports.authoring.PoseBackend`` (``capture``, ``hold``, ``restore``, ``flush``) and the + ``paths`` and ``world`` the host's selection manipulation reads. Isaac Lab drains the gestures on its own thread, so + these are ordinary Isaac Lab state writes between simulation steps. Args: owners: Resolves prims to Isaac Lab asset instances. - authoring: The host's authoring session (clone aware), for the selection's pivot. + bodies: Prim paths whose live world matrices the stage holds (Isaac Lab's rigid bodies); with the asset roots + they form :attr:`paths`, which the selection manipulation uses to read world matrices. + roots: Every asset instance root, the paths a gesture moves. forward: Updates kinematics after pose writes without stepping physics. """ - supports_groups = True - - def __init__(self, owners: AssetOwners, authoring: Any, forward: Callable[[], None]): + def __init__(self, owners: AssetOwners, bodies: Iterable[str], roots: Iterable[str], forward: Callable[[], None]): self._owners = owners - self._authoring = authoring self._forward = forward - self.backend = type("Backend", (), {"paths": MovablePaths(owners)})() - self._groups: dict[tuple[str, str], dict[str, Any]] = {} - - def tick(self, view: Any) -> dict: - """Report the paths held by an unfinished gesture.""" - return {"held": sorted(root for group in self._groups.values() for root in group["roots"])} - - def apply(self, owner: str, body: dict, view: Any) -> dict: - """Apply one ordered gesture command (begin, update, heartbeat, end or cancel) to the selection. - - Args: - owner: Client identity. - body: Gesture with ``paths``, ``action``, ``sequence`` and, for updates, the pivot's new world pose. - view: The view the command runs against, for the selection's live world matrices. - - Returns: - The selection pivot's world position and xyzw orientation. - - Raises: - ValueError: The selection holds a prim no Isaac Lab asset owns, the gesture expired or scales. - """ - if "scale" in body: - raise ValueError("Scaling Isaac Lab assets is unsupported") - paths = body.get("paths") or [body["path"]] - key = (owner, body["gesture"]) - action, sequence = body["action"], body["sequence"] - if action == "begin": - return self._begin(key, paths, sequence, view) - group = self._groups.get(key) - if group is None or group["paths"] != paths: - raise ValueError("The gesture expired or belongs to another client") - if sequence <= group["sequence"]: - raise ValueError("Manipulation sequence must increase") - group["sequence"] = sequence - if action == "update": - self._move(group, np.asarray(body["position"], dtype=float), body["orientation"]) - elif action == "cancel": - for instance, (position, orientation) in zip(group["owners"], group["initial"]): - self._write(instance, position, orientation) + self.paths = frozenset((*bodies, *roots)) + self.world: Any = None + """The host world, whose ``simulation.fail`` the selection manipulation reports unrecoverable errors to.""" + self._dirty = False + + def capture(self, path: str) -> tuple[np.ndarray, ...]: + """Return the instance's root link position ``[1, 3]``, xyzw orientation ``[1, 4]`` and velocity ``[1, 6]``.""" + instance = self._instance(path) + data = instance.asset.data + pose = data.root_link_pose_w.torch[instance.env_id].detach().cpu().numpy().astype(np.float64) + velocity = data.root_link_vel_w.torch[instance.env_id].detach().cpu().numpy().astype(np.float64) + return pose[None, :3].copy(), pose[None, 3:7].copy(), velocity[None, :].copy() + + def hold(self, path: str, position: np.ndarray, orientation: np.ndarray, view: Any) -> None: + """Place the instance's root link at rest.""" + self._write(self._instance(path), position, orientation, np.zeros((1, 6))) + + def restore(self, path: str, captured: Any, view: Any) -> None: + """Restore the captured pose and velocity after a cancelled gesture.""" + position, orientation, velocity = captured + self._write(self._instance(path), position, orientation, velocity) + + def flush(self, view: Any) -> None: + """Update kinematics once after this activation's pose writes, so they show while paused.""" + if self._dirty: + self._dirty = False self._forward() - if action in ("cancel", "end"): - del self._groups[key] - return {"position": group["position"], "orientation": group["orientation"]} - - def _begin(self, key: tuple[str, str], paths: list[str], sequence: int, view: Any) -> dict: - if key in self._groups: - raise ValueError("This gesture already began; use a new gesture identifier") - matrices = {} - for path in paths: - with_matrix = view.read([path], "omni:fabric:worldMatrix") - matrices[path] = np.asarray(with_matrix, dtype=float).reshape(4, 4) - frame = self._authoring.selection_frame(paths, matrices) - instances: list[Owner] = [] - for root in frame["roots"]: - instance = self._owners(root) - if instance is None: - raise ValueError(f"Only Isaac Lab assets (articulations, rigid objects) can be moved; not {root}") - if all(instance.asset is not other.asset or instance.env_id != other.env_id for other in instances): - instances.append(instance) - held = {root for group in self._groups.values() for root in group["roots"]} - if held.intersection(instance.root for instance in instances): - raise ValueError("A selected asset is already being moved") - pivot = np.asarray(frame["matrix"], dtype=float).reshape(4, 4) - initial = [] - for instance in instances: - pose = instance.asset.data.root_link_pose_w.torch[instance.env_id].detach().cpu().numpy().astype(float) - initial.append((pose[:3], pose[3:7])) - self._groups[key] = { - "paths": paths, - "roots": [instance.root for instance in instances], - "owners": instances, - "initial": initial, - "pivot": pivot, - "sequence": sequence, - "position": pivot[3, :3].tolist(), - "orientation": _orientation(pivot[:3, :3]), - } - return {"position": self._groups[key]["position"], "orientation": self._groups[key]["orientation"]} - - def _move(self, group: dict[str, Any], position: np.ndarray, orientation: Any) -> None: - """Move every asset in the group rigidly with the pivot's new pose.""" - pivot = group["pivot"] - # Row-vector rotations: the change from the pivot's start to its new orientation. - delta = pivot[:3, :3].T @ _rotation(orientation) - for instance, (start, start_orientation) in zip(group["owners"], group["initial"]): - moved = (start - pivot[3, :3]) @ delta + position - self._write(instance, moved, _orientation(_rotation(start_orientation) @ delta)) - self._forward() - group["position"], group["orientation"] = position.tolist(), list(map(float, orientation)) - - @staticmethod - def _write(instance: Owner, position: Any, orientation: Any) -> None: - """Place an asset instance's root link, at rest.""" + + def _instance(self, path: str) -> Owner: + instance = self._owners(path) + if instance is None or instance.root != path: + raise ValueError(f"Only Isaac Lab asset instances (articulations, rigid objects) can be moved; not {path}") + return instance + + def _write(self, instance: Owner, position: Any, orientation: Any, velocity: Any) -> None: asset = instance.asset device = asset.data.root_link_pose_w.torch.device - pose = torch.tensor([[*map(float, position), *map(float, orientation)]], dtype=torch.float32, device=device) + pose = np.concatenate([np.asarray(position, float).reshape(3), np.asarray(orientation, float).reshape(4)]) env_ids = torch.tensor([instance.env_id], dtype=torch.int32, device=device) - asset.write_root_link_pose_to_sim_index(root_pose=pose, env_ids=env_ids) + asset.write_root_link_pose_to_sim_index( + root_pose=torch.tensor(pose[None], dtype=torch.float32, device=device), env_ids=env_ids + ) asset.write_root_link_velocity_to_sim_index( - root_velocity=torch.zeros((1, 6), dtype=torch.float32, device=device), env_ids=env_ids + root_velocity=torch.tensor(np.asarray(velocity, float).reshape(1, 6), dtype=torch.float32, device=device), + env_ids=env_ids, ) + self._dirty = True + + +def _stage_world_matrix(view: Any, path: str, bodies: Any = None) -> np.ndarray: + """Read a prim's world matrix from the stage through any view, as ``world_matrix`` does through a native one.""" + return np.asarray(view.read([path], "omni:fabric:worldMatrix"), dtype=np.float64).reshape(4, 4) + + +def asset_manipulation( + world: Any, authoring: Any, owners: AssetOwners, bodies: Iterable[str], forward: Callable[[], None] +) -> Any: + """Build Isaac Sim's live manipulation of Isaac Lab's asset instances for a host world. + + Args: + world: The host world. + authoring: The world's (clone aware) authoring session, which frames selections of Isaac Lab assets. + owners: Resolves prims to Isaac Lab asset instances. + bodies: Isaac Lab's rigid body prim paths. + forward: Updates kinematics without stepping physics. + + Returns: + Isaac Sim's ``SelectionManipulation`` over a native ``LiveManipulation`` of :class:`AssetPoseBackend`. + """ + from isaacsim.application.host.impl import selection_manipulation + from isaacsim.viewports.authoring import LiveManipulation + + # Isaac Sim's selection manipulation reads world matrices with a helper that needs a native simulation view, and + # Isaac Lab drains the host's commands with a Python one. The stage holds every prim's world matrix, so read it + # there. Open point for Isaac Sim: a world-matrix helper that accepts any view would make this unnecessary. + selection_manipulation.world_matrix = _stage_world_matrix + bodies = tuple(bodies) + roots = {instance.root for instance in map(owners, bodies) if instance is not None} + backend = AssetPoseBackend(owners, bodies, roots, forward) + backend.world = world + return selection_manipulation.SelectionManipulation(LiveManipulation(backend), authoring) diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py index 1689d96c1a20..169ce2dd8696 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/isaac_sim/isaac_sim_visualizer.py @@ -133,7 +133,7 @@ def _start_host(self, sim: SimulationContext, renderer) -> None: from .isaac_sim_host_stage import FrameStore, HostStage, SceneWriter from .isaac_sim_host_world import HostWorldOpener - from .isaac_sim_manipulation import AssetManipulation, AssetOwners + from .isaac_sim_manipulation import AssetOwners, asset_manipulation scene = renderer.scene if not isinstance(getattr(scene, "stage_owner", None), HostStage): @@ -152,7 +152,8 @@ def _start_host(self, sim: SimulationContext, renderer) -> None: view.camera.cfg.prim_path: (lambda matrix, view=view: self._move_camera(view, matrix)) for view in self._viewports.values() } - owners = AssetOwners(sim.get_scene_data_provider().get_interactive_scene()) + provider = sim.get_scene_data_provider() + owners = AssetOwners(provider.get_interactive_scene()) self._opener = HostWorldOpener( scene_file, scene.stage_owner.context, @@ -164,7 +165,9 @@ def _start_host(self, sim: SimulationContext, renderer) -> None: UsdGeom.GetStageMetersPerUnit(sim.stage), scene.clone_copies, renderer, - lambda authoring: AssetManipulation(owners, authoring, sim.forward), + lambda world, authoring: asset_manipulation( + world, authoring, owners, provider.backend.transform_paths, sim.forward + ), owners, ) client_roots = client_roots_for_backend("web") diff --git a/source/isaaclab_visualizers/test/test_isaac_sim_visualizer.py b/source/isaaclab_visualizers/test/test_isaac_sim_visualizer.py index 1b1f324d47ff..397ae688c7d5 100644 --- a/source/isaaclab_visualizers/test/test_isaac_sim_visualizer.py +++ b/source/isaaclab_visualizers/test/test_isaac_sim_visualizer.py @@ -101,6 +101,7 @@ def __init__(self, prim_path: str, poses): self._poses = torch.tensor(poses, dtype=torch.float32) self.data = type("Data", (), {})() self.data.root_link_pose_w = type("Pose", (), {"torch": self._poses})() + self.data.root_link_vel_w = type("Velocity", (), {"torch": torch.zeros((len(poses), 6))})() self.velocities = [] def write_root_link_pose_to_sim_index(self, *, root_pose, env_ids): @@ -110,88 +111,46 @@ def write_root_link_velocity_to_sim_index(self, *, root_velocity, env_ids): self.velocities.append((env_ids.tolist(), root_velocity.tolist())) -def _manipulation(): +def _backend(): from types import SimpleNamespace - from isaaclab_visualizers.isaac_sim.isaac_sim_host_adapter import CloneAuthoring - from isaaclab_visualizers.isaac_sim.isaac_sim_manipulation import AssetManipulation, AssetOwners + from isaaclab_visualizers.isaac_sim.isaac_sim_manipulation import AssetOwners, AssetPoseBackend robot = _FakeAsset("/World/envs/env_.*/Robot", [[0, 0, 0, 0, 0, 0, 1], [5, 0, 0, 0, 0, 0, 1]]) - scene = SimpleNamespace(articulations={"robot": robot}, rigid_objects={}) - owners = AssetOwners(scene) + owners = AssetOwners(SimpleNamespace(articulations={"robot": robot}, rigid_objects={})) forwards = [] - authoring = CloneAuthoring(session=None, copies=(), owners=owners) - return robot, owners, AssetManipulation(owners, authoring, lambda: forwards.append(1)), forwards + bodies = ["/World/envs/env_0/Robot/pelvis", "/World/envs/env_1/Robot/pelvis"] + roots = ["/World/envs/env_0/Robot", "/World/envs/env_1/Robot"] + return robot, owners, AssetPoseBackend(owners, bodies, roots, lambda: forwards.append(1)), forwards -class _PoseView: - """World matrices of selected prims, as the host's view reads them.""" - - def __init__(self, positions: dict[str, tuple[float, float, float]]): - self._positions = positions - - def read(self, paths, attribute): - matrix = np.eye(4) - matrix[3, :3] = self._positions[paths[0]] - return matrix.reshape(1, 16) - - -def test_any_prim_of_an_asset_moves_its_instance(): - _, owners, manipulation, _ = _manipulation() +def test_any_prim_of_an_asset_resolves_to_its_instance(): + _, owners, backend, _ = _backend() owner = owners("/World/envs/env_1/Robot/torso_link/visuals/mesh_0") assert owner.env_id == 1 and owner.root == "/World/envs/env_1/Robot" assert owners("/World/ground") is None - assert "/World/envs/env_1/Robot/pelvis" in manipulation.backend.paths - assert "/World/ground" not in manipulation.backend.paths - - -def test_gizmo_moves_and_turns_the_owning_instance_at_rest(): - robot, _, manipulation, forwards = _manipulation() - mesh = "/World/envs/env_1/Robot/torso_link/visuals/mesh_0" - view = _PoseView({mesh: (5.0, 0.0, 1.0)}) - gesture = {"paths": [mesh], "gesture": "g"} - begun = manipulation.apply("me", {**gesture, "action": "begin", "sequence": 0}, view) - assert begun["position"] == [5.0, 0.0, 1.0] - assert manipulation.tick(view)["held"] == ["/World/envs/env_1/Robot"] - # Raise the pivot 1 m and turn 90 degrees about z: the root, 1 m below the pivot, follows rigidly. - turn = [0.0, 0.0, float(np.sin(np.pi / 4)), float(np.cos(np.pi / 4))] - manipulation.apply( - "me", {**gesture, "action": "update", "sequence": 1, "position": [5.0, 0.0, 2.0], "orientation": turn}, view - ) - np.testing.assert_allclose(robot._poses[1, :3].numpy(), [5.0, 0.0, 1.0], atol=1e-6) - np.testing.assert_allclose(np.abs(robot._poses[1, 3:].numpy()), np.abs(turn), atol=1e-6) + # The selection manipulation reads body world matrices and moves instance roots. + assert {"/World/envs/env_1/Robot/pelvis", "/World/envs/env_1/Robot"} <= backend.paths + + +def test_pose_backend_places_the_instance_at_rest_and_restores_it(): + robot, _, backend, forwards = _backend() + root = "/World/envs/env_1/Robot" + captured = backend.capture(root) + np.testing.assert_allclose(captured[0], [[5, 0, 0]]) + turn = np.array([[0.0, 0.0, np.sin(np.pi / 4), np.cos(np.pi / 4)]]) + backend.hold(root, np.array([[5.0, 0.0, 1.0]]), turn, view=None) + backend.flush(view=None) + np.testing.assert_allclose(robot._poses[1].numpy(), [5, 0, 1, *turn[0]], atol=1e-6) np.testing.assert_allclose(robot._poses[0].numpy(), [0, 0, 0, 0, 0, 0, 1]) - assert robot.velocities[-1] == ([1], [[0.0] * 6]) and forwards - manipulation.apply("me", {**gesture, "action": "end", "sequence": 2}, view) - assert manipulation.tick(view)["held"] == [] - - -def test_cancel_restores_the_starting_pose(): - robot, _, manipulation, _ = _manipulation() - mesh = "/World/envs/env_1/Robot/pelvis" - view = _PoseView({mesh: (5.0, 0.0, 0.0)}) - gesture = {"paths": [mesh], "gesture": "g"} - manipulation.apply("me", {**gesture, "action": "begin", "sequence": 0}, view) - manipulation.apply( - "me", - {**gesture, "action": "update", "sequence": 1, "position": [9.0, 9.0, 9.0], "orientation": [0, 0, 0, 1]}, - view, - ) - manipulation.apply("me", {**gesture, "action": "cancel", "sequence": 2}, view) + assert robot.velocities[-1] == ([1], [[0.0] * 6]) and forwards == [1] + backend.restore(root, captured, view=None) np.testing.assert_allclose(robot._poses[1].numpy(), [5, 0, 0, 0, 0, 0, 1]) -def test_scaling_an_asset_is_rejected(): - _, _, manipulation, _ = _manipulation() - with pytest.raises(ValueError, match="Scaling"): - manipulation.apply( - "me", - { - "paths": ["/World/envs/env_0/Robot"], - "gesture": "g", - "action": "update", - "sequence": 1, - "scale": [2, 2, 2], - }, - None, - ) +def test_only_instance_roots_are_moved(): + _, _, backend, _ = _backend() + with pytest.raises(ValueError, match="asset instances"): + backend.hold("/World/envs/env_1/Robot/pelvis", np.zeros((1, 3)), np.array([[0, 0, 0, 1.0]]), view=None) + with pytest.raises(ValueError, match="asset instances"): + backend.capture("/World/ground")