From acf74ba15e0dd8647cd9f6e5ee6d5e1e163c7070 Mon Sep 17 00:00:00 2001 From: Jun-Jee Chao Date: Tue, 1 Dec 2026 16:37:09 -0800 Subject: [PATCH 1/5] feat(examples/televiz): place the picture with camera_viz's lock modes The picture was always the camera's field of view on a plane that follows the operator's position. A config can now say where it sits in the keys of camera_viz's placements: lock_mode (gimbal, world, lazy, head), distance, size and offsets. camera_viz's own strategies do the placing, run in a frame that turns with the camera, so that a picture of a given size looks smaller from farther away and a recenter seats it anew. gimbal with no size is the default and is what the plane did before. render.distance_m becomes placement.distance. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Jun-Jee Chao --- docs/source/references/televiz.rst | 45 +++- examples/televiz/configs/oakd.yaml | 7 +- examples/televiz/configs/replay.yaml | 7 +- examples/televiz/configs/synthetic.yaml | 7 +- examples/televiz/configs/zed.yaml | 7 +- .../isaaccapture_examples/televiz/app.py | 4 +- .../televiz/pipeline/config.py | 78 ++++++- .../televiz/render/placement.py | 155 +++++++++++++ .../televiz/render/quad_stage.py | 91 +++++--- .../televiz/render/window_view.py | 4 +- .../python/examples/televiz/test_placement.py | 213 ++++++++++++++++++ .../examples/televiz/test_quad_placement.py | 14 +- 12 files changed, 575 insertions(+), 57 deletions(-) create mode 100644 examples/televiz/python/isaaccapture_examples/televiz/render/placement.py create mode 100644 tests/python/examples/televiz/test_placement.py diff --git a/docs/source/references/televiz.rst b/docs/source/references/televiz.rst index 35e31eee3d..bd6752bfc8 100644 --- a/docs/source/references/televiz.rst +++ b/docs/source/references/televiz.rst @@ -297,7 +297,37 @@ Display modes * - ``none`` - No display. The camera and the tracker run and print their rates. -The plane is ``render.distance_m`` in front of the viewer, 2 m by default. +.. _televiz-placement: + +Placement +^^^^^^^^^ + +Where the picture sits is the ``placement`` section, in the keys of the ``display.placements`` +block of :doc:`camera_viz `. Its ``lock_mode`` says how the picture follows +you. In every mode but ``head`` the picture turns with the camera: + +.. list-table:: + :header-rows: 1 + :widths: 16 84 + + * - Mode + - Behavior + * - ``gimbal`` + - The default. The picture follows your position: turn your head and it stays where it is, + lean or walk and it comes with you. + * - ``world`` + - The picture stays where it was seated. Lean or walk and you move against it. + * - ``lazy`` + - As ``world``, and when you have looked away from the picture it glides back in front of + you. The knobs are ``look_away_angle_deg``, ``reposition_distance``, + ``reposition_delay_s`` and ``transition_duration_s``. + * - ``head`` + - The picture stays in front of your eyes and nothing is stabilized, as in camera_viz. + +The picture is ``distance`` metres away, 2 by default. With ``size`` left out it covers the +camera's field of view at any distance, so what it shows keeps its true angular size. With +``size: [width, height]`` in metres it is a screen of that size, which looks smaller from +farther away. A recenter seats the picture anew on the camera's axis. .. _televiz-recenter: @@ -392,8 +422,19 @@ relative path is resolved against the config file's directory. # world from the camera's IMU; 0 skips it, as # does a camera without an IMU + placement: + lock_mode: gimbal # gimbal | world | lazy | head + distance: 2.0 # metres from the viewer + size: null # [width, height] in metres; null: the + # camera's field of view at that distance + offset_x: 0.0 # metres to the right of straight ahead + offset_y: 0.0 # metres up + look_away_angle_deg: 45.0 # lazy: looking this far away from the picture + reposition_distance: 0.5 # or moving this many metres from its seat, + reposition_delay_s: 0.5 # for this long, brings it back + transition_duration_s: 0.3 # over this long + render: - distance_m: 2.0 # the plane's distance from the viewer stereo: true # false: both eyes show the same image composition: openxr # openxr: the runtime composites the plane # builtin: the visualization module draws it, diff --git a/examples/televiz/configs/oakd.yaml b/examples/televiz/configs/oakd.yaml index 3aca561a40..8663962057 100644 --- a/examples/televiz/configs/oakd.yaml +++ b/examples/televiz/configs/oakd.yaml @@ -37,8 +37,13 @@ pose: corrections: gravity_align_s: 2.0 # hold the camera still for this long at start +# Where the picture sits, in the keys of camera_viz's `display.placements`. +placement: + lock_mode: gimbal # it follows your position and turns with the camera + distance: 2.0 # metres from you + # size: [3.2, 1.8] # metres; left out, it covers the camera's field of view + render: - distance_m: 2.0 stereo: false # one colour camera viewpoint: diff --git a/examples/televiz/configs/replay.yaml b/examples/televiz/configs/replay.yaml index 9080de38ec..ddf117c47c 100644 --- a/examples/televiz/configs/replay.yaml +++ b/examples/televiz/configs/replay.yaml @@ -37,8 +37,13 @@ pose: corrections: gravity_align_s: 0.0 # a recording carries no IMU +# Where the picture sits, in the keys of camera_viz's `display.placements`. +placement: + lock_mode: gimbal # it follows your position and turns with the camera + distance: 2.0 # metres from you + # size: [3.2, 1.8] # metres; left out, it covers the camera's field of view + render: - distance_m: 2.0 stereo: true # No controller button is bound here: space in the run terminal recenters. diff --git a/examples/televiz/configs/synthetic.yaml b/examples/televiz/configs/synthetic.yaml index 9ae98ee192..9c2b01bae8 100644 --- a/examples/televiz/configs/synthetic.yaml +++ b/examples/televiz/configs/synthetic.yaml @@ -31,8 +31,13 @@ pose: corrections: gravity_align_s: 0.0 # the drawn camera has no IMU +# Where the picture sits, in the keys of camera_viz's `display.placements`. +placement: + lock_mode: gimbal # it follows your position and turns with the camera + distance: 2.0 # metres from you + # size: [3.2, 1.8] # metres; left out, it covers the camera's field of view + render: - distance_m: 2.0 stereo: true # A controller button for recenter, as an example to copy into a config of diff --git a/examples/televiz/configs/zed.yaml b/examples/televiz/configs/zed.yaml index 0af410af8a..094782ec98 100644 --- a/examples/televiz/configs/zed.yaml +++ b/examples/televiz/configs/zed.yaml @@ -37,8 +37,13 @@ pose: corrections: gravity_align_s: 2.0 # skipped with a warning on a ZED without an IMU +# Where the picture sits, in the keys of camera_viz's `display.placements`. +placement: + lock_mode: gimbal # it follows your position and turns with the camera + distance: 2.0 # metres from you + # size: [3.2, 1.8] # metres; left out, it covers the camera's field of view + render: - distance_m: 2.0 stereo: true # No controller button is bound here: space in the run terminal recenters. diff --git a/examples/televiz/python/isaaccapture_examples/televiz/app.py b/examples/televiz/python/isaaccapture_examples/televiz/app.py index 94262e0037..ac045731d7 100644 --- a/examples/televiz/python/isaaccapture_examples/televiz/app.py +++ b/examples/televiz/python/isaaccapture_examples/televiz/app.py @@ -182,7 +182,7 @@ def build_pipeline(config: AppConfig, session=None, window=None) -> Pipeline: frames, pose, viewpoint, - distance_m=config.render.distance_m, + placement=config.placement, stereo=config.render.stereo, composition=config.render.composition, # The head latch uses the same key, so both agree on the @@ -201,7 +201,7 @@ def build_pipeline(config: AppConfig, session=None, window=None) -> Pipeline: Viewpoint(config.viewpoint, pose_in=pose), window.camera, window.images, - distance_m=config.render.distance_m, + placement=config.placement, anchor_eye=config.viewpoint.anchor_eye, ) ) diff --git a/examples/televiz/python/isaaccapture_examples/televiz/pipeline/config.py b/examples/televiz/python/isaaccapture_examples/televiz/pipeline/config.py index 9f918de07d..1d1faef025 100644 --- a/examples/televiz/python/isaaccapture_examples/televiz/pipeline/config.py +++ b/examples/televiz/python/isaaccapture_examples/televiz/pipeline/config.py @@ -53,9 +53,9 @@ def _from_mapping(cls: Type[D], data: Any, context: str) -> D: } #: Keys and whole sections the type check leaves alone, because the code -#: that reads them refuses a wrong value in words of its own: resolve_camera -#: and BindingsConfig. -_OWN_CHECK = ("source.camera", "bindings") +#: that reads them refuses a wrong value in words of its own: resolve_camera, +#: PlacementConfig and BindingsConfig. +_OWN_CHECK = ("source.camera", "placement.size", "bindings") def _wrong_type(cls, data: dict, context: str) -> str: @@ -174,10 +174,74 @@ def __post_init__(self) -> None: ) +#: How the picture follows the operator (render/placement.py). +LOCK_MODES = ("world", "head", "gimbal", "lazy") + + +@dataclass(frozen=True) +class PlacementConfig: + # Where the picture sits, in the keys of the camera_viz example's + # `display.placements` block, which its Camera Streaming guide describes. + # + # gimbal: the picture follows your position and turns with the camera. + # world: it stays where it was seated and turns with the camera. + # lazy: as world, and it comes back when you look away from it. + # head: it stays in front of your eyes, and nothing is stabilized. + lock_mode: str = "gimbal" + # Metres from the viewer. + distance: float = 2.0 + # [width, height] in metres. Left out, the picture covers the camera's + # field of view, at any distance. + size: Optional[list] = None + # Metres to the right and up of straight ahead. + offset_x: float = 0.0 + offset_y: float = 0.0 + # lazy: looking this far away from the picture, or moving this far + # from where it would be seated, for the delay brings it back over the + # transition. + look_away_angle_deg: float = 45.0 + reposition_distance: float = 0.5 + reposition_delay_s: float = 0.5 + transition_duration_s: float = 0.3 + + def __post_init__(self) -> None: + if self.lock_mode not in LOCK_MODES: + raise ConfigError( + f"placement.lock_mode must be {'|'.join(LOCK_MODES)}, got " + f"{self.lock_mode!r}" + ) + if self.distance <= 0.0: + raise ConfigError(f"placement.distance must be > 0, got {self.distance}") + size = self.size + if size is not None and not ( + isinstance(size, (list, tuple)) + and len(size) == 2 + and all( + isinstance(side, (int, float)) + and not isinstance(side, bool) + and math.isfinite(side) + and side > 0 + for side in size + ) + ): + raise ConfigError( + "placement.size takes [width, height] in metres, both above 0, " + f"got {size!r}" + ) + for name in ( + "look_away_angle_deg", + "reposition_distance", + "reposition_delay_s", + "transition_duration_s", + ): + if getattr(self, name) < 0.0: + raise ConfigError( + f"placement.{name} must be 0 or above, got {getattr(self, name)}" + ) + + @dataclass(frozen=True) class RenderConfig: - # The image rides a flat stereo plane this far in front of the camera. - distance_m: float = 2.0 # True textures the right eye from the right camera. stereo: bool = True # openxr: the runtime composites the plane. builtin: Isaac Capture's @@ -185,8 +249,6 @@ class RenderConfig: composition: str = "openxr" def __post_init__(self) -> None: - if self.distance_m <= 0.0: - raise ConfigError(f"render.distance_m must be > 0, got {self.distance_m}") if self.composition not in ("openxr", "builtin"): raise ConfigError( f"render.composition must be openxr|builtin, got {self.composition!r}" @@ -306,6 +368,7 @@ def __post_init__(self) -> None: "source": SourceConfig, "pose": PoseConfig, "corrections": CorrectionsConfig, + "placement": PlacementConfig, "render": RenderConfig, "viewpoint": ViewpointConfig, "bindings": BindingsConfig, @@ -322,6 +385,7 @@ class AppConfig: source: SourceConfig = field(default_factory=SourceConfig) pose: PoseConfig = field(default_factory=PoseConfig) corrections: CorrectionsConfig = field(default_factory=CorrectionsConfig) + placement: PlacementConfig = field(default_factory=PlacementConfig) render: RenderConfig = field(default_factory=RenderConfig) viewpoint: ViewpointConfig = field(default_factory=ViewpointConfig) bindings: BindingsConfig = field(default_factory=BindingsConfig) diff --git a/examples/televiz/python/isaaccapture_examples/televiz/render/placement.py b/examples/televiz/python/isaaccapture_examples/televiz/render/placement.py new file mode 100644 index 0000000000..cefd682a20 --- /dev/null +++ b/examples/televiz/python/isaaccapture_examples/televiz/render/placement.py @@ -0,0 +1,155 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Where the picture sits: camera_viz's placement of a plane, in a frame +that turns with the camera. + +camera_viz seats a plane from the operator's head alone, by one of four +rules, its ``lock_mode``. Here the same rules run in a frame that carries +the camera's orientation and pivots on where the operator's eye was when +the picture was last seated: + +- ``gimbal``: the picture follows the operator's position and turns with + the camera. +- ``world``: its home stays where it was seated, and it swings about that + place with the camera. +- ``lazy``: as ``world``, and it comes back in front of an operator who + has looked away from it. +- ``head``: it stays in front of the eyes. The camera's turn cancels out, + so nothing is stabilized. + +Pure NumPy over camera_viz's strategies: no session and no layer. +""" + +from __future__ import annotations + +from typing import NamedTuple, Optional, Tuple + +import numpy as np + +from ..pipeline.config import LOCK_MODES, ConfigError +from .viewpoint import quat_wxyz + +_INSTALL = "uv pip install -e ./examples/camera_viz --no-sources" + + +def camera_viz_placements(): + """camera_viz's placement strategies, which this example does not copy.""" + try: + from isaaccapture_examples.camera_viz import placements + except ImportError as exc: + raise ConfigError( + "the picture is placed by the camera_viz example, which is not in " + f"this environment: run `{_INSTALL}` (README, 'Setup'): {exc}" + ) from exc + return placements + + +def true_size(model, distance: float) -> Tuple[float, float]: + """Width and height in metres of a plane ``distance`` away that covers + the field of view of the camera ``model`` describes.""" + return (model.width * distance / model.fx, model.height * distance / model.fy) + + +def placement_config(settings, model): + """camera_viz's ``PlacementConfig`` for the config's ``placement`` + section. A picture whose size is left out covers the field of view of + the camera ``model`` describes.""" + size = settings.size + return camera_viz_placements().PlacementConfig( + size_meters=( + true_size(model, settings.distance) + if size is None + else (float(size[0]), float(size[1])) + ), + distance=settings.distance, + offset_x=settings.offset_x, + offset_y=settings.offset_y, + look_away_angle_deg=settings.look_away_angle_deg, + reposition_distance=settings.reposition_distance, + reposition_delay_s=settings.reposition_delay_s, + transition_duration_s=settings.transition_duration_s, + ) + + +class Plane(NamedTuple): + """A placed picture, in the XR world.""" + + centre: np.ndarray + rotation: np.ndarray # its axes: x right, y up, +z toward the viewer + size_meters: Tuple[float, float] + + +def _rotation(quat) -> np.ndarray: + """Unit quaternion (w, x, y, z) -> rotation matrix.""" + w, x, y, z = (float(c) for c in quat) + return np.array( + [ + [1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y - w * z), 2.0 * (x * z + w * y)], + [2.0 * (x * y + w * z), 1.0 - 2.0 * (x * x + z * z), 2.0 * (y * z - w * x)], + [2.0 * (x * z - w * y), 2.0 * (y * z + w * x), 1.0 - 2.0 * (x * x + y * y)], + ] + ) + + +class CameraPlacement: + """One picture's placement. Used on the frame loop's thread only.""" + + def __init__(self, lock_mode: str, config) -> None: + if lock_mode not in LOCK_MODES: + raise ConfigError( + f"placement.lock_mode must be {'|'.join(LOCK_MODES)}, got {lock_mode!r}" + ) + self._placements = camera_viz_placements() + self._lock_mode = lock_mode + self._config = config # camera_viz's PlacementConfig + self._strategy = None + self._pivot: Optional[np.ndarray] = None + + @property + def lock_mode(self) -> str: + return self._lock_mode + + @property + def config(self): + return self._config + + def seat(self) -> None: + """Seat the picture anew with the next update: on the camera's + axis, about where the eye then is.""" + self._strategy = None + + def set_lock_mode(self, lock_mode: str) -> None: + if lock_mode not in LOCK_MODES: + raise ValueError(f"no lock mode {lock_mode!r}") + self._lock_mode = lock_mode + self.seat() + + def retune(self, config) -> None: + """Take another size, distance or offset without seating anew.""" + self._config = config + if self._strategy is not None: + self._strategy.retune(config) + + def update(self, eye, head_rotation, camera_rotation) -> Plane: + """This frame's plane. ``eye`` is where the picture is seen from, + ``head_rotation`` the head's axes and ``camera_rotation`` the + camera's (both x right, y up, +z back), all in the XR world.""" + eye = np.asarray(eye, dtype=np.float64) + camera = np.asarray(camera_rotation, dtype=np.float64) + if self._strategy is None: + self._strategy = self._placements.build(self._lock_mode, self._config) + self._pivot = eye.copy() + # Seated by a head that looks along the camera's axis, which is + # where a recenter has put the operator's heading. + self._strategy.update(tuple(eye), (1.0, 0.0, 0.0, 0.0)) + pivot = self._pivot + # The head as the camera's frame sees it. + head = pivot + camera.T @ (eye - pivot) + facing = camera.T @ np.asarray(head_rotation, dtype=np.float64) + placed = self._strategy.update( + tuple(float(c) for c in head), tuple(float(q) for q in quat_wxyz(facing)) + ) + centre = pivot + camera @ (np.asarray(placed.position) - pivot) + return Plane( + centre, camera @ _rotation(placed.orientation), tuple(placed.size_meters) + ) diff --git a/examples/televiz/python/isaaccapture_examples/televiz/render/quad_stage.py b/examples/televiz/python/isaaccapture_examples/televiz/render/quad_stage.py index 3ca36fb391..1bce79030a 100644 --- a/examples/televiz/python/isaaccapture_examples/televiz/render/quad_stage.py +++ b/examples/televiz/python/isaaccapture_examples/televiz/render/quad_stage.py @@ -2,12 +2,11 @@ # SPDX-License-Identifier: Apache-2.0 """QuadRenderStage: the camera image on one flat stereo plane. -The plane's orientation follows the capture camera and its position -follows the head, so the view is stabilized in orientation only. With M -the map-to-view transform (Viewpoint) and K the capture pose with its -translation replaced by the head's:: - - T_xrworld_from_plane = inv(M) @ K @ _C +The plane turns with the capture camera, so the view is stabilized in +orientation only. With M the map-to-view transform (Viewpoint) and K the +capture pose, the camera's axes in the XR world are those of +``inv(M) @ K @ _C``; where the plane sits about them is the config's +``placement`` section (render/placement.py). The plane is a native OpenXR quad layer by default, which the runtime places and samples itself; no depth is submitted. @@ -25,8 +24,10 @@ import numpy as np +from ..pipeline.config import PlacementConfig from ..pipeline.mailbox import Mailbox from ..pipeline.stage import Stage +from .placement import CameraPlacement, placement_config # _C is imported, not re-declared: the optical-to-XR swap folded into the # plane's pose must be the one compose() folds in. @@ -70,7 +71,7 @@ def __init__( pose_in: Mailbox, # PoseSample: the plane's orientation viewpoint: Viewpoint, *, - distance_m: float = 2.0, + placement: Optional[PlacementConfig] = None, # the config's section stereo: bool = False, # texture the right eye from the right camera composition: str = "openxr", # openxr: the runtime composites the quad anchor_eye: str = "left", # must match viewpoint.anchor_eye @@ -80,7 +81,10 @@ def __init__( self._frames_in = frames_in self._pose_in = pose_in self._viewpoint = viewpoint - self._distance_m = float(distance_m) + self._settings = PlacementConfig() if placement is None else placement + self._camera_placement: Optional[CameraPlacement] = None + self._placed_model = None # the camera the placement is sized for + self._seated_epoch = None # the view's re-seat the picture is seated for self._stereo = bool(stereo) self._composition = composition self._anchor_eye = anchor_eye @@ -316,35 +320,49 @@ def _placement(self, views, model, T_map_from_cam): def _plane(self, views, model, T_map_from_cam): """Where the plane is this frame, in the XR world: its centre, its axes as a rotation (x right, y up, +z toward the viewer) and its - size in metres. Capture orientation, head position.""" + size in metres.""" anchor = self._anchor(views) - if anchor is not None: - head = np.asarray(views[anchor].T_map_from_cam)[:3, 3] - else: - # Midpoint mode, eyes with no separation, or a single view. - head = np.mean([np.asarray(v.T_map_from_cam)[:3, 3] for v in views], axis=0) - - T = np.asarray(T_map_from_cam, dtype=np.float64).copy() - T[:3, 3] = head - # Map to XR, then optical axes to quad axes. A quad is x-right, - # y-up, +z toward the viewer and centred on its pose; the optical - # camera is y-down, z-forward. - Txr = self._viewpoint.content_pose_xr(T) @ _C - - d = self._distance_m + eyes = [np.asarray(v.position, dtype=np.float64) for v in views] + eye = eyes[anchor] if anchor is not None else np.mean(eyes, axis=0) + # The capture orientation in the XR world, optical axes turned to a + # quad's: x right, y up, +z toward the viewer. + camera = (self._viewpoint.content_pose_xr(T_map_from_cam) @ _C)[:3, :3] + placed = self._seated(model).update( + eye, pose_to_matrix(views[0])[:3, :3], camera + ) + width_m, height_m = placed.size_meters # Rectification does not centre the principal point, and a quad is - # centred on its pose, so without this offset the image sits off + # centred on its pose, so without this shift the image sits off # axis. (W - 1) / 2 and not W / 2: cx and cy are pixel-centre - # coordinates. - cx_o = ((model.width - 1) * 0.5 - model.cx) * d / model.fx - cy_o = ((model.height - 1) * 0.5 - model.cy) * d / model.fy - R = Txr[:3, :3] - # Optical (cx_o, cy_o, d) in quad axes: y flips, and the plane in - # front of the camera sits at quad-local -z. - centre = Txr[:3, 3] + R @ np.array([cx_o, -cy_o, -d]) - # The camera's full field of view at distance d. - size_meters = (model.width * d / model.fx, model.height * d / model.fy) - return centre, R, size_meters + # coordinates. A quad's y points up. + shift = np.array( + [ + ((model.width - 1) * 0.5 - model.cx) * width_m / model.width, + -((model.height - 1) * 0.5 - model.cy) * height_m / model.height, + 0.0, + ] + ) + centre = placed.centre + placed.rotation @ shift + return centre, placed.rotation, placed.size_meters + + def _seated(self, model) -> CameraPlacement: + """The picture's placement, sized for ``model`` and seated anew + after every re-seat of the view: a recenter turns the camera's + frame under a picture that keeps its seat.""" + if self._camera_placement is None or model != self._placed_model: + config = placement_config(self._settings, model) + if self._camera_placement is None: + self._camera_placement = CameraPlacement( + self._settings.lock_mode, config + ) + else: + self._camera_placement.retune(config) + self._placed_model = model + epoch = self._viewpoint.anchor_epoch + if epoch != self._seated_epoch: + self._seated_epoch = epoch + self._camera_placement.seat() + return self._camera_placement # -- layer --------------------------------------------------------------- # Layers are added and removed on the frame-loop thread, which is this @@ -388,11 +406,12 @@ def _ensure_layer(self, model) -> None: self._layer = self._session.add_quad_layer(cfg) self._layer_size = size log.info( - "render:quad: %dx%d %s plane at %.2f m (%s composition)", + "render:quad: %dx%d %s plane at %.2f m, %s-locked (%s composition)", size[0], size[1], "stereo" if self._stereo else "mono", - self._distance_m, + self._settings.distance, + self._settings.lock_mode, "native OpenXR" if cfg.openxr_composition else "built-in", ) diff --git a/examples/televiz/python/isaaccapture_examples/televiz/render/window_view.py b/examples/televiz/python/isaaccapture_examples/televiz/render/window_view.py index dbf0f9475b..97f5095127 100644 --- a/examples/televiz/python/isaaccapture_examples/televiz/render/window_view.py +++ b/examples/televiz/python/isaaccapture_examples/televiz/render/window_view.py @@ -351,7 +351,7 @@ def __init__( camera: OrbitCamera, images_out: Mailbox, # host RGBA8 images for DesktopWindow *, - distance_m: float = 2.0, + placement=None, # the config's section anchor_eye: str = "left", ) -> None: super().__init__( @@ -359,7 +359,7 @@ def __init__( frames_in, pose_in, viewpoint, - distance_m=distance_m, + placement=placement, anchor_eye=anchor_eye, ) self._camera = camera diff --git a/tests/python/examples/televiz/test_placement.py b/tests/python/examples/televiz/test_placement.py new file mode 100644 index 0000000000..72de3673ed --- /dev/null +++ b/tests/python/examples/televiz/test_placement.py @@ -0,0 +1,213 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Where the picture sits: camera_viz's lock modes, in a frame that turns +with the camera.""" + +from __future__ import annotations + +import dataclasses +import math + +import numpy as np +import pytest +from _app import ZED_SOURCE + +from isaaccapture_examples.camera_viz.placements import ( + PlacementConfig as CameraVizPlacement, +) +from isaaccapture_examples.camera_viz.placements import lock_modes +from isaaccapture_examples.televiz.pipeline.config import ( + LOCK_MODES, + AppConfig, + ConfigError, + PlacementConfig, +) +from isaaccapture_examples.televiz.pipeline.messages import CameraModel +from isaaccapture_examples.televiz.render.placement import ( + CameraPlacement, + placement_config, + true_size, +) + +MODEL = CameraModel(1280, 720, 800.0, 800.0, 639.5, 359.5) +EYE = np.array([0.2, 1.6, -0.3]) +LEVEL = np.eye(3) +AHEAD = np.array([0.0, 0.0, -1.0]) # a level head or camera looks along -z + + +def yaw(deg: float) -> np.ndarray: + """A turn to the left by ``deg`` about the vertical.""" + c, s = math.cos(math.radians(deg)), math.sin(math.radians(deg)) + return np.array([[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]) + + +def pitch(deg: float) -> np.ndarray: + """A tilt upward by ``deg``.""" + c, s = math.cos(math.radians(deg)), math.sin(math.radians(deg)) + return np.array([[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]) + + +def placement(lock_mode: str, **settings) -> CameraPlacement: + section = PlacementConfig(lock_mode=lock_mode, **settings) + return CameraPlacement(lock_mode, placement_config(section, MODEL)) + + +@pytest.mark.parametrize("lock_mode", LOCK_MODES) +def test_a_seated_picture_is_straight_ahead_of_a_level_camera(lock_mode): + plane = placement(lock_mode).update(EYE, LEVEL, LEVEL) + np.testing.assert_allclose(plane.centre, EYE + 2.0 * AHEAD, atol=1e-9) + np.testing.assert_allclose(plane.rotation, LEVEL, atol=1e-9) + assert plane.size_meters == pytest.approx(true_size(MODEL, 2.0)) + + +@pytest.mark.parametrize("lock_mode", ["world", "gimbal", "lazy"]) +def test_the_picture_turns_with_the_camera_and_not_with_the_head(lock_mode): + placed = placement(lock_mode) + placed.update(EYE, LEVEL, LEVEL) + camera = yaw(30.0) @ pitch(-10.0) + for head in (LEVEL, yaw(20.0), yaw(-25.0) @ pitch(15.0)): + plane = placed.update(EYE, head, camera) + np.testing.assert_allclose( + plane.centre, EYE + camera @ (2.0 * AHEAD), atol=1e-9 + ) + np.testing.assert_allclose(plane.rotation, camera, atol=1e-9) + + +def test_head_locked_the_picture_stays_before_the_eyes_whatever_the_camera_does(): + placed = placement("head") + placed.update(EYE, LEVEL, LEVEL) + head = yaw(40.0) @ pitch(-15.0) + plane = placed.update(EYE, head, yaw(-70.0) @ pitch(20.0)) + np.testing.assert_allclose(plane.centre, EYE + head @ (2.0 * AHEAD), atol=1e-9) + np.testing.assert_allclose(plane.rotation, head, atol=1e-9) + + +def test_gimbal_follows_the_eye_and_world_stays_where_it_was_seated(): + step = np.array([0.4, -0.1, 0.3]) + camera = yaw(25.0) + follows, stays = placement("gimbal"), placement("world") + for placed in (follows, stays): + placed.update(EYE, LEVEL, LEVEL) + moved = follows.update(EYE + step, LEVEL, camera) + np.testing.assert_allclose( + moved.centre, EYE + step + camera @ (2.0 * AHEAD), atol=1e-9 + ) + # Seated about where the eye was: the operator walks up to it. + still = stays.update(EYE + step, LEVEL, camera) + np.testing.assert_allclose(still.centre, EYE + camera @ (2.0 * AHEAD), atol=1e-9) + + +def test_a_seat_puts_the_picture_back_on_the_cameras_axis_about_the_eye(): + placed = placement("world") + placed.update(EYE, LEVEL, LEVEL) + there = EYE + np.array([1.0, 0.0, 2.0]) + camera = yaw(-50.0) + placed.seat() + plane = placed.update(there, yaw(35.0), camera) # wherever the head looks + np.testing.assert_allclose(plane.centre, there + camera @ (2.0 * AHEAD), atol=1e-9) + + +@pytest.fixture +def clock(monkeypatch): + """The time camera_viz's lazy lock goes by.""" + now = [100.0] + monkeypatch.setattr(lock_modes.time, "monotonic", lambda: now[0]) + return now + + +def test_lazy_brings_back_a_picture_the_operator_has_looked_away_from(clock): + placed = placement("lazy", reposition_delay_s=0.5, transition_duration_s=0.2) + placed.update(EYE, LEVEL, LEVEL) + away = yaw(60.0) + placed.update(EYE, away, LEVEL) # looks away: the delay starts + clock[0] += 0.4 + held = placed.update(EYE, away, LEVEL) + np.testing.assert_allclose(held.centre, EYE + 2.0 * AHEAD, atol=1e-9) + clock[0] += 0.2 + placed.update(EYE, away, LEVEL) # past the delay: the glide begins + clock[0] += 0.3 + back = placed.update(EYE, away, LEVEL) + np.testing.assert_allclose(back.centre, EYE + away @ (2.0 * AHEAD), atol=1e-6) + + +def test_lazy_leaves_a_picture_the_operator_follows_with_the_camera(clock): + """It is the picture on display that is looked at, not its seat.""" + placed = placement("lazy", reposition_delay_s=0.5) + placed.update(EYE, LEVEL, LEVEL) + turned = yaw(80.0) # the camera turns, and the operator's head with it + for _ in range(5): + clock[0] += 0.5 + plane = placed.update(EYE, turned, turned) + np.testing.assert_allclose( + plane.centre, EYE + turned @ (2.0 * AHEAD), atol=1e-9 + ) + + +def test_a_picture_of_a_given_size_looks_smaller_from_farther_away(): + near = placement("gimbal", size=[1.6, 0.9], distance=2.0).update(EYE, LEVEL, LEVEL) + far = placement("gimbal", size=[1.6, 0.9], distance=4.0).update(EYE, LEVEL, LEVEL) + assert near.size_meters == far.size_meters == (1.6, 0.9) + np.testing.assert_allclose(far.centre, EYE + 4.0 * AHEAD, atol=1e-9) + + +def test_a_picture_whose_size_is_left_out_covers_the_cameras_field_of_view(): + for distance in (1.0, 2.0, 5.0): + width, height = placement("gimbal", distance=distance).config.size_meters + assert 2.0 * math.atan(width / 2.0 / distance) == pytest.approx( + 2.0 * math.atan(MODEL.width / 2.0 / MODEL.fx) + ) + assert height / width == pytest.approx(MODEL.height / MODEL.width) + + +def test_offsets_shift_the_picture_in_the_cameras_frame(): + placed = placement("gimbal", offset_x=0.5, offset_y=-0.25) + camera = yaw(90.0) + plane = placed.update(EYE, LEVEL, camera) + np.testing.assert_allclose( + plane.centre, EYE + camera @ np.array([0.5, -0.25, -2.0]), atol=1e-9 + ) + + +def test_a_retune_resizes_the_picture_where_it_sits(): + placed = placement("world") + placed.update(EYE, LEVEL, LEVEL) + placed.retune(dataclasses.replace(placed.config, size_meters=(1.0, 0.5))) + plane = placed.update(EYE + 0.3, LEVEL, LEVEL) + assert plane.size_meters == (1.0, 0.5) + np.testing.assert_allclose(plane.centre, EYE + 2.0 * AHEAD, atol=1e-9) + + +def test_the_placement_keys_are_camera_viz_s(): + """The section is passed on to camera_viz's placement by name.""" + ours = {f.name for f in dataclasses.fields(PlacementConfig)} + theirs = {f.name for f in dataclasses.fields(CameraVizPlacement)} + assert ours - {"lock_mode", "size"} == theirs - {"size_meters"} + + +@pytest.mark.parametrize( + "section, complaint", + [ + ( + "{lock_mode: sticky}", + r"placement\.lock_mode must be world\|head\|gimbal\|lazy", + ), + ("{size: 2.0}", r"placement\.size takes \[width, height\]"), + ("{size: [1.6, 0]}", r"placement\.size takes \[width, height\]"), + ("{size: [1.6, 0.9, 1]}", r"placement\.size takes \[width, height\]"), + ("{distance: '2'}", r"placement\.distance takes a number, got '2'"), + ( + "{reposition_delay_s: -1}", + r"placement\.reposition_delay_s must be 0 or above", + ), + ], +) +def test_a_placement_the_picture_cannot_take_is_refused(tmp_path, section, complaint): + path = tmp_path / "televiz.yaml" + path.write_text(ZED_SOURCE + f"placement: {section}\n") + with pytest.raises(ConfigError, match=complaint): + AppConfig.load(path) + + +def test_an_unknown_lock_mode_is_refused_by_the_placement_too(): + with pytest.raises(ConfigError, match=r"placement\.lock_mode"): + CameraPlacement("sticky", placement_config(PlacementConfig(), MODEL)) diff --git a/tests/python/examples/televiz/test_quad_placement.py b/tests/python/examples/televiz/test_quad_placement.py index fb5266f0b2..320f8b6711 100644 --- a/tests/python/examples/televiz/test_quad_placement.py +++ b/tests/python/examples/televiz/test_quad_placement.py @@ -20,6 +20,7 @@ from isaaccapture_examples.televiz.pipeline.config import ( AppConfig, ConfigError, + PlacementConfig, RenderConfig, ViewpointConfig, ) @@ -134,11 +135,15 @@ def _stub_stage(vp, distance_m, anchor_eye): stage = SimpleNamespace( _viz=VIZ_STUB, _viewpoint=vp, - _distance_m=distance_m, + _settings=PlacementConfig(distance=distance_m), + _camera_placement=None, + _placed_model=None, + _seated_epoch=None, _anchor_eye=anchor_eye, ) stage._plane = lambda *args: QuadRenderStage._plane(stage, *args) stage._anchor = lambda views: QuadRenderStage._anchor(stage, views) + stage._seated = lambda model: QuadRenderStage._seated(stage, model) return stage @@ -438,15 +443,16 @@ def _config(tmp_path, body): def test_the_render_defaults(tmp_path): cfg = AppConfig.load(_config(tmp_path, ZED_SOURCE)) - assert cfg.render.distance_m == PLANE_DISTANCE_M + assert cfg.placement.distance == PLANE_DISTANCE_M + assert cfg.placement.lock_mode == "gimbal" and cfg.placement.size is None assert cfg.render.composition == "openxr" # the runtime composites it assert cfg.render.stereo is True @pytest.mark.parametrize("distance_m", [0.0, -2.0]) def test_the_plane_distance_must_be_positive(distance_m): - with pytest.raises(ConfigError, match="distance_m"): - RenderConfig(distance_m=distance_m) + with pytest.raises(ConfigError, match=r"placement\.distance must be > 0"): + PlacementConfig(distance=distance_m) def test_an_unknown_composition_is_rejected(): From 1894aad1bb4d3699839f309ca3c2d23778f618e9 Mon Sep 17 00:00:00 2001 From: Jun-Jee Chao Date: Tue, 1 Dec 2026 17:52:29 -0800 Subject: [PATCH 2/5] feat(examples/televiz): camera_viz's controller bindings for the view The controllers now change the view live, as in the camera_viz example: the lock mode, mono or stereo, the picture's size and height, the gap between the two eyes' planes, and a reset to the config's values. Each is an action or an axis on the stream every input path posts to, bound in the config's bindings table: none takes a binding away, and an optional hold gates them all. The shipped configs preset camera_viz's layout. What a change does to a size, a height or a gap is camera_viz's own code, and a change shows on its head-locked panel in the headset. The view's own lazy-lock goes: lock_mode lazy is the one lazy rule. The guide gains a Controller bindings section with the figure. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Jun-Jee Chao --- docs/source/_static/televiz-controls.png | 3 + .../_static/televiz-controls.png.license | 2 + docs/source/references/televiz.rst | 146 +++-- examples/televiz/configs/oakd.yaml | 14 +- examples/televiz/configs/replay.yaml | 14 +- examples/televiz/configs/synthetic.yaml | 16 +- examples/televiz/configs/zed.yaml | 14 +- .../isaaccapture_examples/televiz/app.py | 5 +- .../televiz/pipeline/actions.py | 64 ++- .../televiz/pipeline/config.py | 108 ++-- .../televiz/render/controller_actions.py | 84 ++- .../televiz/render/placement.py | 4 + .../televiz/render/quad_stage.py | 60 ++- .../televiz/render/view_controls.py | 271 ++++++++++ .../televiz/render/viewpoint.py | 177 +----- .../televiz/render/window_view.py | 4 +- tests/python/examples/televiz/test_actions.py | 130 +++-- .../televiz/test_controller_actions.py | 94 +++- tests/python/examples/televiz/test_heading.py | 4 +- .../python/examples/televiz/test_placement.py | 8 +- .../examples/televiz/test_quad_placement.py | 1 + .../televiz/test_recenter_full_latch_drift.py | 173 ------ .../examples/televiz/test_view_controls.py | 502 ++++++++++++++++++ .../python/examples/televiz/test_viewpoint.py | 90 ---- 24 files changed, 1375 insertions(+), 613 deletions(-) create mode 100644 docs/source/_static/televiz-controls.png create mode 100644 docs/source/_static/televiz-controls.png.license create mode 100644 examples/televiz/python/isaaccapture_examples/televiz/render/view_controls.py create mode 100644 tests/python/examples/televiz/test_view_controls.py diff --git a/docs/source/_static/televiz-controls.png b/docs/source/_static/televiz-controls.png new file mode 100644 index 0000000000..8c9d41dc78 --- /dev/null +++ b/docs/source/_static/televiz-controls.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82f6c9a281d227bb3da37b8a462b99af5e6c4b8948575d0ce8aab81a15b709db +size 1404131 diff --git a/docs/source/_static/televiz-controls.png.license b/docs/source/_static/televiz-controls.png.license new file mode 100644 index 0000000000..817df24424 --- /dev/null +++ b/docs/source/_static/televiz-controls.png.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: Apache-2.0 diff --git a/docs/source/references/televiz.rst b/docs/source/references/televiz.rst index bd6752bfc8..6130c50440 100644 --- a/docs/source/references/televiz.rst +++ b/docs/source/references/televiz.rst @@ -174,8 +174,10 @@ First-session checklist - **Head movement:** turn your head; the plane stays where it is. - **Leaning:** lean or step sideways; the plane follows you, with no parallax. The view is stabilized in orientation only. -- **Recenter:** press space in the terminal; the plane comes back in front of you. With - controllers, hold the left grip and press ``X``, which ``synthetic.yaml`` binds. +- **Recenter:** press space in the terminal, or click the right controller's stick; the plane + comes back in front of you. +- **Controllers:** push the left stick to resize the plane; :ref:`televiz-controls` lists the + rest. - **Restart:** press ``Ctrl+C``, rerun, and reconnect if needed. If a check fails, see :ref:`televiz-troubleshooting`. @@ -319,8 +321,10 @@ you. In every mode but ``head`` the picture turns with the camera: - The picture stays where it was seated. Lean or walk and you move against it. * - ``lazy`` - As ``world``, and when you have looked away from the picture it glides back in front of - you. The knobs are ``look_away_angle_deg``, ``reposition_distance``, - ``reposition_delay_s`` and ``transition_duration_s``. + you. That also happens when the camera turns and your head does not: the picture then + sits in front of you and no longer where the camera looks, until the next recenter. The + knobs are ``look_away_angle_deg``, ``reposition_distance``, ``reposition_delay_s`` and + ``transition_duration_s``. * - ``head`` - The picture stays in front of your eyes and nothing is stabilized, as in camera_viz. @@ -329,30 +333,96 @@ camera's field of view at any distance, so what it shows keeps its true angular ``size: [width, height]`` in metres it is a screen of that size, which looks smaller from farther away. A recenter seats the picture anew on the camera's axis. -.. _televiz-recenter: +.. _televiz-controls: -Recenter -^^^^^^^^ +Controller bindings +^^^^^^^^^^^^^^^^^^^ -Recentering puts the picture back in front of you. Two inputs do it: +In the headset the controllers retune the view live, without editing the YAML and restarting. +The configs in :code-dir:`configs/ ` come with the layout of +:ref:`camera_viz ` bound. The right hand changes how the picture +reads; the left, its size and height: -- **Space**, in the terminal the example runs in or in the window of ``--mode window``. -- **A controller button**, when the config binds one. Nothing is bound by default, because - controllers worn for teleoperation already give their buttons a meaning. +.. figure:: ../_static/televiz-controls.png + :alt: Televiz XR controller bindings: the left controller sets the picture's size and + height and resets the view; the right controller sets depth, lock mode, mono or + stereo, and recenters. + :width: 100% + + Bindings at a glance. The table below is the same thing in words. -A bound action fires when its button is pressed while the ``hold`` input is held. -``configs/synthetic.yaml`` binds recenter to the left primary button (``X``) while the left grip -is held; copy its ``bindings`` section into your own config: +.. list-table:: + :header-rows: 1 + :widths: 22 18 60 + + * - Input + - Binding + - Effect + * - Right stick ←/→ + - ``stereo_gap`` + - The gap between the two eyes' planes (``placement.stereo_plane_distance_cm``). Widening + it sets the whole scene farther back. Stereo pictures only. + * - Right stick click + - ``recenter`` + - Puts the picture back in front of you. + * - ``A`` + - ``lock_mode`` + - Cycles the lock mode: ``world`` → ``head`` → ``gimbal`` → ``lazy``. + * - ``B`` + - ``mono_stereo`` + - Shows both eyes the left image, or each eye its own again. Stereo pictures only. + * - ``Y`` + - ``reset`` + - Puts the view back to the YAML's values: lock mode, size, height, gap and stereo. + * - Left stick ←/→ + - ``size`` + - The picture's size, with its aspect ratio kept. + * - Left stick ↑/↓ + - ``height`` + - The picture's height (``placement.offset_y``). + +``X`` is free: it cycles the shape in camera_viz, and this example has one. A change shows in the +log and on a head-locked panel in the headset that hides again after about 2.5 seconds. Nothing is +written back to the YAML. + +The bindings are the ``bindings`` section. Each line gives one function its input, and the word +``none`` takes it away: .. code-block:: yaml bindings: - hold: left_squeeze - recenter: left_primary # hold the left grip and press X + recenter: right_thumbstick # click + lock_mode: right_primary # A + mono_stereo: right_secondary # B + reset: left_secondary # Y + size: left_thumbstick_x + height: left_thumbstick_y + stereo_gap: right_thumbstick_x + +A button is named by role: ``left_`` or ``right_`` followed by ``squeeze``, ``trigger``, +``primary``, ``secondary`` or ``thumbstick``, and ``left_menu``. A stick axis is ``left_`` or +``right_`` followed by ``thumbstick_x`` or ``thumbstick_y``. + +.. note:: -Inputs are named by role: ``left_`` or ``right_`` followed by ``squeeze``, ``trigger``, -``primary``, ``secondary`` or ``thumbstick``, and ``left_menu``. The word ``none`` leaves an action -without a controller input. + Controllers worn for teleoperation already give their buttons and sticks a meaning. In a + config for such a rig, leave the ``bindings`` section out, which binds nothing, or keep what + you need behind a held input: with ``hold: left_squeeze`` every binding acts only while the + left grip is held. + +How fast a held stick changes its value, and whether the panel is shown, is the ``controls`` +section; :ref:`televiz-configuration` lists its keys. + +.. _televiz-recenter: + +Recenter +^^^^^^^^ + +Recentering puts the picture back in front of you. Two inputs do it: + +- **Space**, in the terminal the example runs in or in the window of ``--mode window``. +- **The controller input** bound to ``recenter``: a click of the right stick in the shipped + configs. The view also recenters by itself onto the first tracked pose, and when the headset's own origin jumps, which is what a recenter on the client looks like to the example. @@ -384,6 +454,8 @@ February 25, 2026, which includes a restriction to NVIDIA Platforms; ``--accept- it. This example's Apache-2.0 license does not apply to cuVSLAM. Read :ref:`televiz-external-materials` before running the script. +.. _televiz-configuration: + Configuration ------------- @@ -428,11 +500,14 @@ relative path is resolved against the config file's directory. size: null # [width, height] in metres; null: the # camera's field of view at that distance offset_x: 0.0 # metres to the right of straight ahead - offset_y: 0.0 # metres up + offset_y: 0.0 # metres up, both as the camera sees it look_away_angle_deg: 45.0 # lazy: looking this far away from the picture reposition_distance: 0.5 # or moving this many metres from its seat, reposition_delay_s: 0.5 # for this long, brings it back transition_duration_s: 0.3 # over this long + stereo_plane_distance_cm: 0.0 + # the gap between the two eyes' planes, + # within -10..10 render: stereo: true # false: both eyes show the same image @@ -442,12 +517,6 @@ relative path is resolved against the config file's directory. viewpoint: recenter_on_first_pose: true - lazy_enabled: false # re-anchor the view once the head has drifted - # past a threshold below for lazy_delay_s - lazy_angle_deg: 1.0 - lazy_translation_m: 0.10 # <= 0 ignores translation - lazy_delay_s: 0.3 - lazy_transition_s: 0.1 # <= 0 snaps auto_relatch: true # recenter when the headset's origin jumps auto_recenter_threshold_m: 0.0 # recenter when the head stays farther than @@ -458,10 +527,22 @@ relative path is resolved against the config file's directory. anchor_eye: left # the eye placed at the camera's optical # centre: left | right | midpoint - bindings: - hold: left_squeeze + bindings: # none: no controller input + hold: none # an input that must be held for the others recenter: none - lazy_toggle: none + lock_mode: none + mono_stereo: none + reset: none + size: none + height: none + stereo_gap: none + + controls: + hud: true # show a change on a panel in the headset + deadzone: 0.2 # a stick this near its centre is at rest + size_rate_m_per_s: 0.5 # what a stick held all the way changes + offset_rate_m_per_s: 0.5 # in a second + plane_distance_rate_cm_per_s: 2.0 pipeline: stats_interval_s: null # seconds between statistics; --stats replaces it @@ -599,8 +680,8 @@ A run is a pipeline of stages, each on its own thread, that hand each other the OpenXR quad layer on a ``VizSession``; the desktop window draws the same plane itself. - **The viewpoint** (:code-file:`render/viewpoint.py `) - owns the one transform between the tracker's map and the headset's world. Recenter and - lazy-lock are the policies that change it. + owns the one transform between the tracker's map and the headset's world, which a recenter + changes. Tests ----- @@ -635,7 +716,8 @@ Next steps ---------- - :ref:`Connect a camera ` or replay your own stereo recording. -- :ref:`Bind a controller button ` to recenter. +- :ref:`Change what the controllers do `, or bind nothing beside a teleop + stack. - Place feeds that need no tracking, or several cameras at once, with ``camera_viz``: :doc:`/references/camera_streaming`. - Read about the compositor underneath in :doc:`/development/visualization`. diff --git a/examples/televiz/configs/oakd.yaml b/examples/televiz/configs/oakd.yaml index 8663962057..611cb85f14 100644 --- a/examples/televiz/configs/oakd.yaml +++ b/examples/televiz/configs/oakd.yaml @@ -49,8 +49,18 @@ render: viewpoint: anchor_eye: midpoint # a mono picture sits between the eyes -# No controller button is bound here: space in the run terminal recenters. -# configs/synthetic.yaml shows how to bind one. +# What the controllers do: the layout of the camera_viz example. `none` +# takes one binding away, and without this section nothing is bound. With +# `hold: left_squeeze` every one of them needs the left grip held, which +# keeps them apart from a teleop stack that reads the same buttons. +bindings: + recenter: right_thumbstick # click: the picture back in front of you + lock_mode: right_primary # A: world -> head -> gimbal -> lazy + mono_stereo: right_secondary # B (a stereo picture only) + reset: left_secondary # Y: back to this file's values + size: left_thumbstick_x + height: left_thumbstick_y + stereo_gap: right_thumbstick_x # how far away the scene reads (a stereo picture only) pipeline: stats_interval_s: 5.0 diff --git a/examples/televiz/configs/replay.yaml b/examples/televiz/configs/replay.yaml index ddf117c47c..d126cb4ff4 100644 --- a/examples/televiz/configs/replay.yaml +++ b/examples/televiz/configs/replay.yaml @@ -46,8 +46,18 @@ placement: render: stereo: true -# No controller button is bound here: space in the run terminal recenters. -# configs/synthetic.yaml shows how to bind one. +# What the controllers do: the layout of the camera_viz example. `none` +# takes one binding away, and without this section nothing is bound. With +# `hold: left_squeeze` every one of them needs the left grip held, which +# keeps them apart from a teleop stack that reads the same buttons. +bindings: + recenter: right_thumbstick # click: the picture back in front of you + lock_mode: right_primary # A: world -> head -> gimbal -> lazy + mono_stereo: right_secondary # B + reset: left_secondary # Y: back to this file's values + size: left_thumbstick_x + height: left_thumbstick_y + stereo_gap: right_thumbstick_x # how far away the scene reads pipeline: stats_interval_s: 5.0 diff --git a/examples/televiz/configs/synthetic.yaml b/examples/televiz/configs/synthetic.yaml index 9c2b01bae8..c0280758ac 100644 --- a/examples/televiz/configs/synthetic.yaml +++ b/examples/televiz/configs/synthetic.yaml @@ -40,12 +40,18 @@ placement: render: stereo: true -# A controller button for recenter, as an example to copy into a config of -# your own: the action fires when its button is pressed while `hold` is -# held. BindingsConfig in pipeline/config.py names the inputs. +# What the controllers do: the layout of the camera_viz example. `none` +# takes one binding away, and without this section nothing is bound. With +# `hold: left_squeeze` every one of them needs the left grip held, which +# keeps them apart from a teleop stack that reads the same buttons. bindings: - hold: left_squeeze - recenter: left_primary # hold the left grip and press X + recenter: right_thumbstick # click: the picture back in front of you + lock_mode: right_primary # A: world -> head -> gimbal -> lazy + mono_stereo: right_secondary # B + reset: left_secondary # Y: back to this file's values + size: left_thumbstick_x + height: left_thumbstick_y + stereo_gap: right_thumbstick_x # how far away the scene reads pipeline: stats_interval_s: 5.0 diff --git a/examples/televiz/configs/zed.yaml b/examples/televiz/configs/zed.yaml index 094782ec98..ece3e892ec 100644 --- a/examples/televiz/configs/zed.yaml +++ b/examples/televiz/configs/zed.yaml @@ -46,8 +46,18 @@ placement: render: stereo: true -# No controller button is bound here: space in the run terminal recenters. -# configs/synthetic.yaml shows how to bind one. +# What the controllers do: the layout of the camera_viz example. `none` +# takes one binding away, and without this section nothing is bound. With +# `hold: left_squeeze` every one of them needs the left grip held, which +# keeps them apart from a teleop stack that reads the same buttons. +bindings: + recenter: right_thumbstick # click: the picture back in front of you + lock_mode: right_primary # A: world -> head -> gimbal -> lazy + mono_stereo: right_secondary # B + reset: left_secondary # Y: back to this file's values + size: left_thumbstick_x + height: left_thumbstick_y + stereo_gap: right_thumbstick_x # how far away the scene reads pipeline: stats_interval_s: 5.0 diff --git a/examples/televiz/python/isaaccapture_examples/televiz/app.py b/examples/televiz/python/isaaccapture_examples/televiz/app.py index ac045731d7..d8578edb62 100644 --- a/examples/televiz/python/isaaccapture_examples/televiz/app.py +++ b/examples/televiz/python/isaaccapture_examples/televiz/app.py @@ -171,7 +171,9 @@ def build_pipeline(config: AppConfig, session=None, window=None) -> Pipeline: try: from .render.controller_actions import ControllerActions - controller = ControllerActions(session, config.bindings) + controller = ControllerActions( + session, config.bindings, deadzone=config.controls.deadzone + ) except Exception as exc: # noqa: BLE001 log.warning("controller input disabled: %s", exc) @@ -183,6 +185,7 @@ def build_pipeline(config: AppConfig, session=None, window=None) -> Pipeline: pose, viewpoint, placement=config.placement, + controls=config.controls, stereo=config.render.stereo, composition=config.render.composition, # The head latch uses the same key, so both agree on the diff --git a/examples/televiz/python/isaaccapture_examples/televiz/pipeline/actions.py b/examples/televiz/python/isaaccapture_examples/televiz/pipeline/actions.py index 53d040beac..8980fc8a5b 100644 --- a/examples/televiz/python/isaaccapture_examples/televiz/pipeline/actions.py +++ b/examples/televiz/python/isaaccapture_examples/televiz/pipeline/actions.py @@ -11,7 +11,8 @@ here: the controllers through the bindings (render/controller_actions.py), and the space key of the run terminal (app.py) and of the desktop window (render/window_view.py). A consumer never looks at buttons; it reads the -events posted since it last looked. +events posted since it last looked. A stick held off centre is no event: +it sets an axis, which a consumer reads every frame. Automatic triggers are not operator actions and do not come through here (render/recenter.py). @@ -19,10 +20,11 @@ from __future__ import annotations +import time from collections import deque from dataclasses import dataclass from enum import Enum -from typing import List +from typing import Callable, List class Action(str, Enum): @@ -31,8 +33,26 @@ class Action(str, Enum): #: Put the view back in front of the operator. RECENTER = "recenter" - #: Switch lazy-lock on or off (viewpoint.lazy_*). - LAZY_TOGGLE = "lazy_toggle" + #: Change how the picture follows the operator, to the next lock mode. + LOCK_MODE = "lock_mode" + #: Show both eyes the left image, or each eye its own again. + MONO_STEREO = "mono_stereo" + #: Put the view back to the config's: lock mode, size, height, gap + #: and stereo. + RESET = "reset" + + +class Axis(str, Enum): + """Every setting a stick changes for as long as it is held off centre. + The values are the names used in a config's ``bindings`` section.""" + + #: The picture's size (placement.size). + SIZE = "size" + #: Its height (placement.offset_y). + HEIGHT = "height" + #: The gap between the two eyes' planes, which sets how far away the + #: scene reads (placement.stereo_plane_distance_cm). + STEREO_GAP = "stereo_gap" #: Who posted an action. The values are render/recenter.py's source labels, @@ -96,6 +116,31 @@ def poll(self) -> List[ActionEvent]: ACTIONS = ActionStream() +#: An axis nobody has set for this long is at rest: an input path that +#: stops, with its stick still pushed, must not go on changing a setting. +AXIS_GOES_STALE_S = 0.25 + + +class AxisValues: + """Where each axis stands, from -1 to 1, with 0 at rest. An input path + sets it once per frame and the view stage reads it once per frame.""" + + def __init__(self, clock: Callable[[], float] = time.monotonic) -> None: + self._clock = clock + self._values = dict.fromkeys(Axis, (0.0, 0.0)) # value, when it was set + + def set(self, axis: Axis, value: float) -> None: + pushed = min(1.0, max(-1.0, float(value))) + self._values[Axis(axis)] = (pushed, self._clock()) + + def get(self, axis: Axis) -> float: + value, since = self._values[Axis(axis)] + return value if self._clock() - since <= AXIS_GOES_STALE_S else 0.0 + + +AXES = AxisValues() + + # -- controller inputs a binding can name -------------------------------------- #: name -> (hand, ControllerInputState field). Buttons are clicks; squeeze @@ -120,5 +165,14 @@ def poll(self) -> List[ActionEvent]: "right_thumbstick": ("right", "thumbstick_click"), } -#: A binding's value that leaves its action without a controller input. +#: name -> (hand, ControllerInputState field), for an axis. +CONTROLLER_AXES = { + "left_thumbstick_x": ("left", "thumbstick_x"), + "left_thumbstick_y": ("left", "thumbstick_y"), + "right_thumbstick_x": ("right", "thumbstick_x"), + "right_thumbstick_y": ("right", "thumbstick_y"), +} + +#: A binding's value that leaves its action or axis without a controller +#: input, and the hold's that asks for none. UNBOUND = "none" diff --git a/examples/televiz/python/isaaccapture_examples/televiz/pipeline/config.py b/examples/televiz/python/isaaccapture_examples/televiz/pipeline/config.py index 1d1faef025..0caf1c9f58 100644 --- a/examples/televiz/python/isaaccapture_examples/televiz/pipeline/config.py +++ b/examples/televiz/python/isaaccapture_examples/televiz/pipeline/config.py @@ -15,7 +15,7 @@ import yaml -from .actions import CONTROLLER_INPUTS, UNBOUND +from .actions import CONTROLLER_AXES, CONTROLLER_INPUTS, UNBOUND, Action, Axis D = TypeVar("D") @@ -176,6 +176,9 @@ def __post_init__(self) -> None: #: How the picture follows the operator (render/placement.py). LOCK_MODES = ("world", "head", "gimbal", "lazy") +#: The widest gap between the two eyes' planes, either way, in centimetres: +#: the range of camera_viz's stick. +MAX_STEREO_PLANE_DISTANCE_CM = 10.0 @dataclass(frozen=True) @@ -193,7 +196,7 @@ class PlacementConfig: # [width, height] in metres. Left out, the picture covers the camera's # field of view, at any distance. size: Optional[list] = None - # Metres to the right and up of straight ahead. + # Metres to the right and up of straight ahead, as the camera sees it. offset_x: float = 0.0 offset_y: float = 0.0 # lazy: looking this far away from the picture, or moving this far @@ -203,6 +206,9 @@ class PlacementConfig: reposition_distance: float = 0.5 reposition_delay_s: float = 0.5 transition_duration_s: float = 0.3 + # The gap between the two eyes' planes, in centimetres: a wider one + # sets the whole scene farther back. + stereo_plane_distance_cm: float = 0.0 def __post_init__(self) -> None: if self.lock_mode not in LOCK_MODES: @@ -228,6 +234,12 @@ def __post_init__(self) -> None: "placement.size takes [width, height] in metres, both above 0, " f"got {size!r}" ) + if abs(self.stereo_plane_distance_cm) > MAX_STEREO_PLANE_DISTANCE_CM: + raise ConfigError( + "placement.stereo_plane_distance_cm must be within " + f"-{MAX_STEREO_PLANE_DISTANCE_CM:g}..{MAX_STEREO_PLANE_DISTANCE_CM:g}, " + f"got {self.stereo_plane_distance_cm}" + ) for name in ( "look_away_angle_deg", "reposition_distance", @@ -257,19 +269,12 @@ def __post_init__(self) -> None: @dataclass(frozen=True) class ViewpointConfig: - # Recenter and lazy-lock both move the one transform between the - # tracker's map and the headset's world (render/viewpoint.py). + # A recenter moves the one transform between the tracker's map and the + # headset's world (render/viewpoint.py). # # Recenter onto the first tracked pose, so the view starts in front of # the operator. recenter_on_first_pose: bool = True - # Lazy-lock: re-anchor the view after the head has drifted past either - # threshold for lazy_delay_s. The lazy_toggle action switches it. - lazy_enabled: bool = False - lazy_angle_deg: float = 1.0 - lazy_translation_m: float = 0.10 # <= 0 ignores translation - lazy_delay_s: float = 0.3 - lazy_transition_s: float = 0.1 # <= 0 snaps # Recenter when the headset's own origin jumps, which is what a # recenter on the client looks like from here. auto_relatch: bool = True @@ -284,8 +289,6 @@ class ViewpointConfig: anchor_eye: str = "left" def __post_init__(self) -> None: - if self.lazy_delay_s < 0 or self.lazy_angle_deg < 0: - raise ConfigError("viewpoint.lazy_delay_s/lazy_angle_deg must be >= 0") if self.auto_recenter_threshold_m < 0: raise ConfigError("viewpoint.auto_recenter_threshold_m must be >= 0") if self.latch not in ("gravity", "6dof"): @@ -301,36 +304,46 @@ def __post_init__(self) -> None: @dataclass(frozen=True) class BindingsConfig: - # Which controller input triggers which action (pipeline/actions.py). - # Nothing is bound by default: controllers worn for teleoperation - # already give their buttons a meaning. An action fires when its button - # is pressed while `hold` is held. Inputs are named by role: left_ or - # right_ plus squeeze, trigger, primary, secondary, thumbstick; and - # left_menu. The space key is fixed. configs/synthetic.yaml binds - # recenter, as an example. - hold: str = "left_squeeze" + # Which controller input does what (pipeline/actions.py). Nothing is + # bound by default: controllers worn for teleoperation already give + # their buttons a meaning. The shipped configs bind the layout of the + # camera_viz example, and `none` takes a binding away. + # + # An action fires on the press of its button: left_ or right_ plus + # squeeze, trigger, primary, secondary, thumbstick; and left_menu. An + # axis follows a stick: left_ or right_ plus thumbstick_x or + # thumbstick_y. With a `hold`, both do so only while that input is + # held. The space key is fixed. + hold: str = UNBOUND recenter: str = UNBOUND - lazy_toggle: str = UNBOUND + lock_mode: str = UNBOUND + mono_stereo: str = UNBOUND + reset: str = UNBOUND + size: str = UNBOUND + height: str = UNBOUND + stereo_gap: str = UNBOUND def __post_init__(self) -> None: - actions = [f.name for f in fields(self) if f.name != "hold"] - for name in ("hold", *actions): + sticks = [axis.value for axis in Axis] + bindings = [action.value for action in Action] + sticks + for name in ("hold", *bindings): value = getattr(self, name) - if value == UNBOUND and name != "hold": + if value == UNBOUND: continue if value is None or value is False: # YAML reads `null`, `~`, `off` and `no` as these. raise ConfigError( - f"bindings.{name}: write the word {UNBOUND} to leave an action " - "without a controller input (the hold input cannot be left out)" + f"bindings.{name}: write the word {UNBOUND} to leave it " + "without a controller input" ) - if not isinstance(value, str) or value not in CONTROLLER_INPUTS: + inputs = CONTROLLER_AXES if name in sticks else CONTROLLER_INPUTS + if not isinstance(value, str) or value not in inputs: raise ConfigError( - f"bindings.{name}: {value!r} is not a controller input; use one " - f"of {sorted(CONTROLLER_INPUTS)}" - + ("" if name == "hold" else f", or {UNBOUND}") + f"bindings.{name}: {value!r} is not a controller " + f"{'stick axis' if name in sticks else 'input'}; use one of " + f"{sorted(inputs)}, or {UNBOUND}" ) - bound = {n: getattr(self, n) for n in actions if getattr(self, n) != UNBOUND} + bound = {n: getattr(self, n) for n in bindings if getattr(self, n) != UNBOUND} for name, value in bound.items(): if value == self.hold: raise ConfigError( @@ -341,7 +354,34 @@ def __post_init__(self) -> None: if len(twins) > 1: raise ConfigError( f"bindings: {' and '.join(twins)} are both on {value}; " - "one button, one action" + "one input, one binding" + ) + + +@dataclass(frozen=True) +class ControlsConfig: + # How the bound sticks change the view, in the keys of camera_viz's + # `display.controls`. + hud: bool = True # show in the headset what a press changed + deadzone: float = 0.2 # a stick this near its centre is at rest + # What a stick held all the way changes in a second. + size_rate_m_per_s: float = 0.5 + offset_rate_m_per_s: float = 0.5 + plane_distance_rate_cm_per_s: float = 2.0 + + def __post_init__(self) -> None: + if not 0.0 <= self.deadzone < 1.0: + raise ConfigError( + f"controls.deadzone must be 0 or above and below 1, got {self.deadzone}" + ) + for name in ( + "size_rate_m_per_s", + "offset_rate_m_per_s", + "plane_distance_rate_cm_per_s", + ): + if getattr(self, name) <= 0.0: + raise ConfigError( + f"controls.{name} must be above 0, got {getattr(self, name)}" ) @@ -372,6 +412,7 @@ def __post_init__(self) -> None: "render": RenderConfig, "viewpoint": ViewpointConfig, "bindings": BindingsConfig, + "controls": ControlsConfig, "pipeline": PipelineRunConfig, } @@ -389,6 +430,7 @@ class AppConfig: render: RenderConfig = field(default_factory=RenderConfig) viewpoint: ViewpointConfig = field(default_factory=ViewpointConfig) bindings: BindingsConfig = field(default_factory=BindingsConfig) + controls: ControlsConfig = field(default_factory=ControlsConfig) pipeline: PipelineRunConfig = field(default_factory=PipelineRunConfig) @staticmethod diff --git a/examples/televiz/python/isaaccapture_examples/televiz/render/controller_actions.py b/examples/televiz/python/isaaccapture_examples/televiz/render/controller_actions.py index 51ffd016f5..6065bb1cd3 100644 --- a/examples/televiz/python/isaaccapture_examples/televiz/render/controller_actions.py +++ b/examples/televiz/python/isaaccapture_examples/televiz/render/controller_actions.py @@ -1,16 +1,19 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""XR controller input: turns button presses into operator actions. +"""XR controller input: turns button presses into operator actions, and +sticks held off centre into axes. A deviceio ControllerTracker shares the display's OpenXR session, so no second session is opened. ``update()`` runs once per XR frame on the view stage's frame loop; the Viewpoint calls it. -Which input triggers which action is the config's ``bindings`` section. -Left out, nothing is bound and this module posts nothing. An action fires -on the press of its button, the frame it goes from up to down, while the -hold input is held, so a stray press does nothing. What leaves this module -is an action event on the action stream (pipeline/actions.py). +Which input does what is the config's ``bindings`` section. Left out, +nothing is bound and this module posts nothing. An action fires on the +press of its button, the frame it goes from up to down, and an axis +follows its stick outside the deadzone. Where the config names a hold +input, both do so only while it is held, so a stray press does nothing. +What leaves this module is an action event on the action stream and the +axes' values (pipeline/actions.py). Without deviceio, without controllers, or on a runtime that lacks the extensions, no action is posted and the app runs as it does without @@ -21,14 +24,19 @@ from __future__ import annotations import logging +import math from ..pipeline.actions import ( ACTIONS, + AXES, + CONTROLLER_AXES, CONTROLLER_INPUTS, SOURCE_CONTROLLER, UNBOUND, Action, ActionStream, + Axis, + AxisValues, ) from ..pipeline.config import BindingsConfig @@ -57,12 +65,17 @@ def required_extensions_for_controllers(): class ControllerActions: - """Posts an action event for every bound button pressed while the hold - input is held. Construction raises on failure, and the app then runs - without controller input.""" + """Posts an action event for every bound button pressed, and sets + every bound axis, while the hold input is held. Construction raises on + failure, and the app then runs without controller input.""" def __init__( - self, viz_session, bindings: BindingsConfig, stream: ActionStream = ACTIONS + self, + viz_session, + bindings: BindingsConfig, + stream: ActionStream = ACTIONS, + axes: AxisValues = AXES, + deadzone: float = 0.2, ) -> None: import isaaccapture.deviceio as deviceio @@ -77,18 +90,24 @@ def __init__( for action in Action if getattr(bindings, action.value) != UNBOUND } + #: axis -> the stick axis it is bound to. + self._sticks = { + axis: getattr(bindings, axis.value) + for axis in Axis + if getattr(bindings, axis.value) != UNBOUND + } + self._axes = axes + self._deadzone = float(deadzone) self._down = dict.fromkeys(self._buttons, False) self._analog_down: dict = {} # analog input name -> down (the hysteresis memory) self._warned = False self._seen_controller = False - if self._buttons: + bound = {**self._buttons, **self._sticks} + if bound: log.info( - "controller input: shared-session tracker attached (hold %s, then %s)", - self._hold, - ", ".join( - f"{button} = {action.value}" - for action, button in self._buttons.items() - ), + "controller input: shared-session tracker attached (%s%s)", + "" if self._hold == UNBOUND else f"hold {self._hold}, then ", + ", ".join(f"{name} = {what.value}" for what, name in bound.items()), ) else: log.info( @@ -109,18 +128,26 @@ def update(self) -> None: self._tracker.get_right_controller(self._session) ), } - hold = self._held(inputs, self._hold) + hold = self._hold == UNBOUND or self._held(inputs, self._hold) down = { action: self._held(inputs, button) for action, button in self._buttons.items() } + pushed = { + axis: self._pushed(inputs, stick) if hold else 0.0 + for axis, stick in self._sticks.items() + } except Exception: # noqa: BLE001 if not self._warned: self._warned = True log.exception("controller input: update failed (disabled until fixed)") # Nothing was read, so nothing changed: a button still down - # when updates resume is not a new press. + # when updates resume is not a new press. A stick is at rest. + for axis in self._sticks: + self._axes.set(axis, 0.0) return + for axis, value in pushed.items(): + self._axes.set(axis, value) # Enough to trace a "buttons do nothing" report from the log: the # first controller sighting and every fired action at INFO, every # button edge at DEBUG. @@ -135,13 +162,14 @@ def update(self) -> None: if is_down == self._down[action]: continue self._down[action] = is_down - fires = is_down and hold # a press, while the hold input is held + fires = is_down and hold # a press, while any hold input is held + held = "" if self._hold == UNBOUND else f" while holding {self._hold}" log.log( logging.INFO if fires else logging.DEBUG, "controller input: %s %s%s", self._buttons[action], "pressed" if is_down else "released", - f" while holding {self._hold} = {action.value}" if fires else "", + f"{held} = {action.value}" if fires else "", ) if fires: self._stream.post(action, SOURCE_CONTROLLER) @@ -164,6 +192,20 @@ def _held(self, inputs_by_hand: dict, name: str) -> bool: self._analog_down[name] = down return down + def _pushed(self, inputs_by_hand: dict, name: str) -> float: + """How far the stick axis ``name`` is pushed, from -1 to 1: 0 inside + the deadzone, and from 0 at its edge. 0 while its controller is + inactive.""" + hand, field = CONTROLLER_AXES[name] + inputs = inputs_by_hand[hand] + if inputs is None: + return 0.0 + value = float(getattr(inputs, field)) + if abs(value) < self._deadzone: + return 0.0 + span = 1.0 - self._deadzone + return math.copysign(min(1.0, (abs(value) - self._deadzone) / span), value) + @staticmethod def _inputs(snapshot): """A controller's input state, or None while it is inactive. diff --git a/examples/televiz/python/isaaccapture_examples/televiz/render/placement.py b/examples/televiz/python/isaaccapture_examples/televiz/render/placement.py index cefd682a20..13c655801b 100644 --- a/examples/televiz/python/isaaccapture_examples/televiz/render/placement.py +++ b/examples/televiz/python/isaaccapture_examples/televiz/render/placement.py @@ -17,6 +17,10 @@ - ``head``: it stays in front of the eyes. The camera's turn cancels out, so nothing is stabilized. +The lazy rule is a placement's because it moves a plane. A rule that +re-seats every kind of view would belong in the Viewpoint +(render/viewpoint.py). + Pure NumPy over camera_viz's strategies: no session and no layer. """ diff --git a/examples/televiz/python/isaaccapture_examples/televiz/render/quad_stage.py b/examples/televiz/python/isaaccapture_examples/televiz/render/quad_stage.py index 1bce79030a..f44f0e073f 100644 --- a/examples/televiz/python/isaaccapture_examples/televiz/render/quad_stage.py +++ b/examples/televiz/python/isaaccapture_examples/televiz/render/quad_stage.py @@ -19,15 +19,16 @@ import logging import threading import time -from collections import OrderedDict, deque +from collections import OrderedDict, deque, namedtuple from typing import Optional import numpy as np -from ..pipeline.config import PlacementConfig +from ..pipeline.config import ControlsConfig, PlacementConfig from ..pipeline.mailbox import Mailbox from ..pipeline.stage import Stage from .placement import CameraPlacement, placement_config +from .view_controls import ViewControls # _C is imported, not re-declared: the optical-to-XR swap folded into the # plane's pose must be the one compose() folds in. @@ -55,6 +56,11 @@ JOIN_WAIT_S = 0.004 +#: The head as camera_viz's panel takes it: a position and an orientation +#: (w, x, y, z) in the XR world. +_HeadPose = namedtuple("_HeadPose", "position orientation") + + def _texture_model(frame): """Intrinsics of the image being shown: the colour camera's own when the frame carries them, else the left camera's.""" @@ -72,6 +78,7 @@ def __init__( viewpoint: Viewpoint, *, placement: Optional[PlacementConfig] = None, # the config's section + controls: Optional[ControlsConfig] = None, # the config's section stereo: bool = False, # texture the right eye from the right camera composition: str = "openxr", # openxr: the runtime composites the quad anchor_eye: str = "left", # must match viewpoint.anchor_eye @@ -86,6 +93,10 @@ def __init__( self._placed_model = None # the camera the placement is sized for self._seated_epoch = None # the view's re-seat the picture is seated for self._stereo = bool(stereo) + # The operator's live changes to the view (render/view_controls.py). + self._controls = ViewControls(self._settings, controls, stereo=self._stereo) + self._head_pose = None # the last frame's, for the panel in the headset + self._ipd_mm: Optional[float] = None self._composition = composition self._anchor_eye = anchor_eye self._xr = session.is_xr_mode() @@ -146,6 +157,13 @@ def step(self) -> bool: peek = self._joined.latest() if peek is not None: self._ensure_layer(_texture_model(peek[0][0])) + # Before the frame, so that a change shows in it. + self._controls.step( + self._camera_placement, + self._layer, + ipd_mm=self._ipd_mm, + head_pose=self._head_now(), + ) info = self._session.begin_frame() # blocks on the runtime's pacing self._grant_times.append(time.monotonic()) self.mark_work_start() # the pacing block is not this stage's work @@ -165,6 +183,7 @@ def _frame(self, info) -> bool: if not info.should_render: return False self._take_join() + self._note_head(list(info.views)) views = self._resolve_views(list(info.views)) if self._pending is None: return False # nothing joined yet @@ -279,6 +298,28 @@ def _pull(self) -> None: # -- pose ---------------------------------------------------------------- + def _head_now(self): + """Where the head is, for the panel in the headset: the session's + newest pose, or else the last frame's.""" + now = getattr(self._session, "head_pose_now", None) + head = now() if now is not None else None + return self._head_pose if head is None else head + + def _note_head(self, views) -> None: + """Keep where the head is and how far apart its eyes are, for the + controls' next step.""" + if not views: + return + eyes = [np.asarray(v.pose.position, dtype=np.float64) for v in views] + self._head_pose = _HeadPose( + tuple(float(c) for c in np.mean(eyes, axis=0)), + tuple(float(q) for q in views[0].pose.orientation), + ) + if len(eyes) == 2: + apart_mm = 1000.0 * float(np.linalg.norm(eyes[0] - eyes[1])) + if apart_mm > 1.0: # an untracked head has both eyes in one place + self._ipd_mm = apart_mm + def _resolve_views(self, views): """Compose the runtime's views through the Viewpoint.""" eye_mats = [pose_to_matrix(v.pose) for v in views] @@ -348,7 +389,8 @@ def _plane(self, views, model, T_map_from_cam): def _seated(self, model) -> CameraPlacement: """The picture's placement, sized for ``model`` and seated anew after every re-seat of the view: a recenter turns the camera's - frame under a picture that keeps its seat.""" + frame under a picture that keeps its seat. Another camera model + starts from the config's size again.""" if self._camera_placement is None or model != self._placed_model: config = placement_config(self._settings, model) if self._camera_placement is None: @@ -358,6 +400,7 @@ def _seated(self, model) -> CameraPlacement: else: self._camera_placement.retune(config) self._placed_model = model + self._controls.placed_for(config) epoch = self._viewpoint.anchor_epoch if epoch != self._seated_epoch: self._seated_epoch = epoch @@ -397,14 +440,17 @@ def _ensure_layer(self, model) -> None: # Mipmaps only where they are sampled: the runtime samples a native # quad itself. cfg.generate_mipmaps = not cfg.openxr_composition - # One shared plane with a texture per eye. The stereo baseline - # stays 0: the disparity is in the image pair, and offsetting the - # planes would add to it. + # One shared plane with a texture per eye. The disparity is in the + # image pair; the gap between the eyes' planes, 0 unless the config + # or the operator sets one, moves the whole scene back. cfg.stereo = self._stereo # No placement yet: _frame sets it before the first submit, from a # pose that does not exist at construction. self._layer = self._session.add_quad_layer(cfg) self._layer_size = size + if self._xr and self._controls.wants_hud: + # After the picture's layer, which it is then drawn over. + self._controls.attach_hud(self._session) log.info( "render:quad: %dx%d %s plane at %.2f m, %s-locked (%s composition)", size[0], @@ -423,7 +469,7 @@ def _submit(self, frame) -> None: if not self._stereo: self._layer.submit(frame.color, stream=stream) return - right = frame.color_right + right = frame.color if self._controls.mono else frame.color_right if right is None: # A stereo layer needs both buffers, so fall back to the left # image instead of losing the frame. diff --git a/examples/televiz/python/isaaccapture_examples/televiz/render/view_controls.py b/examples/televiz/python/isaaccapture_examples/televiz/render/view_controls.py new file mode 100644 index 0000000000..5d35a358c8 --- /dev/null +++ b/examples/televiz/python/isaaccapture_examples/televiz/render/view_controls.py @@ -0,0 +1,271 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""The operator's live changes to the view, as the camera_viz example has +them: the lock mode, mono or stereo, the picture's size and height, the gap +between the two eyes' planes, and back to the config's values. + +They arrive as actions and axes (pipeline/actions.py), whoever posts them, +and nothing is written back to the config. What a change does to a size, a +height or a gap is camera_viz's own code, and so is the panel that shows +it in the headset. + +Used on the frame loop's thread only. +""" + +from __future__ import annotations + +import dataclasses +import logging +import time +from typing import Callable, Optional + +from ..pipeline.actions import ACTIONS, AXES, Action, ActionStream, Axis, AxisValues +from ..pipeline.config import LOCK_MODES, ControlsConfig, PlacementConfig +from .placement import CameraPlacement + +log = logging.getLogger("isaaccapture.televiz.render.view_controls") + +#: How often a stick held off centre is logged, in seconds. +_LOG_EVERY_S = 0.25 +#: The longest time one step of a held stick counts for: a frame loop that +#: stood still must not turn into one large change. +_LONGEST_STEP_S = 0.1 + + +def camera_viz_controls(): + """camera_viz's controls, or None where they cannot be loaded: its + panel draws with Pillow, which comes with isaaccapture's cloudxr extra.""" + try: + from isaaccapture_examples.camera_viz import controls + except ImportError as exc: + log.warning("the controls of the camera_viz example cannot be loaded: %s", exc) + return None + return controls + + +class _Target: + """What camera_viz's stick control changes: the placement's tuning.""" + + name = "picture" + + def __init__(self, placement: CameraPlacement) -> None: + self._placement = placement + + @property + def placement_config(self): + return self._placement.config + + @placement_config.setter + def placement_config(self, config) -> None: + self._placement.retune(config) + + +class ViewControls: + """Applies the actions and axes to one picture's placement and layer.""" + + def __init__( + self, + settings: PlacementConfig, + controls: Optional[ControlsConfig] = None, + *, + stereo: bool = False, # the picture has an image for each eye + actions: Optional[ActionStream] = None, # None: the process-wide stream + axes: AxisValues = AXES, + clock: Callable[[], float] = time.monotonic, + ) -> None: + self._settings = settings + self._config = controls or ControlsConfig() + self._stereo = bool(stereo) + self._events = (ACTIONS if actions is None else actions).reader() + self._axes = axes + self._clock = clock + self._then: Optional[float] = None + self._camera_viz = camera_viz_controls() + self._tuning = None # camera_viz's ControlsConfig: rates and limits + if self._camera_viz is not None: + self._tuning = self._camera_viz.ControlsConfig( + deadzone=self._config.deadzone, + size_rate_m_per_s=self._config.size_rate_m_per_s, + offset_rate_m_per_s=self._config.offset_rate_m_per_s, + plane_distance_rate_cm_per_s=self._config.plane_distance_rate_cm_per_s, + ) + self._first_tuning = None # the placement's, as the config gave it + self._mono = False + self._gap_cm = float(settings.stereo_plane_distance_cm) + self._gap_layer = None # the layer the gap was handed to + self._gap_applied: Optional[float] = None # what that layer has, in cm + self._ipd_mm: Optional[float] = None + self._hud = None + self._logged: dict = {} + #: The last change, in words. + self.last_event = "" + + @property + def mono(self) -> bool: + """Both eyes are to be shown the left image.""" + return self._mono + + @property + def wants_hud(self) -> bool: + return self._config.hud and self._camera_viz is not None + + def attach_hud(self, session) -> None: + """Make the panel that shows a change in the headset, in place of + any earlier one. It adds a layer, so not inside a frame, and after + the picture's layer, which a layer added later is drawn over.""" + old = getattr(self._hud, "_layer", None) + self._hud = None + try: + if old is not None: + session.remove_layer(old) + self._hud = self._camera_viz.make_hud(session, True) + except Exception as exc: # noqa: BLE001 - the view runs without it + log.warning("no readout in the headset: %s", exc) + + def placed_for(self, tuning) -> None: + """The placement was sized anew, for a camera model: ``tuning`` is + what a reset now goes back to, and the sticks' limits make room for + it.""" + self._first_tuning = tuning + if self._tuning is None: + return + low, high = self._camera_viz.ControlsConfig().size_range_m + width = tuning.size_meters[0] + low_y, high_y = self._camera_viz.ControlsConfig().offset_y_range_m + self._tuning = dataclasses.replace( + self._tuning, + size_range_m=(min(low, width), max(high, width)), + offset_y_range_m=( + min(low_y, tuning.offset_y), + max(high_y, tuning.offset_y), + ), + ) + + def step( + self, + placement: Optional[CameraPlacement], + layer, + *, + ipd_mm: Optional[float] = None, + head_pose=None, + ) -> None: + """Once per frame, before it: apply what was pressed and where the + sticks stand. ``placement`` and ``layer`` are None until the first + image has been placed.""" + now = self._clock() + dt = 0.0 if self._then is None else max(0.0, now - self._then) + self._then = now + held = min(dt, _LONGEST_STEP_S) + if ipd_mm is not None: + self._ipd_mm = ipd_mm + events = self._events.poll() + if placement is None: + return # presses made before there is a picture are dropped + if self._first_tuning is None: + self._first_tuning = placement.config + for event in events: + if event.action is Action.LOCK_MODE: + self._next_lock_mode(placement) + elif event.action is Action.MONO_STEREO: + self._toggle_mono() + elif event.action is Action.RESET: + self._reset(placement) + self._resize(placement, held) + self._widen(held) + self._apply_gap(layer) + if self._hud is not None: + self._hud.step(dt, head_pose) + + # -- the actions --------------------------------------------------------- + + def _next_lock_mode(self, placement: CameraPlacement) -> None: + index = LOCK_MODES.index(placement.lock_mode) + placement.set_lock_mode(LOCK_MODES[(index + 1) % len(LOCK_MODES)]) + self._say(f"lock mode: {placement.lock_mode}") + + def _toggle_mono(self) -> None: + if not self._stereo: + self._say("mono/stereo: the picture has one image") + return + self._mono = not self._mono + self._say("eyes: mono" if self._mono else "eyes: stereo") + + def _reset(self, placement: CameraPlacement) -> None: + self._mono = False + self._gap_cm = float(self._settings.stereo_plane_distance_cm) + placement.retune(self._first_tuning) + if placement.lock_mode != self._settings.lock_mode: + placement.set_lock_mode(self._settings.lock_mode) + self._say("reset to the config's values") + + # -- the axes ------------------------------------------------------------ + + def _resize(self, placement: CameraPlacement, dt: float) -> None: + across, up = self._axes.get(Axis.SIZE), self._axes.get(Axis.HEIGHT) + if self._tuning is None or (across == 0.0 and up == 0.0): + return + changed = self._camera_viz.shapes.for_shape("quad").adjust( + _Target(placement), self._tuning, None, across, up, dt + ) + if changed: + self._say(" ".join(changed), held="resize") + + def _widen(self, dt: float) -> None: + pushed = self._axes.get(Axis.STEREO_GAP) + if self._tuning is None or pushed == 0.0 or not self._stereo or self._mono: + return + stereo = self._camera_viz.stereo + limits = ( + self._tuning.plane_distance_min_cm, + self._tuning.plane_distance_max_cm, + ) + gap = self._gap_cm + pushed * self._tuning.plane_distance_rate_cm_per_s * dt + gap = stereo.clamp_gap_cm(gap, self._ipd_mm or stereo.DEFAULT_IPD_MM, limits) + stepped = stereo.step(gap) != stereo.step(self._gap_cm) + self._gap_cm = gap + if stepped: + self._say(f"stereo planes: {stereo.step(gap):.1f} cm", held="gap") + + def _apply_gap(self, layer) -> None: + """Hand a stereo layer the gap it is to show: none while mono, and + never more than the eyes can take. A layer of one image has no + second plane to move.""" + if not self._stereo or layer is None: + return + if layer is not self._gap_layer: # a new layer starts without a gap + self._gap_layer, self._gap_applied = layer, None + gap = 0.0 if self._mono else self._gap_cm + if self._tuning is not None: + stereo = self._camera_viz.stereo + limits = ( + self._tuning.plane_distance_min_cm, + self._tuning.plane_distance_max_cm, + ) + ipd_mm = self._ipd_mm or stereo.DEFAULT_IPD_MM + gap = stereo.step(stereo.clamp_gap_cm(gap, ipd_mm, limits)) + if gap == self._gap_applied: + return + setter = getattr(layer, "set_stereo_baseline_mm", None) + if setter is None: + if gap != 0.0 and self._gap_applied is None: + log.warning( + "this isaaccapture has no Layer.set_stereo_baseline_mm: the " + "gap between the eyes' planes stays 0" + ) + else: + setter(gap * 10.0) + self._gap_applied = gap + + # -- saying what changed ------------------------------------------------- + + def _say(self, message: str, held: Optional[str] = None) -> None: + """To the log and to the panel in the headset. ``held`` names a + stick whose changes are logged at intervals; the panel shows each.""" + self.last_event = message + now = self._clock() + if held is None or now - self._logged.get(held, -1e9) >= _LOG_EVERY_S: + if held is not None: + self._logged[held] = now + log.info("view: %s", message) + if self._hud is not None: + self._hud.show(self._camera_viz.split_message(message)) diff --git a/examples/televiz/python/isaaccapture_examples/televiz/render/viewpoint.py b/examples/televiz/python/isaaccapture_examples/televiz/render/viewpoint.py index 225f68226f..500cdeed87 100644 --- a/examples/televiz/python/isaaccapture_examples/televiz/render/viewpoint.py +++ b/examples/televiz/python/isaaccapture_examples/televiz/render/viewpoint.py @@ -4,15 +4,14 @@ Owns ``T_view_from_map``, the single transform between the map frame (x-left, y-down, z-back) and the XR view frame (x-right, y-up, z-back), and -every policy that changes it: recenter and lazy-lock. +the policy that changes it: recenter. The XR world and the map are taken to start at the same place. The initial transform is the axis bridge captured at the first XR frame, so the first XR view is the first camera view. A recenter re-seats it per ``viewpoint.latch``: ``gravity`` uses the operator's heading and position only, so nothing can tilt the map's vertical; ``6dof`` matches the full -head and camera rotations. Lazy-lock watches heading and position in both -modes, and re-seats the view as the latch does. +head and camera rotations. Pure NumPy with an injectable clock and action stream, so it is testable without a display session or a headset. @@ -165,57 +164,11 @@ def _yaw_angle(T: np.ndarray) -> float: return math.atan2(T[0, 2], T[0, 0]) -def _yaw_delta(a: np.ndarray, b: np.ndarray) -> float: - """|heading(a) - heading(b)| wrapped to [0, pi].""" - d = abs(_yaw_angle(a) - _yaw_angle(b)) % (2.0 * math.pi) - return min(d, 2.0 * math.pi - d) - - -def _translation_delta(a: np.ndarray, b: np.ndarray) -> float: - return float(np.linalg.norm(a[:3, 3] - b[:3, 3])) - - -def _rotation_fraction(R: np.ndarray, t: float) -> np.ndarray: - """The part ``t`` of rotation ``R``, about R's own axis.""" - angle = math.acos(min(1.0, max(-1.0, (float(np.trace(R)) - 1.0) / 2.0))) - if angle < 1e-12: - return np.eye(3) - turn = np.array([R[2, 1] - R[1, 2], R[0, 2] - R[2, 0], R[1, 0] - R[0, 1]]) - if angle > math.pi - 1e-6: - # Near half a turn the antisymmetric part vanishes. The axis is - # then the symmetric part's eigenvector of eigenvalue 1, on the - # side the turn goes. - values, vectors = np.linalg.eigh((R + R.T) / 2.0) - axis = vectors[:, int(np.argmax(values))] - if axis @ turn < 0.0: - axis = -axis - else: - axis = turn / (2.0 * math.sin(angle)) - x, y, z = axis - K = np.array([[0.0, -z, y], [z, 0.0, -x], [-y, x, 0.0]]) - part = t * angle - return np.eye(3) + math.sin(part) * K + (1.0 - math.cos(part)) * (K @ K) - - -def _interpolate_pose(a: np.ndarray, b: np.ndarray, t: float) -> np.ndarray: - """Shortest-path rotation and linear translation blend of two poses.""" - out = np.eye(4) - out[:3, :3] = a[:3, :3] @ _rotation_fraction(a[:3, :3].T @ b[:3, :3], t) - out[:3, 3] = (1.0 - t) * a[:3, 3] + t * b[:3, 3] - return out - - -def _smoothstep01(x: float) -> float: - x = min(max(x, 0.0), 1.0) - return x * x * (3.0 - 2.0 * x) - - class _RecenterTarget: """Where a recenter taken now would seat the view: the heading-only head pose (XR frame) and the heading-only camera pose (map frame). - Kept as the pair so the lazy-lock compares each component. With - ``latch: 6dof`` the full poses ride along and ``anchor()`` uses them, + With ``latch: 6dof`` the full poses ride along and ``anchor()`` uses them, so the latched head sits exactly at the camera for any attitude. """ @@ -241,7 +194,7 @@ def anchor(self) -> np.ndarray: class Viewpoint: - """Owns T_view_from_map and the recenter and lazy-lock policies. + """Owns T_view_from_map and the recenter policy. Single-threaded: every method runs on the view stage's frame loop. """ @@ -270,8 +223,7 @@ def __init__( # bridge at the first XR frame. self._T_map_from_view = FLIP.copy() self._anchored = False - #: Counts every discrete re-seat of the view: the bridge, a - #: recenter, a completed lazy re-anchor. + #: Counts every re-seat of the view: the bridge and each recenter. self.anchor_epoch = 0 # The newest camera sample (optical T_map_from_cam). @@ -300,27 +252,12 @@ def __init__( # left also waits for the baseline that seats it. self._first_pose_recenter_pending = bool(self._config.recenter_on_first_pose) - # Lazy-lock state. - self._lazy_enabled = bool(self._config.lazy_enabled) - self._lazy_reference: Optional[_RecenterTarget] = None - self._lazy_reset_pending = self._lazy_enabled - self._lazy_armed_since: Optional[float] = None - self._transitioning = False - self._transition_start_time = 0.0 - self._transition_to: Optional[_RecenterTarget] = None - # The view's own seat when the transition started. - self._transition_from_anchor: Optional[np.ndarray] = None - # -- public state -------------------------------------------------------- @property def T_view_from_map(self) -> np.ndarray: return np.linalg.inv(self._T_map_from_view) - @property - def lazy_enabled(self) -> bool: - return self._lazy_enabled - def _gravity_latch(self) -> bool: return self._config.latch == "gravity" @@ -333,18 +270,6 @@ def set_baseline_m(self, baseline_m: float) -> None: self._baseline_m = float(baseline_m) self._baseline_known = True - def set_lazy(self, enabled: bool) -> None: - """Switching on re-baselines to the current pose, so it never jumps. - Switching off mid-transition freezes the view where it is.""" - if enabled == self._lazy_enabled: - return - self._lazy_enabled = enabled - self._lazy_reference = None - self._lazy_reset_pending = enabled - self._lazy_armed_since = None - self._transitioning = False - log.info("viewpoint: lazy-lock %s", "enabled" if enabled else "disabled") - # -- per-frame ----------------------------------------------------------- def update( @@ -354,9 +279,9 @@ def update( pose_flags=None, # that sample's PoseFlags, when passed explicitly ) -> None: """Run once per XR frame, before compose(): captures the frame - bridge, handles the operator's actions, applies a recenter and - steps the lazy-lock. Without ``T_map_from_cam`` the camera sample - is read from the pose mailbox.""" + bridge, handles the operator's actions and applies a recenter. + Without ``T_map_from_cam`` the camera sample is read from the pose + mailbox.""" # The pose of the image on display, when the caller hands one in. of_the_image = T_map_from_cam is not None if T_map_from_cam is None and self._pose_in is not None: @@ -397,8 +322,8 @@ def update( self._recenter_requested = True # A head rolled onto its side has no heading (pipeline/heading.py). - # It is treated like an untracked head in both latch modes, because - # the lazy-lock needs a heading even when the 6dof anchor does not. + # It is treated like an untracked head in both latch modes: the + # headset-jump rule reads the heading even where the anchor does not. eyes_valid = self._eyes_valid(eye_poses) self._no_heading = eyes_valid and not math.isfinite(heading_rad(eye_poses[0])) eyes_valid = eyes_valid and not self._no_heading @@ -426,14 +351,13 @@ def update( self._prev_head_time = None # never compare across an untracked gap self._drift_over_frames = 0 - target = self._compute_target(eye_poses) if eyes_valid else None - if COORDINATOR.generation != self._seen_gen: self._seen_gen = COORDINATOR.generation self._recenter_requested = True if self._recenter_requested: self._recenter_requested = False + target = self._compute_target(eye_poses) if eyes_valid else None if target is not None: self._apply_target(target) if first_pose_ready: @@ -459,14 +383,6 @@ def update( self._warned_not_ready = why log.warning("viewpoint: recenter requested %s, ignored", why) - if self._lazy_enabled and target is not None: - self._update_lazy(target) - else: - # The lazy delay runs only while there is a target to compare. - self._lazy_armed_since = None - if self._transitioning: - self._step_transition(self._clock()) - def compose(self, T_view_from_eye: np.ndarray) -> np.ndarray: """XR eye pose -> its optical pose in the map.""" return self._T_map_from_view @ T_view_from_eye @ _C @@ -499,8 +415,6 @@ def _process_actions(self) -> None: source = RecenterSource.EXTERNAL COORDINATOR.note(source) self._recenter_requested = True - elif event.action is Action.LAZY_TOGGLE: - self.set_lazy(not self._lazy_enabled) # The head pose a runtime reports before a headset connects. The viz # session exposes no tracking flags, so an untracked head is recognized @@ -622,74 +536,5 @@ def _apply_target(self, target: _RecenterTarget) -> None: # The drift rule measures from the head position at this latch. self._latched_head_pos = target.head_yaw[:3, 3].copy() self._drift_over_frames = 0 - self._lazy_reference = target - self._lazy_reset_pending = False - self._lazy_armed_since = None - self._transitioning = False # A later dropped request must be warned about again. self._warned_not_ready = None - - # -- lazy-lock ----------------------------------------------------------- - - def _update_lazy(self, target: _RecenterTarget) -> None: - now = self._clock() - if self._lazy_reset_pending or self._lazy_reference is None: - self._lazy_reference = target - self._lazy_reset_pending = False - self._lazy_armed_since = None - return - if self._transitioning: - self._step_transition(now) - return - - ref = self._lazy_reference - angle_delta = max( - _yaw_delta(ref.head_yaw, target.head_yaw), - _yaw_delta(ref.cam_yaw, target.cam_yaw), - ) - translation_delta = max( - _translation_delta(ref.head_yaw, target.head_yaw), - _translation_delta(ref.cam_yaw, target.cam_yaw), - ) - angle_hit = angle_delta > math.radians(max(0.0, self._config.lazy_angle_deg)) - trans_thresh = self._config.lazy_translation_m - trans_hit = trans_thresh > 0.0 and translation_delta > trans_thresh - - if angle_hit or trans_hit: - if self._lazy_armed_since is None: - self._lazy_armed_since = now - elif now - self._lazy_armed_since >= self._config.lazy_delay_s: - self._start_transition(target, now) - else: - self._lazy_armed_since = None - - def _start_transition(self, target: _RecenterTarget, now: float) -> None: - if not (self._config.lazy_transition_s > 0.0): - self._apply_target(target) - return - # Blend from the seat on display, so the first step moves nothing. - self._transition_from_anchor = self._T_map_from_view.copy() - self._transition_to = target - self._transition_start_time = now - self._transitioning = True - self._lazy_armed_since = None - self._step_transition(now) - log.info("viewpoint: lazy re-anchor transition started") - - def _step_transition(self, now: float) -> None: - duration = self._config.lazy_transition_s - linear = ( - (now - self._transition_start_time) / duration if duration > 0.0 else 1.0 - ) - b = self._transition_to - if linear < 1.0: - # One turn from where the view sits to the target's seat. Two - # gravity seats differ by a turn about the map's vertical, so - # that latch stays upright; the 6dof latch keeps its tilt. - self._T_map_from_view = _interpolate_pose( - self._transition_from_anchor, b.anchor(), _smoothstep01(linear) - ) - else: - # A completed re-anchor is one re-seat like a recenter's, so - # the drift rule measures from it too. - self._apply_target(b) diff --git a/examples/televiz/python/isaaccapture_examples/televiz/render/window_view.py b/examples/televiz/python/isaaccapture_examples/televiz/render/window_view.py index 97f5095127..f357219a71 100644 --- a/examples/televiz/python/isaaccapture_examples/televiz/render/window_view.py +++ b/examples/televiz/python/isaaccapture_examples/televiz/render/window_view.py @@ -38,8 +38,8 @@ #: and the Viewpoint ignores it. It is higher above the floor than a person, #: so that a picture below the head has room before it reaches the floor. HEAD_POSITION = (0.0, 3.5, 0.0) -#: Its two eyes are this far apart: the Viewpoint anchors, recenters and -#: lazy-locks on a stereo head only. +#: Its two eyes are this far apart: the Viewpoint anchors and recenters on +#: a stereo head only. EYE_SEPARATION_M = 0.064 HEAD_MARKER_RADIUS_M = 0.09 diff --git a/tests/python/examples/televiz/test_actions.py b/tests/python/examples/televiz/test_actions.py index a71115999d..e8cec4bb8c 100644 --- a/tests/python/examples/televiz/test_actions.py +++ b/tests/python/examples/televiz/test_actions.py @@ -28,6 +28,7 @@ Action, ActionEvent, ActionStream, + Axis, ) from isaaccapture_examples.televiz.pipeline.config import ( AppConfig, @@ -47,11 +48,11 @@ def test_a_reader_gets_each_event_once_and_in_order(): reader = stream.reader() assert reader.poll() == [] stream.post(Action.RECENTER, SOURCE_CONTROLLER) - stream.post(Action.LAZY_TOGGLE, SOURCE_CONTROLLER) + stream.post(Action.LOCK_MODE, SOURCE_CONTROLLER) stream.post(Action.RECENTER, SOURCE_TTY_KEY) assert reader.poll() == [ ActionEvent(Action.RECENTER, SOURCE_CONTROLLER), - ActionEvent(Action.LAZY_TOGGLE, SOURCE_CONTROLLER), + ActionEvent(Action.LOCK_MODE, SOURCE_CONTROLLER), ActionEvent(Action.RECENTER, SOURCE_TTY_KEY), ] assert reader.poll() == [] @@ -61,10 +62,10 @@ def test_the_same_action_twice_is_two_events(): """Two presses of one toggle must not collapse into one.""" stream = ActionStream() reader = stream.reader() - stream.post(Action.LAZY_TOGGLE, SOURCE_CONTROLLER) - stream.post(Action.LAZY_TOGGLE, SOURCE_CONTROLLER) + stream.post(Action.LOCK_MODE, SOURCE_CONTROLLER) + stream.post(Action.LOCK_MODE, SOURCE_CONTROLLER) assert len(reader.poll()) == 2 - stream.post(Action.LAZY_TOGGLE, SOURCE_CONTROLLER) # equal to the last one seen + stream.post(Action.LOCK_MODE, SOURCE_CONTROLLER) # equal to the last one seen assert len(reader.poll()) == 1 @@ -83,8 +84,8 @@ def test_a_new_reader_does_not_see_the_past(): stream.post(Action.RECENTER, SOURCE_TTY_KEY) reader = stream.reader() assert reader.poll() == [] - stream.post(Action.LAZY_TOGGLE, SOURCE_CONTROLLER) - assert [e.action for e in reader.poll()] == [Action.LAZY_TOGGLE] + stream.post(Action.LOCK_MODE, SOURCE_CONTROLLER) + assert [e.action for e in reader.poll()] == [Action.LOCK_MODE] def test_a_reader_that_fell_behind_gets_the_newest_events(): @@ -133,47 +134,58 @@ def post(source): # -- the bindings table -------------------------------------------------------- -def test_by_default_no_controller_input_triggers_anything(): - assert dataclasses.asdict(BindingsConfig()) == { - "hold": "left_squeeze", - "recenter": "none", - "lazy_toggle": "none", - } +def test_by_default_no_controller_input_does_anything(): + assert set(dataclasses.asdict(BindingsConfig()).values()) == {"none"} -def test_every_action_has_exactly_one_binding_line(): +def test_every_action_and_axis_has_exactly_one_binding_line(): lines = {f.name for f in dataclasses.fields(BindingsConfig)} - {"hold"} - assert lines == {action.value for action in Action} + assert lines == {action.value for action in Action} | {a.value for a in Axis} -@pytest.mark.parametrize("config", ["zed.yaml", "oakd.yaml", "replay.yaml"]) -def test_a_config_that_binds_nothing_acts_on_no_controller_button(config, tmp_path): +def test_a_config_that_binds_nothing_acts_on_no_controller_input(tmp_path): """Controllers worn for teleoperation give their buttons a meaning of their own. The view must not act on those presses unless told to.""" + path = tmp_path / "rig.yaml" + path.write_text(ZED_SOURCE) + assert AppConfig.load(path).bindings == BindingsConfig() + + +#: The layout of the camera_viz example, less its shape button. +CAMERA_VIZ_LAYOUT = BindingsConfig( + recenter="right_thumbstick", + lock_mode="right_primary", + mono_stereo="right_secondary", + reset="left_secondary", + size="left_thumbstick_x", + height="left_thumbstick_y", + stereo_gap="right_thumbstick_x", +) + + +@pytest.mark.parametrize( + "config", ["zed.yaml", "oakd.yaml", "replay.yaml", "synthetic.yaml"] +) +def test_the_shipped_configs_bind_camera_viz_s_layout(config, tmp_path): shutil.copytree(EXAMPLE_DIR / "configs", tmp_path / "configs") # replay.yaml loads only with the recording it names, the user's own. (tmp_path / "test_data").mkdir() (tmp_path / "test_data" / "stereo_sbs.mp4").touch() - bindings = AppConfig.load(tmp_path / "configs" / config).bindings - assert (bindings.recenter, bindings.lazy_toggle) == ("none", "none") - - -def test_the_synthetic_example_binds_recenter_and_nothing_else(): - """Left squeeze + left primary: the binding the README points to.""" - shipped = AppConfig.load(EXAMPLE_DIR / "configs/synthetic.yaml").bindings - assert shipped == BindingsConfig( - hold="left_squeeze", recenter="left_primary", lazy_toggle="none" - ) + assert AppConfig.load(tmp_path / "configs" / config).bindings == CAMERA_VIZ_LAYOUT def test_a_config_can_bind_rebind_and_unbind(tmp_path): path = tmp_path / "rig.yaml" path.write_text( ZED_SOURCE - + "bindings:\n hold: right_squeeze\n recenter: left_secondary\n lazy_toggle: none\n" + + "bindings:\n hold: right_squeeze\n recenter: left_secondary\n" + + " lock_mode: none\n height: right_thumbstick_y\n" ) assert AppConfig.load(path).bindings == BindingsConfig( - hold="right_squeeze", recenter="left_secondary", lazy_toggle="none" + hold="right_squeeze", + recenter="left_secondary", + lock_mode="none", + height="right_thumbstick_y", ) @@ -193,16 +205,30 @@ def test_a_config_can_bind_rebind_and_unbind(tmp_path): "bindings.recenter: 'right_menu' is not a controller input", ), ({"hold": "left_grip"}, "bindings.hold: 'left_grip' is not a controller input"), - ({"hold": "none"}, "bindings.hold: 'none' is not a controller input"), ({"recenter": 3}, "bindings.recenter: 3 is not a controller input"), ({"recenter": ["right_primary"]}, "is not a controller input"), ({"recenter": None}, "bindings.recenter: write the word none"), - ({"lazy_toggle": False}, "bindings.lazy_toggle: write the word none"), + ({"lock_mode": False}, "bindings.lock_mode: write the word none"), ({"hold": None}, "bindings.hold: write the word none"), - ({"recenter": "left_squeeze"}, "left_squeeze is the hold input"), ( - {"recenter": "left_primary", "lazy_toggle": "left_primary"}, - "lazy_toggle and recenter are both on left_primary", + {"hold": "left_squeeze", "recenter": "left_squeeze"}, + "left_squeeze is the hold input", + ), + ( + {"recenter": "left_primary", "lock_mode": "left_primary"}, + "lock_mode and recenter are both on left_primary", + ), + ( + {"size": "left_primary"}, + "bindings.size: 'left_primary' is not a controller stick axis", + ), + ( + {"reset": "left_thumbstick_x"}, + "bindings.reset: 'left_thumbstick_x' is not a controller input", + ), + ( + {"size": "left_thumbstick_x", "height": "left_thumbstick_x"}, + "height and size are both on left_thumbstick_x", ), ], ) @@ -227,7 +253,12 @@ def test_an_unknown_action_in_the_table_is_refused(tmp_path): def test_two_actions_can_both_be_unbound(): - BindingsConfig(recenter="none", lazy_toggle="none") + BindingsConfig(recenter="none", lock_mode="none") + + +def test_a_hold_is_an_input_or_none(): + assert BindingsConfig(hold="none", recenter="left_primary").hold == "none" + assert BindingsConfig(hold="left_squeeze").hold == "left_squeeze" def test_the_input_names_cover_both_controllers(): @@ -408,29 +439,10 @@ def test_every_viewpoint_acts_on_a_recenter_action(): def test_a_new_viewpoint_ignores_actions_from_before_it_existed(): stream = ActionStream() stream.post(Action.RECENTER, SOURCE_TTY_KEY) - stream.post(Action.LAZY_TOGGLE, SOURCE_CONTROLLER) vp = anchored(stream) epoch = vp.anchor_epoch vp.update(eyes(yaw_deg=20.0), T_map_from_cam=np.eye(4)) - assert vp.anchor_epoch == epoch and not vp.lazy_enabled - - -def test_the_lazy_toggle_action_switches_lazy_lock_each_time(): - stream = ActionStream() - vp = anchored(stream) - assert not vp.lazy_enabled - stream.post(Action.LAZY_TOGGLE, SOURCE_CONTROLLER) - vp.update(eyes(), T_map_from_cam=np.eye(4)) - assert vp.lazy_enabled - stream.post(Action.LAZY_TOGGLE, SOURCE_CONTROLLER) - vp.update(eyes(), T_map_from_cam=np.eye(4)) - assert not vp.lazy_enabled - stream.post( - Action.LAZY_TOGGLE, SOURCE_CONTROLLER - ) # two presses between two frames: - stream.post(Action.LAZY_TOGGLE, SOURCE_CONTROLLER) # on and off again - vp.update(eyes(), T_map_from_cam=np.eye(4)) - assert not vp.lazy_enabled + assert vp.anchor_epoch == epoch @pytest.mark.parametrize( @@ -529,9 +541,11 @@ def test_the_controller_is_read_once_per_frame_and_its_press_acts_that_frame(): ) vp.update(eyes(), T_map_from_cam=np.eye(4)) assert controller.updates == 1 - controller.press = Action.LAZY_TOGGLE - vp.update(eyes(), T_map_from_cam=np.eye(4)) - assert controller.updates == 2 and vp.lazy_enabled # same frame, not the next + epoch = vp.anchor_epoch + controller.press = Action.RECENTER + vp.update(eyes(yaw_deg=20.0), T_map_from_cam=np.eye(4)) + # In the same frame, not the next. + assert controller.updates == 2 and vp.anchor_epoch == epoch + 1 vp.close() assert controller.closed diff --git a/tests/python/examples/televiz/test_controller_actions.py b/tests/python/examples/televiz/test_controller_actions.py index 08a4776568..652a6679ba 100644 --- a/tests/python/examples/televiz/test_controller_actions.py +++ b/tests/python/examples/televiz/test_controller_actions.py @@ -24,6 +24,8 @@ Action, ActionEvent, ActionStream, + Axis, + AxisValues, ) from isaaccapture_examples.televiz.pipeline.config import AppConfig, BindingsConfig from isaaccapture_examples.televiz.render import controller_actions @@ -39,7 +41,7 @@ schema = None RECENTER = [ActionEvent(Action.RECENTER, SOURCE_CONTROLLER)] -LAZY_TOGGLE = [ActionEvent(Action.LAZY_TOGGLE, SOURCE_CONTROLLER)] +LOCK_MODE = [ActionEvent(Action.LOCK_MODE, SOURCE_CONTROLLER)] FIELDS = ("primary_click", "secondary_click", "thumbstick_click", "menu_click", "thumbstick_x", "thumbstick_y", "squeeze_value", "trigger_value") # fmt: skip @@ -102,7 +104,7 @@ def tracker(monkeypatch): #: A rig with hand-held controllers. HAND_HELD = dict( - hold="left_squeeze", recenter="right_primary", lazy_toggle="left_primary" + hold="left_squeeze", recenter="right_primary", lock_mode="left_primary" ) @@ -141,10 +143,10 @@ def test_recenter_fires_on_its_button_while_the_hold_is_held(rig): ) -def test_lazy_toggle_fires_on_its_button_while_the_hold_is_held(rig): +def test_a_second_action_fires_on_its_own_button_while_the_hold_is_held(rig): assert ( frame(*rig, left=snapshot(primary_click=True, **HOLD), right=snapshot()) - == LAZY_TOGGLE + == LOCK_MODE ) @@ -201,7 +203,7 @@ def test_once_held_the_hold_stays_held_down_to_forty_percent(rig): def test_a_noisy_pull_of_an_analog_button_is_one_press(tracker): stream = ActionStream() rig = ( - controller(stream, recenter="right_trigger", lazy_toggle="none"), + controller(stream, recenter="right_trigger", lock_mode="none"), tracker, stream.reader(), ) @@ -242,7 +244,7 @@ def test_two_actions_pressed_in_one_frame_both_fire(rig): left=snapshot(primary_click=True, **HOLD), right=snapshot(primary_click=True), ) - assert sorted(e.action.value for e in got) == ["lazy_toggle", "recenter"] + assert sorted(e.action.value for e in got) == ["lock_mode", "recenter"] def test_buttons_with_no_binding_do_nothing(rig): @@ -273,7 +275,7 @@ def test_any_input_can_be_an_actions_button(tracker, button): hold = "right_squeeze" if button == "left_squeeze" else "left_squeeze" stream = ActionStream() rig = ( - controller(stream, hold=hold, recenter=button, lazy_toggle="none"), + controller(stream, hold=hold, recenter=button, lock_mode="none"), tracker, stream.reader(), ) @@ -297,7 +299,7 @@ def test_any_input_can_be_the_hold(tracker, hold): button = "right_secondary" if hold == "right_primary" else "right_primary" stream = ActionStream() rig = ( - controller(stream, hold=hold, recenter=button, lazy_toggle="none"), + controller(stream, hold=hold, recenter=button, lock_mode="none"), tracker, stream.reader(), ) @@ -323,7 +325,7 @@ def test_any_input_can_be_the_hold(tracker, hold): def test_an_unbound_action_never_fires(tracker): stream = ActionStream() - rig = controller(stream, lazy_toggle="none"), tracker, stream.reader() + rig = controller(stream, lock_mode="none"), tracker, stream.reader() assert ( frame(*rig, left=snapshot(primary_click=True, **HOLD), right=snapshot()) == [] ) @@ -386,9 +388,10 @@ def test_the_app_gives_the_controller_the_configs_bindings(tracker, monkeypatch, built = [] real = controller_actions.ControllerActions - def spy(session, bindings, *args): + def spy(session, bindings, **options): built.append(bindings) - return real(session, bindings, *args) + assert options == {"deadzone": shipped.controls.deadzone} + return real(session, bindings, **options) monkeypatch.setattr(controller_actions, "ControllerActions", spy) session = stand_in_session() @@ -504,3 +507,72 @@ def test_without_deviceio_the_app_asks_for_no_extensions(monkeypatch): monkeypatch.setitem(sys.modules, "isaaccapture", None) # makes the import fail monkeypatch.setitem(sys.modules, "isaaccapture.deviceio", None) assert controller_actions.required_extensions_for_controllers() == [] + + +# -- no hold, and the sticks --------------------------------------------------- + + +def test_without_a_hold_a_press_fires_on_its_own(tracker): + stream = ActionStream() + rig = controller(stream, hold="none"), tracker, stream.reader() + assert frame(*rig, left=snapshot(), right=snapshot(primary_click=True)) == RECENTER + assert frame(*rig, left=snapshot(primary_click=True), right=snapshot()) == LOCK_MODE + + +def sticks(tracker, **bindings): + """Controller input whose sticks set the axes: (controller, axes).""" + axes = AxisValues() + table = BindingsConfig( + **{ + "size": "left_thumbstick_x", + "height": "left_thumbstick_y", + "stereo_gap": "right_thumbstick_x", + **bindings, + } + ) + return ControllerActions(SESSION, table, ActionStream(), axes, deadzone=0.2), axes + + +def read(control, tracker, left=None, right=None): + tracker.left, tracker.right = left, right + control.update() + + +def test_a_stick_sets_its_axis_from_the_edge_of_the_deadzone(tracker): + control, axes = sticks(tracker) + read(control, tracker, snapshot(thumbstick_x=0.1, thumbstick_y=-0.6), snapshot()) + assert axes.get(Axis.SIZE) == 0.0 # at rest inside the deadzone + assert axes.get(Axis.HEIGHT) == pytest.approx(-0.5) # (0.6 - 0.2) / 0.8 + read(control, tracker, snapshot(thumbstick_x=1.0), snapshot(thumbstick_x=-1.0)) + assert (axes.get(Axis.SIZE), axes.get(Axis.STEREO_GAP)) == (1.0, -1.0) + assert axes.get(Axis.HEIGHT) == 0.0 # let go + + +def test_a_stick_whose_controller_is_asleep_is_at_rest(tracker): + control, axes = sticks(tracker) + read(control, tracker, snapshot(thumbstick_x=1.0), snapshot()) + read(control, tracker, None, snapshot()) + assert axes.get(Axis.SIZE) == 0.0 + + +def test_with_a_hold_a_stick_moves_its_axis_only_while_it_is_held(tracker): + control, axes = sticks(tracker, hold="right_squeeze") + read(control, tracker, snapshot(thumbstick_x=1.0), snapshot()) + assert axes.get(Axis.SIZE) == 0.0 + read(control, tracker, snapshot(thumbstick_x=1.0), snapshot(squeeze_value=0.9)) + assert axes.get(Axis.SIZE) == 1.0 + + +def test_an_unbound_axis_is_left_alone(tracker): + control, axes = sticks(tracker, size="none") + axes.set(Axis.SIZE, 0.7) # another input path's + read(control, tracker, snapshot(thumbstick_x=1.0), snapshot()) + assert axes.get(Axis.SIZE) == 0.7 + + +def test_a_failed_read_puts_the_sticks_at_rest(tracker): + control, axes = sticks(tracker) + read(control, tracker, snapshot(thumbstick_x=1.0), snapshot()) + tracker.fail = RuntimeError("xrSyncActions failed") + control.update() + assert axes.get(Axis.SIZE) == 0.0 diff --git a/tests/python/examples/televiz/test_heading.py b/tests/python/examples/televiz/test_heading.py index 009d87ca03..25fc6cac31 100644 --- a/tests/python/examples/televiz/test_heading.py +++ b/tests/python/examples/televiz/test_heading.py @@ -285,8 +285,8 @@ def test_a_recenter_dropped_for_the_cameras_roll_says_so(caplog): def test_the_6dof_latch_does_not_latch_onto_a_pose_on_its_side_either(): - """Its anchor needs no heading, but the lazy pair and the navigator - that go with every latch do.""" + """Its anchor needs no heading, but the headset-jump rule that goes + with every latch does.""" stream = ActionStream() quiet = ViewpointConfig( recenter_on_first_pose=False, auto_relatch=False, latch="6dof" diff --git a/tests/python/examples/televiz/test_placement.py b/tests/python/examples/televiz/test_placement.py index 72de3673ed..b134d3c5d1 100644 --- a/tests/python/examples/televiz/test_placement.py +++ b/tests/python/examples/televiz/test_placement.py @@ -181,7 +181,9 @@ def test_the_placement_keys_are_camera_viz_s(): """The section is passed on to camera_viz's placement by name.""" ours = {f.name for f in dataclasses.fields(PlacementConfig)} theirs = {f.name for f in dataclasses.fields(CameraVizPlacement)} - assert ours - {"lock_mode", "size"} == theirs - {"size_meters"} + assert ours - {"lock_mode", "size", "stereo_plane_distance_cm"} == theirs - { + "size_meters" + } @pytest.mark.parametrize( @@ -199,6 +201,10 @@ def test_the_placement_keys_are_camera_viz_s(): "{reposition_delay_s: -1}", r"placement\.reposition_delay_s must be 0 or above", ), + ( + "{stereo_plane_distance_cm: 20}", + r"placement\.stereo_plane_distance_cm must be within -10\.\.10", + ), ], ) def test_a_placement_the_picture_cannot_take_is_refused(tmp_path, section, complaint): diff --git a/tests/python/examples/televiz/test_quad_placement.py b/tests/python/examples/televiz/test_quad_placement.py index 320f8b6711..9d3469b43c 100644 --- a/tests/python/examples/televiz/test_quad_placement.py +++ b/tests/python/examples/televiz/test_quad_placement.py @@ -139,6 +139,7 @@ def _stub_stage(vp, distance_m, anchor_eye): _camera_placement=None, _placed_model=None, _seated_epoch=None, + _controls=SimpleNamespace(placed_for=lambda tuning: None), _anchor_eye=anchor_eye, ) stage._plane = lambda *args: QuadRenderStage._plane(stage, *args) diff --git a/tests/python/examples/televiz/test_recenter_full_latch_drift.py b/tests/python/examples/televiz/test_recenter_full_latch_drift.py index 6696441ebd..3a40544bf0 100644 --- a/tests/python/examples/televiz/test_recenter_full_latch_drift.py +++ b/tests/python/examples/televiz/test_recenter_full_latch_drift.py @@ -217,176 +217,3 @@ def test_full_latch_alignment_consistent_through_mirrored_motion(): assert err < 1e-9, (hy_deg, hp_deg, err) # The whole sequence rode ONE latch — no auto re-latch masked an error. assert vp.anchor_epoch == epoch_after_latch - - -# -- lazy-lock re-anchors as the latch does ------------------------------------- - -LAZY = dict( - lazy_enabled=True, lazy_angle_deg=5.0, lazy_delay_s=0.3, lazy_transition_s=2.0 -) - - -def _seat(vp): - """T_map_from_view: where the view sits in the map.""" - return np.linalg.inv(vp.T_view_from_map) - - -def _turn_the_head_and_wait(vp, cam, clock, eyes): - """The head turns past the lazy angle and stays. Returns the view's seat - on each frame of the re-anchor: its first step, three more, the last.""" - clock.tick() - vp.update(eyes, T_map_from_cam=cam) # past the angle: the delay starts - seats = [] - for _ in range(5): # 0.5 s a frame: the transition's steps 0, 1/4 ... 1 - clock.tick() - vp.update(eyes, T_map_from_cam=cam) - seats.append(_seat(vp)) - return seats - - -def test_a_lazy_reanchor_under_the_full_latch_keeps_the_latched_tilt(): - """The camera sits pitched against the head, and the 6dof latch holds - that. A lazy re-anchor starts where the view is, turns straight to the - new seat, and ends with the anchor eye on the camera again.""" - vp, eyes, cam, clock = _drifted_rig( - config=ViewpointConfig(latch="6dof", **LAZY), drift_pitch=math.radians(15.0) - ) - _recenter(vp, eyes, cam, clock) - before, epoch = _seat(vp), vp.anchor_epoch - turned = _eyes(yaw=math.radians(30.0)) - first, _, middle, _, last = _turn_the_head_and_wait(vp, cam, clock, turned) - - np.testing.assert_allclose(first, before, atol=1e-12) # no jump at the start - # Halfway along the one rotation from the old seat to the new. - whole = _rot_err_deg(np.linalg.inv(before) @ last) - assert whole > 20.0 - assert _rot_err_deg(np.linalg.inv(before) @ middle) == pytest.approx(whole / 2.0) - assert _rot_err_deg(np.linalg.inv(middle) @ last) == pytest.approx(whole / 2.0) - np.testing.assert_allclose(middle[:3, 3], (before[:3, 3] + last[:3, 3]) / 2.0) - # The new seat is the full latch's: the anchor eye sees the camera's image. - rel = _rel(vp, turned[0], cam) - assert np.abs(rel[:3, :3] - np.eye(3)).max() < 1e-9 - np.testing.assert_allclose(rel[:3, 3], 0.0, atol=1e-9) - assert vp.anchor_epoch == epoch + 1 - - -def test_a_lazy_reanchor_under_the_gravity_latch_follows_the_heading_only(): - dp = math.radians(15.0) - vp, eyes, cam, clock = _drifted_rig(config=ViewpointConfig(**LAZY), drift_pitch=dp) - _recenter(vp, eyes, cam, clock) - turned = _eyes(yaw=math.radians(30.0)) - _turn_the_head_and_wait(vp, cam, clock, turned) - # The camera's pitch against the head stays in the view, as after a recenter. - np.testing.assert_allclose( - _fwd_err_deg(vp, turned[0], cam), math.degrees(dp), atol=1e-9 - ) - - -def _tilt(seat): - """How far a seat is from carrying the headset's up onto the map's up - (-Y), element-wise: zero for a view that is not tilted.""" - up = np.array([0.0, -1.0, 0.0]) - return max(np.abs(seat[:3, 1] - up).max(), np.abs(seat[1, :3] - up).max()) - - -def _check_gravity_reanchor(before, seats, turned, cam): - """A re-anchor under the gravity latch starts where the view is, turns - about the vertical only, is halfway at half time, and ends on the seat - a recenter gives. Returns the whole turn in degrees.""" - first, _, middle, _, last = seats - np.testing.assert_allclose(first, before, atol=1e-12) # no jump at the start - whole = _rot_err_deg(np.linalg.inv(before) @ last) - assert _rot_err_deg(np.linalg.inv(before) @ middle) == pytest.approx(whole / 2.0) - assert _rot_err_deg(np.linalg.inv(middle) @ last) == pytest.approx(whole / 2.0) - np.testing.assert_allclose( - middle[:3, 3], (before[:3, 3] + last[:3, 3]) / 2.0, atol=1e-12 - ) - assert max(_tilt(seat) for seat in seats) < 1e-12 - recentered = Viewpoint() # its first frame recenters onto this head and camera - recentered.update(turned, T_map_from_cam=cam) - np.testing.assert_array_equal(last, _seat(recentered)) - return whole - - -def test_a_gravity_lazy_reanchor_starts_at_the_seat_and_not_at_the_lazy_reference(): - """Lazy-lock is switched on with the head turned away from its latch, - so the pair it compares against is not the seat on display.""" - vp, eyes, cam, clock = _drifted_rig( - config=ViewpointConfig(**{**LAZY, "lazy_enabled": False}) - ) - _recenter(vp, eyes, cam, clock) - aside = _eyes(yaw=math.radians(40.0)) - clock.tick() - vp.update(aside, T_map_from_cam=cam) - vp.set_lazy(True) - clock.tick() - vp.update(aside, T_map_from_cam=cam) # lazy-lock's reference is this pose - before = _seat(vp) - turned = _eyes(yaw=math.radians(70.0)) - seats = _turn_the_head_and_wait(vp, cam, clock, turned) - assert _check_gravity_reanchor(before, seats, turned, cam) == pytest.approx(70.0) - - -def test_a_gravity_lazy_reanchor_from_the_frame_bridge_does_not_jump(): - """Without the recenter onto the first pose the view sits on the frame - bridge, half a turn from where a recenter seats it for a camera at the - map's origin.""" - vp, _, cam, clock = _drifted_rig( - config=ViewpointConfig(recenter_on_first_pose=False, **LAZY) - ) - before = _seat(vp) - turned = _eyes(yaw=math.radians(30.0)) - seats = _turn_the_head_and_wait(vp, cam, clock, turned) - assert _check_gravity_reanchor(before, seats, turned, cam) == pytest.approx(150.0) - - -def _on_its_side(pose): - """The pose rolled a quarter turn about its own forward axis: it has - no heading.""" - out = pose.copy() - out[:3, :3] = pose[:3, :3] @ _rotz(math.pi / 2.0) - return out - - -@pytest.mark.parametrize("lost", ["no eyes", "head on its side", "camera on its side"]) -def test_the_lazy_delay_starts_over_after_a_frame_without_a_target(lost): - """The head turns past the lazy angle and is then lost for longer than - the delay. Back in view, it waits out the delay again.""" - snap = {**LAZY, "lazy_transition_s": 0.0} # a re-anchor is one re-seat - vp, eyes, cam, clock = _drifted_rig(config=ViewpointConfig(**snap)) - _recenter(vp, eyes, cam, clock) - epoch = vp.anchor_epoch - turned = _eyes(yaw=math.radians(30.0)) - lost_eyes, lost_cam = { - "no eyes": ([], cam), - "head on its side": ([_on_its_side(eye) for eye in turned], cam), - "camera on its side": (turned, _on_its_side(cam)), - }[lost] - clock.tick() - vp.update(turned, T_map_from_cam=cam) # past the angle: the delay starts - clock.tick() - vp.update(lost_eyes, T_map_from_cam=lost_cam) - clock.tick() - vp.update(turned, T_map_from_cam=cam) # back: the delay starts over - assert vp.anchor_epoch == epoch - clock.tick() - vp.update(turned, T_map_from_cam=cam) - assert vp.anchor_epoch == epoch + 1 - - -def test_a_lazy_reanchor_under_way_goes_on_without_a_target(): - vp, eyes, cam, clock = _drifted_rig(config=ViewpointConfig(**LAZY)) - _recenter(vp, eyes, cam, clock) - turned = _eyes(yaw=math.radians(30.0)) - for _ in range(2): # past the angle, then the re-anchor's first step - clock.tick() - vp.update(turned, T_map_from_cam=cam) - before, epoch = _seat(vp), vp.anchor_epoch - for _ in range(4): # the head is lost for the rest of it - clock.tick() - vp.update([], T_map_from_cam=cam) - assert not np.allclose(_seat(vp), before) - assert vp.anchor_epoch == epoch + 1 - recentered = Viewpoint() # its first frame recenters onto this head and camera - recentered.update(turned, T_map_from_cam=cam) - np.testing.assert_array_equal(_seat(vp), _seat(recentered)) diff --git a/tests/python/examples/televiz/test_view_controls.py b/tests/python/examples/televiz/test_view_controls.py new file mode 100644 index 0000000000..07cb7c2c7e --- /dev/null +++ b/tests/python/examples/televiz/test_view_controls.py @@ -0,0 +1,502 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""The operator's live changes to the view: actions and axes, applied to +the picture's placement and layer.""" + +from __future__ import annotations + +import logging +import time +from types import SimpleNamespace + +import numpy as np +import pytest + +from isaaccapture_examples.camera_viz import controls as camera_viz_controls +from isaaccapture_examples.televiz.pipeline.actions import ( + ACTIONS, + SOURCE_CONTROLLER, + Action, + ActionStream, + Axis, + AxisValues, +) +from isaaccapture_examples.televiz.pipeline.config import ( + ConfigError, + ControlsConfig, + PlacementConfig, +) +from isaaccapture_examples.televiz.pipeline.config import ViewpointConfig +from isaaccapture_examples.televiz.pipeline.mailbox import Mailbox +from isaaccapture_examples.televiz.pipeline.messages import ( + CameraModel, + PoseSample, + StereoFrame, +) +from isaaccapture_examples.televiz.render.placement import ( + CameraPlacement, + placement_config, +) +from isaaccapture_examples.televiz.render.quad_stage import QuadRenderStage +from isaaccapture_examples.televiz.render.view_controls import ViewControls +from isaaccapture_examples.televiz.render.viewpoint import Viewpoint + +MODEL = CameraModel(1280, 720, 800.0, 800.0, 639.5, 359.5) # 3.2 m x 1.8 m at 2 m +IPD_MM = 63.0 + + +class Layer: + """The quad layer's part the controls use.""" + + def __init__(self) -> None: + self.gaps_mm = [] + + def set_stereo_baseline_mm(self, gap_mm: float) -> None: + self.gaps_mm.append(round(gap_mm, 6)) + + +def rig(stereo=True, **settings): + """The controls over one seated picture, with a clock the test turns.""" + section = PlacementConfig(**settings) + placement = CameraPlacement(section.lock_mode, placement_config(section, MODEL)) + stream, axes, now = ActionStream(), AxisValues(), [0.0] + controls = ViewControls( + section, + ControlsConfig(), + stereo=stereo, + actions=stream, + axes=axes, + clock=lambda: now[0], + ) + out = SimpleNamespace( + controls=controls, placement=placement, layer=Layer(), axes=axes, now=now + ) + out.press = lambda action: stream.post(action, SOURCE_CONTROLLER) + controls.placed_for(placement.config) # as the stage does, per camera model + frame(out) # the first frame: there is a picture, and no time has passed + return out + + +def frame(r, dt=0.0): + r.now[0] += dt + r.controls.step(r.placement, r.layer, ipd_mm=IPD_MM) + + +def hold(r, seconds, fps=20): + """Frames at ``fps`` for ``seconds``, with the sticks where they stand.""" + for _ in range(round(seconds * fps)): + frame(r, 1.0 / fps) + + +def test_the_lock_mode_action_goes_round_the_modes_from_the_config_s(): + r = rig(lock_mode="gimbal") + seen = [] + for _ in range(4): + r.press(Action.LOCK_MODE) + frame(r) + seen.append(r.placement.lock_mode) + assert seen == ["lazy", "world", "head", "gimbal"] + assert r.controls.last_event == "lock mode: gimbal" + + +def test_two_presses_between_two_frames_are_two_steps(): + r = rig(lock_mode="world") + r.press(Action.LOCK_MODE) + r.press(Action.LOCK_MODE) + frame(r) + assert r.placement.lock_mode == "gimbal" + + +def test_mono_shows_both_eyes_one_image_and_closes_the_gap(): + r = rig(stereo_plane_distance_cm=2.0) + assert not r.controls.mono and r.layer.gaps_mm == [20.0] + r.press(Action.MONO_STEREO) + frame(r) + assert r.controls.mono and r.layer.gaps_mm == [20.0, 0.0] + r.press(Action.MONO_STEREO) + frame(r) + assert not r.controls.mono and r.layer.gaps_mm == [20.0, 0.0, 20.0] + + +def test_a_picture_of_one_image_has_no_mono_to_switch_to(): + r = rig(stereo=False, stereo_plane_distance_cm=2.0) + r.press(Action.MONO_STEREO) + r.axes.set(Axis.STEREO_GAP, 1.0) + hold(r, 1.0) + assert not r.controls.mono + assert r.layer.gaps_mm == [] # and no second plane to move + assert r.controls.last_event == "mono/stereo: the picture has one image" + + +def test_the_size_axis_scales_the_picture_and_keeps_its_shape(): + r = rig() + r.axes.set(Axis.SIZE, 1.0) + hold(r, 1.0) # a second at camera_viz's 0.5 m/s + width, height = r.placement.config.size_meters + assert (width, height) == pytest.approx((3.7, 3.7 * 1.8 / 3.2)) + r.axes.set(Axis.SIZE, -1.0) + hold(r, 10.0) + assert r.placement.config.size_meters[0] == pytest.approx(0.2) # its floor + + +def test_the_height_axis_moves_the_picture_up_and_down(): + r = rig() + r.axes.set(Axis.HEIGHT, -0.5) + hold(r, 2.0) + assert r.placement.config.offset_y == pytest.approx(-0.5) + assert r.controls.last_event == "height: -0.50 m" + + +def test_a_stick_at_rest_changes_nothing(): + r = rig() + before = r.placement.config + hold(r, 5.0) + assert r.placement.config is before and r.layer.gaps_mm == [0.0] + + +def test_the_gap_axis_widens_the_gap_in_steps_up_to_what_the_eyes_can_take(): + r = rig() + r.axes.set(Axis.STEREO_GAP, 1.0) + hold(r, 0.5) # half a second at 2 cm/s + assert r.layer.gaps_mm[-1] == pytest.approx(10.0) + handed = len(r.layer.gaps_mm) + frame(r, 0.02) # less than a step of 0.1 cm: the layer is left alone + assert len(r.layer.gaps_mm) == handed + hold(r, 10.0) + # Nine tenths of the eyes' own distance, in whole steps. + limit_cm = camera_viz_controls.stereo.max_gap_cm(IPD_MM, 10.0) + assert r.layer.gaps_mm[-1] == pytest.approx( + 10.0 * camera_viz_controls.stereo.step(limit_cm) + ) + assert r.layer.gaps_mm[-1] < IPD_MM + + +def test_the_gap_axis_does_nothing_while_mono(): + r = rig() + r.press(Action.MONO_STEREO) + r.axes.set(Axis.STEREO_GAP, 1.0) + hold(r, 1.0) + assert r.layer.gaps_mm == [0.0] + + +def test_reset_puts_back_what_the_config_said(): + r = rig(lock_mode="world", stereo_plane_distance_cm=1.0, offset_y=0.2) + first = r.placement.config + r.press(Action.LOCK_MODE) + r.press(Action.MONO_STEREO) + for axis in Axis: + r.axes.set(axis, 1.0) + hold(r, 1.0) + assert r.placement.config != first and r.placement.lock_mode != "world" + for axis in Axis: + r.axes.set(axis, 0.0) + r.press(Action.RESET) + frame(r) + assert r.placement.config == first and r.placement.lock_mode == "world" + assert not r.controls.mono and r.layer.gaps_mm[-1] == 10.0 + + +def test_presses_made_before_there_is_a_picture_are_dropped(): + stream = ActionStream() + section = PlacementConfig() + controls = ViewControls(section, actions=stream, axes=AxisValues()) + stream.post(Action.LOCK_MODE, SOURCE_CONTROLLER) + controls.step(None, None) + placement = CameraPlacement("gimbal", placement_config(section, MODEL)) + controls.step(placement, Layer()) + assert placement.lock_mode == "gimbal" + + +def test_a_layer_that_cannot_take_a_gap_is_said_once_and_left_alone(caplog): + r = rig(stereo_plane_distance_cm=2.0) + r.layer = object() # of an isaaccapture older than the setter + with caplog.at_level(logging.WARNING): + frame(r) + frame(r) + assert caplog.text.count("no Layer.set_stereo_baseline_mm") == 1 + + +def test_a_rebuilt_layer_is_handed_the_gap_again(): + r = rig(stereo_plane_distance_cm=2.0) + r.layer = Layer() # the camera's resolution changed + frame(r) + assert r.layer.gaps_mm == [20.0] + + +def test_a_gap_wider_than_the_eyes_can_take_is_not_handed_on(): + r = rig(stereo_plane_distance_cm=9.0) + limit_cm = camera_viz_controls.stereo.max_gap_cm(IPD_MM, 10.0) + assert r.layer.gaps_mm == [ + pytest.approx(10.0 * camera_viz_controls.stereo.step(limit_cm)) + ] + + +def test_a_stick_nobody_reads_any_more_is_at_rest(): + """The headset is taken off with the stick pushed: the frames go on + without the controllers being read.""" + now = [0.0] + axes = AxisValues(clock=lambda: now[0]) + axes.set(Axis.SIZE, 1.0) + assert axes.get(Axis.SIZE) == 1.0 + now[0] += 1.0 + assert axes.get(Axis.SIZE) == 0.0 + axes.set(Axis.SIZE, 1.0) # read again + assert axes.get(Axis.SIZE) == 1.0 + + +def test_a_frame_loop_that_stood_still_is_one_short_step(): + r = rig() + r.axes.set(Axis.SIZE, 1.0) + frame(r, 30.0) + assert r.placement.config.size_meters[0] == pytest.approx(3.2 + 0.5 * 0.1) + + +def test_reset_after_another_camera_goes_back_to_that_camera_s_size(): + r = rig() + other = CameraModel(640, 480, 300.0, 300.0, 319.5, 239.5) + tuning = placement_config(PlacementConfig(), other) + r.placement.retune(tuning) + r.controls.placed_for(tuning) # as the stage does for another model + r.axes.set(Axis.SIZE, 1.0) + hold(r, 1.0) + r.axes.set(Axis.SIZE, 0.0) + r.press(Action.RESET) + frame(r) + assert r.placement.config == tuning + + +def test_the_sticks_limits_make_room_for_a_picture_larger_than_their_own(): + r = rig(distance=6.0) # 9.6 m of picture, past camera_viz's 8 m + assert r.placement.config.size_meters[0] == pytest.approx(9.6) + r.axes.set(Axis.SIZE, -1.0) + frame(r, 0.05) + assert r.placement.config.size_meters[0] == pytest.approx(9.6 - 0.5 * 0.05) + + +class Hud: + """camera_viz's panel, as the controls use it.""" + + def __init__(self) -> None: + self.shown, self.steps = [], [] + + def show(self, lines) -> None: + self.shown.append(list(lines)) + + def step(self, dt, head_pose) -> None: + self.steps.append((dt, head_pose)) + + +def test_a_change_is_shown_on_the_panel_in_the_headset(monkeypatch): + hud = Hud() + monkeypatch.setattr(camera_viz_controls, "make_hud", lambda session, on: hud) + r = rig() + assert r.controls.wants_hud + r.controls.attach_hud(session=object()) + r.press(Action.LOCK_MODE) + r.now[0] += 0.1 + r.controls.step(r.placement, r.layer, head_pose="the head") + assert hud.shown == [["lock mode: lazy"]] + assert hud.steps == [(pytest.approx(0.1), "the head")] + + +def test_a_panel_that_cannot_be_made_leaves_the_view_running(monkeypatch, caplog): + def no_panel(session, on): + raise RuntimeError("no layer to be had") + + monkeypatch.setattr(camera_viz_controls, "make_hud", no_panel) + r = rig() + with caplog.at_level(logging.WARNING): + r.controls.attach_hud(session=object()) + assert "no readout in the headset: no layer to be had" in caplog.text + r.press(Action.LOCK_MODE) + frame(r) + assert r.placement.lock_mode == "lazy" + + +def test_the_panel_can_be_switched_off_in_the_config(): + controls = ViewControls(PlacementConfig(), ControlsConfig(hud=False)) + assert not controls.wants_hud + + +@pytest.mark.parametrize( + "section, complaint", + [ + ({"deadzone": 1.0}, r"controls\.deadzone must be 0 or above and below 1"), + ({"deadzone": -0.1}, r"controls\.deadzone must be 0 or above and below 1"), + ({"size_rate_m_per_s": 0.0}, r"controls\.size_rate_m_per_s must be above 0"), + ], +) +def test_controls_the_sticks_cannot_work_with_are_refused(section, complaint): + with pytest.raises(ConfigError, match=complaint): + ControlsConfig(**section) + + +# -- in the headset view stage ------------------------------------------------- + +GIVE_UP_S = 5.0 + + +class StageLayer(Layer): + """The quad layer the stage adds to the session.""" + + def __init__(self) -> None: + super().__init__() + self.submitted, self.placements = [], [] + + def submit(self, left, right=None, stream=0) -> None: + self.submitted.append((left, right)) + + def set_placement(self, placement) -> None: + self.placements.append(placement) + + +class Headset: + """In place of the display session: a worn headset that grants every + frame, with its eyes 64 mm apart.""" + + def __init__(self) -> None: + self.layer = None + self.removed = [] + + def is_xr_mode(self) -> bool: + return True + + def begin_frame(self): + time.sleep(0.002) + level = (1.0, 0.0, 0.0, 0.0) + eyes = [ + SimpleNamespace( + pose=SimpleNamespace(position=(x, 1.5, 0.0), orientation=level) + ) + for x in (-0.032, 0.032) + ] + return SimpleNamespace(should_render=True, views=eyes) + + def end_frame(self) -> None: + pass + + def should_close(self) -> bool: + return False + + def add_quad_layer(self, config): + self.layer = StageLayer() + return self.layer + + def remove_layer(self, layer) -> None: + self.removed.append(layer) + + +def show(stage, session, frames, poses, model=MODEL, timestamp_ns=7): + """Publish one stereo frame with its pose and step until it is shown.""" + height, width = model.height, model.width + frames.publish( + StereoFrame( + left=None, + right=None, + timestamp_ns=timestamp_ns, + seq=0, + left_model=model, + baseline_m=0.063, + color=np.zeros((height, width, 4), np.uint8), + color_right=np.ones((height, width, 4), np.uint8), + ) + ) + poses.publish( + PoseSample(timestamp_ns=timestamp_ns, seq=0, T_map_from_cam=np.eye(4)) + ) + shown = 0 if session.layer is None else len(session.layer.submitted) + layer, began = session.layer, time.monotonic() + while session.layer is layer and (layer is None or len(layer.submitted) == shown): + assert time.monotonic() - began < GIVE_UP_S, "the frame was never shown" + stage.step() + while not session.layer.submitted: + assert time.monotonic() - began < GIVE_UP_S, "the frame was never shown" + stage.step() + + +@pytest.fixture +def headset_view(): + """A headset view stage over a stand-in session: make(controls) -> + (stage, session, frames, poses).""" + pytest.importorskip("isaaccapture.viz", reason="needs isaaccapture") + stages = [] + + def make(controls): + frames, poses = Mailbox("frames"), Mailbox("poses", history_size=16) + session = Headset() + stage = QuadRenderStage( + session, + frames, + poses, + Viewpoint(ViewpointConfig(), pose_in=poses), + placement=PlacementConfig(stereo_plane_distance_cm=1.5), + controls=controls, + stereo=True, + ) + stage.setup() + stages.append(stage) + return stage, session, frames, poses + + yield make + for stage in stages: + stage.teardown() + + +@pytest.fixture +def view(headset_view): + """A headset view stage that shows one stereo frame: (stage, layer, press).""" + stage, session, frames, poses = headset_view(ControlsConfig(hud=False)) + show(stage, session, frames, poses) + return stage, session.layer, lambda action: ACTIONS.post(action, SOURCE_CONTROLLER) + + +def test_the_stage_gives_the_layer_the_config_s_gap_and_both_images(view): + stage, layer, _ = view + stage.step() + assert layer.gaps_mm == [15.0] + left, right = layer.submitted[-1] + assert left is not right + + +def test_mono_in_the_stage_sends_the_left_image_to_both_eyes(view): + stage, layer, press = view + stage.step() + press(Action.MONO_STEREO) + stage.step() + stage._unsubmitted = True # the picture is sent again with the next image + stage.step() + left, right = layer.submitted[-1] + assert left is right and layer.gaps_mm == [15.0, 0.0] + + +def test_a_lock_mode_press_changes_the_stage_s_placement(view): + stage, layer, press = view + press(Action.LOCK_MODE) + stage.step() + assert stage._camera_placement.lock_mode == "lazy" + assert layer.placements # and the plane is still placed every frame + + +def test_the_panel_is_made_after_the_picture_s_layer_and_again_after_a_rebuild( + headset_view, monkeypatch +): + """A layer added later is drawn over the earlier ones.""" + made = [] + + def make_hud(session, on): + made.append(session.layer) # the picture's layer when the panel is made + return SimpleNamespace( + _layer=f"panel {len(made)}", show=lambda lines: None, step=lambda *a: None + ) + + monkeypatch.setattr(camera_viz_controls, "make_hud", make_hud) + stage, session, frames, poses = headset_view(ControlsConfig(hud=True)) + show(stage, session, frames, poses) + first = session.layer + assert made == [first] + smaller = CameraModel(640, 480, 300.0, 300.0, 319.5, 239.5) + show(stage, session, frames, poses, model=smaller, timestamp_ns=8) + assert session.layer is not first and made == [first, session.layer] + assert session.removed == [first, "panel 1"] # the panel after its picture + stage.step() + assert session.layer.gaps_mm == [15.0] # and the new layer has the gap diff --git a/tests/python/examples/televiz/test_viewpoint.py b/tests/python/examples/televiz/test_viewpoint.py index 61ced1be0c..f0257b925d 100644 --- a/tests/python/examples/televiz/test_viewpoint.py +++ b/tests/python/examples/televiz/test_viewpoint.py @@ -15,7 +15,6 @@ AUTO_RECENTER_DEBOUNCE_FRAMES, FLIP, Viewpoint, - _interpolate_pose, is_recenter_jump, request_recenter, ) @@ -331,92 +330,3 @@ def test_drift_is_measured_from_the_first_seat_when_no_pose_recenters(): vp.update(_eyes(x0=0.7), T_map_from_cam=cam) assert COORDINATOR._counts[RecenterSource.DRIFT] == drift_recenters + 1 assert vp.anchor_epoch == epoch + 1 - - -def test_drift_is_measured_from_a_completed_lazy_reanchor(): - """The head walks off in two steps, each under the drift threshold and - past the lazy one, and the lazy-lock re-anchors after each. It then - sits at its anchor, so the drift rule has nothing to recenter.""" - t = [0.0] - config = ViewpointConfig( - auto_recenter_threshold_m=0.5, - lazy_enabled=True, - lazy_translation_m=0.1, - lazy_delay_s=0.3, - lazy_transition_s=0.5, - ) - vp = Viewpoint(config, clock=lambda: t[0]) - cam = np.eye(4) - vp.update(_eyes(), T_map_from_cam=cam) # latched: drift is measured from here - epoch = vp.anchor_epoch - drift_recenters = COORDINATOR._counts[RecenterSource.DRIFT] - for x0 in (0.3, 0.6): - for _ in range(3): # past the lazy threshold, the re-anchor's start, its end - t[0] += 0.5 - vp.update(_eyes(x0=x0), T_map_from_cam=cam) - assert vp.anchor_epoch == epoch + 2 - for _ in range(2 * AUTO_RECENTER_DEBOUNCE_FRAMES): - t[0] += 0.5 - vp.update(_eyes(x0=0.6), T_map_from_cam=cam) - assert COORDINATOR._counts[RecenterSource.DRIFT] == drift_recenters - assert vp.anchor_epoch == epoch + 2 - - -def test_a_pose_blend_turns_about_one_axis_also_through_half_a_turn(): - """Twice the halfway rotation is the whole one, and the position goes - straight.""" - axis = np.array([1.0, 2.0, -2.0]) / 3.0 - x, y, z = axis - K = np.array([[0.0, -z, y], [z, 0.0, -x], [-y, x, 0.0]]) - start = np.eye(4) - start[:3, :3] = [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]] - start[:3, 3] = (1.0, 0.0, -1.0) - for angle in (0.0, 1e-13, 0.7, 3.0, math.pi - 1e-8, math.pi): - end = np.eye(4) - turn = np.eye(3) + math.sin(angle) * K + (1.0 - math.cos(angle)) * (K @ K) - end[:3, :3] = start[:3, :3] @ turn - end[:3, 3] = (3.0, 2.0, 1.0) - np.testing.assert_allclose( - _interpolate_pose(start, end, 0.0), start, atol=1e-12 - ) - np.testing.assert_allclose(_interpolate_pose(start, end, 1.0), end, atol=1e-7) - half = _interpolate_pose(start, end, 0.5) - part = start[:3, :3].T @ half[:3, :3] - np.testing.assert_allclose(part @ part, turn, atol=1e-7, err_msg=str(angle)) - np.testing.assert_allclose(half[:3, 3], (2.0, 1.0, 0.0)) - - -def test_a_pose_blend_of_two_gravity_seats_keeps_the_vertical(): - """The seats the gravity latch gives, the frame bridge and a recenter, - differ by a turn about the map's vertical, so a blend of two carries - the headset's up onto the map's up all the way. Also near half a turn, - where the blend finds its axis another way.""" - rng = np.random.default_rng(5) - up = np.array([0.0, -1.0, 0.0]) - - def seat(recentered): - vp = Viewpoint(ViewpointConfig(recenter_on_first_pose=recentered)) - cam = np.eye(4) - cam[:3, :3] = _eyes(yaw_deg=rng.uniform(-180.0, 180.0))[0][:3, :3] - cam[:3, 3] = rng.uniform(-2.0, 2.0, 3) - vp.update(_eyes(*rng.uniform(-2.0, 2.0, 3), rng.uniform(-180.0, 180.0)), cam) - return np.linalg.inv(vp.T_view_from_map) - - def turned(seat, angle): - out = seat.copy() - out[:3, :3] = seat[:3, :3] @ _eyes(yaw_deg=math.degrees(angle))[0][:3, :3] - return out - - pairs = [ - (seat(a), seat(b)) - for _ in range(25) - for a in (False, True) - for b in (False, True) - ] - near_half_a_turn = [math.pi - d for d in (0.0, 1e-9, 9e-7, 1.1e-6, 1e-4)] - pairs += [(a, turned(a, angle)) for a, _ in pairs[:4] for angle in near_half_a_turn] - for a, b in pairs: - for t in (0.0, 0.1, 0.5, 0.9, 1.0): - R = _interpolate_pose(a, b, t)[:3, :3] - assert np.abs(R[:, 1] - up).max() < 1e-12 - assert np.abs(R[1, :] - up).max() < 1e-12 From 2c8ef0efe1a4540b597e290d7fe9d3ce735d9887 Mon Sep 17 00:00:00 2001 From: Jun-Jee Chao Date: Tue, 1 Dec 2026 18:04:14 -0800 Subject: [PATCH 3/5] fix(examples/televiz): show a mono switch at once, and bound the gap always A switch between mono and stereo showed only with the next camera image. The gap between the eyes' planes is handed to the layer only with camera_viz's bound on it. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Jun-Jee Chao --- .../televiz/render/quad_stage.py | 8 ++- .../televiz/render/view_controls.py | 4 +- .../examples/televiz/test_view_controls.py | 66 ++++++++++++++----- 3 files changed, 58 insertions(+), 20 deletions(-) diff --git a/examples/televiz/python/isaaccapture_examples/televiz/render/quad_stage.py b/examples/televiz/python/isaaccapture_examples/televiz/render/quad_stage.py index f44f0e073f..f98f3df450 100644 --- a/examples/televiz/python/isaaccapture_examples/televiz/render/quad_stage.py +++ b/examples/televiz/python/isaaccapture_examples/televiz/render/quad_stage.py @@ -117,6 +117,7 @@ def __init__( # (StereoFrame, T_map_from_cam, baseline_m, PoseFlags) self._pending = None self._unsubmitted = False # _pending holds a texture not yet sent + self._submitted_mono = False # what the last submit showed the eyes self._right_missing_warned = False # Times of the runtime's frame grants: how often it asks for a frame. self._grant_times = deque(maxlen=256) @@ -196,8 +197,13 @@ def _frame(self, info) -> bool: # The placement is set every frame because the head moves; the # texture only when new, because a quad layer keeps its last image. self._layer.set_placement(self._placement(views, model, T_map_from_cam)) - if self._unsubmitted: + # Sent again when the operator switches between mono and stereo: + # the next image may be a while, with a recording that has ended. + mono = self._controls.mono + if self._unsubmitted or mono != self._submitted_mono: self._submit(frame) + self._submitted_mono = mono + if self._unsubmitted: self._unsubmitted = False self.last_timestamp_ns = frame.timestamp_ns self.last_host_recv_ns = frame.host_recv_ns diff --git a/examples/televiz/python/isaaccapture_examples/televiz/render/view_controls.py b/examples/televiz/python/isaaccapture_examples/televiz/render/view_controls.py index 5d35a358c8..1f6f4e6805 100644 --- a/examples/televiz/python/isaaccapture_examples/televiz/render/view_controls.py +++ b/examples/televiz/python/isaaccapture_examples/televiz/render/view_controls.py @@ -234,7 +234,9 @@ def _apply_gap(self, layer) -> None: return if layer is not self._gap_layer: # a new layer starts without a gap self._gap_layer, self._gap_applied = layer, None - gap = 0.0 if self._mono else self._gap_cm + # No gap without camera_viz's bound on it: one wider than the eyes + # are apart would have them diverge. + gap = 0.0 if self._mono or self._tuning is None else self._gap_cm if self._tuning is not None: stereo = self._camera_viz.stereo limits = ( diff --git a/tests/python/examples/televiz/test_view_controls.py b/tests/python/examples/televiz/test_view_controls.py index 07cb7c2c7e..e1293e752d 100644 --- a/tests/python/examples/televiz/test_view_controls.py +++ b/tests/python/examples/televiz/test_view_controls.py @@ -59,7 +59,8 @@ def rig(stereo=True, **settings): """The controls over one seated picture, with a clock the test turns.""" section = PlacementConfig(**settings) placement = CameraPlacement(section.lock_mode, placement_config(section, MODEL)) - stream, axes, now = ActionStream(), AxisValues(), [0.0] + now = [0.0] + stream, axes = ActionStream(), AxisValues(clock=lambda: now[0]) controls = ViewControls( section, ControlsConfig(), @@ -69,16 +70,27 @@ def rig(stereo=True, **settings): clock=lambda: now[0], ) out = SimpleNamespace( - controls=controls, placement=placement, layer=Layer(), axes=axes, now=now + controls=controls, + placement=placement, + layer=Layer(), + axes=axes, + now=now, + pushed={}, # where the sticks stand, as the controllers are read ) out.press = lambda action: stream.post(action, SOURCE_CONTROLLER) + out.push = out.pushed.__setitem__ controls.placed_for(placement.config) # as the stage does, per camera model frame(out) # the first frame: there is a picture, and no time has passed return out -def frame(r, dt=0.0): +def frame(r, dt=0.0, read=True): + """One frame ``dt`` after the last. ``read``: the controllers are read + in it, which sets every axis anew.""" r.now[0] += dt + if read: + for axis, value in r.pushed.items(): + r.axes.set(axis, value) r.controls.step(r.placement, r.layer, ipd_mm=IPD_MM) @@ -121,7 +133,7 @@ def test_mono_shows_both_eyes_one_image_and_closes_the_gap(): def test_a_picture_of_one_image_has_no_mono_to_switch_to(): r = rig(stereo=False, stereo_plane_distance_cm=2.0) r.press(Action.MONO_STEREO) - r.axes.set(Axis.STEREO_GAP, 1.0) + r.push(Axis.STEREO_GAP, 1.0) hold(r, 1.0) assert not r.controls.mono assert r.layer.gaps_mm == [] # and no second plane to move @@ -130,18 +142,18 @@ def test_a_picture_of_one_image_has_no_mono_to_switch_to(): def test_the_size_axis_scales_the_picture_and_keeps_its_shape(): r = rig() - r.axes.set(Axis.SIZE, 1.0) + r.push(Axis.SIZE, 1.0) hold(r, 1.0) # a second at camera_viz's 0.5 m/s width, height = r.placement.config.size_meters assert (width, height) == pytest.approx((3.7, 3.7 * 1.8 / 3.2)) - r.axes.set(Axis.SIZE, -1.0) + r.push(Axis.SIZE, -1.0) hold(r, 10.0) assert r.placement.config.size_meters[0] == pytest.approx(0.2) # its floor def test_the_height_axis_moves_the_picture_up_and_down(): r = rig() - r.axes.set(Axis.HEIGHT, -0.5) + r.push(Axis.HEIGHT, -0.5) hold(r, 2.0) assert r.placement.config.offset_y == pytest.approx(-0.5) assert r.controls.last_event == "height: -0.50 m" @@ -156,7 +168,7 @@ def test_a_stick_at_rest_changes_nothing(): def test_the_gap_axis_widens_the_gap_in_steps_up_to_what_the_eyes_can_take(): r = rig() - r.axes.set(Axis.STEREO_GAP, 1.0) + r.push(Axis.STEREO_GAP, 1.0) hold(r, 0.5) # half a second at 2 cm/s assert r.layer.gaps_mm[-1] == pytest.approx(10.0) handed = len(r.layer.gaps_mm) @@ -174,7 +186,7 @@ def test_the_gap_axis_widens_the_gap_in_steps_up_to_what_the_eyes_can_take(): def test_the_gap_axis_does_nothing_while_mono(): r = rig() r.press(Action.MONO_STEREO) - r.axes.set(Axis.STEREO_GAP, 1.0) + r.push(Axis.STEREO_GAP, 1.0) hold(r, 1.0) assert r.layer.gaps_mm == [0.0] @@ -185,11 +197,11 @@ def test_reset_puts_back_what_the_config_said(): r.press(Action.LOCK_MODE) r.press(Action.MONO_STEREO) for axis in Axis: - r.axes.set(axis, 1.0) + r.push(axis, 1.0) hold(r, 1.0) assert r.placement.config != first and r.placement.lock_mode != "world" for axis in Axis: - r.axes.set(axis, 0.0) + r.push(axis, 0.0) r.press(Action.RESET) frame(r) assert r.placement.config == first and r.placement.lock_mode == "world" @@ -244,9 +256,23 @@ def test_a_stick_nobody_reads_any_more_is_at_rest(): assert axes.get(Axis.SIZE) == 1.0 +def test_a_stick_the_controls_stop_hearing_of_stops_changing_the_picture(): + r = rig() + r.push(Axis.SIZE, 1.0) + hold(r, 1.0) + grown = r.placement.config.size_meters[0] + for _ in range(10): # half a second in which no controller is read + frame(r, 0.05, read=False) + ran_on = r.placement.config.size_meters[0] - grown + assert 0.0 < ran_on <= 0.5 * 0.25 + 1e-9 # while the value was fresh + for _ in range(40): + frame(r, 0.05, read=False) + assert r.placement.config.size_meters[0] == pytest.approx(grown + ran_on) + + def test_a_frame_loop_that_stood_still_is_one_short_step(): r = rig() - r.axes.set(Axis.SIZE, 1.0) + r.push(Axis.SIZE, 1.0) frame(r, 30.0) assert r.placement.config.size_meters[0] == pytest.approx(3.2 + 0.5 * 0.1) @@ -257,9 +283,9 @@ def test_reset_after_another_camera_goes_back_to_that_camera_s_size(): tuning = placement_config(PlacementConfig(), other) r.placement.retune(tuning) r.controls.placed_for(tuning) # as the stage does for another model - r.axes.set(Axis.SIZE, 1.0) + r.push(Axis.SIZE, 1.0) hold(r, 1.0) - r.axes.set(Axis.SIZE, 0.0) + r.push(Axis.SIZE, 0.0) r.press(Action.RESET) frame(r) assert r.placement.config == tuning @@ -268,7 +294,7 @@ def test_reset_after_another_camera_goes_back_to_that_camera_s_size(): def test_the_sticks_limits_make_room_for_a_picture_larger_than_their_own(): r = rig(distance=6.0) # 9.6 m of picture, past camera_viz's 8 m assert r.placement.config.size_meters[0] == pytest.approx(9.6) - r.axes.set(Axis.SIZE, -1.0) + r.push(Axis.SIZE, -1.0) frame(r, 0.05) assert r.placement.config.size_meters[0] == pytest.approx(9.6 - 0.5 * 0.05) @@ -461,12 +487,16 @@ def test_the_stage_gives_the_layer_the_config_s_gap_and_both_images(view): def test_mono_in_the_stage_sends_the_left_image_to_both_eyes(view): stage, layer, press = view stage.step() + sent = len(layer.submitted) press(Action.MONO_STEREO) - stage.step() - stage._unsubmitted = True # the picture is sent again with the next image - stage.step() + stage.step() # no new image: the one on display is sent again + assert len(layer.submitted) == sent + 1 left, right = layer.submitted[-1] assert left is right and layer.gaps_mm == [15.0, 0.0] + press(Action.MONO_STEREO) + stage.step() + left, right = layer.submitted[-1] + assert left is not right and layer.gaps_mm == [15.0, 0.0, 15.0] def test_a_lock_mode_press_changes_the_stage_s_placement(view): From 3a620952db680af7cdd56ffe685a280585949493 Mon Sep 17 00:00:00 2001 From: Jun-Jee Chao Date: Tue, 1 Dec 2026 18:13:48 -0800 Subject: [PATCH 4/5] test(examples/televiz): two action tests that could pass for the wrong reason Co-Authored-By: Claude Fable 5.2 Signed-off-by: Jun-Jee Chao --- tests/python/examples/televiz/test_actions.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/python/examples/televiz/test_actions.py b/tests/python/examples/televiz/test_actions.py index e8cec4bb8c..eeacfba098 100644 --- a/tests/python/examples/televiz/test_actions.py +++ b/tests/python/examples/televiz/test_actions.py @@ -441,6 +441,8 @@ def test_a_new_viewpoint_ignores_actions_from_before_it_existed(): stream.post(Action.RECENTER, SOURCE_TTY_KEY) vp = anchored(stream) epoch = vp.anchor_epoch + # Its first frame seated it once, as it does with nothing posted before. + assert epoch == anchored(ActionStream()).anchor_epoch vp.update(eyes(yaw_deg=20.0), T_map_from_cam=np.eye(4)) assert vp.anchor_epoch == epoch @@ -534,8 +536,9 @@ def close(self): def test_the_controller_is_read_once_per_frame_and_its_press_acts_that_frame(): stream = ActionStream() controller = Controller(stream) + # No automatic recenter: only the press can move the anchor. vp = Viewpoint( - ViewpointConfig(recenter_on_first_pose=False), + ViewpointConfig(recenter_on_first_pose=False, auto_relatch=False), controller=controller, actions=stream, ) From f6087d215f27b9b22ad22d353dbbdd42c2a036c1 Mon Sep 17 00:00:00 2001 From: Jun-Jee Chao Date: Tue, 1 Dec 2026 21:14:09 -0800 Subject: [PATCH 5/5] test(examples/televiz): scipy and Pillow for the tests' environment The placement and view-control tests import camera_viz's placements and controls, which use scipy's Rotation and draw their panel with PIL. The tests' own environment listed neither, so they failed to import in CI. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Jun-Jee Chao --- tests/python/examples/televiz/pyproject.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/python/examples/televiz/pyproject.toml b/tests/python/examples/televiz/pyproject.toml index fd86fabe7b..5448653114 100644 --- a/tests/python/examples/televiz/pyproject.toml +++ b/tests/python/examples/televiz/pyproject.toml @@ -13,6 +13,10 @@ dev = [ "pyyaml>=6.0", # Calibration loading and the rectification maps in test_rectify.py. "opencv-python>=4.5,<5", + # The picture is placed by camera_viz's placements, which use Rotation. + "scipy>=1.15", + # camera_viz's controls draw their panel with PIL. + "pillow>=10.0", ] [tool.pytest.ini_options]