feat(viewer): unify spatial clipping, planning and observation surfaces
Share spatial clipping and height slices across live planning and recorded observations. Refine scene navigation, report serialization and viewer presentation.
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
"""View-only height bands; never mutate source geometry or tracking inputs."""
|
||||
import math
|
||||
import numpy as np
|
||||
|
||||
|
||||
def height_mask(points, floor_m=None, ceiling_m=None):
|
||||
if any(v is not None and not math.isfinite(v) for v in (floor_m, ceiling_m)):
|
||||
raise ValueError("Height bounds must be finite")
|
||||
if floor_m is not None and ceiling_m is not None and floor_m > ceiling_m:
|
||||
raise ValueError("Lower height exceeds upper height")
|
||||
mask = np.ones(len(points), dtype=bool)
|
||||
if floor_m is not None or ceiling_m is not None:
|
||||
mask &= np.isfinite(points).all(axis=1)
|
||||
if floor_m is not None:
|
||||
mask &= points[:, 2] >= floor_m
|
||||
if ceiling_m is not None:
|
||||
mask &= points[:, 2] <= ceiling_m
|
||||
return mask
|
||||
@@ -0,0 +1,38 @@
|
||||
"""One bounded encoded report; dynamic telemetry is never cached.
|
||||
|
||||
Caller holds the report lock and increments revision on every report mutation.
|
||||
Only terminal reports may be cached. Active reports are encoded from their
|
||||
current values on every request, including changes between published revisions.
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
|
||||
def _encode(value):
|
||||
return json.dumps(value, ensure_ascii=False, allow_nan=False,
|
||||
separators=(",", ":")).encode("utf-8")
|
||||
|
||||
|
||||
class ReportJSONCache:
|
||||
def __init__(self, max_bytes=8 * 1024 * 1024):
|
||||
self.max_bytes = max_bytes
|
||||
self.clear()
|
||||
|
||||
def clear(self):
|
||||
self._key = None
|
||||
self._prefix = None
|
||||
|
||||
def encode(self, report, revision, overlay, *, cacheable):
|
||||
if not cacheable:
|
||||
self.clear()
|
||||
return _encode(report | overlay)
|
||||
key = (id(report), revision, tuple(sorted(overlay)))
|
||||
prefix = self._prefix if key == self._key else None
|
||||
if prefix is None:
|
||||
self.clear()
|
||||
prefix = _encode({k: v for k, v in report.items() if k not in overlay})[:-1]
|
||||
if len(prefix) <= self.max_bytes:
|
||||
self._key, self._prefix = key, prefix
|
||||
suffix = _encode(overlay)[1:]
|
||||
separator = b"," if len(prefix) > 1 and len(suffix) > 1 else b""
|
||||
return prefix + separator + suffix
|
||||
@@ -5,26 +5,28 @@ import rerun as rr
|
||||
from rerun import blueprint as rrb
|
||||
|
||||
from .registration import transform
|
||||
from k1link.height_slice import height_mask
|
||||
|
||||
from .registration_colors import query_colors
|
||||
|
||||
|
||||
def clip_reference(points, ceiling_m):
|
||||
if ceiling_m is None:
|
||||
def clip_reference(points, ceiling_m, floor_m=None):
|
||||
if ceiling_m is None and floor_m is None:
|
||||
return points
|
||||
return points[points[:, 2] <= ceiling_m]
|
||||
return points[height_mask(points, floor_m, ceiling_m)]
|
||||
|
||||
|
||||
def clip_query(points, matrix, ceiling_m):
|
||||
if ceiling_m is None or not len(points):
|
||||
def clip_query(points, matrix, ceiling_m, floor_m=None):
|
||||
if (ceiling_m is None and floor_m is None) or not len(points):
|
||||
return points
|
||||
transformed = transform(points, matrix)
|
||||
return points[np.isfinite(transformed).all(axis=1) & (transformed[:, 2] <= ceiling_m)]
|
||||
return points[height_mask(transformed, floor_m, ceiling_m)]
|
||||
|
||||
|
||||
def log_base(recording, reference, reference_path, options):
|
||||
size = options.get("point_size", 1.8)
|
||||
recording.log("world", rr.ViewCoordinates.RIGHT_HAND_Z_UP, static=True)
|
||||
visible_reference = clip_reference(reference, options.get("ceiling_m"))
|
||||
visible_reference = clip_reference(reference, options.get("ceiling_m"), options.get("floor_m"))
|
||||
recording.log(
|
||||
"world/reference",
|
||||
rr.Points3D(
|
||||
@@ -97,14 +99,13 @@ def log_view(recording, reference, options):
|
||||
)
|
||||
|
||||
|
||||
def log_evidence(recording, evidence, size, ceiling_m=None):
|
||||
def log_evidence(recording, evidence, size, ceiling_m=None, floor_m=None):
|
||||
fitted, accepted = evidence
|
||||
indices = np.asarray(accepted.get("matched_query_indices", []), dtype=int)
|
||||
indices = indices[(indices >= 0) & (indices < len(fitted["points"]))]
|
||||
if accepted["status"] == "candidate" and len(indices):
|
||||
points = transform(fitted["points"][indices], np.array(accepted["T_reference_query"]))
|
||||
if ceiling_m is not None:
|
||||
points = points[np.isfinite(points).all(axis=1) & (points[:, 2] <= ceiling_m)]
|
||||
points = points[height_mask(points, floor_m, ceiling_m)]
|
||||
recording.log(
|
||||
"world/validated_query",
|
||||
rr.Points3D(
|
||||
@@ -148,7 +149,7 @@ def scene_bytes(
|
||||
and options.get("query", True)
|
||||
):
|
||||
t = np.array(result["T_reference_query"])
|
||||
points = clip_query(sample["points"], t, options.get("ceiling_m"))
|
||||
points = clip_query(sample["points"], t, options.get("ceiling_m"), options.get("floor_m"))
|
||||
recording.log(
|
||||
"world/query",
|
||||
rr.Points3D(
|
||||
@@ -165,7 +166,7 @@ def scene_bytes(
|
||||
static=True,
|
||||
)
|
||||
if evidence:
|
||||
log_evidence(recording, evidence, size, options.get("ceiling_m"))
|
||||
log_evidence(recording, evidence, size, options.get("ceiling_m"), options.get("floor_m"))
|
||||
recording.flush()
|
||||
return sink.read()
|
||||
finally:
|
||||
|
||||
@@ -87,7 +87,7 @@ def scene_delta(
|
||||
name = f"world/query/cloud/{slot}"
|
||||
# Empty Points3D replaces every component; no temporal history.
|
||||
points = np.empty((0, 3)) if points is None else points
|
||||
points = clip_query(points, matrix, options.get("ceiling_m"))
|
||||
points = clip_query(points, matrix, options.get("ceiling_m"), options.get("floor_m"))
|
||||
recording.log(
|
||||
name,
|
||||
rr.Points3D(
|
||||
@@ -96,7 +96,7 @@ def scene_delta(
|
||||
static=True,
|
||||
)
|
||||
current_points = clip_query(
|
||||
sample.get("current_points", np.empty((0, 3))), matrix, options.get("ceiling_m")
|
||||
sample.get("current_points", np.empty((0, 3))), matrix, options.get("ceiling_m"), options.get("floor_m")
|
||||
)
|
||||
if live:
|
||||
# Temporal head follows the scanner receipt sequence. Frozen chunks
|
||||
@@ -137,7 +137,7 @@ def scene_delta(
|
||||
if full or previous.get("evidence") != current["evidence"]:
|
||||
recording.log("world/validated_query", rr.Clear(recursive=True), static=True)
|
||||
if evidence and options.get("query", True):
|
||||
log_evidence(recording, evidence, size, options.get("ceiling_m"))
|
||||
log_evidence(recording, evidence, size, options.get("ceiling_m"), options.get("floor_m"))
|
||||
recording.flush()
|
||||
return sink.read(), token
|
||||
finally:
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Polling projection: no route geometry, point indices or calculation history.
|
||||
|
||||
Full evidence remains in the existing report API and immutable stored reports.
|
||||
Select fields before copying; traversing the whole report defeats this boundary.
|
||||
"""
|
||||
import copy
|
||||
|
||||
FIELDS = ("id", "profile", "plugin_id", "state", "planning_phase", "tracking_state",
|
||||
"tracking_established", "message", "query_session_id", "distance_m", "query_points")
|
||||
|
||||
|
||||
def status_document(run):
|
||||
result = {key: run[key] for key in FIELDS if key in run}
|
||||
result["schema_version"] = "missioncore.planning-live-status/v1"
|
||||
draft = run["draft"]
|
||||
result["draft"] = {key: draft[key] for key in
|
||||
("id", "revision", "name", "updated_at_utc", "vehicle_id", "zone")
|
||||
if key in draft}
|
||||
result["draft"]["route"] = {key: draft["route"][key] for key in
|
||||
("start_index", "end_index", "direction", "length_m")
|
||||
if key in draft["route"]}
|
||||
match = run.get("result")
|
||||
result["result"] = None if match is None else {
|
||||
key: match[key] for key in ("status", "overlap", "inlier_rmse_m", "reasons")
|
||||
if key in match}
|
||||
policy = run.get("route_relocalization_policy")
|
||||
if policy is not None:
|
||||
result["route_relocalization_policy"] = {
|
||||
key: policy[key] for key in ("version", "query_radius_m") if key in policy}
|
||||
return copy.deepcopy(result)
|
||||
@@ -21,6 +21,7 @@ from .drafts import DraftConflict
|
||||
from .live_display_buffer import LiveDisplayBuffer
|
||||
from .live_limits import live_route_limits
|
||||
from .live_presentation import PRESENTATION_POLICY, LivePresentation, stored_alignment
|
||||
from .live_report_json import ReportJSONCache
|
||||
from .live_scene import scene_bytes
|
||||
from .live_scene_delta import scene_delta
|
||||
from .observation_profiles import SCENE_INPUT
|
||||
@@ -58,6 +59,7 @@ class PlanningLiveTests:
|
||||
self.cancel = threading.Event()
|
||||
self.thread = None
|
||||
self.revision = 0
|
||||
self._report_json = ReportJSONCache()
|
||||
self.last_frame_ns = 0
|
||||
self.last_result_ns = 0
|
||||
self.source = None
|
||||
@@ -189,36 +191,66 @@ class PlanningLiveTests:
|
||||
self.revision += 1
|
||||
self.persist()
|
||||
|
||||
def get(self):
|
||||
def get_status(self):
|
||||
return self.get(compact=True)
|
||||
|
||||
def get(self, *, compact=False):
|
||||
with self.lock:
|
||||
if self.run is None:
|
||||
return None
|
||||
result = json.loads(json.dumps(self.run))
|
||||
now = time.monotonic_ns()
|
||||
result["frame_age_s"] = (now - self.last_frame_ns) / 1e9 if self.last_frame_ns else None
|
||||
result["result_age_s"] = (
|
||||
(now - self.last_result_ns) / 1e9 if self.last_result_ns else None
|
||||
)
|
||||
result["stale"] = not self.last_frame_ns or now - self.last_frame_ns > 8_000_000_000
|
||||
result["scene_available"] = self.reference is not None
|
||||
result["scene_height_min_m"], result["scene_height_max_m"] = self.scene_height_bounds()
|
||||
result["scene_revision"] = self.revision
|
||||
result["presentation_state"] = (
|
||||
"live"
|
||||
if self._view_live(now)
|
||||
else "historical"
|
||||
if self.presentation.result
|
||||
else "unlocalized"
|
||||
)
|
||||
result["pose_age_s"] = (
|
||||
(now - self.latest_pose["monotonic_ns"]) / 1e9 if self.latest_pose else None
|
||||
)
|
||||
result["scanner_pose"] = self.latest_pose
|
||||
if self.display.packet is not None or "display" not in result:
|
||||
result["display"] = self.display.diagnostics()
|
||||
result["browser_presentation"] = self.browser_presentation.diagnostics()
|
||||
if compact:
|
||||
from .live_status import status_document
|
||||
result = status_document(self.run)
|
||||
else:
|
||||
result = json.loads(json.dumps(self.run))
|
||||
fields = self._runtime_status(compact=compact)
|
||||
if not compact and self.display.packet is None and "display" in self.run:
|
||||
fields.pop("display") # Preserve the independent report copy.
|
||||
result.update(fields)
|
||||
return result
|
||||
|
||||
def get_json(self):
|
||||
"""Full legacy report without repeatedly copying immutable numerical evidence."""
|
||||
with self.lock:
|
||||
if self.run is None:
|
||||
self._report_json.clear()
|
||||
return b"null"
|
||||
return self._report_json.encode(
|
||||
self.run, self.revision, self._runtime_status(),
|
||||
cacheable=self.run["state"] in TERMINAL,
|
||||
)
|
||||
|
||||
def _runtime_status(self, *, compact=False):
|
||||
result = {}
|
||||
now = time.monotonic_ns()
|
||||
result["frame_age_s"] = (now - self.last_frame_ns) / 1e9 if self.last_frame_ns else None
|
||||
result["result_age_s"] = (
|
||||
(now - self.last_result_ns) / 1e9 if self.last_result_ns else None
|
||||
)
|
||||
result["stale"] = not self.last_frame_ns or now - self.last_frame_ns > 8_000_000_000
|
||||
result["scene_available"] = self.reference is not None
|
||||
result["scene_height_min_m"], result["scene_height_max_m"] = self.scene_height_bounds()
|
||||
result["scene_revision"] = self.revision
|
||||
result["presentation_state"] = (
|
||||
"live"
|
||||
if self._view_live(now)
|
||||
else "historical"
|
||||
if self.presentation.result
|
||||
else "unlocalized"
|
||||
)
|
||||
if compact:
|
||||
return result
|
||||
result["pose_age_s"] = (
|
||||
(now - self.latest_pose["monotonic_ns"]) / 1e9 if self.latest_pose else None
|
||||
)
|
||||
result["scanner_pose"] = self.latest_pose
|
||||
if self.display.packet is not None or "display" not in self.run:
|
||||
result["display"] = self.display.diagnostics()
|
||||
else:
|
||||
result["display"] = self.run["display"]
|
||||
result["browser_presentation"] = self.browser_presentation.diagnostics()
|
||||
return result
|
||||
|
||||
def scene_height_bounds(self):
|
||||
# Reference arrays are frozen and replaced as a unit. Do not rescan
|
||||
# and copy a route-wide map under the consumer lock on every UI poll.
|
||||
|
||||
@@ -9,6 +9,8 @@ import rerun as rr
|
||||
from rerun import blueprint as rrb
|
||||
from rerun.experimental import RrdReader
|
||||
|
||||
from k1link.height_slice import height_mask
|
||||
|
||||
from .overview_comparison import OverviewComparison
|
||||
|
||||
|
||||
@@ -87,6 +89,7 @@ def render_spatial_update(
|
||||
aspect: float = 1.5,
|
||||
comparison: OverviewComparison | None = None,
|
||||
representation: Literal["original", "corrected"] = "original",
|
||||
floor_m: float | None = None,
|
||||
):
|
||||
app_id, recording_id, xyz, colors = geometry(path)
|
||||
if representation == "corrected" and comparison is None:
|
||||
@@ -108,7 +111,7 @@ def render_spatial_update(
|
||||
colors = np.column_stack(
|
||||
[70 + 100 * normalized, 135 + 80 * normalized, 220 - 90 * normalized]
|
||||
).astype(np.uint8)
|
||||
selected = xyz[:, 2] <= ceiling_m if ceiling_m is not None else np.ones(len(xyz), dtype=bool)
|
||||
selected = height_mask(xyz, floor_m, ceiling_m)
|
||||
recording = rr.RecordingStream(app_id, recording_id=recording_id, send_properties=False)
|
||||
sink = rr.binary_stream(recording)
|
||||
eye = None
|
||||
|
||||
@@ -48,6 +48,11 @@ def build_planning_live_router(service):
|
||||
except (ValueError, RuntimeError) as exc:
|
||||
raise HTTPException(409, str(exc)) from exc
|
||||
|
||||
@router.get("/status")
|
||||
async def status():
|
||||
value = await call(service.get_status)
|
||||
return JSONResponse(value, headers={"Cache-Control": "no-store"})
|
||||
|
||||
@router.get("/active")
|
||||
async def active(request: Request):
|
||||
accepts_gzip = "gzip" in request.headers.get("accept-encoding", "")
|
||||
@@ -57,7 +62,8 @@ def build_planning_live_router(service):
|
||||
# Returning its dict sends it through FastAPI's recursive encoder
|
||||
# and gzip on the event loop, delaying unrelated control requests.
|
||||
# Keep the exact JSON contract, but finish both operations here.
|
||||
response = JSONResponse(service.get(), headers={"Cache-Control": "no-store"})
|
||||
response = Response(service.get_json(), media_type="application/json",
|
||||
headers={"Cache-Control": "no-store"})
|
||||
if accepts_gzip and len(response.body) >= 1024:
|
||||
return Response(
|
||||
gzip.compress(response.body, compresslevel=5, mtime=0),
|
||||
@@ -109,6 +115,7 @@ def build_planning_live_router(service):
|
||||
grid: bool = True,
|
||||
point_size: float = Query(1.8, ge=0.5, le=12),
|
||||
ceiling_m: float | None = Query(default=None, allow_inf_nan=False),
|
||||
floor_m: float | None = Query(default=None, allow_inf_nan=False),
|
||||
):
|
||||
options = dict(
|
||||
mode=mode,
|
||||
@@ -118,6 +125,7 @@ def build_planning_live_router(service):
|
||||
grid=grid,
|
||||
point_size=point_size,
|
||||
ceiling_m=ceiling_m,
|
||||
floor_m=floor_m,
|
||||
)
|
||||
return Response(
|
||||
await call(service.scene, str(run_id), base, options),
|
||||
@@ -138,6 +146,7 @@ def build_planning_live_router(service):
|
||||
grid: bool = True,
|
||||
point_size: float = Query(1.8, ge=0.5, le=12),
|
||||
ceiling_m: float | None = Query(default=None, allow_inf_nan=False),
|
||||
floor_m: float | None = Query(default=None, allow_inf_nan=False),
|
||||
):
|
||||
options = dict(
|
||||
mode=mode,
|
||||
@@ -148,6 +157,7 @@ def build_planning_live_router(service):
|
||||
grid=grid,
|
||||
point_size=point_size,
|
||||
ceiling_m=ceiling_m,
|
||||
floor_m=floor_m,
|
||||
)
|
||||
payload, next_cursor, info = await call(
|
||||
service.scene_update, str(run_id), cursor, base, options
|
||||
|
||||
@@ -16,6 +16,7 @@ class OverviewSpatialRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
generation: str = Field(pattern="^[a-f0-9]{64}$")
|
||||
ceiling_m: float | None = Field(default=None, allow_inf_nan=False)
|
||||
floor_m: float | None = Field(default=None, allow_inf_nan=False)
|
||||
mode: Literal["3d", "top"] | None = None
|
||||
comparison_generation: str | None = Field(default=None, pattern="^[a-f0-9]{64}$")
|
||||
representation: Literal["original", "corrected"] = "original"
|
||||
@@ -84,6 +85,7 @@ def build_session_overview_router(service: SessionOverviewService) -> APIRouter:
|
||||
request.aspect,
|
||||
comparison,
|
||||
request.representation,
|
||||
request.floor_m,
|
||||
)
|
||||
headers = {"Cache-Control": "no-store", "X-Overview-Visible-Points": str(visible)}
|
||||
if eye is not None:
|
||||
|
||||
Reference in New Issue
Block a user