240 lines
9.7 KiB
Python
240 lines
9.7 KiB
Python
from __future__ import annotations
|
|
|
|
from math import hypot
|
|
from typing import TYPE_CHECKING
|
|
|
|
import rtree
|
|
|
|
if TYPE_CHECKING:
|
|
from inire.geometry.collision import RoutingWorld
|
|
from inire.geometry.primitives import Port
|
|
|
|
class VisibilityManager:
|
|
"""
|
|
Manages corners of static obstacles for sparse A* / Visibility Graph jumps.
|
|
"""
|
|
__slots__ = (
|
|
"collision_engine",
|
|
"corners",
|
|
"_exact_corners",
|
|
"corner_index",
|
|
"_corner_graph",
|
|
"_point_visibility_cache",
|
|
"_corner_index_version",
|
|
"_corner_graph_version",
|
|
)
|
|
|
|
def __init__(self, collision_engine: RoutingWorld) -> None:
|
|
self.collision_engine = collision_engine
|
|
self.corners: list[tuple[float, float]] = []
|
|
self._exact_corners: list[tuple[float, float]] = []
|
|
self.corner_index = rtree.index.Index()
|
|
self._corner_graph: dict[int, list[tuple[float, float, float]]] = {}
|
|
self._point_visibility_cache: dict[tuple[int, int, int], list[tuple[float, float, float]]] = {}
|
|
self._corner_index_version = -1
|
|
self._corner_graph_version = -1
|
|
|
|
def clear_cache(self) -> None:
|
|
"""
|
|
Reset all static visibility data.
|
|
"""
|
|
self.corners = []
|
|
self._exact_corners = []
|
|
self.corner_index = rtree.index.Index()
|
|
self._corner_graph = {}
|
|
self._point_visibility_cache = {}
|
|
self._corner_index_version = -1
|
|
self._corner_graph_version = -1
|
|
|
|
def ensure_corner_index_current(self) -> None:
|
|
if self._corner_index_version != self.collision_engine.get_static_version():
|
|
self._build_corner_index()
|
|
|
|
def ensure_corner_graph_current(self) -> None:
|
|
self.ensure_corner_index_current()
|
|
static_version = self.collision_engine.get_static_version()
|
|
if self._corner_graph_version != static_version:
|
|
self._build_corner_graph()
|
|
|
|
def _build_corner_index(self) -> None:
|
|
if self.collision_engine.metrics is not None:
|
|
self.collision_engine.metrics.total_visibility_corner_index_builds += 1
|
|
self.corners = []
|
|
self._exact_corners = []
|
|
self.corner_index = rtree.index.Index()
|
|
self._corner_graph = {}
|
|
self._point_visibility_cache = {}
|
|
self._corner_graph_version = -1
|
|
self._corner_index_version = self.collision_engine.get_static_version()
|
|
raw_corners = []
|
|
for poly in self.collision_engine.iter_static_dilated_geometries():
|
|
coords = list(poly.exterior.coords)
|
|
if coords[0] == coords[-1]:
|
|
coords = coords[:-1]
|
|
raw_corners.extend(coords)
|
|
for ring in poly.interiors:
|
|
coords = list(ring.coords)
|
|
if coords[0] == coords[-1]:
|
|
coords = coords[:-1]
|
|
raw_corners.extend(coords)
|
|
|
|
if not raw_corners:
|
|
return
|
|
|
|
seen = set()
|
|
for x, y in raw_corners:
|
|
sx, sy = round(x, 3), round(y, 3)
|
|
if (sx, sy) not in seen:
|
|
seen.add((sx, sy))
|
|
self.corners.append((sx, sy))
|
|
self._exact_corners.append((x, y))
|
|
|
|
for i, (x, y) in enumerate(self.corners):
|
|
self.corner_index.insert(i, (x, y, x, y))
|
|
|
|
def _build_corner_graph(self) -> None:
|
|
"""
|
|
Pre-compute corner-to-corner visibility from the current corner index.
|
|
"""
|
|
self.ensure_corner_index_current()
|
|
if self.collision_engine.metrics is not None:
|
|
self.collision_engine.metrics.total_visibility_builds += 1
|
|
self._corner_graph = {}
|
|
self._corner_graph_version = self.collision_engine.get_static_version()
|
|
|
|
if not self.corners:
|
|
return
|
|
|
|
# Pre-compute visibility graph between corners
|
|
num_corners = len(self.corners)
|
|
if num_corners > 200:
|
|
# Limit pre-computation if too many corners
|
|
return
|
|
|
|
for i in range(num_corners):
|
|
self._corner_graph[i] = []
|
|
for j in range(num_corners):
|
|
if i == j:
|
|
continue
|
|
if self.collision_engine.metrics is not None:
|
|
self.collision_engine.metrics.total_visibility_corner_pairs_checked += 1
|
|
start, end = self._exact_corners[i], self._exact_corners[j]
|
|
if self.collision_engine.corner_segment_visible(start, end):
|
|
cx, cy = self.corners[j]
|
|
self._corner_graph[i].append((cx, cy, hypot(end[0] - start[0], end[1] - start[1])))
|
|
|
|
def _corner_idx_at(self, origin: Port) -> int | None:
|
|
self.ensure_corner_index_current()
|
|
ox, oy = round(origin.x, 3), round(origin.y, 3)
|
|
nearby = list(self.corner_index.intersection((ox - 0.001, oy - 0.001, ox + 0.001, oy + 0.001)))
|
|
for idx in nearby:
|
|
cx, cy = self.corners[idx]
|
|
if abs(cx - ox) < 1e-4 and abs(cy - oy) < 1e-4:
|
|
return idx
|
|
return None
|
|
|
|
def get_tangent_corner_candidates(
|
|
self,
|
|
origin: Port,
|
|
*,
|
|
min_forward: float,
|
|
max_forward: float,
|
|
radii: tuple[float, ...],
|
|
tolerance: float = 2.0,
|
|
) -> list[int]:
|
|
self.ensure_corner_index_current()
|
|
if max_forward <= min_forward or not radii or not self.corners:
|
|
return []
|
|
|
|
candidate_ids: set[int] = set()
|
|
x0 = float(origin.x)
|
|
y0 = float(origin.y)
|
|
|
|
def _add_hits(bounds: tuple[float, float, float, float]) -> None:
|
|
min_x, min_y, max_x, max_y = bounds
|
|
if min_x > max_x or min_y > max_y:
|
|
return
|
|
candidate_ids.update(self.corner_index.intersection(bounds))
|
|
|
|
for radius in radii:
|
|
if origin.r == 0:
|
|
x_bounds = (x0 + min_forward, x0 + max_forward)
|
|
_add_hits((x_bounds[0], y0 + radius - tolerance, x_bounds[1], y0 + radius + tolerance))
|
|
_add_hits((x_bounds[0], y0 - radius - tolerance, x_bounds[1], y0 - radius + tolerance))
|
|
elif origin.r == 180:
|
|
x_bounds = (x0 - max_forward, x0 - min_forward)
|
|
_add_hits((x_bounds[0], y0 + radius - tolerance, x_bounds[1], y0 + radius + tolerance))
|
|
_add_hits((x_bounds[0], y0 - radius - tolerance, x_bounds[1], y0 - radius + tolerance))
|
|
elif origin.r == 90:
|
|
y_bounds = (y0 + min_forward, y0 + max_forward)
|
|
_add_hits((x0 + radius - tolerance, y_bounds[0], x0 + radius + tolerance, y_bounds[1]))
|
|
_add_hits((x0 - radius - tolerance, y_bounds[0], x0 - radius + tolerance, y_bounds[1]))
|
|
else:
|
|
y_bounds = (y0 - max_forward, y0 - min_forward)
|
|
_add_hits((x0 + radius - tolerance, y_bounds[0], x0 + radius + tolerance, y_bounds[1]))
|
|
_add_hits((x0 - radius - tolerance, y_bounds[0], x0 - radius + tolerance, y_bounds[1]))
|
|
|
|
return sorted(candidate_ids)
|
|
|
|
def get_point_visibility(self, origin: Port, max_dist: float = 1000.0) -> list[tuple[float, float, float]]:
|
|
"""
|
|
Find visible corners from an arbitrary point.
|
|
This may test local corner segments against keepouts.
|
|
"""
|
|
if self.collision_engine.metrics is not None:
|
|
self.collision_engine.metrics.total_visibility_point_queries += 1
|
|
self.ensure_corner_index_current()
|
|
if max_dist < 0:
|
|
return []
|
|
|
|
corner_idx = self._corner_idx_at(origin)
|
|
if corner_idx is not None:
|
|
self.ensure_corner_graph_current()
|
|
if corner_idx is not None and corner_idx in self._corner_graph:
|
|
return [corner for corner in self._corner_graph[corner_idx] if corner[2] <= max_dist]
|
|
|
|
ox, oy = round(origin.x, 3), round(origin.y, 3)
|
|
cache_key = (int(ox * 1000), int(oy * 1000), int(round(max_dist * 1000)))
|
|
if cache_key in self._point_visibility_cache:
|
|
if self.collision_engine.metrics is not None:
|
|
self.collision_engine.metrics.total_visibility_point_cache_hits += 1
|
|
return self._point_visibility_cache[cache_key]
|
|
if self.collision_engine.metrics is not None:
|
|
self.collision_engine.metrics.total_visibility_point_cache_misses += 1
|
|
|
|
bounds = (origin.x - max_dist, origin.y - max_dist, origin.x + max_dist, origin.y + max_dist)
|
|
candidates = sorted(self.corner_index.intersection(bounds))
|
|
|
|
visible = []
|
|
start = (origin.x, origin.y) if corner_idx is None else self._exact_corners[corner_idx]
|
|
for i in candidates:
|
|
end = self._exact_corners[i]
|
|
dist = hypot(end[0] - start[0], end[1] - start[1])
|
|
|
|
if dist > max_dist or dist < 1e-3:
|
|
continue
|
|
|
|
if self.collision_engine.corner_segment_visible(start, end):
|
|
cx, cy = self.corners[i]
|
|
visible.append((cx, cy, dist))
|
|
|
|
if len(self._point_visibility_cache) >= 4096:
|
|
self._point_visibility_cache.clear()
|
|
self._point_visibility_cache[cache_key] = visible
|
|
return visible
|
|
|
|
def get_corner_visibility(self, origin: Port, max_dist: float = 1000.0) -> list[tuple[float, float, float]]:
|
|
"""
|
|
Return visible neighbors when the origin is already at a known corner.
|
|
"""
|
|
if self.collision_engine.metrics is not None:
|
|
self.collision_engine.metrics.total_visibility_corner_queries_exact += 1
|
|
if max_dist < 0:
|
|
return []
|
|
|
|
corner_idx = self._corner_idx_at(origin)
|
|
if corner_idx is None:
|
|
return []
|
|
if self.collision_engine.metrics is not None:
|
|
self.collision_engine.metrics.total_visibility_corner_hits_exact += 1
|
|
return self.get_point_visibility(origin, max_dist)
|