From 91661551d096d68916d9f2c216e248dbbbc819ff Mon Sep 17 00:00:00 2001 From: Robert Brenick Date: Mon, 9 Nov 2026 10:24:53 -0600 Subject: [PATCH 1/8] GUI: upgrade NiceGUI and add a satellite map view to the control panel NiceGUI 1.4.8 is replaced by NiceGUI 3.19.x on Python 3.10 (Ubuntu 22.04, ROS 2 Humble) and NiceGUI 4.x on Python >= 3.11 (Ubuntu 24.04 Jazzy and newer). Both share one API, so no compatibility shims are needed. On Python < 3.10 (ROS 2 Foxy) the GUI dependencies are skipped and the launch files start ATOS without the GUI. - Port to the NiceGUI 3/4 API: ui.navigate.to, Quasar classes instead of .tailwind, no auto-index client, AG Grid object rowSelection and get_selected_rows(), sanitize=False for trusted ui.html markup. - anyio >= 4.14.2 in the shared venv on Python >= 3.10 (required by NiceGUI). - Serve atos_gui/static in normal mode as well as fleet mode. Map view on /control: - Esri World Imagery (no API key), OpenStreetMap or a custom tile URL. Resizable, and fits never zoom past the deepest available imagery. - Scenario trajectories (/atos/object_/path) loaded after Init, and connected objects (/atos/object_monitor) drawn as heading-rotated markers that turn grey when monitor data stops. - Exact local frame -> WGS84 conversion with the same PROJ tmerc definition as EsminiAdapter. Headings are converted to true bearings, including meridian convergence. - User settings for trajectory width/style/opacity, marker size/style, labels and per-object colours, persisted on the ATOS host. Tests: 23 pytest tests for the geodesy and the ROS data source. They run under colcon test (pyproj from rosdep, pytest declared as a test extra). Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 + atos/launch/launch_utils/launch_base.py | 22 +- atos_gui/atos_gui/configpanel/configpanel.py | 2 +- .../atos_gui/configpanel/local_file_picker.py | 15 +- .../atos_gui/controlpanel/controlpanel.py | 13 +- atos_gui/atos_gui/main.py | 10 +- atos_gui/atos_gui/mapview/__init__.py | 0 atos_gui/atos_gui/mapview/geo.py | 125 +++++ atos_gui/atos_gui/mapview/map_data.py | 317 +++++++++++++ atos_gui/atos_gui/mapview/map_view.py | 247 ++++++++++ atos_gui/atos_gui/objectpanel/objectpanel.py | 7 +- atos_gui/atos_gui/static/atos_map.js | 433 ++++++++++++++++++ atos_gui/package.xml | 7 + atos_gui/requirements.txt | 8 +- atos_gui/setup.py | 2 + atos_gui/test/test_geo.py | 132 ++++++ atos_gui/test/test_map_data.py | 253 ++++++++++ docs/Usage/GUI/controlpanel.md | 20 +- scripts/installation/install_deps.sh | 7 +- scripts/installation/requirements.txt | 5 +- 20 files changed, 1602 insertions(+), 26 deletions(-) create mode 100644 atos_gui/atos_gui/mapview/__init__.py create mode 100644 atos_gui/atos_gui/mapview/geo.py create mode 100644 atos_gui/atos_gui/mapview/map_data.py create mode 100644 atos_gui/atos_gui/mapview/map_view.py create mode 100644 atos_gui/atos_gui/static/atos_map.js create mode 100644 atos_gui/test/test_geo.py create mode 100644 atos_gui/test/test_map_data.py diff --git a/.gitignore b/.gitignore index 56bf0e00d..88e44b215 100644 --- a/.gitignore +++ b/.gitignore @@ -62,3 +62,6 @@ log/ # *.env + +# NiceGUI storage (map view settings) when the GUI is run from the repository +.nicegui/ diff --git a/atos/launch/launch_utils/launch_base.py b/atos/launch/launch_utils/launch_base.py index 22113737b..da84587ee 100644 --- a/atos/launch/launch_utils/launch_base.py +++ b/atos/launch/launch_utils/launch_base.py @@ -1,5 +1,6 @@ # Don't launch this file directly, rather use the launch files one level up instead import copy +import importlib.util import os from pathlib import Path @@ -32,8 +33,8 @@ def get_files(): return validate_atos_dir() -def get_pythonpath_setup_action(): - venv_site_packages = ( +def get_venv_site_packages(): + return ( Path.home() / ".local" / "share" @@ -43,6 +44,17 @@ def get_pythonpath_setup_action(): / (f"python{os.sys.version_info.major}.{os.sys.version_info.minor}") / "site-packages" ) + + +def gui_dependencies_available(): + """The GUI needs NiceGUI, which is only installed on Python >= 3.10 (not ROS 2 Foxy).""" + if importlib.util.find_spec("nicegui") is not None: + return True + return (get_venv_site_packages() / "nicegui").is_dir() + + +def get_pythonpath_setup_action(): + venv_site_packages = get_venv_site_packages() if not venv_site_packages.exists(): return None @@ -167,6 +179,12 @@ def get_base_nodes(include_gui=True): if pythonpath_setup is not None: base_nodes.insert(2, pythonpath_setup) + if include_gui and not gui_dependencies_available(): + logging.get_logger("launch").warning( + "NiceGUI is not installed (the ATOS GUI requires Python >= 3.10), skipping the GUI." + ) + include_gui = False + if include_gui: base_nodes.insert( 3 if pythonpath_setup is not None else 2, diff --git a/atos_gui/atos_gui/configpanel/configpanel.py b/atos_gui/atos_gui/configpanel/configpanel.py index bd86a4623..3091b46fb 100644 --- a/atos_gui/atos_gui/configpanel/configpanel.py +++ b/atos_gui/atos_gui/configpanel/configpanel.py @@ -570,4 +570,4 @@ def refresh(self) -> None: threading.Thread( target=self.fetch_parameters_list, args=(self.parameter_clients,) ).start() - ui.open("/config") + ui.navigate.to("/config") diff --git a/atos_gui/atos_gui/configpanel/local_file_picker.py b/atos_gui/atos_gui/configpanel/local_file_picker.py index 41b7a4c02..5ca2288fb 100644 --- a/atos_gui/atos_gui/configpanel/local_file_picker.py +++ b/atos_gui/atos_gui/configpanel/local_file_picker.py @@ -48,7 +48,9 @@ def __init__( ui.aggrid( { "columnDefs": [{"field": "name", "headerName": "File"}], - "rowSelection": "multiple" if multiple else "single", + "rowSelection": { + "mode": "multiRow" if multiple else "singleRow" + }, }, html_columns=[0], ) @@ -83,7 +85,7 @@ def update_grid(self) -> None: paths.sort(key=lambda p: p.name.lower()) paths.sort(key=lambda p: not p.is_dir()) - self.grid.options["rowData"] = [ + rows = [ { "name": f"📁 {p.name}" if p.is_dir() else p.name, "path": str(p), @@ -96,14 +98,15 @@ def update_grid(self) -> None: or self.upper_limit is not None and self.path != self.upper_limit ): - self.grid.options["rowData"].insert( + rows.insert( 0, { "name": "📁 ..", "path": str(self.path.parent), }, ) - self.grid.update() + # Assigning to the element's options updates the grid (NiceGUI >= 3.0). + self.grid.options["rowData"] = rows def handle_double_click(self, e: events.GenericEventArguments) -> None: """Handle a double click on a file or directory.""" @@ -115,7 +118,5 @@ def handle_double_click(self, e: events.GenericEventArguments) -> None: async def _handle_ok(self): """Handle the OK button click.""" - rows = await ui.run_javascript( - f"getElement({self.grid.id}).gridOptions.api.getSelectedRows()" - ) + rows = await self.grid.get_selected_rows() self.submit([r["path"] for r in rows]) diff --git a/atos_gui/atos_gui/controlpanel/controlpanel.py b/atos_gui/atos_gui/controlpanel/controlpanel.py index 2fb6445ca..e302cdb12 100644 --- a/atos_gui/atos_gui/controlpanel/controlpanel.py +++ b/atos_gui/atos_gui/controlpanel/controlpanel.py @@ -9,6 +9,8 @@ from std_msgs.msg import Empty from atos_interfaces.srv import * +from atos_gui.mapview.map_data import MapDataSource +from atos_gui.mapview.map_view import MapView QOS = rclpy.qos.QoSProfile(depth=10) @@ -54,12 +56,17 @@ def __init__(self) -> None: ) self.OBC_state = {"state": "UNDEFINED"} + self.OBC_state_number = None self.lost_connection = True + self.map_data = MapDataSource( + self, get_control_state=lambda: self.OBC_state_number + ) + @ui.page(path="/control", title="ATOS Control Panel") def render_page(): with ui.row().bind_visibility_from(self, "lost_connection"): - ui.label("Lost connection to ATOS...").tailwind.text_color("red") + ui.label("Lost connection to ATOS...").classes("text-red") with ui.row(): ui.button( "Abort", @@ -113,6 +120,7 @@ def render_page(): on_click=lambda: self.reloadObjectSettingsPub.publish(Empty()), color="grey", ) + MapView(self.map_data) def get_object_control_state_callback(self): # Call the service @@ -133,4 +141,5 @@ def get_object_control_state_callback_done(self, future): except Exception as e: self.get_logger().info("Service call failed %r" % (e,)) else: - self.OBC_state["state"] = OBC_STATES[response.state] + self.OBC_state_number = response.state + self.OBC_state["state"] = OBC_STATES.get(response.state, "UNDEFINED") diff --git a/atos_gui/atos_gui/main.py b/atos_gui/atos_gui/main.py index e78bde436..ce2f8106b 100644 --- a/atos_gui/atos_gui/main.py +++ b/atos_gui/atos_gui/main.py @@ -151,9 +151,6 @@ def _on_state(self, msg: String) -> None: def render_atosfleetmanagement_pages() -> None: - if FLEET_STATIC_DIR.exists(): - app.add_static_files(FLEET_STATIC_ROUTE, str(FLEET_STATIC_DIR)) - @ui.page(path="/", title="TruckObjectGUI") def render_home() -> None: ui.add_head_html( @@ -208,7 +205,8 @@ def render_home() -> None: ) map_id = "fleet-road-map" ui.html( - f'
' + f'
', + sanitize=False, # trusted static markup; keep id/style ) ui.timer( @@ -295,6 +293,10 @@ def configure_app() -> None: if APP_CONFIGURED: return + # Scripts for the fleet road map and the control panel map view. + if FLEET_STATIC_DIR.exists(): + app.add_static_files(FLEET_STATIC_ROUTE, str(FLEET_STATIC_DIR)) + if FLEET_MODE: render_atosfleetmanagement_pages() else: diff --git a/atos_gui/atos_gui/mapview/__init__.py b/atos_gui/atos_gui/mapview/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/atos_gui/atos_gui/mapview/geo.py b/atos_gui/atos_gui/mapview/geo.py new file mode 100644 index 000000000..665067922 --- /dev/null +++ b/atos_gui/atos_gui/mapview/geo.py @@ -0,0 +1,125 @@ +"""This Source Code Form is subject to the terms of the Mozilla Public +License, v. 2.0. If a copy of the MPL was not distributed with this +file, You can obtain one at https://mozilla.org/MPL/2.0/. +""" + +"""Conversions from the ATOS local test frame to WGS84 for the map view. + +ATOS' local frame (see EsminiAdapter, esminiadapter.cpp) is a transverse Mercator +projection centred on the test origin: + + +proj=tmerc +lat_0= +lon_0= +datum=WGS84 +units=m + +x is grid east, y is grid north (metres), and headings are ENU yaw: counter-clockwise +from +x. Using the same PROJ definition here makes the inverse exact, unlike the +flat-earth approximation (llhOffsetMeters) behind the gnss_path / gnss_fix topics. + +Leaflet's Web Mercator display is conformal and always north-up, so a marker rotated +clockwise on screen by the true geodesic bearing points the right way. +""" + +import math +import threading + +import numpy as np +from pyproj import Geod, Transformer + +WGS84 = Geod(ellps="WGS84") + +# Length of the step used to turn a heading into a geodesic bearing. The tmerc +# scale/curvature over one metre is far below anything visible on a map. +_HEADING_STEP_M = 1.0 + + +def yaw_from_quaternion(x: float, y: float, z: float, w: float) -> float: + """Yaw (rotation about z) of a quaternion, in radians, CCW from +x.""" + return math.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z)) + + +class LocalFrame: + """The ATOS local frame for one test origin.""" + + def __init__(self, origin_lat: float, origin_lon: float) -> None: + if not (-90.0 <= origin_lat <= 90.0 and -180.0 <= origin_lon <= 180.0): + raise ValueError(f"Invalid origin {origin_lat}, {origin_lon}") + self.origin_lat = origin_lat + self.origin_lon = origin_lon + self.proj_string = ( + f"+proj=tmerc +lat_0={origin_lat!r} +lon_0={origin_lon!r} " + "+datum=WGS84 +units=m" + ) + self._to_wgs84 = Transformer.from_crs( + self.proj_string, "EPSG:4326", always_xy=True + ) + self._from_wgs84 = Transformer.from_crs( + "EPSG:4326", self.proj_string, always_xy=True + ) + # pyproj Transformer objects must not be used from several threads at once. + self._lock = threading.Lock() + + def to_lonlat(self, xs, ys) -> tuple[np.ndarray, np.ndarray]: + """Local x/y (metres) to WGS84 longitude/latitude (degrees).""" + return self._transform(self._to_wgs84, xs, ys) + + def from_lonlat(self, lons, lats) -> tuple[np.ndarray, np.ndarray]: + """WGS84 longitude/latitude (degrees) to local x/y (metres).""" + return self._transform(self._from_wgs84, lons, lats) + + def _transform(self, transformer: Transformer, a, b) -> tuple[np.ndarray, np.ndarray]: + a = np.asarray(a, dtype=float) + b = np.asarray(b, dtype=float) + with self._lock: + if a.size == 1: + # pyproj's single-point fast path calls float() on its inputs, which NumPy + # deprecates for size-1 arrays (pyproj 3.7, the last for Python 3.10). + p, q = transformer.transform(float(a.item()), float(b.item())) + return np.full(a.shape, p), np.full(b.shape, q) + p, q = transformer.transform(a, b) + return np.asarray(p), np.asarray(q) + + def poses_to_geo(self, xs, ys, yaws) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Local poses to (lat, lon, bearing). + + The bearing is in degrees clockwise from true north, in [0, 360). It is the + geodesic azimuth from each position to a point one step ahead along the + heading, so it includes the meridian convergence exactly. + """ + xs = np.atleast_1d(np.asarray(xs, dtype=float)) + ys = np.atleast_1d(np.asarray(ys, dtype=float)) + yaws = np.atleast_1d(np.asarray(yaws, dtype=float)) + lons, lats = self.to_lonlat(xs, ys) + lons_ahead, lats_ahead = self.to_lonlat( + xs + _HEADING_STEP_M * np.cos(yaws), ys + _HEADING_STEP_M * np.sin(yaws) + ) + if lons.size == 1: + # Same single-point fast path as in _transform. + azimuth, _, _ = WGS84.inv(lons.item(), lats.item(), lons_ahead.item(), lats_ahead.item()) + azimuths = np.full(lons.shape, azimuth) + else: + azimuths, _, _ = WGS84.inv(lons, lats, lons_ahead, lats_ahead) + bearings = np.mod(np.asarray(azimuths, dtype=float), 360.0) + return lats, lons, bearings + + +def decimate(xs, ys, min_spacing_m: float = 0.1) -> np.ndarray: + """Indices of points at least min_spacing_m apart (first and last always kept). + + Trajectories from esmini are densely sampled; dropping points closer than a few + centimetres keeps the browser payload small without visibly changing the line. + """ + xs = np.asarray(xs, dtype=float) + ys = np.asarray(ys, dtype=float) + n = len(xs) + if n <= 2: + return np.arange(n) + keep = [0] + last_x, last_y = xs[0], ys[0] + limit = min_spacing_m * min_spacing_m + for i in range(1, n - 1): + dx = xs[i] - last_x + dy = ys[i] - last_y + if dx * dx + dy * dy >= limit: + keep.append(i) + last_x, last_y = xs[i], ys[i] + keep.append(n - 1) + return np.asarray(keep) diff --git a/atos_gui/atos_gui/mapview/map_data.py b/atos_gui/atos_gui/mapview/map_data.py new file mode 100644 index 000000000..5a82afbc1 --- /dev/null +++ b/atos_gui/atos_gui/mapview/map_data.py @@ -0,0 +1,317 @@ +"""This Source Code Form is subject to the terms of the Mozilla Public +License, v. 2.0. If a copy of the MPL was not distributed with this +file, You can obtain one at https://mozilla.org/MPL/2.0/. +""" + +"""ROS side of the map view: collects the test origin, scenario trajectories and live +object poses, and converts them to WGS84 for the browser. + +Data sources (all in the ATOS local frame, see geo.py): +- /atos/get_test_origin GeoPose of the local frame origin (EsminiAdapter) +- /atos/get_object_ids object ids and names (OpenScenarioGateway) +- /atos/object_/path nav_msgs/Path, transient local (EsminiAdapter/ObjectControl) +- /atos/object_monitor atos_interfaces/Monitor for all objects (ObjectControl) +- /atos/connected_object_ids ids of connected objects, every second (ObjectControl) +- /atos/state_change ObjectControl state transitions +""" + +import math +import threading +import time + +import rclpy +from atos_interfaces.msg import Monitor, ObjectIdArray, StateChange +from atos_interfaces.srv import GetObjectIds, GetTestOrigin +from nav_msgs.msg import Path +from rclpy.callback_groups import MutuallyExclusiveCallbackGroup +from rclpy.node import Node +from rclpy.qos import DurabilityPolicy, QoSProfile + +from .geo import LocalFrame, decimate, yaw_from_quaternion + +# ObjectControl states as returned by GetObjectControlState / StateChange (OBCState_t). +STATE_IDLE = 1 +STATE_INITIALIZED = 2 + +ORIGIN_TIMEOUT_S = 5.0 +IDS_TIMEOUT_S = 5.0 +CONNECTED_IDS_MAX_AGE_S = 3.0 +MONITOR_STALE_S = 2.0 +MONITOR_FORGET_S = 10.0 + +PATH_QOS = QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL) +LATEST_QOS = QoSProfile(depth=1) + + +class MapDataSource: + """Thread-safe store of map data, fed by ROS callbacks and read by the UI.""" + + def __init__(self, node: Node, get_control_state=lambda: None) -> None: + self.node = node + self._get_control_state = get_control_state + self._lock = threading.Lock() + + self.frame: LocalFrame | None = None + self.status = "Waiting for a scenario to be initialized..." + self.object_names: dict[int, str] = {} + # Raw trajectories in the local frame, per object id: (xs, ys). + self._raw_paths: dict[int, tuple[list[float], list[float]]] = {} + self._geo_paths: dict[int, list[list[float]]] = {} + self.traj_version = 0 + self._monitors: dict[int, dict] = {} + self._connected_ids: set[int] = set() + self._connected_ids_stamp = 0.0 + + self._loading = False + self._needs_load = True + self._path_subs: dict[int, object] = {} + + # A separate callback group, so the control panel's blocking state polling + # cannot stall map updates (and the callbacks below run one at a time). + self._cb_group = cb = MutuallyExclusiveCallbackGroup() + self._ids_client = node.create_client( + GetObjectIds, "/atos/get_object_ids", callback_group=cb + ) + self._origin_client = node.create_client( + GetTestOrigin, "/atos/get_test_origin", callback_group=cb + ) + node.create_subscription( + StateChange, "/atos/state_change", self._on_state_change, + QoSProfile(depth=10), callback_group=cb, + ) + node.create_subscription( + Monitor, "/atos/object_monitor", self._on_monitor, LATEST_QOS, callback_group=cb + ) + node.create_subscription( + ObjectIdArray, "/atos/connected_object_ids", self._on_connected_ids, + QoSProfile(depth=10), callback_group=cb, + ) + node.create_timer(1.0, self._maintain, callback_group=cb) + + # ------------------------------------------------------------------ loading + + def request_reload(self) -> None: + with self._lock: + self._needs_load = True + + def _maintain(self) -> None: + """Start a (re)load once ObjectControl has initialized a scenario. + + get_test_origin busy-waits inside EsminiAdapter until an origin is set, which + only happens while a scenario is loaded, so it is only called from INITIALIZED on. + """ + state = self._get_control_state() + with self._lock: + if self._loading or not self._needs_load: + return + if state is None or state < STATE_INITIALIZED: + return + self._loading = True + self._needs_load = False + self._load_object_ids() + + def _on_state_change(self, msg: StateChange) -> None: + if msg.prev_state == STATE_IDLE and msg.current_state == STATE_INITIALIZED: + self.request_reload() + + def _finish_load(self, status: str) -> None: + with self._lock: + self._loading = False + self.status = status + self.node.get_logger().info(f"Map view: {status}") + + def _call_with_timeout(self, client, request, timeout_s, on_result, what) -> None: + if not client.service_is_ready(): + self._finish_load(f"{what} service is not available") + with self._lock: + self._needs_load = True # try again on the next tick + return + future = client.call_async(request) + timer = None + + def stop_timer(): + if timer is not None and not timer.is_canceled(): + timer.cancel() + self.node.destroy_timer(timer) + + def on_timeout(): + stop_timer() + if not future.done(): + client.remove_pending_request(future) + self._finish_load(f"Timed out waiting for {what}") + + def on_done(fut): + stop_timer() + if fut.cancelled(): + return + try: + result = fut.result() + except Exception as e: # noqa: BLE001 - report any service failure + self._finish_load(f"{what} failed: {e!r}") + return + on_result(result) + + timer = self.node.create_timer(timeout_s, on_timeout, callback_group=self._cb_group) + future.add_done_callback(on_done) + + def _load_object_ids(self) -> None: + self._call_with_timeout( + self._ids_client, GetObjectIds.Request(), IDS_TIMEOUT_S, self._on_object_ids, "object ids" + ) + + def _on_object_ids(self, result) -> None: + names = {} + for index, object_id in enumerate(result.ids): + name = result.names[index] if index < len(result.names) else "" + names[int(object_id)] = name or f"Object {object_id}" + with self._lock: + self.object_names = names + self._call_with_timeout( + self._origin_client, GetTestOrigin.Request(), ORIGIN_TIMEOUT_S, self._on_origin, "test origin" + ) + + def _on_origin(self, result) -> None: + position = result.origin.position + lat, lon = position.latitude, position.longitude + if not result.success or not (math.isfinite(lat) and math.isfinite(lon)): + self._finish_load("Scenario has no geo-reference, cannot place overlays") + return + try: + frame = LocalFrame(lat, lon) + except ValueError as e: + self._finish_load(str(e)) + return + with self._lock: + frame_changed = self.frame is None or ( + (self.frame.origin_lat, self.frame.origin_lon) != (lat, lon) + ) + self.frame = frame + ids = set(self.object_names) + for object_id in list(self._raw_paths): + if object_id not in ids: + del self._raw_paths[object_id] + self._geo_paths = { + object_id: self._convert_path(frame, *raw) + for object_id, raw in self._raw_paths.items() + } + if frame_changed: + self._monitors.clear() + self.traj_version += 1 + self._update_path_subscriptions(ids) + self._finish_load(f"Origin {lat:.7f}, {lon:.7f}") + + def _update_path_subscriptions(self, ids: set[int]) -> None: + for object_id in list(self._path_subs): + if object_id not in ids: + self.node.destroy_subscription(self._path_subs.pop(object_id)) + for object_id in ids: + if object_id not in self._path_subs: + self._path_subs[object_id] = self.node.create_subscription( + Path, + f"/atos/object_{object_id}/path", + lambda msg, object_id=object_id: self._on_path(object_id, msg), + PATH_QOS, + callback_group=self._cb_group, + ) + + # ---------------------------------------------------------------- callbacks + + @staticmethod + def _convert_path(frame: LocalFrame, xs, ys) -> list[list[float]]: + if not xs: + return [] + keep = decimate(xs, ys) + lons, lats = frame.to_lonlat([xs[i] for i in keep], [ys[i] for i in keep]) + return [[round(float(lat), 9), round(float(lon), 9)] for lat, lon in zip(lats, lons)] + + def _on_path(self, object_id: int, msg: Path) -> None: + xs = [pose.pose.position.x for pose in msg.poses] + ys = [pose.pose.position.y for pose in msg.poses] + with self._lock: + frame = self.frame + geo = self._convert_path(frame, xs, ys) if frame is not None else None + with self._lock: + self._raw_paths[object_id] = (xs, ys) + if geo is not None and frame is self.frame: + self._geo_paths[object_id] = geo + self.traj_version += 1 + + def _on_monitor(self, msg: Monitor) -> None: + pose = msg.pose.pose + q = pose.orientation + entry = { + "x": pose.position.x, + "y": pose.position.y, + "yaw": yaw_from_quaternion(q.x, q.y, q.z, q.w), + "speed": math.hypot(msg.velocity.twist.linear.x, msg.velocity.twist.linear.y), + "state": int(msg.object_state.state), + "received": time.monotonic(), + } + with self._lock: + self._monitors[int(msg.atos_header.object_id)] = entry + + def _on_connected_ids(self, msg: ObjectIdArray) -> None: + with self._lock: + self._connected_ids = {int(i) for i in msg.ids} + self._connected_ids_stamp = time.monotonic() + + # ------------------------------------------------------------------ for the UI + + def snapshot(self, known_traj_version: int | None) -> dict: + """Data for one browser update. + + Trajectories are only included when they changed since known_traj_version. + Monitor poses are converted here, at the UI rate, not at the MONR rate. + """ + now = time.monotonic() + with self._lock: + frame = self.frame + names = dict(self.object_names) + connected_fresh = now - self._connected_ids_stamp < CONNECTED_IDS_MAX_AGE_S + connected = set(self._connected_ids) if connected_fresh else set() + for object_id in [i for i, m in self._monitors.items() if now - m["received"] > MONITOR_FORGET_S]: + del self._monitors[object_id] + monitors = {i: dict(m) for i, m in self._monitors.items()} + payload = { + "status": self.status, + "origin": [frame.origin_lat, frame.origin_lon] if frame else None, + "traj_version": self.traj_version, + } + if known_traj_version != self.traj_version: + payload["trajectories"] = [ + {"id": object_id, "name": names.get(object_id, f"Object {object_id}"), "latlngs": latlngs} + for object_id, latlngs in sorted(self._geo_paths.items()) + if latlngs + ] + + objects = [] + if frame is not None and monitors: + # Show connected objects; if the connected list is not being published, + # fall back to any object that reports monitor data. + ids = sorted(i for i in monitors if i in connected or not connected_fresh) + if ids: + lats, lons, bearings = frame.poses_to_geo( + [monitors[i]["x"] for i in ids], + [monitors[i]["y"] for i in ids], + [monitors[i]["yaw"] for i in ids], + ) + for k, object_id in enumerate(ids): + m = monitors[object_id] + objects.append( + { + "id": object_id, + "name": names.get(object_id, f"Object {object_id}"), + "lat": round(float(lats[k]), 9), + "lon": round(float(lons[k]), 9), + "bearing": round(float(bearings[k]), 2), + "speed": round(m["speed"], 2), + "stale": now - m["received"] > MONITOR_STALE_S, + } + ) + payload["objects"] = objects + return payload + + @property + def object_ids(self) -> list[int]: + with self._lock: + return sorted(set(self.object_names) | set(self._geo_paths)) diff --git a/atos_gui/atos_gui/mapview/map_view.py b/atos_gui/atos_gui/mapview/map_view.py new file mode 100644 index 000000000..516b2a353 --- /dev/null +++ b/atos_gui/atos_gui/mapview/map_view.py @@ -0,0 +1,247 @@ +"""This Source Code Form is subject to the terms of the Mozilla Public +License, v. 2.0. If a copy of the MPL was not distributed with this +file, You can obtain one at https://mozilla.org/MPL/2.0/. +""" + +"""NiceGUI part of the map view: a resizable satellite map with scenario +trajectories and live, heading-rotated object markers, plus style settings. + +The overlays are drawn by static/atos_map.js; this module creates the ui.leaflet +element, pushes MapDataSource snapshots to it at UI_RATE_S, and keeps the user's +style settings (persisted in app.storage.general). +""" + +import copy +import json + +from nicegui import app, ui + +from .map_data import MapDataSource + +STATIC_ROUTE = "/atos_gui_static" +MAP_JS_VERSION = "20261105-2" +UI_RATE_S = 0.1 +SETTINGS_KEY = "atos_map_settings" + +# Bright colours that stay readable on aerial imagery. +PALETTE = ["#ffd400", "#00e5ff", "#ff4fd8", "#7cfc00", "#ff8c00", "#ffffff", "#ff3b3b", "#9b8cff"] + +DEFAULT_SETTINGS = { + "trajectory": {"width": 3, "dash": "solid", "opacity": 0.9}, + "marker": {"shape": "arrow", "size": 32, "labels": True}, + "base": "satellite", + "customUrl": "", + "colorOverrides": {}, +} + +DASH_OPTIONS = {"solid": "Solid", "dashed": "Dashed", "dotted": "Dotted", "dashdot": "Dash-dot"} +SHAPE_OPTIONS = {"arrow": "Arrow", "chevron": "Chevron", "vehicle": "Vehicle", "circle": "Circle + heading"} +BASE_OPTIONS = {"satellite": "Satellite (Esri World Imagery)", "osm": "OpenStreetMap", "custom": "Custom tile URL"} + + +def load_settings() -> dict: + settings = copy.deepcopy(DEFAULT_SETTINGS) + stored = app.storage.general.get(SETTINGS_KEY) or {} + for key, value in stored.items(): + if isinstance(value, dict) and isinstance(settings.get(key), dict): + settings[key].update(value) + elif key in settings: + settings[key] = value + return settings + + +def save_settings(settings: dict) -> None: + app.storage.general[SETTINGS_KEY] = copy.deepcopy(settings) + + +class MapView: + """One map view instance, created inside a page function (one per browser tab).""" + + def __init__(self, data: MapDataSource) -> None: + self.data = data + self.settings = load_settings() + self._sent_traj_version = None + self._sent_origin = None + self._style_sent = False + self._known_ids: list[int] = [] + self._color_inputs: dict[int, ui.color_input] = {} + + ui.add_head_html(f'') + + with ui.card().classes("w-full"): + with ui.row().classes("w-full items-center gap-2"): + ui.label("Map").classes("text-lg font-medium") + self.status_label = ui.label().classes("text-sm text-grey-7") + ui.space() + self.follow_select = ui.select( + {"": "Follow: off"}, value="", on_change=self._on_follow + ).props("dense outlined options-dense").classes("w-44") + ui.button("Fit to scenario", icon="fit_screen", on_click=self._fit).props("flat dense") + + with ui.row().classes("w-full items-start gap-4 md:flex-nowrap"): + # Drag the bottom-right corner to resize; atos_map.js reflows the map + # and remembers the size in the browser. + with ui.element("div").style( + "resize: both; overflow: hidden; width: 100%; max-width: 100%;" + "height: 60vh; min-height: 250px; min-width: 280px;" + "border-radius: 8px; border: 1px solid rgba(128,128,128,.4);" + ): + self.map = ui.leaflet( + center=(0.0, 0.0), zoom=2, options={"maxZoom": 22} + ).style("width: 100%; height: 100%;") + # Drop NiceGUI's default OSM layer; base layers are managed in JS. + # Not initialized yet, so clearing the Python-side list is enough. + self.map.layers.clear() + + with ui.column().classes("w-full md:w-72 shrink-0"): + self._build_settings() + + ui.timer(UI_RATE_S, self._tick) + + # ---------------------------------------------------------------- settings + + def _build_settings(self) -> None: + s = self.settings + with ui.expansion("Map settings", icon="tune").classes("w-full").props("dense"): + ui.label("Trajectory").classes("text-sm font-medium") + ui.label().bind_text_from(s["trajectory"], "width", lambda v: f"Width: {v} px").classes("text-xs") + ui.slider(min=1, max=12, step=1, value=s["trajectory"]["width"], + on_change=lambda e: self._set("trajectory", "width", e.value)) + ui.select(DASH_OPTIONS, label="Line style", value=s["trajectory"]["dash"], + on_change=lambda e: self._set("trajectory", "dash", e.value)).classes("w-full") + ui.label().bind_text_from(s["trajectory"], "opacity", lambda v: f"Opacity: {round(v * 100)} %").classes("text-xs") + ui.slider(min=0.1, max=1.0, step=0.05, value=s["trajectory"]["opacity"], + on_change=lambda e: self._set("trajectory", "opacity", e.value)) + + ui.separator() + ui.label("Object marker").classes("text-sm font-medium") + ui.label().bind_text_from(s["marker"], "size", lambda v: f"Size: {v} px").classes("text-xs") + ui.slider(min=12, max=96, step=2, value=s["marker"]["size"], + on_change=lambda e: self._set("marker", "size", e.value)) + ui.select(SHAPE_OPTIONS, label="Marker style", value=s["marker"]["shape"], + on_change=lambda e: self._set("marker", "shape", e.value)).classes("w-full") + ui.switch("Show labels", value=s["marker"]["labels"], + on_change=lambda e: self._set("marker", "labels", e.value)) + + ui.separator() + ui.label("Object colours").classes("text-sm font-medium") + self.colors_column = ui.column().classes("w-full gap-1") + ui.button("Reset colours", on_click=self._reset_colors).props("flat dense size=sm") + + ui.separator() + ui.label("Base map").classes("text-sm font-medium") + ui.select(BASE_OPTIONS, value=s["base"], + on_change=lambda e: self._set(None, "base", e.value)).classes("w-full") + custom_url = ui.input( + "Custom tile URL", value=s["customUrl"], placeholder="https://host/{z}/{x}/{y}.png" + ).classes("w-full").bind_visibility_from(s, "base", lambda v: v == "custom") + # Apply on blur/enter only, so typing does not reload tiles per keystroke. + for event in ("blur", "keydown.enter"): + custom_url.on(event, lambda: self._set(None, "customUrl", (custom_url.value or "").strip())) + ui.label("Satellite imagery: Esri World Imagery (no API key, attribution required).").classes( + "text-xs text-grey-7") + + def _set(self, group: str | None, key: str, value) -> None: + target = self.settings[group] if group else self.settings + if target.get(key) == value: + return + target[key] = value + save_settings(self.settings) + self._push_style() + + def _object_colors(self) -> dict[str, str]: + overrides = self.settings["colorOverrides"] + return { + str(object_id): overrides.get(str(object_id)) or PALETTE[index % len(PALETTE)] + for index, object_id in enumerate(self._known_ids) + } + + def _set_color(self, object_id: int, color: str) -> None: + if not color: + return + overrides = self.settings["colorOverrides"] + if overrides.get(str(object_id)) == color: + return + overrides[str(object_id)] = color + save_settings(self.settings) + self._push_style() + + def _reset_colors(self) -> None: + self.settings["colorOverrides"] = {} + save_settings(self.settings) + colors = self._object_colors() + for object_id, color_input in self._color_inputs.items(): + color_input.value = colors.get(str(object_id), "") + self._push_style() + + def _rebuild_object_controls(self, names: dict[int, str]) -> None: + colors = self._object_colors() + self.colors_column.clear() + self._color_inputs = {} + with self.colors_column: + if not self._known_ids: + ui.label("No objects yet").classes("text-xs text-grey-7") + for object_id in self._known_ids: + self._color_inputs[object_id] = ui.color_input( + names.get(object_id, f"Object {object_id}"), + value=colors[str(object_id)], + on_change=lambda e, object_id=object_id: self._set_color(object_id, e.value), + ).props("dense").classes("w-full") + options = {"": "Follow: off"} + options.update({str(i): f"Follow: {names.get(i, i)}" for i in self._known_ids}) + self.follow_select.set_options(options, value=self.follow_select.value if self.follow_select.value in options else "") + + def _style_payload(self) -> dict: + s = self.settings + return { + "trajectory": s["trajectory"], + "marker": s["marker"], + "base": s["base"], + "customUrl": s["customUrl"], + "colors": self._object_colors(), + } + + def _js(self, code: str) -> None: + ui.run_javascript(f"window.atosMap ? {code} : false") + + def _push_style(self) -> None: + if self.map.is_initialized: + self._js(f"window.atosMap.setStyle({self.map.id}, {json.dumps(self._style_payload())})") + + # ------------------------------------------------------------------ updates + + def _fit(self) -> None: + self._js(f"window.atosMap.fit({self.map.id})") + + def _on_follow(self, e) -> None: + self._js(f"window.atosMap.follow({self.map.id}, {json.dumps(e.value or '')})") + + async def _tick(self) -> None: + if not self.map.is_initialized: + return + if not self._style_sent: + # Leaflet and atos_map.js load asynchronously; retry until both are there. + ok = await ui.run_javascript( + f"window.atosMap ? window.atosMap.setStyle({self.map.id}, {json.dumps(self._style_payload())}) : false" + ) + self._style_sent = bool(ok) + if not self._style_sent: + return + + payload = self.data.snapshot(self._sent_traj_version) + self.status_label.text = payload["status"] + + ids = self.data.object_ids + if ids != self._known_ids: + self._known_ids = ids + self._rebuild_object_controls(dict(self.data.object_names)) + self._push_style() + + if payload["origin"] != self._sent_origin: + if self._sent_origin is not None: + self._js(f"window.atosMap.reset({self.map.id})") + self._sent_origin = payload["origin"] + payload["trajectories"] = payload.get("trajectories") or self.data.snapshot(None)["trajectories"] + + self._js(f"window.atosMap.update({self.map.id}, {json.dumps(payload)})") + self._sent_traj_version = payload["traj_version"] diff --git a/atos_gui/atos_gui/objectpanel/objectpanel.py b/atos_gui/atos_gui/objectpanel/objectpanel.py index f12d1eb70..a87a2429e 100644 --- a/atos_gui/atos_gui/objectpanel/objectpanel.py +++ b/atos_gui/atos_gui/objectpanel/objectpanel.py @@ -1,4 +1,4 @@ -from nicegui import Client, ui +from nicegui import ui from rclpy.node import Node from atos_interfaces.srv import GetObjectIds, GetObjectIp, SetObjectIp @@ -28,9 +28,6 @@ def __init__(self) -> None: self.object_id_ip_map = {} self.get_object_ids() - with Client.auto_index_client: - pass - @ui.page(path="/object", title="ATOS Object Panel") def render_objectpanel() -> None: """Render the object panel page. Generates a list of objects and their IPs.""" @@ -160,4 +157,4 @@ def update_object_ip_result(self, result): def refresh(self): """Refreshes the object panel by fetching all object IDs and their IPs in the current scenario.""" self.get_object_ids() - ui.open("/object") + ui.navigate.to("/object") diff --git a/atos_gui/atos_gui/static/atos_map.js b/atos_gui/atos_gui/static/atos_map.js new file mode 100644 index 000000000..88adc1139 --- /dev/null +++ b/atos_gui/atos_gui/static/atos_map.js @@ -0,0 +1,433 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + * + * Map view overlays for the ATOS control panel. Works on the Leaflet map created + * by NiceGUI's ui.leaflet (reached through getElement(id).map, Leaflet as window.L). + * + * All positions arrive as WGS84 lat/lon and headings as geodesic bearings + * (degrees clockwise from true north), already converted from the ATOS local + * frame in Python (atos_gui/mapview/geo.py). Web Mercator is conformal and the + * map is north-up, so rotating a north-pointing icon clockwise by the bearing is + * geographically correct. + */ +(function () { + "use strict"; + + const SIZE_STORAGE_KEY = "atosMapSize"; + + const BASE_LAYERS = { + satellite: { + url: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", + options: { + maxNativeZoom: 19, + maxZoom: 22, + attribution: + "Tiles © Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community", + }, + }, + osm: { + url: "https://tile.openstreetmap.org/{z}/{x}/{y}.png", + options: { + maxNativeZoom: 19, + maxZoom: 22, + attribution: '© OpenStreetMap contributors', + }, + }, + }; + + // Every shape points north (up) in a 100x100 box centred on the object position. + const OUTLINE = "#111"; + const SHAPES = { + arrow: (c) => + ``, + chevron: (c) => + `` + + ``, + vehicle: (c) => + `` + + `` + + ``, + circle: (c) => + `` + + `` + + ``, + }; + const STALE_COLOR = "#9e9e9e"; + + // Esri imagery depth varies by location (e.g. zoom 18 at AstaZero); deeper tiles are a + // "Map data not yet available" placeholder. The tilemap service says where imagery exists. + const ESRI_TILEMAP = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tilemap"; + const IMAGERY_PROBE_ZOOMS = [19, 18, 17, 16, 15, 14, 13, 12]; + const IMAGERY_PROBE_TIMEOUT_MS = 3000; + const FIT_FALLBACK_MAX_ZOOM = 18; // satellite, while/if the probe gives no answer + const FIT_PADDING_PX = 40; + + function dashArray(dash, weight) { + const w = Math.max(1, weight); + switch (dash) { + case "dashed": + return `${3 * w} ${2 * w}`; + case "dotted": + return `1 ${2 * w}`; + case "dashdot": + return `${4 * w} ${2 * w} 1 ${2 * w}`; + default: + return null; + } + } + + function escapeHtml(value) { + return String(value ?? "") + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); + } + + function storageGet(key) { + try { + return JSON.parse(window.localStorage.getItem(key)); + } catch (e) { + return null; + } + } + + function storageSet(key, value) { + try { + window.localStorage.setItem(key, JSON.stringify(value)); + } catch (e) { + /* private mode or blocked storage: size is just not remembered */ + } + } + + function getState(elementId) { + const comp = typeof getElement === "function" ? getElement(elementId) : null; + if (!comp || !comp.map || !window.L) return null; + if (!comp._atos) { + comp._atos = { + map: comp.map, + style: null, + base: null, + baseKey: null, + trajectories: {}, // id -> {group, line, start, end, name} + objects: {}, // id -> {marker, shapeKey, size, color} + lastObjects: [], + fitted: false, + centeredOnOrigin: false, + follow: null, + imageryMaxZoom: null, // deepest Esri zoom with imagery over the scenario + generation: 0, // bumped on reset, so late probe results are ignored + }; + watchResize(comp); + } + return comp._atos; + } + + function watchResize(comp) { + const wrapper = comp.$el.parentElement; + if (!wrapper) return; + const saved = storageGet(SIZE_STORAGE_KEY); + if (saved && saved.h > 0) wrapper.style.height = `${saved.h}px`; + if (saved && saved.w > 0) wrapper.style.width = `${saved.w}px`; + let timer = null; + let first = true; + const observer = new ResizeObserver(() => { + comp.map.invalidateSize({ pan: false }); + if (first) { + first = false; // initial notification, not a user resize + return; + } + clearTimeout(timer); + timer = setTimeout( + () => storageSet(SIZE_STORAGE_KEY, { w: wrapper.offsetWidth, h: wrapper.offsetHeight }), + 300, + ); + }); + observer.observe(wrapper); + comp.map.on("unload", () => observer.disconnect()); + } + + function applyBaseLayer(state) { + const style = state.style; + let key = style.base; + let def = BASE_LAYERS[key]; + if (key === "custom") { + def = style.customUrl + ? { url: style.customUrl, options: { maxZoom: 22, maxNativeZoom: style.customMaxNativeZoom || 19 } } + : BASE_LAYERS.satellite; + key = `custom:${style.customUrl}`; + } + if (!def) { + def = BASE_LAYERS.satellite; + key = "satellite"; + } + if (state.baseKey === key) return; + if (state.base) state.map.removeLayer(state.base); + const options = Object.assign({}, def.options); + if (key === "satellite" && state.imageryMaxZoom) options.maxNativeZoom = state.imageryMaxZoom; + state.base = window.L.tileLayer(def.url, options).addTo(state.map); + state.base.bringToBack(); + state.baseKey = key; + } + + /** Deepest zoom the active base layer has real tiles for; fits never go closer. */ + function nativeMaxZoom(state) { + if (state.baseKey === "satellite") return state.imageryMaxZoom || FIT_FALLBACK_MAX_ZOOM; + return (state.base && state.base.options.maxNativeZoom) || 19; + } + + async function tileHasImagery(z, x, y) { + const response = await fetch(`${ESRI_TILEMAP}/${z}/${y}/${x}/1/1`); + if (!response.ok) throw new Error(`tilemap HTTP ${response.status}`); + const json = await response.json(); + return Array.isArray(json.data) && json.data[0] === 1; + } + + /** Deepest zoom where the scenario's centre and corners all have Esri imagery. */ + async function probeImageryMaxZoom(map, bounds) { + const points = [bounds.getCenter(), bounds.getNorthWest(), bounds.getNorthEast(), bounds.getSouthWest(), bounds.getSouthEast()]; + for (const z of IMAGERY_PROBE_ZOOMS) { + const tiles = new Map(); + for (const p of points) { + const t = map.project(p, z).divideBy(256).floor(); + tiles.set(`${t.x},${t.y}`, t); + } + const results = await Promise.all([...tiles.values()].map((t) => tileHasImagery(z, t.x, t.y))); + if (results.every(Boolean)) return z; + } + return IMAGERY_PROBE_ZOOMS[IMAGERY_PROBE_ZOOMS.length - 1]; + } + + /** + * Find the imagery depth over `bounds` and stop the satellite layer from requesting + * deeper tiles: past it Leaflet scales up the deepest real tiles instead. Resolves + * (possibly without a result) within IMAGERY_PROBE_TIMEOUT_MS. + */ + function updateImageryMaxZoom(state, bounds) { + const generation = state.generation; + const probe = probeImageryMaxZoom(state.map, bounds) + .then((z) => { + if (generation !== state.generation) return; + state.imageryMaxZoom = z; + if (state.baseKey === "satellite" && state.base && state.base.options.maxNativeZoom !== z) { + state.base.options.maxNativeZoom = z; + state.base.redraw(); + } + }) + .catch(() => { + /* offline or blocked: keep the defaults */ + }); + const timeout = new Promise((resolve) => setTimeout(resolve, IMAGERY_PROBE_TIMEOUT_MS)); + return Promise.race([probe, timeout]); + } + + function colorFor(state, id) { + const colors = (state.style && state.style.colors) || {}; + return colors[id] || colors[String(id)] || "#ffd400"; + } + + function styleTrajectory(state, id, traj) { + const s = state.style.trajectory; + const color = colorFor(state, id); + traj.line.setStyle({ + color, + weight: s.width, + opacity: s.opacity, + dashArray: dashArray(s.dash, s.width), + lineCap: s.dash === "dotted" ? "round" : "butt", + }); + const r = Math.max(3, s.width + 2); + traj.start.setStyle({ radius: r, color: OUTLINE, weight: 2, fillColor: color, fillOpacity: 1, opacity: s.opacity }); + traj.start.setRadius(r); + traj.end.setStyle({ radius: r, color, weight: Math.max(2, s.width / 2), fillOpacity: 0, opacity: s.opacity }); + traj.end.setRadius(r); + } + + function setTrajectories(state, trajectories) { + const L = window.L; + const seen = new Set(); + for (const t of trajectories) { + seen.add(String(t.id)); + let traj = state.trajectories[t.id]; + if (!traj) { + const line = L.polyline(t.latlngs, { interactive: true }); + const start = L.circleMarker(t.latlngs[0], { interactive: false }); + const end = L.circleMarker(t.latlngs[t.latlngs.length - 1], { interactive: false }); + const group = L.layerGroup([line, start, end]).addTo(state.map); + traj = { group, line, start, end }; + state.trajectories[t.id] = traj; + } else { + traj.line.setLatLngs(t.latlngs); + traj.start.setLatLng(t.latlngs[0]); + traj.end.setLatLng(t.latlngs[t.latlngs.length - 1]); + } + traj.name = t.name; + traj.line.bindTooltip(escapeHtml(t.name), { sticky: true }); + styleTrajectory(state, t.id, traj); + } + for (const id of Object.keys(state.trajectories)) { + if (!seen.has(String(id))) { + state.map.removeLayer(state.trajectories[id].group); + delete state.trajectories[id]; + } + } + if (!state.fitted && trajectories.length > 0) { + state.fitted = true; + const generation = state.generation; + const bounds = scenarioBounds(state); + updateImageryMaxZoom(state, bounds).then(() => { + if (generation === state.generation) fitScenario(state); + }); + } + } + + function markerIcon(state, color, size) { + const shape = SHAPES[state.style.marker.shape] || SHAPES.arrow; + const html = + `
` + + `` + + shape(color) + + "
"; + return window.L.divIcon({ className: "atos-obj-icon", html, iconSize: [size, size], iconAnchor: [size / 2, size / 2] }); + } + + function tooltipText(o) { + return `${escapeHtml(o.name)}
${o.speed.toFixed(1)} m/s, heading ${Math.round(o.bearing)}°` + + (o.stale ? "
no recent data" : ""); + } + + function setObjects(state, objects) { + const L = window.L; + const ms = state.style.marker; + const seen = new Set(); + for (const o of objects) { + seen.add(String(o.id)); + const color = o.stale ? STALE_COLOR : colorFor(state, o.id); + const shapeKey = `${ms.shape}|${ms.size}|${color}|${ms.labels}`; + let obj = state.objects[o.id]; + if (!obj) { + const marker = L.marker([o.lat, o.lon], { keyboard: false, zIndexOffset: 1000 }).addTo(state.map); + obj = { marker, shapeKey: null }; + state.objects[o.id] = obj; + } else { + obj.marker.setLatLng([o.lat, o.lon]); + } + if (obj.shapeKey !== shapeKey) { + obj.marker.setIcon(markerIcon(state, color, ms.size)); + obj.marker.unbindTooltip(); + obj.marker.bindTooltip("", { + permanent: !!ms.labels, + direction: "right", + offset: [ms.size / 2, 0], + className: "atos-obj-label", + }); + obj.shapeKey = shapeKey; + } + obj.marker.setOpacity(o.stale ? 0.7 : 1); + obj.marker.setTooltipContent(ms.labels ? escapeHtml(o.name) : tooltipText(o)); + const el = obj.marker.getElement(); + const rot = el && el.querySelector(".atos-obj-rot"); + if (rot) rot.style.transform = `rotate(${o.bearing}deg)`; + } + for (const id of Object.keys(state.objects)) { + if (!seen.has(String(id))) { + state.map.removeLayer(state.objects[id].marker); + delete state.objects[id]; + } + } + state.lastObjects = objects; + if (state.follow !== null && state.follow !== undefined) { + const target = objects.find((o) => String(o.id) === String(state.follow)); + if (target) state.map.panTo([target.lat, target.lon], { animate: false }); + } + } + + function scenarioBounds(state) { + let bounds = null; + for (const traj of Object.values(state.trajectories)) { + const b = traj.line.getBounds(); + if (b.isValid()) bounds = bounds ? bounds.extend(b) : window.L.latLngBounds(b.getSouthWest(), b.getNorthEast()); + } + for (const obj of Object.values(state.objects)) { + const ll = obj.marker.getLatLng(); + bounds = bounds ? bounds.extend(ll) : window.L.latLngBounds(ll, ll); + } + return bounds; + } + + function fitScenario(state) { + const bounds = scenarioBounds(state); + if (bounds) { + state.map.fitBounds(bounds, { padding: [FIT_PADDING_PX, FIT_PADDING_PX], maxZoom: nativeMaxZoom(state) }); + } + return !!bounds; + } + + function injectCss() { + if (document.getElementById("atos-map-css")) return; + const css = document.createElement("style"); + css.id = "atos-map-css"; + css.textContent = + ".atos-obj-icon{background:transparent;border:none;}" + + ".atos-obj-label{font-weight:600;}"; + document.head.appendChild(css); + } + + window.atosMap = { + /** Apply all user style settings; safe to call repeatedly. Returns false until the map exists. */ + setStyle(elementId, style) { + const state = getState(elementId); + if (!state) return false; + injectCss(); + state.style = style; + applyBaseLayer(state); + for (const [id, traj] of Object.entries(state.trajectories)) styleTrajectory(state, id, traj); + for (const obj of Object.values(state.objects)) obj.shapeKey = null; // rebuild icons + setObjects(state, state.lastObjects); + return true; + }, + + /** Apply one data snapshot from Python (MapDataSource.snapshot). */ + update(elementId, payload) { + const state = getState(elementId); + if (!state || !state.style) return false; + if (payload.origin && !state.centeredOnOrigin) { + state.centeredOnOrigin = true; + if (!state.fitted) state.map.setView(payload.origin, Math.min(17, nativeMaxZoom(state))); + } + if (payload.trajectories) setTrajectories(state, payload.trajectories); + if (payload.objects) setObjects(state, payload.objects); + return true; + }, + + fit(elementId) { + const state = getState(elementId); + return state ? fitScenario(state) : false; + }, + + follow(elementId, objectId) { + const state = getState(elementId); + if (!state) return false; + state.follow = objectId === "" ? null : objectId; + if (state.follow !== null) setObjects(state, state.lastObjects); + return true; + }, + + /** Forget overlays, e.g. after a new scenario was initialized. */ + reset(elementId) { + const state = getState(elementId); + if (!state) return false; + for (const traj of Object.values(state.trajectories)) state.map.removeLayer(traj.group); + for (const obj of Object.values(state.objects)) state.map.removeLayer(obj.marker); + state.trajectories = {}; + state.objects = {}; + state.lastObjects = []; + state.fitted = false; + state.centeredOnOrigin = false; + state.imageryMaxZoom = null; // the new scenario may be somewhere else + state.generation += 1; + return true; + }, + }; +})(); diff --git a/atos_gui/package.xml b/atos_gui/package.xml index c5d9db555..b847914e7 100644 --- a/atos_gui/package.xml +++ b/atos_gui/package.xml @@ -10,6 +10,13 @@ rclpy rcl_interfaces atos_interfaces + nav_msgs + std_msgs + python3-numpy + + python3-pyproj + python3-pytest ament_python diff --git a/atos_gui/requirements.txt b/atos_gui/requirements.txt index d0e1c667a..42349aef8 100644 --- a/atos_gui/requirements.txt +++ b/atos_gui/requirements.txt @@ -1,2 +1,6 @@ -nicegui==1.4.8 -fastapi==0.108.0 +# NiceGUI 4.x requires Python >= 3.11 (ROS 2 Jazzy and newer). ROS 2 Humble (Python 3.10) +# uses NiceGUI 3.19.x, which has the same API. Python < 3.10 (ROS 2 Foxy) gets no GUI. +nicegui>=3.19,<4; python_version >= "3.10" and python_version < "3.11" +nicegui>=4.0,<5; python_version >= "3.11" +# Map view: exact local frame <-> WGS84 conversion (same PROJ definition as EsminiAdapter). +pyproj>=3.6; python_version >= "3.10" diff --git a/atos_gui/setup.py b/atos_gui/setup.py index 55469add6..52f87955c 100644 --- a/atos_gui/setup.py +++ b/atos_gui/setup.py @@ -21,6 +21,8 @@ (str(data / "launch"), ["launch/gui.py"]), ], install_requires=["setuptools"], + # Makes colcon test run the tests in test/ with pytest. + extras_require={"test": ["pytest"]}, zip_safe=True, entry_points={ "console_scripts": [ diff --git a/atos_gui/test/test_geo.py b/atos_gui/test/test_geo.py new file mode 100644 index 000000000..e0231641c --- /dev/null +++ b/atos_gui/test/test_geo.py @@ -0,0 +1,132 @@ +"""This Source Code Form is subject to the terms of the Mozilla Public +License, v. 2.0. If a copy of the MPL was not distributed with this +file, You can obtain one at https://mozilla.org/MPL/2.0/. +""" + +import math + +import numpy as np +import pytest +from pyproj import Transformer + +from atos_gui.mapview.geo import WGS84, LocalFrame, decimate, yaw_from_quaternion + +# Origin of conf/odr/GaragePlanHighRes.xodr (AstaZero). +ORIGIN_LAT = 57.7775 +ORIGIN_LON = 12.7814 + + +@pytest.fixture +def frame(): + return LocalFrame(ORIGIN_LAT, ORIGIN_LON) + + +def angle_diff_deg(a, b): + return (np.asarray(a) - np.asarray(b) + 180.0) % 360.0 - 180.0 + + +def test_origin_maps_to_origin(frame): + lons, lats = frame.to_lonlat([0.0], [0.0]) + assert lats[0] == pytest.approx(ORIGIN_LAT, abs=1e-12) + assert lons[0] == pytest.approx(ORIGIN_LON, abs=1e-12) + + +def test_matches_esmini_projection_round_trip(frame): + # Forward with the exact definition EsminiAdapter uses, inverse with ours. + esmini = Transformer.from_crs( + "EPSG:4326", + f"+proj=tmerc +lat_0={ORIGIN_LAT} +lon_0={ORIGIN_LON} +datum=WGS84 +units=m", + always_xy=True, + ) + xs = np.array([-2000.0, -150.0, 0.0, 300.0, 2000.0]) + ys = np.array([1500.0, -2000.0, 0.0, 42.0, -2000.0]) + lons, lats = frame.to_lonlat(xs, ys) + xs_back, ys_back = esmini.transform(lons, lats) + np.testing.assert_allclose(xs_back, xs, atol=1e-3) + np.testing.assert_allclose(ys_back, ys, atol=1e-3) + + +def test_axes_point_east_and_north(frame): + lons, lats = frame.to_lonlat([100.0, 0.0], [0.0, 100.0]) + assert lons[0] > ORIGIN_LON and lats[0] == pytest.approx(ORIGIN_LAT, abs=1e-6) + assert lats[1] > ORIGIN_LAT and lons[1] == pytest.approx(ORIGIN_LON, abs=1e-12) + # Distances are true metres (tmerc scale factor is 1 on the central meridian). + _, _, d_east = WGS84.inv(ORIGIN_LON, ORIGIN_LAT, lons[0], lats[0]) + _, _, d_north = WGS84.inv(ORIGIN_LON, ORIGIN_LAT, lons[1], lats[1]) + assert d_east == pytest.approx(100.0, abs=1e-3) + assert d_north == pytest.approx(100.0, abs=1e-6) + + +@pytest.mark.parametrize( + "yaw, bearing", + [ + (0.0, 90.0), # ENU east + (math.pi / 2, 0.0), # north + (math.pi, 270.0), # west + (-math.pi / 2, 180.0), # south + (3 * math.pi / 2, 180.0), # [0, 2pi) as stored by ATOS + (math.radians(30), 60.0), + ], +) +def test_yaw_to_bearing_on_central_meridian(frame, yaw, bearing): + _, _, bearings = frame.poses_to_geo([0.0], [0.0], [yaw]) + assert angle_diff_deg(bearings[0], bearing) == pytest.approx(0.0, abs=1e-6) + assert 0.0 <= bearings[0] < 360.0 + + +def test_meridian_convergence_sign(frame): + # Grid north east of the central meridian (northern hemisphere) is rotated + # clockwise from true north by about dlon * sin(lat); west of it, anticlockwise. + _, _, bearings = frame.poses_to_geo([2000.0, -2000.0], [0.0, 0.0], [math.pi / 2] * 2) + lons, _ = frame.to_lonlat([2000.0], [0.0]) + expected = (lons[0] - ORIGIN_LON) * math.sin(math.radians(ORIGIN_LAT)) + assert expected > 0.02 # big enough for the test to mean something + assert angle_diff_deg(bearings[0], expected) == pytest.approx(0.0, abs=1e-3) + assert angle_diff_deg(bearings[1], -expected) == pytest.approx(0.0, abs=1e-3) + + +def test_heading_follows_drawn_trajectory(frame): + # A marker heading along a straight local segment must point along the segment + # as drawn on the map, anywhere in a +-2 km test area. + rng = np.random.default_rng(0) + for _ in range(50): + x0, y0 = rng.uniform(-2000, 2000, 2) + yaw = rng.uniform(0, 2 * math.pi) + x1, y1 = x0 + 20 * math.cos(yaw), y0 + 20 * math.sin(yaw) + lats, lons, bearings = frame.poses_to_geo([x0], [y0], [yaw]) + lon1, lat1 = frame.to_lonlat([x1], [y1]) + azimuth, _, _ = WGS84.inv(lons[0], lats[0], lon1[0], lat1[0]) + assert angle_diff_deg(bearings[0], azimuth) == pytest.approx(0.0, abs=1e-3) + + +def test_differs_from_flat_earth_gnss_topics_as_expected(frame): + # llhOffsetMeters (CRSTransformation.cpp), used for gnss_path / gnss_fix, is a + # flat-earth step on a sphere of radius a. It should agree to within ~0.3%. + a = 6378137.0 + for x, y in [(1000.0, 0.0), (0.0, 1000.0), (-700.0, 700.0)]: + flat_lat = ORIGIN_LAT + y / a * 180 / math.pi + flat_lon = ORIGIN_LON + x / a * 180 / math.pi / math.cos(math.radians(ORIGIN_LAT)) + lons, lats = frame.to_lonlat([x], [y]) + _, _, error = WGS84.inv(flat_lon, flat_lat, lons[0], lats[0]) + assert error < 0.003 * math.hypot(x, y) + + +def test_yaw_from_quaternion(): + for yaw in [0.0, 0.3, math.pi / 2, 3.0, -2.0]: + q = (0.0, 0.0, math.sin(yaw / 2), math.cos(yaw / 2)) + assert yaw_from_quaternion(*q) == pytest.approx(math.atan2(math.sin(yaw), math.cos(yaw))) + assert yaw_from_quaternion(0.0, 0.0, 0.0, 1.0) == 0.0 + + +def test_decimate_keeps_endpoints_and_spacing(): + xs = np.linspace(0, 10, 1001) # 1 cm spacing + ys = np.zeros_like(xs) + keep = decimate(xs, ys, 0.1) + assert keep[0] == 0 and keep[-1] == len(xs) - 1 + assert np.all(np.diff(xs[keep[:-1]]) >= 0.1 - 1e-9) + assert len(keep) < 110 + + +def test_invalid_origin_rejected(): + with pytest.raises(ValueError): + LocalFrame(123.0, 0.0) diff --git a/atos_gui/test/test_map_data.py b/atos_gui/test/test_map_data.py new file mode 100644 index 000000000..0e9ee5b6a --- /dev/null +++ b/atos_gui/test/test_map_data.py @@ -0,0 +1,253 @@ +"""This Source Code Form is subject to the terms of the Mozilla Public +License, v. 2.0. If a copy of the MPL was not distributed with this +file, You can obtain one at https://mozilla.org/MPL/2.0/. +""" + +"""MapDataSource tests with a fake rclpy node (no ROS graph needed).""" + +import math +from types import SimpleNamespace as NS + +import pytest + +from atos_gui.mapview import map_data +from atos_gui.mapview.geo import LocalFrame +from atos_gui.mapview.map_data import MapDataSource + +ORIGIN = (57.7775, 12.7814) + + +class FakeFuture: + def __init__(self): + self._done, self._result, self._callbacks = False, None, [] + + def done(self): + return self._done + + def cancelled(self): + return False + + def result(self): + return self._result + + def add_done_callback(self, cb): + self._callbacks.append(cb) + + def set_result(self, result): + self._done, self._result = True, result + for cb in self._callbacks: + cb(self) + + +class FakeClient: + def __init__(self, name): + self.name, self.calls, self.removed, self.ready = name, [], [], True + + def service_is_ready(self): + return self.ready + + def call_async(self, request): + future = FakeFuture() + self.calls.append(future) + return future + + def remove_pending_request(self, future): + self.removed.append(future) + + +class FakeTimer: + def __init__(self, period, cb): + self.period, self.cb, self.canceled = period, cb, False + + def cancel(self): + self.canceled = True + + def is_canceled(self): + return self.canceled + + +class FakeNode: + def __init__(self): + self.clients, self.subs, self.timers, self.destroyed_subs = {}, {}, [], [] + + def create_client(self, _type, name, callback_group=None): + self.clients[name] = FakeClient(name) + return self.clients[name] + + def create_subscription(self, _type, topic, cb, qos, callback_group=None): + self.subs[topic] = cb + return topic + + def destroy_subscription(self, sub): + self.destroyed_subs.append(sub) + self.subs.pop(sub, None) + + def create_timer(self, period, cb, callback_group=None): + timer = FakeTimer(period, cb) + self.timers.append(timer) + return timer + + def destroy_timer(self, timer): + timer.canceled = True + + def get_logger(self): + return NS(info=lambda *_: None, warning=lambda *_: None) + + +def pose(x, y, yaw): + return NS( + position=NS(x=x, y=y, z=0.0), + orientation=NS(x=0.0, y=0.0, z=math.sin(yaw / 2), w=math.cos(yaw / 2)), + ) + + +def path_msg(points): + return NS(poses=[NS(pose=pose(x, y, 0.0)) for x, y in points]) + + +def monitor_msg(object_id, x, y, yaw, vx=3.0, vy=4.0): + return NS( + atos_header=NS(object_id=object_id), + pose=NS(pose=pose(x, y, yaw)), + velocity=NS(twist=NS(linear=NS(x=vx, y=vy, z=0.0))), + object_state=NS(state=4), + ) + + +def origin_result(lat, lon, success=True): + return NS(success=success, origin=NS(position=NS(latitude=lat, longitude=lon, altitude=0.0))) + + +@pytest.fixture +def setup(): + node = FakeNode() + state = {"value": 1} + data = MapDataSource(node, get_control_state=lambda: state["value"]) + maintain = node.timers[0].cb + return node, state, data, maintain + + +def load(node, state, maintain, ids=(1, 2), names=("Car", "Truck")): + state["value"] = 2 + maintain() + node.clients["/atos/get_object_ids"].calls[-1].set_result(NS(ids=list(ids), names=list(names))) + node.clients["/atos/get_test_origin"].calls[-1].set_result(origin_result(*ORIGIN)) + + +def test_waits_for_initialized_before_calling_services(setup): + node, state, data, maintain = setup + maintain() + assert node.clients["/atos/get_object_ids"].calls == [] + assert node.clients["/atos/get_test_origin"].calls == [] + + +def test_load_sequence_and_snapshot(setup): + node, state, data, maintain = setup + load(node, state, maintain) + assert data.frame is not None and data.status.startswith("Origin") + assert "/atos/object_1/path" in node.subs and "/atos/object_2/path" in node.subs + + node.subs["/atos/object_1/path"](path_msg([(0, 0), (10, 0), (10, 10)])) + node.subs["/atos/object_monitor"](monitor_msg(1, 10.0, 0.0, math.pi / 2)) + node.subs["/atos/connected_object_ids"](NS(ids=[1])) + + snap = data.snapshot(None) + assert snap["origin"] == list(ORIGIN) + (traj,) = snap["trajectories"] + assert traj["id"] == 1 and traj["name"] == "Car" and len(traj["latlngs"]) == 3 + assert traj["latlngs"][0] == pytest.approx(list(ORIGIN), abs=1e-9) + + (obj,) = snap["objects"] + frame = LocalFrame(*ORIGIN) + lats, lons, bearings = frame.poses_to_geo([10.0], [0.0], [math.pi / 2]) + assert obj["lat"] == pytest.approx(lats[0], abs=1e-8) + assert obj["lon"] == pytest.approx(lons[0], abs=1e-8) + assert obj["bearing"] == pytest.approx(bearings[0], abs=0.01) + assert obj["bearing"] == pytest.approx(0.0, abs=0.01) or obj["bearing"] == pytest.approx(360.0, abs=0.01) + assert obj["speed"] == pytest.approx(5.0) + assert obj["stale"] is False + + # Unchanged trajectories are not resent. + assert "trajectories" not in data.snapshot(snap["traj_version"]) + + +def test_path_received_before_origin_is_converted_later(setup): + node, state, data, maintain = setup + state["value"] = 2 + maintain() + node.clients["/atos/get_object_ids"].calls[-1].set_result(NS(ids=[1], names=["Car"])) + assert data.frame is None + # Origin not answered yet; a (re)subscribed path arrives via a previous subscription. + data._on_path(1, path_msg([(0, 0), (5, 5)])) + assert data.snapshot(None)["trajectories"] == [] + node.clients["/atos/get_test_origin"].calls[-1].set_result(origin_result(*ORIGIN)) + assert len(data.snapshot(None)["trajectories"][0]["latlngs"]) == 2 + + +def test_only_connected_objects_shown_and_stale_flag(setup, monkeypatch): + node, state, data, maintain = setup + load(node, state, maintain) + now = [1000.0] + monkeypatch.setattr(map_data.time, "monotonic", lambda: now[0]) + node.subs["/atos/object_monitor"](monitor_msg(1, 0.0, 0.0, 0.0)) + node.subs["/atos/object_monitor"](monitor_msg(2, 5.0, 0.0, 0.0)) + node.subs["/atos/connected_object_ids"](NS(ids=[2])) + assert [o["id"] for o in data.snapshot(None)["objects"]] == [2] + + # Connected list not published any more: fall back to all objects with data. + now[0] += map_data.CONNECTED_IDS_MAX_AGE_S + 0.1 + objects = data.snapshot(None)["objects"] + assert [o["id"] for o in objects] == [1, 2] + assert all(o["stale"] for o in objects) # older than MONITOR_STALE_S + + now[0] += map_data.MONITOR_FORGET_S + assert data.snapshot(None)["objects"] == [] + + +def test_origin_timeout_reports_and_retries(setup): + node, state, data, maintain = setup + state["value"] = 2 + maintain() + node.clients["/atos/get_object_ids"].calls[-1].set_result(NS(ids=[1], names=["Car"])) + origin_client = node.clients["/atos/get_test_origin"] + timeout_timer = node.timers[-1] + assert timeout_timer.period == map_data.ORIGIN_TIMEOUT_S + timeout_timer.cb() + assert origin_client.removed == [origin_client.calls[-1]] + assert "Timed out" in data.status and data.frame is None + + # A new scenario init triggers another attempt. + node.subs["/atos/state_change"](NS(prev_state=1, current_state=2)) + maintain() + assert len(node.clients["/atos/get_object_ids"].calls) == 2 + + +def test_service_unavailable_retries_next_tick(setup): + node, state, data, maintain = setup + node.clients["/atos/get_object_ids"].ready = False + state["value"] = 2 + maintain() + assert "not available" in data.status + node.clients["/atos/get_object_ids"].ready = True + maintain() + assert len(node.clients["/atos/get_object_ids"].calls) == 1 + + +def test_reinit_with_fewer_objects_drops_subscriptions(setup): + node, state, data, maintain = setup + load(node, state, maintain) + node.subs["/atos/object_2/path"](path_msg([(0, 0), (1, 1)])) + node.subs["/atos/state_change"](NS(prev_state=1, current_state=2)) + load(node, state, maintain, ids=(1,), names=("Car",)) + assert "/atos/object_2/path" in node.destroyed_subs + assert [t["id"] for t in data.snapshot(None)["trajectories"]] == [] + assert data.object_ids == [1] + + +def test_missing_georeference(setup): + node, state, data, maintain = setup + state["value"] = 2 + maintain() + node.clients["/atos/get_object_ids"].calls[-1].set_result(NS(ids=[1], names=["Car"])) + node.clients["/atos/get_test_origin"].calls[-1].set_result(origin_result(float("nan"), 0.0)) + assert data.frame is None and "geo-reference" in data.status diff --git a/docs/Usage/GUI/controlpanel.md b/docs/Usage/GUI/controlpanel.md index 501c660c7..89d5f02c2 100644 --- a/docs/Usage/GUI/controlpanel.md +++ b/docs/Usage/GUI/controlpanel.md @@ -1,6 +1,9 @@ # Control Panel Control Panel is used to run ATOS without any further visualisation. In order to start Control Panel, start ATOS and then open your web browser and go to `ATOS_host_address:3000`, where `ATOS_host_address` is the address to the server that ATOS is hosted on. If you run ATOS on your own computer and want to use Control Panel on the same computer, you would go to `localhost:3000`. +## Requirements +The GUI is built with [NiceGUI](https://nicegui.io). The installation script installs NiceGUI 4.x on Python 3.11 or newer (ROS 2 Jazzy and newer) and NiceGUI 3.19.x on Python 3.10 (ROS 2 Humble). The GUI is not available on ROS 2 Foxy (Python 3.8); ATOS still launches there, without the GUI. + ## Running over HTTPS/TLS To connect to a remote ATOS server, you have to accept the following certificates in your browser: `https://hostname.of.atos:3443`, `https://hostname.of.atos:9090`. You can now follow the steps above to connect to the remote server either using the standalone Control Panel, or as a panel in [FoxGlove Studio](./foxglove.md). @@ -16,4 +19,19 @@ When opening Control Panel there will be a set of buttons, A state value determi - **Reset Test** - Reset the loaded test - **All clear** - Clears the test. - **Disarm** - Disarms the objects, meaning that they are no longer ready to start the test. -- **Abort** - Stops the test, for instance if something goes wrong or the test needs to be stopped for some reason. \ No newline at end of file +- **Abort** - Stops the test, for instance if something goes wrong or the test needs to be stopped for some reason. + +## Map view +Below the buttons, a satellite map shows the trajectories of the loaded scenario and, once objects are connected, a marker for each object, rotated by its reported heading. + +- **When data appears**: trajectories and the test origin are loaded once ObjectControl reaches `INITIALIZED` (after **Init**), and reloaded on each new Init. Object markers are shown for the objects in `/atos/connected_object_ids`. A marker turns grey when no monitor data has arrived for 2 seconds. +- **Geographic accuracy**: ATOS works in a local transverse Mercator frame centred on the test origin (from the OpenDRIVE ``). The map converts trajectories (`/atos/object_/path`) and monitor poses (`/atos/object_monitor`) with that same projection, using PROJ via `pyproj`, so overlays are exact. Headings, which are counter-clockwise from east in the local frame, are converted to true bearings, including meridian convergence. If the scenario has no geo-reference, the map says so and draws nothing. +- **Resizing**: drag the bottom-right corner of the map. The browser remembers the size. +- **Settings** (*Map settings*, saved on the ATOS host): + - Trajectory width, line style (solid, dashed, dotted, dash-dot) and opacity. + - Marker size and style (arrow, chevron, vehicle, circle with heading line), and whether labels are shown. + - A colour per object. +- **Base map**: satellite imagery is Esri World Imagery, which needs no API key (attribution is shown on the map). OpenStreetMap or a custom tile URL (e.g. a local tile server for sites without internet) can be selected instead. Overlays are drawn even if no tiles load. How deep Esri's imagery goes varies by location (zoom 18 at AstaZero, for example). After each Init the map asks Esri's tile-map service where imagery exists over the scenario. Fitting never zooms closer than that, and when you zoom in further by hand, the deepest real imagery is scaled up instead of showing "Map data not yet available" tiles. +- **Fit to scenario / Follow**: zoom to all trajectories, or keep one object centred. + +In relative-kinematics (anchor) mode, the map still shows everything in the test origin frame. \ No newline at end of file diff --git a/scripts/installation/install_deps.sh b/scripts/installation/install_deps.sh index a9e28cc27..7593995b1 100755 --- a/scripts/installation/install_deps.sh +++ b/scripts/installation/install_deps.sh @@ -132,7 +132,12 @@ check_command_failed $? "Failed to install ROS2 dependencies." ######## Install ATOS GUI dependencies ######## ############################################### -"${ATOS_VENV_PATH}/bin/python" -m pip install -r ${ATOS_REPO_PATH}/atos_gui/requirements.txt +if "${ATOS_VENV_PATH}/bin/python" -c 'import sys; sys.exit(sys.version_info < (3, 10))'; then + "${ATOS_VENV_PATH}/bin/python" -m pip install -r ${ATOS_REPO_PATH}/atos_gui/requirements.txt + check_command_failed $? "Failed to install ATOS GUI dependencies." +else + echo "The ATOS GUI requires Python >= 3.10; skipping GUI dependencies." +fi ########################################### ###### Install some deps from source ###### diff --git a/scripts/installation/requirements.txt b/scripts/installation/requirements.txt index ba65e5608..39a8508ca 100644 --- a/scripts/installation/requirements.txt +++ b/scripts/installation/requirements.txt @@ -3,4 +3,7 @@ pyOpenSSL >= 23.2.0 numpy<2.0 scenariogeneration pytest>=6.2,<7.5 -anyio>=3.6,<4.0 +# NiceGUI (atos_gui, installed in the same venv) requires anyio >= 4.14.2. +# Python < 3.10 (ROS 2 Foxy) gets no GUI and keeps the old pin. +anyio>=3.6,<4.0; python_version < "3.10" +anyio>=4.14.2; python_version >= "3.10" From ca79e53f8fa6029fd8ba54c8c31c1baa17b55f9a Mon Sep 17 00:00:00 2001 From: Robert Brenick Date: Mon, 9 Nov 2026 10:37:02 -0600 Subject: [PATCH 2/8] Make the missing GUI on ROS 2 Foxy visible in docs and installer The GUI needs Python >= 3.10, so Ubuntu 20.04 / ROS 2 Foxy installs ATOS without it. Say so in the README, the installation docs and setup_atos.sh --help. setup_atos.sh now prints a highlighted notice at the start and end of the installation, so it isn't lost in the install output. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 ++ docs/Installation/installation.md | 3 +++ scripts/installation/install_deps.sh | 2 +- scripts/installation/install_functions.sh | 26 +++++++++++++++++++++++ setup_atos.sh | 7 ++++++ 5 files changed, 39 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3c57d25c8..71679755f 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,8 @@ ATOS comes with an installation script that automates the installation process. ./setup_atos.sh ``` +> **Note:** The ATOS GUI (control panel with map view, config and object panels) requires Python 3.10 or newer, so it is **not available on Ubuntu 20.04 / ROS 2 Foxy**. ATOS is installed and runs there without the GUI. For the GUI, use Ubuntu 22.04 or newer, or the Docker image (Ubuntu 22.04 / ROS 2 Humble). + ## Building from source manually You can find instructions on how to manually install ATOS and its dependencies from source [here](https://atos.readthedocs.io/en/latest/Installation/installation/). diff --git a/docs/Installation/installation.md b/docs/Installation/installation.md index 196c3a0df..31ec07494 100644 --- a/docs/Installation/installation.md +++ b/docs/Installation/installation.md @@ -22,6 +22,9 @@ ATOS comes with an installation script that automates the installation process. ./setup_atos.sh ``` +!!! note + The ATOS GUI ([control panel](../Usage/GUI/controlpanel.md) with map view, config and object panels) requires Python 3.10 or newer, so it is **not available on Ubuntu 20.04 / ROS 2 Foxy**. ATOS is installed and runs there without the GUI. For the GUI, use Ubuntu 22.04 or newer, or the [Docker image](#docker) (Ubuntu 22.04 / ROS 2 Humble). + ## Starting ATOS Launch ATOS ```bash diff --git a/scripts/installation/install_deps.sh b/scripts/installation/install_deps.sh index 7593995b1..75032c3db 100755 --- a/scripts/installation/install_deps.sh +++ b/scripts/installation/install_deps.sh @@ -136,7 +136,7 @@ if "${ATOS_VENV_PATH}/bin/python" -c 'import sys; sys.exit(sys.version_info < (3 "${ATOS_VENV_PATH}/bin/python" -m pip install -r ${ATOS_REPO_PATH}/atos_gui/requirements.txt check_command_failed $? "Failed to install ATOS GUI dependencies." else - echo "The ATOS GUI requires Python >= 3.10; skipping GUI dependencies." + echo "The ATOS GUI requires Python >= 3.10; skipping GUI dependencies (see the note at the end of the installation)." fi ########################################### diff --git a/scripts/installation/install_functions.sh b/scripts/installation/install_functions.sh index da9b9dae5..97ce734a1 100755 --- a/scripts/installation/install_functions.sh +++ b/scripts/installation/install_functions.sh @@ -54,6 +54,32 @@ get_supported_ros_distro() { esac } +# The ATOS GUI needs Python >= 3.10 (NiceGUI 3.19 or newer). Ubuntu 20.04 / ROS 2 Foxy has Python 3.8. +gui_supported() { + python3 -c 'import sys; sys.exit(sys.version_info < (3, 10))' 2>/dev/null +} + +# Printed before and after the installation, so it is not lost in the install output. +print_no_gui_notice() { + local python_version color="" reset="" + python_version="$(python3 -c 'import platform; print(platform.python_version())' 2>/dev/null || echo unknown)" + if [ -t 1 ]; then + color="\033[1;33m" + reset="\033[0m" + fi + printf '%b' "${color}" + echo "" + echo "==============================================================================" + echo " NOTE: The ATOS GUI (control panel with map view, config and object panels)" + echo " is NOT available on this system. It requires Python 3.10 or newer, and this" + echo " system has Python ${python_version} (Ubuntu 20.04 / ROS 2 Foxy)." + echo " ATOS itself installs and runs without the GUI." + echo " For the GUI, use Ubuntu 22.04 or newer, or the ATOS Docker image." + echo "==============================================================================" + echo "" + printf '%b' "${reset}" +} + get_atos_venv_path() { echo "$HOME/.local/share/atos/venv" } diff --git a/setup_atos.sh b/setup_atos.sh index 6ada7c3eb..57f749234 100755 --- a/setup_atos.sh +++ b/setup_atos.sh @@ -41,6 +41,7 @@ if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then echo "Usage: ./setup_atos.sh [single option]" echo "This script will install all necessary dependencies, setup the ROS workspace at ~/atos_ws and install ATOS." echo "Supported native targets: Ubuntu 20.04 with ROS 2 Foxy, Ubuntu 22.04 with ROS 2 Humble, and Ubuntu 24.04 with ROS 2 Jazzy." + echo "The ATOS GUI requires Ubuntu 22.04 or newer; on Ubuntu 20.04 (ROS 2 Foxy) ATOS is installed without the GUI." echo "Options:" echo " -h, --help Show this help message and exit" echo " -r Reinstall dependencies" @@ -55,6 +56,10 @@ fi ####################################### ###### Install ATOS dependencies ###### ####################################### +if ! gui_supported; then + print_no_gui_notice +fi + echo "Installing ATOS dependencies..." ${REPO_DIR}/scripts/installation/install_deps.sh ${REPO_DIR} ${REINSTALL_DEPS} @@ -66,6 +71,7 @@ fi ###### Start installation of ATOS ###### ######################################## if ! [ -z "$REINSTALL_DEPS" ]; then + gui_supported || print_no_gui_notice echo "ATOS installation skipped." exit 0 fi @@ -78,5 +84,6 @@ if [ $? -ne 0 ]; then exit 1 fi +gui_supported || print_no_gui_notice echo "ATOS build and setup is complete. Please restart your terminal to complete the installation." echo "Please see the documentation for further details: https://atos.readthedocs.io/en/latest/" From 895d7e9a1486371363ec42f9bfebd56883c7623a Mon Sep 17 00:00:00 2001 From: Robert Brenick Date: Mon, 9 Nov 2026 11:00:00 -0600 Subject: [PATCH 3/8] Map view: fix hairline gaps between map tiles on HiDPI screens When the map sits at a fractional page offset, Chrome snapped each tile to device pixels on its own, leaving a light line between tile rows at 2x scaling. Compositing the map element as one layer removes it. Co-Authored-By: Claude Opus 5.5 --- atos_gui/atos_gui/mapview/map_view.py | 2 +- atos_gui/atos_gui/static/atos_map.js | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/atos_gui/atos_gui/mapview/map_view.py b/atos_gui/atos_gui/mapview/map_view.py index 516b2a353..dee0efb17 100644 --- a/atos_gui/atos_gui/mapview/map_view.py +++ b/atos_gui/atos_gui/mapview/map_view.py @@ -19,7 +19,7 @@ from .map_data import MapDataSource STATIC_ROUTE = "/atos_gui_static" -MAP_JS_VERSION = "20261105-2" +MAP_JS_VERSION = "20261109-1" UI_RATE_S = 0.1 SETTINGS_KEY = "atos_map_settings" diff --git a/atos_gui/atos_gui/static/atos_map.js b/atos_gui/atos_gui/static/atos_map.js index 88adc1139..63f60bc18 100644 --- a/atos_gui/atos_gui/static/atos_map.js +++ b/atos_gui/atos_gui/static/atos_map.js @@ -120,6 +120,10 @@ generation: 0, // bumped on reset, so late probe results are ignored }; watchResize(comp); + // Composite the map as one layer. Otherwise Chrome snaps each tile to device pixels + // on its own, and on HiDPI screens a map at a fractional page offset shows hairline + // gaps between tile rows. + comp.$el.style.willChange = "transform"; } return comp._atos; } From c88e4e97e2f222689c5cffe3ef6895aeb6ada82b Mon Sep 17 00:00:00 2001 From: Robert Brenick Date: Mon, 9 Nov 2026 11:18:23 -0600 Subject: [PATCH 4/8] Fix ruff findings reported by the format CI check - Merge the license header and module description into one docstring, so imports are at the top of the module (E402). - configpanel: type(x) is not T instead of != (E721), same semantics. - controlpanel: import GetObjectControlState instead of * (F403/F405). - map_data: drop unused rclpy import (F401); ruff import order and format. Co-Authored-By: Claude Opus 5.5 --- atos_gui/atos_gui/configpanel/configpanel.py | 22 +-- .../atos_gui/configpanel/local_file_picker.py | 5 +- .../atos_gui/controlpanel/controlpanel.py | 2 +- atos_gui/atos_gui/mapview/geo.py | 11 +- atos_gui/atos_gui/mapview/map_data.py | 65 +++++-- atos_gui/atos_gui/mapview/map_view.py | 181 +++++++++++++----- atos_gui/test/test_geo.py | 12 +- atos_gui/test/test_map_data.py | 32 +++- 8 files changed, 238 insertions(+), 92 deletions(-) diff --git a/atos_gui/atos_gui/configpanel/configpanel.py b/atos_gui/atos_gui/configpanel/configpanel.py index 3091b46fb..42ea51c40 100644 --- a/atos_gui/atos_gui/configpanel/configpanel.py +++ b/atos_gui/atos_gui/configpanel/configpanel.py @@ -484,67 +484,67 @@ def assign_value_and_type_to_parameter( """ match param_type: case "file": - if type(param_value) != str: + if type(param_value) is not str: ui.notify("Please select a file") return parameter.value.type = ParameterType.PARAMETER_STRING parameter.value.string_value = param_value case "bool": - if type(param_value) != bool: + if type(param_value) is not bool: ui.notify("Please select a boolean") return parameter.value.type = ParameterType.PARAMETER_BOOL parameter.value.bool_value = param_value case "int": - if type(param_value) != int: + if type(param_value) is not int: ui.notify("Please select an integer") return parameter.value.type = ParameterType.PARAMETER_INTEGER parameter.value.integer_value = param_value case "double": - if type(param_value) != float: + if type(param_value) is not float: ui.notify("Please select a double") return parameter.value.type = ParameterType.PARAMETER_DOUBLE parameter.value.double_value = param_value case "string": - if type(param_value) != str: + if type(param_value) is not str: ui.notify("Please select a string") return parameter.value.type = ParameterType.PARAMETER_STRING parameter.value.string_value = param_value case "file_array": - if type(param_value) != list or type(param_value[0]) != str: + if type(param_value) is not list or type(param_value[0]) is not str: ui.notify("Please select one or more files") return parameter.value.type = ParameterType.PARAMETER_STRING_ARRAY parameter.value.string_array_value = param_value case "byte_array": - if type(param_value) != list or type(param_value[0]) != int: + if type(param_value) is not list or type(param_value[0]) is not int: ui.notify("Please select one or more bytes") return parameter.value.type = ParameterType.PARAMETER_BYTE_ARRAY parameter.value.byte_array_value = param_value case "bool_array": - if type(param_value) != list or type(param_value[0]) != bool: + if type(param_value) is not list or type(param_value[0]) is not bool: ui.notify("Please select one or more booleans") return parameter.value.type = ParameterType.PARAMETER_BOOL_ARRAY parameter.value.bool_array_value = param_value case "int_array": - if type(param_value) != list or type(param_value[0]) != int: + if type(param_value) is not list or type(param_value[0]) is not int: ui.notify("Please select one or more integers") return parameter.value.type = ParameterType.PARAMETER_INTEGER_ARRAY parameter.value.integer_array_value = param_value case "double_array": - if type(param_value) != list or type(param_value[0]) != float: + if type(param_value) is not list or type(param_value[0]) is not float: ui.notify("Please select one or more doubles") return parameter.value.type = ParameterType.PARAMETER_DOUBLE_ARRAY parameter.value.double_array_value = param_value case "string_array": - if type(param_value) != list or type(param_value[0]) != str: + if type(param_value) is not list or type(param_value[0]) is not str: ui.notify("Please select one or more strings") return parameter.value.type = ParameterType.PARAMETER_STRING_ARRAY diff --git a/atos_gui/atos_gui/configpanel/local_file_picker.py b/atos_gui/atos_gui/configpanel/local_file_picker.py index 5ca2288fb..ade84b393 100644 --- a/atos_gui/atos_gui/configpanel/local_file_picker.py +++ b/atos_gui/atos_gui/configpanel/local_file_picker.py @@ -1,10 +1,9 @@ """This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. -""" -"""This file is taken from the NiceGUI repository and added some dosctrings for clarifications. -Original file: https://github.com/zauberzeug/nicegui/blob/main/examples/local_file_picker/local_file_picker.py """ +This file is taken from the NiceGUI repository and added some dosctrings for clarifications. +Original file: https://github.com/zauberzeug/nicegui/blob/main/examples/local_file_picker/local_file_picker.py""" import platform from pathlib import Path diff --git a/atos_gui/atos_gui/controlpanel/controlpanel.py b/atos_gui/atos_gui/controlpanel/controlpanel.py index e302cdb12..7fa56a595 100644 --- a/atos_gui/atos_gui/controlpanel/controlpanel.py +++ b/atos_gui/atos_gui/controlpanel/controlpanel.py @@ -8,9 +8,9 @@ from rclpy.node import Node from std_msgs.msg import Empty -from atos_interfaces.srv import * from atos_gui.mapview.map_data import MapDataSource from atos_gui.mapview.map_view import MapView +from atos_interfaces.srv import GetObjectControlState QOS = rclpy.qos.QoSProfile(depth=10) diff --git a/atos_gui/atos_gui/mapview/geo.py b/atos_gui/atos_gui/mapview/geo.py index 665067922..237b48826 100644 --- a/atos_gui/atos_gui/mapview/geo.py +++ b/atos_gui/atos_gui/mapview/geo.py @@ -1,9 +1,8 @@ """This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. -""" -"""Conversions from the ATOS local test frame to WGS84 for the map view. +Conversions from the ATOS local test frame to WGS84 for the map view. ATOS' local frame (see EsminiAdapter, esminiadapter.cpp) is a transverse Mercator projection centred on the test origin: @@ -65,7 +64,9 @@ def from_lonlat(self, lons, lats) -> tuple[np.ndarray, np.ndarray]: """WGS84 longitude/latitude (degrees) to local x/y (metres).""" return self._transform(self._from_wgs84, lons, lats) - def _transform(self, transformer: Transformer, a, b) -> tuple[np.ndarray, np.ndarray]: + def _transform( + self, transformer: Transformer, a, b + ) -> tuple[np.ndarray, np.ndarray]: a = np.asarray(a, dtype=float) b = np.asarray(b, dtype=float) with self._lock: @@ -93,7 +94,9 @@ def poses_to_geo(self, xs, ys, yaws) -> tuple[np.ndarray, np.ndarray, np.ndarray ) if lons.size == 1: # Same single-point fast path as in _transform. - azimuth, _, _ = WGS84.inv(lons.item(), lats.item(), lons_ahead.item(), lats_ahead.item()) + azimuth, _, _ = WGS84.inv( + lons.item(), lats.item(), lons_ahead.item(), lats_ahead.item() + ) azimuths = np.full(lons.shape, azimuth) else: azimuths, _, _ = WGS84.inv(lons, lats, lons_ahead, lats_ahead) diff --git a/atos_gui/atos_gui/mapview/map_data.py b/atos_gui/atos_gui/mapview/map_data.py index 5a82afbc1..1961d675f 100644 --- a/atos_gui/atos_gui/mapview/map_data.py +++ b/atos_gui/atos_gui/mapview/map_data.py @@ -1,9 +1,8 @@ """This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. -""" -"""ROS side of the map view: collects the test origin, scenario trajectories and live +ROS side of the map view: collects the test origin, scenario trajectories and live object poses, and converts them to WGS84 for the browser. Data sources (all in the ATOS local frame, see geo.py): @@ -19,14 +18,14 @@ import threading import time -import rclpy -from atos_interfaces.msg import Monitor, ObjectIdArray, StateChange -from atos_interfaces.srv import GetObjectIds, GetTestOrigin from nav_msgs.msg import Path from rclpy.callback_groups import MutuallyExclusiveCallbackGroup from rclpy.node import Node from rclpy.qos import DurabilityPolicy, QoSProfile +from atos_interfaces.msg import Monitor, ObjectIdArray, StateChange +from atos_interfaces.srv import GetObjectIds, GetTestOrigin + from .geo import LocalFrame, decimate, yaw_from_quaternion # ObjectControl states as returned by GetObjectControlState / StateChange (OBCState_t). @@ -76,15 +75,25 @@ def __init__(self, node: Node, get_control_state=lambda: None) -> None: GetTestOrigin, "/atos/get_test_origin", callback_group=cb ) node.create_subscription( - StateChange, "/atos/state_change", self._on_state_change, - QoSProfile(depth=10), callback_group=cb, + StateChange, + "/atos/state_change", + self._on_state_change, + QoSProfile(depth=10), + callback_group=cb, ) node.create_subscription( - Monitor, "/atos/object_monitor", self._on_monitor, LATEST_QOS, callback_group=cb + Monitor, + "/atos/object_monitor", + self._on_monitor, + LATEST_QOS, + callback_group=cb, ) node.create_subscription( - ObjectIdArray, "/atos/connected_object_ids", self._on_connected_ids, - QoSProfile(depth=10), callback_group=cb, + ObjectIdArray, + "/atos/connected_object_ids", + self._on_connected_ids, + QoSProfile(depth=10), + callback_group=cb, ) node.create_timer(1.0, self._maintain, callback_group=cb) @@ -151,12 +160,18 @@ def on_done(fut): return on_result(result) - timer = self.node.create_timer(timeout_s, on_timeout, callback_group=self._cb_group) + timer = self.node.create_timer( + timeout_s, on_timeout, callback_group=self._cb_group + ) future.add_done_callback(on_done) def _load_object_ids(self) -> None: self._call_with_timeout( - self._ids_client, GetObjectIds.Request(), IDS_TIMEOUT_S, self._on_object_ids, "object ids" + self._ids_client, + GetObjectIds.Request(), + IDS_TIMEOUT_S, + self._on_object_ids, + "object ids", ) def _on_object_ids(self, result) -> None: @@ -167,7 +182,11 @@ def _on_object_ids(self, result) -> None: with self._lock: self.object_names = names self._call_with_timeout( - self._origin_client, GetTestOrigin.Request(), ORIGIN_TIMEOUT_S, self._on_origin, "test origin" + self._origin_client, + GetTestOrigin.Request(), + ORIGIN_TIMEOUT_S, + self._on_origin, + "test origin", ) def _on_origin(self, result) -> None: @@ -222,7 +241,9 @@ def _convert_path(frame: LocalFrame, xs, ys) -> list[list[float]]: return [] keep = decimate(xs, ys) lons, lats = frame.to_lonlat([xs[i] for i in keep], [ys[i] for i in keep]) - return [[round(float(lat), 9), round(float(lon), 9)] for lat, lon in zip(lats, lons)] + return [ + [round(float(lat), 9), round(float(lon), 9)] for lat, lon in zip(lats, lons) + ] def _on_path(self, object_id: int, msg: Path) -> None: xs = [pose.pose.position.x for pose in msg.poses] @@ -243,7 +264,9 @@ def _on_monitor(self, msg: Monitor) -> None: "x": pose.position.x, "y": pose.position.y, "yaw": yaw_from_quaternion(q.x, q.y, q.z, q.w), - "speed": math.hypot(msg.velocity.twist.linear.x, msg.velocity.twist.linear.y), + "speed": math.hypot( + msg.velocity.twist.linear.x, msg.velocity.twist.linear.y + ), "state": int(msg.object_state.state), "received": time.monotonic(), } @@ -269,7 +292,11 @@ def snapshot(self, known_traj_version: int | None) -> dict: names = dict(self.object_names) connected_fresh = now - self._connected_ids_stamp < CONNECTED_IDS_MAX_AGE_S connected = set(self._connected_ids) if connected_fresh else set() - for object_id in [i for i, m in self._monitors.items() if now - m["received"] > MONITOR_FORGET_S]: + for object_id in [ + i + for i, m in self._monitors.items() + if now - m["received"] > MONITOR_FORGET_S + ]: del self._monitors[object_id] monitors = {i: dict(m) for i, m in self._monitors.items()} payload = { @@ -279,7 +306,11 @@ def snapshot(self, known_traj_version: int | None) -> dict: } if known_traj_version != self.traj_version: payload["trajectories"] = [ - {"id": object_id, "name": names.get(object_id, f"Object {object_id}"), "latlngs": latlngs} + { + "id": object_id, + "name": names.get(object_id, f"Object {object_id}"), + "latlngs": latlngs, + } for object_id, latlngs in sorted(self._geo_paths.items()) if latlngs ] diff --git a/atos_gui/atos_gui/mapview/map_view.py b/atos_gui/atos_gui/mapview/map_view.py index dee0efb17..b68139bbb 100644 --- a/atos_gui/atos_gui/mapview/map_view.py +++ b/atos_gui/atos_gui/mapview/map_view.py @@ -1,9 +1,8 @@ """This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. -""" -"""NiceGUI part of the map view: a resizable satellite map with scenario +NiceGUI part of the map view: a resizable satellite map with scenario trajectories and live, heading-rotated object markers, plus style settings. The overlays are drawn by static/atos_map.js; this module creates the ui.leaflet @@ -24,7 +23,16 @@ SETTINGS_KEY = "atos_map_settings" # Bright colours that stay readable on aerial imagery. -PALETTE = ["#ffd400", "#00e5ff", "#ff4fd8", "#7cfc00", "#ff8c00", "#ffffff", "#ff3b3b", "#9b8cff"] +PALETTE = [ + "#ffd400", + "#00e5ff", + "#ff4fd8", + "#7cfc00", + "#ff8c00", + "#ffffff", + "#ff3b3b", + "#9b8cff", +] DEFAULT_SETTINGS = { "trajectory": {"width": 3, "dash": "solid", "opacity": 0.9}, @@ -34,9 +42,23 @@ "colorOverrides": {}, } -DASH_OPTIONS = {"solid": "Solid", "dashed": "Dashed", "dotted": "Dotted", "dashdot": "Dash-dot"} -SHAPE_OPTIONS = {"arrow": "Arrow", "chevron": "Chevron", "vehicle": "Vehicle", "circle": "Circle + heading"} -BASE_OPTIONS = {"satellite": "Satellite (Esri World Imagery)", "osm": "OpenStreetMap", "custom": "Custom tile URL"} +DASH_OPTIONS = { + "solid": "Solid", + "dashed": "Dashed", + "dotted": "Dotted", + "dashdot": "Dash-dot", +} +SHAPE_OPTIONS = { + "arrow": "Arrow", + "chevron": "Chevron", + "vehicle": "Vehicle", + "circle": "Circle + heading", +} +BASE_OPTIONS = { + "satellite": "Satellite (Esri World Imagery)", + "osm": "OpenStreetMap", + "custom": "Custom tile URL", +} def load_settings() -> dict: @@ -66,17 +88,23 @@ def __init__(self, data: MapDataSource) -> None: self._known_ids: list[int] = [] self._color_inputs: dict[int, ui.color_input] = {} - ui.add_head_html(f'') + ui.add_head_html( + f'' + ) with ui.card().classes("w-full"): with ui.row().classes("w-full items-center gap-2"): ui.label("Map").classes("text-lg font-medium") self.status_label = ui.label().classes("text-sm text-grey-7") ui.space() - self.follow_select = ui.select( - {"": "Follow: off"}, value="", on_change=self._on_follow - ).props("dense outlined options-dense").classes("w-44") - ui.button("Fit to scenario", icon="fit_screen", on_click=self._fit).props("flat dense") + self.follow_select = ( + ui.select({"": "Follow: off"}, value="", on_change=self._on_follow) + .props("dense outlined options-dense") + .classes("w-44") + ) + ui.button( + "Fit to scenario", icon="fit_screen", on_click=self._fit + ).props("flat dense") with ui.row().classes("w-full items-start gap-4 md:flex-nowrap"): # Drag the bottom-right corner to resize; atos_map.js reflows the map @@ -104,42 +132,91 @@ def _build_settings(self) -> None: s = self.settings with ui.expansion("Map settings", icon="tune").classes("w-full").props("dense"): ui.label("Trajectory").classes("text-sm font-medium") - ui.label().bind_text_from(s["trajectory"], "width", lambda v: f"Width: {v} px").classes("text-xs") - ui.slider(min=1, max=12, step=1, value=s["trajectory"]["width"], - on_change=lambda e: self._set("trajectory", "width", e.value)) - ui.select(DASH_OPTIONS, label="Line style", value=s["trajectory"]["dash"], - on_change=lambda e: self._set("trajectory", "dash", e.value)).classes("w-full") - ui.label().bind_text_from(s["trajectory"], "opacity", lambda v: f"Opacity: {round(v * 100)} %").classes("text-xs") - ui.slider(min=0.1, max=1.0, step=0.05, value=s["trajectory"]["opacity"], - on_change=lambda e: self._set("trajectory", "opacity", e.value)) + ui.label().bind_text_from( + s["trajectory"], "width", lambda v: f"Width: {v} px" + ).classes("text-xs") + ui.slider( + min=1, + max=12, + step=1, + value=s["trajectory"]["width"], + on_change=lambda e: self._set("trajectory", "width", e.value), + ) + ui.select( + DASH_OPTIONS, + label="Line style", + value=s["trajectory"]["dash"], + on_change=lambda e: self._set("trajectory", "dash", e.value), + ).classes("w-full") + ui.label().bind_text_from( + s["trajectory"], "opacity", lambda v: f"Opacity: {round(v * 100)} %" + ).classes("text-xs") + ui.slider( + min=0.1, + max=1.0, + step=0.05, + value=s["trajectory"]["opacity"], + on_change=lambda e: self._set("trajectory", "opacity", e.value), + ) ui.separator() ui.label("Object marker").classes("text-sm font-medium") - ui.label().bind_text_from(s["marker"], "size", lambda v: f"Size: {v} px").classes("text-xs") - ui.slider(min=12, max=96, step=2, value=s["marker"]["size"], - on_change=lambda e: self._set("marker", "size", e.value)) - ui.select(SHAPE_OPTIONS, label="Marker style", value=s["marker"]["shape"], - on_change=lambda e: self._set("marker", "shape", e.value)).classes("w-full") - ui.switch("Show labels", value=s["marker"]["labels"], - on_change=lambda e: self._set("marker", "labels", e.value)) + ui.label().bind_text_from( + s["marker"], "size", lambda v: f"Size: {v} px" + ).classes("text-xs") + ui.slider( + min=12, + max=96, + step=2, + value=s["marker"]["size"], + on_change=lambda e: self._set("marker", "size", e.value), + ) + ui.select( + SHAPE_OPTIONS, + label="Marker style", + value=s["marker"]["shape"], + on_change=lambda e: self._set("marker", "shape", e.value), + ).classes("w-full") + ui.switch( + "Show labels", + value=s["marker"]["labels"], + on_change=lambda e: self._set("marker", "labels", e.value), + ) ui.separator() ui.label("Object colours").classes("text-sm font-medium") self.colors_column = ui.column().classes("w-full gap-1") - ui.button("Reset colours", on_click=self._reset_colors).props("flat dense size=sm") + ui.button("Reset colours", on_click=self._reset_colors).props( + "flat dense size=sm" + ) ui.separator() ui.label("Base map").classes("text-sm font-medium") - ui.select(BASE_OPTIONS, value=s["base"], - on_change=lambda e: self._set(None, "base", e.value)).classes("w-full") - custom_url = ui.input( - "Custom tile URL", value=s["customUrl"], placeholder="https://host/{z}/{x}/{y}.png" - ).classes("w-full").bind_visibility_from(s, "base", lambda v: v == "custom") + ui.select( + BASE_OPTIONS, + value=s["base"], + on_change=lambda e: self._set(None, "base", e.value), + ).classes("w-full") + custom_url = ( + ui.input( + "Custom tile URL", + value=s["customUrl"], + placeholder="https://host/{z}/{x}/{y}.png", + ) + .classes("w-full") + .bind_visibility_from(s, "base", lambda v: v == "custom") + ) # Apply on blur/enter only, so typing does not reload tiles per keystroke. for event in ("blur", "keydown.enter"): - custom_url.on(event, lambda: self._set(None, "customUrl", (custom_url.value or "").strip())) - ui.label("Satellite imagery: Esri World Imagery (no API key, attribution required).").classes( - "text-xs text-grey-7") + custom_url.on( + event, + lambda: self._set( + None, "customUrl", (custom_url.value or "").strip() + ), + ) + ui.label( + "Satellite imagery: Esri World Imagery (no API key, attribution required)." + ).classes("text-xs text-grey-7") def _set(self, group: str | None, key: str, value) -> None: target = self.settings[group] if group else self.settings @@ -152,7 +229,8 @@ def _set(self, group: str | None, key: str, value) -> None: def _object_colors(self) -> dict[str, str]: overrides = self.settings["colorOverrides"] return { - str(object_id): overrides.get(str(object_id)) or PALETTE[index % len(PALETTE)] + str(object_id): overrides.get(str(object_id)) + or PALETTE[index % len(PALETTE)] for index, object_id in enumerate(self._known_ids) } @@ -182,14 +260,25 @@ def _rebuild_object_controls(self, names: dict[int, str]) -> None: if not self._known_ids: ui.label("No objects yet").classes("text-xs text-grey-7") for object_id in self._known_ids: - self._color_inputs[object_id] = ui.color_input( - names.get(object_id, f"Object {object_id}"), - value=colors[str(object_id)], - on_change=lambda e, object_id=object_id: self._set_color(object_id, e.value), - ).props("dense").classes("w-full") + self._color_inputs[object_id] = ( + ui.color_input( + names.get(object_id, f"Object {object_id}"), + value=colors[str(object_id)], + on_change=lambda e, object_id=object_id: self._set_color( + object_id, e.value + ), + ) + .props("dense") + .classes("w-full") + ) options = {"": "Follow: off"} options.update({str(i): f"Follow: {names.get(i, i)}" for i in self._known_ids}) - self.follow_select.set_options(options, value=self.follow_select.value if self.follow_select.value in options else "") + self.follow_select.set_options( + options, + value=self.follow_select.value + if self.follow_select.value in options + else "", + ) def _style_payload(self) -> dict: s = self.settings @@ -206,7 +295,9 @@ def _js(self, code: str) -> None: def _push_style(self) -> None: if self.map.is_initialized: - self._js(f"window.atosMap.setStyle({self.map.id}, {json.dumps(self._style_payload())})") + self._js( + f"window.atosMap.setStyle({self.map.id}, {json.dumps(self._style_payload())})" + ) # ------------------------------------------------------------------ updates @@ -241,7 +332,9 @@ async def _tick(self) -> None: if self._sent_origin is not None: self._js(f"window.atosMap.reset({self.map.id})") self._sent_origin = payload["origin"] - payload["trajectories"] = payload.get("trajectories") or self.data.snapshot(None)["trajectories"] + payload["trajectories"] = ( + payload.get("trajectories") or self.data.snapshot(None)["trajectories"] + ) self._js(f"window.atosMap.update({self.map.id}, {json.dumps(payload)})") self._sent_traj_version = payload["traj_version"] diff --git a/atos_gui/test/test_geo.py b/atos_gui/test/test_geo.py index e0231641c..c740c139c 100644 --- a/atos_gui/test/test_geo.py +++ b/atos_gui/test/test_geo.py @@ -77,7 +77,9 @@ def test_yaw_to_bearing_on_central_meridian(frame, yaw, bearing): def test_meridian_convergence_sign(frame): # Grid north east of the central meridian (northern hemisphere) is rotated # clockwise from true north by about dlon * sin(lat); west of it, anticlockwise. - _, _, bearings = frame.poses_to_geo([2000.0, -2000.0], [0.0, 0.0], [math.pi / 2] * 2) + _, _, bearings = frame.poses_to_geo( + [2000.0, -2000.0], [0.0, 0.0], [math.pi / 2] * 2 + ) lons, _ = frame.to_lonlat([2000.0], [0.0]) expected = (lons[0] - ORIGIN_LON) * math.sin(math.radians(ORIGIN_LAT)) assert expected > 0.02 # big enough for the test to mean something @@ -105,7 +107,9 @@ def test_differs_from_flat_earth_gnss_topics_as_expected(frame): a = 6378137.0 for x, y in [(1000.0, 0.0), (0.0, 1000.0), (-700.0, 700.0)]: flat_lat = ORIGIN_LAT + y / a * 180 / math.pi - flat_lon = ORIGIN_LON + x / a * 180 / math.pi / math.cos(math.radians(ORIGIN_LAT)) + flat_lon = ORIGIN_LON + x / a * 180 / math.pi / math.cos( + math.radians(ORIGIN_LAT) + ) lons, lats = frame.to_lonlat([x], [y]) _, _, error = WGS84.inv(flat_lon, flat_lat, lons[0], lats[0]) assert error < 0.003 * math.hypot(x, y) @@ -114,7 +118,9 @@ def test_differs_from_flat_earth_gnss_topics_as_expected(frame): def test_yaw_from_quaternion(): for yaw in [0.0, 0.3, math.pi / 2, 3.0, -2.0]: q = (0.0, 0.0, math.sin(yaw / 2), math.cos(yaw / 2)) - assert yaw_from_quaternion(*q) == pytest.approx(math.atan2(math.sin(yaw), math.cos(yaw))) + assert yaw_from_quaternion(*q) == pytest.approx( + math.atan2(math.sin(yaw), math.cos(yaw)) + ) assert yaw_from_quaternion(0.0, 0.0, 0.0, 1.0) == 0.0 diff --git a/atos_gui/test/test_map_data.py b/atos_gui/test/test_map_data.py index 0e9ee5b6a..3aa5e7926 100644 --- a/atos_gui/test/test_map_data.py +++ b/atos_gui/test/test_map_data.py @@ -1,9 +1,8 @@ """This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/. -""" -"""MapDataSource tests with a fake rclpy node (no ROS graph needed).""" +MapDataSource tests with a fake rclpy node (no ROS graph needed).""" import math from types import SimpleNamespace as NS @@ -115,7 +114,10 @@ def monitor_msg(object_id, x, y, yaw, vx=3.0, vy=4.0): def origin_result(lat, lon, success=True): - return NS(success=success, origin=NS(position=NS(latitude=lat, longitude=lon, altitude=0.0))) + return NS( + success=success, + origin=NS(position=NS(latitude=lat, longitude=lon, altitude=0.0)), + ) @pytest.fixture @@ -130,7 +132,9 @@ def setup(): def load(node, state, maintain, ids=(1, 2), names=("Car", "Truck")): state["value"] = 2 maintain() - node.clients["/atos/get_object_ids"].calls[-1].set_result(NS(ids=list(ids), names=list(names))) + node.clients["/atos/get_object_ids"].calls[-1].set_result( + NS(ids=list(ids), names=list(names)) + ) node.clients["/atos/get_test_origin"].calls[-1].set_result(origin_result(*ORIGIN)) @@ -163,7 +167,9 @@ def test_load_sequence_and_snapshot(setup): assert obj["lat"] == pytest.approx(lats[0], abs=1e-8) assert obj["lon"] == pytest.approx(lons[0], abs=1e-8) assert obj["bearing"] == pytest.approx(bearings[0], abs=0.01) - assert obj["bearing"] == pytest.approx(0.0, abs=0.01) or obj["bearing"] == pytest.approx(360.0, abs=0.01) + assert obj["bearing"] == pytest.approx(0.0, abs=0.01) or obj[ + "bearing" + ] == pytest.approx(360.0, abs=0.01) assert obj["speed"] == pytest.approx(5.0) assert obj["stale"] is False @@ -175,7 +181,9 @@ def test_path_received_before_origin_is_converted_later(setup): node, state, data, maintain = setup state["value"] = 2 maintain() - node.clients["/atos/get_object_ids"].calls[-1].set_result(NS(ids=[1], names=["Car"])) + node.clients["/atos/get_object_ids"].calls[-1].set_result( + NS(ids=[1], names=["Car"]) + ) assert data.frame is None # Origin not answered yet; a (re)subscribed path arrives via a previous subscription. data._on_path(1, path_msg([(0, 0), (5, 5)])) @@ -208,7 +216,9 @@ def test_origin_timeout_reports_and_retries(setup): node, state, data, maintain = setup state["value"] = 2 maintain() - node.clients["/atos/get_object_ids"].calls[-1].set_result(NS(ids=[1], names=["Car"])) + node.clients["/atos/get_object_ids"].calls[-1].set_result( + NS(ids=[1], names=["Car"]) + ) origin_client = node.clients["/atos/get_test_origin"] timeout_timer = node.timers[-1] assert timeout_timer.period == map_data.ORIGIN_TIMEOUT_S @@ -248,6 +258,10 @@ def test_missing_georeference(setup): node, state, data, maintain = setup state["value"] = 2 maintain() - node.clients["/atos/get_object_ids"].calls[-1].set_result(NS(ids=[1], names=["Car"])) - node.clients["/atos/get_test_origin"].calls[-1].set_result(origin_result(float("nan"), 0.0)) + node.clients["/atos/get_object_ids"].calls[-1].set_result( + NS(ids=[1], names=["Car"]) + ) + node.clients["/atos/get_test_origin"].calls[-1].set_result( + origin_result(float("nan"), 0.0) + ) assert data.frame is None and "geo-reference" in data.status From 4f4ee38d051364b75453e412bccd1f25f1db74fc Mon Sep 17 00:00:00 2001 From: Robert Brenick Date: Mon, 9 Nov 2026 11:58:14 -0600 Subject: [PATCH 5/8] Require pytest 7.x in the ATOS venv on Python >= 3.10 anyio 4 (required by NiceGUI) registers a pytest plugin that imports _pytest.scope, added in pytest 7.0. The venv uses --system-site-packages, and Ubuntu 22.04's system pytest 6.2.5 satisfied the old pin, so the integration test (python3 -m pytest in the venv) failed at start-up with "No module named '_pytest.scope'". Require pytest >= 7.0 (still < 7.5) on Python >= 3.10 so pip installs 7.4.4 into the venv. Co-Authored-By: Claude Opus 5.5 --- scripts/installation/requirements.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/installation/requirements.txt b/scripts/installation/requirements.txt index 39a8508ca..2c297ccf2 100644 --- a/scripts/installation/requirements.txt +++ b/scripts/installation/requirements.txt @@ -2,7 +2,10 @@ pre-commit pyOpenSSL >= 23.2.0 numpy<2.0 scenariogeneration -pytest>=6.2,<7.5 +pytest>=6.2,<7.5; python_version < "3.10" +# anyio 4 (below) installs a pytest plugin that needs pytest >= 7. Ubuntu 22.04's system +# pytest 6.2.5 would satisfy a looser pin through --system-site-packages, so require 7.x here. +pytest>=7.0,<7.5; python_version >= "3.10" # NiceGUI (atos_gui, installed in the same venv) requires anyio >= 4.14.2. # Python < 3.10 (ROS 2 Foxy) gets no GUI and keeps the old pin. anyio>=3.6,<4.0; python_version < "3.10" From ab5df580162b98d94aeb6cfa914e092e45815ae9 Mon Sep 17 00:00:00 2001 From: Robert Brenick Date: Mon, 9 Nov 2026 15:48:30 -0600 Subject: [PATCH 6/8] Map view: collapsible settings pane and window-following map size - The settings pane is toggled from a "Map settings" button in the map header and only takes space while open; closed, the map uses the full width. - Only a drag of the resize handle is remembered, and the width is stored as a percentage of the available width. Window resizes no longer get persisted as a fixed pixel width that kept the map small after the window grew again, also across reloads. The storage key changes so the old pixel sizes are ignored. Co-Authored-By: Claude Opus 5.5 --- atos_gui/atos_gui/mapview/map_view.py | 33 ++++++++++++++---- atos_gui/atos_gui/static/atos_map.js | 49 ++++++++++++++++++--------- 2 files changed, 59 insertions(+), 23 deletions(-) diff --git a/atos_gui/atos_gui/mapview/map_view.py b/atos_gui/atos_gui/mapview/map_view.py index b68139bbb..f63e222c9 100644 --- a/atos_gui/atos_gui/mapview/map_view.py +++ b/atos_gui/atos_gui/mapview/map_view.py @@ -18,7 +18,7 @@ from .map_data import MapDataSource STATIC_ROUTE = "/atos_gui_static" -MAP_JS_VERSION = "20261109-1" +MAP_JS_VERSION = "20261109-2" UI_RATE_S = 0.1 SETTINGS_KEY = "atos_map_settings" @@ -87,6 +87,7 @@ def __init__(self, data: MapDataSource) -> None: self._style_sent = False self._known_ids: list[int] = [] self._color_inputs: dict[int, ui.color_input] = {} + self.settings_open = False ui.add_head_html( f'' @@ -105,14 +106,21 @@ def __init__(self, data: MapDataSource) -> None: ui.button( "Fit to scenario", icon="fit_screen", on_click=self._fit ).props("flat dense") + self.settings_button = ui.button( + "Map settings", icon="tune", on_click=self._toggle_settings + ).props("flat dense") with ui.row().classes("w-full items-start gap-4 md:flex-nowrap"): # Drag the bottom-right corner to resize; atos_map.js reflows the map # and remembers the size in the browser. - with ui.element("div").style( - "resize: both; overflow: hidden; width: 100%; max-width: 100%;" - "height: 60vh; min-height: 250px; min-width: 280px;" - "border-radius: 8px; border: 1px solid rgba(128,128,128,.4);" + with ( + ui.element("div") + .classes("min-w-0") + .style( + "resize: both; overflow: hidden; width: 100%; max-width: 100%;" + "height: 60vh; min-height: 250px; min-width: 280px;" + "border-radius: 8px; border: 1px solid rgba(128,128,128,.4);" + ) ): self.map = ui.leaflet( center=(0.0, 0.0), zoom=2, options={"maxZoom": 22} @@ -121,16 +129,27 @@ def __init__(self, data: MapDataSource) -> None: # Not initialized yet, so clearing the Python-side list is enough. self.map.layers.clear() - with ui.column().classes("w-full md:w-72 shrink-0"): + # Only takes space while open; otherwise the map gets the full width. + settings_pane = ui.column().classes("w-full md:w-72 shrink-0") + settings_pane.bind_visibility_from(self, "settings_open") + with settings_pane: self._build_settings() ui.timer(UI_RATE_S, self._tick) # ---------------------------------------------------------------- settings + def _toggle_settings(self) -> None: + self.settings_open = not self.settings_open + # Filled button while the pane is open, flat while it is closed. + if self.settings_open: + self.settings_button.props(remove="flat") + else: + self.settings_button.props("flat") + def _build_settings(self) -> None: s = self.settings - with ui.expansion("Map settings", icon="tune").classes("w-full").props("dense"): + with ui.column().classes("w-full gap-2"): ui.label("Trajectory").classes("text-sm font-medium") ui.label().bind_text_from( s["trajectory"], "width", lambda v: f"Width: {v} px" diff --git a/atos_gui/atos_gui/static/atos_map.js b/atos_gui/atos_gui/static/atos_map.js index 63f60bc18..63cc38d78 100644 --- a/atos_gui/atos_gui/static/atos_map.js +++ b/atos_gui/atos_gui/static/atos_map.js @@ -14,7 +14,9 @@ (function () { "use strict"; - const SIZE_STORAGE_KEY = "atosMapSize"; + // v2: width is stored as a percentage of the available width. The old key held + // absolute pixels, which also captured window shrinks and pinned the map small. + const SIZE_STORAGE_KEY = "atosMapSize2"; const BASE_LAYERS = { satellite: { @@ -128,28 +130,43 @@ return comp._atos; } + // Only a drag of the resize handle is remembered. Window resizes just reflow the + // map: the width stays a percentage, so the map grows again with the window. function watchResize(comp) { const wrapper = comp.$el.parentElement; if (!wrapper) return; const saved = storageGet(SIZE_STORAGE_KEY); if (saved && saved.h > 0) wrapper.style.height = `${saved.h}px`; - if (saved && saved.w > 0) wrapper.style.width = `${saved.w}px`; - let timer = null; - let first = true; - const observer = new ResizeObserver(() => { - comp.map.invalidateSize({ pan: false }); - if (first) { - first = false; // initial notification, not a user resize - return; - } - clearTimeout(timer); - timer = setTimeout( - () => storageSet(SIZE_STORAGE_KEY, { w: wrapper.offsetWidth, h: wrapper.offsetHeight }), - 300, + if (saved && saved.wPct > 0) wrapper.style.width = `${Math.min(100, saved.wPct)}%`; + + const observer = new ResizeObserver(() => comp.map.invalidateSize({ pan: false })); + observer.observe(wrapper); + + // The resize grip belongs to the wrapper itself; the map covers everything else. + const onPointerDown = (ev) => { + if (ev.target !== wrapper) return; + const startW = wrapper.offsetWidth; + const startH = wrapper.offsetHeight; + window.addEventListener( + "pointerup", + () => { + const w = wrapper.offsetWidth; + const h = wrapper.offsetHeight; + if (w === startW && h === startH) return; + const avail = wrapper.parentElement ? wrapper.parentElement.clientWidth : 0; + const wPct = avail > 0 ? Math.min(100, (w / avail) * 100) : 100; + // Replace the browser's pixel width with a relative one. + wrapper.style.width = `${wPct}%`; + storageSet(SIZE_STORAGE_KEY, { wPct, h }); + }, + { once: true }, ); + }; + wrapper.addEventListener("pointerdown", onPointerDown); + comp.map.on("unload", () => { + observer.disconnect(); + wrapper.removeEventListener("pointerdown", onPointerDown); }); - observer.observe(wrapper); - comp.map.on("unload", () => observer.disconnect()); } function applyBaseLayer(state) { From efa604cc35837b63323473e06295eab085c3076c Mon Sep 17 00:00:00 2001 From: Robert Brenick Date: Mon, 9 Nov 2026 16:50:34 -0600 Subject: [PATCH 7/8] Map view: optional scenario origin marker - New "Show origin and x/y axes" map setting, off by default and saved on the ATOS host like the other settings. It draws a crosshair at the test origin with the local frame's x (east) and y (north) axes; hovering it shows the origin's latitude and longitude. The marker follows origin changes after a new Init and is cleared on reset. - Docs: describe the new setting, the Map settings pane and the map following the window width. Co-Authored-By: Claude Opus 5.5 --- atos_gui/atos_gui/mapview/map_view.py | 12 +++++- atos_gui/atos_gui/static/atos_map.js | 53 +++++++++++++++++++++++++++ docs/Usage/GUI/controlpanel.md | 5 ++- 3 files changed, 67 insertions(+), 3 deletions(-) diff --git a/atos_gui/atos_gui/mapview/map_view.py b/atos_gui/atos_gui/mapview/map_view.py index f63e222c9..304ec2b1b 100644 --- a/atos_gui/atos_gui/mapview/map_view.py +++ b/atos_gui/atos_gui/mapview/map_view.py @@ -18,7 +18,7 @@ from .map_data import MapDataSource STATIC_ROUTE = "/atos_gui_static" -MAP_JS_VERSION = "20261109-2" +MAP_JS_VERSION = "20261109-3" UI_RATE_S = 0.1 SETTINGS_KEY = "atos_map_settings" @@ -37,6 +37,7 @@ DEFAULT_SETTINGS = { "trajectory": {"width": 3, "dash": "solid", "opacity": 0.9}, "marker": {"shape": "arrow", "size": 32, "labels": True}, + "showOrigin": False, "base": "satellite", "customUrl": "", "colorOverrides": {}, @@ -202,6 +203,14 @@ def _build_settings(self) -> None: on_change=lambda e: self._set("marker", "labels", e.value), ) + ui.separator() + ui.label("Scenario origin").classes("text-sm font-medium") + ui.switch( + "Show origin and x/y axes", + value=s["showOrigin"], + on_change=lambda e: self._set(None, "showOrigin", e.value), + ) + ui.separator() ui.label("Object colours").classes("text-sm font-medium") self.colors_column = ui.column().classes("w-full gap-1") @@ -304,6 +313,7 @@ def _style_payload(self) -> dict: return { "trajectory": s["trajectory"], "marker": s["marker"], + "showOrigin": s["showOrigin"], "base": s["base"], "customUrl": s["customUrl"], "colors": self._object_colors(), diff --git a/atos_gui/atos_gui/static/atos_map.js b/atos_gui/atos_gui/static/atos_map.js index 63cc38d78..6b3c213ee 100644 --- a/atos_gui/atos_gui/static/atos_map.js +++ b/atos_gui/atos_gui/static/atos_map.js @@ -118,6 +118,8 @@ fitted: false, centeredOnOrigin: false, follow: null, + origin: null, // [lat, lon] of the scenario's local frame origin + originMarker: null, imageryMaxZoom: null, // deepest Esri zoom with imagery over the scenario generation: 0, // bumped on reset, so late probe results are ignored }; @@ -364,6 +366,49 @@ } } + // Crosshair at the local frame origin with its x (east) and y (north) axes. + const ORIGIN_ICON_SIZE = 56; + function originIcon() { + const n = ORIGIN_ICON_SIZE; + const c = n / 2; + const axis = (x2, y2, color) => + `` + + ``; + const html = + `` + + axis(n - 4, c, "#ff3b3b") + + axis(c, 4, "#7cfc00") + + `` + + `` + + `x` + + `y` + + `` + + `` + + `` + + ``; + return window.L.divIcon({ className: "atos-obj-icon", html, iconSize: [n, n], iconAnchor: [c, c] }); + } + + /** Show, move or remove the origin marker to match the setting and the latest origin. */ + function syncOrigin(state) { + const show = !!(state.style && state.style.showOrigin) && !!state.origin; + if (!show) { + if (state.originMarker) state.map.removeLayer(state.originMarker); + state.originMarker = null; + return; + } + const [lat, lon] = state.origin; + if (!state.originMarker) { + state.originMarker = window.L.marker([lat, lon], { icon: originIcon(), keyboard: false, zIndexOffset: 500 }).addTo( + state.map, + ); + state.originMarker.bindTooltip("", { direction: "top", offset: [0, -ORIGIN_ICON_SIZE / 2] }); + } else { + state.originMarker.setLatLng([lat, lon]); + } + state.originMarker.setTooltipContent(`Scenario origin
${lat.toFixed(7)}, ${lon.toFixed(7)}`); + } + function scenarioBounds(state) { let bounds = null; for (const traj of Object.values(state.trajectories)) { @@ -406,6 +451,7 @@ for (const [id, traj] of Object.entries(state.trajectories)) styleTrajectory(state, id, traj); for (const obj of Object.values(state.objects)) obj.shapeKey = null; // rebuild icons setObjects(state, state.lastObjects); + syncOrigin(state); return true; }, @@ -417,6 +463,11 @@ state.centeredOnOrigin = true; if (!state.fitted) state.map.setView(payload.origin, Math.min(17, nativeMaxZoom(state))); } + const origin = payload.origin || null; + if (String(origin) !== String(state.origin)) { + state.origin = origin; + syncOrigin(state); + } if (payload.trajectories) setTrajectories(state, payload.trajectories); if (payload.objects) setObjects(state, payload.objects); return true; @@ -444,6 +495,8 @@ state.trajectories = {}; state.objects = {}; state.lastObjects = []; + state.origin = null; + syncOrigin(state); state.fitted = false; state.centeredOnOrigin = false; state.imageryMaxZoom = null; // the new scenario may be somewhere else diff --git a/docs/Usage/GUI/controlpanel.md b/docs/Usage/GUI/controlpanel.md index 89d5f02c2..cee6d6e54 100644 --- a/docs/Usage/GUI/controlpanel.md +++ b/docs/Usage/GUI/controlpanel.md @@ -26,10 +26,11 @@ Below the buttons, a satellite map shows the trajectories of the loaded scenario - **When data appears**: trajectories and the test origin are loaded once ObjectControl reaches `INITIALIZED` (after **Init**), and reloaded on each new Init. Object markers are shown for the objects in `/atos/connected_object_ids`. A marker turns grey when no monitor data has arrived for 2 seconds. - **Geographic accuracy**: ATOS works in a local transverse Mercator frame centred on the test origin (from the OpenDRIVE ``). The map converts trajectories (`/atos/object_/path`) and monitor poses (`/atos/object_monitor`) with that same projection, using PROJ via `pyproj`, so overlays are exact. Headings, which are counter-clockwise from east in the local frame, are converted to true bearings, including meridian convergence. If the scenario has no geo-reference, the map says so and draws nothing. -- **Resizing**: drag the bottom-right corner of the map. The browser remembers the size. -- **Settings** (*Map settings*, saved on the ATOS host): +- **Resizing**: drag the bottom-right corner of the map. The browser remembers the size; otherwise the map follows the window width. +- **Settings** (the *Map settings* button opens a pane next to the map; saved on the ATOS host): - Trajectory width, line style (solid, dashed, dotted, dash-dot) and opacity. - Marker size and style (arrow, chevron, vehicle, circle with heading line), and whether labels are shown. + - Show the scenario origin (off by default): a crosshair at the test origin with the local frame's x (east) and y (north) axes. Hover it for its latitude and longitude. - A colour per object. - **Base map**: satellite imagery is Esri World Imagery, which needs no API key (attribution is shown on the map). OpenStreetMap or a custom tile URL (e.g. a local tile server for sites without internet) can be selected instead. Overlays are drawn even if no tiles load. How deep Esri's imagery goes varies by location (zoom 18 at AstaZero, for example). After each Init the map asks Esri's tile-map service where imagery exists over the scenario. Fitting never zooms closer than that, and when you zoom in further by hand, the deepest real imagery is scaled up instead of showing "Map data not yet available" tiles. - **Fit to scenario / Follow**: zoom to all trajectories, or keep one object centred. From b8c19d6ee4385e34eafa40f194d394a9a43f1be1 Mon Sep 17 00:00:00 2001 From: Robert Brenick Date: Mon, 9 Nov 2026 18:12:36 -0600 Subject: [PATCH 8/8] Update access shint so that it fits both truck and normal operation --- atos_gui/atos_gui/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atos_gui/atos_gui/main.py b/atos_gui/atos_gui/main.py index ce2f8106b..323612539 100644 --- a/atos_gui/atos_gui/main.py +++ b/atos_gui/atos_gui/main.py @@ -285,7 +285,7 @@ def ros_main() -> None: def print_access_hint() -> None: scheme = "https" if USE_SSL else "http" - print(f"TruckObjectGUI ready. Open {scheme}://localhost:8420", flush=True) + print(f"GUI ready. Open {scheme}://localhost:8420", flush=True) def configure_app() -> None: