From cd9513cdf218a18bcd291bf3d3d35599d44589a1 Mon Sep 17 00:00:00 2001 From: nblauch Date: Mon, 23 Nov 2026 19:34:57 -0800 Subject: [PATCH 01/11] Add viewer gaze and foveation controls for foveated cameras Every foveated camera adds a collapsing section to the Newton viewer's side panel with gaze tilt and pan sliders that follow the camera's gaze, a center button, and a discrete log-spaced cmf_a selector (viewer_gaze_controls, viewer_cmf_a_values). Newton cameras with a fixed sample count change cmf_a at runtime through FoveatedCamera.set_cmf_a; other renderers show it as fixed. The foveated camera example puts the eye in the viewer's scene-camera slot, covers the view with the sphere and retina comparison, and steers the gaze by dragging or with I/J/K/L. The comparison redraws only when the viewer shows a new eye frame and reuses that frame, so OVRTX sampling noise no longer makes it flicker in a still scene. --- .../experimental-features/foveated_camera.rst | 23 +- examples/sensors/foveated_camera.py | 201 +++++++++++++----- ...at-isaaclab-fovi-viewer-controls.added.rst | 5 + .../feat-isaaclab-fovi-viewer-controls.minor | 0 .../isaaclab_fovi/sensors/foveated_camera.py | 109 +++++++++- .../sensors/foveated_camera_cfg.py | 7 + .../sensors/foveated_newton_camera.py | 7 + .../isaaclab_fovi/sensors/gaze_controls.py | 110 ++++++++++ .../test/foveated_render_cases.py | 27 +++ source/isaaclab_fovi/test/test_camera_gaze.py | 126 +++++++++++ .../test/test_foveated_camera_render.py | 4 + .../test/test_foveated_camera_render_ovrtx.py | 4 + 12 files changed, 551 insertions(+), 72 deletions(-) create mode 100644 source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-viewer-controls.added.rst create mode 100644 source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-viewer-controls.minor create mode 100644 source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py diff --git a/docs/source/experimental-features/foveated_camera.rst b/docs/source/experimental-features/foveated_camera.rst index a37614cb0ef5..60bf1ffdab8f 100644 --- a/docs/source/experimental-features/foveated_camera.rst +++ b/docs/source/experimental-features/foveated_camera.rst @@ -15,12 +15,12 @@ several minutes with a cold shader cache: uv run --extra fovi [--extra ovrtx] isaaclab example foveated-camera [renderer=ovrtx] -The Newton viewer shows the retina. A panel shows the fisheye on a curved viewing sphere beside a magnified retina: -the green lens boundary follows the camera mount, and the blue gaze circle and sampling grid show the magnified -retina's coverage. Use WASD or the arrow keys to move and Q/E to lower or raise the camera. I/K tilt the gaze and J/L -pan it; O/U magnify the panel's retina and zoom back out; H shows or hides the viewer controls. Pass -``--target power_drill`` to start fixating the drill, or ``env.scene.eye.cmf_a_deg=1000`` for a matched, nearly -uniform retina. +The Newton viewer shows the retina, covered at launch by a window that shows the fisheye on a curved viewing sphere +beside the retina: the green lens boundary follows the camera mount, and the blue gaze circle and sampling grid show the retina's coverage. Use WASD or +the arrow keys to move the camera and Q/E to lower or raise it. Drag with the left mouse button, or press I/K and J/L, to steer the gaze; the +side panel's sliders follow the gaze and set it, and on Newton its foveation slider steps the CMF constant through +``env.scene.eye.viewer_cmf_a_values``. H shows or hides the viewer controls. Pass ``--target power_drill`` to start +fixating the drill. .. figure:: ../_static/overview/sensors/foveated_camera_overview.jpg :alt: A retina behind a 180-degree fisheye lens on the viewing sphere, and its rendered images at two fixations. @@ -101,8 +101,15 @@ Use :attr:`~sensors.FoveatedCameraCfg.retinal_window_fraction` to shrink this wi :attr:`~sensors.FoveatedCameraCfg.image_rotation_deg` to compensate for mount roll. Call ``camera.set_gaze_angles(angles)`` with shape ``(num_envs, 2)`` in tilt, pan order and in degrees. -Positive tilt looks up and positive pan looks left. :meth:`~sensors.FoveatedCamera.get_world_poses` -reports the mount pose. Enable :attr:`~sensors.FoveatedCameraCfg.mask_to_sensor_fov` to zero rays that fall +Positive tilt looks up and positive pan looks left. In a Newton viewer, each foveated camera also adds tilt and pan +sliders to the side panel, which follow its gaze and set it in every environment; a gaze action overrides them each +step. A foveation slider beside them switches the CMF constant among +:attr:`~sensors.FoveatedCameraCfg.viewer_cmf_a_values` with :meth:`~sensors.FoveatedCamera.set_cmf_a`, which +re-samples the retina in place. That works on Newton for styles whose sample count does not depend on the constant, +the warped-Cartesian and ``_fixn`` isotropic ones; OVRTX and Isaac RTX read their lens textures once, so there the +slider shows the constant as fixed. Set :attr:`~sensors.FoveatedCameraCfg.viewer_gaze_controls` to ``False`` to leave a +camera out. +:meth:`~sensors.FoveatedCamera.get_world_poses` reports the mount pose. Enable :attr:`~sensors.FoveatedCameraCfg.mask_to_sensor_fov` to zero rays that fall outside the physical image as the gaze moves. Pooling diff --git a/examples/sensors/foveated_camera.py b/examples/sensors/foveated_camera.py index d991cfe032e8..cbf99c3973c0 100644 --- a/examples/sensors/foveated_camera.py +++ b/examples/sensors/foveated_camera.py @@ -5,10 +5,12 @@ """Explore a cluttered scene through the experimental foveated camera. -The viewer shows the camera's retina; a panel shows the gaze on the viewing sphere beside a magnified retina. -Use WASD or the arrow keys to move, and Q/E to lower or raise the camera. -I/K tilt the gaze and J/L pan it. O/U magnify the panel's retina and zoom back out. -Press H to show or hide the viewer controls. +The viewer shows the camera's retina, covered at launch by a window that shows the gaze on the viewing sphere beside +the retina; move or resize that window to see the viewer's own view of the retina. +Use WASD or the arrow keys to move the camera, and Q/E to lower or raise it. +Drag with the left mouse button, or press I/K and J/L, to steer the gaze. +The side panel's sliders follow the gaze and set it, and step the foveation (cmf_a) through +``env.scene.eye.viewer_cmf_a_values`` on Newton. Press H to show or hide the viewer controls. Use --target to choose where the retina looks at launch. .. code-block:: bash @@ -224,8 +226,8 @@ def gaze_toward(centre: tuple[float, float, float], camera_cfg: FoveatedCameraCf def camera_comparison( camera: FoveatedCamera, overview: FoveatedCamera -) -> tuple[Callable[[], None], Callable[[torch.Tensor, float], wp.array]]: - """Draw the lens and gaze on the viewing sphere used in the docs, beside the retina magnified by a zoom.""" +) -> tuple[Callable[[], None], Callable[[torch.Tensor], wp.array]]: + """Draw the lens and gaze on the viewing sphere used in the docs, beside the retina.""" size, gap = PREVIEW_SIZE, 6 header_height = 28 image_width = 2 * size + gap @@ -234,13 +236,12 @@ def camera_comparison( draw = ImageDraw.Draw(header) font = ImageFont.load_default(size=17) draw.text((8, header_height / 2), "Viewing sphere", font=font, fill="white", anchor="lm") - draw.text((size + gap + 8, header_height / 2), "FoveatedCamera view", font=font, fill="white", anchor="lm") + draw.text((size + gap + 8, header_height / 2), "Retina", font=font, fill="white", anchor="lm") labels = torch.from_numpy(np.array(header)).to(camera.device) divider = labels[:1, size : size + gap].expand(size, -1, -1) - displayed_zoom = None + displayed_cmf_a = None coords = overview.sampling_coords - retina_coords = camera.sampling_coords pixels = torch.arange(size, device=camera.device) center = (pixels + 0.5) * (2 / size) - 1 screen = torch.stack(torch.meshgrid(center, center, indexing="xy"), dim=-1) @@ -257,21 +258,21 @@ def camera_comparison( def prepare() -> None: overview.set_world_poses(*camera.get_world_poses(convention="opengl"), convention="opengl") - if camera.supports_batch_update and overview.supports_batch_update: - camera.update_batch((camera, overview), 0.0) - - def compose(retina: torch.Tensor, zoom: float) -> wp.array: - """The panel for one RGB retina image (H, W, 3): the viewing sphere, then the retina magnified by ``zoom``.""" - nonlocal displayed_zoom - if zoom != displayed_zoom: - draw.rectangle((image_width - 68, 0, image_width - 1, header_height - 1), fill=header_color) - draw.text((image_width - 8, header_height / 2), f"{zoom:.2f}x", font=font, fill="white", anchor="rm") + if overview.supports_batch_update: + overview.update_batch((overview,), 0.0) + + def compose(retina: torch.Tensor) -> wp.array: + """The view for one RGB retina image (H, W, 3): the viewing sphere, then the retina.""" + nonlocal displayed_cmf_a + # The retina may change its foveation at runtime, so its coordinates are read for every frame. + retina_coords = camera.sampling_coords + if camera.cfg.cmf_a_deg != displayed_cmf_a: + displayed_cmf_a = camera.cfg.cmf_a_deg + draw.rectangle((image_width - 140, 0, image_width - 1, header_height - 1), fill=header_color) + text = f"cmf_a {displayed_cmf_a:g} deg" + draw.text((image_width - 8, header_height / 2), text, font=font, fill="white", anchor="rm") labels.copy_(torch.from_numpy(np.array(header))) - displayed_zoom = zoom detail = torch.cat((retina, torch.full_like(retina[..., :1], 255)), dim=-1) - height, width = detail.shape[:2] - crop_h, crop_w = max(1, round(height / zoom)), max(1, round(width / zoom)) - top, left = (height - crop_h) // 2, (width - crop_w) // 2 # Transform the fixed observer into the live camera frame, independently of active gaze. position, orientation = camera.get_world_poses(convention="opengl") @@ -309,7 +310,7 @@ def compose(retina: torch.Tensor, zoom: float) -> wp.array: radius = torch.linalg.vector_norm(2 * grid - 1, dim=-1) else: radius = torch.acos(alignment.clamp(-1, 1)) / math.radians(retina_coords.fov / 2) - in_retina = radius <= min(crop_h / height, crop_w / width) + in_retina = radius <= 1.0 # Match the docs: an untextured near shell, a faded peripheral texture, and independent lens/gaze edges. texel = 0.72 * rgb + 0.28 * 255 @@ -331,8 +332,8 @@ def compose(retina: torch.Tensor, zoom: float) -> wp.array: full = torch.where(outline(hit)[..., None], lens_color, full) full = torch.cat((full.to(torch.uint8), torch.full_like(texture[..., :1], 255)), dim=-1) - crop = detail[top : top + crop_h, left : left + crop_w].permute(2, 0, 1).unsqueeze(0) - detail = torch.nn.functional.interpolate(crop, size=(size, size), mode="nearest")[0].permute(1, 2, 0) + detail = detail.permute(2, 0, 1).unsqueeze(0) + detail = torch.nn.functional.interpolate(detail, size=(size, size), mode="nearest")[0].permute(1, 2, 0) detail[..., :3].masked_fill_(~retina_disc[..., None], 0) return wp.from_torch(torch.cat((labels, torch.cat((full, divider, detail), dim=1)), dim=0)) @@ -340,11 +341,109 @@ def compose(retina: torch.Tensor, zoom: float) -> wp.array: def newton_window(visualizer): - """The window of a Newton visualizer, which shows the example's panel. Isaac Lab's Newton raycast example reaches it + """The window of a Newton visualizer, which shows the example's view. Isaac Lab's Newton raycast example reaches it the same way.""" return visualizer._viewer +COMPARISON_WINDOW = "Foveated camera" +"""Title of the window that shows the viewing sphere beside the retina.""" + + +def comparison_image_hovered(imgui, edge: float = 8.0) -> bool: + """Whether the mouse is inside the comparison window's image: below its title bar and away from its resize edges.""" + window = imgui.get_current_context().hovered_window + if window is None or str(window.root_window.name) != COMPARISON_WINDOW: + return False + root = window.root_window + mouse = imgui.get_io().mouse_pos + left, top = root.pos.x + edge, root.title_bar_rect().max.y + right, bottom = root.pos.x + root.size.x - edge, root.pos.y + root.size.y - edge + return left <= mouse.x <= right and top <= mouse.y <= bottom + + +def cover_view_with_comparison(frames: int = 30): + """A side-panel callback that stretches the comparison window over the whole view beside the panel for its first + ``frames`` frames, then leaves its size and position to the user.""" + remaining = [frames] + + def cover(imgui) -> None: + if remaining[0] <= 0: + return + remaining[0] -= 1 + # The callback draws inside the side panel, whose right edge is where the view begins. + viewport = imgui.get_main_viewport() + left = imgui.get_window_pos().x + imgui.get_window_width() + width = viewport.work_pos.x + viewport.work_size.x - left + imgui.set_window_pos(COMPARISON_WINDOW, imgui.ImVec2(left, viewport.work_pos.y)) + imgui.set_window_size(COMPARISON_WINDOW, imgui.ImVec2(width, viewport.work_size.y)) + + return cover + + +class GazeSteering: + """Steer the eye's gaze with the mouse and I/J/K/L. + + Left-dragging the viewer steers only the gaze, as I/J/K/L and the side panel's sliders do; a drag that starts over + the viewer's panels stays with them. The viewer itself moves the eye's mount with WASD/QE. + """ + + DRAG_DEG_PER_PIXEL = 0.15 + GAZE_LIMIT_DEG = 85.0 + + def __init__(self, camera: FoveatedCamera, visualizers: list): + self.camera = camera + self.visualizers = visualizers + self.angles = torch.zeros_like(camera.gaze_angles.torch) + self.drag = [0.0, 0.0] + self.press_over_panel = False + for visualizer in visualizers: + window = getattr(newton_window(visualizer), "renderer", None) + native = getattr(window, "window", None) + if native is not None: + native.push_handlers(on_mouse_press=self._on_mouse_press, on_mouse_drag=self._on_mouse_drag) + + def _on_mouse_press(self, x, y, button, modifiers): + """Decide where a press's drag goes: inside the comparison image or on the bare view it steers the gaze; on any + other panel, or on the comparison window's title bar or edges, it stays with the panel.""" + from imgui_bundle import imgui + from pyglet import event + + self.press_over_panel = imgui.get_io().want_capture_mouse + if self.press_over_panel and comparison_image_hovered(imgui): + self.press_over_panel = False + # Keep ImGui from taking the press, which would drag the window instead of the gaze. + return event.EVENT_HANDLED + return None + + def _on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): + """Collect left drags that started on the view.""" + from pyglet import event + from pyglet.window import mouse + + if not buttons & mouse.LEFT or self.press_over_panel: + return None + self.drag[0] += dx + self.drag[1] += dy + return event.EVENT_HANDLED + + def steer(self, tilt_deg: float, pan_deg: float) -> None: + """Turn the gaze by (tilt, pan) [deg], starting from wherever the sliders or a drag left it.""" + # Dragging right looks right (negative pan); dragging up looks up. + pan_deg -= self.drag[0] * self.DRAG_DEG_PER_PIXEL + tilt_deg += self.drag[1] * self.DRAG_DEG_PER_PIXEL + self.drag = [0.0, 0.0] + if not tilt_deg and not pan_deg: + return + self.angles.copy_(self.camera.gaze_angles.torch) + step = self.angles.new_tensor((tilt_deg, pan_deg)) + self.angles.copy_((self.angles + step).clamp(-self.GAZE_LIMIT_DEG, self.GAZE_LIMIT_DEG)) + self.camera.set_gaze_angles(self.angles) + for visualizer in self.visualizers: + # The viewer shows the eye; a new gaze redraws it even while paused. + visualizer.current_image_view.invalidate() + + def main() -> None: """Render the docs scene and let the viewer drive the camera.""" # Config-only registration reuses the standard preset and Hydra override resolver. @@ -381,34 +480,26 @@ def main() -> None: pool_enabled=False, mask_to_sensor_fov=True, data_types=["rgb"], + # The overview only draws the panel; the viewer's gaze sliders are for the eye. + viewer_gaze_controls=False, ) scene = instantiate(cfg.scene) sim.register_interactive_scene(scene) sim.reset() camera = scene["eye"] - gaze = (0.0, 0.0) - if args_cli.target is not None: - gaze = gaze_toward(centres[args_cli.target], cfg.scene.eye) - angles = torch.tensor([gaze], device=sim.device).repeat(scene.num_envs, 1) + angles = torch.zeros(scene.num_envs, 2, device=sim.device) if args_cli.target is not None: + angles[:] = angles.new_tensor(gaze_toward(centres[args_cli.target], cfg.scene.eye)) camera.set_gaze_angles(angles) viewers = [v for v in sim.visualizers if v.cfg.backend.visualizer_type == "newton"] - - def set_gaze(value: tuple[float, float]) -> None: - nonlocal gaze - if gaze == value: - return - gaze = value - angles.copy_(angles.new_tensor(gaze).expand_as(angles)) - camera.set_gaze_angles(angles) - for viewer in viewers: - viewer.current_image_view.invalidate() - if viewers: prepare, compose = camera_comparison(camera, scene["overview"]) - zoom = 1.0 + gaze = GazeSteering(camera, viewers) + for viewer in viewers: + viewer.register_ui_callback(cover_view_with_comparison(), position="side") last_gaze_update = time.monotonic() + shown_frame = None # The viewer's frame of the eye that the comparison window shows. frame = 0 while sim.is_running() and (args_cli.max_steps < 0 or frame < args_cli.max_steps): now = time.monotonic() @@ -418,24 +509,20 @@ def set_gaze(value: tuple[float, float]) -> None: viewer = viewers[0] tilt = int(viewer.is_key_down("i")) - int(viewer.is_key_down("k")) pan = int(viewer.is_key_down("j")) - int(viewer.is_key_down("l")) - magnify = int(viewer.is_key_down("o")) - int(viewer.is_key_down("u")) - zoom = max(1.0, min(8.0, zoom * math.exp(1.5 * magnify * elapsed))) - if tilt or pan: - set_gaze( - ( - max(-85.0, min(85.0, gaze[0] + tilt * 50 * elapsed)), - max(-85.0, min(85.0, gaze[1] + pan * 50 * elapsed)), - ) - ) + gaze.steer(tilt * 50 * elapsed, pan * 50 * elapsed) scene.update(sim.get_physics_dt()) sim.render() if viewers: - # The panel follows the retina the viewer shows: the dense overview takes the eye's pose, then both - # render, and the panel is drawn from them. - prepare() - panel = compose(camera.data.output["rgb"].torch[0, ..., :3], zoom) - for viewer in viewers: - newton_window(viewer).log_image("Foveated camera", panel) + # The comparison is redrawn only when the viewer shows a new frame of the eye, and from that very + # frame. The viewer keeps showing one frame until the eye moves, its gaze or foveation changes; + # re-rendering in between would show OVRTX's frame-to-frame sampling noise as jitter. + latest = viewers[0].current_image_view.frame.data + if latest is not None and (shown_frame is None or not torch.equal(wp.to_torch(latest), shown_frame)): + shown_frame = wp.to_torch(latest).clone() + prepare() + view = compose(shown_frame[..., :3]) + for viewer in viewers: + newton_window(viewer).log_image(COMPARISON_WINDOW, view) if not sim.visualizers: # Without a viewer, explicitly request sensor data to render the frame. _ = camera.data diff --git a/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-viewer-controls.added.rst b/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-viewer-controls.added.rst new file mode 100644 index 000000000000..1f55e53a2ce6 --- /dev/null +++ b/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-viewer-controls.added.rst @@ -0,0 +1,5 @@ +* Added gaze and foveation controls to the Newton viewer's side panel for every foveated camera + (``viewer_gaze_controls``), with sliders kept in sync with the camera's gaze and a discrete, log-spaced + ``cmf_a`` selector (``viewer_cmf_a_values``). +* Added :meth:`~isaaclab_fovi.sensors.FoveatedCamera.set_cmf_a`, which changes the CMF constant of fixed-count + Newton foveated cameras at runtime. diff --git a/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-viewer-controls.minor b/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-viewer-controls.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index afb5459230ba..2f25815d23bf 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -7,6 +7,8 @@ from __future__ import annotations +import contextlib +import io import math import warnings from collections.abc import Mapping, Sequence @@ -14,6 +16,7 @@ import torch import warp as wp +from fovi.sensing.coords import WARPED_CARTESIAN_STYLES from fovi.sensing.projection import CameraModel from isaaclab.sensors.camera.camera import Camera @@ -21,6 +24,7 @@ from isaaclab.utils.warp import ProxyArray from .calibrated_geometry import camera_model_from_spawn, retinal_directions +from .gaze_controls import add_viewer_gaze_controls from .gaze_kernels import ( CameraParams, apply_gaze_indexed_kernel, @@ -34,6 +38,7 @@ ) from .native_grid import GRID_STYLE, buffer_tensor, native_grid_directions from .pooling import ( + build_pooler, build_retinal_coords, is_segmentation_output, pool_hwc_buffer, @@ -51,6 +56,21 @@ """Axis signs between OpenGL camera-frame directions (x right, y up, -z forward) and ROS ones (x right, y down).""" +def fixed_count_style(style: str) -> bool: + """Whether a sampling style keeps its sample count for every CMF constant: the warped-Cartesian styles, whose + count is the grid's, and the ``_fixn`` isotropic ones, which fix it.""" + return style in WARPED_CARTESIAN_STYLES or "fixn" in style + + +def runtime_cmf_a_limitation(camera: FoveatedCamera) -> str: + """Why ``camera`` cannot change its CMF constant at runtime, for messages and the viewer panel.""" + if not camera._renders_switchable_rays: + return "OVRTX and Isaac RTX read the retina's lens textures once, when the renderer loads the stage" + if not fixed_count_style(camera.cfg.foveated_style): + return f"a {camera.cfg.foveated_style!r} retina's sample count depends on cmf_a" + return "the retina can change its cmf_a at runtime" + + class FoveatedCamera(Camera): """Camera that samples the scene on a foveated retina instead of a uniform pixel grid. @@ -72,6 +92,9 @@ class FoveatedCamera(Camera): cfg: FoveatedCameraCfg + _renders_switchable_rays = False + """Whether the renderer traces rays the camera can replace while it runs, as :meth:`set_cmf_a` needs.""" + def __new__(cls, cfg: FoveatedCameraCfg, *args, **kwargs): """Create the implementation that matches the configured renderer. @@ -121,9 +144,14 @@ def __init__(self, cfg: FoveatedCameraCfg, *, turns_pose_by_gaze: bool = False): self._published_shape: tuple[int, int] | None = None self._segmentation_neighbors: torch.Tensor | None = None self._sensor_fov_valid: torch.Tensor | None = None + self._pooler = None + self._retinas: dict[float, tuple] = {} + """Retinas built for :meth:`set_cmf_a`, by CMF constant.""" self.mount_turns = 0 """How many times :meth:`set_world_poses` or :meth:`set_world_poses_from_view` has turned the camera's mount.""" super().__init__(cfg) + if cfg.viewer_gaze_controls: + add_viewer_gaze_controls(self) @property def image_shape(self) -> tuple[int, int]: @@ -303,14 +331,8 @@ def _initialize_sampling(self) -> None: self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device) self._ray_coords = self._sampling_coords_highres or self._sampling_coords self._gaze_camera = camera_params(self._camera_model) - coords = self._ray_coords rotation_deg = self.cfg.image_rotation_deg - # The rays as rendered, mount roll included, in the ROS frame the camera model projects. - if coords.style == GRID_STYLE: - rays = native_grid_directions(coords, image_rotation_deg=rotation_deg) - else: - rays = retinal_directions(coords.cartesian, coords.fov, rotation_deg) - self._gaze_rays = (rays * rays.new_tensor(OPENGL_TO_ROS_AXES)).float().contiguous() + self._gaze_rays = self._retina_rays(self._ray_coords) # No gaze until one is set: the camera looks along its optical axis untouched. self._gaze_angles = None self._gaze_rotation = None @@ -335,6 +357,79 @@ def _initialize_sampling(self) -> None: wp.quatf(*to_ros), ) + def _retina_rays(self, coords) -> torch.Tensor: + """The rendered rays of ``coords``, mount roll included, in the ROS frame the camera model projects, shape + (N, 3).""" + rotation_deg = self.cfg.image_rotation_deg + if coords.style == GRID_STYLE: + rays = native_grid_directions(coords, image_rotation_deg=rotation_deg) + else: + rays = retinal_directions(coords.cartesian, coords.fov, rotation_deg) + return (rays * rays.new_tensor(OPENGL_TO_ROS_AXES)).float().contiguous() + + @property + def supports_runtime_cmf_a(self) -> bool: + """Whether :meth:`set_cmf_a` can change this camera's foveation while it runs: on Newton, for retinas whose + sample count does not depend on the CMF constant (the warped-Cartesian and ``_fixn`` isotropic styles).""" + return self._renders_switchable_rays and fixed_count_style(self.cfg.foveated_style) + + def set_cmf_a(self, cmf_a_deg: float) -> None: + """Re-sample the retina for a new CMF constant [deg], keeping the gaze, the sample count and every buffer. + + Each constant's retina is built once and cached, so switching back to it is immediate. + + Raises: + RuntimeError: The camera is not initialized. + NotImplementedError: The renderer or sampling style cannot change the retina at runtime; see + :attr:`supports_runtime_cmf_a`. + """ + if not self.is_initialized: + raise RuntimeError("Initialize the foveated camera (reset the simulation) before changing its cmf_a.") + if not self.supports_runtime_cmf_a: + raise NotImplementedError(runtime_cmf_a_limitation(self)) + cmf_a_deg = float(cmf_a_deg) + if cmf_a_deg == self.cfg.cmf_a_deg: + return + if not self._retinas: + self._retinas[self.cfg.cmf_a_deg] = ( + self._sampling_coords, + self._sampling_coords_highres, + self._gaze_rays.clone(), + self._pooler, + ) + if cmf_a_deg not in self._retinas: + self._retinas[cmf_a_deg] = self._build_retina(cmf_a_deg) + self._sampling_coords, self._sampling_coords_highres, rays, self._pooler = self._retinas[cmf_a_deg] + self._ray_coords = self._sampling_coords_highres or self._sampling_coords + # The sensor mask, the grid layout and the renderer read the rays in place, so they follow without new launches. + self._gaze_rays.copy_(rays) + self._write_render_rays() + if self._segmentation_neighbors is not None: + self._prepare_segmentation_pooling(["semantic_segmentation"]) + self.cfg.cmf_a_deg = cmf_a_deg + + def _build_retina(self, cmf_a_deg: float) -> tuple: + """The retina at ``cmf_a_deg``: its coordinates on the sensor device, rendered rays and pooler.""" + cfg = self.cfg.replace(cmf_a_deg=cmf_a_deg) + # fovi reports its isotropic ring fitting on stdout. + with contextlib.redirect_stdout(io.StringIO()): + lowres, highres = build_retinal_coords(cfg, self._camera_model, "cpu") + lowres = lowres.to(device=self._device) + highres = None if highres is None else highres.to(device=self._device) + ray_coords = highres or lowres + if len(ray_coords) != self._num_ray_samples or not torch.equal( + ray_coords.valid_mask, self._ray_coords.valid_mask + ): + raise NotImplementedError( + f"cmf_a {cmf_a_deg:g} changes this retina's samples; {runtime_cmf_a_limitation(self)}" + ) + pooler, _ = build_pooler(cfg, lowres, highres, device=str(self._device)) + return lowres, highres, self._retina_rays(ray_coords), pooler + + def _write_render_rays(self) -> None: + """Hand the renderer the rays now in :attr:`_gaze_rays`; only renderers that trace them support it.""" + raise NotImplementedError(runtime_cmf_a_limitation(self)) + def _allocate_gaze(self) -> None: """Allocate one stored gaze per camera, on the optical axis, its rotation and the mount, on the sensor device.""" diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index 1dc9b4e9533b..241befabc9d2 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -62,6 +62,13 @@ class FoveatedCameraCfg(CameraCfg): mask_to_sensor_fov: bool = False """Zero the samples outside the physical camera's image at the current gaze.""" + viewer_gaze_controls: bool = True + """Add this camera's gaze and foveation controls to the side panel of each Newton viewer window.""" + + viewer_cmf_a_values: tuple[float, ...] = (0.1, 0.3, 1.0, 3.0, 10.0, 30.0, 100.0) + """CMF constants [deg] the viewer's foveation control offers, with :attr:`cmf_a_deg` added; see + :meth:`FoveatedCamera.set_cmf_a`.""" + retinal_window_fraction: float = 1.0 """Diameter of the retinal window as a fraction of the reference image side.""" diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index 97c7bc35424a..95ada8efdb30 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -66,9 +66,16 @@ class FoveatedNewtonCamera(FoveatedCamera): cfg: FoveatedCameraCfg + _renders_switchable_rays = True + def __init__(self, cfg: FoveatedCameraCfg): super().__init__(cfg, turns_pose_by_gaze=True) + def _write_render_rays(self) -> None: + # Newton reads the camera's ray array each render, so the new rays go into it in place. + ray_directions = self._gaze_rays * self._gaze_rays.new_tensor(OPENGL_TO_ROS_AXES) + wp.copy(self._render_data.camera_rays, explicit_rays(ray_directions, self.cfg.height, self.cfg.width)) + def _initialize_impl(self): # The pooler's KNN tensors are plain attributes that nn.Module.to() does not move, so the coordinates start on # the CPU and the pooler is built on the sensor device after the parent initializes. diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py new file mode 100644 index 000000000000..2cd00d7a7938 --- /dev/null +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py @@ -0,0 +1,110 @@ +# 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 + +"""Gaze sliders for foveated cameras in the side panel of Newton viewer windows.""" + +from __future__ import annotations + +import weakref +from collections.abc import Callable +from typing import TYPE_CHECKING, Any + +import torch + +from isaaclab.sim import SimulationContext + +if TYPE_CHECKING: + from isaaclab.visualizers import BaseVisualizer + + from .foveated_camera import FoveatedCamera + +GAZE_LIMIT_DEG = 90.0 +"""Largest tilt or pan [deg] the sliders reach.""" + + +class ViewerGazeControls: + """Gaze and foveation controls for one foveated camera in each Newton viewer window. + + The tilt and pan sliders show the first environment's gaze every frame, so they follow whatever sets it, such as a + gaze action or a drag in the viewer. Moving one sets that gaze in every environment; a gaze action that sets the + gaze every step overrides them. The foveation slider steps through :attr:`FoveatedCameraCfg.viewer_cmf_a_values` + where :meth:`FoveatedCamera.set_cmf_a` can change the retina, and otherwise shows the CMF constant and why it is + fixed. + """ + + def __init__(self, camera: FoveatedCamera): + """Create the sliders for ``camera``, which they hold weakly: once it is gone, they draw nothing.""" + self._camera = weakref.ref(camera) + self._label = camera.cfg.prim_path.rsplit("/", 1)[-1] + self._attached: set[int] = set() + self._angles: torch.Tensor | None = None + + def attach(self, sim: SimulationContext) -> None: + """Add the sliders to every Newton viewer window of ``sim`` that does not show them yet.""" + for visualizer in sim.visualizers: + if visualizer.cfg.backend.visualizer_type == "newton" and id(visualizer) not in self._attached: + self._attached.add(id(visualizer)) + visualizer.register_ui_callback(self._render_callback(visualizer), position="side") + + def _render_callback(self, visualizer: BaseVisualizer) -> Callable[[Any], None]: + """Return the ImGui callback that draws the sliders in one window.""" + + def render(imgui: Any) -> None: + camera = self._camera() + if camera is None or not camera.is_initialized: + return + if not imgui.collapsing_header(f"Foveated camera: {self._label}##{id(self)}"): + return + tilt, pan = camera.gaze_angles.torch[0].tolist() + tilt_changed, tilt = imgui.slider_float("Gaze tilt", tilt, -GAZE_LIMIT_DEG, GAZE_LIMIT_DEG, "%.1f deg") + pan_changed, pan = imgui.slider_float("Gaze pan", pan, -GAZE_LIMIT_DEG, GAZE_LIMIT_DEG, "%.1f deg") + if imgui.is_item_hovered(): + imgui.set_tooltip("Positive tilt looks up, positive pan looks left. A gaze action overrides these.") + center = imgui.button("Center gaze") + if tilt_changed or pan_changed or center: + self._set_gaze(camera, (0.0, 0.0) if center else (tilt, pan), visualizer) + self._draw_foveation(imgui, camera, visualizer) + + return render + + def _draw_foveation(self, imgui: Any, camera: FoveatedCamera, visualizer: BaseVisualizer) -> None: + """Draw the CMF constant: a slider over the configured values, or the fixed value and why it is fixed.""" + from .foveated_camera import runtime_cmf_a_limitation # The camera module imports this one. + + current = float(camera.cfg.cmf_a_deg) + if not camera.supports_runtime_cmf_a: + imgui.text(f"Foveation: cmf_a {current:g} deg (fixed)") + if imgui.is_item_hovered(): + imgui.set_tooltip(f"Fixed because {runtime_cmf_a_limitation(camera)}.") + return + values = sorted({float(value) for value in camera.cfg.viewer_cmf_a_values} | {current}) + index = values.index(current) + changed, index = imgui.slider_int("Foveation", index, 0, len(values) - 1, f"cmf_a {current:g} deg") + if imgui.is_item_hovered(): + imgui.set_tooltip("Smaller cmf_a concentrates the samples at the fixation; larger spreads them evenly.") + if changed and values[index] != current: + camera.set_cmf_a(values[index]) + view = getattr(visualizer, "current_image_view", None) + if view is not None: + view.invalidate() + + def _set_gaze(self, camera: FoveatedCamera, angles: tuple[float, float], visualizer: BaseVisualizer) -> None: + """Set ``angles`` [deg] in every environment and redraw the window's camera view, even while paused.""" + gaze = camera.gaze_angles.torch + if self._angles is None or self._angles.shape != gaze.shape: + self._angles = torch.empty_like(gaze) + self._angles[:] = torch.tensor(angles, device=gaze.device) + camera.set_gaze_angles(self._angles) + view = getattr(visualizer, "current_image_view", None) + if view is not None: + view.invalidate() + + +def add_viewer_gaze_controls(camera: FoveatedCamera) -> None: + """Show ``camera``'s gaze sliders in the Newton viewer windows of every simulation reset while it exists.""" + controls = ViewerGazeControls(camera) + name = f"isaaclab_fovi.viewer_gaze_controls.{id(controls)}" + SimulationContext.add_reset_callback(name, controls.attach) + weakref.finalize(camera, SimulationContext.remove_reset_callback, name) diff --git a/source/isaaclab_fovi/test/foveated_render_cases.py b/source/isaaclab_fovi/test/foveated_render_cases.py index ea9e21197784..948f1bffa5e8 100644 --- a/source/isaaclab_fovi/test/foveated_render_cases.py +++ b/source/isaaclab_fovi/test/foveated_render_cases.py @@ -281,3 +281,30 @@ def foveated_camera_samples_densest_at_the_fixation(ground: GroundScene): even_angles = _cell_angles(even.as_grid(even.cartesian, sample_dim=0).float(), fov) errors, _ = _relative_errors(distance[0], even_angles) assert float((errors < 0.03).float().mean()) < 0.5 + + +def cmf_a_switches_the_retina_at_runtime(ground: GroundScene): + """Newton re-samples the retina for a new CMF constant in place: each sample renders along its new ray, the outputs + keep their shape, and switching back restores the first image. Renderers that read a lens texture refuse.""" + camera = ground.calibrated + ground.reset_mounts(camera) + camera.set_gaze_angles(torch.zeros(NUM_ENVS, 2, device=ground.sim.device)) + if not camera.supports_runtime_cmf_a: + with pytest.raises(NotImplementedError, match="lens textures"): + camera.set_cmf_a(10.0) + return + first = camera.cfg.cmf_a_deg + before, _, first_angles, _ = ground.render(camera) + camera.set_cmf_a(10.0) + try: + after, _, angles, _ = ground.render(camera) + assert after.shape == before.shape + errors, _ = _relative_errors(after[0], angles) + assert float((errors < 0.03).float().mean()) > 0.98 + # The new image does not follow the first retina's rays. + errors, _ = _relative_errors(after[0], first_angles) + assert float((errors < 0.03).float().mean()) < 0.9 + finally: + camera.set_cmf_a(first) + again, _, _, _ = ground.render(camera) + assert torch.equal(again, before) diff --git a/source/isaaclab_fovi/test/test_camera_gaze.py b/source/isaaclab_fovi/test/test_camera_gaze.py index 7905155aca64..c659a4e18dbe 100644 --- a/source/isaaclab_fovi/test/test_camera_gaze.py +++ b/source/isaaclab_fovi/test/test_camera_gaze.py @@ -18,6 +18,7 @@ from isaaclab_fovi.sensors.calibrated_geometry import retinal_directions from isaaclab_fovi.sensors.foveated_camera import FoveatedCamera from isaaclab_fovi.sensors.foveated_rtx_camera import FoveatedRTXCamera +from isaaclab_fovi.sensors.gaze_controls import ViewerGazeControls, add_viewer_gaze_controls from isaaclab_fovi.sensors.gaze_kernels import ( camera_params, project_directions, @@ -30,6 +31,7 @@ from isaaclab.sensors.camera.camera import Camera from isaaclab.sensors.camera.camera_data import CameraData +from isaaclab.sim import SimulationContext from isaaclab.test.utils import DeviceScope, test_devices from isaaclab.utils.math import ( convert_camera_frame_orientation_convention, @@ -538,3 +540,127 @@ def test_publish_kernel_matches_masking_then_copying_to_the_grid() -> None: assert (visible[updated] == valid[updated]).float().mean() > 0.999 assert not visible[~updated].any() assert valid.any() and (~valid).any() + + +class _SliderCamera: + """The parts of a foveated camera that the viewer's gaze and foveation controls use.""" + + def __init__(self, num_envs: int, switchable: bool = True): + self.cfg = SimpleNamespace( + prim_path="/World/envs/env_.*/Eye", + cmf_a_deg=0.591, + viewer_cmf_a_values=(0.1, 1.0, 10.0), + foveated_style="warped_cartesian_as_grid", + ) + self.is_initialized = True + self.supports_runtime_cmf_a = switchable + self._renders_switchable_rays = switchable + self.gaze_angles = SimpleNamespace(torch=torch.tensor([[5.0, -10.0]]).repeat(num_envs, 1)) + self.written = [] + + def set_gaze_angles(self, angles: torch.Tensor) -> None: + self.written.append(angles.clone()) + self.gaze_angles.torch.copy_(angles) + + def set_cmf_a(self, cmf_a_deg: float) -> None: + self.cfg.cmf_a_deg = cmf_a_deg + + +class _Imgui: + """The ImGui calls the controls make; each float slider returns a scripted (changed, value), and the foveation + slider a scripted (changed, index).""" + + def __init__(self, sliders=(), button=False, foveation=None): + self.sliders = list(sliders) + self.button_pressed = button + self.foveation = foveation + self.shown = [] + + def collapsing_header(self, label): + self.shown.append(label) + return True + + def slider_float(self, label, value, *_args): + self.shown.append((label, value)) + return self.sliders.pop(0) if self.sliders else (False, value) + + def slider_int(self, label, index, low, high, display): + self.shown.append((label, index, low, high, display)) + return (True, self.foveation) if self.foveation is not None else (False, index) + + def text(self, text): + self.shown.append(text) + + def is_item_hovered(self): + return False + + def button(self, label): + return self.button_pressed + + +def _visualizer(kind: str) -> SimpleNamespace: + """A visualizer of ``kind`` that records its UI callbacks and counts redraws of its camera view.""" + view = SimpleNamespace(invalidated=0) + view.invalidate = lambda: setattr(view, "invalidated", view.invalidated + 1) + callbacks = [] + return SimpleNamespace( + cfg=SimpleNamespace(backend=SimpleNamespace(visualizer_type=kind)), + register_ui_callback=lambda callback, position: callbacks.append((callback, position)), + current_image_view=view, + callbacks=callbacks, + ) + + +def test_viewer_gaze_sliders_follow_and_set_the_gaze_in_newton_windows() -> None: + camera = _SliderCamera(num_envs=3) + newton, kit = _visualizer("newton"), _visualizer("kit") + controls = ViewerGazeControls(camera) + # Each simulation reset attaches again; a window gets the sliders once, and only Newton windows get them. + controls.attach(SimpleNamespace(visualizers=[newton, kit])) + controls.attach(SimpleNamespace(visualizers=[newton, kit])) + assert [position for _, position in newton.callbacks] == ["side"] and not kit.callbacks + render = newton.callbacks[0][0] + + # The sliders show the first environment's gaze, and leave it alone until moved. + imgui = _Imgui() + render(imgui) + assert ("Gaze tilt", 5.0) in imgui.shown and ("Gaze pan", -10.0) in imgui.shown and not camera.written + # Moving one sets that gaze in every environment and redraws the window's camera view. + render(_Imgui(sliders=[(True, 20.0), (False, -10.0)])) + assert torch.equal(camera.written[-1], torch.tensor([[20.0, -10.0]]).repeat(3, 1)) + assert newton.current_image_view.invalidated == 1 + render(_Imgui(button=True)) + assert not camera.written[-1].any() + + # The foveation slider steps through the configured CMF constants with the camera's own added, in order. + imgui = _Imgui() + render(imgui) + assert ("Foveation", 1, 0, 3, "cmf_a 0.591 deg") in imgui.shown # 0.1, 0.591, 1, 10 + render(_Imgui(foveation=3)) + assert camera.cfg.cmf_a_deg == 10.0 and newton.current_image_view.invalidated == 3 + # A camera that cannot switch shows its constant as fixed instead. + fixed = _SliderCamera(num_envs=1, switchable=False) + fixed_controls = ViewerGazeControls(fixed) + fixed_window = _visualizer("newton") + fixed_controls.attach(SimpleNamespace(visualizers=[fixed_window])) + imgui = _Imgui(foveation=0) + fixed_window.callbacks[0][0](imgui) + assert "Foveation: cmf_a 0.591 deg (fixed)" in imgui.shown and fixed.cfg.cmf_a_deg == 0.591 + + # Once the camera is gone, the window's callback draws nothing. + del camera + imgui = _Imgui() + render(imgui) + assert not imgui.shown + + +def test_every_foveated_camera_adds_its_sliders_on_reset_until_it_is_gone() -> None: + camera = _SliderCamera(num_envs=1) + before = set(SimulationContext._reset_callbacks) + add_viewer_gaze_controls(camera) + (name,) = set(SimulationContext._reset_callbacks) - before + newton = _visualizer("newton") + SimulationContext._reset_callbacks[name](SimpleNamespace(visualizers=[newton])) + assert len(newton.callbacks) == 1 + del camera + assert name not in SimulationContext._reset_callbacks diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render.py b/source/isaaclab_fovi/test/test_foveated_camera_render.py index 4f8862871c08..53f70fb9a458 100644 --- a/source/isaaclab_fovi/test/test_foveated_camera_render.py +++ b/source/isaaclab_fovi/test/test_foveated_camera_render.py @@ -63,3 +63,7 @@ def test_gaze_stays_relative_to_moved_mounts(ground): def test_foveated_camera_samples_densest_at_the_fixation(ground): cases.foveated_camera_samples_densest_at_the_fixation(ground) + + +def test_cmf_a_switches_the_retina_at_runtime(ground): + cases.cmf_a_switches_the_retina_at_runtime(ground) diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py b/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py index e72878601758..d31ec6bdf911 100644 --- a/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py +++ b/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py @@ -47,3 +47,7 @@ def test_gaze_stays_relative_to_moved_mounts(ground): def test_foveated_camera_samples_densest_at_the_fixation(ground): cases.foveated_camera_samples_densest_at_the_fixation(ground) + + +def test_cmf_a_switches_the_retina_at_runtime(ground): + cases.cmf_a_switches_the_retina_at_runtime(ground) From d569921a8676b6608d784089f9ac994bddcc3736 Mon Sep 17 00:00:00 2001 From: nblauch Date: Mon, 23 Nov 2026 20:13:52 -0800 Subject: [PATCH 02/11] Address review of the viewer gaze and foveation controls Give each camera's side-panel widgets their own ImGui ID scope, so two cameras' sliders no longer share state, and keep the camera's starting cmf_a as a foveation option after a switch. Release the controls' buffers when the camera is collected. Clear the cmf_a retina cache when the camera initializes again, cache the renderer's rays per value instead of rebuilding them on each switch, and annotate the backend capability flags as ClassVar. In the example, redraw the comparison when the gaze or foveation changes as well as when the eye frame does, and cover the view once the window exists and again only when the view is resized, so a moved window stays. Test the RTX refusal without a simulator, run the runtime cmf_a render case on Newton only, check that building a camera adds its controls, and check that the sliders follow a gaze set elsewhere. --- .../experimental-features/foveated_camera.rst | 18 +-- examples/sensors/foveated_camera.py | 71 +++++++----- .../isaaclab_fovi/sensors/foveated_camera.py | 106 ++++++++++-------- .../sensors/foveated_newton_camera.py | 12 +- .../isaaclab_fovi/sensors/gaze_controls.py | 55 ++++++--- .../test/foveated_render_cases.py | 15 ++- source/isaaclab_fovi/test/test_camera_gaze.py | 42 +++++++ .../test/test_foveated_camera_render.py | 2 + .../test/test_foveated_camera_render_ovrtx.py | 4 - 9 files changed, 208 insertions(+), 117 deletions(-) diff --git a/docs/source/experimental-features/foveated_camera.rst b/docs/source/experimental-features/foveated_camera.rst index 60bf1ffdab8f..4a2f04a2cc20 100644 --- a/docs/source/experimental-features/foveated_camera.rst +++ b/docs/source/experimental-features/foveated_camera.rst @@ -16,11 +16,11 @@ several minutes with a cold shader cache: uv run --extra fovi [--extra ovrtx] isaaclab example foveated-camera [renderer=ovrtx] The Newton viewer shows the retina, covered at launch by a window that shows the fisheye on a curved viewing sphere -beside the retina: the green lens boundary follows the camera mount, and the blue gaze circle and sampling grid show the retina's coverage. Use WASD or -the arrow keys to move the camera and Q/E to lower or raise it. Drag with the left mouse button, or press I/K and J/L, to steer the gaze; the -side panel's sliders follow the gaze and set it, and on Newton its foveation slider steps the CMF constant through -``env.scene.eye.viewer_cmf_a_values``. H shows or hides the viewer controls. Pass ``--target power_drill`` to start -fixating the drill. +beside the retina: the green lens boundary follows the camera mount, and the blue gaze circle and sampling grid show +the retina's coverage. Use WASD or the arrow keys to move the camera and Q/E to lower or raise it. Drag with the left +mouse button, or press I/K and J/L, to steer the gaze; the side panel's sliders follow the gaze and set it, and on +Newton its foveation slider steps the CMF constant through ``env.scene.eye.viewer_cmf_a_values``. H shows or hides +the viewer controls. Pass ``--target power_drill`` to start fixating the drill. .. figure:: ../_static/overview/sensors/foveated_camera_overview.jpg :alt: A retina behind a 180-degree fisheye lens on the viewing sphere, and its rendered images at two fixations. @@ -107,10 +107,10 @@ step. A foveation slider beside them switches the CMF constant among :attr:`~sensors.FoveatedCameraCfg.viewer_cmf_a_values` with :meth:`~sensors.FoveatedCamera.set_cmf_a`, which re-samples the retina in place. That works on Newton for styles whose sample count does not depend on the constant, the warped-Cartesian and ``_fixn`` isotropic ones; OVRTX and Isaac RTX read their lens textures once, so there the -slider shows the constant as fixed. Set :attr:`~sensors.FoveatedCameraCfg.viewer_gaze_controls` to ``False`` to leave a -camera out. -:meth:`~sensors.FoveatedCamera.get_world_poses` reports the mount pose. Enable :attr:`~sensors.FoveatedCameraCfg.mask_to_sensor_fov` to zero rays that fall -outside the physical image as the gaze moves. +slider shows the constant as fixed. Set :attr:`~sensors.FoveatedCameraCfg.viewer_gaze_controls` to ``False`` to +leave a camera out. :meth:`~sensors.FoveatedCamera.get_world_poses` reports the mount pose. Enable +:attr:`~sensors.FoveatedCameraCfg.mask_to_sensor_fov` to zero rays that fall outside the physical image as the gaze +moves. Pooling ------- diff --git a/examples/sensors/foveated_camera.py b/examples/sensors/foveated_camera.py index cbf99c3973c0..1e92cc16fbdd 100644 --- a/examples/sensors/foveated_camera.py +++ b/examples/sensors/foveated_camera.py @@ -101,6 +101,8 @@ distortion=sim_utils.OpenCvFisheyeDistortionCfg(fx=FOCAL, fy=FOCAL, cx=511.5, cy=511.5, image_size=(1024, 1024)), ) PREVIEW_SIZE = 256 +COMPARISON_WINDOW = "Foveated camera" +"""Title of the window that shows the viewing sphere beside the retina.""" def viewing_sphere_rays(screen: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: @@ -346,10 +348,6 @@ def newton_window(visualizer): return visualizer._viewer -COMPARISON_WINDOW = "Foveated camera" -"""Title of the window that shows the viewing sphere beside the retina.""" - - def comparison_image_hovered(imgui, edge: float = 8.0) -> bool: """Whether the mouse is inside the comparison window's image: below its title bar and away from its resize edges.""" window = imgui.get_current_context().hovered_window @@ -362,19 +360,24 @@ def comparison_image_hovered(imgui, edge: float = 8.0) -> bool: return left <= mouse.x <= right and top <= mouse.y <= bottom -def cover_view_with_comparison(frames: int = 30): - """A side-panel callback that stretches the comparison window over the whole view beside the panel for its first - ``frames`` frames, then leaves its size and position to the user.""" - remaining = [frames] +def cover_view_with_comparison(): + """A side-panel callback that stretches the comparison window over the whole view beside the panel. + + It places the window once it exists, and again only when that view changes size, as while the viewer opens or when + its window or side panel is resized; otherwise the window's size and position are the user's. + """ + covered = [None] def cover(imgui) -> None: - if remaining[0] <= 0: - return - remaining[0] -= 1 # The callback draws inside the side panel, whose right edge is where the view begins. viewport = imgui.get_main_viewport() left = imgui.get_window_pos().x + imgui.get_window_width() width = viewport.work_pos.x + viewport.work_size.x - left + view = (left, viewport.work_pos.y, width, viewport.work_size.y) + # Placing a window by name does nothing before its first frame. + if view == covered[0] or imgui.internal.find_window_by_name(COMPARISON_WINDOW) is None: + return + covered[0] = view imgui.set_window_pos(COMPARISON_WINDOW, imgui.ImVec2(left, viewport.work_pos.y)) imgui.set_window_size(COMPARISON_WINDOW, imgui.ImVec2(width, viewport.work_size.y)) @@ -403,6 +406,22 @@ def __init__(self, camera: FoveatedCamera, visualizers: list): if native is not None: native.push_handlers(on_mouse_press=self._on_mouse_press, on_mouse_drag=self._on_mouse_drag) + def steer(self, tilt_deg: float, pan_deg: float) -> None: + """Turn the gaze by (tilt, pan) [deg], starting from wherever the sliders or a drag left it.""" + # Dragging right looks right (negative pan); dragging up looks up. + pan_deg -= self.drag[0] * self.DRAG_DEG_PER_PIXEL + tilt_deg += self.drag[1] * self.DRAG_DEG_PER_PIXEL + self.drag = [0.0, 0.0] + if not tilt_deg and not pan_deg: + return + self.angles.copy_(self.camera.gaze_angles.torch) + step = self.angles.new_tensor((tilt_deg, pan_deg)) + self.angles.copy_((self.angles + step).clamp(-self.GAZE_LIMIT_DEG, self.GAZE_LIMIT_DEG)) + self.camera.set_gaze_angles(self.angles) + for visualizer in self.visualizers: + # The viewer shows the eye; a new gaze redraws it even while paused. + visualizer.current_image_view.invalidate() + def _on_mouse_press(self, x, y, button, modifiers): """Decide where a press's drag goes: inside the comparison image or on the bare view it steers the gaze; on any other panel, or on the comparison window's title bar or edges, it stays with the panel.""" @@ -427,22 +446,6 @@ def _on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): self.drag[1] += dy return event.EVENT_HANDLED - def steer(self, tilt_deg: float, pan_deg: float) -> None: - """Turn the gaze by (tilt, pan) [deg], starting from wherever the sliders or a drag left it.""" - # Dragging right looks right (negative pan); dragging up looks up. - pan_deg -= self.drag[0] * self.DRAG_DEG_PER_PIXEL - tilt_deg += self.drag[1] * self.DRAG_DEG_PER_PIXEL - self.drag = [0.0, 0.0] - if not tilt_deg and not pan_deg: - return - self.angles.copy_(self.camera.gaze_angles.torch) - step = self.angles.new_tensor((tilt_deg, pan_deg)) - self.angles.copy_((self.angles + step).clamp(-self.GAZE_LIMIT_DEG, self.GAZE_LIMIT_DEG)) - self.camera.set_gaze_angles(self.angles) - for visualizer in self.visualizers: - # The viewer shows the eye; a new gaze redraws it even while paused. - visualizer.current_image_view.invalidate() - def main() -> None: """Render the docs scene and let the viewer drive the camera.""" @@ -500,6 +503,7 @@ def main() -> None: last_gaze_update = time.monotonic() shown_frame = None # The viewer's frame of the eye that the comparison window shows. + shown_state = None # The gaze and CMF constant it was drawn with. frame = 0 while sim.is_running() and (args_cli.max_steps < 0 or frame < args_cli.max_steps): now = time.monotonic() @@ -513,12 +517,17 @@ def main() -> None: scene.update(sim.get_physics_dt()) sim.render() if viewers: - # The comparison is redrawn only when the viewer shows a new frame of the eye, and from that very - # frame. The viewer keeps showing one frame until the eye moves, its gaze or foveation changes; - # re-rendering in between would show OVRTX's frame-to-frame sampling noise as jitter. + # The comparison is redrawn from the viewer's frame of the eye, only when that frame changes or the + # gaze or foveation it overlays does. The viewer keeps showing one frame until the eye moves, its gaze + # or foveation changes; re-rendering in between would show OVRTX's frame-to-frame sampling noise as + # jitter. latest = viewers[0].current_image_view.frame.data - if latest is not None and (shown_frame is None or not torch.equal(wp.to_torch(latest), shown_frame)): + state = (tuple(camera.gaze_angles.torch[0].tolist()), camera.cfg.cmf_a_deg) + if latest is not None and ( + shown_frame is None or state != shown_state or not torch.equal(wp.to_torch(latest), shown_frame) + ): shown_frame = wp.to_torch(latest).clone() + shown_state = state prepare() view = compose(shown_frame[..., :3]) for viewer in viewers: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index 2f25815d23bf..79a26fc94df6 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -12,7 +12,7 @@ import math import warnings from collections.abc import Mapping, Sequence -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, ClassVar import torch import warp as wp @@ -92,7 +92,7 @@ class FoveatedCamera(Camera): cfg: FoveatedCameraCfg - _renders_switchable_rays = False + _renders_switchable_rays: ClassVar[bool] = False """Whether the renderer traces rays the camera can replace while it runs, as :meth:`set_cmf_a` needs.""" def __new__(cls, cfg: FoveatedCameraCfg, *args, **kwargs): @@ -220,6 +220,12 @@ def mount_quat_w_ros(self) -> ProxyArray: self._allocate_gaze() return self._mount_quat_ros + @property + def supports_runtime_cmf_a(self) -> bool: + """Whether :meth:`set_cmf_a` can change this camera's foveation while it runs: on Newton, for retinas whose + sample count does not depend on the CMF constant (the warped-Cartesian and ``_fixn`` isotropic styles).""" + return self._renders_switchable_rays and fixed_count_style(self.cfg.foveated_style) + def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: """Turn the retina to (tilt, pan) [deg] from the physical camera's optical axis. @@ -310,6 +316,44 @@ def set_intrinsic_matrices(self, matrices, focal_length=None, env_ids=None): stacklevel=2, ) + def set_cmf_a(self, cmf_a_deg: float) -> None: + """Re-sample the retina for a new CMF constant [deg], keeping the gaze, the sample count and every buffer. + + Each constant's retina is built once and cached until the camera is initialized again, so switching back to + one reuses it. + + Raises: + RuntimeError: The camera is not initialized. + NotImplementedError: The renderer or sampling style cannot change the retina at runtime; see + :attr:`supports_runtime_cmf_a`. + """ + if not self.is_initialized: + raise RuntimeError("Initialize the foveated camera (reset the simulation) before changing its cmf_a.") + if not self.supports_runtime_cmf_a: + raise NotImplementedError(runtime_cmf_a_limitation(self)) + cmf_a_deg = float(cmf_a_deg) + if cmf_a_deg == self.cfg.cmf_a_deg: + return + if not self._retinas: + rays = self._gaze_rays.clone() + self._retinas[self.cfg.cmf_a_deg] = ( + self._sampling_coords, + self._sampling_coords_highres, + rays, + self._render_rays(rays), + self._pooler, + ) + if cmf_a_deg not in self._retinas: + self._retinas[cmf_a_deg] = self._build_retina(cmf_a_deg) + self._sampling_coords, self._sampling_coords_highres, rays, render_rays, self._pooler = self._retinas[cmf_a_deg] + self._ray_coords = self._sampling_coords_highres or self._sampling_coords + # The sensor mask, the grid layout and the renderer read the rays in place, so they follow without new launches. + self._gaze_rays.copy_(rays) + self._write_render_rays(render_rays) + if self._segmentation_neighbors is not None: + self._prepare_segmentation_pooling(["semantic_segmentation"]) + self.cfg.cmf_a_deg = cmf_a_deg + def _prepare_sampling(self) -> None: """Resolve physical calibration and retinal coordinates before the renderer sizes its buffers.""" calibration = self.cfg.camera_model @@ -326,6 +370,8 @@ def _prepare_sampling(self) -> None: def _initialize_sampling(self) -> None: """Move retinal coordinates to the sensor device and prepare the gaze rays and frame conversions.""" + # Retinas cached by set_cmf_a hold the previous initialization's coordinates, rays and poolers. + self._retinas = {} self._sampling_coords = self._sampling_coords.to(device=self._device) if self._sampling_coords_highres is not None: self._sampling_coords_highres = self._sampling_coords_highres.to(device=self._device) @@ -367,49 +413,9 @@ def _retina_rays(self, coords) -> torch.Tensor: rays = retinal_directions(coords.cartesian, coords.fov, rotation_deg) return (rays * rays.new_tensor(OPENGL_TO_ROS_AXES)).float().contiguous() - @property - def supports_runtime_cmf_a(self) -> bool: - """Whether :meth:`set_cmf_a` can change this camera's foveation while it runs: on Newton, for retinas whose - sample count does not depend on the CMF constant (the warped-Cartesian and ``_fixn`` isotropic styles).""" - return self._renders_switchable_rays and fixed_count_style(self.cfg.foveated_style) - - def set_cmf_a(self, cmf_a_deg: float) -> None: - """Re-sample the retina for a new CMF constant [deg], keeping the gaze, the sample count and every buffer. - - Each constant's retina is built once and cached, so switching back to it is immediate. - - Raises: - RuntimeError: The camera is not initialized. - NotImplementedError: The renderer or sampling style cannot change the retina at runtime; see - :attr:`supports_runtime_cmf_a`. - """ - if not self.is_initialized: - raise RuntimeError("Initialize the foveated camera (reset the simulation) before changing its cmf_a.") - if not self.supports_runtime_cmf_a: - raise NotImplementedError(runtime_cmf_a_limitation(self)) - cmf_a_deg = float(cmf_a_deg) - if cmf_a_deg == self.cfg.cmf_a_deg: - return - if not self._retinas: - self._retinas[self.cfg.cmf_a_deg] = ( - self._sampling_coords, - self._sampling_coords_highres, - self._gaze_rays.clone(), - self._pooler, - ) - if cmf_a_deg not in self._retinas: - self._retinas[cmf_a_deg] = self._build_retina(cmf_a_deg) - self._sampling_coords, self._sampling_coords_highres, rays, self._pooler = self._retinas[cmf_a_deg] - self._ray_coords = self._sampling_coords_highres or self._sampling_coords - # The sensor mask, the grid layout and the renderer read the rays in place, so they follow without new launches. - self._gaze_rays.copy_(rays) - self._write_render_rays() - if self._segmentation_neighbors is not None: - self._prepare_segmentation_pooling(["semantic_segmentation"]) - self.cfg.cmf_a_deg = cmf_a_deg - def _build_retina(self, cmf_a_deg: float) -> tuple: - """The retina at ``cmf_a_deg``: its coordinates on the sensor device, rendered rays and pooler.""" + """The retina at ``cmf_a_deg``: its coordinates on the sensor device, its rays, the renderer's copy of them, + and its pooler.""" cfg = self.cfg.replace(cmf_a_deg=cmf_a_deg) # fovi reports its isotropic ring fitting on stdout. with contextlib.redirect_stdout(io.StringIO()): @@ -424,10 +430,16 @@ def _build_retina(self, cmf_a_deg: float) -> tuple: f"cmf_a {cmf_a_deg:g} changes this retina's samples; {runtime_cmf_a_limitation(self)}" ) pooler, _ = build_pooler(cfg, lowres, highres, device=str(self._device)) - return lowres, highres, self._retina_rays(ray_coords), pooler + rays = self._retina_rays(ray_coords) + return lowres, highres, rays, self._render_rays(rays), pooler + + def _render_rays(self, rays: torch.Tensor): + """The renderer's form of ``rays`` (ROS frame), which :meth:`_write_render_rays` hands it; only renderers that + trace the camera's rays support it.""" + raise NotImplementedError(runtime_cmf_a_limitation(self)) - def _write_render_rays(self) -> None: - """Hand the renderer the rays now in :attr:`_gaze_rays`; only renderers that trace them support it.""" + def _write_render_rays(self, render_rays) -> None: + """Hand the renderer rays made by :meth:`_render_rays`.""" raise NotImplementedError(runtime_cmf_a_limitation(self)) def _allocate_gaze(self) -> None: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py index 95ada8efdb30..8140129146d7 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_newton_camera.py @@ -8,7 +8,7 @@ from __future__ import annotations import logging -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, ClassVar import torch import warp as wp @@ -66,15 +66,17 @@ class FoveatedNewtonCamera(FoveatedCamera): cfg: FoveatedCameraCfg - _renders_switchable_rays = True + _renders_switchable_rays: ClassVar[bool] = True def __init__(self, cfg: FoveatedCameraCfg): super().__init__(cfg, turns_pose_by_gaze=True) - def _write_render_rays(self) -> None: + def _render_rays(self, rays: torch.Tensor) -> wp.array: + return explicit_rays(rays * rays.new_tensor(OPENGL_TO_ROS_AXES), self.cfg.height, self.cfg.width) + + def _write_render_rays(self, render_rays: wp.array) -> None: # Newton reads the camera's ray array each render, so the new rays go into it in place. - ray_directions = self._gaze_rays * self._gaze_rays.new_tensor(OPENGL_TO_ROS_AXES) - wp.copy(self._render_data.camera_rays, explicit_rays(ray_directions, self.cfg.height, self.cfg.width)) + wp.copy(self._render_data.camera_rays, render_rays) def _initialize_impl(self): # The pooler's KNN tensors are plain attributes that nn.Module.to() does not move, so the coordinates start on diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py index 2cd00d7a7938..60918a63301a 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py @@ -30,17 +30,28 @@ class ViewerGazeControls: The tilt and pan sliders show the first environment's gaze every frame, so they follow whatever sets it, such as a gaze action or a drag in the viewer. Moving one sets that gaze in every environment; a gaze action that sets the gaze every step overrides them. The foveation slider steps through :attr:`FoveatedCameraCfg.viewer_cmf_a_values` - where :meth:`FoveatedCamera.set_cmf_a` can change the retina, and otherwise shows the CMF constant and why it is - fixed. + and the camera's starting CMF constant where :meth:`FoveatedCamera.set_cmf_a` can change the retina, and otherwise + shows the CMF constant and why it is fixed. """ def __init__(self, camera: FoveatedCamera): """Create the sliders for ``camera``, which they hold weakly: once it is gone, they draw nothing.""" self._camera = weakref.ref(camera) self._label = camera.cfg.prim_path.rsplit("/", 1)[-1] + self._cmf_a_values = sorted( + {float(value) for value in camera.cfg.viewer_cmf_a_values} | {float(camera.cfg.cmf_a_deg)} + ) + """The foveation slider's CMF constants [deg]; the starting one stays an option after a switch.""" self._attached: set[int] = set() self._angles: torch.Tensor | None = None + def detach(self) -> None: + """Release the gaze buffer once the camera is gone; the windows' callbacks then draw nothing. + + The viewer cannot unregister a UI callback, so each window keeps a callback that returns at once. + """ + self._angles = None + def attach(self, sim: SimulationContext) -> None: """Add the sliders to every Newton viewer window of ``sim`` that does not show them yet.""" for visualizer in sim.visualizers: @@ -55,20 +66,28 @@ def render(imgui: Any) -> None: camera = self._camera() if camera is None or not camera.is_initialized: return - if not imgui.collapsing_header(f"Foveated camera: {self._label}##{id(self)}"): - return - tilt, pan = camera.gaze_angles.torch[0].tolist() - tilt_changed, tilt = imgui.slider_float("Gaze tilt", tilt, -GAZE_LIMIT_DEG, GAZE_LIMIT_DEG, "%.1f deg") - pan_changed, pan = imgui.slider_float("Gaze pan", pan, -GAZE_LIMIT_DEG, GAZE_LIMIT_DEG, "%.1f deg") - if imgui.is_item_hovered(): - imgui.set_tooltip("Positive tilt looks up, positive pan looks left. A gaze action overrides these.") - center = imgui.button("Center gaze") - if tilt_changed or pan_changed or center: - self._set_gaze(camera, (0.0, 0.0) if center else (tilt, pan), visualizer) - self._draw_foveation(imgui, camera, visualizer) + # Each camera's widgets share labels, so they need their own ID scope; a header does not open one. + imgui.push_id(f"isaaclab_fovi.viewer_gaze_controls.{id(self)}") + try: + if imgui.collapsing_header(f"Foveated camera: {self._label}"): + self._draw_controls(imgui, camera, visualizer) + finally: + imgui.pop_id() return render + def _draw_controls(self, imgui: Any, camera: FoveatedCamera, visualizer: BaseVisualizer) -> None: + """Draw the gaze sliders, the center button and the foveation control.""" + tilt, pan = camera.gaze_angles.torch[0].tolist() + tilt_changed, tilt = imgui.slider_float("Gaze tilt", tilt, -GAZE_LIMIT_DEG, GAZE_LIMIT_DEG, "%.1f deg") + pan_changed, pan = imgui.slider_float("Gaze pan", pan, -GAZE_LIMIT_DEG, GAZE_LIMIT_DEG, "%.1f deg") + if imgui.is_item_hovered(): + imgui.set_tooltip("Positive tilt looks up, positive pan looks left. A gaze action overrides these.") + center = imgui.button("Center gaze") + if tilt_changed or pan_changed or center: + self._set_gaze(camera, (0.0, 0.0) if center else (tilt, pan), visualizer) + self._draw_foveation(imgui, camera, visualizer) + def _draw_foveation(self, imgui: Any, camera: FoveatedCamera, visualizer: BaseVisualizer) -> None: """Draw the CMF constant: a slider over the configured values, or the fixed value and why it is fixed.""" from .foveated_camera import runtime_cmf_a_limitation # The camera module imports this one. @@ -79,7 +98,7 @@ def _draw_foveation(self, imgui: Any, camera: FoveatedCamera, visualizer: BaseVi if imgui.is_item_hovered(): imgui.set_tooltip(f"Fixed because {runtime_cmf_a_limitation(camera)}.") return - values = sorted({float(value) for value in camera.cfg.viewer_cmf_a_values} | {current}) + values = self._cmf_a_values if current in self._cmf_a_values else sorted({*self._cmf_a_values, current}) index = values.index(current) changed, index = imgui.slider_int("Foveation", index, 0, len(values) - 1, f"cmf_a {current:g} deg") if imgui.is_item_hovered(): @@ -107,4 +126,10 @@ def add_viewer_gaze_controls(camera: FoveatedCamera) -> None: controls = ViewerGazeControls(camera) name = f"isaaclab_fovi.viewer_gaze_controls.{id(controls)}" SimulationContext.add_reset_callback(name, controls.attach) - weakref.finalize(camera, SimulationContext.remove_reset_callback, name) + weakref.finalize(camera, _forget_controls, name, controls) + + +def _forget_controls(name: str, controls: ViewerGazeControls) -> None: + """Stop adding a collected camera's controls on reset and release their buffers.""" + SimulationContext.remove_reset_callback(name) + controls.detach() diff --git a/source/isaaclab_fovi/test/foveated_render_cases.py b/source/isaaclab_fovi/test/foveated_render_cases.py index 948f1bffa5e8..ad53e65feed4 100644 --- a/source/isaaclab_fovi/test/foveated_render_cases.py +++ b/source/isaaclab_fovi/test/foveated_render_cases.py @@ -23,11 +23,12 @@ from fovi.sensing.coords import SamplingCoords from fovi.sensing.projection import angular_directions from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg +from isaaclab_fovi.sensors.gaze_controls import ViewerGazeControls import isaaclab.sim as sim_utils from isaaclab.assets import AssetBaseCfg, RigidObjectCfg from isaaclab.scene import InteractiveScene, InteractiveSceneCfg -from isaaclab.sim import SimulationCfg, build_simulation_context +from isaaclab.sim import SimulationCfg, SimulationContext, build_simulation_context from isaaclab.terrains import TerrainImporterCfg from isaaclab.test.utils.devices import resolve_test_sim_device from isaaclab.utils.configclass import configclass @@ -285,14 +286,16 @@ def foveated_camera_samples_densest_at_the_fixation(ground: GroundScene): def cmf_a_switches_the_retina_at_runtime(ground: GroundScene): """Newton re-samples the retina for a new CMF constant in place: each sample renders along its new ray, the outputs - keep their shape, and switching back restores the first image. Renderers that read a lens texture refuse.""" + keep their shape, and switching back restores the first image. Building the camera added its viewer controls.""" camera = ground.calibrated + controls = [ + callback.__self__ + for callback in SimulationContext._reset_callbacks.values() + if isinstance(getattr(callback, "__self__", None), ViewerGazeControls) + ] + assert any(control._camera() is camera for control in controls) ground.reset_mounts(camera) camera.set_gaze_angles(torch.zeros(NUM_ENVS, 2, device=ground.sim.device)) - if not camera.supports_runtime_cmf_a: - with pytest.raises(NotImplementedError, match="lens textures"): - camera.set_cmf_a(10.0) - return first = camera.cfg.cmf_a_deg before, _, first_angles, _ = ground.render(camera) camera.set_cmf_a(10.0) diff --git a/source/isaaclab_fovi/test/test_camera_gaze.py b/source/isaaclab_fovi/test/test_camera_gaze.py index c659a4e18dbe..8be1351eeca1 100644 --- a/source/isaaclab_fovi/test/test_camera_gaze.py +++ b/source/isaaclab_fovi/test/test_camera_gaze.py @@ -575,12 +575,23 @@ def __init__(self, sliders=(), button=False, foveation=None): self.button_pressed = button self.foveation = foveation self.shown = [] + self.ids = [] + self.scopes = [] + + def push_id(self, name): + self.ids.append(name) + self.scopes.append(name) + + def pop_id(self): + self.ids.pop() def collapsing_header(self, label): self.shown.append(label) return True def slider_float(self, label, value, *_args): + # Widgets with the same label in two cameras' sections need distinct ID scopes. + assert self.ids, "slider drawn outside its camera's ID scope" self.shown.append((label, value)) return self.sliders.pop(0) if self.sliders else (False, value) @@ -625,6 +636,16 @@ def test_viewer_gaze_sliders_follow_and_set_the_gaze_in_newton_windows() -> None imgui = _Imgui() render(imgui) assert ("Gaze tilt", 5.0) in imgui.shown and ("Gaze pan", -10.0) in imgui.shown and not camera.written + assert not imgui.ids # Each draw closes the ID scope it opens. + # A gaze set elsewhere, as by a gaze action, shows on the next draw. + camera.gaze_angles.torch[:] = torch.tensor([-30.0, 40.0]) + imgui = _Imgui() + render(imgui) + assert ("Gaze tilt", -30.0) in imgui.shown and ("Gaze pan", 40.0) in imgui.shown and not camera.written + # Two cameras' sections open different ID scopes, so their same-named widgets stay apart. + other, other_camera = _Imgui(), _SliderCamera(num_envs=1) + ViewerGazeControls(other_camera)._render_callback(newton)(other) + assert imgui.scopes and other.scopes and imgui.scopes != other.scopes # Moving one sets that gaze in every environment and redraws the window's camera view. render(_Imgui(sliders=[(True, 20.0), (False, -10.0)])) assert torch.equal(camera.written[-1], torch.tensor([[20.0, -10.0]]).repeat(3, 1)) @@ -638,6 +659,10 @@ def test_viewer_gaze_sliders_follow_and_set_the_gaze_in_newton_windows() -> None assert ("Foveation", 1, 0, 3, "cmf_a 0.591 deg") in imgui.shown # 0.1, 0.591, 1, 10 render(_Imgui(foveation=3)) assert camera.cfg.cmf_a_deg == 10.0 and newton.current_image_view.invalidated == 3 + # The starting constant stays an option after the switch, so the panel can switch back to it. + imgui = _Imgui() + render(imgui) + assert ("Foveation", 3, 0, 3, "cmf_a 10 deg") in imgui.shown # A camera that cannot switch shows its constant as fixed instead. fixed = _SliderCamera(num_envs=1, switchable=False) fixed_controls = ViewerGazeControls(fixed) @@ -664,3 +689,20 @@ def test_every_foveated_camera_adds_its_sliders_on_reset_until_it_is_gone() -> N assert len(newton.callbacks) == 1 del camera assert name not in SimulationContext._reset_callbacks + + +class _UnbuiltRTXCamera(FoveatedRTXCamera): + """An RTX camera made without a simulation, which has nothing to release when collected.""" + + def __del__(self): + pass + + +def test_rtx_cameras_refuse_runtime_cmf_a() -> None: + # OVRTX and Isaac RTX share FoveatedRTXCamera, whose renderers read the retina's lens textures once. + camera = object.__new__(_UnbuiltRTXCamera) + camera._is_initialized = True + camera.cfg = SimpleNamespace(foveated_style="warped_cartesian_as_grid", cmf_a_deg=1.0) + assert not camera.supports_runtime_cmf_a + with pytest.raises(NotImplementedError, match="lens textures"): + camera.set_cmf_a(10.0) diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render.py b/source/isaaclab_fovi/test/test_foveated_camera_render.py index 53f70fb9a458..ed649a08a794 100644 --- a/source/isaaclab_fovi/test/test_foveated_camera_render.py +++ b/source/isaaclab_fovi/test/test_foveated_camera_render.py @@ -65,5 +65,7 @@ def test_foveated_camera_samples_densest_at_the_fixation(ground): cases.foveated_camera_samples_densest_at_the_fixation(ground) +# Only Newton traces rays a camera can replace; test_camera_gaze checks that the RTX camera refuses. +@pytest.mark.parametrize("ground", ["newton_warp", "newton_optix"], indirect=True) def test_cmf_a_switches_the_retina_at_runtime(ground): cases.cmf_a_switches_the_retina_at_runtime(ground) diff --git a/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py b/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py index d31ec6bdf911..e72878601758 100644 --- a/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py +++ b/source/isaaclab_fovi/test/test_foveated_camera_render_ovrtx.py @@ -47,7 +47,3 @@ def test_gaze_stays_relative_to_moved_mounts(ground): def test_foveated_camera_samples_densest_at_the_fixation(ground): cases.foveated_camera_samples_densest_at_the_fixation(ground) - - -def test_cmf_a_switches_the_retina_at_runtime(ground): - cases.cmf_a_switches_the_retina_at_runtime(ground) From 03b0d28a24af3b9d86a1604aa7a2e227b5e03b01 Mon Sep 17 00:00:00 2001 From: nblauch Date: Mon, 23 Nov 2026 21:49:06 -0800 Subject: [PATCH 03/11] Address second review of the viewer gaze and foveation controls Redraw the camera view of every window the controls are in, not only the one that changed. Write slider and steering changes into the camera's own gaze buffer instead of separate copies, and let the example's comparison window keep right and middle presses. Give the retina cache a typed record, mark the runtime cmf_a helpers private, put the example's main before its steering class, and annotate the steering callbacks. --- examples/sensors/foveated_camera.py | 131 +++++++++--------- .../isaaclab_fovi/sensors/foveated_camera.py | 64 +++++---- .../isaaclab_fovi/sensors/gaze_controls.py | 105 ++++++-------- source/isaaclab_fovi/test/test_camera_gaze.py | 8 +- 4 files changed, 156 insertions(+), 152 deletions(-) diff --git a/examples/sensors/foveated_camera.py b/examples/sensors/foveated_camera.py index 1e92cc16fbdd..174d09878ca4 100644 --- a/examples/sensors/foveated_camera.py +++ b/examples/sensors/foveated_camera.py @@ -60,7 +60,7 @@ quat_apply_inverse, quat_from_matrix, ) -from isaaclab.visualizers import SceneCameraCfg, VisualizerCfg +from isaaclab.visualizers import BaseVisualizer, SceneCameraCfg, VisualizerCfg from isaaclab_tasks.utils import preset, setup_preset_cli from isaaclab_tasks.utils.hydra import resolve_task_config @@ -384,69 +384,6 @@ def cover(imgui) -> None: return cover -class GazeSteering: - """Steer the eye's gaze with the mouse and I/J/K/L. - - Left-dragging the viewer steers only the gaze, as I/J/K/L and the side panel's sliders do; a drag that starts over - the viewer's panels stays with them. The viewer itself moves the eye's mount with WASD/QE. - """ - - DRAG_DEG_PER_PIXEL = 0.15 - GAZE_LIMIT_DEG = 85.0 - - def __init__(self, camera: FoveatedCamera, visualizers: list): - self.camera = camera - self.visualizers = visualizers - self.angles = torch.zeros_like(camera.gaze_angles.torch) - self.drag = [0.0, 0.0] - self.press_over_panel = False - for visualizer in visualizers: - window = getattr(newton_window(visualizer), "renderer", None) - native = getattr(window, "window", None) - if native is not None: - native.push_handlers(on_mouse_press=self._on_mouse_press, on_mouse_drag=self._on_mouse_drag) - - def steer(self, tilt_deg: float, pan_deg: float) -> None: - """Turn the gaze by (tilt, pan) [deg], starting from wherever the sliders or a drag left it.""" - # Dragging right looks right (negative pan); dragging up looks up. - pan_deg -= self.drag[0] * self.DRAG_DEG_PER_PIXEL - tilt_deg += self.drag[1] * self.DRAG_DEG_PER_PIXEL - self.drag = [0.0, 0.0] - if not tilt_deg and not pan_deg: - return - self.angles.copy_(self.camera.gaze_angles.torch) - step = self.angles.new_tensor((tilt_deg, pan_deg)) - self.angles.copy_((self.angles + step).clamp(-self.GAZE_LIMIT_DEG, self.GAZE_LIMIT_DEG)) - self.camera.set_gaze_angles(self.angles) - for visualizer in self.visualizers: - # The viewer shows the eye; a new gaze redraws it even while paused. - visualizer.current_image_view.invalidate() - - def _on_mouse_press(self, x, y, button, modifiers): - """Decide where a press's drag goes: inside the comparison image or on the bare view it steers the gaze; on any - other panel, or on the comparison window's title bar or edges, it stays with the panel.""" - from imgui_bundle import imgui - from pyglet import event - - self.press_over_panel = imgui.get_io().want_capture_mouse - if self.press_over_panel and comparison_image_hovered(imgui): - self.press_over_panel = False - # Keep ImGui from taking the press, which would drag the window instead of the gaze. - return event.EVENT_HANDLED - return None - - def _on_mouse_drag(self, x, y, dx, dy, buttons, modifiers): - """Collect left drags that started on the view.""" - from pyglet import event - from pyglet.window import mouse - - if not buttons & mouse.LEFT or self.press_over_panel: - return None - self.drag[0] += dx - self.drag[1] += dy - return event.EVENT_HANDLED - - def main() -> None: """Render the docs scene and let the viewer drive the camera.""" # Config-only registration reuses the standard preset and Hydra override resolver. @@ -538,5 +475,71 @@ def main() -> None: frame += 1 +class GazeSteering: + """Steer the eye's gaze with the mouse and I/J/K/L. + + Left-dragging the viewer steers only the gaze, as I/J/K/L and the side panel's sliders do; a drag that starts over + the viewer's panels stays with them. The viewer itself moves the eye's mount with WASD/QE. + """ + + DRAG_DEG_PER_PIXEL = 0.15 + GAZE_LIMIT_DEG = 85.0 + + def __init__(self, camera: FoveatedCamera, visualizers: list[BaseVisualizer]) -> None: + self.camera = camera + self.visualizers = visualizers + self.drag = [0.0, 0.0] + self.press_over_panel = False + for visualizer in visualizers: + window = getattr(newton_window(visualizer), "renderer", None) + native = getattr(window, "window", None) + if native is not None: + native.push_handlers(on_mouse_press=self._on_mouse_press, on_mouse_drag=self._on_mouse_drag) + + def steer(self, tilt_deg: float, pan_deg: float) -> None: + """Turn the gaze by (tilt, pan) [deg], starting from wherever the sliders or a drag left it.""" + # Dragging right looks right (negative pan); dragging up looks up. + pan_deg -= self.drag[0] * self.DRAG_DEG_PER_PIXEL + tilt_deg += self.drag[1] * self.DRAG_DEG_PER_PIXEL + self.drag = [0.0, 0.0] + if not tilt_deg and not pan_deg: + return + # The camera's stored angles are writable; set_gaze_angles then publishes them. + gaze = self.camera.gaze_angles.torch + gaze.add_(gaze.new_tensor((tilt_deg, pan_deg))).clamp_(-self.GAZE_LIMIT_DEG, self.GAZE_LIMIT_DEG) + self.camera.set_gaze_angles(gaze) + for visualizer in self.visualizers: + # The viewer shows the eye; a new gaze redraws it even while paused. + visualizer.current_image_view.invalidate() + + def _on_mouse_press(self, x: int, y: int, button: int, modifiers: int) -> bool | None: + """Decide where a left press's drag goes: inside the comparison image or on the bare view it steers the gaze; + on any other panel, or on the comparison window's title bar or edges, it stays with the panel. Other buttons + keep their usual handling.""" + from imgui_bundle import imgui + from pyglet import event + from pyglet.window import mouse + + if button != mouse.LEFT: + return None + self.press_over_panel = imgui.get_io().want_capture_mouse + if self.press_over_panel and comparison_image_hovered(imgui): + self.press_over_panel = False + # Keep ImGui from taking the press, which would drag the window instead of the gaze. + return event.EVENT_HANDLED + return None + + def _on_mouse_drag(self, x: int, y: int, dx: int, dy: int, buttons: int, modifiers: int) -> bool | None: + """Collect left drags that started on the view.""" + from pyglet import event + from pyglet.window import mouse + + if not buttons & mouse.LEFT or self.press_over_panel: + return None + self.drag[0] += dx + self.drag[1] += dy + return event.EVENT_HANDLED + + if __name__ == "__main__": main() diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index 79a26fc94df6..683e9aa6bd4d 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -12,11 +12,11 @@ import math import warnings from collections.abc import Mapping, Sequence -from typing import TYPE_CHECKING, ClassVar +from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple import torch import warp as wp -from fovi.sensing.coords import WARPED_CARTESIAN_STYLES +from fovi.sensing.coords import WARPED_CARTESIAN_STYLES, SamplingCoords from fovi.sensing.projection import CameraModel from isaaclab.sensors.camera.camera import Camera @@ -56,17 +56,32 @@ """Axis signs between OpenGL camera-frame directions (x right, y up, -z forward) and ROS ones (x right, y down).""" -def fixed_count_style(style: str) -> bool: +class _Retina(NamedTuple): + """One CMF constant's retina, cached by :meth:`FoveatedCamera.set_cmf_a`.""" + + coords: SamplingCoords + """Sampling coordinates on the sensor device.""" + coords_highres: SamplingCoords | None + """High-resolution ray coordinates, when the retina pools them.""" + rays: torch.Tensor + """Rendered rays in the ROS camera frame, shape (N, 3).""" + render_rays: Any + """The renderer's form of :attr:`rays`, from :meth:`FoveatedCamera._render_rays`.""" + pooler: Any + """The pooler of :attr:`coords`, or None.""" + + +def _fixed_count_style(style: str) -> bool: """Whether a sampling style keeps its sample count for every CMF constant: the warped-Cartesian styles, whose count is the grid's, and the ``_fixn`` isotropic ones, which fix it.""" return style in WARPED_CARTESIAN_STYLES or "fixn" in style -def runtime_cmf_a_limitation(camera: FoveatedCamera) -> str: +def _runtime_cmf_a_limitation(camera: FoveatedCamera) -> str: """Why ``camera`` cannot change its CMF constant at runtime, for messages and the viewer panel.""" if not camera._renders_switchable_rays: return "OVRTX and Isaac RTX read the retina's lens textures once, when the renderer loads the stage" - if not fixed_count_style(camera.cfg.foveated_style): + if not _fixed_count_style(camera.cfg.foveated_style): return f"a {camera.cfg.foveated_style!r} retina's sample count depends on cmf_a" return "the retina can change its cmf_a at runtime" @@ -145,7 +160,7 @@ def __init__(self, cfg: FoveatedCameraCfg, *, turns_pose_by_gaze: bool = False): self._segmentation_neighbors: torch.Tensor | None = None self._sensor_fov_valid: torch.Tensor | None = None self._pooler = None - self._retinas: dict[float, tuple] = {} + self._retinas: dict[float, _Retina] = {} """Retinas built for :meth:`set_cmf_a`, by CMF constant.""" self.mount_turns = 0 """How many times :meth:`set_world_poses` or :meth:`set_world_poses_from_view` has turned the camera's mount.""" @@ -224,7 +239,7 @@ def mount_quat_w_ros(self) -> ProxyArray: def supports_runtime_cmf_a(self) -> bool: """Whether :meth:`set_cmf_a` can change this camera's foveation while it runs: on Newton, for retinas whose sample count does not depend on the CMF constant (the warped-Cartesian and ``_fixn`` isotropic styles).""" - return self._renders_switchable_rays and fixed_count_style(self.cfg.foveated_style) + return self._renders_switchable_rays and _fixed_count_style(self.cfg.foveated_style) def set_gaze_angles(self, angles_deg: torch.Tensor) -> None: """Turn the retina to (tilt, pan) [deg] from the physical camera's optical axis. @@ -330,26 +345,27 @@ def set_cmf_a(self, cmf_a_deg: float) -> None: if not self.is_initialized: raise RuntimeError("Initialize the foveated camera (reset the simulation) before changing its cmf_a.") if not self.supports_runtime_cmf_a: - raise NotImplementedError(runtime_cmf_a_limitation(self)) + raise NotImplementedError(_runtime_cmf_a_limitation(self)) cmf_a_deg = float(cmf_a_deg) if cmf_a_deg == self.cfg.cmf_a_deg: return if not self._retinas: rays = self._gaze_rays.clone() - self._retinas[self.cfg.cmf_a_deg] = ( - self._sampling_coords, - self._sampling_coords_highres, - rays, - self._render_rays(rays), - self._pooler, + self._retinas[self.cfg.cmf_a_deg] = _Retina( + self._sampling_coords, self._sampling_coords_highres, rays, self._render_rays(rays), self._pooler ) if cmf_a_deg not in self._retinas: self._retinas[cmf_a_deg] = self._build_retina(cmf_a_deg) - self._sampling_coords, self._sampling_coords_highres, rays, render_rays, self._pooler = self._retinas[cmf_a_deg] + retina = self._retinas[cmf_a_deg] + self._sampling_coords, self._sampling_coords_highres, self._pooler = ( + retina.coords, + retina.coords_highres, + retina.pooler, + ) self._ray_coords = self._sampling_coords_highres or self._sampling_coords # The sensor mask, the grid layout and the renderer read the rays in place, so they follow without new launches. - self._gaze_rays.copy_(rays) - self._write_render_rays(render_rays) + self._gaze_rays.copy_(retina.rays) + self._write_render_rays(retina.render_rays) if self._segmentation_neighbors is not None: self._prepare_segmentation_pooling(["semantic_segmentation"]) self.cfg.cmf_a_deg = cmf_a_deg @@ -413,7 +429,7 @@ def _retina_rays(self, coords) -> torch.Tensor: rays = retinal_directions(coords.cartesian, coords.fov, rotation_deg) return (rays * rays.new_tensor(OPENGL_TO_ROS_AXES)).float().contiguous() - def _build_retina(self, cmf_a_deg: float) -> tuple: + def _build_retina(self, cmf_a_deg: float) -> _Retina: """The retina at ``cmf_a_deg``: its coordinates on the sensor device, its rays, the renderer's copy of them, and its pooler.""" cfg = self.cfg.replace(cmf_a_deg=cmf_a_deg) @@ -427,20 +443,20 @@ def _build_retina(self, cmf_a_deg: float) -> tuple: ray_coords.valid_mask, self._ray_coords.valid_mask ): raise NotImplementedError( - f"cmf_a {cmf_a_deg:g} changes this retina's samples; {runtime_cmf_a_limitation(self)}" + f"cmf_a {cmf_a_deg:g} changes this retina's samples; {_runtime_cmf_a_limitation(self)}" ) pooler, _ = build_pooler(cfg, lowres, highres, device=str(self._device)) rays = self._retina_rays(ray_coords) - return lowres, highres, rays, self._render_rays(rays), pooler + return _Retina(lowres, highres, rays, self._render_rays(rays), pooler) - def _render_rays(self, rays: torch.Tensor): + def _render_rays(self, rays: torch.Tensor) -> Any: """The renderer's form of ``rays`` (ROS frame), which :meth:`_write_render_rays` hands it; only renderers that trace the camera's rays support it.""" - raise NotImplementedError(runtime_cmf_a_limitation(self)) + raise NotImplementedError(_runtime_cmf_a_limitation(self)) - def _write_render_rays(self, render_rays) -> None: + def _write_render_rays(self, render_rays: Any) -> None: """Hand the renderer rays made by :meth:`_render_rays`.""" - raise NotImplementedError(runtime_cmf_a_limitation(self)) + raise NotImplementedError(_runtime_cmf_a_limitation(self)) def _allocate_gaze(self) -> None: """Allocate one stored gaze per camera, on the optical axis, its rotation and the mount, on the sensor diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py index 60918a63301a..64de66b22d84 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py @@ -8,11 +8,8 @@ from __future__ import annotations import weakref -from collections.abc import Callable from typing import TYPE_CHECKING, Any -import torch - from isaaclab.sim import SimulationContext if TYPE_CHECKING: @@ -31,52 +28,46 @@ class ViewerGazeControls: gaze action or a drag in the viewer. Moving one sets that gaze in every environment; a gaze action that sets the gaze every step overrides them. The foveation slider steps through :attr:`FoveatedCameraCfg.viewer_cmf_a_values` and the camera's starting CMF constant where :meth:`FoveatedCamera.set_cmf_a` can change the retina, and otherwise - shows the CMF constant and why it is fixed. + shows the CMF constant and why it is fixed. A change in any window redraws the camera view of every window. """ def __init__(self, camera: FoveatedCamera): - """Create the sliders for ``camera``, which they hold weakly: once it is gone, they draw nothing.""" + """Create the sliders for ``camera``, which they hold weakly: once it is gone, they draw nothing. + + The viewer cannot unregister a UI callback, so each window keeps a callback that then returns at once. + """ self._camera = weakref.ref(camera) self._label = camera.cfg.prim_path.rsplit("/", 1)[-1] self._cmf_a_values = sorted( {float(value) for value in camera.cfg.viewer_cmf_a_values} | {float(camera.cfg.cmf_a_deg)} ) """The foveation slider's CMF constants [deg]; the starting one stays an option after a switch.""" - self._attached: set[int] = set() - self._angles: torch.Tensor | None = None - - def detach(self) -> None: - """Release the gaze buffer once the camera is gone; the windows' callbacks then draw nothing. - - The viewer cannot unregister a UI callback, so each window keeps a callback that returns at once. - """ - self._angles = None + self._windows: list[BaseVisualizer] = [] + """The Newton viewer windows that show the controls.""" def attach(self, sim: SimulationContext) -> None: """Add the sliders to every Newton viewer window of ``sim`` that does not show them yet.""" for visualizer in sim.visualizers: - if visualizer.cfg.backend.visualizer_type == "newton" and id(visualizer) not in self._attached: - self._attached.add(id(visualizer)) - visualizer.register_ui_callback(self._render_callback(visualizer), position="side") - - def _render_callback(self, visualizer: BaseVisualizer) -> Callable[[Any], None]: - """Return the ImGui callback that draws the sliders in one window.""" - - def render(imgui: Any) -> None: - camera = self._camera() - if camera is None or not camera.is_initialized: - return - # Each camera's widgets share labels, so they need their own ID scope; a header does not open one. - imgui.push_id(f"isaaclab_fovi.viewer_gaze_controls.{id(self)}") - try: - if imgui.collapsing_header(f"Foveated camera: {self._label}"): - self._draw_controls(imgui, camera, visualizer) - finally: - imgui.pop_id() - - return render - - def _draw_controls(self, imgui: Any, camera: FoveatedCamera, visualizer: BaseVisualizer) -> None: + if visualizer.cfg.backend.visualizer_type == "newton" and all( + window is not visualizer for window in self._windows + ): + self._windows.append(visualizer) + visualizer.register_ui_callback(self._render, position="side") + + def _render(self, imgui: Any) -> None: + """Draw the controls in the side panel of one window.""" + camera = self._camera() + if camera is None or not camera.is_initialized: + return + # Each camera's widgets share labels, so they need their own ID scope; a header does not open one. + imgui.push_id(f"isaaclab_fovi.viewer_gaze_controls.{id(self)}") + try: + if imgui.collapsing_header(f"Foveated camera: {self._label}"): + self._draw_controls(imgui, camera) + finally: + imgui.pop_id() + + def _draw_controls(self, imgui: Any, camera: FoveatedCamera) -> None: """Draw the gaze sliders, the center button and the foveation control.""" tilt, pan = camera.gaze_angles.torch[0].tolist() tilt_changed, tilt = imgui.slider_float("Gaze tilt", tilt, -GAZE_LIMIT_DEG, GAZE_LIMIT_DEG, "%.1f deg") @@ -85,18 +76,22 @@ def _draw_controls(self, imgui: Any, camera: FoveatedCamera, visualizer: BaseVis imgui.set_tooltip("Positive tilt looks up, positive pan looks left. A gaze action overrides these.") center = imgui.button("Center gaze") if tilt_changed or pan_changed or center: - self._set_gaze(camera, (0.0, 0.0) if center else (tilt, pan), visualizer) - self._draw_foveation(imgui, camera, visualizer) - - def _draw_foveation(self, imgui: Any, camera: FoveatedCamera, visualizer: BaseVisualizer) -> None: + # The camera's stored angles are writable; set_gaze_angles then publishes them. + gaze = camera.gaze_angles.torch + gaze[:] = gaze.new_tensor((0.0, 0.0) if center else (tilt, pan)) + camera.set_gaze_angles(gaze) + self._redraw() + self._draw_foveation(imgui, camera) + + def _draw_foveation(self, imgui: Any, camera: FoveatedCamera) -> None: """Draw the CMF constant: a slider over the configured values, or the fixed value and why it is fixed.""" - from .foveated_camera import runtime_cmf_a_limitation # The camera module imports this one. + from .foveated_camera import _runtime_cmf_a_limitation # The camera module imports this one. current = float(camera.cfg.cmf_a_deg) if not camera.supports_runtime_cmf_a: imgui.text(f"Foveation: cmf_a {current:g} deg (fixed)") if imgui.is_item_hovered(): - imgui.set_tooltip(f"Fixed because {runtime_cmf_a_limitation(camera)}.") + imgui.set_tooltip(f"Fixed because {_runtime_cmf_a_limitation(camera)}.") return values = self._cmf_a_values if current in self._cmf_a_values else sorted({*self._cmf_a_values, current}) index = values.index(current) @@ -105,31 +100,19 @@ def _draw_foveation(self, imgui: Any, camera: FoveatedCamera, visualizer: BaseVi imgui.set_tooltip("Smaller cmf_a concentrates the samples at the fixation; larger spreads them evenly.") if changed and values[index] != current: camera.set_cmf_a(values[index]) - view = getattr(visualizer, "current_image_view", None) + self._redraw() + + def _redraw(self) -> None: + """Redraw the camera view of every window, which shows the change even while paused.""" + for window in self._windows: + view = getattr(window, "current_image_view", None) if view is not None: view.invalidate() - def _set_gaze(self, camera: FoveatedCamera, angles: tuple[float, float], visualizer: BaseVisualizer) -> None: - """Set ``angles`` [deg] in every environment and redraw the window's camera view, even while paused.""" - gaze = camera.gaze_angles.torch - if self._angles is None or self._angles.shape != gaze.shape: - self._angles = torch.empty_like(gaze) - self._angles[:] = torch.tensor(angles, device=gaze.device) - camera.set_gaze_angles(self._angles) - view = getattr(visualizer, "current_image_view", None) - if view is not None: - view.invalidate() - def add_viewer_gaze_controls(camera: FoveatedCamera) -> None: """Show ``camera``'s gaze sliders in the Newton viewer windows of every simulation reset while it exists.""" controls = ViewerGazeControls(camera) name = f"isaaclab_fovi.viewer_gaze_controls.{id(controls)}" SimulationContext.add_reset_callback(name, controls.attach) - weakref.finalize(camera, _forget_controls, name, controls) - - -def _forget_controls(name: str, controls: ViewerGazeControls) -> None: - """Stop adding a collected camera's controls on reset and release their buffers.""" - SimulationContext.remove_reset_callback(name) - controls.detach() + weakref.finalize(camera, SimulationContext.remove_reset_callback, name) diff --git a/source/isaaclab_fovi/test/test_camera_gaze.py b/source/isaaclab_fovi/test/test_camera_gaze.py index 8be1351eeca1..f3f1003f2f96 100644 --- a/source/isaaclab_fovi/test/test_camera_gaze.py +++ b/source/isaaclab_fovi/test/test_camera_gaze.py @@ -644,12 +644,14 @@ def test_viewer_gaze_sliders_follow_and_set_the_gaze_in_newton_windows() -> None assert ("Gaze tilt", -30.0) in imgui.shown and ("Gaze pan", 40.0) in imgui.shown and not camera.written # Two cameras' sections open different ID scopes, so their same-named widgets stay apart. other, other_camera = _Imgui(), _SliderCamera(num_envs=1) - ViewerGazeControls(other_camera)._render_callback(newton)(other) + ViewerGazeControls(other_camera)._render(other) assert imgui.scopes and other.scopes and imgui.scopes != other.scopes - # Moving one sets that gaze in every environment and redraws the window's camera view. + # Moving one sets that gaze in every environment and redraws the camera view of every window, even another one. + second = _visualizer("newton") + controls.attach(SimpleNamespace(visualizers=[newton, second])) render(_Imgui(sliders=[(True, 20.0), (False, -10.0)])) assert torch.equal(camera.written[-1], torch.tensor([[20.0, -10.0]]).repeat(3, 1)) - assert newton.current_image_view.invalidated == 1 + assert newton.current_image_view.invalidated == 1 and second.current_image_view.invalidated == 1 render(_Imgui(button=True)) assert not camera.written[-1].any() From a119576a670446be16b749bc1a39b30e9b75a14b Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 24 Nov 2026 11:57:50 -0800 Subject: [PATCH 04/11] Run the foveated-camera example on Isaac RTX With renderer=isaacsim_rtx the example crashed while Kit started: its top-level imports loaded the pip USD library before launch_simulation started Kit, whose own USD then failed to load. The example now imports pxr inside the clutter helper, which runs after launch, and imports the FoveatedCamera and BaseVisualizer runtime classes, which load USD, only for type checking, as the microduck-warehouse demo keeps runtime imports out of module scope. --- examples/sensors/foveated_camera.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/examples/sensors/foveated_camera.py b/examples/sensors/foveated_camera.py index 174d09878ca4..e97846b848fe 100644 --- a/examples/sensors/foveated_camera.py +++ b/examples/sensors/foveated_camera.py @@ -28,13 +28,14 @@ import math import time from collections.abc import Callable +from typing import TYPE_CHECKING import gymnasium as gym import numpy as np import torch import warp as wp from fovi.sensing.projection import gaze_rotation -from isaaclab_fovi.sensors import FoveatedCamera, FoveatedCameraCfg +from isaaclab_fovi.sensors import FoveatedCameraCfg from isaaclab_fovi.sensors.native_grid import GRID_STYLE, native_grid_exit_uv from isaaclab_isaacsim.physics import PhysxCfg from isaaclab_isaacsim.renderers import IsaacRtxRendererCfg @@ -43,8 +44,6 @@ from isaaclab_ov.renderers import OVRTXRendererCfg from PIL import Image, ImageDraw, ImageFont -from pxr import Usd, UsdGeom - import isaaclab.sim as sim_utils from isaaclab.app import add_launcher_args, launch_simulation from isaaclab.assets import AssetBaseCfg, RigidObjectCfg @@ -60,12 +59,18 @@ quat_apply_inverse, quat_from_matrix, ) -from isaaclab.visualizers import BaseVisualizer, SceneCameraCfg, VisualizerCfg +from isaaclab.visualizers import SceneCameraCfg, VisualizerCfg from isaaclab_tasks.utils import preset, setup_preset_cli from isaaclab_tasks.utils.hydra import resolve_task_config from isaaclab_tasks.utils.presets import MultiBackendRendererCfg +if TYPE_CHECKING: + # Importing the runtime classes loads USD, which must come from Kit when the selected backends start it. + from isaaclab_fovi.sensors import FoveatedCamera + + from isaaclab.visualizers import BaseVisualizer + logger = logging.getLogger("isaaclab.examples.foveated_camera") OFFSET = (0.5, 0.5) @@ -140,6 +145,9 @@ def _eye_rotation() -> torch.Tensor: def _add_clutter(scene_cfg: InteractiveSceneCfg) -> dict[str, tuple[float, float, float]]: """Place the docs assets on the ground and return their centres in the scene frame.""" + # USD comes from Kit when the selected backends start it, so it is imported once the simulation has launched. + from pxr import Usd, UsdGeom + centres = {} for name, (usd, azimuth, distance) in OBJECTS.items(): stage = Usd.Stage.Open(retrieve_file_path(usd)) From 08968a9c2115d13555b346f2b7ab3d3786e5f958 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 24 Nov 2026 12:54:42 -0800 Subject: [PATCH 05/11] List the foveated-camera example's Isaac RTX fix under Fixed The example crashed on main with renderer=isaacsim_rtx; a119576 fixed it without a changelog entry. The entry goes in isaaclab's changelog, where the example was added. --- .../changelog.d/feat-isaaclab-fovi-viewer-controls.fixed.rst | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 source/isaaclab/changelog.d/feat-isaaclab-fovi-viewer-controls.fixed.rst diff --git a/source/isaaclab/changelog.d/feat-isaaclab-fovi-viewer-controls.fixed.rst b/source/isaaclab/changelog.d/feat-isaaclab-fovi-viewer-controls.fixed.rst new file mode 100644 index 000000000000..1e545e111b51 --- /dev/null +++ b/source/isaaclab/changelog.d/feat-isaaclab-fovi-viewer-controls.fixed.rst @@ -0,0 +1,3 @@ +* Fixed the ``foveated-camera`` example crashing while Kit started with ``renderer=isaacsim_rtx``: its top-level + imports loaded USD before Kit, whose own USD then failed to load. It now imports USD once the simulation has + launched. From 44eceea9481d2efc720dac90f0bc396dc5d4d7d6 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 24 Nov 2026 13:12:10 -0800 Subject: [PATCH 06/11] Show viewer gaze controls for the camera a window shows, without config keys FoveatedCameraCfg carried two viewer settings: viewer_gaze_controls, which only kept the example's helper overview camera out of the side panel, and viewer_cmf_a_values, the foveation slider's stops. Both are gone. A Newton window now draws a camera's controls while its camera view shows that camera, so a camera the viewer cannot show, such as the overview, has none, and switching cameras in the window's menu switches the controls. The stops are ViewerGazeControls.cmf_a_values, now 0.001 to 1000 degrees in decades, which the sliders read as they draw, with each camera's starting cmf_a added. ViewerGazeControls is exported and documented for that. The foveated-camera example sets the stops with --cmf_a_values, comma separated so that the overrides after it stay overrides. --- .../api/lab_fovi/isaaclab_fovi.sensors.rst | 9 ++++ .../experimental-features/foveated_camera.rst | 20 ++++---- examples/sensors/foveated_camera.py | 31 +++++++++-- ...at-isaaclab-fovi-viewer-controls.added.rst | 6 +-- .../isaaclab_fovi/sensors/__init__.pyi | 2 + .../isaaclab_fovi/sensors/foveated_camera.py | 4 +- .../sensors/foveated_camera_cfg.py | 7 --- .../isaaclab_fovi/sensors/gaze_controls.py | 50 ++++++++++-------- source/isaaclab_fovi/test/test_camera_gaze.py | 51 ++++++++++++++----- 9 files changed, 121 insertions(+), 59 deletions(-) diff --git a/docs/source/api/lab_fovi/isaaclab_fovi.sensors.rst b/docs/source/api/lab_fovi/isaaclab_fovi.sensors.rst index 32c513aace16..e0e84bea5901 100644 --- a/docs/source/api/lab_fovi/isaaclab_fovi.sensors.rst +++ b/docs/source/api/lab_fovi/isaaclab_fovi.sensors.rst @@ -11,6 +11,7 @@ isaaclab_fovi.sensors FoveatedCameraCfg FoveatedNewtonCamera FoveatedRTXCamera + ViewerGazeControls Foveated Camera @@ -39,3 +40,11 @@ Constructing :class:`FoveatedCamera` returns one of the following implementation .. autoclass:: FoveatedRTXCamera :members: :show-inheritance: + +Viewer Controls +--------------- + +Each foveated camera adds these controls to the side panel of every Newton viewer window that shows it. + +.. autoclass:: ViewerGazeControls + :members: cmf_a_values diff --git a/docs/source/experimental-features/foveated_camera.rst b/docs/source/experimental-features/foveated_camera.rst index 4a2f04a2cc20..628751ec4fc8 100644 --- a/docs/source/experimental-features/foveated_camera.rst +++ b/docs/source/experimental-features/foveated_camera.rst @@ -19,8 +19,8 @@ The Newton viewer shows the retina, covered at launch by a window that shows the beside the retina: the green lens boundary follows the camera mount, and the blue gaze circle and sampling grid show the retina's coverage. Use WASD or the arrow keys to move the camera and Q/E to lower or raise it. Drag with the left mouse button, or press I/K and J/L, to steer the gaze; the side panel's sliders follow the gaze and set it, and on -Newton its foveation slider steps the CMF constant through ``env.scene.eye.viewer_cmf_a_values``. H shows or hides -the viewer controls. Pass ``--target power_drill`` to start fixating the drill. +Newton its foveation slider steps the CMF constant, through other stops with ``--cmf_a_values 0.2,2,20`` plus the +camera's own. H shows or hides the viewer controls. Pass ``--target power_drill`` to start fixating the drill. .. figure:: ../_static/overview/sensors/foveated_camera_overview.jpg :alt: A retina behind a 180-degree fisheye lens on the viewing sphere, and its rendered images at two fixations. @@ -101,14 +101,14 @@ Use :attr:`~sensors.FoveatedCameraCfg.retinal_window_fraction` to shrink this wi :attr:`~sensors.FoveatedCameraCfg.image_rotation_deg` to compensate for mount roll. Call ``camera.set_gaze_angles(angles)`` with shape ``(num_envs, 2)`` in tilt, pan order and in degrees. -Positive tilt looks up and positive pan looks left. In a Newton viewer, each foveated camera also adds tilt and pan -sliders to the side panel, which follow its gaze and set it in every environment; a gaze action overrides them each -step. A foveation slider beside them switches the CMF constant among -:attr:`~sensors.FoveatedCameraCfg.viewer_cmf_a_values` with :meth:`~sensors.FoveatedCamera.set_cmf_a`, which -re-samples the retina in place. That works on Newton for styles whose sample count does not depend on the constant, -the warped-Cartesian and ``_fixn`` isotropic ones; OVRTX and Isaac RTX read their lens textures once, so there the -slider shows the constant as fixed. Set :attr:`~sensors.FoveatedCameraCfg.viewer_gaze_controls` to ``False`` to -leave a camera out. :meth:`~sensors.FoveatedCamera.get_world_poses` reports the mount pose. Enable +Positive tilt looks up and positive pan looks left. While a Newton viewer window shows a foveated camera, its side +panel has tilt and pan sliders for it, which follow its gaze and set it in every environment; a gaze action +overrides them each step. A foveation slider beside them switches the CMF constant among +:attr:`~sensors.ViewerGazeControls.cmf_a_values`, which can be assigned to change the stops, with +:meth:`~sensors.FoveatedCamera.set_cmf_a`, which re-samples the retina in place. That works on Newton for styles +whose sample count does not depend on the constant, the warped-Cartesian and ``_fixn`` isotropic ones; OVRTX and +Isaac RTX read their lens textures once, so there the slider shows the constant as fixed. +:meth:`~sensors.FoveatedCamera.get_world_poses` reports the mount pose. Enable :attr:`~sensors.FoveatedCameraCfg.mask_to_sensor_fov` to zero rays that fall outside the physical image as the gaze moves. diff --git a/examples/sensors/foveated_camera.py b/examples/sensors/foveated_camera.py index e97846b848fe..cb5f76febecf 100644 --- a/examples/sensors/foveated_camera.py +++ b/examples/sensors/foveated_camera.py @@ -9,8 +9,8 @@ the retina; move or resize that window to see the viewer's own view of the retina. Use WASD or the arrow keys to move the camera, and Q/E to lower or raise it. Drag with the left mouse button, or press I/K and J/L, to steer the gaze. -The side panel's sliders follow the gaze and set it, and step the foveation (cmf_a) through -``env.scene.eye.viewer_cmf_a_values`` on Newton. Press H to show or hide the viewer controls. +The side panel's sliders follow the gaze and set it, and on Newton step the foveation (cmf_a) through +--cmf_a_values. Press H to show or hide the viewer controls. Use --target to choose where the retina looks at launch. .. code-block:: bash @@ -19,6 +19,8 @@ uv run --extra fovi --extra ovrtx isaaclab example foveated-camera renderer=ovrtx --viz newton # A large CMF constant gives the matched non-foveated retina, for comparison: uv run --extra fovi isaaclab example foveated-camera env.scene.eye.cmf_a_deg=1000 + # Other stops for the foveation slider, with the camera's own cmf_a added: + uv run --extra fovi isaaclab example foveated-camera --cmf_a_values 0.2,2,20 """ from __future__ import annotations @@ -125,11 +127,29 @@ def outline(mask: torch.Tensor) -> torch.Tensor: return mask & torch.nn.functional.max_pool2d((~mask)[None, None].float(), 3, 1, 1)[0, 0].bool() +def _cmf_a_values(text: str) -> tuple[float, ...]: + """Parse comma-separated CMF constants [deg], each positive and finite.""" + try: + values = tuple(float(value) for value in text.split(",")) + except ValueError: + raise argparse.ArgumentTypeError(f"expected comma-separated numbers, got {text!r}") from None + if not all(0 < value < math.inf for value in values): + raise argparse.ArgumentTypeError(f"expected positive, finite CMF constants, got {text!r}") + return values + + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument( "--max_steps", type=int, default=-1, help="Number of render frames; -1 runs until the viewer closes." ) parser.add_argument("--target", choices=OBJECTS, help="Set the initial gaze toward this object.") +parser.add_argument( + "--cmf_a_values", + type=_cmf_a_values, + metavar="DEG,DEG,...", + help="Comma-separated CMF constants [deg] the side panel's foveation slider steps through, with the camera's own" + " added.", +) add_launcher_args(parser) parser.set_defaults(visualizer=["newton"]) args_cli, overrides = setup_preset_cli(parser) @@ -404,6 +424,11 @@ def main() -> None: if cfg.scene.eye.renderer_cfg.renderer_type == "ovrtx": print("Starting OVRTX. The first frame can take several minutes with a cold shader cache.", flush=True) with launch_simulation(cfg, args_cli): + if args_cli.cmf_a_values is not None: + # The panel's controls load USD, so they are imported once the simulation has launched. + from isaaclab_fovi.sensors import ViewerGazeControls + + ViewerGazeControls.cmf_a_values = args_cli.cmf_a_values visualizer_types = {v.backend.visualizer_type for v in cfg.sim.visualizer_cfgs} if visualizer_types - {"newton"}: logger.warning( @@ -428,8 +453,6 @@ def main() -> None: pool_enabled=False, mask_to_sensor_fov=True, data_types=["rgb"], - # The overview only draws the panel; the viewer's gaze sliders are for the eye. - viewer_gaze_controls=False, ) scene = instantiate(cfg.scene) sim.register_interactive_scene(scene) diff --git a/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-viewer-controls.added.rst b/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-viewer-controls.added.rst index 1f55e53a2ce6..6ca915206495 100644 --- a/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-viewer-controls.added.rst +++ b/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-viewer-controls.added.rst @@ -1,5 +1,5 @@ -* Added gaze and foveation controls to the Newton viewer's side panel for every foveated camera - (``viewer_gaze_controls``), with sliders kept in sync with the camera's gaze and a discrete, log-spaced - ``cmf_a`` selector (``viewer_cmf_a_values``). +* Added gaze and foveation controls for foveated cameras to the Newton viewer's side panel, shown while a window + shows the camera, with sliders kept in sync with the camera's gaze and a discrete, log-spaced ``cmf_a`` selector + (:attr:`~isaaclab_fovi.sensors.ViewerGazeControls.cmf_a_values`). * Added :meth:`~isaaclab_fovi.sensors.FoveatedCamera.set_cmf_a`, which changes the CMF constant of fixed-count Newton foveated cameras at runtime. diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.pyi b/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.pyi index 09fec5f420b4..5555cfcdcaff 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.pyi +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/__init__.pyi @@ -8,9 +8,11 @@ __all__ = [ "FoveatedCameraCfg", "FoveatedNewtonCamera", "FoveatedRTXCamera", + "ViewerGazeControls", ] from .foveated_camera import FoveatedCamera from .foveated_camera_cfg import FoveatedCameraCfg from .foveated_newton_camera import FoveatedNewtonCamera from .foveated_rtx_camera import FoveatedRTXCamera +from .gaze_controls import ViewerGazeControls diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py index 683e9aa6bd4d..7fa4f9f2d5ab 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera.py @@ -165,8 +165,8 @@ def __init__(self, cfg: FoveatedCameraCfg, *, turns_pose_by_gaze: bool = False): self.mount_turns = 0 """How many times :meth:`set_world_poses` or :meth:`set_world_poses_from_view` has turned the camera's mount.""" super().__init__(cfg) - if cfg.viewer_gaze_controls: - add_viewer_gaze_controls(self) + # Each Newton viewer window draws the controls while it shows this camera. + add_viewer_gaze_controls(self) @property def image_shape(self) -> tuple[int, int]: diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py index 241befabc9d2..1dc9b4e9533b 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/foveated_camera_cfg.py @@ -62,13 +62,6 @@ class FoveatedCameraCfg(CameraCfg): mask_to_sensor_fov: bool = False """Zero the samples outside the physical camera's image at the current gaze.""" - viewer_gaze_controls: bool = True - """Add this camera's gaze and foveation controls to the side panel of each Newton viewer window.""" - - viewer_cmf_a_values: tuple[float, ...] = (0.1, 0.3, 1.0, 3.0, 10.0, 30.0, 100.0) - """CMF constants [deg] the viewer's foveation control offers, with :attr:`cmf_a_deg` added; see - :meth:`FoveatedCamera.set_cmf_a`.""" - retinal_window_fraction: float = 1.0 """Diameter of the retinal window as a fraction of the reference image side.""" diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py index 64de66b22d84..bee44f45e595 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py @@ -8,7 +8,8 @@ from __future__ import annotations import weakref -from typing import TYPE_CHECKING, Any +from functools import partial +from typing import TYPE_CHECKING, Any, ClassVar from isaaclab.sim import SimulationContext @@ -22,15 +23,22 @@ class ViewerGazeControls: - """Gaze and foveation controls for one foveated camera in each Newton viewer window. - - The tilt and pan sliders show the first environment's gaze every frame, so they follow whatever sets it, such as a - gaze action or a drag in the viewer. Moving one sets that gaze in every environment; a gaze action that sets the - gaze every step overrides them. The foveation slider steps through :attr:`FoveatedCameraCfg.viewer_cmf_a_values` - and the camera's starting CMF constant where :meth:`FoveatedCamera.set_cmf_a` can change the retina, and otherwise - shows the CMF constant and why it is fixed. A change in any window redraws the camera view of every window. + """Gaze and foveation controls for one foveated camera, in the side panel of each Newton viewer window that shows + it. + + A window draws the controls while its camera view shows the camera, so a camera the viewer cannot show, or another + camera chosen in the window's camera menu, has none. The tilt and pan sliders show the first environment's gaze + every frame, so they follow whatever sets it, such as a gaze action or a drag in the viewer. Moving one sets that + gaze in every environment; a gaze action that sets the gaze every step overrides them. The foveation slider steps + through :attr:`cmf_a_values` and the camera's starting CMF constant where :meth:`FoveatedCamera.set_cmf_a` can + change the retina, and otherwise shows the CMF constant and why it is fixed. A change in any window redraws the + camera view of every window. """ + cmf_a_values: ClassVar[tuple[float, ...]] = (0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 1000.0) + """CMF constants [deg] the foveation slider offers every camera, with its starting one. Assign another tuple to + change them; the sliders read it as they draw.""" + def __init__(self, camera: FoveatedCamera): """Create the sliders for ``camera``, which they hold weakly: once it is gone, they draw nothing. @@ -38,27 +46,28 @@ def __init__(self, camera: FoveatedCamera): """ self._camera = weakref.ref(camera) self._label = camera.cfg.prim_path.rsplit("/", 1)[-1] - self._cmf_a_values = sorted( - {float(value) for value in camera.cfg.viewer_cmf_a_values} | {float(camera.cfg.cmf_a_deg)} - ) - """The foveation slider's CMF constants [deg]; the starting one stays an option after a switch.""" + self._start_cmf_a = float(camera.cfg.cmf_a_deg) + """The camera's starting CMF constant [deg], which stays a stop of the foveation slider after a switch.""" self._windows: list[BaseVisualizer] = [] - """The Newton viewer windows that show the controls.""" + """The Newton viewer windows that draw the controls while they show the camera.""" def attach(self, sim: SimulationContext) -> None: - """Add the sliders to every Newton viewer window of ``sim`` that does not show them yet.""" + """Add the controls to every Newton viewer window of ``sim`` that does not have them yet.""" for visualizer in sim.visualizers: if visualizer.cfg.backend.visualizer_type == "newton" and all( window is not visualizer for window in self._windows ): self._windows.append(visualizer) - visualizer.register_ui_callback(self._render, position="side") + visualizer.register_ui_callback(partial(self._render, visualizer), position="side") - def _render(self, imgui: Any) -> None: - """Draw the controls in the side panel of one window.""" + def _render(self, window: BaseVisualizer, imgui: Any) -> None: + """Draw the controls in the side panel of ``window`` while its camera view shows the camera.""" camera = self._camera() if camera is None or not camera.is_initialized: return + view = window.current_image_view + if view is None or view.camera is not camera: + return # Each camera's widgets share labels, so they need their own ID scope; a header does not open one. imgui.push_id(f"isaaclab_fovi.viewer_gaze_controls.{id(self)}") try: @@ -84,7 +93,7 @@ def _draw_controls(self, imgui: Any, camera: FoveatedCamera) -> None: self._draw_foveation(imgui, camera) def _draw_foveation(self, imgui: Any, camera: FoveatedCamera) -> None: - """Draw the CMF constant: a slider over the configured values, or the fixed value and why it is fixed.""" + """Draw the CMF constant: a slider over :attr:`cmf_a_values`, or the fixed value and why it is fixed.""" from .foveated_camera import _runtime_cmf_a_limitation # The camera module imports this one. current = float(camera.cfg.cmf_a_deg) @@ -93,7 +102,7 @@ def _draw_foveation(self, imgui: Any, camera: FoveatedCamera) -> None: if imgui.is_item_hovered(): imgui.set_tooltip(f"Fixed because {_runtime_cmf_a_limitation(camera)}.") return - values = self._cmf_a_values if current in self._cmf_a_values else sorted({*self._cmf_a_values, current}) + values = sorted({float(value) for value in self.cmf_a_values} | {self._start_cmf_a, current}) index = values.index(current) changed, index = imgui.slider_int("Foveation", index, 0, len(values) - 1, f"cmf_a {current:g} deg") if imgui.is_item_hovered(): @@ -111,7 +120,8 @@ def _redraw(self) -> None: def add_viewer_gaze_controls(camera: FoveatedCamera) -> None: - """Show ``camera``'s gaze sliders in the Newton viewer windows of every simulation reset while it exists.""" + """Add ``camera``'s controls to the Newton viewer windows of every simulation reset while it exists; a window + draws them while it shows the camera.""" controls = ViewerGazeControls(camera) name = f"isaaclab_fovi.viewer_gaze_controls.{id(controls)}" SimulationContext.add_reset_callback(name, controls.attach) diff --git a/source/isaaclab_fovi/test/test_camera_gaze.py b/source/isaaclab_fovi/test/test_camera_gaze.py index f3f1003f2f96..68501f31e2bf 100644 --- a/source/isaaclab_fovi/test/test_camera_gaze.py +++ b/source/isaaclab_fovi/test/test_camera_gaze.py @@ -6,6 +6,7 @@ """The camera's gaze, mount and sensor mask, and the Warp kernels behind them, without launching a simulator.""" import math +import weakref from dataclasses import asdict from types import SimpleNamespace @@ -549,7 +550,6 @@ def __init__(self, num_envs: int, switchable: bool = True): self.cfg = SimpleNamespace( prim_path="/World/envs/env_.*/Eye", cmf_a_deg=0.591, - viewer_cmf_a_values=(0.1, 1.0, 10.0), foveated_style="warped_cartesian_as_grid", ) self.is_initialized = True @@ -609,22 +609,40 @@ def button(self, label): return self.button_pressed -def _visualizer(kind: str) -> SimpleNamespace: - """A visualizer of ``kind`` that records its UI callbacks and counts redraws of its camera view.""" - view = SimpleNamespace(invalidated=0) - view.invalidate = lambda: setattr(view, "invalidated", view.invalidated + 1) +class _View: + """A window's camera view: the camera it shows, held weakly as the test drops cameras, and its redraw count.""" + + def __init__(self, camera=None): + self.camera = camera + self.invalidated = 0 + + @property + def camera(self): + return None if self._camera is None else self._camera() + + @camera.setter + def camera(self, camera): + self._camera = None if camera is None else weakref.ref(camera) + + def invalidate(self): + self.invalidated += 1 + + +def _visualizer(kind: str, shows=None) -> SimpleNamespace: + """A visualizer of ``kind`` whose camera view shows ``shows``, recording its UI callbacks.""" callbacks = [] return SimpleNamespace( cfg=SimpleNamespace(backend=SimpleNamespace(visualizer_type=kind)), register_ui_callback=lambda callback, position: callbacks.append((callback, position)), - current_image_view=view, + current_image_view=_View(shows), callbacks=callbacks, ) -def test_viewer_gaze_sliders_follow_and_set_the_gaze_in_newton_windows() -> None: +def test_viewer_gaze_sliders_follow_and_set_the_gaze_in_newton_windows(monkeypatch) -> None: + monkeypatch.setattr(ViewerGazeControls, "cmf_a_values", (0.1, 1.0, 10.0)) camera = _SliderCamera(num_envs=3) - newton, kit = _visualizer("newton"), _visualizer("kit") + newton, kit = _visualizer("newton", camera), _visualizer("kit", camera) controls = ViewerGazeControls(camera) # Each simulation reset attaches again; a window gets the sliders once, and only Newton windows get them. controls.attach(SimpleNamespace(visualizers=[newton, kit])) @@ -644,18 +662,25 @@ def test_viewer_gaze_sliders_follow_and_set_the_gaze_in_newton_windows() -> None assert ("Gaze tilt", -30.0) in imgui.shown and ("Gaze pan", 40.0) in imgui.shown and not camera.written # Two cameras' sections open different ID scopes, so their same-named widgets stay apart. other, other_camera = _Imgui(), _SliderCamera(num_envs=1) - ViewerGazeControls(other_camera)._render(other) + ViewerGazeControls(other_camera)._render(_visualizer("newton", other_camera), other) assert imgui.scopes and other.scopes and imgui.scopes != other.scopes - # Moving one sets that gaze in every environment and redraws the camera view of every window, even another one. - second = _visualizer("newton") + # A window draws the controls only while its view shows the camera. + second = _visualizer("newton", other_camera) controls.attach(SimpleNamespace(visualizers=[newton, second])) + imgui = _Imgui() + second.callbacks[0][0](imgui) + assert not imgui.shown + second.current_image_view.camera = camera + second.callbacks[0][0](imgui) + assert ("Gaze tilt", -30.0) in imgui.shown + # Moving one sets that gaze in every environment and redraws the camera view of every window, even another one. render(_Imgui(sliders=[(True, 20.0), (False, -10.0)])) assert torch.equal(camera.written[-1], torch.tensor([[20.0, -10.0]]).repeat(3, 1)) assert newton.current_image_view.invalidated == 1 and second.current_image_view.invalidated == 1 render(_Imgui(button=True)) assert not camera.written[-1].any() - # The foveation slider steps through the configured CMF constants with the camera's own added, in order. + # The foveation slider steps through ViewerGazeControls.cmf_a_values with the camera's own added, in order. imgui = _Imgui() render(imgui) assert ("Foveation", 1, 0, 3, "cmf_a 0.591 deg") in imgui.shown # 0.1, 0.591, 1, 10 @@ -668,7 +693,7 @@ def test_viewer_gaze_sliders_follow_and_set_the_gaze_in_newton_windows() -> None # A camera that cannot switch shows its constant as fixed instead. fixed = _SliderCamera(num_envs=1, switchable=False) fixed_controls = ViewerGazeControls(fixed) - fixed_window = _visualizer("newton") + fixed_window = _visualizer("newton", fixed) fixed_controls.attach(SimpleNamespace(visualizers=[fixed_window])) imgui = _Imgui(foveation=0) fixed_window.callbacks[0][0](imgui) From 8164e3dfb15fdaa5a00f6ed6560bda42558ad6f0 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 24 Nov 2026 14:33:39 -0800 Subject: [PATCH 07/11] Draw foveated camera controls below the Camera Source selector The Newton visualizer let other code add controls only through its register_ui_callback slots, so the foveated camera's gaze and foveation controls sat in their own section under the Simulation header. NewtonVisualizerBase.register_sensor_ui_callback adds a generic hook: while a scene sensor is a window's camera source, each callback draws in the Camera Sensor section, after its channel and environment controls, with that sensor. The environment controls move to _draw_sensor_envs so that their early return for a single-environment sensor does not skip the callbacks. Foveated cameras register through it and draw a "Foveated Camera" group when the sensor is theirs. --- .../api/lab_fovi/isaaclab_fovi.sensors.rst | 3 +- .../experimental-features/foveated_camera.rst | 6 +- ...at-isaaclab-fovi-viewer-controls.added.rst | 6 +- .../isaaclab_fovi/sensors/gaze_controls.py | 31 ++++----- source/isaaclab_fovi/test/test_camera_gaze.py | 67 +++++++------------ ...at-isaaclab-fovi-viewer-controls.added.rst | 3 + .../feat-isaaclab-fovi-viewer-controls.minor | 0 .../newton/newton_visualizer.py | 21 +++++- .../test/test_newton_task_views.py | 19 ++++++ 9 files changed, 87 insertions(+), 69 deletions(-) create mode 100644 source/isaaclab_visualizers/changelog.d/feat-isaaclab-fovi-viewer-controls.added.rst create mode 100644 source/isaaclab_visualizers/changelog.d/feat-isaaclab-fovi-viewer-controls.minor diff --git a/docs/source/api/lab_fovi/isaaclab_fovi.sensors.rst b/docs/source/api/lab_fovi/isaaclab_fovi.sensors.rst index e0e84bea5901..ca247269e58c 100644 --- a/docs/source/api/lab_fovi/isaaclab_fovi.sensors.rst +++ b/docs/source/api/lab_fovi/isaaclab_fovi.sensors.rst @@ -44,7 +44,8 @@ Constructing :class:`FoveatedCamera` returns one of the following implementation Viewer Controls --------------- -Each foveated camera adds these controls to the side panel of every Newton viewer window that shows it. +Each foveated camera adds these controls to every Newton viewer window, below the Camera Source selector while it +is the window's camera source. .. autoclass:: ViewerGazeControls :members: cmf_a_values diff --git a/docs/source/experimental-features/foveated_camera.rst b/docs/source/experimental-features/foveated_camera.rst index 628751ec4fc8..98f63f147d95 100644 --- a/docs/source/experimental-features/foveated_camera.rst +++ b/docs/source/experimental-features/foveated_camera.rst @@ -101,9 +101,9 @@ Use :attr:`~sensors.FoveatedCameraCfg.retinal_window_fraction` to shrink this wi :attr:`~sensors.FoveatedCameraCfg.image_rotation_deg` to compensate for mount roll. Call ``camera.set_gaze_angles(angles)`` with shape ``(num_envs, 2)`` in tilt, pan order and in degrees. -Positive tilt looks up and positive pan looks left. While a Newton viewer window shows a foveated camera, its side -panel has tilt and pan sliders for it, which follow its gaze and set it in every environment; a gaze action -overrides them each step. A foveation slider beside them switches the CMF constant among +Positive tilt looks up and positive pan looks left. While a foveated camera is a Newton viewer window's camera +source, tilt and pan sliders for it appear below the Camera Source selector, which follow its gaze and set it in +every environment; a gaze action overrides them each step. A foveation slider beside them switches the CMF constant among :attr:`~sensors.ViewerGazeControls.cmf_a_values`, which can be assigned to change the stops, with :meth:`~sensors.FoveatedCamera.set_cmf_a`, which re-samples the retina in place. That works on Newton for styles whose sample count does not depend on the constant, the warped-Cartesian and ``_fixn`` isotropic ones; OVRTX and diff --git a/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-viewer-controls.added.rst b/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-viewer-controls.added.rst index 6ca915206495..ef6022704333 100644 --- a/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-viewer-controls.added.rst +++ b/source/isaaclab_fovi/changelog.d/feat-isaaclab-fovi-viewer-controls.added.rst @@ -1,5 +1,5 @@ -* Added gaze and foveation controls for foveated cameras to the Newton viewer's side panel, shown while a window - shows the camera, with sliders kept in sync with the camera's gaze and a discrete, log-spaced ``cmf_a`` selector - (:attr:`~isaaclab_fovi.sensors.ViewerGazeControls.cmf_a_values`). +* Added gaze and foveation controls for foveated cameras to the Newton viewer, below the Camera Source selector while + a foveated camera is the window's source, with sliders kept in sync with the camera's gaze and a discrete, + log-spaced ``cmf_a`` selector (:attr:`~isaaclab_fovi.sensors.ViewerGazeControls.cmf_a_values`). * Added :meth:`~isaaclab_fovi.sensors.FoveatedCamera.set_cmf_a`, which changes the CMF constant of fixed-count Newton foveated cameras at runtime. diff --git a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py index bee44f45e595..5e3e6bb855d7 100644 --- a/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py +++ b/source/isaaclab_fovi/isaaclab_fovi/sensors/gaze_controls.py @@ -3,12 +3,11 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Gaze sliders for foveated cameras in the side panel of Newton viewer windows.""" +"""Gaze and foveation controls for foveated cameras in the Camera Sensor section of Newton viewer windows.""" from __future__ import annotations import weakref -from functools import partial from typing import TYPE_CHECKING, Any, ClassVar from isaaclab.sim import SimulationContext @@ -23,10 +22,10 @@ class ViewerGazeControls: - """Gaze and foveation controls for one foveated camera, in the side panel of each Newton viewer window that shows - it. + """Gaze and foveation controls for one foveated camera, in the Camera Sensor section of each Newton viewer window, + below its Camera Source selector. - A window draws the controls while its camera view shows the camera, so a camera the viewer cannot show, or another + A window draws the controls while the camera is its camera source, so a camera the viewer cannot show, or another camera chosen in the window's camera menu, has none. The tilt and pan sliders show the first environment's gaze every frame, so they follow whatever sets it, such as a gaze action or a drag in the viewer. Moving one sets that gaze in every environment; a gaze action that sets the gaze every step overrides them. The foveation slider steps @@ -45,11 +44,10 @@ def __init__(self, camera: FoveatedCamera): The viewer cannot unregister a UI callback, so each window keeps a callback that then returns at once. """ self._camera = weakref.ref(camera) - self._label = camera.cfg.prim_path.rsplit("/", 1)[-1] self._start_cmf_a = float(camera.cfg.cmf_a_deg) """The camera's starting CMF constant [deg], which stays a stop of the foveation slider after a switch.""" self._windows: list[BaseVisualizer] = [] - """The Newton viewer windows that draw the controls while they show the camera.""" + """The Newton viewer windows that draw the controls while the camera is their source.""" def attach(self, sim: SimulationContext) -> None: """Add the controls to every Newton viewer window of ``sim`` that does not have them yet.""" @@ -58,21 +56,18 @@ def attach(self, sim: SimulationContext) -> None: window is not visualizer for window in self._windows ): self._windows.append(visualizer) - visualizer.register_ui_callback(partial(self._render, visualizer), position="side") + visualizer.register_sensor_ui_callback(self._render) - def _render(self, window: BaseVisualizer, imgui: Any) -> None: - """Draw the controls in the side panel of ``window`` while its camera view shows the camera.""" + def _render(self, imgui: Any, sensor: Any) -> None: + """Draw the controls in a window's Camera Sensor section while ``sensor``, its camera source, is the camera.""" camera = self._camera() - if camera is None or not camera.is_initialized: + if camera is None or sensor is not camera or not camera.is_initialized: return - view = window.current_image_view - if view is None or view.camera is not camera: - return - # Each camera's widgets share labels, so they need their own ID scope; a header does not open one. + # Each camera's widgets share labels, so they need their own ID scope. imgui.push_id(f"isaaclab_fovi.viewer_gaze_controls.{id(self)}") try: - if imgui.collapsing_header(f"Foveated camera: {self._label}"): - self._draw_controls(imgui, camera) + imgui.separator_text("Foveated Camera") + self._draw_controls(imgui, camera) finally: imgui.pop_id() @@ -121,7 +116,7 @@ def _redraw(self) -> None: def add_viewer_gaze_controls(camera: FoveatedCamera) -> None: """Add ``camera``'s controls to the Newton viewer windows of every simulation reset while it exists; a window - draws them while it shows the camera.""" + draws them while the camera is its camera source.""" controls = ViewerGazeControls(camera) name = f"isaaclab_fovi.viewer_gaze_controls.{id(controls)}" SimulationContext.add_reset_callback(name, controls.attach) diff --git a/source/isaaclab_fovi/test/test_camera_gaze.py b/source/isaaclab_fovi/test/test_camera_gaze.py index 68501f31e2bf..6eedc522805d 100644 --- a/source/isaaclab_fovi/test/test_camera_gaze.py +++ b/source/isaaclab_fovi/test/test_camera_gaze.py @@ -6,8 +6,8 @@ """The camera's gaze, mount and sensor mask, and the Warp kernels behind them, without launching a simulator.""" import math -import weakref from dataclasses import asdict +from functools import partial from types import SimpleNamespace import pytest @@ -585,9 +585,8 @@ def push_id(self, name): def pop_id(self): self.ids.pop() - def collapsing_header(self, label): + def separator_text(self, label): self.shown.append(label) - return True def slider_float(self, label, value, *_args): # Widgets with the same label in two cameras' sections need distinct ID scopes. @@ -609,32 +608,15 @@ def button(self, label): return self.button_pressed -class _View: - """A window's camera view: the camera it shows, held weakly as the test drops cameras, and its redraw count.""" - - def __init__(self, camera=None): - self.camera = camera - self.invalidated = 0 - - @property - def camera(self): - return None if self._camera is None else self._camera() - - @camera.setter - def camera(self, camera): - self._camera = None if camera is None else weakref.ref(camera) - - def invalidate(self): - self.invalidated += 1 - - -def _visualizer(kind: str, shows=None) -> SimpleNamespace: - """A visualizer of ``kind`` whose camera view shows ``shows``, recording its UI callbacks.""" +def _visualizer(kind: str) -> SimpleNamespace: + """A visualizer of ``kind`` that records its sensor UI callbacks and counts redraws of its camera view.""" + view = SimpleNamespace(invalidated=0) + view.invalidate = lambda: setattr(view, "invalidated", view.invalidated + 1) callbacks = [] return SimpleNamespace( cfg=SimpleNamespace(backend=SimpleNamespace(visualizer_type=kind)), - register_ui_callback=lambda callback, position: callbacks.append((callback, position)), - current_image_view=_View(shows), + register_sensor_ui_callback=callbacks.append, + current_image_view=view, callbacks=callbacks, ) @@ -642,13 +624,14 @@ def _visualizer(kind: str, shows=None) -> SimpleNamespace: def test_viewer_gaze_sliders_follow_and_set_the_gaze_in_newton_windows(monkeypatch) -> None: monkeypatch.setattr(ViewerGazeControls, "cmf_a_values", (0.1, 1.0, 10.0)) camera = _SliderCamera(num_envs=3) - newton, kit = _visualizer("newton", camera), _visualizer("kit", camera) + newton, kit = _visualizer("newton"), _visualizer("kit") controls = ViewerGazeControls(camera) # Each simulation reset attaches again; a window gets the sliders once, and only Newton windows get them. controls.attach(SimpleNamespace(visualizers=[newton, kit])) controls.attach(SimpleNamespace(visualizers=[newton, kit])) - assert [position for _, position in newton.callbacks] == ["side"] and not kit.callbacks - render = newton.callbacks[0][0] + assert len(newton.callbacks) == 1 and not kit.callbacks + # The window draws the sensor callbacks with its camera source; here, the camera. + render = partial(newton.callbacks[0], sensor=camera) # The sliders show the first environment's gaze, and leave it alone until moved. imgui = _Imgui() @@ -662,17 +645,16 @@ def test_viewer_gaze_sliders_follow_and_set_the_gaze_in_newton_windows(monkeypat assert ("Gaze tilt", -30.0) in imgui.shown and ("Gaze pan", 40.0) in imgui.shown and not camera.written # Two cameras' sections open different ID scopes, so their same-named widgets stay apart. other, other_camera = _Imgui(), _SliderCamera(num_envs=1) - ViewerGazeControls(other_camera)._render(_visualizer("newton", other_camera), other) + ViewerGazeControls(other_camera)._render(other, other_camera) assert imgui.scopes and other.scopes and imgui.scopes != other.scopes - # A window draws the controls only while its view shows the camera. - second = _visualizer("newton", other_camera) + # A window draws the controls only while the camera is its source. + second = _visualizer("newton") controls.attach(SimpleNamespace(visualizers=[newton, second])) imgui = _Imgui() - second.callbacks[0][0](imgui) + second.callbacks[0](imgui, other_camera) assert not imgui.shown - second.current_image_view.camera = camera - second.callbacks[0][0](imgui) - assert ("Gaze tilt", -30.0) in imgui.shown + second.callbacks[0](imgui, camera) + assert "Foveated Camera" in imgui.shown and ("Gaze tilt", -30.0) in imgui.shown # Moving one sets that gaze in every environment and redraws the camera view of every window, even another one. render(_Imgui(sliders=[(True, 20.0), (False, -10.0)])) assert torch.equal(camera.written[-1], torch.tensor([[20.0, -10.0]]).repeat(3, 1)) @@ -693,17 +675,18 @@ def test_viewer_gaze_sliders_follow_and_set_the_gaze_in_newton_windows(monkeypat # A camera that cannot switch shows its constant as fixed instead. fixed = _SliderCamera(num_envs=1, switchable=False) fixed_controls = ViewerGazeControls(fixed) - fixed_window = _visualizer("newton", fixed) + fixed_window = _visualizer("newton") fixed_controls.attach(SimpleNamespace(visualizers=[fixed_window])) imgui = _Imgui(foveation=0) - fixed_window.callbacks[0][0](imgui) + fixed_window.callbacks[0](imgui, fixed) assert "Foveation: cmf_a 0.591 deg (fixed)" in imgui.shown and fixed.cfg.cmf_a_deg == 0.591 - # Once the camera is gone, the window's callback draws nothing. - del camera + # Once the camera is gone, the window's callback draws nothing, whatever the window shows. + callback = newton.callbacks[0] + del camera, render imgui = _Imgui() - render(imgui) - assert not imgui.shown + callback(imgui, other_camera) + assert not imgui.shown and controls._camera() is None def test_every_foveated_camera_adds_its_sliders_on_reset_until_it_is_gone() -> None: diff --git a/source/isaaclab_visualizers/changelog.d/feat-isaaclab-fovi-viewer-controls.added.rst b/source/isaaclab_visualizers/changelog.d/feat-isaaclab-fovi-viewer-controls.added.rst new file mode 100644 index 000000000000..c10e16ce4237 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/feat-isaaclab-fovi-viewer-controls.added.rst @@ -0,0 +1,3 @@ +* Added ``register_sensor_ui_callback`` to the Newton visualizer, which lets a scene sensor draw its own controls in + the Camera Sensor section, below the Camera Source selector, while it is the window's camera source. Foveated + cameras use it for their gaze and foveation controls. diff --git a/source/isaaclab_visualizers/changelog.d/feat-isaaclab-fovi-viewer-controls.minor b/source/isaaclab_visualizers/changelog.d/feat-isaaclab-fovi-viewer-controls.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py index 0dc3af6e30da..a52ffd2a4444 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py @@ -782,6 +782,9 @@ class NewtonVisualizerBase(BaseVisualizer): rtx_view_index: int | None = None rtx_rendering: bool = False sensor_view_selected: bool = False + _sensor_ui_callbacks: tuple[Callable[[Any, Camera], None], ...] = () + """Callbacks that draw a scene sensor's own controls in the Camera Sensor section; see + :meth:`register_sensor_ui_callback`.""" def __init__(self, cfg): super().__init__(cfg) @@ -1180,11 +1183,25 @@ def _source_rank(self, view) -> int: """Order the Camera Source list: the free Perspective, then scene sensors.""" return 0 if view.camera is None else 1 + def register_sensor_ui_callback(self, callback: Callable[[Any, Camera], None]) -> None: + """Draw a scene sensor's own controls in the Camera Sensor section, below the Camera Source selector. + + While a scene sensor is the camera source, ``callback`` is invoked every UI frame with the ``imgui`` module and + that sensor, after the section's channel and environment controls. It draws only for the sensors it handles. + """ + self._sensor_ui_callbacks = (*self._sensor_ui_callbacks, callback) + def _draw_sensor_controls(self, imgui, view) -> None: - """Choose which channel of a sensor is shown, and which environment, or tile several environments.""" - camera = view.camera + """Choose which channel of a sensor is shown and which environments, then draw the sensor's own controls.""" imgui.separator_text("Camera Sensor") self._draw_sensor_channels(imgui, view) + self._draw_sensor_envs(imgui, view) + for callback in self._sensor_ui_callbacks: + callback(imgui, view.camera) + + def _draw_sensor_envs(self, imgui, view) -> None: + """Choose which environment of a sensor is shown, or tile several environments.""" + camera = view.camera offered = self._sensor_tiles.get(view) if offered is None: # A single-instance sensor has no environment to choose. return diff --git a/source/isaaclab_visualizers/test/test_newton_task_views.py b/source/isaaclab_visualizers/test/test_newton_task_views.py index c1303137a40f..3b3f0ab99a1d 100644 --- a/source/isaaclab_visualizers/test/test_newton_task_views.py +++ b/source/isaaclab_visualizers/test/test_newton_task_views.py @@ -113,6 +113,25 @@ def test_a_perspective_that_was_never_left_has_no_pose_to_restore(): assert not viz._restore_perspective_pose() +def test_sensor_ui_callbacks_draw_in_the_camera_sensor_section_with_the_selected_sensor(): + camera = object() + sensor = _View("/World/envs/env_[^/]+/Camera", camera=camera) + viz = _visualizer([_view(PerspectiveCameraCfg()), sensor]) + drawn = [] + imgui = SimpleNamespace(separator_text=lambda label: drawn.append(label)) + viz._draw_sensor_channels = lambda imgui, view: drawn.append("channels") + viz._draw_sensor_envs = lambda imgui, view: drawn.append("environments") + viz.register_sensor_ui_callback(lambda imgui, shown: drawn.append(("first", shown))) + viz.register_sensor_ui_callback(lambda imgui, shown: drawn.append(("second", shown))) + + viz._draw_sensor_controls(imgui, sensor) + + # Each callback draws after the section's own controls, in registration order, with the sensor shown. + assert drawn == ["Camera Sensor", "channels", "environments", ("first", camera), ("second", camera)] + # Callbacks belong to the window that registered them. + assert _visualizer([sensor])._sensor_ui_callbacks == () + + def _rtx_view(): camera = SimpleNamespace(cfg=SimpleNamespace(prim_path="/World/viewer_camera_0", renderer_cfg="ovrtx")) return _View("/World/viewer_camera_0", camera=camera) From a602a4aa94dd9ce6dc2743306ecb47e4014c19cc Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 24 Nov 2026 14:33:39 -0800 Subject: [PATCH 08/11] Drop the header of the foveated-camera example's comparison The comparison window's header titled its two images "Viewing sphere" and "Retina" and showed the CMF constant, which the foveation slider below the Camera Source selector already shows; the right image is also the cortical view rather than the retina. The window now shows the two images side by side, and the example no longer needs PIL or NumPy. --- examples/sensors/foveated_camera.py | 23 ++--------------------- 1 file changed, 2 insertions(+), 21 deletions(-) diff --git a/examples/sensors/foveated_camera.py b/examples/sensors/foveated_camera.py index cb5f76febecf..729a3121ff9f 100644 --- a/examples/sensors/foveated_camera.py +++ b/examples/sensors/foveated_camera.py @@ -33,7 +33,6 @@ from typing import TYPE_CHECKING import gymnasium as gym -import numpy as np import torch import warp as wp from fovi.sensing.projection import gaze_rotation @@ -44,7 +43,6 @@ from isaaclab_newton.physics import NewtonCfg, XPBDSolverCfg from isaaclab_newton.renderers import NewtonWarpRendererCfg from isaaclab_ov.renderers import OVRTXRendererCfg -from PIL import Image, ImageDraw, ImageFont import isaaclab.sim as sim_utils from isaaclab.app import add_launcher_args, launch_simulation @@ -259,17 +257,7 @@ def camera_comparison( ) -> tuple[Callable[[], None], Callable[[torch.Tensor], wp.array]]: """Draw the lens and gaze on the viewing sphere used in the docs, beside the retina.""" size, gap = PREVIEW_SIZE, 6 - header_height = 28 - image_width = 2 * size + gap - header_color = (25, 28, 32, 255) - header = Image.new("RGBA", (image_width, header_height), header_color) - draw = ImageDraw.Draw(header) - font = ImageFont.load_default(size=17) - draw.text((8, header_height / 2), "Viewing sphere", font=font, fill="white", anchor="lm") - draw.text((size + gap + 8, header_height / 2), "Retina", font=font, fill="white", anchor="lm") - labels = torch.from_numpy(np.array(header)).to(camera.device) - divider = labels[:1, size : size + gap].expand(size, -1, -1) - displayed_cmf_a = None + divider = torch.tensor((25, 28, 32, 255), dtype=torch.uint8, device=camera.device).expand(size, gap, -1) coords = overview.sampling_coords pixels = torch.arange(size, device=camera.device) @@ -293,15 +281,8 @@ def prepare() -> None: def compose(retina: torch.Tensor) -> wp.array: """The view for one RGB retina image (H, W, 3): the viewing sphere, then the retina.""" - nonlocal displayed_cmf_a # The retina may change its foveation at runtime, so its coordinates are read for every frame. retina_coords = camera.sampling_coords - if camera.cfg.cmf_a_deg != displayed_cmf_a: - displayed_cmf_a = camera.cfg.cmf_a_deg - draw.rectangle((image_width - 140, 0, image_width - 1, header_height - 1), fill=header_color) - text = f"cmf_a {displayed_cmf_a:g} deg" - draw.text((image_width - 8, header_height / 2), text, font=font, fill="white", anchor="rm") - labels.copy_(torch.from_numpy(np.array(header))) detail = torch.cat((retina, torch.full_like(retina[..., :1], 255)), dim=-1) # Transform the fixed observer into the live camera frame, independently of active gaze. @@ -365,7 +346,7 @@ def compose(retina: torch.Tensor) -> wp.array: detail = detail.permute(2, 0, 1).unsqueeze(0) detail = torch.nn.functional.interpolate(detail, size=(size, size), mode="nearest")[0].permute(1, 2, 0) detail[..., :3].masked_fill_(~retina_disc[..., None], 0) - return wp.from_torch(torch.cat((labels, torch.cat((full, divider, detail), dim=1)), dim=0)) + return wp.from_torch(torch.cat((full, divider, detail), dim=1).contiguous()) return prepare, compose From f8ae4e592d47b277b9a575bc3bb6b260f10161e6 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 24 Nov 2026 14:35:06 -0800 Subject: [PATCH 09/11] Describe the cortical view and the new control placement in the docs and example The docs page and the foveated-camera example still placed the gaze and foveation sliders in the side panel at large and called the camera's image the retina. The Sampling section now names the published lattice image the retina's cortical view, and the example's description, help text and docstrings use that name and place the sliders below the Camera Source selector, in the Camera Sensor section. --- .../experimental-features/foveated_camera.rst | 27 ++++++++++--------- examples/sensors/foveated_camera.py | 22 +++++++-------- 2 files changed, 25 insertions(+), 24 deletions(-) diff --git a/docs/source/experimental-features/foveated_camera.rst b/docs/source/experimental-features/foveated_camera.rst index 98f63f147d95..ca65c35483f9 100644 --- a/docs/source/experimental-features/foveated_camera.rst +++ b/docs/source/experimental-features/foveated_camera.rst @@ -15,12 +15,13 @@ several minutes with a cold shader cache: uv run --extra fovi [--extra ovrtx] isaaclab example foveated-camera [renderer=ovrtx] -The Newton viewer shows the retina, covered at launch by a window that shows the fisheye on a curved viewing sphere -beside the retina: the green lens boundary follows the camera mount, and the blue gaze circle and sampling grid show -the retina's coverage. Use WASD or the arrow keys to move the camera and Q/E to lower or raise it. Drag with the left -mouse button, or press I/K and J/L, to steer the gaze; the side panel's sliders follow the gaze and set it, and on -Newton its foveation slider steps the CMF constant, through other stops with ``--cmf_a_values 0.2,2,20`` plus the -camera's own. H shows or hides the viewer controls. Pass ``--target power_drill`` to start fixating the drill. +The Newton viewer shows the camera's image, the retina's cortical view (see `Sampling`_), covered at launch by a window +that shows the fisheye on a curved viewing sphere beside that view: the green lens boundary follows the camera mount, +and the blue gaze circle and sampling grid show the retina's coverage. Use WASD or the arrow keys to move the camera and +Q/E to lower or raise it. Drag with the left mouse button, or press I/K and J/L, to steer the gaze. Below the side +panel's Camera Source selector, gaze sliders follow the gaze and set it, and on Newton a foveation slider steps the CMF +constant, through other stops with ``--cmf_a_values 0.2,2,20`` plus the camera's own. H shows or hides the viewer +controls. Pass ``--target power_drill`` to start fixating the drill. .. figure:: ../_static/overview/sensors/foveated_camera_overview.jpg :alt: A retina behind a 180-degree fisheye lens on the viewing sphere, and its rendered images at two fixations. @@ -52,7 +53,7 @@ The default ``foveated_style="warped_cartesian_as_grid"`` warps an :math:`N \tim r(\rho) = a\left[\left(1 + \frac{r_{\max}}{a}\right)^{\rho} - 1\right], where :math:`r_{\max}` is half the retina's field of view, and the camera publishes the lattice as an upright -``(num_envs, N, N, channels)`` image. +``(num_envs, N, N, channels)`` image: the retina's cortical view, laid out by cortical distance rather than by angle. ``foveated_style="isotropic"`` instead places rings evenly in :math:`w`, and gives each ring as many samples as keep neighbours about equally far apart in every direction: @@ -102,12 +103,12 @@ Use :attr:`~sensors.FoveatedCameraCfg.retinal_window_fraction` to shrink this wi Call ``camera.set_gaze_angles(angles)`` with shape ``(num_envs, 2)`` in tilt, pan order and in degrees. Positive tilt looks up and positive pan looks left. While a foveated camera is a Newton viewer window's camera -source, tilt and pan sliders for it appear below the Camera Source selector, which follow its gaze and set it in -every environment; a gaze action overrides them each step. A foveation slider beside them switches the CMF constant among -:attr:`~sensors.ViewerGazeControls.cmf_a_values`, which can be assigned to change the stops, with -:meth:`~sensors.FoveatedCamera.set_cmf_a`, which re-samples the retina in place. That works on Newton for styles -whose sample count does not depend on the constant, the warped-Cartesian and ``_fixn`` isotropic ones; OVRTX and -Isaac RTX read their lens textures once, so there the slider shows the constant as fixed. +source, tilt and pan sliders for it appear below the Camera Source selector, in the Camera Sensor section; they +follow its gaze and set it in every environment, and a gaze action overrides them each step. A foveation slider +beside them switches the CMF constant among :attr:`~sensors.ViewerGazeControls.cmf_a_values`, which can be assigned +to change the stops, with :meth:`~sensors.FoveatedCamera.set_cmf_a`, which re-samples the retina in place. That +works on Newton for styles whose sample count does not depend on the constant, the warped-Cartesian and ``_fixn`` +isotropic ones; OVRTX and Isaac RTX read their lens textures once, so there the slider shows the constant as fixed. :meth:`~sensors.FoveatedCamera.get_world_poses` reports the mount pose. Enable :attr:`~sensors.FoveatedCameraCfg.mask_to_sensor_fov` to zero rays that fall outside the physical image as the gaze moves. diff --git a/examples/sensors/foveated_camera.py b/examples/sensors/foveated_camera.py index 729a3121ff9f..351fe9b04304 100644 --- a/examples/sensors/foveated_camera.py +++ b/examples/sensors/foveated_camera.py @@ -5,12 +5,12 @@ """Explore a cluttered scene through the experimental foveated camera. -The viewer shows the camera's retina, covered at launch by a window that shows the gaze on the viewing sphere beside -the retina; move or resize that window to see the viewer's own view of the retina. +The viewer shows the camera's image, the retina's cortical view, covered at launch by a window that shows the gaze on +the viewing sphere beside that view; move or resize that window to see the viewer's own. Use WASD or the arrow keys to move the camera, and Q/E to lower or raise it. Drag with the left mouse button, or press I/K and J/L, to steer the gaze. -The side panel's sliders follow the gaze and set it, and on Newton step the foveation (cmf_a) through ---cmf_a_values. Press H to show or hide the viewer controls. +Below the side panel's Camera Source selector, gaze sliders follow the gaze and set it, and on Newton a foveation +slider steps the CMF constant (cmf_a) through --cmf_a_values. Press H to show or hide the viewer controls. Use --target to choose where the retina looks at launch. .. code-block:: bash @@ -107,7 +107,7 @@ ) PREVIEW_SIZE = 256 COMPARISON_WINDOW = "Foveated camera" -"""Title of the window that shows the viewing sphere beside the retina.""" +"""Title of the window that shows the viewing sphere beside the retina's cortical view.""" def viewing_sphere_rays(screen: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: @@ -145,8 +145,8 @@ def _cmf_a_values(text: str) -> tuple[float, ...]: "--cmf_a_values", type=_cmf_a_values, metavar="DEG,DEG,...", - help="Comma-separated CMF constants [deg] the side panel's foveation slider steps through, with the camera's own" - " added.", + help="Comma-separated CMF constants [deg] the foveation slider below the Camera Source selector steps through," + " with the camera's own added.", ) add_launcher_args(parser) parser.set_defaults(visualizer=["newton"]) @@ -255,7 +255,7 @@ def gaze_toward(centre: tuple[float, float, float], camera_cfg: FoveatedCameraCf def camera_comparison( camera: FoveatedCamera, overview: FoveatedCamera ) -> tuple[Callable[[], None], Callable[[torch.Tensor], wp.array]]: - """Draw the lens and gaze on the viewing sphere used in the docs, beside the retina.""" + """Draw the lens and gaze on the viewing sphere used in the docs, beside the retina's cortical view.""" size, gap = PREVIEW_SIZE, 6 divider = torch.tensor((25, 28, 32, 255), dtype=torch.uint8, device=camera.device).expand(size, gap, -1) @@ -280,7 +280,7 @@ def prepare() -> None: overview.update_batch((overview,), 0.0) def compose(retina: torch.Tensor) -> wp.array: - """The view for one RGB retina image (H, W, 3): the viewing sphere, then the retina.""" + """The view for one RGB image of the retina (H, W, 3): the viewing sphere, then that cortical view.""" # The retina may change its foveation at runtime, so its coordinates are read for every frame. retina_coords = camera.sampling_coords detail = torch.cat((retina, torch.full_like(retina[..., :1], 255)), dim=-1) @@ -413,7 +413,7 @@ def main() -> None: visualizer_types = {v.backend.visualizer_type for v in cfg.sim.visualizer_cfgs} if visualizer_types - {"newton"}: logger.warning( - "The foveated-camera example's gaze keys and viewing-sphere panel need the Newton visualizer" + "The foveated-camera example's gaze keys and viewing-sphere window need the Newton visualizer" " (--viz newton). With %s, the gaze stays where it starts (see --target).", ", ".join(sorted(visualizer_types - {"newton"})), ) @@ -490,7 +490,7 @@ def main() -> None: class GazeSteering: """Steer the eye's gaze with the mouse and I/J/K/L. - Left-dragging the viewer steers only the gaze, as I/J/K/L and the side panel's sliders do; a drag that starts over + Left-dragging the viewer steers only the gaze, as I/J/K/L and the gaze sliders do; a drag that starts over the viewer's panels stays with them. The viewer itself moves the eye's mount with WASD/QE. """ From 656523b585530077d0828134222bb99b72352f58 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 24 Nov 2026 14:38:28 -0800 Subject: [PATCH 10/11] Call the camera's image the foveated camera's cortical view The cortical view belongs to the foveated camera, not to its retina; the docs page and the foveated-camera example now say so. --- .../experimental-features/foveated_camera.rst | 17 +++++++++-------- examples/sensors/foveated_camera.py | 11 ++++++----- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/docs/source/experimental-features/foveated_camera.rst b/docs/source/experimental-features/foveated_camera.rst index ca65c35483f9..064c45720a77 100644 --- a/docs/source/experimental-features/foveated_camera.rst +++ b/docs/source/experimental-features/foveated_camera.rst @@ -15,13 +15,13 @@ several minutes with a cold shader cache: uv run --extra fovi [--extra ovrtx] isaaclab example foveated-camera [renderer=ovrtx] -The Newton viewer shows the camera's image, the retina's cortical view (see `Sampling`_), covered at launch by a window -that shows the fisheye on a curved viewing sphere beside that view: the green lens boundary follows the camera mount, -and the blue gaze circle and sampling grid show the retina's coverage. Use WASD or the arrow keys to move the camera and -Q/E to lower or raise it. Drag with the left mouse button, or press I/K and J/L, to steer the gaze. Below the side -panel's Camera Source selector, gaze sliders follow the gaze and set it, and on Newton a foveation slider steps the CMF -constant, through other stops with ``--cmf_a_values 0.2,2,20`` plus the camera's own. H shows or hides the viewer -controls. Pass ``--target power_drill`` to start fixating the drill. +The Newton viewer shows the camera's image, the foveated camera's cortical view (see `Sampling`_), covered at launch by +a window that shows the fisheye on a curved viewing sphere beside that view: the green lens boundary follows the camera +mount, and the blue gaze circle and sampling grid show the retina's coverage. Use WASD or the arrow keys to move the +camera and Q/E to lower or raise it. Drag with the left mouse button, or press I/K and J/L, to steer the gaze. Below +the side panel's Camera Source selector, gaze sliders follow the gaze and set it, and on Newton a foveation slider +steps the CMF constant, through other stops with ``--cmf_a_values 0.2,2,20`` plus the camera's own. H shows or hides +the viewer controls. Pass ``--target power_drill`` to start fixating the drill. .. figure:: ../_static/overview/sensors/foveated_camera_overview.jpg :alt: A retina behind a 180-degree fisheye lens on the viewing sphere, and its rendered images at two fixations. @@ -53,7 +53,8 @@ The default ``foveated_style="warped_cartesian_as_grid"`` warps an :math:`N \tim r(\rho) = a\left[\left(1 + \frac{r_{\max}}{a}\right)^{\rho} - 1\right], where :math:`r_{\max}` is half the retina's field of view, and the camera publishes the lattice as an upright -``(num_envs, N, N, channels)`` image: the retina's cortical view, laid out by cortical distance rather than by angle. +``(num_envs, N, N, channels)`` image: the foveated camera's cortical view, laid out by cortical distance rather than +by angle. ``foveated_style="isotropic"`` instead places rings evenly in :math:`w`, and gives each ring as many samples as keep neighbours about equally far apart in every direction: diff --git a/examples/sensors/foveated_camera.py b/examples/sensors/foveated_camera.py index 351fe9b04304..17d32cc021d7 100644 --- a/examples/sensors/foveated_camera.py +++ b/examples/sensors/foveated_camera.py @@ -5,8 +5,8 @@ """Explore a cluttered scene through the experimental foveated camera. -The viewer shows the camera's image, the retina's cortical view, covered at launch by a window that shows the gaze on -the viewing sphere beside that view; move or resize that window to see the viewer's own. +The viewer shows the camera's image, the foveated camera's cortical view, covered at launch by a window that shows the +gaze on the viewing sphere beside that view; move or resize that window to see the viewer's own. Use WASD or the arrow keys to move the camera, and Q/E to lower or raise it. Drag with the left mouse button, or press I/K and J/L, to steer the gaze. Below the side panel's Camera Source selector, gaze sliders follow the gaze and set it, and on Newton a foveation @@ -107,7 +107,7 @@ ) PREVIEW_SIZE = 256 COMPARISON_WINDOW = "Foveated camera" -"""Title of the window that shows the viewing sphere beside the retina's cortical view.""" +"""Title of the window that shows the viewing sphere beside the foveated camera's cortical view.""" def viewing_sphere_rays(screen: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: @@ -255,7 +255,7 @@ def gaze_toward(centre: tuple[float, float, float], camera_cfg: FoveatedCameraCf def camera_comparison( camera: FoveatedCamera, overview: FoveatedCamera ) -> tuple[Callable[[], None], Callable[[torch.Tensor], wp.array]]: - """Draw the lens and gaze on the viewing sphere used in the docs, beside the retina's cortical view.""" + """Draw the lens and gaze on the viewing sphere used in the docs, beside the foveated camera's cortical view.""" size, gap = PREVIEW_SIZE, 6 divider = torch.tensor((25, 28, 32, 255), dtype=torch.uint8, device=camera.device).expand(size, gap, -1) @@ -280,7 +280,8 @@ def prepare() -> None: overview.update_batch((overview,), 0.0) def compose(retina: torch.Tensor) -> wp.array: - """The view for one RGB image of the retina (H, W, 3): the viewing sphere, then that cortical view.""" + """The view for one RGB cortical-view image of the foveated camera (H, W, 3): the viewing sphere, then that + image.""" # The retina may change its foveation at runtime, so its coordinates are read for every frame. retina_coords = camera.sampling_coords detail = torch.cat((retina, torch.full_like(retina[..., :1], 255)), dim=-1) From 9d8f35d48dc02bb72a118e408cdde1195dc2db54 Mon Sep 17 00:00:00 2001 From: nblauch Date: Tue, 24 Nov 2026 14:43:14 -0800 Subject: [PATCH 11/11] Name the comparison's input image rather than retina The comparison composes the foveated camera's output image, which is in cortical space; the retina is the sampling space it comes from. --- examples/sensors/foveated_camera.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/sensors/foveated_camera.py b/examples/sensors/foveated_camera.py index 17d32cc021d7..7cc1977c4b12 100644 --- a/examples/sensors/foveated_camera.py +++ b/examples/sensors/foveated_camera.py @@ -279,12 +279,12 @@ def prepare() -> None: if overview.supports_batch_update: overview.update_batch((overview,), 0.0) - def compose(retina: torch.Tensor) -> wp.array: + def compose(image: torch.Tensor) -> wp.array: """The view for one RGB cortical-view image of the foveated camera (H, W, 3): the viewing sphere, then that image.""" # The retina may change its foveation at runtime, so its coordinates are read for every frame. retina_coords = camera.sampling_coords - detail = torch.cat((retina, torch.full_like(retina[..., :1], 255)), dim=-1) + detail = torch.cat((image, torch.full_like(image[..., :1], 255)), dim=-1) # Transform the fixed observer into the live camera frame, independently of active gaze. position, orientation = camera.get_world_poses(convention="opengl")